diff --git a/crates/agentdeck-gui/src/pr_table.rs b/crates/agentdeck-gui/src/pr_table.rs index dea6d44..da2913d 100644 --- a/crates/agentdeck-gui/src/pr_table.rs +++ b/crates/agentdeck-gui/src/pr_table.rs @@ -41,6 +41,10 @@ pub type OnToggle = Box; /// does (archived ones link nothing). pub const NOT_IN_A_WORKSPACE: &str = "Not in a workspace"; +/// What an Unreachable Repository's group header says in place of the Workspaces linking it +/// (spec §11; Penpot "Screens · Main" → "Pull requests · unreachable repository"). +pub const UNREACHABLE_REPOSITORY: &str = "Unreachable: can't sync, PRs may be out of date"; + /// The table's least width: every column, the title at its least, the `space.3` gaps and the /// rows' `space.2` padding, and with `select` the `Select` layer's. Narrower than any window /// the sidebar leaves room for. @@ -111,9 +115,10 @@ pub type OnWorkspace = Rc; /// its checkbox, then, `space.2` after it in sm `muted-foreground`, who links the Repository: /// each Workspace in `workspaces` by name, `·` apart, a link to its Pull requests that runs /// `on_workspace` (underlined on hover, as a PR's reference), or [`NOT_IN_A_WORKSPACE`] with -/// none, then, pushed right into the rows' `Menu` column, its `menu`. `key` names it: tests -/// find it as `group `, its workspaces as `group workspaces ` and each one's link as -/// `workspace link `. +/// none; [`UNREACHABLE_REPOSITORY`] instead of either while `unreachable`. Then, pushed right +/// into the rows' `Menu` column, its `menu`. `key` names it: tests find it as `group `, +/// its workspaces as `group workspaces `, each one's link as `workspace link +/// `, and the Unreachable words as `group unreachable `. #[allow(clippy::too_many_arguments)] pub fn group_header( key: SharedString, @@ -122,6 +127,7 @@ pub fn group_header( collapsed: bool, select: SelectCell, workspaces: &[Linker], + unreachable: bool, on_toggle: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static, on_workspace: OnWorkspace, menu: Option, @@ -137,6 +143,16 @@ pub fn group_header( .text_size(font_size::SM) .text_color(s.muted_foreground); let names = match workspaces { + _ if unreachable => { + let selector = format!("group unreachable {key}"); + names.child( + div() + .debug_selector(move || selector) + .min_w_0() + .truncate() + .child(UNREACHABLE_REPOSITORY), + ) + } [] => names.child(NOT_IN_A_WORKSPACE), workspaces => names.children(workspaces.iter().enumerate().flat_map(|(ix, w)| { let id = w.id; diff --git a/crates/agentdeck-gui/src/pull_requests.rs b/crates/agentdeck-gui/src/pull_requests.rs index 2514bb9..f6e8384 100644 --- a/crates/agentdeck-gui/src/pull_requests.rs +++ b/crates/agentdeck-gui/src/pull_requests.rs @@ -6,7 +6,8 @@ //! Groups go linked Repositories first, then those Not in a workspace, each alphabetically by //! the Repository's name. A group's header names the Workspaces linking its Repository (archived //! ones link nothing), each a link to that Workspace's Pull requests ([`OpenWorkspace`]), or -//! reads "Not in a workspace". On the Pull requests view a group with no PR to show is left out; +//! reads "Not in a workspace"; an Unreachable Repository's reads "Unreachable: can't sync, PRs +//! may be out of date" instead (Penpot "Pull requests · unreachable repository"). On the Pull requests view a group with no PR to show is left out; //! on a Workspace's Pull requests every linked Repository shows, one with none to show over a //! muted "No open PRs" row. A group collapses at a click, remembered per view and per //! Repository across restarts in the GUI's own state ([`gui_state`]). @@ -199,6 +200,8 @@ pub struct Group { /// The Workspaces linking it, archived ones left out, in the sidebar's order; none while /// it is Not in a workspace. pub workspaces: Vec, + /// Whether it is Unreachable: the GitHub sign-in can't see it, so its PRs can't sync. + pub unreachable: bool, } /// The groups of `snapshot`'s PRs a list over `scope` shows, its PRs by number: one per @@ -228,6 +231,7 @@ pub fn groups( label: name.name().to_owned().into(), prs: Vec::new(), workspaces: Vec::new(), + unreachable: false, }; let mut groups: Vec = Vec::new(); for pr in (snapshot.prs.iter()).filter(shown) { @@ -250,6 +254,8 @@ pub fn groups( } } for group in &mut groups { + group.unreachable = (snapshot.repositories.iter()) + .any(|links| links.id == group.repository && links.unreachable); group.workspaces = (snapshot.linking(group.repository).into_iter()) .map(|w| Linker { id: w.id, @@ -296,6 +302,8 @@ enum Item { selectable: Vec, /// The Workspaces linking it. workspaces: Vec, + /// Whether it is Unreachable. + unreachable: bool, }, /// A PR. Row(Box), @@ -319,6 +327,7 @@ fn items(groups: &[Group], collapsed: &BTreeSet) -> Vec { .map(PrKey::of) .collect(), workspaces: group.workspaces.clone(), + unreachable: group.unreachable, }); if folded { continue; @@ -698,6 +707,7 @@ impl PullRequestsView { collapsed, selectable, workspaces, + unreachable, }) => { let repository = *repository; let select = close_prs::select_all(&self.close, name, selectable.clone(), cx); @@ -713,6 +723,7 @@ impl PullRequestsView { *collapsed, select, workspaces, + *unreachable, cx.listener(move |this, _, _, cx| this.toggle(repository, cx)), on_workspace, menu, @@ -2743,6 +2754,66 @@ mod tests { } } + /// An Unreachable Repository's group (spec §11): its header says it can't sync in place of + /// the Workspaces linking it, on both views. + mod unreachable_repository { + use super::*; + + /// [`linked`] with `acme/widgets` and `acme/tools`, both linked by `a`, Unreachable. + fn with_unreachable() -> Snapshot { + let mut snapshot = linked(); + for links in &mut snapshot.repositories { + let name = links.name.to_string(); + links.unreachable = name == "acme/widgets" || name == "acme/tools"; + } + snapshot + } + + #[test] + fn should_mark_its_group_and_keep_it_among_the_linked_ones() { + let groups = groups(&with_unreachable(), Scope::All, false, None); + + let marked: Vec<(String, bool)> = (groups.iter()) + .map(|g| (g.label.to_string(), g.unreachable)) + .collect(); + assert_eq!( + marked, + [ + ("widgets".to_owned(), true), + ("apples".to_owned(), false), + ("gadgets".to_owned(), false), + ("zebra".to_owned(), false), + ] + ); + } + + #[gpui::test] + fn should_say_it_cannot_sync_in_place_of_the_workspaces_linking_it( + cx: &mut TestAppContext, + ) { + let (_harness, cx) = Harness::open(with_unreachable(), cx); + + let header = bounds("group acme/widgets".into(), cx); + let said = bounds("group unreachable acme/widgets".into(), cx); + assert!(said.left() > header.right(), "{said:?} after {header:?}"); + assert!(!shows("workspace link acme/widgets a".into(), cx)); + assert!(!shows("group unreachable acme/apples".into(), cx)); + assert_eq!( + pr_table::UNREACHABLE_REPOSITORY, + "Unreachable: can't sync, PRs may be out of date" + ); + } + + #[gpui::test] + fn should_say_so_on_a_workspaces_pull_requests_too(cx: &mut TestAppContext) { + let (_harness, cx) = Harness::open_in(a(), with_unreachable(), cx); + + assert!(shows("group unreachable acme/tools".into(), cx)); + assert!(shows("no open prs acme/tools".into(), cx)); + assert!(shows("group unreachable acme/widgets".into(), cx)); + } + } + mod show_finished { use super::*; diff --git a/crates/agentdeck/tests/integration/repo.rs b/crates/agentdeck/tests/integration/repo.rs index cc8addc..f42b19e 100644 --- a/crates/agentdeck/tests/integration/repo.rs +++ b/crates/agentdeck/tests/integration/repo.rs @@ -5,7 +5,9 @@ use std::ffi::OsString; use httpmock::MockServer; use serde_json::{Value, json}; -use crate::support::github::{Pr, mock_open_prs, mock_repo, mock_repo_missing, repository_id}; +use crate::support::github::{ + Pr, mock_open_prs, mock_repo, mock_repo_by_id_missing, mock_repo_missing, repository_id, +}; use crate::support::{TestEnv, text}; const TOKEN: &str = "gho_test"; @@ -91,6 +93,43 @@ mod repo_ls { ); } + /// A linked Repository GitHub no longer shows the sign-in, once `pr sync` read it by id. + fn unreachable_widgets(github: &MockServer) -> TestEnv { + let env = showing(github, &[WIDGETS]); + mock_open_prs(github, TOKEN, &[]); + mock_repo_by_id_missing(github, WIDGETS); + env.workspace("web"); + env.ok(&["repo", "link", WIDGETS, "--ws", "web"]); + let status = env.json(&["pr", "sync"]); + assert_eq!(status["last_error"], Value::Null, "{status}"); + env + } + + #[test] + fn should_mark_a_repository_github_no_longer_shows_unreachable_and_keep_its_link() { + let github = MockServer::start(); + let env = unreachable_widgets(&github); + + let stdout = env.ok(&["repo", "ls"]); + + assert_eq!( + stdout, + "REPOSITORY WORKSPACES\n\ + acme/widgets (unreachable) web\n" + ); + } + + #[test] + fn should_say_it_is_unreachable_with_json() { + let github = MockServer::start(); + let env = unreachable_widgets(&github); + + let repositories = env.json(&["repo", "ls"]); + + assert_eq!(repositories[0]["name"], WIDGETS); + assert_eq!(repositories[0]["unreachable"], true); + } + #[test] fn should_say_when_there_are_none() { let env = TestEnv::new(); diff --git a/crates/agentdeck/tests/integration/support/github.rs b/crates/agentdeck/tests/integration/support/github.rs index 56825cf..1ed3cad 100644 --- a/crates/agentdeck/tests/integration/support/github.rs +++ b/crates/agentdeck/tests/integration/support/github.rs @@ -108,6 +108,17 @@ pub fn mock_repo_missing<'a>(server: &'a MockServer, repo: &str) -> Mock<'a> { }) } +/// The REST API's `GET /repositories/{id}` for `repo`'s id, answered 404 as for a Repository +/// deleted, or one the token can no longer see. +pub fn mock_repo_by_id_missing<'a>(server: &'a MockServer, repo: &str) -> Mock<'a> { + server.mock(|when, then| { + when.method(GET) + .path(format!("/repositories/{}", repository_id(repo))); + then.status(404) + .json_body(json!({ "message": "Not Found" })); + }) +} + /// The mocks [`mock_open_prs`] answers a sync with. pub struct OpenPrs<'a> { /// The list of open PRs you authored, which a full sync reads. diff --git a/crates/agentdeckd/src/db/repositories.rs b/crates/agentdeckd/src/db/repositories.rs index 3832f62..d0962de 100644 --- a/crates/agentdeckd/src/db/repositories.rs +++ b/crates/agentdeckd/src/db/repositories.rs @@ -10,14 +10,24 @@ use crate::prsync::github::RemoteRepository; /// Stores `repository` as GitHub reports it now, by its id: a new one is created; a known one /// takes its new name, URL, private and archived, so a rename or a transfer keeps it the same -/// Repository. Returns whether anything changed: `false` when it was stored as it is. +/// Repository, and GitHub showing it clears its Unreachable mark. Returns whether anything +/// changed: `false` when it was stored as it is. pub fn store(conn: &Connection, repository: &RemoteRepository) -> Result { let id = repository.id.get(); - let stored: Option<(String, String, bool, bool)> = conn + let stored: Option<(String, String, bool, bool, bool)> = conn .query_row( - "SELECT full_name, url, private, archived FROM repositories WHERE id = ?1", + "SELECT full_name, url, private, archived, unreachable_at IS NOT NULL + FROM repositories WHERE id = ?1", [id], - |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)), + |row| { + Ok(( + row.get(0)?, + row.get(1)?, + row.get(2)?, + row.get(3)?, + row.get(4)?, + )) + }, ) .optional()?; let now = ( @@ -25,6 +35,7 @@ pub fn store(conn: &Connection, repository: &RemoteRepository) -> Result Result Result { + let marked = conn.execute( + "UPDATE repositories SET unreachable_at = ?2 WHERE id = ?1 AND unreachable_at IS NULL", + params![id.get(), super::now()], + )?; + Ok(marked > 0) +} + +/// Stores what GitHub read by id says of stored Repositories, in one transaction: each of +/// `found` as GitHub shows it now ([`store`]), and each of `unreachable` marked Unreachable +/// ([`mark_unreachable`]). One no longer stored (unlinked while GitHub was asked) is left +/// out, so nothing is stored that nothing references. Returns those that changed. +pub fn refresh( + conn: &mut Connection, + found: &[RemoteRepository], + unreachable: &[RepositoryId], +) -> Result, DbError> { + let tx = conn.transaction()?; + let mut changed = Vec::new(); + for repository in found { + if is_known(&tx, repository.id)? && store(&tx, repository)? { + changed.push(repository.id); + } + } + for id in unreachable { + if mark_unreachable(&tx, *id)? { + changed.push(*id); + } + } + tx.commit()?; + Ok(changed) +} + +/// Every Repository a Workspace links, archived Workspaces' included, by id. +pub fn linked(conn: &Connection) -> Result, DbError> { + let mut stmt = conn.prepare("SELECT DISTINCT repository_id FROM links ORDER BY 1")?; + let rows = stmt.query_map([], |row| row.get::<_, u64>(0))?; + Ok(rows + .map(|id| id.map(RepositoryId::from)) + .collect::>()?) +} + /// What [`link`] and [`store_and_link`] did. #[derive(Debug)] pub struct Linked { diff --git a/crates/agentdeckd/src/prsync/github.rs b/crates/agentdeckd/src/prsync/github.rs index 03dec31..c17061f 100644 --- a/crates/agentdeckd/src/prsync/github.rs +++ b/crates/agentdeckd/src/prsync/github.rs @@ -304,6 +304,73 @@ impl Github { Ok(Some(repository.into())) } + /// Each Repository of `ids` by GitHub's id, in order, read with the REST API's + /// `GET /repositories/{id}`, [`BATCHES_IN_FLIGHT`] requests at once: its name, URL, + /// private and archived as GitHub gives them now, through any rename or transfer. `None` + /// for one GitHub doesn't show to `token` ([`Github::repository_by_id`]). + pub async fn repositories_by_id( + &self, + token: &str, + ids: &[RepositoryId], + ) -> Result>, GithubError> { + use futures_util::{StreamExt as _, TryStreamExt as _}; + + let reads = (ids.iter().copied()).map(|id| self.repository_by_id(token, id)); + futures_util::stream::iter(reads) + .buffered(BATCHES_IN_FLIGHT) + .try_collect() + .await + } + + /// Repository `id` by GitHub's id, read with the REST API's `GET /repositories/{id}`; + /// `None` when GitHub doesn't show it to `token`: a 404 (deleted, or no access), a 451 + /// (blocked), or a 403 that isn't a rate limit (an organisation's SSO or OAuth app + /// restrictions). GraphQL has no lookup by this id, so this is a REST call. Tried again + /// after each of `RETRY_WAITS` while it fails for a reason that may pass. + pub async fn repository_by_id( + &self, + token: &str, + id: RepositoryId, + ) -> Result, GithubError> { + retrying(GithubError::may_pass, || { + self.repository_by_id_once(token, id) + }) + .await + } + + /// [`Github::repository_by_id`], once. + async fn repository_by_id_once( + &self, + token: &str, + id: RepositoryId, + ) -> Result, GithubError> { + let url = format!("{}/repositories/{id}", self.rest); + let response = self + .http + .get(url) + .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 hidden(status, response.headers()) { + return Ok(None); + } + if !status.is_success() { + let body = response.text().await.unwrap_or_default(); + return Err(GithubError::Status { + status: status.as_u16(), + message: message(&body), + }); + } + let repository: RestRepository = response.json().await?; + 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 @@ -668,6 +735,23 @@ fn last_page(header: &str) -> Option { }) } +/// Whether a REST answer `status` with `headers` says GitHub doesn't show the token a +/// Repository: 404 (none, or no access), 451 (blocked for legal reasons), or a 403 that isn't +/// a rate limit, as an organisation's SAML SSO or OAuth app restrictions answer. A rate-limited +/// 403 says so with `x-ratelimit-remaining: 0` or `retry-after`, and is a failure. +fn hidden(status: reqwest::StatusCode, headers: &reqwest::header::HeaderMap) -> bool { + use reqwest::StatusCode; + match status { + StatusCode::NOT_FOUND | StatusCode::UNAVAILABLE_FOR_LEGAL_REASONS => true, + StatusCode::FORBIDDEN => { + let exhausted = (headers.get("x-ratelimit-remaining")) + .is_some_and(|remaining| remaining.as_bytes() == b"0"); + !exhausted && !headers.contains_key(reqwest::header::RETRY_AFTER) + } + _ => false, + } +} + /// A Repository as the REST API's `GET /repos/{owner}/{repo}` and `GET /user/repos` answer it. #[derive(Deserialize)] struct RestRepository { @@ -1356,6 +1440,57 @@ mod tests { } } + mod hidden { + use super::*; + use reqwest::StatusCode; + use reqwest::header::{HeaderMap, HeaderValue}; + + fn headers(pairs: &[(&'static str, &'static str)]) -> HeaderMap { + let mut headers = HeaderMap::new(); + for (name, value) in pairs { + headers.insert(*name, HeaderValue::from_static(value)); + } + headers + } + + #[test] + fn should_be_hidden_when_github_finds_none_or_blocks_it() { + for status in [ + StatusCode::NOT_FOUND, + StatusCode::UNAVAILABLE_FOR_LEGAL_REASONS, + ] { + assert!(hidden(status, &HeaderMap::new()), "{status}"); + } + } + + #[test] + fn should_be_hidden_when_an_organisation_refuses_the_token() { + let sso = headers(&[("x-ratelimit-remaining", "4999")]); + + assert!(hidden(StatusCode::FORBIDDEN, &sso)); + } + + #[test] + fn should_not_be_hidden_when_a_403_is_a_rate_limit() { + let primary = headers(&[("x-ratelimit-remaining", "0")]); + let secondary = headers(&[("retry-after", "60")]); + + assert!(!hidden(StatusCode::FORBIDDEN, &primary)); + assert!(!hidden(StatusCode::FORBIDDEN, &secondary)); + } + + #[test] + fn should_not_be_hidden_when_github_answers_or_fails() { + for status in [ + StatusCode::OK, + StatusCode::TOO_MANY_REQUESTS, + StatusCode::BAD_GATEWAY, + ] { + assert!(!hidden(status, &HeaderMap::new()), "{status}"); + } + } + } + mod parse_scopes { use super::*; diff --git a/crates/agentdeckd/src/prsync/mod.rs b/crates/agentdeckd/src/prsync/mod.rs index ce58f12..e2dfaac 100644 --- a/crates/agentdeckd/src/prsync/mod.rs +++ b/crates/agentdeckd/src/prsync/mod.rs @@ -33,18 +33,25 @@ //! A stored PR GitHub doesn't show to the token, fetched by number, is marked unreachable: it //! keeps its state, and the next full sync fetches it again. //! +//! A full sync also reads Repositories by GitHub's id (REST `GET /repositories/{id}`, as +//! GraphQL has no lookup by that id): each one with a PR that a fetch by its last known name +//! didn't find, so a rename whose old name another Repository took is followed, and every +//! linked one no PR showed, so a Link follows a rename too. One GitHub doesn't show is marked +//! Unreachable, keeping its Links; GitHub showing it again, by id or with a PR, clears that. +//! //! One sync runs at a time: the timer and `POST /v1/prs/sync` queue behind each other. //! Closing PRs (`POST /v1/prs/close`) queues behind them too, so a sync that read a PR as //! open before the close never stores it open again after. pub mod github; +use std::collections::BTreeSet; use std::hash::{DefaultHasher, Hash, Hasher}; use std::sync::{Arc, Mutex, MutexGuard}; use std::time::Duration; use agentdeck_core::ws::Entity; -use agentdeck_core::{ChecksState, PrRef, PrState, ReviewState, Yours}; +use agentdeck_core::{ChecksState, PrRef, PrState, RepositoryId, ReviewState, Yours}; use chrono::{DateTime, SecondsFormat, Utc}; use tokio::time::MissedTickBehavior; @@ -548,9 +555,10 @@ impl PrSync { /// whole: new ones, ones GitHub updated since they were stored, and [`unsettled`] ones. /// /// Then the PRs stored as open that no list or search showed are fetched by number, so a - /// merge, a close or a PR no longer yours is seen; one GitHub doesn't show to the token is - /// marked unreachable, keeping its state. One last updated before `cutoff` isn't fetched: - /// it is Finished, unless it is unreachable. + /// merge, a close or a PR no longer yours is seen ([`PrSync::fetch_left`]); one GitHub + /// doesn't show to the token is marked unreachable, keeping its state. One last updated + /// before `cutoff` isn't fetched: it is Finished, unless it is unreachable. Last, every + /// linked Repository GitHub showed nothing of is read by id ([`PrSync::read_linked`]). async fn read_full(&self, token: &str, cutoff: Option>) -> Result<(), SyncError> { let github = &self.inner.github; let stored = self @@ -627,8 +635,111 @@ impl PrSync { .partition(|pr| older_than(&pr.updated_at, cutoff)); self.finish_aged(aged.iter().map(RemotePr::key).collect()) .await?; - let left = self.fetch(token, &left).await?; - self.store(left.found, left.missing).await + // The Repositories this sync has read: GitHub showed them with a PR in the list or a + // search (the details fetched are theirs), then with a PR fetched, or was asked by id. + let mut read: BTreeSet = + (tally.seen.iter()).map(|pr| pr.repository).collect(); + let left = self.fetch_left(token, &left, &mut read).await?; + self.store(left.found, left.missing).await?; + self.read_linked(token, &read).await + } + + /// Fetches `left`, stored open PRs that no list or search showed, by number under the + /// name each one's Repository last went by. Then reads by GitHub's id each Repository + /// that GitHub showed no PR of, here or in `read`, and that has a PR it didn't show as + /// asked (none, or another Repository's: its name was taken after a rename agentdeck + /// hadn't seen). One GitHub shows under a new name is stored so, and those PRs are fetched + /// again under it; one it doesn't show is marked Unreachable, and they are missing. Adds + /// every Repository GitHub showed, or was asked about by id, to `read`. + async fn fetch_left( + &self, + token: &str, + left: &[RemotePr], + read: &mut BTreeSet, + ) -> Result { + let mut fetched = self.fetch(token, left).await?; + read.extend(fetched.found.iter().map(|pr| pr.repository.id)); + let unread: BTreeSet = (fetched.missing.iter()) + .map(|pr| pr.repository) + .filter(|id| !read.contains(id)) + .collect(); + if unread.is_empty() { + return Ok(fetched); + } + let now = self.read_by_id(token, unread, read).await?; + let again: Vec = (left.iter()) + .filter(|pr| fetched.missing.contains(&pr.key())) + .filter_map(|pr| { + let now = now.iter().find(|r| r.id == pr.repository.id)?; + let renamed = + !(now.name.to_string()).eq_ignore_ascii_case(&pr.repository.name.to_string()); + renamed.then(|| RemotePr { + repository: now.clone(), + ..pr.clone() + }) + }) + .collect(); + if again.is_empty() { + return Ok(fetched); + } + let refetched = self.fetch(token, &again).await?; + fetched + .missing + .retain(|key| !again.iter().any(|pr| pr.key() == *key)); + fetched.found.extend(refetched.found); + fetched.missing.extend(refetched.missing); + Ok(fetched) + } + + /// Reads by GitHub's id every Repository a Workspace links that this full sync hasn't read + /// (`read`), so a linked Repository with no PR GitHub showed still follows a rename, + /// a lost access (Unreachable, its Links kept) and a regained one (spec §8). + async fn read_linked( + &self, + token: &str, + read: &BTreeSet, + ) -> Result<(), SyncError> { + let linked = (self.inner.db) + .call(|conn| db::repositories::linked(conn)) + .await?; + let unread: BTreeSet = (linked.into_iter()) + .filter(|id| !read.contains(id)) + .collect(); + if !unread.is_empty() { + self.read_by_id(token, unread, &mut BTreeSet::new()).await?; + } + Ok(()) + } + + /// Reads each of `ids` by GitHub's id and stores what GitHub says: its name, URL, private + /// and archived now, or, for one it doesn't show, the Unreachable mark; tells clients which + /// changed. Adds every one of `ids` to `read`, so none is asked about twice in a sync, and + /// returns those GitHub showed. + async fn read_by_id( + &self, + token: &str, + ids: BTreeSet, + read: &mut BTreeSet, + ) -> Result, SyncError> { + let ids: Vec = ids.into_iter().collect(); + let answers = self.inner.github.repositories_by_id(token, &ids).await?; + let mut found = Vec::new(); + let mut unreachable = Vec::new(); + for (id, answer) in ids.into_iter().zip(answers) { + read.insert(id); + match answer { + Some(repository) => found.push(repository), + None => unreachable.push(id), + } + } + let stored = found.clone(); + let changed = (self.inner.db) + .call(move |conn| db::repositories::refresh(conn, &stored, &unreachable)) + .await?; + for repository in changed { + self.inner.events.changed(Entity::Repository, repository); + } + Ok(found) } /// An incremental read: a search for each way a PR is yours ([`Whose`]) for the PRs diff --git a/crates/agentdeckd/tests/integration/prs.rs b/crates/agentdeckd/tests/integration/prs.rs index e24352a..a40f399 100644 --- a/crates/agentdeckd/tests/integration/prs.rs +++ b/crates/agentdeckd/tests/integration/prs.rs @@ -2717,3 +2717,250 @@ mod yours { } } } + +/// Repositories read by GitHub's id (spec §8): at each full sync, every linked Repository no +/// PR showed, so a rename, lost access (Unreachable) or regained access shows without a PR to +/// carry it; and the Repository of a PR that left the list and that a fetch by its last known +/// name didn't find, so a renamed Repository's PR is fetched under its name now. +mod repositories_by_id { + use super::*; + use crate::support::github::{ + RestRepo, mock_rest_repo, mock_rest_repo_by_id, mock_rest_repo_by_id_missing, + }; + use agentdeck_client::types::RepositoryLinks; + use agentdeck_core::WorkspaceId; + + const WIDGETS: &str = "acme/widgets"; + + /// GitHub's id for `acme/widgets`, which keeps it through a rename. + fn widgets_id() -> u64 { + repository_id(WIDGETS) + } + + /// `acme/widgets` as GitHub shows it by id once renamed to `name`. + fn widgets_named(name: &'static str) -> RestRepo { + RestRepo { + id: widgets_id(), + ..RestRepo::new(name) + } + } + + /// A daemon whose every sync is full, on a GitHub showing no PR, with a Workspace `web` + /// linking `acme/widgets`, which has none. + async fn linked(github: &MockServer) -> (TestDaemon, WorkspaceId) { + mock_search(github, TOKEN, &[]); + let daemon = full_daemon(github, Some(TOKEN)).await; + let web = link(&daemon.client, github).await; + (daemon, web) + } + + /// Creates Workspace `web` and links it to `acme/widgets`, which GitHub finds by name. + async fn link(client: &Client, github: &MockServer) -> WorkspaceId { + let mut lookup = mock_rest_repo(github, TOKEN, WIDGETS, RestRepo::new(WIDGETS)); + let web = (client.workspace_create()) + .body(NewWorkspace { + name: "web".into(), + link: Vec::new(), + }) + .send() + .await + .expect("create a workspace") + .into_inner(); + let response = (client.link_create()) + .id(web.id) + .body(NewLink::named(WIDGETS.parse().expect("a Repository"))) + .send() + .await + .expect("link"); + assert_eq!(response.status().as_u16(), 200); + lookup.delete(); + web.id + } + + /// Every Repository agentdeck keeps, as `GET /v1/repositories` lists them. + async fn repositories(client: &Client) -> Vec { + let response = client.repository_list().send().await; + response.expect("list Repositories").into_inner() + } + + /// `repo`, as `GET /v1/repositories` lists it, linked by `web`. + fn listed(repo: RestRepo, unreachable: bool, web: WorkspaceId) -> RepositoryLinks { + RepositoryLinks { + id: RepositoryId::from(repo.id), + name: repo.name.parse().unwrap(), + url: repo.url(), + private: repo.private, + archived: false, + unreachable, + workspaces: vec![web], + } + } + + #[tokio::test] + async fn should_follow_a_rename_of_a_linked_repository_with_no_prs_and_keep_its_link_200() { + let github = MockServer::start_async().await; + let (daemon, web) = linked(&github).await; + mock_rest_repo_by_id(&github, TOKEN, widgets_id(), widgets_named("acme/gizmos")); + + let status = sync(&daemon.client).await; + + assert_eq!(status.last_error, None); + assert_eq!( + repositories(&daemon.client).await, + [listed(widgets_named("acme/gizmos"), false, web)] + ); + } + + #[tokio::test] + async fn should_mark_a_linked_repository_github_no_longer_shows_unreachable_and_keep_its_link_200() + { + let github = MockServer::start_async().await; + let (daemon, web) = linked(&github).await; + mock_rest_repo_by_id_missing(&github, widgets_id()); + + let status = sync(&daemon.client).await; + + assert_eq!(status.last_error, None); + assert_eq!( + repositories(&daemon.client).await, + [listed(RestRepo::new(WIDGETS), true, web)] + ); + } + + #[tokio::test] + async fn should_clear_the_mark_once_github_shows_it_again_200() { + let github = MockServer::start_async().await; + let (daemon, web) = linked(&github).await; + let mut missing = mock_rest_repo_by_id_missing(&github, widgets_id()); + sync(&daemon.client).await; + assert!(repositories(&daemon.client).await[0].unreachable); + + missing.delete(); + mock_rest_repo_by_id(&github, TOKEN, widgets_id(), RestRepo::new(WIDGETS)); + sync(&daemon.client).await; + + assert_eq!( + repositories(&daemon.client).await, + [listed(RestRepo::new(WIDGETS), false, web)] + ); + } + + #[tokio::test] + async fn should_tell_websocket_clients_a_repository_became_unreachable_200() { + let github = MockServer::start_async().await; + let (daemon, _web) = linked(&github).await; + let mut ws = Ws::connect(&daemon).await; + mock_rest_repo_by_id_missing(&github, widgets_id()); + + sync(&daemon.client).await; + + let changed = ws + .until(|frame| match frame { + Frame::Message(ServerMessage::Changed { + entity: Entity::Repository, + id, + }) => Some(id), + _ => None, + }) + .await; + assert_eq!(changed, widgets_id().to_string()); + } + + #[tokio::test] + async fn should_not_read_a_repository_by_id_while_github_shows_it_with_a_pr_200() { + let github = MockServer::start_async().await; + let mut listing = mock_search(&github, TOKEN, &[Pr::open(7)]); + let daemon = full_daemon(&github, Some(TOKEN)).await; + sync(&daemon.client).await; + link(&daemon.client, &github).await; + let by_id = mock_rest_repo_by_id(&github, TOKEN, widgets_id(), RestRepo::new(WIDGETS)); + // Listed, then merged and fetched by number: both show its Repository. + sync(&daemon.client).await; + listing.delete(); + mock_search(&github, TOKEN, &[]); + mock_fetch( + &github, + &[Pr { + state: "MERGED", + ..Pr::open(7) + }], + ); + + sync(&daemon.client).await; + + by_id.assert_calls(0); + } + + #[tokio::test] + async fn should_mark_the_repository_of_a_pr_github_no_longer_shows_unreachable_with_it_200() { + let github = MockServer::start_async().await; + let mut listing = mock_search(&github, TOKEN, &[Pr::open(7)]); + let daemon = full_daemon(&github, Some(TOKEN)).await; + sync(&daemon.client).await; + link(&daemon.client, &github).await; + + listing.delete(); + mock_search(&github, TOKEN, &[]); + mock_hidden(&github, TOKEN, &Pr::open(7)); + let by_id = mock_rest_repo_by_id_missing(&github, widgets_id()); + sync(&daemon.client).await; + + let pr = pr_numbered(&daemon.client, 7).await; + assert!(pr.unreachable); + assert_eq!(pr.state, PrState::Open); + let repositories = repositories(&daemon.client).await; + assert_eq!(names_and_marks(&repositories), [(WIDGETS.to_owned(), true)]); + // Read once: as its PR's Repository, not again as a linked one. + by_id.assert_calls(1); + } + + /// Each Repository's name and whether it is Unreachable. + fn names_and_marks(repositories: &[RepositoryLinks]) -> Vec<(String, bool)> { + (repositories.iter()) + .map(|r| (r.name.to_string(), r.unreachable)) + .collect() + } + + /// #390: `acme/widgets` renamed to `acme/gizmos`, another Repository then created as + /// `acme/widgets` with a PR 7 of its own, and the renamed one's PR 7 merged before any + /// sync saw the rename. Fetched by its last known name, GitHub answers with the newcomer's + /// PR; read by id, its Repository's name now finds it. + #[tokio::test] + async fn should_fetch_a_pr_under_its_repositorys_name_now_when_another_took_the_old_one_200() { + let github = MockServer::start_async().await; + let mut listing = mock_search(&github, TOKEN, &[Pr::open(7)]); + let daemon = full_daemon(&github, Some(TOKEN)).await; + sync(&daemon.client).await; + let newcomer = Pr { + repo_id: Some(repository_id("acme/widgets, the second")), + title: "Start over", + ..Pr::open(7) + }; + let merged = Pr { + repo: "acme/gizmos", + repo_id: Some(widgets_id()), + state: "MERGED", + ..Pr::open(7) + }; + + listing.delete(); + mock_search(&github, TOKEN, &[]); + mock_fetch(&github, &[newcomer]); + mock_rest_repo_by_id(&github, TOKEN, widgets_id(), widgets_named("acme/gizmos")); + mock_fetch(&github, &[merged]); + let status = sync(&daemon.client).await; + + assert_eq!(status.last_error, None); + let prs = kept_prs(&daemon.client).await; + assert_eq!(prs.len(), 1, "{prs:?}"); + assert_eq!(prs[0].reference.to_string(), "acme/gizmos#7"); + assert_eq!(prs[0].repository.id, RepositoryId::from(widgets_id())); + assert_eq!(prs[0].state, PrState::Merged); + assert!(prs[0].finished); + assert!(!prs[0].unreachable); + assert_eq!( + names_and_marks(&repositories(&daemon.client).await), + [("acme/gizmos".to_owned(), false)] + ); + } +} diff --git a/crates/agentdeckd/tests/integration/support/github.rs b/crates/agentdeckd/tests/integration/support/github.rs index cd50d48..9edf4ec 100644 --- a/crates/agentdeckd/tests/integration/support/github.rs +++ b/crates/agentdeckd/tests/integration/support/github.rs @@ -88,6 +88,45 @@ pub fn mock_rest_repo_missing<'a>(server: &'a MockServer, asked: &str) -> Mock<' }) } +/// `GET /repositories/{id}` for GitHub's id `id` with `token`, answered with `repo` as GitHub +/// calls it now: the same name, or a new one after a rename or a transfer. +pub fn mock_rest_repo_by_id<'a>( + server: &'a MockServer, + token: &str, + id: u64, + repo: RestRepo, +) -> Mock<'a> { + server.mock(|when, then| { + when.method(GET) + .path(format!("/repositories/{id}")) + .header("authorization", format!("Bearer {token}")) + .header("x-github-api-version", "2022-11-28"); + then.status(200).json_body(json!({ + "id": id, + "node_id": "R_kgDOtest", + "name": repo.name.split_once('/').expect("owner/name").1, + "full_name": repo.name, + "html_url": repo.url(), + "private": repo.private, + "archived": false, + "default_branch": "main" + })); + }) +} + +/// `GET /repositories/{id}` for GitHub's id `id`, answered 404 as GitHub answers for a +/// Repository deleted, or one the token can no longer see. +pub fn mock_rest_repo_by_id_missing(server: &MockServer, id: u64) -> Mock<'_> { + server.mock(|when, then| { + when.method(GET).path(format!("/repositories/{id}")); + then.status(404).json_body(json!({ + "message": "Not Found", + "documentation_url": "https://docs.github.com/rest", + "status": "404" + })); + }) +} + /// `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 { diff --git a/docs/spec.md b/docs/spec.md index bc1927b..40ce61d 100644 --- a/docs/spec.md +++ b/docs/spec.md @@ -115,7 +115,7 @@ A pane's **current folder** is where it works now (§6): `cwd` stays the folder An agent pane runs its agent only until its process exits. An exited agent pane keeps `kind` and `agent`, so it can be restarted (`POST /v1/panes/{id}/respawn`, §4). An agent pane that comes back as a shell (§6), or that the user turns into one, **becomes a shell pane**: `kind` `shell`, `agent` and `session_id` NULL, `argv` the shell. It keeps its `cwd`. -A **Repository** is a GitHub repository a Workspace links or a kept PR belongs to, named for good by GitHub's id: a rename or a transfer changes its `full_name` and `url`, never which Repository it is, so its PRs and every Link follow its name (§8). It holds only what GitHub says of it, and `unreachable_at` (nothing sets it yet; the sync of linked Repositories that will is tracked in [#362](https://github.com/bRRRITSCOLD/agentdeck/issues/362)). +A **Repository** is a GitHub repository a Workspace links or a kept PR belongs to, named for good by GitHub's id: a rename or a transfer changes its `full_name` and `url`, never which Repository it is, so its PRs and every Link follow its name (§8). It holds only what GitHub says of it, and `unreachable_at`, set while GitHub doesn't show it to the sign-in and cleared once GitHub shows it again (§8). An Unreachable Repository keeps its Links and its PRs. A **Pull request** row is named by its Repository's id and its number, and has no name of its own: it is listed under its Repository's `full_name` now. Nothing is unique on the name, so a renamed Repository's PRs and those of another Repository that took its old name are different rows, even before PR sync has seen the rename. It is one you authored, one where your review is requested, or one assigned to you, and stores which of these it is, any of them at once (`authored`, `review_requested`, `assigned`), as GitHub last showed it (§8). Only those you authored alert (§11). @@ -336,12 +336,13 @@ min_ms = 400 # a new state must hold this long before it is pu - **Incremental:** the rest search once for each way a PR is yours, `is:pr author:@me updated:>=`, `is:pr user-review-requested:@me updated:>=` and `is:pr assignee:@me updated:>=`, where `T` is 10 minutes before the last good sync began, so a merged or closed PR comes back in its new state and a review newly requested of you or a new assignment comes in. A merged or closed PR not stored as open is skipped, and so is any PR updated before the cutoff. Then the open PRs the searches left out that are unsettled or yours only as a reviewer or an assignee (below), updated within the cutoff, are fetched by number; Finished and unreachable PRs are left out. Nothing is found unreachable. - **Unsettled:** a PR whose checks are `pending` or none (none had started when it was stored), or whose review is `review_required` or `changes_requested`. A check run finishing doesn't update a PR, so the search misses it. A submitted review does update it, to the second (checked on public PRs, #247), so a change requested on an `approved` PR comes back in the search. No review decision means the repo requires none, and `approved` waits on nobody. - **Yours only as a reviewer or an assignee:** submitting your review takes you out of its review requests, and unassigning you out of its assignees, so the PR leaves the searches that found it, and only a fetch by number sees it is no longer yours. Each incremental sync fetches these, as it does the unsettled ones; most PRs waiting on your review are `review_required` and so unsettled anyway. - - **What a sync costs:** an incremental sync is 3 searches (one request each, and one more per further 50 PRs updated since `T`), then one request per 25 PRs that are unsettled or yours only as a reviewer or an assignee, 4 at a time: 4 requests with a few such PRs, where it was 2 while only the PRs you authored synced. A full sync is one request per 100 PRs you authored, one per 50 open PRs where your review is requested and one per 50 assigned to you, then one per 25 PRs it fetches by number. By GitHub's rate-limit formula (each connection's possible nodes, over 100), a list or search page costs 2 points and a fetch by number 1, so 30 syncs an hour, one of them full, come to about 210 points out of the 5,000 an hour GitHub allows. + - **What a sync costs:** an incremental sync is 3 searches (one request each, and one more per further 50 PRs updated since `T`), then one request per 25 PRs that are unsettled or yours only as a reviewer or an assignee, 4 at a time: 4 requests with a few such PRs, where it was 2 while only the PRs you authored synced. A full sync is one request per 100 PRs you authored, one per 50 open PRs where your review is requested and one per 50 assigned to you, then one per 25 PRs it fetches by number. By GitHub's rate-limit formula (each connection's possible nodes, over 100), a list or search page costs 2 points and a fetch by number 1, so 30 syncs an hour, one of them full, come to about 210 points out of the 5,000 an hour GitHub allows. A full sync also makes one REST request per Repository it reads by id (below): each linked Repository GitHub showed no PR of, and each Repository with a PR that left the list and wasn't found under its last known name; 4 at a time. REST requests count against REST's own 5,000 an hour, not GraphQL's points, so ten such Repositories cost 10 REST requests an hour and no points. An incremental sync reads none. - `POST /v1/prs/sync` answers once its sync finishes, with the same body as `GET /v1/prs/status`: `{ login: "logged_in"|"logged_out", last_synced_at, last_error, progress, max_age_days, synced_as? }`. `max_age_days` is the age cutoff the next sync uses (`0` for none), so clients never read `config.toml` themselves. `synced_as` is the login GitHub gave for the token of the last good sync, stored in `pr_sync`, so it outlasts a sign-out and a restart: the logged-out banner says whose PRs show (§11). Signing out changes no stored PR. A failed sync is still 200, with `last_error` set: `GitHub answered `, plus GitHub's `message` when the body is JSON. A request that fails with a 5xx or in transit is tried up to 3 times, 1 s then 2 s apart. One that fails in transit says why: "GitHub didn't answer in time", "couldn't connect to GitHub", "couldn't read GitHub's response" or "calling GitHub failed", then the URL without credentials, query or fragment, then the causes reqwest gives (`operation timed out`, `tcp connect error: Connection refused (os error 111)`, a DNS or TLS error), e.g. `GitHub didn't answer in time (https://api.github.com/graphql): operation timed out`. A close's `error` reads the same. -- **Repository:** every read of a PR, the list's light fields included, takes its repository's GitHub id (`fullDatabaseId`), `owner/name`, URL, private and archived, its base branch (`baseRefName`), its author's login (`author`, null once the account is gone), and why it is yours (above). Each Repository is stored by its id (§3): one PR sync hasn't seen is created, and a new `owner/name`, URL, private or archived for a known id updates it, so a rename or a transfer keeps the Repository and its PRs. A stored PR is found by its Repository's id and number (§3), so GitHub showing it under a new name updates its row rather than making a new one, and another Repository that took the old name has PRs of its own, however the two are listed. Each Repository created or changed sends `changed` `repository` (§5) once per store. The full sync's PRs that "left the list" (those neither the list nor either search showed) are worked out by Repository id and number after the list and searches are stored, so a renamed Repository's PR, listed under its new name, hasn't left it; the incremental sync keeps a merged or closed PR it finds when its Repository's id and number are stored open. A fetch by number asks by the name the Repository last went by; one GitHub answers with another Repository's PR (the name was taken by another before PR sync saw the rename) counts as not shown. A PR GitHub gives no Repository id for (`fullDatabaseId` null) can't be stored and is left out. +- **Repository:** every read of a PR, the list's light fields included, takes its repository's GitHub id (`fullDatabaseId`), `owner/name`, URL, private and archived, its base branch (`baseRefName`), its author's login (`author`, null once the account is gone), and why it is yours (above). Each Repository is stored by its id (§3): one PR sync hasn't seen is created, and a new `owner/name`, URL, private or archived for a known id updates it, so a rename or a transfer keeps the Repository and its PRs. A stored PR is found by its Repository's id and number (§3), so GitHub showing it under a new name updates its row rather than making a new one, and another Repository that took the old name has PRs of its own, however the two are listed. Each Repository created or changed sends `changed` `repository` (§5) once per store. The full sync's PRs that "left the list" (those neither the list nor either search showed) are worked out by Repository id and number after the list and searches are stored, so a renamed Repository's PR, listed under its new name, hasn't left it; the incremental sync keeps a merged or closed PR it finds when its Repository's id and number are stored open. A fetch by number asks by the name the Repository last went by; one GitHub answers with another Repository's PR (the name was taken by another before PR sync saw the rename) counts as not shown, and so does one it doesn't answer. In a full sync, the Repository of a PR not shown is then read by id (below), unless GitHub showed another PR of it in this sync: when GitHub calls it by another name now, it is stored so and those PRs are fetched again under that name, so a renamed Repository whose old name another took still has its PRs read, merged or closed ones included; when GitHub doesn't show it, the Repository is marked Unreachable and its PRs are too. A PR GitHub gives no Repository id for (`fullDatabaseId` null) can't be stored and is left out. +- **Repositories read by id:** GraphQL has no lookup by a Repository's id, so a full sync reads one with REST `GET /repositories/{id}`, with the token and headers a lookup uses (below), the same timeout, retries and wording, reading `id`, `full_name`, `html_url`, `private` and `archived`. After the PRs that left the list are fetched, it reads every Repository a Workspace links (archived Workspaces' included) that no PR GitHub showed in this sync belongs to and that it hasn't read already, so a Link with no PR to carry it follows a rename or a transfer, a lost access and a regained one. GitHub's answer updates the Repository's name, URL, private and archived, as a PR's read does. A 404 (deleted, or no access), a 451 (blocked) or a 403 that isn't a rate limit (no `x-ratelimit-remaining: 0`, no `retry-after`: an organisation's SSO or OAuth app restrictions) means GitHub doesn't show it: it is marked **Unreachable** (`unreachable_at` set), keeping its Links, its PRs and what GitHub last said of it. GitHub showing it again, by id or with any PR, clears the mark. Each Repository that changes or is marked sends `changed` `repository` (§5). A Repository unlinked while GitHub was asked isn't stored again. A 401 is the token's, as for any request; any other failure fails the sync. - Each result is kept as a **Pull request**, with its title and every field above; nothing else is made of it. agentdeck no longer files PRs under Workspaces itself: a Workspace's Pull requests are those of the Repositories it links (§3, §4). - **New, merged, closed, reopened, no longer yours:** the PR is stored as GitHub shows it. In a full sync, PRs that left the list are fetched by number, once, so one merged, closed or no longer yours (your review submitted, you unassigned) since is seen. Fetches by number go 25 to a request, 4 requests at a time. - - **Unreachable:** a PR fetched by number that GitHub doesn't show to the token (no repository or no pull request: not found, or no access, as for a fine-grained token that reaches other repos, or a PR synced under another account) is not stored as closed. It is marked unreachable (`unreachable_at` set, a `changed` event), keeping its state and every field as last synced. It stays stored `open`, so each full sync fetches it again; the incremental sync's unsettled fetches leave it out, and it can't be closed (below). Clients show it dimmed and leave it out of PR counts (§11). Once GitHub shows it again (in the list, a search or a fetch), it is no longer unreachable, and is stored as GitHub shows it. Unreachable PRs get no Finished window: one last updated before the cutoff is not Finished, and none is deleted; it stays, marked, until GitHub shows it again. + - **Unreachable:** a PR fetched by number that GitHub doesn't show to the token (no repository or no pull request: not found, or no access, as for a fine-grained token that reaches other repos, or a PR synced under another account) is not stored as closed. It is marked unreachable (`unreachable_at` set, a `changed` event), keeping its state and every field as last synced. It stays stored `open`, so each full sync fetches it again; the incremental sync's unsettled fetches leave it out, and it can't be closed (below). Clients show it dimmed and leave it out of PR counts (§11). Once GitHub shows it again (in the list, a search or a fetch), it is no longer unreachable, and is stored as GitHub shows it. A PR whose Repository GitHub doesn't show by id (above) is marked with it, without a fetch under the Repository's last known name. Unreachable PRs get no Finished window: one last updated before the cutoff is not Finished, and none is deleted; it stays, marked, until GitHub shows it again. - **Finished:** a kept PR becomes Finished (`finished_at` set to when the sync stored it so) once the sync stores it merged or closed, or open but yours no way at all (no longer its author's, reviewer's or assignee's: `yours` empty), and a PR closed from agentdeck (below) is Finished at once. In a full sync, a reachable PR stored as open that left the list and searches and was last updated before the cutoff is not fetched: it is Finished instead, still `open`, once (a `changed` event); the cutoff counts the same for a PR you authored, review or are assigned. Nothing changes on GitHub. A Finished PR stays Finished from the first time it was, until GitHub shows it open, yours and within the cutoff (in the list, a search or a fetch by number): then it is no longer Finished, and keeps no Finished window from before. - **Leaving:** at the end of each good sync, every PR Finished 7 days ago or more (`AGENTDECK_PR_FINISHED_SECS` replaces the 7 days, `0` for none; tests use it) is deleted (a `changed` `pull_request` event each), unless it is unreachable, and then each of their Repositories that no Link and no kept PR references any more (a `changed` `repository` event each). `GET /v1/prs` leaves Finished PRs out unless asked (§4); clients leave them out of PR counts and show them only under Show finished (§11). - `checks` and `review` come from `statusCheckRollup` (`ERROR` counts as failure, `EXPECTED` as pending) and `reviewDecision`. Every PR in the API carries `unreachable`, true while the GitHub sign-in can't see it (above). @@ -401,7 +402,7 @@ agentdeck tail [--bytes N] - `config` names a setting by its dotted key (§2). `ls` prints each key and value, and `set` the key it set, adding "(an environment variable overrides config.toml)" to an overridden one; with `--json`, both print the settings object. `get` prints the value alone, or `{key, value}` with `--json`; a key that isn't a setting is an error. `set` sends a value that reads as a number, `true` or `false` as that, anything else as text, and the daemon checks it (`invalid_setting`). - Every command except `daemon restart` prints one line to stderr, after `agentdeck: `, when the daemon is older than the CLI (§2), then runs as usual: "warning: agentdeck's background service (agentdeckd) is older than this CLI. Run agentdeck daemon restart to use new features; your agents resume after the restart." - `pr sync` runs a full sync (`?full=true`, §8), as Sync now does. `pr sync` and `pr status` print the status (§8) a line each: `github:` `logged_in` or `logged_out` (whichever source gives the token), `last sync:` its time or `never`, `syncing:` its progress while one runs, and `last error:` while the last one failed. -- `repo ls` lists the Repositories agentdeck keeps with `GET /v1/repositories` (§4), with `--ws` only those that workspace links: a line per Repository under `REPOSITORY WORKSPACES`, its name marked `(unreachable)` while the GitHub sign-in can't see it, then the slugs of the workspaces that link it, oldest first, separated by `, `, an archived one marked `(archived)`, or `-` when none does; "no repositories" when there are none. With `--json` it prints the list of `RepositoryLinks` objects, each with its workspaces' ids. +- `repo ls` lists the Repositories agentdeck keeps with `GET /v1/repositories` (§4), with `--ws` only those that workspace links: a line per Repository under `REPOSITORY WORKSPACES`, its name marked `(unreachable)` while the GitHub sign-in can't see it (a full sync found GitHub no longer shows it, §8; `unreachable: true` in `--json`), then the slugs of the workspaces that link it, oldest first, separated by `, `, an archived one marked `(archived)`, or `-` when none does; "no repositories" when there are none. With `--json` it prints the list of `RepositoryLinks` objects, each with its workspaces' ids. - `repo link` links a Repository to a workspace with `POST /v1/workspaces/{id}/links` (§4): one agentdeck doesn't know is looked up on GitHub first, and one GitHub doesn't show the sign-in is the daemon's `unknown_repository`, "GitHub can't see owner/name. Check the name or your token's access.". It prints `linked to `, the Repository by its name now, or the `RepositoryLinks` with `--json`. - `repo unlink` finds the Repository among those the workspace links (`GET /v1/repositories?workspace=`), by name ignoring case, and unlinks it with `DELETE /v1/workspaces/{id}/links/{repository}`; one the workspace doesn't link is an error, "owner/name isn't linked to (not_found)". agentdeck forgets the Repository when no other workspace links it and none of your PRs belongs to it (§3). It prints `unlinked from `, or `{workspace_id, repository_id, unlinked}` with `--json`. - `repo link` and `repo unlink` need `--ws`, and no `repo` or `pr` command defaults a workspace from `$AGENTDECK_WORKSPACE`, so a command prints the same wherever it runs: an agent passes `--ws "$AGENTDECK_WORKSPACE"` itself. @@ -456,11 +457,11 @@ Built on `brrritscold-core-gpui` (`init`, `Root`, theme preference, toasts). Scr - **Appearance:** Theme, a Select of System / Dark / Light, its trigger as wide as its value and chevron (about 96px for "System"), not the section's 480px, "System follows your desktop's light or dark setting." Picking one applies it at once and saves it with `PATCH /v1/settings`; a failed save puts the saved theme back and toasts why. - **Terminal:** "Open file paths with", an input holding `terminal.file_opener`, "Ctrl+click a file path in a pane to run this. {path} is the file and {line} its line, when the path has one (src/main.rs:42). For example: code -g {path}:{line}". It saves as the days field does: Enter or leaving the field. A blank command ("Enter a command, such as xdg-open {path}."), an unclosed quote ("Close the quote in the command.") or one with no `{path}` ("Pass {path} to the command, as in code -g {path}:{line}.") shows the field's error and isn't saved, as does the daemon's `invalid_setting`. Any other failure toasts why. - **General**, last (Penpot "Settings" → `General`): "Ask before quitting while agents run", a horizontal Field with a Switch holding `gui.confirm_quit`, described "Agents keep running in the background after agentdeck quits. Off, Quit and the close button quit at once." Flipping it shows the new value at once and saves it with `PATCH /v1/settings`; a failed save puts the saved value back and toasts "Couldn't save Ask before quitting" with why. -- **Pull requests view** (Penpot "Screens · Main" → "Pull requests", "· row menu", "· row menu · unreachable PR", "· unreachable PR", "· logged out", "· empty", "· show finished", "· highlighted row", "· select", "· group menu", "· group menu · no workspace to link", "· linked"): every pull request PR sync keeps that is open on GitHub and not Finished, each under its **Repository** (`GET /v1/prs?finished=true`, §4, read with the sidebar's other reads and again on each `changed`), and the Finished ones too while Show finished is on. +- **Pull requests view** (Penpot "Screens · Main" → "Pull requests", "· row menu", "· row menu · unreachable PR", "· unreachable PR", "· logged out", "· empty", "· show finished", "· highlighted row", "· select", "· group menu", "· group menu · no workspace to link", "· linked", "· unreachable repository"): every pull request PR sync keeps that is open on GitHub and not Finished, each under its **Repository** (`GET /v1/prs?finished=true`, §4, read with the sidebar's other reads and again on each `changed`), and the Finished ones too while Show finished is on. - **Header:** "Pull requests" (xl medium) over two sm `muted-foreground` lines with no gap between them: "Your open PRs, by repository." ("Your open and finished PRs, by repository." while Show finished is on), then the age cutoff from `GET /v1/prs/status` (§8): "PRs not updated in the last N days are left out; change that in Settings." ("1 day" for 1), or "Every open PR syncs." for `0`, its "Settings" a link (`primary`, underlined on hover, as core-gpui's link button) that opens Settings at its GitHub section; until the status is read only the first line shows. Then, pushed right, **Select** (Select mode, below), **Show finished** (a Switch and its Label, `space.2` apart), when PRs last synced (sm `muted-foreground`: "Synced 2 min ago", "Syncing… 100 of 271 PRs", "Syncing details…", "Sync failed", "Not synced yet", or "Not signed in" while `logged_out`, a running sync showing first) and an outline **Sync now**, which runs a full sync (§8), reads "Syncing…" until the daemon says more, is disabled until it answers, and has the sidebar read again once it ends, since a sync that changes nothing broadcasts nothing; a failure toasts "Couldn't sync PRs" with why. The heading and description take what the rest leave, the description wrapping, so the header fits the narrowest window (Window, above). - **Logged out** (Penpot "Pull requests · logged out", "· logged out · synced before"): while `GET /v1/prs/status` says `logged_out`, a default alert with the `Info` icon sits between the header and the list, over the empty state too: "Not signed in to GitHub, so PRs don't sync.", or, once a sync ran as a login (`synced_as`, §8), "Synced as . Sign in to refresh.", the stored PRs still listed as last synced, with an **Open Settings** link (as the description's "Settings" link) that opens Settings at its GitHub section. It goes once a token works again. - **Show finished** shows Finished PRs (§8) in their Repositories' groups and counts, and hides them again when turned off. It is remembered across restarts in the GUI state (Window, above). - - **Groups:** one per Repository with a PR to show, by GitHub's Repository id; a Repository with none shows no group. Linked Repositories come first, then those Not in a workspace, each alphabetical by the Repository's name without its owner (ignoring case, then by owner). A group's header is Penpot's `GroupHeader` (a chevron, the name in sm medium, a `secondary` badge counting its PRs) followed, `space.2` after it, by who links it (sm `muted-foreground`): each Workspace linking the Repository by name, in the sidebar's order, " · " between them, each a link (underlined on hover, as a PR's reference) to that Workspace's Pull requests (Workspace view, above); or "Not in a workspace" while none does. Archived Workspaces link nothing (`GET /v1/repositories`, §4): they are absent from the headers and the order, so a Repository linked only by them reads Not in a workspace. Two Repositories with the same name read `owner/name` instead. A click on the `GroupHeader` collapses the group, or opens it, and the collapsed groups are remembered across restarts in the GUI state (Window, above), apart from each Workspace's Pull requests'. Its PRs go by number. + - **Groups:** one per Repository with a PR to show, by GitHub's Repository id; a Repository with none shows no group. Linked Repositories come first, then those Not in a workspace, each alphabetical by the Repository's name without its owner (ignoring case, then by owner). A group's header is Penpot's `GroupHeader` (a chevron, the name in sm medium, a `secondary` badge counting its PRs) followed, `space.2` after it, by who links it (sm `muted-foreground`): each Workspace linking the Repository by name, in the sidebar's order, " · " between them, each a link (underlined on hover, as a PR's reference) to that Workspace's Pull requests (Workspace view, above); or "Not in a workspace" while none does. An **Unreachable** Repository's header (§8, Penpot "Pull requests · unreachable repository") reads "Unreachable: can't sync, PRs may be out of date" in the same style in place of either, truncated with an ellipsis when it doesn't fit; it keeps its place among the linked ones, its group menu and its Links. On a Workspace's Pull requests it reads so too, over "No open PRs" when it has none to show. Archived Workspaces link nothing (`GET /v1/repositories`, §4): they are absent from the headers and the order, so a Repository linked only by them reads Not in a workspace. Two Repositories with the same name read `owner/name` instead. A click on the `GroupHeader` collapses the group, or opens it, and the collapsed groups are remembered across restarts in the GUI state (Window, above), apart from each Workspace's Pull requests'. Its PRs go by number. - **Group menu** (Penpot "Pull requests · group menu", "· group menu · no workspace to link"): each group header ends, pushed right into the rows' `…` column, in a ghost icon-xs `…` opening 4px below it with their right edges lined up, as a row's does: **Open on GitHub**, which opens the Repository's GitHub page (Opening PRs, below; a handler that can't start toasts "Couldn't open the repository"), and **Link to a workspace**, a submenu (opening on the menu's left when the window has no room on its right) of the Workspaces that aren't archived and don't link the Repository, by name in the sidebar's order, then a separator and **New workspace**; with no Workspace to offer, New workspace is its only item. Archived Workspaces are never offered: unarchive one first. A Workspace's Pull requests adds a separator and **Unlink from this workspace** (Workspace's Pull requests, below). - **Linking** applies at once, with no dialog: it links by GitHub's id with the Repository as last read (`POST /v1/workspaces/{id}/links` with `id`, §4), so it never asks GitHub, and toasts "Linked owner/name to " with **Undo**, which unlinks it again (Penpot "Pull requests · linked"). The group's header names the Workspace once the daemon's `changed` is read, and a Repository that was Not in a workspace moves up among the linked ones. A failure toasts "Couldn't link owner/name to " with why. - **New workspace** opens the new workspace dialog (Dialogs, below) with the Repository already picked in its Repositories, staged to link. @@ -560,11 +561,11 @@ 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), why a PR is yours (`why_yours`: its author, review requests and assignees against your login, ignoring case), which open PRs an incremental sync fetches again, 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 you review, are assigned, or both, never alerts), 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 PRs of each kind are tested here too: the ones you authored, those where your review is requested and those assigned to you, and one that is yours several ways at once, each with why it is yours in `GET /v1/prs`, in a full sync (the list and the two open searches) and an incremental one (a search for each), the age cutoff leaving out old ones of each kind in both. Its Finished PRs too: Finished on merge, on close (from GitHub and from agentdeck), past the cutoff and once no longer yours (your review submitted, seen by the incremental sync's fetch by number; you unassigned, seen by a full sync's), an authored PR whose review request goes staying unfinished, no longer Finished once GitHub shows a PR open and yours 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), why a PR is yours (`why_yours`: its author, review requests and assignees against your login, ignoring case), which open PRs an incremental sync fetches again, 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, an Unreachable Repository's header in place of its Workspaces on both views; 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 you review, are assigned, or both, never alerts), 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, `GET /repositories/{id}` for Repositories read by id 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 PRs of each kind are tested here too: the ones you authored, those where your review is requested and those assigned to you, and one that is yours several ways at once, each with why it is yours in `GET /v1/prs`, in a full sync (the list and the two open searches) and an incremental one (a search for each), the age cutoff leaving out old ones of each kind in both. Its Finished PRs too: Finished on merge, on close (from GitHub and from agentdeck), past the cutoff and once no longer yours (your review submitted, seen by the incremental sync's fetch by number; you unassigned, seen by a full sync's), an authored PR whose review request goes staying unfinished, no longer Finished once GitHub shows a PR open and yours 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. Repositories read by id are tested here too: a linked Repository with no PR renamed (its Link kept), lost (Unreachable, its Link kept, a `changed repository`) and regained (the mark cleared), none read while GitHub shows a PR of it, a PR's Repository GitHub doesn't show marked Unreachable with the PR, and a PR merged after its Repository's rename, the old name since taken by another Repository with a PR of the same number, fetched under the new name and Finished, not Unreachable. 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, and why each PR is yours in `--json`), `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 | +| 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, and why each PR is yours in `--json`), `pr close`, `repo ls|link|unlink` (`repo ls` marking a Repository a `pr sync` found Unreachable, in text and `--json`) 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 | | integration | `agentdeck-notify/tests/integration` | the desktop notifier against a fake notification server on a private `dbus-daemon` session bus, the app side (GPUI's headless platform) in a child process: what it sends (the `desktop-entry` hint), one connection and no thread per notification, a click routed by id, a closed notification forgotten, a tag shown again replacing its open notification, a withdrawn, clicked or (on quit) left-open notification closed with `CloseNotification`. The GUI's unit tests stand in a fake `Notifier` for it | There is no e2e tier. GPUI's headless context doesn't advance real sockets, so anything touching sockets is an integration test. CI is Linux only: fmt, clippy, unit, integration and doc, with warnings denied.