From 4a61a0f7f79b078fb09b8ab9b7104baa5e998d9e Mon Sep 17 00:00:00 2001 From: bRRRITSCOLD Date: Mon, 23 Nov 2026 17:20:08 -0700 Subject: [PATCH 1/5] feat(daemon): the GitHub repository list for the Link picker (#371) GET /v1/github/repositories and POST /v1/github/repositories/refresh: GET /user/repos 100 a page, page 1 first, then the last page, then the rest 4 at a time; kept in memory for the run, refreshed quietly, with progress and changed github_repositories as pages arrive. API_VERSION 27. Co-Authored-By: Claude Opus 5.5 --- crates/agentdeck-client/src/generated.rs | 317 ++++++++++++ crates/agentdeck-client/src/repositories.rs | 23 +- crates/agentdeck-core/src/daemon.rs | 2 +- crates/agentdeck-core/src/ws.rs | 12 + crates/agentdeckd/src/api/github.rs | 37 +- crates/agentdeckd/src/api/mod.rs | 7 +- crates/agentdeckd/src/daemon.rs | 3 + crates/agentdeckd/src/github_list.rs | 327 +++++++++++++ crates/agentdeckd/src/main.rs | 1 + crates/agentdeckd/src/model.rs | 35 ++ crates/agentdeckd/src/prsync/github.rs | 112 ++++- crates/agentdeckd/src/suggestions/mod.rs | 6 +- .../tests/integration/github_list.rs | 456 ++++++++++++++++++ crates/agentdeckd/tests/integration/main.rs | 1 + .../tests/integration/repositories_client.rs | 72 ++- .../tests/integration/support/github.rs | 122 +++++ openapi.json | 127 +++++ 17 files changed, 1646 insertions(+), 14 deletions(-) create mode 100644 crates/agentdeckd/src/github_list.rs create mode 100644 crates/agentdeckd/tests/integration/github_list.rs diff --git a/crates/agentdeck-client/src/generated.rs b/crates/agentdeck-client/src/generated.rs index 457f81a..08e6173 100644 --- a/crates/agentdeck-client/src/generated.rs +++ b/crates/agentdeck-client/src/generated.rs @@ -147,6 +147,95 @@ pub mod types { Default::default() } } + ///Where loading the GitHub repository list stands. + #[derive( + ::serde::Deserialize, + ::serde::Serialize, + Clone, + Copy, + Debug, + Eq, + Hash, + Ord, + PartialEq, + PartialOrd, + )] + pub enum GithubListStatus { + ///Nothing asked for it yet this run, or since the sign-in changed. + #[serde(rename = "not_loaded")] + NotLoaded, + ///The first load runs: `repositories` holds the pages that have arrived. + #[serde(rename = "loading")] + Loading, + ///Every page loaded. A refresh runs quietly under it, the list changing once it ends. + #[serde(rename = "loaded")] + Loaded, + ///The load failed (no connection, a rate limit, a token GitHub rejects): `error` says why. + #[serde(rename = "failed")] + Failed, + ///There's no GitHub token to list with. + #[serde(rename = "signed_out")] + SignedOut, + } + impl ::std::fmt::Display for GithubListStatus { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + match *self { + Self::NotLoaded => f.write_str("not_loaded"), + Self::Loading => f.write_str("loading"), + Self::Loaded => f.write_str("loaded"), + Self::Failed => f.write_str("failed"), + Self::SignedOut => f.write_str("signed_out"), + } + } + } + impl ::std::str::FromStr for GithubListStatus { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + match value { + "not_loaded" => Ok(Self::NotLoaded), + "loading" => Ok(Self::Loading), + "loaded" => Ok(Self::Loaded), + "failed" => Ok(Self::Failed), + "signed_out" => Ok(Self::SignedOut), + _ => Err("invalid value".into()), + } + } + } + impl ::std::convert::TryFrom<&str> for GithubListStatus { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } + } + impl ::std::convert::TryFrom<::std::string::String> for GithubListStatus { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } + } + ///`GET /v1/github/repositories`: every GitHub repository the sign-in can reach, as the Link picker offers them (spec §8), with how far loading them has got. Kept in memory for the run. + #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug, PartialEq)] + pub struct GithubRepositoryList { + ///Why the last load failed, while `status` is `failed`: GitHub's message, or why the request failed. + #[serde(skip_serializing_if = "::std::option::Option::is_none")] + pub error: ::std::option::Option<::std::string::String>, + ///How many repositories have loaded: `repositories`' length. + pub loaded: u32, + ///The repositories loaded so far, by `owner/name` as GitHub sorts them. While a list is refreshed, the one before it, whole. + pub repositories: ::std::vec::Vec, + ///Where loading the list stands. + pub status: GithubListStatus, + ///About how many there are, from the last page's number in page 1's `Link` header, then exact once the last page has loaded; `None` until page 1 answers. + #[serde(skip_serializing_if = "::std::option::Option::is_none")] + pub total: ::std::option::Option, + } + impl GithubRepositoryList { + pub fn builder() -> builder::GithubRepositoryList { + Default::default() + } + } ///`PUT /v1/github/token`. #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug, PartialEq)] pub struct GithubTokenBody { @@ -1395,6 +1484,106 @@ pub mod types { } } #[derive(Clone, Debug)] + pub struct GithubRepositoryList { + error: ::std::result::Result< + ::std::option::Option<::std::string::String>, + ::std::string::String, + >, + loaded: ::std::result::Result, + repositories: + ::std::result::Result<::std::vec::Vec, ::std::string::String>, + status: ::std::result::Result, + total: ::std::result::Result<::std::option::Option, ::std::string::String>, + } + impl ::std::default::Default for GithubRepositoryList { + fn default() -> Self { + Self { + error: Ok(Default::default()), + loaded: Err("no value supplied for loaded".to_string()), + repositories: Err("no value supplied for repositories".to_string()), + status: Err("no value supplied for status".to_string()), + total: Ok(Default::default()), + } + } + } + impl GithubRepositoryList { + pub fn error(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option<::std::string::String>>, + T::Error: ::std::fmt::Display, + { + self.error = value + .try_into() + .map_err(|e| format!("error converting supplied value for error: {e}")); + self + } + pub fn loaded(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.loaded = value + .try_into() + .map_err(|e| format!("error converting supplied value for loaded: {e}")); + self + } + pub fn repositories(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::vec::Vec>, + T::Error: ::std::fmt::Display, + { + self.repositories = value + .try_into() + .map_err(|e| format!("error converting supplied value for repositories: {e}")); + self + } + pub fn status(mut self, value: T) -> Self + where + T: ::std::convert::TryInto, + T::Error: ::std::fmt::Display, + { + self.status = value + .try_into() + .map_err(|e| format!("error converting supplied value for status: {e}")); + self + } + pub fn total(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::option::Option>, + T::Error: ::std::fmt::Display, + { + self.total = value + .try_into() + .map_err(|e| format!("error converting supplied value for total: {e}")); + self + } + } + impl ::std::convert::TryFrom for super::GithubRepositoryList { + type Error = super::error::ConversionError; + fn try_from( + value: GithubRepositoryList, + ) -> ::std::result::Result { + Ok(Self { + error: value.error?, + loaded: value.loaded?, + repositories: value.repositories?, + status: value.status?, + total: value.total?, + }) + } + } + impl ::std::convert::From for GithubRepositoryList { + fn from(value: super::GithubRepositoryList) -> Self { + Self { + error: Ok(value.error), + loaded: Ok(value.loaded), + repositories: Ok(value.repositories), + status: Ok(value.status), + total: Ok(value.total), + } + } + } + #[derive(Clone, Debug)] pub struct GithubTokenBody { token: ::std::result::Result<::std::string::String, ::std::string::String>, } @@ -3949,6 +4138,34 @@ impl Client { pub fn github_device_cancel(&self) -> builder::GithubDeviceCancel<'_> { builder::GithubDeviceCancel::new(self) } + ///Every GitHub repository the sign-in can reach, as the Link picker's All your repositories + /// + ///offers them, by `owner/name` as GitHub sorts them, with how far loading them has got: the list kept in memory for the run. Nothing loads until `POST /v1/github/repositories/refresh` asks; while the first load runs, the pages that have arrived. Never fails: a failed load is `status: failed` with its `error`. + /// + ///Sends a `GET` request to `/v1/github/repositories` + /// + ///```ignore + ///let response = client.github_repository_list() + /// .send() + /// .await; + ///``` + pub fn github_repository_list(&self) -> builder::GithubRepositoryList<'_> { + builder::GithubRepositoryList::new(self) + } + ///Loads the GitHub repository list again (`GET /user/repos`, 100 a page: page 1, then the + /// + ///rest 4 at a time), answering 204 at once, before GitHub does. A list already loaded keeps showing until the new one has loaded whole; a load already running is left to finish. Each change to the list or its progress sends `changed github_repositories`. With no token the list reads `signed_out`. + /// + ///Sends a `POST` request to `/v1/github/repositories/refresh` + /// + ///```ignore + ///let response = client.github_repository_refresh() + /// .send() + /// .await; + ///``` + pub fn github_repository_refresh(&self) -> builder::GithubRepositoryRefresh<'_> { + builder::GithubRepositoryRefresh::new(self) + } ///Checks a pasted token with GitHub and saves it in the system keyring, replacing any saved /// ///one; PR sync syncs at once. A blank token, or one GitHub answers 401 for, is 422 `invalid_token`; no keyring is 503 `no_keyring`; any other GitHub failure is 502 `github_error`. @@ -4757,6 +4974,106 @@ pub mod builder { } } } + ///Builder for [`Client::github_repository_list`] + /// + ///[`Client::github_repository_list`]: super::Client::github_repository_list + #[derive(Debug, Clone)] + pub struct GithubRepositoryList<'a> { + client: &'a super::Client, + } + impl<'a> GithubRepositoryList<'a> { + pub fn new(client: &'a super::Client) -> Self { + Self { client: client } + } + ///Sends a `GET` request to `/v1/github/repositories` + pub async fn send( + self, + ) -> Result, Error> { + let Self { client } = self; + let url = format!("{}/v1/github/repositories", client.baseurl,); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); + header_map.append( + ::reqwest::header::HeaderName::from_static("api-version"), + ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), + ); + #[allow(unused_mut)] + let mut request = client + .client + .get(url) + .header( + ::reqwest::header::ACCEPT, + ::reqwest::header::HeaderValue::from_static("application/json"), + ) + .headers(header_map) + .build()?; + let info = OperationInfo { + operation_id: "github_repository_list", + }; + client.pre(&mut request, &info).await?; + let result = client.exec(request, &info).await; + client.post(&result, &info).await?; + let response = result?; + match response.status().as_u16() { + 200u16 => ResponseValue::from_response(response).await, + 400u16..=499u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 500u16..=599u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + _ => Err(Error::UnexpectedResponse(response)), + } + } + } + ///Builder for [`Client::github_repository_refresh`] + /// + ///[`Client::github_repository_refresh`]: super::Client::github_repository_refresh + #[derive(Debug, Clone)] + pub struct GithubRepositoryRefresh<'a> { + client: &'a super::Client, + } + impl<'a> GithubRepositoryRefresh<'a> { + pub fn new(client: &'a super::Client) -> Self { + Self { client: client } + } + ///Sends a `POST` request to `/v1/github/repositories/refresh` + pub async fn send(self) -> Result, Error> { + let Self { client } = self; + let url = format!("{}/v1/github/repositories/refresh", client.baseurl,); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); + header_map.append( + ::reqwest::header::HeaderName::from_static("api-version"), + ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), + ); + #[allow(unused_mut)] + let mut request = client + .client + .post(url) + .header( + ::reqwest::header::ACCEPT, + ::reqwest::header::HeaderValue::from_static("application/json"), + ) + .headers(header_map) + .build()?; + let info = OperationInfo { + operation_id: "github_repository_refresh", + }; + client.pre(&mut request, &info).await?; + let result = client.exec(request, &info).await; + client.post(&result, &info).await?; + let response = result?; + match response.status().as_u16() { + 204u16 => Ok(ResponseValue::empty(response)), + 400u16..=499u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 500u16..=599u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + _ => Err(Error::UnexpectedResponse(response)), + } + } + } ///Builder for [`Client::github_token_put`] /// ///[`Client::github_token_put`]: super::Client::github_token_put diff --git a/crates/agentdeck-client/src/repositories.rs b/crates/agentdeck-client/src/repositories.rs index 2aa9087..936199f 100644 --- a/crates/agentdeck-client/src/repositories.rs +++ b/crates/agentdeck-client/src/repositories.rs @@ -1,12 +1,13 @@ //! Repositories as the GUI reads them (spec §4 `GET /v1/repositories`, §11 Notifications), //! and the Links a Repository group's `…` menu makes and takes away (spec §4 //! `/v1/workspaces/{id}/links`, §11 Pull requests view), and each Workspace's Suggestions -//! (`/v1/workspaces/{id}/suggestions`). +//! (`/v1/workspaces/{id}/suggestions`), and the GitHub repository list the Link picker's All +//! your repositories offers (`/v1/github/repositories`). use agentdeck_core::{RepositoryId, RepositoryName, WorkspaceId}; use crate::error::OLDER_DAEMON; -use crate::types::{NewLink, Repository, RepositoryLinks}; +use crate::types::{GithubRepositoryList, NewLink, Repository, RepositoryLinks}; use crate::{ApiError, Client}; /// Every Repository the daemon keeps, by name, each with the Workspaces linking it, archived @@ -116,3 +117,21 @@ pub async fn unlink( .await?; Ok(()) } + +/// Every GitHub repository the sign-in can reach, by `owner/name`, with how far loading them +/// has got (spec §8): `status`, `loaded`, the `total` estimated from the last page, and why a +/// load failed. The daemon keeps it in memory for the run; nothing loads until +/// [`refresh_github_list`] asks. +pub async fn github_list(client: &Client) -> Result { + let list = client.github_repository_list().send().await?; + Ok(list.into_inner()) +} + +/// Asks the daemon to load the GitHub repository list again, as each Link picker does when it +/// opens. Answers at once: pages arrive in the background, each with a `changed +/// github_repositories` event, and a list already loaded keeps showing until the new one has +/// loaded whole. +pub async fn refresh_github_list(client: &Client) -> Result<(), ApiError> { + client.github_repository_refresh().send().await?; + Ok(()) +} diff --git a/crates/agentdeck-core/src/daemon.rs b/crates/agentdeck-core/src/daemon.rs index db52acc..662fcd0 100644 --- a/crates/agentdeck-core/src/daemon.rs +++ b/crates/agentdeck-core/src/daemon.rs @@ -13,7 +13,7 @@ use serde::{Deserialize, Serialize}; /// fails when `openapi.json` changes without a bump. /// /// `0` is every daemon from before it existed, whose `daemon.json` has no `api_version`. -pub const API_VERSION: u32 = 26; +pub const API_VERSION: u32 = 27; /// What `$XDG_RUNTIME_DIR/agentdeck/daemon.json` holds. The daemon writes it once it serves; /// the GUI and the CLI read it to reach the daemon. diff --git a/crates/agentdeck-core/src/ws.rs b/crates/agentdeck-core/src/ws.rs index 0d308a6..6f584bf 100644 --- a/crates/agentdeck-core/src/ws.rs +++ b/crates/agentdeck-core/src/ws.rs @@ -218,6 +218,11 @@ pub enum Entity { /// Its id is the Workspace's. It came with `API_VERSION` 26; an older client skips the /// message. Suggestions, + /// `/v1/github/repositories`: the GitHub repository list the Link picker offers changed, + /// as a page of it arrived, its load began, finished or failed, or the sign-in changed. + /// Its id is always `list`. It came with `API_VERSION` 27; an older client skips the + /// message. + GithubRepositories, } #[cfg(test)] @@ -400,6 +405,13 @@ mod tests { json!({"t": "changed", "entity": "suggestions", "id": "019a0000-0000-7000-8000-000000000001"}), ), + ( + ServerMessage::Changed { + entity: Entity::GithubRepositories, + id: "list".into(), + }, + json!({"t": "changed", "entity": "github_repositories", "id": "list"}), + ), ( ServerMessage::Lagged { channel: 3 }, json!({"t": "lagged", "channel": 3}), diff --git a/crates/agentdeckd/src/api/github.rs b/crates/agentdeckd/src/api/github.rs index 7aabdd0..104ddbf 100644 --- a/crates/agentdeckd/src/api/github.rs +++ b/crates/agentdeckd/src/api/github.rs @@ -1,14 +1,16 @@ -//! The GitHub token and Sign in with GitHub: `/v1/github` (spec §4, §8). No route answers -//! with the token or the client ID. +//! The GitHub token, Sign in with GitHub and the GitHub repository list: `/v1/github` (spec +//! §4, §8). No route answers with the token or the client ID. use dropshot::{ ClientErrorStatusCode, ErrorStatusCode, HttpError, HttpResponseDeleted, HttpResponseOk, - RequestContext, TypedBody, endpoint, + HttpResponseUpdatedNoContent, RequestContext, TypedBody, endpoint, }; use super::{ApiContext, Authorized, client_error, server_error}; use crate::github_auth::AuthError; -use crate::model::{DeviceSignIn, GithubAuthInfo, GithubClientIdBody, GithubTokenBody}; +use crate::model::{ + DeviceSignIn, GithubAuthInfo, GithubClientIdBody, GithubRepositoryList, GithubTokenBody, +}; /// Where the GitHub token comes from, whose it is and what it may do, and whether an OAuth /// client ID is set. Never the token or the client ID. @@ -105,6 +107,33 @@ pub(crate) async fn github_device_cancel( Ok(HttpResponseDeleted()) } +/// Every GitHub repository the sign-in can reach, as the Link picker's All your repositories +/// offers them, by `owner/name` as GitHub sorts them, with how far loading them has got: the +/// list kept in memory for the run. Nothing loads until `POST /v1/github/repositories/refresh` +/// asks; while the first load runs, the pages that have arrived. Never fails: a failed load +/// is `status: failed` with its `error`. +#[endpoint { method = GET, path = "/v1/github/repositories" }] +pub(crate) async fn github_repository_list( + rqctx: RequestContext, + _auth: Authorized, +) -> Result, HttpError> { + Ok(HttpResponseOk(rqctx.context().github_list.list())) +} + +/// Loads the GitHub repository list again (`GET /user/repos`, 100 a page: page 1, then the +/// rest 4 at a time), answering 204 at once, before GitHub does. A list already loaded keeps +/// showing until the new one has loaded whole; a load already running is left to finish. Each +/// change to the list or its progress sends `changed github_repositories`. With no token the +/// list reads `signed_out`. +#[endpoint { method = POST, path = "/v1/github/repositories/refresh" }] +pub(crate) async fn github_repository_refresh( + rqctx: RequestContext, + _auth: Authorized, +) -> Result { + rqctx.context().github_list.refresh().await; + Ok(HttpResponseUpdatedNoContent()) +} + /// The status and `error_code` of each failure. fn http_error(err: AuthError) -> HttpError { let message = err.to_string(); diff --git a/crates/agentdeckd/src/api/mod.rs b/crates/agentdeckd/src/api/mod.rs index 1c9c387..179e54e 100644 --- a/crates/agentdeckd/src/api/mod.rs +++ b/crates/agentdeckd/src/api/mod.rs @@ -30,6 +30,7 @@ use crate::config::Config; use crate::db::{Db, DbError}; use crate::events::Events; use crate::github_auth::GithubAuth; +use crate::github_list::GithubList; use crate::prsync::PrSync; use crate::prsync::github::Github; use crate::suggestions::Suggestions; @@ -60,6 +61,8 @@ pub struct ApiContext { pub events: Events, /// Each Workspace's Suggestions, for `/v1/workspaces/{id}/suggestions`. pub suggestions: Suggestions, + /// The GitHub repository list, for `/v1/github/repositories`. + pub github_list: GithubList, } /// Every endpoint. @@ -94,6 +97,8 @@ pub fn api() -> ApiDescription { api.register(github::github_client_id_delete), api.register(github::github_device_start), api.register(github::github_device_cancel), + api.register(github::github_repository_list), + api.register(github::github_repository_refresh), api.register(settings::settings_get), api.register(settings::settings_update), api.register(panes::pane_create), @@ -235,7 +240,7 @@ mod tests { /// `openapi.json`'s fingerprint when [`agentdeck_core::API_VERSION`] was last set, /// and that version. Clients tell an older daemon by its API version, so a route or /// field added without a bump would go unnoticed: they would call it and get a 404. - const FINGERPRINT_AT_API_VERSION: (u64, u32) = (0xc935_79a3_d8ff_d5cc, 26); + const FINGERPRINT_AT_API_VERSION: (u64, u32) = (0xd70e_7ecf_0702_a3ac, 27); /// FNV-1a: stable across Rust releases, unlike `DefaultHasher`. fn fingerprint(text: &str) -> u64 { diff --git a/crates/agentdeckd/src/daemon.rs b/crates/agentdeckd/src/daemon.rs index a1f2905..5ca62d4 100644 --- a/crates/agentdeckd/src/daemon.rs +++ b/crates/agentdeckd/src/daemon.rs @@ -14,6 +14,7 @@ use crate::config::{self, Config}; use crate::db::Db; use crate::events::Events; use crate::github_auth::{self, GithubAuth, device, keyring}; +use crate::github_list::GithubList; use crate::instance::Instance; use crate::paths::Paths; use crate::prsync::{self, PrSync}; @@ -105,6 +106,7 @@ async fn serve(paths: &Paths, instance: &Instance) -> anyhow::Result<()> { github.clone(), ); suggestions.watch(); + let github_list = GithubList::new(events.clone(), credentials.clone(), github.clone()); let token = auth::new_token(); let context = ApiContext { db, @@ -117,6 +119,7 @@ async fn serve(paths: &Paths, instance: &Instance) -> anyhow::Result<()> { terminals: terminals.clone(), events, suggestions, + github_list, }; let config = ConfigDropshot { bind_address: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)), diff --git a/crates/agentdeckd/src/github_list.rs b/crates/agentdeckd/src/github_list.rs new file mode 100644 index 0000000..13d9536 --- /dev/null +++ b/crates/agentdeckd/src/github_list.rs @@ -0,0 +1,327 @@ +//! The GitHub repository list (spec §8): every repository the sign-in can reach, as the Link +//! picker's All your repositories offers them. +//! +//! Nothing loads until a client asks with [`GithubList::refresh`], which the GUI does each +//! time a picker opens. A load reads `GET /user/repos` 100 a page, by `owner/name`: page 1 +//! first, whose `Link` header names the last page, then the last page, so the total is exact +//! early, then the pages between, [`PAGES_IN_FLIGHT`] at once. About 1,100 repositories take +//! 12 requests. Each page is served as it arrives while no list is held; once one is, a +//! refresh runs quietly under it and replaces it whole. One load runs at a time. +//! +//! The list is kept in memory for the run, for the sign-in it was read with: when the token +//! changes, it is dropped and, if a client had asked for it, loaded again. Every change to it +//! or its progress sends `changed github_repositories`. `search/repositories` is never called: +//! it allows 30 requests a minute and misses repositories you only collaborate on. + +use std::sync::{Arc, Mutex, MutexGuard}; + +use agentdeck_core::ws::Entity; +use futures_util::{StreamExt as _, TryStreamExt as _}; + +use crate::events::Events; +use crate::github_auth::{GithubAuth, NoToken}; +use crate::model::{GithubListStatus, GithubRepositoryList, Repository}; +use crate::prsync::github::{Github, GithubError, REPOS_PAGE_SIZE, RemoteRepository, ReposPage}; + +/// How many pages after the first are read at once. +const PAGES_IN_FLIGHT: usize = 4; + +/// The id a [`Entity::GithubRepositories`] event names: there is one list. +const LIST_ID: &str = "list"; + +/// The list, kept in memory for the run; clones share it. +#[derive(Clone)] +pub struct GithubList { + inner: Arc, +} + +struct Inner { + events: Events, + auth: GithubAuth, + github: Github, + state: Mutex, +} + +#[derive(Default)] +struct State { + /// Bumped when the sign-in changes, so a load from before stores nothing. + generation: u64, + /// Whether a load of this generation runs. + loading: bool, + /// Whether a client has asked for the list since the sign-in last changed. + asked: bool, + /// The last list loaded whole. + held: Option>, + /// While no list is held, the first load's pages that have arrived, by number from 1. + pages: Vec>>, + /// The first load's last page number, once page 1 has answered. + last: Option, + /// Why the last load failed; cleared when one succeeds. + failed: Option, + /// The last refresh found no token. + signed_out: bool, +} + +impl State { + /// The list as `GET /v1/github/repositories` answers it. + fn list(&self) -> GithubRepositoryList { + let (status, repositories, total) = match &self.held { + Some(held) => (GithubListStatus::Loaded, held.clone(), Some(len(held))), + None if self.loading => { + let repositories: Vec = + self.pages.iter().flatten().flatten().cloned().collect(); + (GithubListStatus::Loading, repositories, self.estimate()) + } + None if self.failed.is_some() => (GithubListStatus::Failed, Vec::new(), None), + None if self.signed_out => (GithubListStatus::SignedOut, Vec::new(), None), + None => (GithubListStatus::NotLoaded, Vec::new(), None), + }; + GithubRepositoryList { + status, + loaded: len(&repositories), + total, + error: self.failed.clone(), + repositories, + } + } + + /// About how many repositories the first load will hold: every page before the last full, + /// and the last one as it came, or full until it has. + fn estimate(&self) -> Option { + let last = self.last?; + let last_page = (self.pages.get(last as usize - 1)) + .and_then(Option::as_ref) + .map_or(REPOS_PAGE_SIZE, |page| len(page)); + Some((last - 1) * REPOS_PAGE_SIZE + last_page) + } +} + +fn len(items: &[T]) -> u32 { + u32::try_from(items.len()).unwrap_or(u32::MAX) +} + +fn repository(found: RemoteRepository) -> Repository { + Repository { + id: found.id, + name: found.name, + url: found.url, + private: found.private, + archived: found.archived, + } +} + +impl GithubList { + /// A list read from `github` with `auth`'s token, announced on `events`. Watches the + /// token for changes, so must be called inside a tokio runtime. + pub fn new(events: Events, auth: GithubAuth, github: Github) -> GithubList { + let list = GithubList { + inner: Arc::new(Inner { + events, + auth, + github, + state: Mutex::new(State::default()), + }), + }; + let watching = list.clone(); + let mut changes = list.inner.auth.token_changes(); + tokio::spawn(async move { + while changes.changed().await.is_ok() { + watching.sign_in_changed().await; + } + }); + list + } + + /// The list as it stands, with its progress. + pub fn list(&self) -> GithubRepositoryList { + self.state().list() + } + + /// Loads the list again in the background, unless a load runs already. With no token it + /// reads signed out; with a token GitHub rejects, failed. + pub async fn refresh(&self) { + let token = self.inner.auth.current_token().await; + let (generation, quiet) = { + let mut state = self.state(); + state.asked = true; + if state.loading { + return; + } + let quiet = token.is_ok() && state.held.is_some(); + match &token { + Ok(_) => { + state.loading = true; + state.signed_out = false; + if !quiet { + state.pages.clear(); + state.last = None; + state.failed = None; + } + } + Err(NoToken::None) => { + *state = State { + generation: state.generation, + asked: true, + signed_out: true, + ..State::default() + }; + } + Err(NoToken::Rejected) => { + *state = State { + generation: state.generation, + asked: true, + failed: Some(GithubError::Unauthorized.to_string()), + ..State::default() + }; + } + } + (state.generation, quiet) + }; + if !quiet { + self.changed(); + } + if let Ok(token) = token { + let this = self.clone(); + tokio::spawn(async move { this.load(generation, token).await }); + } + } + + /// Drops the list read with the token before, and loads it again with the new one if a + /// client had asked for it. + async fn sign_in_changed(&self) { + let asked = { + let mut state = self.state(); + let asked = state.asked; + *state = State { + generation: state.generation + 1, + ..State::default() + }; + asked + }; + self.changed(); + if asked { + self.refresh().await; + } + } + + /// Reads every page with `token` and keeps the list, unless the sign-in changed meanwhile. + /// A list held already is replaced whole, and a failure keeps it, saying why; either sends + /// `changed` only when what clients read differs. + async fn load(&self, generation: u64, token: String) { + let loaded = self.read_pages(generation, token).await; + let changed = { + let mut state = self.state(); + if state.generation != generation { + return; + } + let before = state.held.is_some().then(|| state.list()); + state.loading = false; + state.pages.clear(); + state.last = None; + match loaded { + Ok(list) => { + state.held = Some(list); + state.failed = None; + } + Err(err) => { + tracing::warn!("loading the GitHub repository list: {err}"); + state.failed = Some(err.to_string()); + } + } + before.is_none_or(|before| before != state.list()) + }; + if changed { + self.changed(); + } + } + + /// Every page, in order: page 1, then the last, then those between. While no list is held, + /// each is kept as it arrives. + async fn read_pages( + &self, + generation: u64, + token: String, + ) -> Result, GithubError> { + let (first, token) = self.first_page(token).await?; + let last = first.last.unwrap_or(1).max(1); + let mut pages: Vec>> = vec![None; last as usize]; + self.arrived(generation, &mut pages, 1, first, Some(last)); + let order = (last > 1).then_some(last).into_iter().chain(2..last); + let github = &self.inner.github; + let token = token.as_str(); + let mut reads = futures_util::stream::iter(order.map(|page| async move { + github.user_repos_page(token, page).await.map(|read| (page, read)) + })) + .buffer_unordered(PAGES_IN_FLIGHT); + while let Some((page, read)) = reads.try_next().await.inspect_err(|err| { + if matches!(err, GithubError::Unauthorized) { + self.inner.auth.rejected(); + } + })? { + self.arrived(generation, &mut pages, page, read, None); + } + Ok(pages.into_iter().flatten().flatten().collect()) + } + + /// Page 1 and the token that read it: a 401 reads the token's sources again and tries + /// once more, then counts the token as rejected. + async fn first_page(&self, token: String) -> Result<(ReposPage, String), GithubError> { + let github = &self.inner.github; + match github.user_repos_page(&token, 1).await { + Err(GithubError::Unauthorized) => { + let fresh = (self.inner.auth.reread().await) + .map_err(|_| GithubError::Unauthorized)?; + match github.user_repos_page(&fresh, 1).await { + Err(GithubError::Unauthorized) => { + self.inner.auth.rejected(); + Err(GithubError::Unauthorized) + } + read => read.map(|page| (page, fresh)), + } + } + read => read.map(|page| (page, token)), + } + } + + /// Keeps page `page` in `pages`, and, while no list is held and the sign-in is the same, + /// serves it at once; `last` is the last page's number, read from page 1. + fn arrived( + &self, + generation: u64, + pages: &mut [Option>], + page: u32, + read: ReposPage, + last: Option, + ) { + let read: Vec = read.repositories.into_iter().map(repository).collect(); + let at = page as usize - 1; + { + let mut state = self.state(); + if state.generation == generation && state.held.is_none() { + state.pages.resize(pages.len(), None); + state.pages[at] = Some(read.clone()); + if last.is_some() { + state.last = last; + } + } else { + pages[at] = Some(read); + return; + } + } + pages[at] = Some(read); + self.changed(); + } + + fn changed(&self) { + self.inner + .events + .changed(Entity::GithubRepositories, LIST_ID); + } + + fn state(&self) -> MutexGuard<'_, State> { + self.inner + .state + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + } +} diff --git a/crates/agentdeckd/src/main.rs b/crates/agentdeckd/src/main.rs index 046c900..087bfd8 100644 --- a/crates/agentdeckd/src/main.rs +++ b/crates/agentdeckd/src/main.rs @@ -13,6 +13,7 @@ mod daemon; mod db; mod events; mod github_auth; +mod github_list; mod instance; mod logging; mod model; diff --git a/crates/agentdeckd/src/model.rs b/crates/agentdeckd/src/model.rs index d7ecc49..a31c036 100644 --- a/crates/agentdeckd/src/model.rs +++ b/crates/agentdeckd/src/model.rs @@ -114,6 +114,41 @@ pub struct Repository { pub archived: bool, } +/// `GET /v1/github/repositories`: every GitHub repository the sign-in can reach, as the Link +/// picker offers them (spec §8), with how far loading them has got. Kept in memory for the run. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +pub struct GithubRepositoryList { + /// Where loading the list stands. + pub status: GithubListStatus, + /// How many repositories have loaded: `repositories`' length. + pub loaded: u32, + /// About how many there are, from the last page's number in page 1's `Link` header, then + /// exact once the last page has loaded; `None` until page 1 answers. + pub total: Option, + /// Why the last load failed, while `status` is `failed`: GitHub's message, or why the + /// request failed. + pub error: Option, + /// The repositories loaded so far, by `owner/name` as GitHub sorts them. While a list is + /// refreshed, the one before it, whole. + pub repositories: Vec, +} + +/// Where loading the GitHub repository list stands. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum GithubListStatus { + /// Nothing asked for it yet this run, or since the sign-in changed. + NotLoaded, + /// The first load runs: `repositories` holds the pages that have arrived. + Loading, + /// Every page loaded. A refresh runs quietly under it, the list changing once it ends. + Loaded, + /// The load failed (no connection, a rate limit, a token GitHub rejects): `error` says why. + Failed, + /// There's no GitHub token to list with. + SignedOut, +} + /// A pull request PR sync keeps (spec §3, §8), as it last saw it. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] pub struct PullRequest { diff --git a/crates/agentdeckd/src/prsync/github.rs b/crates/agentdeckd/src/prsync/github.rs index eb20846..fe0cf99 100644 --- a/crates/agentdeckd/src/prsync/github.rs +++ b/crates/agentdeckd/src/prsync/github.rs @@ -260,6 +260,52 @@ impl Github { Ok(Some(repository.into())) } + /// Page `page` (from 1) of every repository the token's user can reach, read with the + /// REST API's `GET /user/repos?sort=full_name&direction=asc&per_page=100`: owned, + /// collaborator and organisation ones, by `owner/name`. Tried again after each of + /// `RETRY_WAITS` while it fails for a reason that may pass. + pub async fn user_repos_page(&self, token: &str, page: u32) -> Result { + retrying(GithubError::may_pass, || self.user_repos_page_once(token, page)).await + } + + /// [`Github::user_repos_page`], once. + async fn user_repos_page_once(&self, token: &str, page: u32) -> Result { + let url = format!("{}/user/repos", self.rest); + let response = self + .http + .get(url) + .query(&[ + ("sort", "full_name"), + ("direction", "asc"), + ("per_page", &REPOS_PAGE_SIZE.to_string()), + ("page", &page.to_string()), + ]) + .bearer_auth(token) + .header("accept", "application/vnd.github+json") + .header("x-github-api-version", REST_API_VERSION) + .send() + .await?; + let status = response.status(); + if status == reqwest::StatusCode::UNAUTHORIZED { + return Err(GithubError::Unauthorized); + } + if !status.is_success() { + let body = response.text().await.unwrap_or_default(); + return Err(GithubError::Status { + status: status.as_u16(), + message: message(&body), + }); + } + let last = (response.headers().get(reqwest::header::LINK)) + .and_then(|link| link.to_str().ok()) + .and_then(last_page); + let repositories: Vec = response.json().await?; + Ok(ReposPage { + repositories: repositories.into_iter().map(Into::into).collect(), + last, + }) + } + /// Who `token` belongs to, and its scopes. A token GitHub rejects is /// [`GithubError::Unauthorized`]. pub async fn viewer(&self, token: &str) -> Result { @@ -543,7 +589,35 @@ where } } -/// A Repository as the REST API's `GET /repos/{owner}/{repo}` answers it. +/// Repositories per page of `GET /user/repos`: the most GitHub gives. +pub const REPOS_PAGE_SIZE: u32 = 100; + +/// One page of `GET /user/repos`. +#[derive(Debug, PartialEq, Eq)] +pub struct ReposPage { + /// The page's repositories, in GitHub's order. + pub repositories: Vec, + /// The last page's number, from the `Link` header's `rel="last"`; `None` when there's + /// none, as on the last page itself. + pub last: Option, +} + +/// The `page` of the `rel="last"` URL in a `Link` header; `None` when it has none, or one +/// that can't be read. +fn last_page(header: &str) -> Option { + header.split(',').find_map(|link| { + let (url, params) = link.trim().split_once(';')?; + let last = (params.split(';')).any(|param| param.trim() == "rel=\"last\""); + if !last { + return None; + } + let url = reqwest::Url::parse(url.trim().strip_prefix('<')?.strip_suffix('>')?).ok()?; + let page = url.query_pairs().find(|(key, _)| key == "page")?.1; + page.parse().ok() + }) +} + +/// A Repository as the REST API's `GET /repos/{owner}/{repo}` and `GET /user/repos` answer it. #[derive(Deserialize)] struct RestRepository { id: u64, @@ -1115,6 +1189,42 @@ mod tests { }) } + mod last_page { + use super::*; + + #[test] + fn should_read_the_last_pages_number_from_the_link_header() { + let header = "; rel=\"next\", \ + ; rel=\"last\""; + + assert_eq!(last_page(header), Some(12)); + } + + #[test] + fn should_find_it_wherever_it_sits_among_the_links() { + let header = "; rel=\"last\", \ + ; rel=\"first\""; + + assert_eq!(last_page(header), Some(12)); + } + + #[test] + fn should_be_none_on_the_last_page_itself() { + let header = "; rel=\"prev\", \ + ; rel=\"first\""; + + assert_eq!(last_page(header), None); + } + + #[test] + fn should_be_none_for_a_link_it_cannot_read() { + assert_eq!(last_page("; rel=\"last\""), None); + assert_eq!(last_page("; rel=\"last\""), None); + } + } + mod parse_scopes { use super::*; diff --git a/crates/agentdeckd/src/suggestions/mod.rs b/crates/agentdeckd/src/suggestions/mod.rs index 6c184fc..655cabd 100644 --- a/crates/agentdeckd/src/suggestions/mod.rs +++ b/crates/agentdeckd/src/suggestions/mod.rs @@ -320,7 +320,11 @@ impl Due { Err(_) => self.all = true, }, Entity::Repository => self.all = true, - Entity::PrSync | Entity::Settings | Entity::PullRequest | Entity::Suggestions => {} + Entity::PrSync + | Entity::Settings + | Entity::PullRequest + | Entity::Suggestions + | Entity::GithubRepositories => {} }, ServerMessage::GithubAuth { .. } => self.all = true, _ => {} diff --git a/crates/agentdeckd/tests/integration/github_list.rs b/crates/agentdeckd/tests/integration/github_list.rs new file mode 100644 index 0000000..0ca6305 --- /dev/null +++ b/crates/agentdeckd/tests/integration/github_list.rs @@ -0,0 +1,456 @@ +//! The GitHub repository list for the Link picker: `GET /v1/github/repositories`, +//! `POST /v1/github/repositories/refresh` and `changed github_repositories` (spec §4, §5, §8), +//! with httpmock as GitHub's REST API answering `GET /user/repos` page by page. + +use std::time::Duration; + +use agentdeck_client::Client; +use agentdeck_client::types::{GithubListStatus, GithubRepositoryList, GithubTokenBody}; +use agentdeck_core::ws::{Entity, ServerMessage}; +use httpmock::MockServer; + +use crate::support::github::{ + RestRepo, mock_search_repositories, mock_user_repos, mock_user_repos_failing, + mock_user_repos_page, mock_viewer, set_gh_token, user_repos, +}; +use crate::support::terminal::eventually; +use crate::support::ws::{Frame, Ws}; +use crate::support::{TestDaemon, set_daemon_env}; + +const TOKEN: &str = "gho_test"; + +/// A daemon whose `gh` prints [`TOKEN`] and whose GitHub is `github`. +async fn signed_in(github: &MockServer) -> TestDaemon { + mock_viewer(github, TOKEN, "octocat", None); + let dirs = tempfile::tempdir().expect("a temp dir"); + set_gh_token(dirs.path(), Some(TOKEN)); + TestDaemon::start_with_github(dirs, &github.url("/graphql")).await +} + +async fn list(client: &Client) -> GithubRepositoryList { + let response = client.github_repository_list().send().await; + let response = response.expect("read the GitHub repository list"); + assert_eq!(response.status().as_u16(), 200); + response.into_inner() +} + +async fn refresh(client: &Client) { + let response = client.github_repository_refresh().send().await; + let response = response.expect("refresh the GitHub repository list"); + assert_eq!(response.status().as_u16(), 204); +} + +/// Waits until the list reads `status`, and answers it. +async fn until_status(client: &Client, status: GithubListStatus) -> GithubRepositoryList { + eventually(&format!("the list {status:?}"), || async { + let read = list(client).await; + (read.status == status).then_some(read) + }) + .await +} + +fn names(list: &GithubRepositoryList) -> Vec { + (list.repositories.iter()) + .map(|r| r.name.to_string()) + .collect() +} + +fn named(repos: &[RestRepo]) -> Vec { + repos.iter().map(|r| r.name.to_owned()).collect() +} + +/// Waits for the next `changed github_repositories`. +async fn changed(ws: &mut Ws) { + ws.until(|frame| match frame { + Frame::Message(ServerMessage::Changed { + entity: Entity::GithubRepositories, + id, + }) => { + assert_eq!(id, "list"); + Some(()) + } + _ => None, + }) + .await; +} + +mod get_v1_github_repositories { + use super::*; + + #[tokio::test] + async fn should_read_not_loaded_until_a_refresh_asks_200() { + let github = MockServer::start_async().await; + let pages = mock_user_repos(&github, TOKEN, &user_repos(3)); + let daemon = signed_in(&github).await; + + let read = list(&daemon.client).await; + + assert_eq!(read.status, GithubListStatus::NotLoaded); + assert_eq!((read.loaded, read.total), (0, None)); + assert!(read.repositories.is_empty()); + assert_eq!(pages[0].calls_async().await, 0); + } + + mod paging { + use super::*; + + #[tokio::test] + async fn should_list_every_page_in_githubs_order_once_loaded_200() { + let github = MockServer::start_async().await; + let repos = user_repos(250); + let pages = mock_user_repos(&github, TOKEN, &repos); + let daemon = signed_in(&github).await; + + refresh(&daemon.client).await; + let read = until_status(&daemon.client, GithubListStatus::Loaded).await; + + assert_eq!(names(&read), named(&repos)); + assert_eq!((read.loaded, read.total), (250, Some(250))); + assert_eq!(read.error, None); + let private: Vec = read.repositories.iter().map(|r| r.private).collect(); + assert_eq!(private, repos.iter().map(|r| r.private).collect::>()); + assert_eq!(read.repositories[1].id.get(), repos[1].id); + assert_eq!(read.repositories[1].url, repos[1].url()); + for page in &pages { + assert_eq!(page.calls_async().await, 1); + } + } + + #[tokio::test] + async fn should_list_a_single_page_without_a_link_header_200() { + let github = MockServer::start_async().await; + let repos = user_repos(40); + mock_user_repos(&github, TOKEN, &repos); + let daemon = signed_in(&github).await; + + refresh(&daemon.client).await; + let read = until_status(&daemon.client, GithubListStatus::Loaded).await; + + assert_eq!(names(&read), named(&repos)); + assert_eq!((read.loaded, read.total), (40, Some(40))); + } + + #[tokio::test] + async fn should_serve_page_one_while_the_rest_load_estimating_the_total_200() { + let github = MockServer::start_async().await; + let repos = user_repos(250); + let slow = Duration::from_secs(2); + mock_user_repos_page(&github, TOKEN, &repos, 1, Duration::ZERO); + mock_user_repos_page(&github, TOKEN, &repos, 2, slow); + mock_user_repos_page(&github, TOKEN, &repos, 3, slow); + let daemon = signed_in(&github).await; + + refresh(&daemon.client).await; + let read = eventually("page 1", || async { + let read = list(&daemon.client).await; + (read.loaded > 0).then_some(read) + }) + .await; + + assert_eq!(read.status, GithubListStatus::Loading); + assert_eq!(names(&read), named(&repos[..100])); + assert_eq!((read.loaded, read.total), (100, Some(300))); + let read = until_status(&daemon.client, GithubListStatus::Loaded).await; + assert_eq!(read.loaded, 250); + } + + #[tokio::test] + async fn should_load_the_last_page_first_and_count_the_total_exactly_200() { + let github = MockServer::start_async().await; + let repos = user_repos(250); + mock_user_repos_page(&github, TOKEN, &repos, 1, Duration::ZERO); + mock_user_repos_page(&github, TOKEN, &repos, 2, Duration::from_secs(2)); + mock_user_repos_page(&github, TOKEN, &repos, 3, Duration::ZERO); + let daemon = signed_in(&github).await; + + refresh(&daemon.client).await; + let read = eventually("pages 1 and 3", || async { + let read = list(&daemon.client).await; + (read.loaded == 150).then_some(read) + }) + .await; + + assert_eq!(read.status, GithubListStatus::Loading); + assert_eq!(read.total, Some(250)); + let expected = [named(&repos[..100]), named(&repos[200..])].concat(); + assert_eq!(names(&read), expected, "in GitHub's order, page 2 still to come"); + } + + #[tokio::test] + async fn should_send_changed_as_the_load_begins_each_page_arrives_and_it_ends() { + let github = MockServer::start_async().await; + mock_user_repos(&github, TOKEN, &user_repos(250)); + let daemon = signed_in(&github).await; + let mut ws = Ws::connect(&daemon).await; + + refresh(&daemon.client).await; + for _ in 0..5 { + changed(&mut ws).await; + } + + assert_eq!(list(&daemon.client).await.status, GithubListStatus::Loaded); + } + } + + mod memory { + use super::*; + + #[tokio::test] + async fn should_keep_the_list_across_reads_without_asking_github_again_200() { + let github = MockServer::start_async().await; + let repos = user_repos(150); + let pages = mock_user_repos(&github, TOKEN, &repos); + let daemon = signed_in(&github).await; + refresh(&daemon.client).await; + until_status(&daemon.client, GithubListStatus::Loaded).await; + + let first = list(&daemon.client).await; + let second = list(&daemon.client).await; + + assert_eq!(first, second); + assert_eq!(names(&second), named(&repos)); + for page in &pages { + assert_eq!(page.calls_async().await, 1); + } + } + } + + mod search { + use super::*; + + #[tokio::test] + async fn should_never_call_githubs_repository_search_200() { + let github = MockServer::start_async().await; + let search = mock_search_repositories(&github); + mock_user_repos(&github, TOKEN, &user_repos(250)); + let daemon = signed_in(&github).await; + + refresh(&daemon.client).await; + until_status(&daemon.client, GithubListStatus::Loaded).await; + refresh(&daemon.client).await; + list(&daemon.client).await; + + assert_eq!(search.calls_async().await, 0); + } + } +} + +mod post_v1_github_repositories_refresh { + use super::*; + + #[tokio::test] + async fn should_load_again_quietly_showing_the_list_before_until_it_ends_204() { + let github = MockServer::start_async().await; + let before = user_repos(150); + let mut pages = mock_user_repos(&github, TOKEN, &before); + let daemon = signed_in(&github).await; + refresh(&daemon.client).await; + until_status(&daemon.client, GithubListStatus::Loaded).await; + for page in &mut pages { + page.delete_async().await; + } + let after = user_repos(250); + mock_user_repos_page(&github, TOKEN, &after, 1, Duration::ZERO); + mock_user_repos_page(&github, TOKEN, &after, 2, Duration::from_secs(1)); + mock_user_repos_page(&github, TOKEN, &after, 3, Duration::ZERO); + + refresh(&daemon.client).await; + let meanwhile = list(&daemon.client).await; + + assert_eq!(meanwhile.status, GithubListStatus::Loaded); + assert_eq!(names(&meanwhile), named(&before)); + let read = eventually("the new list", || async { + let read = list(&daemon.client).await; + (read.loaded == 250).then_some(read) + }) + .await; + assert_eq!(read.status, GithubListStatus::Loaded); + assert_eq!(names(&read), named(&after)); + } + + #[tokio::test] + async fn should_leave_a_load_already_running_to_finish_204() { + let github = MockServer::start_async().await; + let repos = user_repos(150); + let first = mock_user_repos_page(&github, TOKEN, &repos, 1, Duration::ZERO); + mock_user_repos_page(&github, TOKEN, &repos, 2, Duration::from_secs(1)); + let daemon = signed_in(&github).await; + + refresh(&daemon.client).await; + refresh(&daemon.client).await; + until_status(&daemon.client, GithubListStatus::Loaded).await; + + assert_eq!(first.calls_async().await, 1); + } + + mod failure { + use super::*; + + #[tokio::test] + async fn should_fail_on_a_5xx_after_trying_three_times_then_load_on_retry_204() { + let github = MockServer::start_async().await; + let broken = + mock_user_repos_failing(&github, 1, 502, "Server Error", &[("x-ignored", "1")]); + let daemon = signed_in(&github).await; + + refresh(&daemon.client).await; + let read = until_status(&daemon.client, GithubListStatus::Failed).await; + + assert_eq!(read.error.as_deref(), Some("GitHub answered 502: Server Error")); + assert!(read.repositories.is_empty()); + assert_eq!(broken.calls_async().await, 3); + broken.delete_async().await; + let repos = user_repos(120); + mock_user_repos(&github, TOKEN, &repos); + refresh(&daemon.client).await; + let read = until_status(&daemon.client, GithubListStatus::Loaded).await; + assert_eq!(names(&read), named(&repos)); + assert_eq!(read.error, None); + } + + #[tokio::test] + async fn should_fail_at_once_when_github_limits_the_rate_403_204() { + let github = MockServer::start_async().await; + let limited = mock_user_repos_failing( + &github, + 1, + 403, + "API rate limit exceeded for user ID 1.", + &[("x-ratelimit-remaining", "0")], + ); + let daemon = signed_in(&github).await; + + refresh(&daemon.client).await; + let read = until_status(&daemon.client, GithubListStatus::Failed).await; + + assert_eq!( + read.error.as_deref(), + Some("GitHub answered 403: API rate limit exceeded for user ID 1.") + ); + assert_eq!(limited.calls_async().await, 1); + } + + #[tokio::test] + async fn should_fail_when_github_answers_too_many_requests_429_204() { + let github = MockServer::start_async().await; + mock_user_repos_failing(&github, 1, 429, "Too Many Requests", &[("retry-after", "60")]); + let daemon = signed_in(&github).await; + + refresh(&daemon.client).await; + let read = until_status(&daemon.client, GithubListStatus::Failed).await; + + assert_eq!( + read.error.as_deref(), + Some("GitHub answered 429: Too Many Requests") + ); + } + + #[tokio::test] + async fn should_fail_whole_when_a_later_page_fails_keeping_none_204() { + let github = MockServer::start_async().await; + let repos = user_repos(250); + mock_user_repos_page(&github, TOKEN, &repos, 1, Duration::ZERO); + mock_user_repos_page(&github, TOKEN, &repos, 3, Duration::ZERO); + mock_user_repos_failing(&github, 2, 403, "Forbidden", &[]); + let daemon = signed_in(&github).await; + + refresh(&daemon.client).await; + let read = until_status(&daemon.client, GithubListStatus::Failed).await; + + assert_eq!(read.error.as_deref(), Some("GitHub answered 403: Forbidden")); + assert_eq!((read.loaded, read.total), (0, None)); + assert!(read.repositories.is_empty()); + } + + #[tokio::test] + async fn should_fail_when_github_rejects_the_token_401_204() { + let github = MockServer::start_async().await; + mock_user_repos_failing(&github, 1, 401, "Bad credentials", &[]); + let daemon = signed_in(&github).await; + + refresh(&daemon.client).await; + let read = until_status(&daemon.client, GithubListStatus::Failed).await; + + assert_eq!(read.error.as_deref(), Some("GitHub rejected the token")); + } + + #[tokio::test] + async fn should_keep_the_list_it_had_when_a_refresh_fails_saying_why_204() { + let github = MockServer::start_async().await; + let repos = user_repos(150); + let mut pages = mock_user_repos(&github, TOKEN, &repos); + let daemon = signed_in(&github).await; + refresh(&daemon.client).await; + until_status(&daemon.client, GithubListStatus::Loaded).await; + for page in &mut pages { + page.delete_async().await; + } + mock_user_repos_failing(&github, 1, 403, "API rate limit exceeded", &[]); + let mut ws = Ws::connect(&daemon).await; + + refresh(&daemon.client).await; + changed(&mut ws).await; + + let read = list(&daemon.client).await; + assert_eq!(read.status, GithubListStatus::Loaded); + assert_eq!(names(&read), named(&repos)); + assert_eq!( + read.error.as_deref(), + Some("GitHub answered 403: API rate limit exceeded") + ); + } + } + + mod signed_out { + use super::*; + + #[tokio::test] + async fn should_read_signed_out_without_asking_github_204() { + let github = MockServer::start_async().await; + let pages = mock_user_repos(&github, TOKEN, &user_repos(3)); + let daemon = TestDaemon::start_with_github( + tempfile::tempdir().expect("a temp dir"), + &github.url("/graphql"), + ) + .await; + + refresh(&daemon.client).await; + let read = until_status(&daemon.client, GithubListStatus::SignedOut).await; + + assert!(read.repositories.is_empty()); + assert_eq!(pages[0].calls_async().await, 0); + } + + #[tokio::test] + async fn should_load_the_new_sign_ins_list_when_the_token_changes_204() { + const OTHER: &str = "gho_other"; + let github = MockServer::start_async().await; + mock_viewer(&github, TOKEN, "octocat", None); + mock_viewer(&github, OTHER, "hubot", None); + let theirs = user_repos(30); + mock_user_repos(&github, TOKEN, &user_repos(120)); + mock_user_repos(&github, OTHER, &theirs); + let dirs = tempfile::tempdir().expect("a temp dir"); + set_gh_token(dirs.path(), Some(TOKEN)); + set_daemon_env(dirs.path(), &[("AGENTDECK_KEYRING", "memory")]); + let daemon = TestDaemon::start_with_github(dirs, &github.url("/graphql")).await; + refresh(&daemon.client).await; + until_status(&daemon.client, GithubListStatus::Loaded).await; + + let saved = (daemon.client.github_token_put()) + .body(GithubTokenBody { + token: OTHER.into(), + }) + .send() + .await; + saved.expect("save the other token"); + + let read = eventually("hubot's list", || async { + let read = list(&daemon.client).await; + (read.status == GithubListStatus::Loaded && read.loaded == 30).then_some(read) + }) + .await; + assert_eq!(names(&read), named(&theirs)); + } + } +} diff --git a/crates/agentdeckd/tests/integration/main.rs b/crates/agentdeckd/tests/integration/main.rs index 1882b7f..dc65b8d 100644 --- a/crates/agentdeckd/tests/integration/main.rs +++ b/crates/agentdeckd/tests/integration/main.rs @@ -7,6 +7,7 @@ mod auth; mod daemon; mod folders; mod github_auth; +mod github_list; mod health; mod hosted; mod keyring; diff --git a/crates/agentdeckd/tests/integration/repositories_client.rs b/crates/agentdeckd/tests/integration/repositories_client.rs index b2c7302..222f91f 100644 --- a/crates/agentdeckd/tests/integration/repositories_client.rs +++ b/crates/agentdeckd/tests/integration/repositories_client.rs @@ -4,16 +4,19 @@ //! the same way (spec §12). use agentdeck_client::Client; -use agentdeck_client::repositories::{link, list, resolve, unlink}; -use agentdeck_client::types::{NewLink, NewWorkspace, Repository}; +use agentdeck_client::repositories::{ + github_list, link, list, refresh_github_list, resolve, unlink, +}; +use agentdeck_client::types::{GithubListStatus, NewLink, NewWorkspace, Repository}; use agentdeck_core::{RepositoryId, WorkspaceId}; use httpmock::MockServer; use crate::support::TestDaemon; use crate::support::github::{ - Pr, RestRepo, mock_rest_repo, mock_rest_repo_missing, mock_search, mock_viewer, repository_id, - set_gh_token, + Pr, RestRepo, mock_rest_repo, mock_rest_repo_missing, mock_search, mock_user_repos, + mock_viewer, repository_id, set_gh_token, user_repos, }; +use crate::support::terminal::eventually; const TOKEN: &str = "gho_test"; @@ -349,3 +352,64 @@ mod suggestions { assert_eq!(err.code.as_deref(), Some("not_found")); } } + +mod github_list { + use super::*; + + #[tokio::test] + async fn should_read_what_a_refresh_loaded_with_its_progress() { + let github = MockServer::start_async().await; + mock_viewer(&github, TOKEN, "octocat", None); + let repos = user_repos(130); + mock_user_repos(&github, TOKEN, &repos); + let dirs = tempfile::tempdir().expect("a temp dir"); + set_gh_token(dirs.path(), Some(TOKEN)); + let daemon = TestDaemon::start_with_github(dirs, &github.url("/graphql")).await; + assert_eq!( + github_list(&daemon.client).await.expect("read").status, + GithubListStatus::NotLoaded + ); + + refresh_github_list(&daemon.client).await.expect("refresh"); + + let read = eventually("the list loaded", || async { + let read = github_list(&daemon.client).await.expect("read"); + (read.status == GithubListStatus::Loaded).then_some(read) + }) + .await; + assert_eq!((read.loaded, read.total), (130, Some(130))); + let names: Vec = (read.repositories.iter()) + .map(|r| r.name.to_string()) + .collect(); + let wanted: Vec = repos.iter().map(|r| r.name.to_owned()).collect(); + assert_eq!(names, wanted); + assert_eq!(read.repositories[0].private, repos[0].private); + } + + #[tokio::test] + async fn should_read_signed_out_after_a_refresh_without_a_token() { + let daemon = TestDaemon::start().await; + + refresh_github_list(&daemon.client).await.expect("refresh"); + + let read = eventually("signed out", || async { + let read = github_list(&daemon.client).await.expect("read"); + (read.status == GithubListStatus::SignedOut).then_some(read) + }) + .await; + assert!(read.repositories.is_empty()); + } + + #[tokio::test] + async fn should_fail_with_the_daemons_words_when_it_refuses_the_token() { + let daemon = TestDaemon::start().await; + let stranger = + agentdeck_client::authenticated(&daemon.base_url(), "not-the-token").expect("a client"); + + let read = github_list(&stranger).await.expect_err("a refusal"); + let refreshed = refresh_github_list(&stranger).await.expect_err("a refusal"); + + assert_eq!(read.code.as_deref(), Some("unauthorized")); + assert_eq!(refreshed.code.as_deref(), Some("unauthorized")); + } +} diff --git a/crates/agentdeckd/tests/integration/support/github.rs b/crates/agentdeckd/tests/integration/support/github.rs index cb7edf1..2041180 100644 --- a/crates/agentdeckd/tests/integration/support/github.rs +++ b/crates/agentdeckd/tests/integration/support/github.rs @@ -85,6 +85,128 @@ pub fn mock_rest_repo_missing<'a>(server: &'a MockServer, asked: &str) -> Mock<' }) } +/// `count` repositories a user can reach, as `GET /user/repos` sorts them: `acme/repo-000`, +/// `acme/repo-001`…, every 7th private. +pub fn user_repos(count: usize) -> Vec { + (0..count) + .map(|i| RestRepo { + private: i % 7 == 0, + ..RestRepo::new(Box::leak(format!("acme/repo-{i:03}").into_boxed_str())) + }) + .collect() +} + +/// The `Link` header GitHub sends with page `page` of `last` of `GET /user/repos` on `server`: +/// `next` and `last` before the last page, `prev` and `first` after the first. +fn user_repos_link(server: &MockServer, page: u32, last: u32) -> String { + let url = |page: u32| { + format!( + "<{}?sort=full_name&direction=asc&per_page=100&page={page}>", + server.url("/user/repos") + ) + }; + let mut links = Vec::new(); + if page > 1 { + links.push(format!("{}; rel=\"prev\"", url(page - 1))); + } + if page < last { + links.push(format!("{}; rel=\"next\"", url(page + 1))); + links.push(format!("{}; rel=\"last\"", url(last))); + } + if page > 1 { + links.push(format!("{}; rel=\"first\"", url(1))); + } + links.join(", ") +} + +/// `GET /user/repos?sort=full_name&direction=asc&per_page=100&page=` with `token`, +/// answered after `delay` with `repos`' page `page` (from 1) and its `Link` header. +pub fn mock_user_repos_page<'a>( + server: &'a MockServer, + token: &str, + repos: &[RestRepo], + page: u32, + delay: Duration, +) -> Mock<'a> { + let last = repos.len().div_ceil(100).max(1) as u32; + let start = (page as usize - 1) * 100; + let body: Vec = (repos.iter().skip(start).take(100)) + .map(|repo| { + let (owner, name) = repo.name.split_once('/').expect("owner/name"); + json!({ + "id": repo.id, + "node_id": "R_kgDOtest", + "name": name, + "full_name": repo.name, + "owner": { "login": owner }, + "html_url": repo.url(), + "private": repo.private, + "archived": false, + "default_branch": "main" + }) + }) + .collect(); + let link = user_repos_link(server, page, last); + server.mock(|when, then| { + when.method(GET) + .path("/user/repos") + .query_param("sort", "full_name") + .query_param("direction", "asc") + .query_param("per_page", "100") + .query_param("page", page.to_string()) + .header("authorization", format!("Bearer {token}")) + .header("x-github-api-version", "2022-11-28"); + let then = then.status(200).delay(delay).json_body(Value::Array(body)); + if !link.is_empty() { + then.header("link", link); + } + }) +} + +/// Every page of `repos` for `token`, answered at once, by page from 1. +pub fn mock_user_repos<'a>( + server: &'a MockServer, + token: &str, + repos: &[RestRepo], +) -> Vec> { + let last = repos.len().div_ceil(100).max(1) as u32; + (1..=last) + .map(|page| mock_user_repos_page(server, token, repos, page, Duration::ZERO)) + .collect() +} + +/// `GET /user/repos` page `page` answered `status` with GitHub's JSON error `message`, and +/// `headers`. +pub fn mock_user_repos_failing<'a>( + server: &'a MockServer, + page: u32, + status: u16, + message: &str, + headers: &[(&str, &str)], +) -> Mock<'a> { + server.mock(|when, then| { + when.method(GET) + .path("/user/repos") + .query_param("page", page.to_string()); + let mut then = then.status(status).json_body(json!({ + "message": message, + "documentation_url": "https://docs.github.com/rest" + })); + for (name, value) in headers { + then = then.header(*name, *value); + } + }) +} + +/// GitHub's repository search, which agentdeck never calls: any request to it. +pub fn mock_search_repositories(server: &MockServer) -> Mock<'_> { + server.mock(|when, then| { + when.path("/search/repositories"); + then.status(200) + .json_body(json!({ "total_count": 0, "items": [] })); + }) +} + /// The stub `gh auth token`: prints `/gh-token`, or fails as a logged-out `gh` does. const STUB_GH: &str = r#"#!/bin/sh [ "$1 $2" = "auth token" ] || { echo "stub gh: unsupported: $*" >&2; exit 2; } diff --git a/openapi.json b/openapi.json index 87469d1..fe595f1 100644 --- a/openapi.json +++ b/openapi.json @@ -195,6 +195,90 @@ ], "type": "object" }, + "GithubListStatus": { + "description": "Where loading the GitHub repository list stands.", + "oneOf": [ + { + "description": "Nothing asked for it yet this run, or since the sign-in changed.", + "enum": [ + "not_loaded" + ], + "type": "string" + }, + { + "description": "The first load runs: `repositories` holds the pages that have arrived.", + "enum": [ + "loading" + ], + "type": "string" + }, + { + "description": "Every page loaded. A refresh runs quietly under it, the list changing once it ends.", + "enum": [ + "loaded" + ], + "type": "string" + }, + { + "description": "The load failed (no connection, a rate limit, a token GitHub rejects): `error` says why.", + "enum": [ + "failed" + ], + "type": "string" + }, + { + "description": "There's no GitHub token to list with.", + "enum": [ + "signed_out" + ], + "type": "string" + } + ] + }, + "GithubRepositoryList": { + "description": "`GET /v1/github/repositories`: every GitHub repository the sign-in can reach, as the Link picker offers them (spec §8), with how far loading them has got. Kept in memory for the run.", + "properties": { + "error": { + "description": "Why the last load failed, while `status` is `failed`: GitHub's message, or why the request failed.", + "nullable": true, + "type": "string" + }, + "loaded": { + "description": "How many repositories have loaded: `repositories`' length.", + "format": "uint32", + "minimum": 0, + "type": "integer" + }, + "repositories": { + "description": "The repositories loaded so far, by `owner/name` as GitHub sorts them. While a list is refreshed, the one before it, whole.", + "items": { + "$ref": "#/components/schemas/Repository" + }, + "type": "array" + }, + "status": { + "allOf": [ + { + "$ref": "#/components/schemas/GithubListStatus" + } + ], + "description": "Where loading the list stands." + }, + "total": { + "description": "About how many there are, from the last page's number in page 1's `Link` header, then exact once the last page has loaded; `None` until page 1 answers.", + "format": "uint32", + "minimum": 0, + "nullable": true, + "type": "integer" + } + }, + "required": [ + "loaded", + "repositories", + "status" + ], + "type": "object" + }, "GithubTokenBody": { "description": "`PUT /v1/github/token`.", "properties": { @@ -1564,6 +1648,49 @@ "summary": "Starts Sign in with GitHub (the OAuth device flow, scope `repo`), cancelling one already" } }, + "/v1/github/repositories": { + "get": { + "description": "offers them, by `owner/name` as GitHub sorts them, with how far loading them has got: the list kept in memory for the run. Nothing loads until `POST /v1/github/repositories/refresh` asks; while the first load runs, the pages that have arrived. Never fails: a failed load is `status: failed` with its `error`.", + "operationId": "github_repository_list", + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GithubRepositoryList" + } + } + }, + "description": "successful operation" + }, + "4XX": { + "$ref": "#/components/responses/Error" + }, + "5XX": { + "$ref": "#/components/responses/Error" + } + }, + "summary": "Every GitHub repository the sign-in can reach, as the Link picker's All your repositories" + } + }, + "/v1/github/repositories/refresh": { + "post": { + "description": "rest 4 at a time), answering 204 at once, before GitHub does. A list already loaded keeps showing until the new one has loaded whole; a load already running is left to finish. Each change to the list or its progress sends `changed github_repositories`. With no token the list reads `signed_out`.", + "operationId": "github_repository_refresh", + "responses": { + "204": { + "description": "resource updated" + }, + "4XX": { + "$ref": "#/components/responses/Error" + }, + "5XX": { + "$ref": "#/components/responses/Error" + } + }, + "summary": "Loads the GitHub repository list again (`GET /user/repos`, 100 a page: page 1, then the" + } + }, "/v1/github/token": { "delete": { "operationId": "github_token_delete", From f64f80b4b65285ce4344c8ac071dc0248cd70a6f Mon Sep 17 00:00:00 2001 From: bRRRITSCOLD Date: Mon, 23 Nov 2026 17:31:32 -0700 Subject: [PATCH 2/5] feat(gui): All your repositories in the Link picker (#371) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The picker lists the daemon's GitHub repository list after Suggested and From your pull requests, leaving out those listed above, linked or Unreachable, with a lock on private ones; it asks for a refresh each time it opens, reads the list again on changed github_repositories, says "Loading your repositories… 400 of about 1,100" while it loads and "Couldn't load your repositories." with Retry when it fails. Rows are drawn only in view. The sidebar skips the list's events. Co-Authored-By: Claude Opus 5.5 --- crates/agentdeck-gui/src/api.rs | 68 +- crates/agentdeck-gui/src/edit_workspace.rs | 18 +- crates/agentdeck-gui/src/link_picker.rs | 979 ++++++++++++++++-- crates/agentdeck-gui/src/new_workspace.rs | 18 +- crates/agentdeck-gui/src/shell.rs | 6 +- crates/agentdeck-gui/src/sidebar.rs | 17 + crates/agentdeckd/src/github_list.rs | 9 +- crates/agentdeckd/src/prsync/github.rs | 10 +- .../tests/integration/github_list.rs | 24 +- 9 files changed, 1019 insertions(+), 130 deletions(-) diff --git a/crates/agentdeck-gui/src/api.rs b/crates/agentdeck-gui/src/api.rs index 8ddec28..faf493d 100644 --- a/crates/agentdeck-gui/src/api.rs +++ b/crates/agentdeck-gui/src/api.rs @@ -5,8 +5,8 @@ use agentdeck_client::daemon::Daemon; use agentdeck_client::panes::{self, pane_if_any}; use agentdeck_client::types::{ - DeviceSignIn, GithubAuthInfo, GithubClientIdBody, GithubTokenBody, Pane, PaneRun, PrClose, - PrCloseResult, Repository, Settings, SettingsPatch, Tab, + DeviceSignIn, GithubAuthInfo, GithubClientIdBody, GithubRepositoryList, GithubTokenBody, Pane, + PaneRun, PrClose, PrCloseResult, Repository, Settings, SettingsPatch, Tab, }; pub use agentdeck_client::workspaces::Change; use agentdeck_client::{ApiError, Client}; @@ -98,6 +98,15 @@ pub trait Api: Send + Sync { cx: &App, ) -> Task>; + /// Every GitHub repository the sign-in can reach, as the daemon holds it now, with how far + /// loading them has got (spec §8): the picker's All your repositories. + fn github_repositories(&self, cx: &App) -> Task>; + + /// Asks the daemon to load the GitHub repository list again, as a picker does when it + /// opens and on Retry. Answers before GitHub does: the pages come with `changed + /// github_repositories` events. + fn refresh_github_repositories(&self, cx: &App) -> Task>; + /// Links `workspace` to `repository` by GitHub's id, as the view holds it (spec §4): the /// Repository the daemon keeps with that id, or, when an unlink took it meanwhile, one /// stored again from `repository` without asking GitHub, so Undo works signed out. @@ -313,6 +322,20 @@ impl Api for Daemon { }) } + fn github_repositories(&self, cx: &App) -> Task> { + let client = self.client.clone(); + runtime::spawn(cx, async move { + Ok(agentdeck_client::repositories::github_list(&client).await?) + }) + } + + fn refresh_github_repositories(&self, cx: &App) -> Task> { + let client = self.client.clone(); + runtime::spawn(cx, async move { + Ok(agentdeck_client::repositories::refresh_github_list(&client).await?) + }) + } + fn link_repository( &self, workspace: WorkspaceId, @@ -604,6 +627,12 @@ pub(crate) mod fake { github_repositories: Mutex>, /// The names looked up on GitHub, in order. pub resolved: Mutex>, + /// The GitHub repository list as the daemon holds it; loaded, and empty, when unset. + github_list: Mutex>, + /// Why reading the GitHub repository list fails, while it does. + github_list_failure: Mutex>, + /// How many times the GitHub repository list was asked to load again. + pub github_list_refreshes: Mutex, /// The workspaces deleted, in order. pub deleted: Mutex>, /// The settings; the daemon's defaults when unset. @@ -755,6 +784,22 @@ pub(crate) mod fake { *self.github.lock().unwrap() = Some(auth); } + /// Answers later reads of the GitHub repository list with `list`. + pub fn set_github_list(&self, list: GithubRepositoryList) { + *self.github_list.lock().unwrap() = Some(list); + } + + /// Fails every read of the GitHub repository list with `reason`, or (with `None`) + /// stops failing them. + pub fn fail_github_list(&self, reason: Option<&str>) { + *self.github_list_failure.lock().unwrap() = reason.map(str::to_owned); + } + + /// How many times the GitHub repository list was asked to load again. + pub fn github_list_refreshes(&self) -> usize { + *self.github_list_refreshes.lock().unwrap() + } + /// Makes GitHub show `repository`: a typed name resolves to it, and linking it by /// name stores it. pub fn on_github(&self, repository: Repository) { @@ -1156,6 +1201,25 @@ pub(crate) mod fake { Task::ready(self.github(&name)) } + fn github_repositories(&self, _cx: &App) -> Task> { + if let Some(reason) = self.github_list_failure.lock().unwrap().clone() { + return Task::ready(Err(anyhow::Error::msg(reason))); + } + let list = self.github_list.lock().unwrap().clone(); + Task::ready(Ok(list.unwrap_or_else(|| GithubRepositoryList { + status: agentdeck_client::types::GithubListStatus::Loaded, + loaded: 0, + total: None, + error: None, + repositories: Vec::new(), + }))) + } + + fn refresh_github_repositories(&self, _cx: &App) -> Task> { + *self.github_list_refreshes.lock().unwrap() += 1; + Task::ready(Ok(())) + } + fn link_repository( &self, workspace: WorkspaceId, diff --git a/crates/agentdeck-gui/src/edit_workspace.rs b/crates/agentdeck-gui/src/edit_workspace.rs index 1fa44d7..4454452 100644 --- a/crates/agentdeck-gui/src/edit_workspace.rs +++ b/crates/agentdeck-gui/src/edit_workspace.rs @@ -27,6 +27,7 @@ use gpui::{ use gpui_base::input::InputEvent; use crate::api::{Api, Change}; +use crate::connection::Connection; use crate::gui_state; use crate::link_picker::{LinkPicker, Offer, Staging}; use crate::workspace::failed; @@ -84,8 +85,14 @@ pub struct EditWorkspaceDialog { impl EventEmitter for EditWorkspaceDialog {} impl EditWorkspaceDialog { - /// A closed dialog that renames workspaces through `api`. - pub fn new(api: Arc, window: &mut Window, cx: &mut Context) -> Self { + /// A closed dialog that renames workspaces through `api`, its picker following + /// `connection`'s events. + pub fn new( + api: Arc, + connection: &Entity, + window: &mut Window, + cx: &mut Context, + ) -> Self { let name = cx.new(|cx| InputState::new(window, cx)); let _name = cx.subscribe_in(&name, window, |this, _, event, window, cx| match event { InputEvent::PressEnter { .. } => this.save(window, cx), @@ -95,7 +102,7 @@ impl EditWorkspaceDialog { } InputEvent::Focus | InputEvent::Blur => {} }); - let picker = cx.new(|cx| LinkPicker::new(api.clone(), window, cx)); + let picker = cx.new(|cx| LinkPicker::new(api.clone(), connection, window, cx)); let _picker = cx.subscribe(&picker, |_, _, _: &Staging, cx| cx.notify()); EditWorkspaceDialog { api, @@ -357,10 +364,13 @@ mod tests { ) -> (Harness, &mut VisualTestContext) { cx.update(brrritscold_core_gpui::init); let api = Arc::new(FakeApi::with(snapshot)); + let connector = std::rc::Rc::new(crate::connection::fake::FakeConnector::default()); + let _remote = connector.then_connect_to(api.clone()); + let connection = cx.update(|cx| cx.new(|cx| Connection::new(connector, cx))); let mut dialog = None; let window = cx.add_window(|window, cx| { let api: Arc = api.clone(); - let view = cx.new(|cx| EditWorkspaceDialog::new(api, window, cx)); + let view = cx.new(|cx| EditWorkspaceDialog::new(api, &connection, window, cx)); dialog = Some(view.clone()); Root::new(view, window, cx) }); diff --git a/crates/agentdeck-gui/src/link_picker.rs b/crates/agentdeck-gui/src/link_picker.rs index 651b6b4..278b136 100644 --- a/crates/agentdeck-gui/src/link_picker.rs +++ b/crates/agentdeck-gui/src/link_picker.rs @@ -9,10 +9,20 @@ //! counts the open PRs that would leave the Workspace. //! //! The picker lists Suggested (the Workspace's Suggestions, Not now or not), then From your -//! pull requests (the Repositories of your kept PRs, but for those Suggested), leaving out what -//! the Workspace links and Unreachable ones; typing filters both. Typed text naming a -//! Repository (`owner/name` or its GitHub URL) that isn't listed offers a "Link owner/name" row, -//! which asks GitHub ([`Api::resolve_repository`]); signed out, typed names are off. +//! pull requests (the Repositories of your kept PRs, but for those Suggested), then All your +//! repositories (every GitHub repository the sign-in can reach, but for those listed above), +//! leaving out what the Workspace links and Unreachable ones; typing filters all three. Typed +//! text naming a Repository (`owner/name` or its GitHub URL) that isn't listed offers a +//! "Link owner/name" row, which asks GitHub ([`Api::resolve_repository`]); signed out, typed +//! names and All your repositories are off. +//! +//! All your repositories is the daemon's GitHub repository list: each [`LinkPicker::reset`] +//! (a dialog opening) asks the daemon to load it again, and each `changed +//! github_repositories` reads it again, so its pages show as they arrive with "Loading your +//! repositories… 400 of about 1,100" under them. A list that failed to load reads "Couldn't +//! load your repositories." with Retry, and the other sections and typed names keep working. +//! The list draws only the rows in view, through GPUI's [`list`](gpui::list): about 1,100 +//! rows drawn whole would make every frame slow. use std::cell::Cell; use std::collections::HashMap; @@ -20,23 +30,28 @@ use std::rc::Rc; use std::sync::Arc; use agentdeck_client::ApiError; +use agentdeck_client::types::{GithubListStatus, GithubRepositoryList}; +use agentdeck_core::ws::{Entity as Changed, ServerMessage}; use agentdeck_core::{PrState, RepositoryId, RepositoryName, WorkspaceId}; use brrritscold_core_gpui::{ ActiveTheme as _, Badge, BadgeVariant, Button, ButtonSize, ButtonVariant, FieldError, Icon, IconName, Input, InputState, Label, }; -use brrritscold_core_gpui_tokens::primitive::{font_size, shadow, space}; +use brrritscold_core_gpui_tokens::primitive::{font_size, font_weight, shadow, space}; use gpui::prelude::FluentBuilder as _; use gpui::{ - Anchor, App, AppContext as _, Bounds, BoxShadow, Context, Entity, EventEmitter, - InteractiveElement as _, IntoElement, ParentElement as _, Pixels, Render, SharedString, - StatefulInteractiveElement as _, Styled as _, Subscription, Task, Window, canvas, div, point, - px, + Anchor, AnyElement, App, AppContext as _, Bounds, BoxShadow, Context, Entity, EventEmitter, + InteractiveElement as _, IntoElement, ListOffset, ListState, ParentElement as _, Pixels, + Render, SharedString, StatefulInteractiveElement as _, Styled as _, Subscription, Task, Window, + canvas, div, list, point, px, }; use gpui_base::input::InputEvent; use crate::api::Api; +use crate::connection::{Connection, DaemonEvent}; use crate::overview::Snapshot; +use crate::rereads::Rereads; +use crate::table; use crate::workspace::failed; /// The picker's placeholder. @@ -48,6 +63,18 @@ pub const SUGGESTED: &str = "Suggested"; /// The heading over the Repositories of your kept PRs. pub const FROM_PRS: &str = "From your pull requests"; +/// The heading over every GitHub repository the sign-in can reach, after the other sections. +pub const ALL_REPOSITORIES: &str = "All your repositories"; + +/// What All your repositories says while its list loads, before page 1 has answered. +pub const LOADING: &str = "Loading your repositories…"; + +/// What All your repositories says when its list didn't load; [`RETRY`] follows it. +pub const COULD_NOT_LOAD: &str = "Couldn't load your repositories."; + +/// What loads the list again after it didn't load. +pub const RETRY: &str = "Retry"; + /// What the list says in place of typed names while signed out of GitHub. pub const SIGNED_OUT: &str = "Sign in to GitHub to find more repositories."; @@ -84,6 +111,8 @@ pub struct Offer { pub open_prs: HashMap, /// Whether GitHub accepts the token, so typed names can be looked up. pub signed_in: bool, + /// Every Repository agentdeck keeps that the GitHub sign-in can't see any more. + pub unreachable: Vec, } impl Offer { @@ -123,16 +152,119 @@ impl Offer { // Unknown until PR status is read: let GitHub answer for the token. let signed_in = (snapshot.pr_sync.as_ref()) .is_none_or(|s| s.login != agentdeck_client::types::GhLogin::LoggedOut); + let unreachable = (repositories.iter()) + .filter(|r| r.unreachable) + .map(|r| r.id) + .collect(); Offer { linked, suggested, from_prs, open_prs, signed_in, + unreachable, + } + } +} + +/// All your repositories, as last read from the daemon's GitHub repository list. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum GithubList { + /// Loading: the repositories loaded so far, in GitHub's order, how many that is, and about + /// how many there are in all (unknown before page 1 answers). + Loading { + repositories: Vec, + loaded: u32, + total: Option, + }, + /// Every repository, in GitHub's order. + Loaded(Vec), + /// The list didn't load: GitHub failed, or the daemon couldn't be asked. + Failed, + /// The daemon has no GitHub token to list with. + SignedOut, +} + +impl Default for GithubList { + fn default() -> Self { + GithubList::Loading { + repositories: Vec::new(), + loaded: 0, + total: None, + } + } +} + +impl GithubList { + /// What the daemon's `list` holds for the picker. A list not loaded yet reads as loading: + /// the picker has just asked for it. + pub fn read(list: GithubRepositoryList) -> GithubList { + let choices = |list: GithubRepositoryList| { + (list.repositories.into_iter()) + .map(|r| Choice { + id: r.id, + name: r.name, + private: r.private, + unreachable: false, + }) + .collect() + }; + match list.status { + GithubListStatus::Loaded => GithubList::Loaded(choices(list)), + GithubListStatus::Failed => GithubList::Failed, + GithubListStatus::SignedOut => GithubList::SignedOut, + GithubListStatus::NotLoaded | GithubListStatus::Loading => GithubList::Loading { + loaded: list.loaded, + total: list.total, + repositories: choices(list), + }, + } + } + + /// The repositories it holds now. + fn repositories(&self) -> &[Choice] { + match self { + GithubList::Loading { repositories, .. } | GithubList::Loaded(repositories) => { + repositories + } + GithubList::Failed | GithubList::SignedOut => &[], } } } +/// The line under All your repositories while it loads: "Loading your repositories… 400 of +/// about 1,100", the total rounded to the hundred; before page 1 answers, no count. +pub fn loading_line(loaded: u32, total: Option) -> String { + match total.filter(|_| loaded > 0) { + Some(total) => { + let about = if total >= 100 { + (total + 50) / 100 * 100 + } else { + total + }; + format!( + "{LOADING} {} of about {}", + thousands(loaded), + thousands(about) + ) + } + None => LOADING.to_owned(), + } +} + +/// `n` with a comma between each group of three digits: `1,104`. +fn thousands(n: u32) -> String { + let digits = n.to_string(); + let mut out = String::new(); + for (i, digit) in digits.chars().enumerate() { + if i > 0 && (digits.len() - i) % 3 == 0 { + out.push(','); + } + out.push(digit); + } + out +} + /// Where a row of the list stands until the dialog saves. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Staged { @@ -160,6 +292,8 @@ pub enum Entry { Suggested(Choice), /// A Repository of your kept PRs. Pick(Choice), + /// A GitHub repository the sign-in can reach: All your repositories. + All(Choice), /// "Link owner/name": a typed Repository the list doesn't hold. Typed(RepositoryName), } @@ -185,19 +319,76 @@ pub struct LinkPicker { lookup: Option>, /// The field's bounds last frame: the list is as wide. field: Rc>>, + /// All your repositories, as last read. + github: GithubList, + /// Whether a dialog has opened the picker, so `changed github_repositories` reads the list. + following: bool, + /// Asking the daemon to load the list again. + github_refresh: Option>, + /// Reading the list. + github_read: Option>, + github_rereads: Rereads, + /// The open list's rows, drawn only where in view. + rows_list: ListState, + /// What the open list showed last frame. + shown: Vec, _input: Subscription, + _events: Subscription, +} + +/// A row of the open list. +#[derive(Debug, Clone, PartialEq, Eq)] +enum Item { + /// A section's heading: its words and how tests find it. + Heading(&'static str, &'static str), + /// A Repository to pick. + Choice(Entry), + /// "Loading your repositories… 400 of about 1,100". + Loading(String), + /// "Couldn't load your repositories." and Retry. + Failed, + /// "No repositories match.". + NoMatch, +} + +/// Heights of the open list's rows, as Penpot `agentdeck/LinkPickerList` lays them out: a +/// ComboboxLabel (`py-1.5 text-xs`), a ComboboxItem (`py-1.5 text-sm`) and ComboboxEmpty +/// (`py-2 text-sm`). The list is as tall as its rows, up to [`MAX_LIST_HEIGHT`]. +const HEADING_HEIGHT: Pixels = px(30.); +const ITEM_HEIGHT: Pixels = px(33.); +const NO_MATCH_HEIGHT: Pixels = px(37.); + +/// ComboboxList's `max-h-[calc(var(--spacing-72)-var(--spacing-9))]`: past it, the rows +/// scroll. +const MAX_LIST_HEIGHT: Pixels = px(252.); + +impl Item { + fn height(&self) -> Pixels { + match self { + Item::Heading(..) | Item::Loading(_) | Item::Failed => HEADING_HEIGHT, + Item::Choice(_) => ITEM_HEIGHT, + Item::NoMatch => NO_MATCH_HEIGHT, + } + } } impl EventEmitter for LinkPicker {} impl LinkPicker { - /// An empty part that asks GitHub through `api`. - pub fn new(api: Arc, window: &mut Window, cx: &mut Context) -> Self { + /// An empty part that asks GitHub through `api`, reading the GitHub repository list again + /// on `connection`'s `changed github_repositories`. + pub fn new( + api: Arc, + connection: &Entity, + window: &mut Window, + cx: &mut Context, + ) -> Self { let input = cx.new(|cx| InputState::new(window, cx).placeholder(PLACEHOLDER)); let _input = cx.subscribe_in(&input, window, |this, _, event, window, cx| match event { InputEvent::Change => { this.problem = None; this.open = true; + this.rows_list.scroll_to(ListOffset::default()); cx.notify(); } InputEvent::Focus => { @@ -210,6 +401,16 @@ impl LinkPicker { } InputEvent::PressEnter { .. } => this.pick_first(window, cx), }); + let _events = cx.subscribe(connection, |this, _, event, cx| match event { + DaemonEvent::Message( + ServerMessage::Changed { + entity: Changed::GithubRepositories, + .. + } + | ServerMessage::Resync, + ) if this.following => this.read_github(cx), + _ => {} + }); LinkPicker { api, input, @@ -221,7 +422,15 @@ impl LinkPicker { focus: false, lookup: None, field: Rc::new(Cell::new(Bounds::default())), + github: GithubList::default(), + following: false, + github_refresh: None, + github_read: None, + github_rereads: Rereads::default(), + rows_list: table::list_state(), + shown: Vec::new(), _input, + _events, } } @@ -241,10 +450,74 @@ impl LinkPicker { self.focus = false; self.input .update(cx, |input, cx| input.set_value("", window, cx)); + self.following = true; + self.refresh_github(cx); cx.emit(Staging); cx.notify(); } + /// Asks the daemon to load the GitHub repository list again, then reads it: what each + /// opening and Retry do. A list held already keeps showing; the daemon refreshes it + /// quietly. + fn refresh_github(&mut self, cx: &mut Context) { + if !matches!(self.github, GithubList::Loaded(_)) { + self.github = GithubList::default(); + } + let refreshing = self.api.refresh_github_repositories(cx); + self.github_refresh = Some(cx.spawn(async move |this, cx| { + let refreshed = refreshing.await; + let _ = this.update(cx, |this, cx| match refreshed { + Ok(()) => this.read_github(cx), + Err(err) => { + tracing::warn!("asking for the GitHub repository list: {err:#}"); + this.github = GithubList::Failed; + cx.notify(); + } + }); + })); + } + + /// Reads the GitHub repository list, once more after a read running now if one does. + fn read_github(&mut self, cx: &mut Context) { + if !self.github_rereads.ask() { + return; + } + let reading = self.api.github_repositories(cx); + self.github_read = Some(cx.spawn(async move |this, cx| { + let read = reading.await; + let _ = this.update(cx, |this, cx| { + this.github = match read { + Ok(list) => GithubList::read(list), + Err(err) => { + tracing::warn!("reading the GitHub repository list: {err:#}"); + GithubList::Failed + } + }; + if this.github_rereads.landed() { + this.read_github(cx); + } + cx.notify(); + }); + })); + } + + /// Retry under a list that didn't load. + fn retry(&mut self, cx: &mut Context) { + self.refresh_github(cx); + cx.notify(); + } + + /// All your repositories, as last read. + #[cfg(test)] + pub fn github(&self) -> &GithubList { + &self.github + } + + /// Whether All your repositories and typed names are on: GitHub accepts the token. + fn signed_in(&self) -> bool { + self.offer.signed_in && self.github != GithubList::SignedOut + } + /// Gives the field the keyboard on the next draw, its list open. pub fn focus(&mut self, cx: &mut Context) { self.focus = true; @@ -293,13 +566,29 @@ impl LinkPicker { .filter(|c| !self.offer.suggested.iter().any(|s| s.id == c.id)) .filter(offered) .collect(); + let signed_in = self.signed_in(); + // Every Repository listed above, whether or not it passes the filter, and every one + // the sign-in can't see. + let above: std::collections::HashSet = (self.offer.suggested.iter()) + .chain(&self.offer.from_prs) + .map(|c| c.id) + .chain(self.offer.unreachable.iter().copied()) + .collect(); + let all: Vec<&Choice> = match signed_in { + true => (self.github.repositories().iter()) + .filter(|c| !above.contains(&c.id)) + .filter(offered) + .collect(), + false => Vec::new(), + }; let mut entries: Vec = (suggested.iter()) .map(|c| Entry::Suggested((*c).clone())) .chain(picks.iter().map(|c| Entry::Pick((*c).clone()))) + .chain(all.iter().map(|c| Entry::All((*c).clone()))) .collect(); - if let Some(named) = named.filter(|_| self.offer.signed_in) { + if let Some(named) = named.filter(|_| signed_in) { let same = |name: &RepositoryName| same_name(name, &named); - let listed = (suggested.iter().chain(&picks)).any(|c| same(&c.name)) + let listed = (suggested.iter().chain(&picks).chain(&all)).any(|c| same(&c.name)) || self.rows.iter().any(|r| same(&r.repository.name)); if !listed { entries.push(Entry::Typed(named)); @@ -467,7 +756,9 @@ impl LinkPicker { /// Enter in the field: picks the list's first entry. fn pick_first(&mut self, window: &mut Window, cx: &mut Context) { match self.entries(cx).into_iter().next() { - Some(Entry::Suggested(choice) | Entry::Pick(choice)) => self.pick(choice, window, cx), + Some(Entry::Suggested(choice) | Entry::Pick(choice) | Entry::All(choice)) => { + self.pick(choice, window, cx) + } Some(Entry::Typed(name)) => self.pick_typed(name, window, cx), None => {} } @@ -562,41 +853,68 @@ impl LinkPicker { }) } - /// The open list (Penpot `agentdeck/LinkPickerList`), drawn as core-gpui's - /// `ComboboxContent`: Suggested, From your pull requests, the typed row, then the last - /// line. - fn list(&self, cx: &mut Context) -> impl IntoElement { - let s = cx.theme().semantic(); + /// The open list's rows for what is typed now: Suggested, From your pull requests, All + /// your repositories with its loading or failed line, the typed row, or "No repositories + /// match.". + fn items(&self, cx: &App) -> Vec { let entries = self.entries(cx); - let suggested: Vec = (entries.iter()) - .filter_map(|e| match e { - Entry::Suggested(choice) => Some(choice.clone()), - Entry::Pick(_) | Entry::Typed(_) => None, - }) - .collect(); - let picks: Vec = (entries.iter()) - .filter_map(|e| match e { - Entry::Pick(choice) => Some(choice.clone()), - Entry::Suggested(_) | Entry::Typed(_) => None, - }) - .collect(); - let typed = entries.iter().find_map(|e| match e { - Entry::Typed(name) => Some(name.clone()), - Entry::Suggested(_) | Entry::Pick(_) => None, - }); - let mut shadows = vec![BoxShadow { - color: s.foreground.opacity(0.1), - offset: point(px(0.), px(0.)), - blur_radius: px(0.), - spread_radius: px(1.), - inset: false, - }]; - shadows.extend_from_slice(shadow::MD); + let mut items = Vec::new(); + let section = |heading: Option, rows: Vec, items: &mut Vec| { + if !rows.is_empty() { + items.extend(heading); + items.extend(rows); + } + }; + let of = |keep: fn(&Entry) -> bool| -> Vec { + (entries.iter()) + .filter(|e| keep(e)) + .map(|e| Item::Choice(e.clone())) + .collect() + }; + section( + Some(Item::Heading(SUGGESTED, "suggested")), + of(|e| matches!(e, Entry::Suggested(_))), + &mut items, + ); + section( + Some(Item::Heading(FROM_PRS, "from your pull requests")), + of(|e| matches!(e, Entry::Pick(_))), + &mut items, + ); + let mut all = of(|e| matches!(e, Entry::All(_))); + if self.signed_in() { + match &self.github { + GithubList::Loading { loaded, total, .. } => { + all.push(Item::Loading(loading_line(*loaded, *total))) + } + GithubList::Failed => all.push(Item::Failed), + GithubList::Loaded(_) | GithubList::SignedOut => {} + } + } + section( + Some(Item::Heading(ALL_REPOSITORIES, "all your repositories")), + all, + &mut items, + ); + section(None, of(|e| matches!(e, Entry::Typed(_))), &mut items); + if items.is_empty() { + items.push(Item::NoMatch); + } + items + } + + /// Row `ix` of the open list, as [`Self::list`] last listed them. + fn item(&mut self, ix: usize, cx: &mut Context) -> AnyElement { + let s = cx.theme().semantic(); + let Some(item) = self.shown.get(ix).cloned() else { + return div().into_any_element(); + }; // ComboboxItem: flex items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm, // hover:bg-accent - let item = |id: SharedString| { + let row = |id: SharedString| { div() .id(id) + .h(ITEM_HEIGHT) .flex() .items_center() .gap(space::S2) @@ -609,6 +927,132 @@ impl LinkPicker { .hover(|d| d.bg(s.accent).text_color(s.accent_foreground)) }; // ComboboxLabel: px-2 py-1.5 text-xs text-muted-foreground + let line = || { + div() + .h(HEADING_HEIGHT) + .flex() + .items_center() + .px(space::S2) + .py(space::S1_5) + .text_size(font_size::XS) + .text_color(s.muted_foreground) + }; + match item { + Item::Heading(text, selector) => line() + .debug_selector(move || selector.into()) + .child(text) + .into_any_element(), + Item::Loading(text) => line() + .debug_selector(|| "loading your repositories".into()) + .child(text) + .into_any_element(), + Item::Failed => div() + .debug_selector(|| "could not load".into()) + .h(HEADING_HEIGHT) + .flex() + .items_center() + .child(line().child(COULD_NOT_LOAD)) + .child( + // Drawn as core-gpui's link xs Button (text-primary hover:underline h-6 px-2 + // text-xs font-medium), without its focus: a button taking the keyboard + // would blur the field, closing the list before the click lands. + div() + .id("retry-github-list") + .debug_selector(|| "retry".into()) + .h(space::S6) + .flex() + .items_center() + .px(space::S2) + .rounded(s.radius_md) + .text_size(font_size::XS) + .font_weight(font_weight::MEDIUM) + .text_color(s.primary) + .cursor_pointer() + .hover(|d| d.underline()) + .child(RETRY) + .on_click(cx.listener(|this, _, _, cx| this.retry(cx))), + ) + .into_any_element(), + // ComboboxEmpty: flex w-full justify-center py-2 text-sm text-muted-foreground + Item::NoMatch => div() + .debug_selector(|| "no match".into()) + .h(NO_MATCH_HEIGHT) + .flex() + .items_center() + .w_full() + .justify_center() + .py(space::S2) + .text_size(font_size::SM) + .text_color(s.muted_foreground) + .child(NO_MATCH) + .into_any_element(), + Item::Choice(Entry::Typed(name)) => { + let busy = (self.looking_up.as_ref()).is_some_and(|n| same_name(n, &name)); + let label = match busy { + true => format!("Looking up {name}…"), + false => format!("Link {name}"), + }; + row("link-typed".into()) + .debug_selector(|| "link typed".into()) + .child(Icon::new(IconName::Plus).size(px(14.))) + .child(label) + .when(busy, |d| d.opacity(0.5)) + .when(!busy, |d| { + d.on_click(cx.listener(move |this, _, window, cx| { + this.pick_typed(name.clone(), window, cx) + })) + }) + .into_any_element() + } + Item::Choice(Entry::Suggested(choice)) => self.choice(row, "suggested", choice, cx), + Item::Choice(Entry::Pick(choice)) => self.choice(row, "pick", choice, cx), + Item::Choice(Entry::All(choice)) => self.choice(row, "all", choice, cx), + } + } + + /// A Repository's row in section `kind`, as tests find it (`all acme/widgets`): a lock if + /// private, then its name; a click picks it. + fn choice( + &self, + row: impl Fn(SharedString) -> gpui::Stateful, + kind: &'static str, + choice: Choice, + cx: &mut Context, + ) -> AnyElement { + let muted = cx.theme().semantic().muted_foreground; + let name = choice.name.to_string(); + let selector = format!("{kind} {name}"); + row(SharedString::from(format!("{kind}-{}", choice.id))) + .debug_selector(move || selector.clone()) + .when(choice.private, |d| d.child(lock(&name, muted))) + .child(name) + .on_click(cx.listener(move |this, _, window, cx| this.pick(choice.clone(), window, cx))) + .into_any_element() + } + + /// The open list (Penpot `agentdeck/LinkPickerList`), drawn as core-gpui's + /// `ComboboxContent`: its rows ([`Self::items`]), as tall as they are up to + /// [`MAX_LIST_HEIGHT`] and scrolling past it, then the last line. + fn list(&mut self, cx: &mut Context) -> impl IntoElement { + let s = cx.theme().semantic(); + let items = self.items(cx); + if items != self.shown { + table::relist(&self.rows_list, items.len()); + self.shown = items; + } + let height = (self.shown.iter()) + .map(Item::height) + .fold(px(0.), |sum, h| sum + h) + .min(MAX_LIST_HEIGHT); + let mut shadows = vec![BoxShadow { + color: s.foreground.opacity(0.1), + offset: point(px(0.), px(0.)), + blur_radius: px(0.), + spread_radius: px(1.), + inset: false, + }]; + shadows.extend_from_slice(shadow::MD); + // ComboboxLabel: px-2 py-1.5 text-xs text-muted-foreground let line = |text: &'static str, selector: &'static str| { div() .debug_selector(move || selector.into()) @@ -618,7 +1062,6 @@ impl LinkPicker { .text_color(s.muted_foreground) .child(text) }; - let looking_up = self.looking_up.clone(); div() .debug_selector(|| "picker list".into()) .id("link-picker-list") @@ -634,72 +1077,20 @@ impl LinkPicker { .bg(s.popover) .text_color(s.popover_foreground) .shadow(shadows) - .when(!suggested.is_empty(), |list| { - list.child(line(SUGGESTED, "suggested")) - .children(suggested.into_iter().map(|choice| { - let name = choice.name.to_string(); - let selector = format!("suggested {name}"); - item(SharedString::from(format!("suggested-{}", choice.id))) - .debug_selector(move || selector.clone()) - .when(choice.private, |d| d.child(lock(&name, s.muted_foreground))) - .child(name) - .on_click(cx.listener(move |this, _, window, cx| { - this.pick(choice.clone(), window, cx) - })) - })) - }) - .when(!picks.is_empty(), |list| { - list.child(line(FROM_PRS, "from your pull requests")) - .children(picks.into_iter().map(|choice| { - let name = choice.name.to_string(); - let selector = format!("pick {name}"); - item(SharedString::from(format!("pick-{}", choice.id))) - .debug_selector(move || selector.clone()) - .when(choice.private, |d| d.child(lock(&name, s.muted_foreground))) - .child(name) - .on_click(cx.listener(move |this, _, window, cx| { - this.pick(choice.clone(), window, cx) - })) - })) - }) - .when_some(typed, |list, name| { - let busy = looking_up.as_ref().is_some_and(|n| same_name(n, &name)); - let label = match busy { - true => format!("Looking up {name}…"), - false => format!("Link {name}"), - }; - list.child( - item("link-typed".into()) - .debug_selector(|| "link typed".into()) - .child(Icon::new(IconName::Plus).size(px(14.))) - .child(label) - .when(busy, |d| d.opacity(0.5)) - .when(!busy, |d| { - d.on_click(cx.listener(move |this, _, window, cx| { - this.pick_typed(name.clone(), window, cx) - })) - }), - ) - }) - .when(entries.is_empty(), |list| { - // ComboboxEmpty: flex w-full justify-center py-2 text-sm text-muted-foreground - list.child( - div() - .debug_selector(|| "no match".into()) - .flex() - .w_full() - .justify_center() - .py(space::S2) - .text_size(font_size::SM) - .text_color(s.muted_foreground) - .child(NO_MATCH), - ) - }) + .child( + div().h(height).child( + list( + self.rows_list.clone(), + cx.processor(|this, ix, _, cx| this.item(ix, cx)), + ) + .size_full(), + ), + ) .child( // ComboboxSeparator: -mx-1 my-1 h-px bg-border div().mx(-space::S1).my(space::S1).h(px(1.)).bg(s.border), ) - .child(match self.offer.signed_in { + .child(match self.signed_in() { true => line(NOT_LISTED, "not listed"), false => line(SIGNED_OUT, "signed out"), }) @@ -805,12 +1196,16 @@ impl Render for LinkPicker { #[cfg(test)] pub(crate) mod tests { + use std::rc::Rc; + use agentdeck_client::types::PullRequest; + use agentdeck_client::ws::{self, Remote}; use brrritscold_core_gpui::Root; use gpui::{Focusable as _, Modifiers, TestAppContext, VisualTestContext}; use super::*; use crate::api::fake::FakeApi; + use crate::connection::fake::FakeConnector; use crate::overview::fixtures::{id, links, pr_sync, pull_request, repository_id, suggestion}; const WIDGETS: &str = "acme/widgets"; @@ -931,6 +1326,13 @@ pub(crate) mod tests { assert_eq!(Offer::read(&snapshot, None).suggested, []); } + #[test] + fn should_hold_every_kept_repository_github_cannot_see() { + let offer = Offer::read(&snapshot(), None); + + assert_eq!(offer.unreachable, [repository_id(LOST)]); + } + #[test] fn should_be_signed_out_only_while_github_rejects_the_token() { let mut snapshot = snapshot(); @@ -945,6 +1347,27 @@ pub(crate) mod tests { pub(crate) struct Harness { pub api: Arc, pub picker: Entity, + /// Plays the daemon's socket. + pub remote: Remote, + _connection: Entity, + } + + /// The daemon's GitHub repository list, loaded whole with `repos`. + pub(crate) fn loaded(repos: &[Choice]) -> GithubRepositoryList { + GithubRepositoryList { + status: GithubListStatus::Loaded, + loaded: repos.len() as u32, + total: Some(repos.len() as u32), + error: None, + repositories: repos.iter().map(as_repository).collect(), + } + } + + fn as_repository(choice: &Choice) -> agentdeck_client::types::Repository { + agentdeck_client::types::Repository { + private: choice.private, + ..repository(&choice.name.to_string()) + } } /// Widgets and a private gadgets linked, widgets with 2 open PRs and gadgets with 1; your @@ -969,20 +1392,36 @@ pub(crate) mod tests { ], open_prs: HashMap::from([(repository_id(WIDGETS), 2), (repository_id(GADGETS), 1)]), signed_in: true, + unreachable: vec![repository_id(LOST)], } } impl Harness { + /// A picker opened on `offer`, whose daemon's GitHub repository list is loaded and + /// holds nothing. pub(crate) fn open( offer: Offer, cx: &mut TestAppContext, + ) -> (Harness, &mut VisualTestContext) { + Harness::open_with(offer, loaded(&[]), cx) + } + + /// A picker opened on `offer`, whose daemon's GitHub repository list reads `github`. + pub(crate) fn open_with( + offer: Offer, + github: GithubRepositoryList, + cx: &mut TestAppContext, ) -> (Harness, &mut VisualTestContext) { cx.update(brrritscold_core_gpui::init); let api = Arc::new(FakeApi::default()); + api.set_github_list(github); + let connector = Rc::new(FakeConnector::default()); + let remote = connector.then_connect_to(api.clone()); + let connection = cx.update(|cx| cx.new(|cx| Connection::new(connector, cx))); let mut picker = None; let window = cx.add_window(|window, cx| { let api: Arc = api.clone(); - let view = cx.new(|cx| LinkPicker::new(api, window, cx)); + let view = cx.new(|cx| LinkPicker::new(api, &connection, window, cx)); picker = Some(view.clone()); Root::new(view, window, cx) }); @@ -990,11 +1429,28 @@ pub(crate) mod tests { cx.update(|window, _| window.activate_window()); let picker = picker.unwrap(); cx.update(|window, cx| picker.update(cx, |p, cx| p.reset(offer, window, cx))); - let harness = Harness { api, picker }; + let harness = Harness { + api, + picker, + remote, + _connection: connection, + }; harness.settle(cx); (harness, cx) } + /// The daemon says its GitHub repository list changed. + pub(crate) fn github_changed(&self, cx: &mut VisualTestContext) { + self.remote + .events + .try_send(ws::Event::Message(ServerMessage::Changed { + entity: Changed::GithubRepositories, + id: "list".into(), + })) + .unwrap(); + self.settle(cx); + } + pub(crate) fn settle(&self, cx: &mut VisualTestContext) { cx.run_until_parked(); cx.update(|window, cx| window.draw(cx).clear(cx)); @@ -1053,6 +1509,7 @@ pub(crate) mod tests { .map(|e| match e { Entry::Suggested(choice) => format!("Suggested {}", choice.name), Entry::Pick(choice) => choice.name.to_string(), + Entry::All(choice) => format!("All {}", choice.name), Entry::Typed(name) => format!("Link {name}"), }) .collect() @@ -1447,4 +1904,308 @@ pub(crate) mod tests { assert_eq!(picks(&harness.entries(cx)), ["acme/tools"]); } } + + mod all_repositories { + use super::*; + + fn private(repo: &str) -> Choice { + Choice { + private: true, + ..choice(repo) + } + } + + /// What GitHub lists: tools and secrets (also your PRs'), widgets (linked), lost + /// (Unreachable) and three only GitHub lists, api, billing (private) and docs. + fn github() -> Vec { + vec![ + choice("acme/api"), + private("acme/billing"), + choice("acme/docs"), + choice(LOST), + private(SECRETS), + choice("acme/tools"), + choice(WIDGETS), + ] + } + + fn shows(selector: &str, cx: &mut VisualTestContext) -> bool { + cx.debug_bounds(selector.to_owned().leak()).is_some() + } + + fn loading(repos: &[Choice], total: Option) -> GithubRepositoryList { + GithubRepositoryList { + status: GithubListStatus::Loading, + total, + ..loaded(repos) + } + } + + fn status(status: GithubListStatus) -> GithubRepositoryList { + GithubRepositoryList { + status, + ..loaded(&[]) + } + } + + #[gpui::test] + fn should_list_them_after_the_other_sections_but_those_listed_linked_or_unreachable( + cx: &mut TestAppContext, + ) { + let (harness, cx) = Harness::open_with(offer(), loaded(&github()), cx); + harness.type_in("", cx); + + assert_eq!( + picks(&harness.entries(cx)), + [ + SECRETS, + "acme/tools", + "All acme/api", + "All acme/billing", + "All acme/docs" + ] + ); + let from_prs = cx.debug_bounds("pick acme/tools").expect("tools"); + let heading = cx + .debug_bounds("all your repositories") + .expect("its heading"); + let first = cx.debug_bounds("all acme/api").expect("api"); + assert!(from_prs.bottom() <= heading.top()); + assert!(heading.bottom() <= first.top()); + assert!(shows("lock acme/billing", cx)); + assert!(!shows("lock acme/api", cx)); + assert!(shows("not listed", cx)); + assert!(!shows("loading your repositories", cx)); + } + + #[gpui::test] + fn should_ask_the_daemon_to_load_them_again_each_time_it_opens(cx: &mut TestAppContext) { + let (harness, cx) = Harness::open_with(offer(), loaded(&github()), cx); + assert_eq!(harness.api.github_list_refreshes(), 1); + + cx.update(|window, cx| { + harness + .picker + .update(cx, |p, cx| p.reset(offer(), window, cx)) + }); + harness.settle(cx); + + assert_eq!(harness.api.github_list_refreshes(), 2); + } + + #[gpui::test] + fn should_filter_them_as_you_type(cx: &mut TestAppContext) { + let (harness, cx) = Harness::open_with(offer(), loaded(&github()), cx); + + harness.type_in("BILL", cx); + + assert_eq!(picks(&harness.entries(cx)), ["All acme/billing"]); + } + + #[gpui::test] + fn should_stage_one_picked_from_the_list(cx: &mut TestAppContext) { + let (harness, cx) = Harness::open_with(offer(), loaded(&github()), cx); + harness.type_in("docs", cx); + + harness.click("all acme/docs", cx); + + assert_eq!( + harness.rows(cx).last(), + Some(&("acme/docs".to_owned(), Staged::Linking)) + ); + assert_eq!(harness.change(cx), (vec!["acme/docs".to_owned()], vec![])); + } + + #[gpui::test] + fn should_pick_one_on_enter(cx: &mut TestAppContext) { + let (harness, cx) = Harness::open_with(offer(), loaded(&github()), cx); + harness.type_in("api", cx); + + cx.simulate_keystrokes("enter"); + harness.settle(cx); + + assert_eq!( + harness.rows(cx).last(), + Some(&("acme/api".to_owned(), Staged::Linking)) + ); + } + + #[gpui::test] + fn should_offer_no_typed_row_for_a_name_it_lists(cx: &mut TestAppContext) { + let (harness, cx) = Harness::open_with(offer(), loaded(&github()), cx); + + harness.type_in("https://github.com/acme/billing", cx); + + assert_eq!(picks(&harness.entries(cx)), ["All acme/billing"]); + assert!(!shows("link typed", cx)); + } + + #[gpui::test] + fn should_show_what_has_loaded_and_how_far_loading_has_got(cx: &mut TestAppContext) { + let (harness, cx) = + Harness::open_with(offer(), loading(&github()[..2], Some(1_104)), cx); + harness.type_in("", cx); + + assert_eq!( + picks(&harness.entries(cx)), + [SECRETS, "acme/tools", "All acme/api", "All acme/billing"] + ); + let line = cx + .debug_bounds("loading your repositories") + .expect("the loading line"); + let last = cx.debug_bounds("all acme/billing").expect("billing"); + assert!(last.bottom() <= line.top()); + let read = harness.picker.read_with(cx, |p, _| p.github().clone()); + assert_eq!( + read, + GithubList::Loading { + repositories: vec![choice("acme/api"), private("acme/billing")], + loaded: 2, + total: Some(1_104), + } + ); + } + + #[gpui::test] + fn should_say_it_is_loading_before_the_first_page(cx: &mut TestAppContext) { + let (harness, cx) = + Harness::open_with(offer(), status(GithubListStatus::NotLoaded), cx); + harness.type_in("", cx); + + assert!(shows("all your repositories", cx)); + assert!(shows("loading your repositories", cx)); + assert!(!shows("no match", cx)); + } + + #[gpui::test] + fn should_read_them_again_as_pages_arrive(cx: &mut TestAppContext) { + let (harness, cx) = Harness::open_with(offer(), loading(&github()[..1], Some(300)), cx); + harness.type_in("", cx); + assert_eq!(picks(&harness.entries(cx))[2..], ["All acme/api"]); + + harness.api.set_github_list(loaded(&github())); + harness.github_changed(cx); + + assert_eq!( + picks(&harness.entries(cx))[2..], + ["All acme/api", "All acme/billing", "All acme/docs"] + ); + assert!(!shows("loading your repositories", cx)); + } + + #[gpui::test] + fn should_say_it_could_not_load_them_and_keep_the_rest_working(cx: &mut TestAppContext) { + let (harness, cx) = Harness::open_with(offer(), status(GithubListStatus::Failed), cx); + harness.type_in("", cx); + + assert_eq!(picks(&harness.entries(cx)), [SECRETS, "acme/tools"]); + assert!(shows("all your repositories", cx)); + assert!(shows("could not load", cx)); + assert!(shows("retry", cx)); + assert!(shows("not listed", cx)); + harness.type_in("octo/hello", cx); + assert_eq!(picks(&harness.entries(cx)), ["Link octo/hello"]); + } + + #[gpui::test] + fn should_say_it_could_not_load_them_when_the_daemon_cannot_be_read( + cx: &mut TestAppContext, + ) { + let (harness, cx) = Harness::open_with(offer(), loaded(&github()), cx); + harness.api.fail_github_list(Some("connection refused")); + + harness.github_changed(cx); + harness.type_in("", cx); + + assert!(shows("could not load", cx)); + assert_eq!(picks(&harness.entries(cx)), [SECRETS, "acme/tools"]); + } + + #[gpui::test] + fn should_load_them_again_on_retry(cx: &mut TestAppContext) { + let (harness, cx) = Harness::open_with(offer(), status(GithubListStatus::Failed), cx); + harness.type_in("", cx); + harness.api.set_github_list(loaded(&github())); + + harness.click("retry", cx); + + assert_eq!(harness.api.github_list_refreshes(), 2); + assert!(!shows("could not load", cx)); + assert!(shows("all acme/api", cx)); + } + + #[gpui::test] + fn should_be_replaced_by_sign_in_while_signed_out(cx: &mut TestAppContext) { + let (harness, cx) = Harness::open_with( + Offer { + signed_in: false, + ..offer() + }, + loaded(&github()), + cx, + ); + harness.type_in("", cx); + + assert_eq!(picks(&harness.entries(cx)), [SECRETS, "acme/tools"]); + assert!(!shows("all your repositories", cx)); + assert!(shows("signed out", cx)); + assert!(!shows("not listed", cx)); + } + + #[gpui::test] + fn should_be_replaced_by_sign_in_when_the_daemon_has_no_token(cx: &mut TestAppContext) { + let (harness, cx) = + Harness::open_with(offer(), status(GithubListStatus::SignedOut), cx); + harness.type_in("", cx); + + assert!(!shows("all your repositories", cx)); + assert!(shows("signed out", cx)); + } + + #[gpui::test] + fn should_draw_only_the_rows_in_view_of_a_long_list(cx: &mut TestAppContext) { + let many: Vec = (0..1_100) + .map(|i| choice(&format!("acme/repo-{i:04}"))) + .collect(); + let (harness, cx) = Harness::open_with(offer(), loaded(&many), cx); + harness.type_in("", cx); + + assert_eq!(harness.entries(cx).len(), 2 + 1_100); + assert!(shows("all acme/repo-0000", cx)); + assert!(!shows("all acme/repo-1099", cx)); + let list = cx.debug_bounds("picker list").expect("the list"); + assert!(list.size.height < px(320.), "{:?}", list.size.height); + assert!(shows("not listed", cx)); + } + } + + mod loading_line { + use super::*; + + #[test] + fn should_count_what_loaded_of_about_the_total_to_the_hundred() { + assert_eq!( + loading_line(400, Some(1_104)), + "Loading your repositories… 400 of about 1,100" + ); + assert_eq!( + loading_line(1_000, Some(1_150)), + "Loading your repositories… 1,000 of about 1,200" + ); + } + + #[test] + fn should_say_no_count_before_page_one() { + assert_eq!(loading_line(0, None), "Loading your repositories…"); + assert_eq!(loading_line(0, Some(300)), "Loading your repositories…"); + } + + #[test] + fn should_count_a_list_under_a_hundred_exactly() { + assert_eq!( + loading_line(40, Some(64)), + "Loading your repositories… 40 of about 64" + ); + } + } } diff --git a/crates/agentdeck-gui/src/new_workspace.rs b/crates/agentdeck-gui/src/new_workspace.rs index 33793b8..dbbb04d 100644 --- a/crates/agentdeck-gui/src/new_workspace.rs +++ b/crates/agentdeck-gui/src/new_workspace.rs @@ -25,6 +25,7 @@ use gpui::{ use gpui_base::input::InputEvent; use crate::api::Api; +use crate::connection::Connection; use crate::link_picker::{Choice, LinkPicker, Offer}; use crate::workspace::failed; @@ -61,15 +62,21 @@ pub struct NewWorkspaceDialog { impl EventEmitter for NewWorkspaceDialog {} impl NewWorkspaceDialog { - /// A closed dialog that makes workspaces through `api`. - pub fn new(api: Arc, window: &mut Window, cx: &mut Context) -> Self { + /// A closed dialog that makes workspaces through `api`, its picker following + /// `connection`'s events. + pub fn new( + api: Arc, + connection: &Entity, + window: &mut Window, + cx: &mut Context, + ) -> Self { let name = cx.new(|cx| InputState::new(window, cx).placeholder("e.g. tabs-a11y")); let _enter = cx.subscribe_in(&name, window, |this, _, event, window, cx| { if let InputEvent::PressEnter { .. } = event { this.create(window, cx); } }); - let picker = cx.new(|cx| LinkPicker::new(api.clone(), window, cx)); + let picker = cx.new(|cx| LinkPicker::new(api.clone(), connection, window, cx)); NewWorkspaceDialog { api, handle: DialogHandle::new(false), @@ -286,10 +293,13 @@ mod tests { ) -> (Harness, &mut VisualTestContext) { cx.update(brrritscold_core_gpui::init); let api = Arc::new(FakeApi::with(snapshot)); + let connector = std::rc::Rc::new(crate::connection::fake::FakeConnector::default()); + let _remote = connector.then_connect_to(api.clone()); + let connection = cx.update(|cx| cx.new(|cx| Connection::new(connector, cx))); let mut dialog = None; let window = cx.add_window(|window, cx| { let api: Arc = api.clone(); - let view = cx.new(|cx| NewWorkspaceDialog::new(api, window, cx)); + let view = cx.new(|cx| NewWorkspaceDialog::new(api, &connection, window, cx)); dialog = Some(view.clone()); Root::new(view, window, cx) }); diff --git a/crates/agentdeck-gui/src/shell.rs b/crates/agentdeck-gui/src/shell.rs index c8190d5..d9a74cb 100644 --- a/crates/agentdeck-gui/src/shell.rs +++ b/crates/agentdeck-gui/src/shell.rs @@ -388,11 +388,13 @@ impl Shell { if self.sidebar.is_none() { let api = session.api.clone(); let connection = self.connection.clone(); - let dialog = cx.new(|cx| NewWorkspaceDialog::new(api.clone(), window, cx)); + let dialog = + cx.new(|cx| NewWorkspaceDialog::new(api.clone(), &connection, window, cx)); let pull_requests = cx.new(|cx| PullRequestsView::new(api.clone(), Scope::All, cx)); let new_agent = cx.new(|_| NewAgentDialog::new(api.clone())); - let edit = cx.new(|cx| EditWorkspaceDialog::new(api.clone(), window, cx)); + let edit = + cx.new(|cx| EditWorkspaceDialog::new(api.clone(), &connection, window, cx)); let delete = cx.new(|cx| DeleteWorkspaceDialog::new(api.clone(), window, cx)); let settings = cx.new(|cx| SettingsView::new(api.clone(), &connection, window, cx)); diff --git a/crates/agentdeck-gui/src/sidebar.rs b/crates/agentdeck-gui/src/sidebar.rs index eab6ff8..b658343 100644 --- a/crates/agentdeck-gui/src/sidebar.rs +++ b/crates/agentdeck-gui/src/sidebar.rs @@ -236,6 +236,11 @@ impl SidebarView { let now = cx.background_executor().now(); self.reattached.attached(*pane, *state, now); } + // The GitHub repository list is the Link picker's own read, page by page. + DaemonEvent::Message(ServerMessage::Changed { + entity: agentdeck_core::ws::Entity::GithubRepositories, + .. + }) => {} // On `resync` the connection missed events: the read is diffed against what the // sidebar held, so a change made meanwhile still alerts. DaemonEvent::Message(ServerMessage::Changed { .. } | ServerMessage::Resync) => { @@ -1323,6 +1328,18 @@ mod tests { assert!(open.shows("row c")); } + #[gpui::test] + fn should_not_read_again_as_the_github_repository_list_loads(cx: &mut TestAppContext) { + let mut open = open(two_workspaces(), cx); + + open.send(ServerMessage::Changed { + entity: Changed::GithubRepositories, + id: "list".into(), + }); + + assert_eq!(open.api.reads(), 1); + } + #[gpui::test] fn should_roll_up_a_state_change_without_reading_again(cx: &mut TestAppContext) { let mut open = open(two_workspaces(), cx); diff --git a/crates/agentdeckd/src/github_list.rs b/crates/agentdeckd/src/github_list.rs index 13d9536..1f24a26 100644 --- a/crates/agentdeckd/src/github_list.rs +++ b/crates/agentdeckd/src/github_list.rs @@ -250,7 +250,10 @@ impl GithubList { let github = &self.inner.github; let token = token.as_str(); let mut reads = futures_util::stream::iter(order.map(|page| async move { - github.user_repos_page(token, page).await.map(|read| (page, read)) + github + .user_repos_page(token, page) + .await + .map(|read| (page, read)) })) .buffer_unordered(PAGES_IN_FLIGHT); while let Some((page, read)) = reads.try_next().await.inspect_err(|err| { @@ -269,8 +272,8 @@ impl GithubList { let github = &self.inner.github; match github.user_repos_page(&token, 1).await { Err(GithubError::Unauthorized) => { - let fresh = (self.inner.auth.reread().await) - .map_err(|_| GithubError::Unauthorized)?; + let fresh = + (self.inner.auth.reread().await).map_err(|_| GithubError::Unauthorized)?; match github.user_repos_page(&fresh, 1).await { Err(GithubError::Unauthorized) => { self.inner.auth.rejected(); diff --git a/crates/agentdeckd/src/prsync/github.rs b/crates/agentdeckd/src/prsync/github.rs index fe0cf99..fb565ec 100644 --- a/crates/agentdeckd/src/prsync/github.rs +++ b/crates/agentdeckd/src/prsync/github.rs @@ -265,7 +265,10 @@ impl Github { /// collaborator and organisation ones, by `owner/name`. Tried again after each of /// `RETRY_WAITS` while it fails for a reason that may pass. pub async fn user_repos_page(&self, token: &str, page: u32) -> Result { - retrying(GithubError::may_pass, || self.user_repos_page_once(token, page)).await + retrying(GithubError::may_pass, || { + self.user_repos_page_once(token, page) + }) + .await } /// [`Github::user_repos_page`], once. @@ -1221,7 +1224,10 @@ mod tests { #[test] fn should_be_none_for_a_link_it_cannot_read() { assert_eq!(last_page("; rel=\"last\""), None); - assert_eq!(last_page("; rel=\"last\""), None); + assert_eq!( + last_page("; rel=\"last\""), + None + ); } } diff --git a/crates/agentdeckd/tests/integration/github_list.rs b/crates/agentdeckd/tests/integration/github_list.rs index 0ca6305..5370066 100644 --- a/crates/agentdeckd/tests/integration/github_list.rs +++ b/crates/agentdeckd/tests/integration/github_list.rs @@ -173,7 +173,11 @@ mod get_v1_github_repositories { assert_eq!(read.status, GithubListStatus::Loading); assert_eq!(read.total, Some(250)); let expected = [named(&repos[..100]), named(&repos[200..])].concat(); - assert_eq!(names(&read), expected, "in GitHub's order, page 2 still to come"); + assert_eq!( + names(&read), + expected, + "in GitHub's order, page 2 still to come" + ); } #[tokio::test] @@ -296,7 +300,10 @@ mod post_v1_github_repositories_refresh { refresh(&daemon.client).await; let read = until_status(&daemon.client, GithubListStatus::Failed).await; - assert_eq!(read.error.as_deref(), Some("GitHub answered 502: Server Error")); + assert_eq!( + read.error.as_deref(), + Some("GitHub answered 502: Server Error") + ); assert!(read.repositories.is_empty()); assert_eq!(broken.calls_async().await, 3); broken.delete_async().await; @@ -333,7 +340,13 @@ mod post_v1_github_repositories_refresh { #[tokio::test] async fn should_fail_when_github_answers_too_many_requests_429_204() { let github = MockServer::start_async().await; - mock_user_repos_failing(&github, 1, 429, "Too Many Requests", &[("retry-after", "60")]); + mock_user_repos_failing( + &github, + 1, + 429, + "Too Many Requests", + &[("retry-after", "60")], + ); let daemon = signed_in(&github).await; refresh(&daemon.client).await; @@ -357,7 +370,10 @@ mod post_v1_github_repositories_refresh { refresh(&daemon.client).await; let read = until_status(&daemon.client, GithubListStatus::Failed).await; - assert_eq!(read.error.as_deref(), Some("GitHub answered 403: Forbidden")); + assert_eq!( + read.error.as_deref(), + Some("GitHub answered 403: Forbidden") + ); assert_eq!((read.loaded, read.total), (0, None)); assert!(read.repositories.is_empty()); } From f1c9a4400db41088ae44d3738e8f0ebefc223b7f Mon Sep 17 00:00:00 2001 From: bRRRITSCOLD Date: Mon, 23 Nov 2026 17:33:23 -0700 Subject: [PATCH 3/5] fix(gui): keep the picker's loading line in view under scrolling rows (#371) Co-Authored-By: Claude Opus 5.5 --- crates/agentdeck-gui/src/link_picker.rs | 76 ++++++++++++++++++------- 1 file changed, 55 insertions(+), 21 deletions(-) diff --git a/crates/agentdeck-gui/src/link_picker.rs b/crates/agentdeck-gui/src/link_picker.rs index 278b136..4fc5f5c 100644 --- a/crates/agentdeck-gui/src/link_picker.rs +++ b/crates/agentdeck-gui/src/link_picker.rs @@ -257,7 +257,7 @@ fn thousands(n: u32) -> String { let digits = n.to_string(); let mut out = String::new(); for (i, digit) in digits.chars().enumerate() { - if i > 0 && (digits.len() - i) % 3 == 0 { + if i > 0 && (digits.len() - i).is_multiple_of(3) { out.push(','); } out.push(digit); @@ -343,8 +343,6 @@ enum Item { Heading(&'static str, &'static str), /// A Repository to pick. Choice(Entry), - /// "Loading your repositories… 400 of about 1,100". - Loading(String), /// "Couldn't load your repositories." and Retry. Failed, /// "No repositories match.". @@ -365,7 +363,7 @@ const MAX_LIST_HEIGHT: Pixels = px(252.); impl Item { fn height(&self) -> Pixels { match self { - Item::Heading(..) | Item::Loading(_) | Item::Failed => HEADING_HEIGHT, + Item::Heading(..) | Item::Failed => HEADING_HEIGHT, Item::Choice(_) => ITEM_HEIGHT, Item::NoMatch => NO_MATCH_HEIGHT, } @@ -854,8 +852,7 @@ impl LinkPicker { } /// The open list's rows for what is typed now: Suggested, From your pull requests, All - /// your repositories with its loading or failed line, the typed row, or "No repositories - /// match.". + /// your repositories or its failed line, the typed row, or "No repositories match.". fn items(&self, cx: &App) -> Vec { let entries = self.entries(cx); let mut items = Vec::new(); @@ -882,14 +879,8 @@ impl LinkPicker { &mut items, ); let mut all = of(|e| matches!(e, Entry::All(_))); - if self.signed_in() { - match &self.github { - GithubList::Loading { loaded, total, .. } => { - all.push(Item::Loading(loading_line(*loaded, *total))) - } - GithubList::Failed => all.push(Item::Failed), - GithubList::Loaded(_) | GithubList::SignedOut => {} - } + if self.signed_in() && self.github == GithubList::Failed { + all.push(Item::Failed); } section( Some(Item::Heading(ALL_REPOSITORIES, "all your repositories")), @@ -897,12 +888,23 @@ impl LinkPicker { &mut items, ); section(None, of(|e| matches!(e, Entry::Typed(_))), &mut items); - if items.is_empty() { + if items.is_empty() && self.loading().is_none() { items.push(Item::NoMatch); } items } + /// The line under the rows while All your repositories loads: "Loading your + /// repositories… 400 of about 1,100". + fn loading(&self) -> Option { + match &self.github { + GithubList::Loading { loaded, total, .. } if self.signed_in() => { + Some(loading_line(*loaded, *total)) + } + _ => None, + } + } + /// Row `ix` of the open list, as [`Self::list`] last listed them. fn item(&mut self, ix: usize, cx: &mut Context) -> AnyElement { let s = cx.theme().semantic(); @@ -942,10 +944,6 @@ impl LinkPicker { .debug_selector(move || selector.into()) .child(text) .into_any_element(), - Item::Loading(text) => line() - .debug_selector(|| "loading your repositories".into()) - .child(text) - .into_any_element(), Item::Failed => div() .debug_selector(|| "could not load".into()) .h(HEADING_HEIGHT) @@ -1032,7 +1030,8 @@ impl LinkPicker { /// The open list (Penpot `agentdeck/LinkPickerList`), drawn as core-gpui's /// `ComboboxContent`: its rows ([`Self::items`]), as tall as they are up to - /// [`MAX_LIST_HEIGHT`] and scrolling past it, then the last line. + /// [`MAX_LIST_HEIGHT`] and scrolling past it, the loading line under them, so it shows + /// however far they scroll, then the last line. fn list(&mut self, cx: &mut Context) -> impl IntoElement { let s = cx.theme().semantic(); let items = self.items(cx); @@ -1086,6 +1085,17 @@ impl LinkPicker { .size_full(), ), ) + .when_some(self.loading(), |list, text| { + list.child( + div() + .debug_selector(|| "loading your repositories".into()) + .px(space::S2) + .py(space::S1_5) + .text_size(font_size::XS) + .text_color(s.muted_foreground) + .child(text), + ) + }) .child( // ComboboxSeparator: -mx-1 my-1 h-px bg-border div().mx(-space::S1).my(space::S1).h(px(1.)).bg(s.border), @@ -2072,7 +2082,6 @@ pub(crate) mod tests { Harness::open_with(offer(), status(GithubListStatus::NotLoaded), cx); harness.type_in("", cx); - assert!(shows("all your repositories", cx)); assert!(shows("loading your repositories", cx)); assert!(!shows("no match", cx)); } @@ -2179,6 +2188,31 @@ pub(crate) mod tests { } } + mod long_list { + use super::*; + + #[gpui::test] + fn should_keep_the_loading_line_in_view_under_rows_that_scroll(cx: &mut TestAppContext) { + let many: Vec = (0..400) + .map(|i| choice(&format!("acme/repo-{i:04}"))) + .collect(); + let list = GithubRepositoryList { + status: GithubListStatus::Loading, + total: Some(1_104), + ..loaded(&many) + }; + let (harness, cx) = Harness::open_with(offer(), list, cx); + harness.type_in("", cx); + + let line = cx + .debug_bounds("loading your repositories") + .expect("the loading line, in view"); + let footer = cx.debug_bounds("not listed").expect("the last line"); + assert!(line.bottom() <= footer.top()); + assert!(cx.debug_bounds("all acme/repo-0399").is_none()); + } + } + mod loading_line { use super::*; From bed01aac6c115718f7acd15f11d95d0a9b9fb5f8 Mon Sep 17 00:00:00 2001 From: bRRRITSCOLD Date: Mon, 23 Nov 2026 17:36:52 -0700 Subject: [PATCH 4/5] docs(spec): the GitHub repository list and All your repositories (#371) Co-Authored-By: Claude Opus 5.5 --- docs/spec.md | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/docs/spec.md b/docs/spec.md index e0e0290..9b928a6 100644 --- a/docs/spec.md +++ b/docs/spec.md @@ -134,6 +134,8 @@ v1.1 adds `channels`, `channel_members` and `messages` in their own migration. Every pane in a response (`POST` and `GET` on `/v1/panes`) carries `hosted_agent`: `claude` or `codex` while a shell pane hosts that agent (§3, §7), else null. It came with `API_VERSION` 6. Every pane also carries `folder`, its current folder (§3, §6), an absolute path; it came with `API_VERSION` 18. +`API_VERSION` 27 added the GitHub repository list (§8) for the Link picker's All your repositories (§11): `GET /v1/github/repositories`, `POST /v1/github/repositories/refresh` and the `github_repositories` change event (§5). An older daemon answers both routes with its code-less 404, so the GUI's picker reads "Couldn't load your repositories." until its Restart banner (§2) is followed; an older client skips the event. + `API_VERSION` 26 added a Workspace's Suggestions (§3): `GET /v1/workspaces/{id}/suggestions` and the `suggestions` change event (§5). An older daemon answers the route with its code-less 404, which the client reads as no Suggestions, so the GUI shows none there until its Restart banner (§2) is followed; an older client skips the event. `API_VERSION` 25 let `POST /v1/workspaces/{id}/links` link a Repository by GitHub's id (§11 Pull requests view, Group menu): it takes `id`, `url`, `private` and `archived` beside `repository`, and with `id` it never asks GitHub. An older daemon ignores them and looks the name up, so Undo after an unlink that deleted the Repository fails there while signed out; the GUI's Restart banner (§2) comes first. @@ -168,6 +170,8 @@ Every pane in a response (`POST` and `GET` on `/v1/panes`) carries `hosted_agent | `PUT /v1/github/token`, `DELETE /v1/github/token` | PUT `{token}` checks a pasted token with GitHub and saves it in the keyring (`422 invalid_token`, `503 no_keyring`, `502 github_error`); DELETE deletes the saved token (sign out). Both answer as `GET /v1/github/auth` | | `PUT /v1/github/client-id`, `DELETE /v1/github/client-id` | write-only: PUT `{client_id}` saves the OAuth client ID in the keyring (`invalid_client_id` for a blank one or a sign-in code, §8; `503 no_keyring`); DELETE deletes it. Both answer as `GET /v1/github/auth`; no route reads the client ID back | | `POST /v1/github/device`, `DELETE /v1/github/device` | start a sign-in with GitHub (§8): `{ user_code, verification_uri, expires_at }` (`409 no_client_id`, `503 no_keyring`, `502 github_error`); how it ends comes as a `github_auth` event (§5). DELETE cancels it, 204 | +| `GET /v1/github/repositories` | the GitHub repository list (§8), kept in memory for the run: `{ status, loaded, total, error, repositories }`. `status` is `not_loaded` (nothing asked for it yet this run, or since the sign-in changed), `loading` (the first load runs; `repositories` holds the pages that have arrived), `loaded`, `failed` or `signed_out` (no token). `loaded` counts `repositories`; `total` is about how many there are, from the last page's number in page 1's `Link` header (every page before the last counted full, the last one as it came once it has, or full until then), and exact once loaded; null before page 1 answers. `error` is why the last load failed: with `failed`, or beside `loaded` when a refresh failed and the list before it stayed. `repositories` are `Repository` objects (`{ id, name, url, private, archived }`) in GitHub's order (`owner/name`). Never fails for GitHub's sake. It came with `API_VERSION` 27 | +| `POST /v1/github/repositories/refresh` | load the GitHub repository list again (§8): 204 at once, before GitHub answers. A load already running is left to finish; a list already loaded keeps answering until the new one has loaded whole. With no token the list reads `signed_out`, with one GitHub still rejects `failed`. It came with `API_VERSION` 27 | | `GET /v1/settings`, `PATCH /v1/settings` | every setting (§2) by section, `{appearance: {theme}, gui: {confirm_quit}, pr_sync: {max_age_days}, terminal: {file_opener}, overridden_by_env}`; PATCH takes a partial object of the same sections (`{"pr_sync": {"max_age_days": 30}}`), writes `config.toml` and answers with every setting | | `GET /v1/ws` | the WebSocket, §5. Not in `openapi.json`: clients use `agentdeck_core::ws` over their own WebSocket client | @@ -194,6 +198,7 @@ Daemon → client: {"t":"changed","entity":"pull_request","id":"1296269#7"} {"t":"changed","entity":"repository","id":"1296269"} {"t":"changed","entity":"suggestions","id":""} +{"t":"changed","entity":"github_repositories","id":"list"} {"t":"github_auth","device":"signed_in"} {"t":"lagged","channel":3} {"t":"resync"} @@ -209,7 +214,7 @@ The message types are `agentdeck_core::ws::{ClientMessage, ServerMessage}`. - **Resize:** the **primary** client's size wins. The most recent client to send `primary` (the focused GUI window) is primary; until one does, or after it detaches, any client's resize applies. A resize from any other client is ignored and answered with `resize` carrying the size the pane keeps. Sending `primary` applies the size that client last asked for. Other attached clients get `resize` when the size changes; bytes after it were written at the new size. - **Terminal queries** (DA, cursor position, …) are answered only by the daemon's `Term`. Clients drop the replies their own `Term` generates. - **Backpressure:** a client more than 1 MiB behind on a channel gets `lagged`. It then re-attaches for a fresh snapshot. -- **Data events:** `changed` tells clients to refetch an entity over REST: `workspace`, `tab` or `pane`, after it is created, changed or deleted (a pane also when an agent starts or stops being hosted in it, §7, and when its current folder moves, §6); `pr_sync` (id `status`) means `GET /v1/prs/status`, when a PR sync begins, reads a page or ends, or a PATCH changes the age cutoff; `settings` (id `settings`) means `GET /v1/settings`, after every PATCH; `repository` (id GitHub's repository id) means `GET /v1/repositories` and `GET /v1/prs`, when PR sync or a lookup stores a Repository it didn't have or GitHub renamed, transferred or otherwise changed one (§8), when a Link to it is added or removed, the Repository deleted with it included (§4), and when PR sync deletes it once no Link and no kept PR references it (§8; it came with `API_VERSION` 16, and an older client skips it); `pull_request` (id its Repository's GitHub id and its number, `1296269#7`, so a rename keeps it) means `GET /v1/prs`, when PR sync stores a PR it didn't have, stores one changed, marks one unreachable or Finished, or deletes one, and when a close from agentdeck stores one closed (§8; it came with `API_VERSION` 22, replacing `task`, and an older client skips it); a Link change sends `workspace` for its Workspace after it; `suggestions` (id a Workspace's id) means `GET /v1/workspaces/{id}/suggestions`, sent when the daemon works that Workspace's Suggestions out again and they differ from the last ones it worked out for it this run (none, at start): it works them out again after a `changed` for a Pane (opened, moved, deleted; its Workspace's), an `exit` (its Workspace's), a tab or a Workspace (a Link added or removed, archived or brought back), a Repository or a `github_auth` (every Workspace's), coalescing a burst into one pass; a Pane's exit alone keeps its last folder, so it changes nothing to send (it came with `API_VERSION` 26, and an older client skips it). `state` and `exit` are sent to every client, attached or not. The daemon subscribes a connection to these events before it answers the upgrade, so every event published after the client sees the 101 reaches it. +- **Data events:** `changed` tells clients to refetch an entity over REST: `workspace`, `tab` or `pane`, after it is created, changed or deleted (a pane also when an agent starts or stops being hosted in it, §7, and when its current folder moves, §6); `pr_sync` (id `status`) means `GET /v1/prs/status`, when a PR sync begins, reads a page or ends, or a PATCH changes the age cutoff; `settings` (id `settings`) means `GET /v1/settings`, after every PATCH; `repository` (id GitHub's repository id) means `GET /v1/repositories` and `GET /v1/prs`, when PR sync or a lookup stores a Repository it didn't have or GitHub renamed, transferred or otherwise changed one (§8), when a Link to it is added or removed, the Repository deleted with it included (§4), and when PR sync deletes it once no Link and no kept PR references it (§8; it came with `API_VERSION` 16, and an older client skips it); `pull_request` (id its Repository's GitHub id and its number, `1296269#7`, so a rename keeps it) means `GET /v1/prs`, when PR sync stores a PR it didn't have, stores one changed, marks one unreachable or Finished, or deletes one, and when a close from agentdeck stores one closed (§8; it came with `API_VERSION` 22, replacing `task`, and an older client skips it); a Link change sends `workspace` for its Workspace after it; `suggestions` (id a Workspace's id) means `GET /v1/workspaces/{id}/suggestions`, sent when the daemon works that Workspace's Suggestions out again and they differ from the last ones it worked out for it this run (none, at start): it works them out again after a `changed` for a Pane (opened, moved, deleted; its Workspace's), an `exit` (its Workspace's), a tab or a Workspace (a Link added or removed, archived or brought back), a Repository or a `github_auth` (every Workspace's), coalescing a burst into one pass; a Pane's exit alone keeps its last folder, so it changes nothing to send (it came with `API_VERSION` 26, and an older client skips it); `github_repositories` (id `list`) means `GET /v1/github/repositories` (§8), sent when a first load begins, as each of its pages arrives, when a load ends with a list or an error that differs from what clients read before it, and when the sign-in changes; a quiet refresh that changes nothing sends none (it came with `API_VERSION` 27, and an older client skips it). `state` and `exit` are sent to every client, attached or not. The daemon subscribes a connection to these events before it answers the upgrade, so every event published after the client sees the 101 reaches it. - **Resync:** a connection that falls more than 1024 events behind misses some. It gets `resync` in their place (and the daemon logs it at info), then the events after. A client reads everything it shows again over REST, as on a `changed` for each entity, and compares what it reads with what it had, so a change made meanwhile still notifies (§11). - **GitHub auth:** `github_auth` means `GET /v1/github/auth` (§8), sent to every client after a token or client ID is saved or deleted, after a re-read changes the token's source, login or `rejected`, when PR sync finds GitHub rejecting a token it accepted a moment ago, and when a sign-in ends. Only then does it carry `device`: `signed_in`, `expired`, `denied`, or `failed` with GitHub's `message`. It never carries the token, the client ID or the user code. - **Errors:** a message the daemon can't act on gets `error` with a `code`: `not_found` (attach to a pane that isn't live), `not_attached` (a channel with nothing attached), `invalid_message`. @@ -340,6 +345,11 @@ min_ms = 400 # a new state must hold this long before it is pu - **Log:** the start, with the code's expiry and the interval, at info; each poll that fails in transit at warn, with why; each `authorization_pending` at debug, with the count so far; and how the sign-in ended, or that it was cancelled (by `DELETE`, or a new `POST`), at info, with the count of polls, pending answers and transit failures. No line carries the client ID, the device code, the user code or the token. - **Cancel:** one sign-in runs at a time, so a new `POST` cancels the one before. `DELETE /v1/github/device` cancels it (204, also with none running) and sends no event. - **Looking up a Repository** (`GET /v1/repositories/resolve`, and linking one agentdeck doesn't know, §4) is agentdeck's REST call to GitHub: `GET /repos/{owner}/{repo}` with the token as a bearer, `Accept: application/vnd.github+json` and `X-GitHub-Api-Version: 2022-11-28`, reading `id`, `full_name`, `html_url`, `private` and `archived`. GitHub redirects an old name to the renamed Repository, so the answer carries its name now. It uses the token as PR sync does (a `gh` token is checked first, a 401 reads the sources again and tries once more, then counts as rejected), the same 30 s timeout, the same retries (after 1 s and 2 s, on a 5xx or a request that failed in transit) and the same wording for a failure. A 404 is a Repository GitHub doesn't show the sign-in (no such repository, or no access): `400 unknown_repository`, "GitHub can't see owner/name. Check the name or your token's access." No token, or one GitHub still rejects, is `409 not_signed_in` ("Sign in to GitHub to look up owner/name.", or "GitHub rejected the token, so agentdeck can't look up owner/name."); any other failure is `502 github_error`. Confirming a Suggestion's name (§3) is the same call, with two differences: it takes the token as last read, never running `gh` or reading the sources while there is none (signed out, it only reads what agentdeck keeps), and its answers, a 404 included, are kept in memory for the run, while a failure is kept by no one and only logged. +- **The GitHub repository list** (`GET /v1/github/repositories`, §4) is every repository the sign-in can reach, as the Link picker's All your repositories offers them (§11): REST `GET /user/repos?sort=full_name&direction=asc&per_page=100&page=N`, with the token and headers a lookup uses, reading `id`, `full_name`, `html_url`, `private` and `archived` of each (owned, collaborator and organisation repositories; what a fine-grained token or an SSO organisation hides stays hidden, which the picker's "Not listed?" line covers). `search/repositories` is never called: it allows 30 requests a minute and misses repositories you only collaborate on. + - **Loading:** nothing loads until a client asks (`POST /v1/github/repositories/refresh`), which the GUI does each time a picker opens and on Retry. Page 1 comes first; its `Link` header's `rel="last"` names the last page (none means page 1 is the only one). Then the last page, so the total is exact early, then the pages between, 4 requests at once. About 1,100 repositories take 12 requests, out of 5,000 an hour. Each page uses the token as a lookup does (page 1's 401 reads the sources again and tries once more, then counts as rejected; a later page's 401 counts as rejected), the same 30 s timeout, the same retries (after 1 s and 2 s, on a 5xx or a request that failed in transit) and the same wording for a failure. A 403 or 429 (a rate limit) isn't tried again. + - **Progress:** while no list is held, each page is served as it arrives, the list keeping GitHub's order with gaps for pages still to come, `loaded` counting it and `total` estimating the whole; a `github_repositories` event goes with each. A page that fails fails the whole load: `status: failed`, its `error`, no repositories. + - **Memory:** the list is kept in memory for the run, only the five fields of each repository. A refresh of a held list runs quietly under it: clients go on reading the list before until the new one has loaded whole, then read the new one; a quiet refresh that fails keeps the list before and sets `error`. One load runs at a time; a refresh while one runs changes nothing. + - **Sign-in:** the list belongs to the token it was read with. When the token changes through the auth routes or a sign-in (§8 Re-read), it is dropped and, if a client had asked for it since the last change, loaded again with the new one. With no token, a refresh reads `signed_out` without calling GitHub. - **Closing PRs** (`POST /v1/prs/close`) closes them only: no comment, no branch delete. - Each PR is named by its reference, `owner/name#123` (or its GitHub URL, which clients turn into one), and found by its Repository's name and its number, ignoring case as GitHub does; the name follows the Repository's renames, so the name GitHub gives it now finds it. It must be stored `open`, Finished ones included, and not unreachable; any other, and one agentdeck doesn't keep, fails with "Not an open PR" and never reaches GitHub. With no token, every one fails with "Not signed in to GitHub". The results come back one per reference, in the order asked, each naming the reference asked for. - The daemon reads the PRs' node ids by Repository name and number, 25 to a request as fetches by number go. Then it closes each PR on its own, one at a time, with its own GraphQL `closePullRequest` mutation, since GitHub has no batch close. @@ -489,8 +499,8 @@ Built on `brrritscold-core-gpui` (`init`, `Root`, theme preference, toasts). Scr - Enter in a dialog's single-line field does what its primary button does, and only that: when the form can't go ahead, or the daemon refuses it, the dialog stays open. - **New agent** (Penpot "Screens · Dialogs" → "New agent", "New agent · folder open") offers a Folder select, each folder once and labelled by its path with `~` for the home folder: first where a new pane starts (Workspace view, above: the focused pane's current folder, else `~`), preset; then the current folder of each other pane in the workspace, in tab and layout order, as the view last read them; then `~`. Its description reads "Where the focused pane is, another pane's folder, or your home folder." A workspace not shown (none of its panes read) offers `~` alone. There is no typed path or folder browser; `agentdeck agent new --cwd` starts one anywhere. The agent starts with no prompt (§6). - **New workspace** (Penpot "Screens · Dialogs" → "New workspace", "New workspace · picker") is titled "New workspace", with "An area of work, such as one product, for any number of repos and agents.", and holds a Field, "Name" ("Names the sidebar entry."), then, `space.4` below, the optional **Repositories** with the "Link a repository…" picker (below): a workspace has no folder. Picked Repositories show as rows with their `×` and are linked by the create itself, `POST /v1/workspaces` `{ name, link }`. Opened from a Repository group's New workspace (Pull requests view, Group menu), it holds that Repository as a picked row already. Enter in the name creates. A blank name ("Give the workspace a name.") or the daemon's `invalid_name` shows under the name field, a Repository the daemon can't link (`unknown_repository`, `not_signed_in`) under the picker, and nothing is made; any other failure toasts "Couldn't make the workspace". Once made it closes. - - **Edit workspace** (Penpot "Screens · Dialogs" → "Edit workspace", "Edit workspace · error" for a blank name, "Edit workspace · unlinked", "· picker", "· picker · suggested", "· typed repo", "· GitHub can't see it" and "· signed out") is titled "Edit ", with "Its pull requests come from the repositories it links.". It holds (Penpot `agentdeck/EditWorkspaceForm`) the "Name" field, which opens holding the name, selected and focused, its error under it, then the **Repositories** the workspace links and the "Link a repository…" picker (below), `space.4` apart. Opened from the no-Repositories state's **Link repository** (`LinkRepository`), the picker takes the keyboard instead, its list open. The footer is Cancel and **Save**; Save is disabled while the name is blank, while nothing changed (the name, trimmed, as it was and nothing staged) and while a typed Repository is being looked up, and Enter in the name does the same. Links and unlinks are staged until Save, which applies them with the name in one request, `PATCH /v1/workspaces/{id}` `{ name?, link, unlink }` (the name only when it changed), and closes; each Repository it unlinked then counts as Not now for the workspace's Suggestions (GUI state, above), and a failed Save dismisses nothing. The changes come back through `changed` to the sidebar, the views and the dialogs that list workspaces. Cancel and Escape discard what was staged, and there is no confirm dialog. The slug stays as it is, so running panes are unaffected and the CLI still finds the workspace by its old slug; nothing on disk changes. Two workspaces may share a name. A blank name shows "Give the workspace a name." under the field as soon as it is blank, its input `aria-invalid`; the daemon's `invalid_name` shows there too and keeps the dialog open. A Repository the daemon can't link (`unknown_repository`, `not_signed_in`, `invalid_links`) shows its message under the picker and keeps the dialog open, with nothing applied. Any other failure keeps it open and toasts "Couldn't save " with why. An archived workspace can be edited too. - - **Repositories** (Penpot `agentdeck/LinkedRepository` rows, `agentdeck/LinkPickerList`, `agentdeck/PickerItem`; an app-local composition, since core-gpui's Combobox draws text-only items): a "Repositories" Label, then a row per Repository the workspace links, by name ignoring case, `space.2` apart from the label, note and field. A row (h-8, `space.2` gaps, sm) is a 14px lucide `Lock` in `muted-foreground` for a private Repository (page-local `agentdeck/icon/Lock` in Penpot until the library has it), its `owner/name` in `foreground`, an outline "Unreachable" Badge while the GitHub sign-in can't see it, then, pushed right, a ghost icon-xs `X`, Unlink. Unlink crosses the row out (`muted-foreground`, line-through) and swaps its `X` for a link xs **Undo**, which puts it back; a picked row's `X` just drops it. Under the rows a sm `muted-foreground` note counts the open PRs the staged unlinks take out of the workspace, counted as its sidebar count is (drafts in, Unreachable and Finished out): "2 open PRs will leave this workspace", "1 open PR will leave this workspace", omitted at 0. Then the picker, an Input with the placeholder "Link a repository…", whose list opens 6px below it, as wide, while it has the keyboard or is typed into, and closes on Escape, a click outside or a pick. The list, drawn as core-gpui's `ComboboxContent`, holds **Suggested** first (a Combobox label over Edit workspace's workspace's Suggestions, §3, in the daemon's order, dismissed ones included, since opening the picker is deliberate; each row with the lock when private; New workspace has none, its workspace not made yet), then **From your pull requests** (a Combobox label over the Repositories of your kept PRs, Finished ones' included, by name, each row with the lock when private, but for those Suggested, so each Repository shows once), each leaving out every Repository the dialog's rows hold and Unreachable ones; typing filters both locally, by name ignoring case, a pasted GitHub URL by the name it holds. A Suggested row is picked as any other: staged by name, linked on Save (Penpot "Edit workspace · picker · suggested"). Text that parses as `owner/name` or a GitHub URL and names no listed or linked Repository adds a "Link owner/name" row (lucide `Plus`), which asks GitHub (`GET /v1/repositories/resolve`; it reads "Looking up owner/name…" meanwhile) and, once GitHub shows it, stages it as a row under the name GitHub gives; if GitHub can't see it, the list closes and the daemon's "GitHub can't see owner/name. Check the name or your token's access." shows under the field, the field `aria-invalid`, until the next keystroke. Nothing matching reads "No repositories match.". After a separator the list ends in "Not listed? Type owner/name or paste its URL.", or, signed out (PR status reads the token logged out), "Sign in to GitHub to find more repositories." with no typed row: only Repositories agentdeck keeps can be picked. Enter in the field picks the list's first row. All your repositories (`/user/repos`) is tracked in [#371](https://github.com/bRRRITSCOLD/agentdeck/issues/371). + - **Edit workspace** (Penpot "Screens · Dialogs" → "Edit workspace", "Edit workspace · error" for a blank name, "Edit workspace · unlinked", "· picker", "· picker · suggested", "· picker · loading", "· picker · couldn't load", "· typed repo", "· GitHub can't see it" and "· signed out") is titled "Edit ", with "Its pull requests come from the repositories it links.". It holds (Penpot `agentdeck/EditWorkspaceForm`) the "Name" field, which opens holding the name, selected and focused, its error under it, then the **Repositories** the workspace links and the "Link a repository…" picker (below), `space.4` apart. Opened from the no-Repositories state's **Link repository** (`LinkRepository`), the picker takes the keyboard instead, its list open. The footer is Cancel and **Save**; Save is disabled while the name is blank, while nothing changed (the name, trimmed, as it was and nothing staged) and while a typed Repository is being looked up, and Enter in the name does the same. Links and unlinks are staged until Save, which applies them with the name in one request, `PATCH /v1/workspaces/{id}` `{ name?, link, unlink }` (the name only when it changed), and closes; each Repository it unlinked then counts as Not now for the workspace's Suggestions (GUI state, above), and a failed Save dismisses nothing. The changes come back through `changed` to the sidebar, the views and the dialogs that list workspaces. Cancel and Escape discard what was staged, and there is no confirm dialog. The slug stays as it is, so running panes are unaffected and the CLI still finds the workspace by its old slug; nothing on disk changes. Two workspaces may share a name. A blank name shows "Give the workspace a name." under the field as soon as it is blank, its input `aria-invalid`; the daemon's `invalid_name` shows there too and keeps the dialog open. A Repository the daemon can't link (`unknown_repository`, `not_signed_in`, `invalid_links`) shows its message under the picker and keeps the dialog open, with nothing applied. Any other failure keeps it open and toasts "Couldn't save " with why. An archived workspace can be edited too. + - **Repositories** (Penpot `agentdeck/LinkedRepository` rows, `agentdeck/LinkPickerList`, `agentdeck/PickerItem`; an app-local composition, since core-gpui's Combobox draws text-only items): a "Repositories" Label, then a row per Repository the workspace links, by name ignoring case, `space.2` apart from the label, note and field. A row (h-8, `space.2` gaps, sm) is a 14px lucide `Lock` in `muted-foreground` for a private Repository (page-local `agentdeck/icon/Lock` in Penpot until the library has it), its `owner/name` in `foreground`, an outline "Unreachable" Badge while the GitHub sign-in can't see it, then, pushed right, a ghost icon-xs `X`, Unlink. Unlink crosses the row out (`muted-foreground`, line-through) and swaps its `X` for a link xs **Undo**, which puts it back; a picked row's `X` just drops it. Under the rows a sm `muted-foreground` note counts the open PRs the staged unlinks take out of the workspace, counted as its sidebar count is (drafts in, Unreachable and Finished out): "2 open PRs will leave this workspace", "1 open PR will leave this workspace", omitted at 0. Then the picker, an Input with the placeholder "Link a repository…", whose list opens 6px below it, as wide, while it has the keyboard or is typed into, and closes on Escape, a click outside or a pick. The list, drawn as core-gpui's `ComboboxContent`, holds **Suggested** first (a Combobox label over Edit workspace's workspace's Suggestions, §3, in the daemon's order, dismissed ones included, since opening the picker is deliberate; each row with the lock when private; New workspace has none, its workspace not made yet), then **From your pull requests** (a Combobox label over the Repositories of your kept PRs, Finished ones' included, by name, each row with the lock when private, but for those Suggested, so each Repository shows once), then **All your repositories** (a Combobox label over the daemon's GitHub repository list, §8, in GitHub's order by `owner/name`, each row with the lock when private, but for those listed above and every Repository agentdeck keeps that is Unreachable), each leaving out every Repository the dialog's rows hold and Unreachable ones; typing filters all three locally, by name ignoring case, a pasted GitHub URL by the name it holds. Each time a dialog opens the picker it asks the daemon to load the list again (`POST /v1/github/repositories/refresh`) and reads it, then reads it again on each `github_repositories` event (§5), so a first load's pages show as they arrive (Penpot "Edit workspace · picker · loading"); a list already loaded keeps showing while the daemon refreshes it. While the list loads, "Loading your repositories… 400 of about 1,100" (ComboboxLabel style; the count once page 1 has answered, with `total` rounded to the hundred, both with thousands commas; "Loading your repositories…" before) sits under the rows, above the separator, so it shows however far they scroll. A list that failed (GitHub's error, a rate limit, a rejected token, or a daemon that couldn't be read) leaves the section's label over "Couldn't load your repositories." and **Retry** (drawn as a link xs Button that doesn't take the keyboard, so the field keeps it and the list stays open), which asks for a load again (Penpot "Edit workspace · picker · couldn't load"); Suggested, From your pull requests and typed names keep working. The rows sit in a scrolling area as tall as they are, up to ComboboxList's 252 px (`spacing-72` − `spacing-9`), and only the rows in view are drawn (GPUI's `list`), so about 1,100 rows cost no more than a screenful. A Suggested row is picked as any other: staged by name, linked on Save (Penpot "Edit workspace · picker · suggested"). Text that parses as `owner/name` or a GitHub URL and names no listed or linked Repository adds a "Link owner/name" row (lucide `Plus`), which asks GitHub (`GET /v1/repositories/resolve`; it reads "Looking up owner/name…" meanwhile) and, once GitHub shows it, stages it as a row under the name GitHub gives; if GitHub can't see it, the list closes and the daemon's "GitHub can't see owner/name. Check the name or your token's access." shows under the field, the field `aria-invalid`, until the next keystroke. Nothing matching reads "No repositories match.". After a separator the list ends in "Not listed? Type owner/name or paste its URL.", or, signed out (PR status reads the token logged out, or the GitHub repository list reads `signed_out`), "Sign in to GitHub to find more repositories." in place of All your repositories, with no typed row: only Repositories agentdeck keeps can be picked. Enter in the field picks the list's first row. The sidebar doesn't read its snapshot again for a `github_repositories` event, which only the picker reads. - **Delete workspace** is titled "Delete ?", with "This can't be undone. Archive it instead to keep its panes and linked Repositories." Deleting touches no folder, so there is nothing on disk to warn about. - Its body (Penpot "Screens · Dialogs" → "Delete workspace", "Delete workspace · panes running") says what deleting does, a muted line each, `space.3` apart: "Its N Repositories are unlinked. Their PRs stay in Pull requests." ("Its 1 Repository is unlinked. Its PRs stay in Pull requests."; left out when it links none), counting the Repositories that link it as the sidebar last read them (`GET /v1/repositories`); then "Its N running panes will be stopped." ("1 running pane"; left out with none); then "Type to confirm" over an input. Running panes are the workspace's panes whose process hasn't exited, as Archive counts them; deleting stops them (§4). - The footer is **Archive instead** (absent once archived), which closes it and archives as the menu does, **Cancel** and the destructive **Delete workspace**. Delete is disabled until the input is the name exactly; Enter does the same, and Escape cancels. @@ -542,8 +552,8 @@ Built on `brrritscold-core-gpui` (`init`, `Root`, theme preference, toasts). Scr | Tier | Where | What | |---|---|---| -| unit | `agentdeck-core`, GUI views (`#[gpui::test]`), daemon pure parts | rules with recorded output (the Copy PR details text among them, one PR's and several joined by a blank line), layout tree, snapshot encode/decode round-trip, env allowlist, `openapi.json` staleness; GUI views over a fake API and a fake notifier, asserting what a user sees (the Pull requests view's groups and their order, collapse and Show finished kept in the GUI state file, Finished rows hidden until Show finished and showing GitHub's state, the row's link and menu, Sync now, the banner, the empty state, Unreachable rows; Select mode: entering and leaving it, picking by row click, group checkbox (folded too) and select-all, which rows can be picked (open and reachable, Finished-but-open included; not merged, closed or Unreachable), the bar's count and order, Copy PR details joined in the list's order, Close PRs asking then closing by reference, a PR that didn't close kept picked and marked with why, a closed PR shown closed at once, "Closing N of M…", and Select disabled on the empty view; the header and the table fitting the narrowest window in Select mode, and that window's minimum fitting the narrowest PR table in Select mode; the sidebar's entries and counts, Finished PRs left out, no Inbox or Tasks entry, each Workspace's count over its linked Repositories, none on an archived row, the no-Workspaces hint and its New workspace, Pull requests the fallback selection; linked groups first, then Not in a workspace, each alphabetical, a group's header naming its linking Workspaces as links that open their Pull requests, Archived Workspaces absent from headers and order; the group `…` menu on every group of both views, in the rows' `…` column: Open on GitHub opening the Repository's page, Link to a workspace offering the Workspaces that aren't archived and don't link it in the sidebar's order then New workspace, New workspace alone when none is eligible, New workspace opening the dialog with the Repository picked, a link applied at once by GitHub's id with "Linked owner/name to " and an Undo that unlinks, Unlink from this workspace only on a Workspace's Pull requests, applied at once with "Unlinked owner/name from " and its open PRs (singular, plural, none, and where they went when no other Workspace links it), its Undo linking again by id once the unlink deleted the Repository, and failures toasted; a Workspace's side switch with its count, `secondary-shift-p`, each Workspace's side remembered across a restart and opened from its sidebar row, a new one on its Panes; a Workspace's Pull requests: only its linked Repositories, "No open PRs", Select, Show finished and Edit workspace with no sync controls, the banner, collapse kept apart from the Pull requests view's, the no-Repositories state whose Link repository opens Edit workspace with its picker focused and open; Edit workspace and New workspace: the linked rows with their Unlink, lock and Unreachable badge, staging until Save (one request with the name, applied to the fake, none before), Save enabled by a staged change alone, Undo, the leaving note and its singular and its absence at 0, Cancel discarding what was staged, a refusal under the picker keeping the dialog open, an archived workspace linked, the picker's From your pull requests (no linked, picked or Unreachable Repository; the lock), local filtering ignoring case and by a pasted URL, picking (the field cleared), Enter picking the first row, the typed row only for an unlisted name, GitHub showing it (staged under GitHub's name, private kept) or not ("GitHub can't see …" under the field, the list closed, cleared by typing), signed out (no typed row, "Sign in to GitHub to find more repositories."), and New workspace linking what was picked on create; the picker's Suggested section first, ignoring dismissals, its rows left out of From your pull requests, filtered as typed, picked by click or Enter; the Suggestions strip on a Workspace's Pull requests (one row alone, several stacked in one strip under the header and over the table, none on the Pull requests view, an archived Workspace or for what it links by now), Link at once by GitHub's id with "Linked owner/name to ", the row gone and the group shown once read, its Undo unlinking without dismissing and a failure toasted with the row kept, Not now taking the row away for that Workspace only and kept across a restart in the GUI state file, the strip under Link repository on a Workspace with no Repositories, and an unlink from the group menu or Edit workspace's Save recording a dismissal (a failed one none); the GUI state's dismissed pairs, written by id; the picker's offer read from a snapshot (linked ones, Unreachable included; Suggestions but what the Workspace links by now; your PRs' reachable Repositories; open PRs counted as the sidebar does; signed out only while the token is logged out); the archived screen with no switch; a pane notifying while its workspace shows its Pull requests; New workspace's Name field and optional picker; New agent's Folder select (where a new pane starts first, the other panes' folders, then `~`, each once) and a new pane starting in `~` in a workspace with none; the Delete workspace dialog's lines (its Repositories unlinked, its running panes stopped, each left out at 0); the archive toast; the top bar's name, centred, before its side switch; a Pane alert's body, " · ", and the pane header's parts; PR alerts over the fake notifier: each trigger, only PRs you authored, one alert per PR replaced on a new change, a click landing on the row with its group opened, a Finished row shown with Show finished left off, scrolled to and highlighted until the highlight fades, "N PRs changed" opening the view, an alert withdrawn once the view shows, and the mute rule with every linking Workspace muted, one unmuted, only Archived muted ones, and none); the PR alert mute rule and the GitHub remote parser (https, ssh and scp-like URLs, for Suggestions) in `agentdeck-core`; the daemon's git config reader for Suggestions (each remote's first URL by name, sections and keys ignoring case, the old dotted header, comments and quotes, `upstream` on GitHub over `origin`, no other remote; a folder deep in a repo, a worktree's `.git` file and `commondir`, a relative `gitdir`, none outside a repo) and which events make Suggestions due | -| integration | `agentdeckd/tests/integration` | temp `$XDG_*` dirs, a real daemon on a random port, a real client; PTYs run `sh`, which moves a pane with `cd` (read through `/proc`) or `printf`s an OSC 7, so a pane's current folder, its `changed` and its restore folder are tested without a shell that reports one; GitHub is httpmock (`AGENTDECK_GITHUB_API`, `AGENTDECK_GITHUB_REST_API` and `AGENTDECK_GITHUB_OAUTH`: GraphQL with `closePullRequest`, REST's `GET /repos/{owner}/{repo}` for Repository lookups, Links and Suggestions, and the device flow's code and token endpoints); Suggestions run Panes (`sh`, `sleep`) in temp git repos with `upstream`, `origin` and other remotes: upstream on GitHub over origin, origin when upstream is elsewhere, other remotes ignored, none outside a repo, one per name, a Pane that `cd`s in, an exited Pane at its last folder, a name GitHub can't see never suggested, a renamed one under GitHub's name, each name asked about once per run across reads and Workspaces, signed out only kept Repositories, one other Workspaces link still suggested, one the Workspace links left out, an archived Workspace none, `404 not_found`, and `changed suggestions` when a Pane opens in or moves into a repo, a Link takes one away and a deleted Pane takes one away; the client's `repositories::suggestions` against the same daemon, none from an older one; `gh` is a stub script on `PATH`, and so are `claude` and `codex`, which read input as their TUIs do, and exit on a submitted `/exit` so a shell pane's hosted agent can leave (raw, bracketed paste on, a read that is a lone `\r` submits, any other read is a paste); the keyring is an in-memory fake store (`AGENTDECK_KEYRING=memory`; without it the harness's daemon has no session bus, so no keyring). The `agentdeck_client` helpers the GUI's real API calls (`panes`, `settings`, `prs`, `repositories`, `workspaces`) are tested here through the real client (`*_client`), each new operation of the GUI's fake API with a test of the same call in the same PR, so the fake can't drift from the daemon; `prs::list` also lists none from a daemon older than `GET /v1/prs`, and lists Finished PRs, marked; `repositories::list` lists each Repository with the Workspaces linking it, Archived ones included, and none from a daemon older than `GET /v1/repositories`; `repositories::resolve` answers the Repository GitHub shows for a typed URL and fails with the daemon's "GitHub can't see …"; `repositories::link` links by GitHub's id and links again, signed out, once an unlink deleted the Repository, and `repositories::unlink` keeps one another Workspace links and fails with the daemon's `not_found` for one the Workspace doesn't link; `workspaces::create` makes a Workspace linking what was picked, or nothing, and `workspaces::update` renames, links and unlinks together, or changes nothing, failing with the daemon's words. The Workspace routes' Links are tested here too: create linking a Repository agentdeck keeps (no GitHub call) and one GitHub resolves, nothing made when GitHub can't see one; update renaming, linking and unlinking in one request (an unreferenced Repository gone), nothing changed when a link fails or the name is blank, `invalid_links`, unlinking one it doesn't link changing nothing, an archived Workspace linked, and `changed` for each Repository then the workspace. The link route's link by GitHub's `id` is tested here too: a Repository an unlink deleted stored again from the body signed out (no GitHub, where a link by name is `not_signed_in`), the Repository kept with that id linked under its name now, `changed` for the Repository then the workspace, and `404 not_found` storing nothing for a Workspace that doesn't exist. PR sync's Finished PRs are tested here too: Finished on merge, on close (from GitHub and from agentdeck) and past the cutoff, no longer Finished once GitHub shows a PR open again, deleted with their unreferenced Repositories after the window (`AGENTDECK_PR_FINISHED_SECS=0`), and Unreachable PRs kept with no window. PRs are kept by Repository and number: a renamed Repository's PR and one of another Repository that took the old name are two PRs. Workspaces without folders are tested here too: creating one makes nothing on disk and its JSON has no folder, an older client's `dir` and `force` are ignored, the dirty report route is gone (dropshot's own 404), deleting one unlinks its Repositories (a Repository nothing else names goes) and stops its panes but leaves every folder on disk (its panes' folders and an old scratch folder), the first pane of a workspace with none opens in `~` through `panes::new_shell_tab`, and `0002` drops the folder columns from a database at `0001`, keeping each Workspace and its Links. The fresh start is tested here too: a fresh data dir gets the migrations' schema (no `tasks`, `comments` or `instructions`; `pull_requests` keyed by `(repository_id, number)` with nothing unique on a name), a current database survives a restart, and a database with a `tasks` table, its last writes still in its WAL, is moved aside with its WAL and SHM files (the moved one still reads), logged, never over an earlier one, with scratch folders left alone, and the daemon starts empty | +| unit | `agentdeck-core`, GUI views (`#[gpui::test]`), daemon pure parts | rules with recorded output (the Copy PR details text among them, one PR's and several joined by a blank line), layout tree, snapshot encode/decode round-trip, env allowlist, `openapi.json` staleness; GUI views over a fake API and a fake notifier, asserting what a user sees (the Pull requests view's groups and their order, collapse and Show finished kept in the GUI state file, Finished rows hidden until Show finished and showing GitHub's state, the row's link and menu, Sync now, the banner, the empty state, Unreachable rows; Select mode: entering and leaving it, picking by row click, group checkbox (folded too) and select-all, which rows can be picked (open and reachable, Finished-but-open included; not merged, closed or Unreachable), the bar's count and order, Copy PR details joined in the list's order, Close PRs asking then closing by reference, a PR that didn't close kept picked and marked with why, a closed PR shown closed at once, "Closing N of M…", and Select disabled on the empty view; the header and the table fitting the narrowest window in Select mode, and that window's minimum fitting the narrowest PR table in Select mode; the sidebar's entries and counts, Finished PRs left out, no Inbox or Tasks entry, each Workspace's count over its linked Repositories, none on an archived row, the no-Workspaces hint and its New workspace, Pull requests the fallback selection; linked groups first, then Not in a workspace, each alphabetical, a group's header naming its linking Workspaces as links that open their Pull requests, Archived Workspaces absent from headers and order; the group `…` menu on every group of both views, in the rows' `…` column: Open on GitHub opening the Repository's page, Link to a workspace offering the Workspaces that aren't archived and don't link it in the sidebar's order then New workspace, New workspace alone when none is eligible, New workspace opening the dialog with the Repository picked, a link applied at once by GitHub's id with "Linked owner/name to " and an Undo that unlinks, Unlink from this workspace only on a Workspace's Pull requests, applied at once with "Unlinked owner/name from " and its open PRs (singular, plural, none, and where they went when no other Workspace links it), its Undo linking again by id once the unlink deleted the Repository, and failures toasted; a Workspace's side switch with its count, `secondary-shift-p`, each Workspace's side remembered across a restart and opened from its sidebar row, a new one on its Panes; a Workspace's Pull requests: only its linked Repositories, "No open PRs", Select, Show finished and Edit workspace with no sync controls, the banner, collapse kept apart from the Pull requests view's, the no-Repositories state whose Link repository opens Edit workspace with its picker focused and open; Edit workspace and New workspace: the linked rows with their Unlink, lock and Unreachable badge, staging until Save (one request with the name, applied to the fake, none before), Save enabled by a staged change alone, Undo, the leaving note and its singular and its absence at 0, Cancel discarding what was staged, a refusal under the picker keeping the dialog open, an archived workspace linked, the picker's From your pull requests (no linked, picked or Unreachable Repository; the lock), local filtering ignoring case and by a pasted URL, picking (the field cleared), Enter picking the first row, the typed row only for an unlisted name, GitHub showing it (staged under GitHub's name, private kept) or not ("GitHub can't see …" under the field, the list closed, cleared by typing), signed out (no typed row, "Sign in to GitHub to find more repositories."), and New workspace linking what was picked on create; the picker's Suggested section first, ignoring dismissals, its rows left out of From your pull requests, filtered as typed, picked by click or Enter; its All your repositories after the other sections (none listed above, linked or Unreachable; the lock), filtered as typed, picked by click or Enter, no typed row for a name it lists, a refresh asked each time it opens, the rows loaded so far with "Loading your repositories… N of about M" under them (and with no count before page 1, and still in view under rows that scroll), read again on `changed github_repositories`, "Couldn't load your repositories." with Retry (GitHub's failure or the daemon unreadable) keeping the other sections and typed names, Retry loading again, "Sign in to GitHub…" in its place signed out (PR status or the list's `signed_out`), and only the rows in view drawn for 1,100; the loading line's count and rounding; the sidebar not reading again for a `github_repositories` event; the Suggestions strip on a Workspace's Pull requests (one row alone, several stacked in one strip under the header and over the table, none on the Pull requests view, an archived Workspace or for what it links by now), Link at once by GitHub's id with "Linked owner/name to ", the row gone and the group shown once read, its Undo unlinking without dismissing and a failure toasted with the row kept, Not now taking the row away for that Workspace only and kept across a restart in the GUI state file, the strip under Link repository on a Workspace with no Repositories, and an unlink from the group menu or Edit workspace's Save recording a dismissal (a failed one none); the GUI state's dismissed pairs, written by id; the picker's offer read from a snapshot (linked ones, Unreachable included; Suggestions but what the Workspace links by now; your PRs' reachable Repositories; open PRs counted as the sidebar does; signed out only while the token is logged out); the archived screen with no switch; a pane notifying while its workspace shows its Pull requests; New workspace's Name field and optional picker; New agent's Folder select (where a new pane starts first, the other panes' folders, then `~`, each once) and a new pane starting in `~` in a workspace with none; the Delete workspace dialog's lines (its Repositories unlinked, its running panes stopped, each left out at 0); the archive toast; the top bar's name, centred, before its side switch; a Pane alert's body, " · ", and the pane header's parts; PR alerts over the fake notifier: each trigger, only PRs you authored, one alert per PR replaced on a new change, a click landing on the row with its group opened, a Finished row shown with Show finished left off, scrolled to and highlighted until the highlight fades, "N PRs changed" opening the view, an alert withdrawn once the view shows, and the mute rule with every linking Workspace muted, one unmuted, only Archived muted ones, and none); the PR alert mute rule and the GitHub remote parser (https, ssh and scp-like URLs, for Suggestions) in `agentdeck-core`; the daemon's git config reader for Suggestions (each remote's first URL by name, sections and keys ignoring case, the old dotted header, comments and quotes, `upstream` on GitHub over `origin`, no other remote; a folder deep in a repo, a worktree's `.git` file and `commondir`, a relative `gitdir`, none outside a repo) and which events make Suggestions due | +| integration | `agentdeckd/tests/integration` | temp `$XDG_*` dirs, a real daemon on a random port, a real client; PTYs run `sh`, which moves a pane with `cd` (read through `/proc`) or `printf`s an OSC 7, so a pane's current folder, its `changed` and its restore folder are tested without a shell that reports one; GitHub is httpmock (`AGENTDECK_GITHUB_API`, `AGENTDECK_GITHUB_REST_API` and `AGENTDECK_GITHUB_OAUTH`: GraphQL with `closePullRequest`, REST's `GET /repos/{owner}/{repo}` for Repository lookups, Links and Suggestions and `GET /user/repos` for the GitHub repository list, and the device flow's code and token endpoints); Suggestions run Panes (`sh`, `sleep`) in temp git repos with `upstream`, `origin` and other remotes: upstream on GitHub over origin, origin when upstream is elsewhere, other remotes ignored, none outside a repo, one per name, a Pane that `cd`s in, an exited Pane at its last folder, a name GitHub can't see never suggested, a renamed one under GitHub's name, each name asked about once per run across reads and Workspaces, signed out only kept Repositories, one other Workspaces link still suggested, one the Workspace links left out, an archived Workspace none, `404 not_found`, and `changed suggestions` when a Pane opens in or moves into a repo, a Link takes one away and a deleted Pane takes one away; the client's `repositories::suggestions` against the same daemon, none from an older one; the GitHub repository list (REST `GET /user/repos` on httpmock, pages with a `Link` header): not loaded until a refresh asks, every page in GitHub's order once loaded, one page with no `Link` header, page 1 served while the rest load (`total` estimated from the last page link), the last page read first so `total` is exact early, a `github_repositories` event as the load begins, as each page arrives and as it ends, the list kept across reads with no new request, a refresh quietly showing the list before until the new one has loaded, a refresh while a load runs left alone, a 5xx tried three times then `failed` and loaded on a retry, a 403 rate limit and a 429 failing at once, a later page failing the whole load, a 401 `failed` ("GitHub rejected the token"), a failed quiet refresh keeping the list with its `error`, `signed_out` with no token and no GitHub call, a changed token loading the new sign-in's list, and `search/repositories` never called; the client's `repositories::github_list` and `refresh_github_list` against the same daemon (loaded, signed out, the daemon's `unauthorized`); `gh` is a stub script on `PATH`, and so are `claude` and `codex`, which read input as their TUIs do, and exit on a submitted `/exit` so a shell pane's hosted agent can leave (raw, bracketed paste on, a read that is a lone `\r` submits, any other read is a paste); the keyring is an in-memory fake store (`AGENTDECK_KEYRING=memory`; without it the harness's daemon has no session bus, so no keyring). The `agentdeck_client` helpers the GUI's real API calls (`panes`, `settings`, `prs`, `repositories`, `workspaces`) are tested here through the real client (`*_client`), each new operation of the GUI's fake API with a test of the same call in the same PR, so the fake can't drift from the daemon; `prs::list` also lists none from a daemon older than `GET /v1/prs`, and lists Finished PRs, marked; `repositories::list` lists each Repository with the Workspaces linking it, Archived ones included, and none from a daemon older than `GET /v1/repositories`; `repositories::resolve` answers the Repository GitHub shows for a typed URL and fails with the daemon's "GitHub can't see …"; `repositories::link` links by GitHub's id and links again, signed out, once an unlink deleted the Repository, and `repositories::unlink` keeps one another Workspace links and fails with the daemon's `not_found` for one the Workspace doesn't link; `workspaces::create` makes a Workspace linking what was picked, or nothing, and `workspaces::update` renames, links and unlinks together, or changes nothing, failing with the daemon's words. The Workspace routes' Links are tested here too: create linking a Repository agentdeck keeps (no GitHub call) and one GitHub resolves, nothing made when GitHub can't see one; update renaming, linking and unlinking in one request (an unreferenced Repository gone), nothing changed when a link fails or the name is blank, `invalid_links`, unlinking one it doesn't link changing nothing, an archived Workspace linked, and `changed` for each Repository then the workspace. The link route's link by GitHub's `id` is tested here too: a Repository an unlink deleted stored again from the body signed out (no GitHub, where a link by name is `not_signed_in`), the Repository kept with that id linked under its name now, `changed` for the Repository then the workspace, and `404 not_found` storing nothing for a Workspace that doesn't exist. PR sync's Finished PRs are tested here too: Finished on merge, on close (from GitHub and from agentdeck) and past the cutoff, no longer Finished once GitHub shows a PR open again, deleted with their unreferenced Repositories after the window (`AGENTDECK_PR_FINISHED_SECS=0`), and Unreachable PRs kept with no window. PRs are kept by Repository and number: a renamed Repository's PR and one of another Repository that took the old name are two PRs. Workspaces without folders are tested here too: creating one makes nothing on disk and its JSON has no folder, an older client's `dir` and `force` are ignored, the dirty report route is gone (dropshot's own 404), deleting one unlinks its Repositories (a Repository nothing else names goes) and stops its panes but leaves every folder on disk (its panes' folders and an old scratch folder), the first pane of a workspace with none opens in `~` through `panes::new_shell_tab`, and `0002` drops the folder columns from a database at `0001`, keeping each Workspace and its Links. The fresh start is tested here too: a fresh data dir gets the migrations' schema (no `tasks`, `comments` or `instructions`; `pull_requests` keyed by `(repository_id, number)` with nothing unique on a name), a current database survives a restart, and a database with a `tasks` table, its last writes still in its WAL, is moved aside with its WAL and SHM files (the moved one still reads), logged, never over an earlier one, with scratch folders left alone, and the daemon starts empty | | integration | `mod integration_tests` in `agentdeckd/src` | a crate-private part over a real dependency, which `tests/integration` can't reach since the daemon is a binary: a `Pane` over a real PTY running `sh` reads as exited only once its exit is recorded. The integration nextest profile runs these modules; the unit one skips them | | integration | `agentdeckd/tests/integration` (keyring) | the keyring store against a real Secret Service: `gnome-keyring-daemon`, unlocked, on a private `dbus-daemon` session bus the test starts, as `agentdeck-notify`'s test does, which CI installs with `script/install-linux-deps.sh`. It saves, finds, replaces and deletes the token and client ID entries, and finds none with no Secret Service. It is the fake store's contract test: the same cases run against the fake, and a fake lands with a test of the real call in the same PR | | integration | `agentdeck/tests/integration` | the real `agentdeck` binary in temp `$XDG_*` dirs, starting the real daemon itself, with GitHub on httpmock, GraphQL and REST, for `pr ls` (by Repository and by workspace), `pr close`, `repo ls|link|unlink` and `ws new|ls|rename|rm` (no folder made or removed, `ws ls`' REPOSITORIES in text and `--json`, `ws rm` unlinking, no `--dir`, `--repo` or `--force`); a long-lived client (the test binary re-run as a child, connecting through `agentdeck_client::daemon`, as the GUI does) for reaping and restarting the daemon it started; panes run `sh`, never a real agent CLI | From 405c6e0dd18f05d7d84e4c51103a9b44cdbb4642 Mon Sep 17 00:00:00 2001 From: bRRRITSCOLD Date: Mon, 23 Nov 2026 17:38:31 -0700 Subject: [PATCH 5/5] docs(gui): plain intra-doc link to GPUI's list (#371) Co-Authored-By: Claude Opus 5.5 --- crates/agentdeck-gui/src/link_picker.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/agentdeck-gui/src/link_picker.rs b/crates/agentdeck-gui/src/link_picker.rs index 4fc5f5c..a4629da 100644 --- a/crates/agentdeck-gui/src/link_picker.rs +++ b/crates/agentdeck-gui/src/link_picker.rs @@ -21,7 +21,7 @@ //! github_repositories` reads it again, so its pages show as they arrive with "Loading your //! repositories… 400 of about 1,100" under them. A list that failed to load reads "Couldn't //! load your repositories." with Retry, and the other sections and typed names keep working. -//! The list draws only the rows in view, through GPUI's [`list`](gpui::list): about 1,100 +//! The list draws only the rows in view, through GPUI's [`list`]: about 1,100 //! rows drawn whole would make every frame slow. use std::cell::Cell;