diff --git a/crates/agentdeck-client/src/generated.rs b/crates/agentdeck-client/src/generated.rs index 08e6173..478d648 100644 --- a/crates/agentdeck-client/src/generated.rs +++ b/crates/agentdeck-client/src/generated.rs @@ -730,6 +730,9 @@ pub mod types { pub updated_at: ::std::string::String, ///Its GitHub page. pub url: ::std::string::String, + ///Why it is yours, in this order: `authored`, `review_requested` (a review request names you), `assigned`; empty once it is none of these, when it is Finished (spec §8). Absent from an older daemon, which read only the PRs you authored. + #[serde(default, skip_serializing_if = "::std::vec::Vec::is_empty")] + pub yours: ::std::vec::Vec, } impl PullRequest { pub fn builder() -> builder::PullRequest { @@ -2887,6 +2890,10 @@ pub mod types { unreachable: ::std::result::Result, updated_at: ::std::result::Result<::std::string::String, ::std::string::String>, url: ::std::result::Result<::std::string::String, ::std::string::String>, + yours: ::std::result::Result< + ::std::vec::Vec, + ::std::string::String, + >, } impl ::std::default::Default for PullRequest { fn default() -> Self { @@ -2906,6 +2913,7 @@ pub mod types { unreachable: Err("no value supplied for unreachable".to_string()), updated_at: Err("no value supplied for updated_at".to_string()), url: Err("no value supplied for url".to_string()), + yours: Ok(Default::default()), } } } @@ -3060,6 +3068,16 @@ pub mod types { .map_err(|e| format!("error converting supplied value for url: {e}")); self } + pub fn yours(mut self, value: T) -> Self + where + T: ::std::convert::TryInto<::std::vec::Vec>, + T::Error: ::std::fmt::Display, + { + self.yours = value + .try_into() + .map_err(|e| format!("error converting supplied value for yours: {e}")); + self + } } impl ::std::convert::TryFrom for super::PullRequest { type Error = super::error::ConversionError; @@ -3082,6 +3100,7 @@ pub mod types { unreachable: value.unreachable?, updated_at: value.updated_at?, url: value.url?, + yours: value.yours?, }) } } @@ -3103,6 +3122,7 @@ pub mod types { unreachable: Ok(value.unreachable), updated_at: Ok(value.updated_at), url: Ok(value.url), + yours: Ok(value.yours), } } } diff --git a/crates/agentdeck-core/src/daemon.rs b/crates/agentdeck-core/src/daemon.rs index 662fcd0..530a5d2 100644 --- a/crates/agentdeck-core/src/daemon.rs +++ b/crates/agentdeck-core/src/daemon.rs @@ -13,7 +13,7 @@ use serde::{Deserialize, Serialize}; /// fails when `openapi.json` changes without a bump. /// /// `0` is every daemon from before it existed, whose `daemon.json` has no `api_version`. -pub const API_VERSION: u32 = 27; +pub const API_VERSION: u32 = 28; /// What `$XDG_RUNTIME_DIR/agentdeck/daemon.json` holds. The daemon writes it once it serves; /// the GUI and the CLI read it to reach the daemon. diff --git a/crates/agentdeck-core/src/lib.rs b/crates/agentdeck-core/src/lib.rs index d661663..f160d67 100644 --- a/crates/agentdeck-core/src/lib.rs +++ b/crates/agentdeck-core/src/lib.rs @@ -32,7 +32,9 @@ pub use daemon::{API_VERSION, DaemonInfo}; pub use id::{PaneId, TabId, WorkspaceId}; pub use layout::{Layout, LayoutError, Ratio, SplitDirection}; pub use pane::{Agent, PaneKind}; -pub use pr::{ChecksState, NotAPr, PrRef, PrState, ReviewState, pr_details, prs_details}; +pub use pr::{ + ChecksState, NotAPr, PrRef, PrState, ReviewState, Yours, pr_details, prs_details, why_yours, +}; pub use repository::{Linking, NotARepository, RepositoryId, RepositoryName, pr_alerts_muted}; pub use state::AgentState; pub use text_enum::UnknownValue; diff --git a/crates/agentdeck-core/src/pr.rs b/crates/agentdeck-core/src/pr.rs index 83eea0a..642876e 100644 --- a/crates/agentdeck-core/src/pr.rs +++ b/crates/agentdeck-core/src/pr.rs @@ -145,6 +145,44 @@ text_enum! { } } +text_enum! { + /// Why a pull request is yours (spec §8): PR sync keeps the ones you authored, the ones + /// where your review is requested and the ones assigned to you. One can be yours several + /// ways at once, and an open one that is yours no way at all is Finished. + pub enum Yours ("why it's yours") { + /// You opened it. + Authored => "authored", + /// Its review requests name you. + ReviewRequested => "review_requested", + /// Its assignees include you. + Assigned => "assigned", + } +} + +/// Why a pull request is yours, the signed-in `login`'s (spec §8), in [`Yours::ALL`]'s order, +/// as GitHub shows it: its `author`'s login (`None` once that account is gone), the logins +/// its review requests name (a team's request names no login) and its assignees' logins. +/// Logins match ignoring case, as GitHub's do. Empty when it is none of these. +pub fn why_yours<'a>( + login: &str, + author: Option<&str>, + requested: impl IntoIterator, + assignees: impl IntoIterator, +) -> Vec { + let me = |other: &str| other.eq_ignore_ascii_case(login); + let authored = author.is_some_and(me); + let requested = requested.into_iter().any(me); + let assigned = assignees.into_iter().any(me); + [ + (authored, Yours::Authored), + (requested, Yours::ReviewRequested), + (assigned, Yours::Assigned), + ] + .into_iter() + .filter_map(|(yes, why)| yes.then_some(why)) + .collect() +} + /// What **Copy PR details** puts on the clipboard for one pull request (spec §11): three lines /// of plain text that also read as markdown. Its reference and title, its GitHub page, then the /// branch it merges from and the one it merges into: @@ -328,4 +366,78 @@ mod tests { assert_eq!(texts, ["approved", "changes_requested", "review_required"]); } } + + mod yours { + use super::*; + + #[test] + fn should_use_the_spec_column_values() { + let texts: Vec<_> = Yours::ALL.iter().map(|s| s.as_str()).collect(); + assert_eq!(texts, ["authored", "review_requested", "assigned"]); + } + } + + mod why_yours { + use super::*; + + const NOBODY: [&str; 0] = []; + + #[test] + fn should_be_authored_when_you_opened_it() { + assert_eq!( + why_yours("octocat", Some("octocat"), NOBODY, NOBODY), + [Yours::Authored] + ); + } + + #[test] + fn should_be_review_requested_when_a_request_names_you() { + assert_eq!( + why_yours("octocat", Some("hubot"), ["monalisa", "octocat"], NOBODY), + [Yours::ReviewRequested] + ); + } + + #[test] + fn should_be_assigned_when_you_are_an_assignee() { + assert_eq!( + why_yours("octocat", Some("hubot"), NOBODY, ["octocat"]), + [Yours::Assigned] + ); + } + + #[test] + fn should_give_every_way_it_is_yours_in_order() { + assert_eq!( + why_yours( + "octocat", + Some("octocat"), + ["octocat"], + ["hubot", "octocat"] + ), + [Yours::Authored, Yours::ReviewRequested, Yours::Assigned] + ); + } + + #[test] + fn should_match_logins_ignoring_case() { + assert_eq!( + why_yours("OctoCat", Some("octocat"), ["OCTOCAT"], ["octoCat"]), + [Yours::Authored, Yours::ReviewRequested, Yours::Assigned] + ); + } + + #[test] + fn should_be_none_once_your_review_and_assignment_are_gone() { + assert_eq!( + why_yours("octocat", Some("hubot"), ["monalisa"], ["hubot"]), + [] + ); + } + + #[test] + fn should_not_be_authored_when_its_authors_account_is_gone() { + assert_eq!(why_yours("octocat", None, NOBODY, NOBODY), []); + } + } } diff --git a/crates/agentdeck-gui/src/overview.rs b/crates/agentdeck-gui/src/overview.rs index f566795..f3c0d19 100644 --- a/crates/agentdeck-gui/src/overview.rs +++ b/crates/agentdeck-gui/src/overview.rs @@ -272,7 +272,7 @@ pub(crate) mod fixtures { PrSyncStatus, PullRequest, Repository, RepositoryLinks, Workspace, }; use agentdeck_core::{ - AgentState, PaneId, PrRef, PrState, RepositoryId, RepositoryName, WorkspaceId, + AgentState, PaneId, PrRef, PrState, RepositoryId, RepositoryName, WorkspaceId, Yours, }; use super::{PaneState, Snapshot}; @@ -374,6 +374,7 @@ pub(crate) mod fixtures { finished: false, updated_at: CREATED.into(), url: format!("https://github.com/{repo}/pull/{n}"), + yours: vec![Yours::Authored], } } diff --git a/crates/agentdeck-gui/src/shell.rs b/crates/agentdeck-gui/src/shell.rs index d9a74cb..469b6ad 100644 --- a/crates/agentdeck-gui/src/shell.rs +++ b/crates/agentdeck-gui/src/shell.rs @@ -2748,7 +2748,7 @@ mod tests { /// in the Pull requests view, muted by the Workspaces linking its Repository. mod pr_alerts { use agentdeck_client::types::PullRequest; - use agentdeck_core::{RepositoryId, ReviewState}; + use agentdeck_core::{RepositoryId, ReviewState, Yours}; use super::*; use crate::gui_state; @@ -2882,6 +2882,41 @@ mod tests { assert_eq!(open.shown(), []); } + + #[gpui::test] + fn should_never_alert_for_a_pr_you_review_or_are_assigned(cx: &mut TestAppContext) { + // Someone else's: yours as a reviewer, as an assignee, and as both. + let theirs = |n, yours: &[Yours], checks, review| PullRequest { + author: Some("hubot".into()), + yours: yours.to_vec(), + review, + ..pr(n, "acme/web", checks) + }; + let ways: [&[Yours]; 3] = [ + &[Yours::ReviewRequested], + &[Yours::Assigned], + &[Yours::ReviewRequested, Yours::Assigned], + ]; + let required = Some(ReviewState::ReviewRequired); + let before = (ways.iter().zip(5..)) + .map(|(yours, n)| theirs(n, yours, ChecksState::Pending, required)) + .collect(); + let after = [ + Some(ReviewState::Approved), + Some(ReviewState::ChangesRequested), + ]; + let mut open = Open::new(holding(before), cx); + + for review in after { + open.sync( + (ways.iter().zip(5..)) + .map(|(yours, n)| theirs(n, yours, ChecksState::Failure, review)) + .collect(), + ); + } + + assert_eq!(open.shown(), []); + } } mod one_per_pr { diff --git a/crates/agentdeck/src/render.rs b/crates/agentdeck/src/render.rs index 03156cc..562c549 100644 --- a/crates/agentdeck/src/render.rs +++ b/crates/agentdeck/src/render.rs @@ -690,6 +690,7 @@ mod tests { reference.repository(), reference.number() ), + yours: vec![agentdeck_core::Yours::Authored], } } diff --git a/crates/agentdeck/tests/integration/pr.rs b/crates/agentdeck/tests/integration/pr.rs index 6eff86e..e0e4282 100644 --- a/crates/agentdeck/tests/integration/pr.rs +++ b/crates/agentdeck/tests/integration/pr.rs @@ -33,10 +33,7 @@ mod pr_sync { fn should_run_a_full_sync_though_an_incremental_one_is_due() { use crate::support::github::{Pr, mock_open_prs}; let github = httpmock::MockServer::start(); - let seven = Pr { - repo: "acme/widgets", - number: 7, - }; + let seven = Pr::open("acme/widgets", 7); let mocks = mock_open_prs(&github, "gho_test", &[seven]); let env = TestEnv::with_github(&github.url("/graphql"), "gho_test"); @@ -69,16 +66,10 @@ mod pr_ls { } fn widgets(number: i64) -> Pr { - Pr { - repo: "acme/widgets", - number, - } + Pr::open("acme/widgets", number) } - const GADGET: Pr = Pr { - repo: "acme/gadgets", - number: 9, - }; + const GADGET: Pr = Pr::open("acme/gadgets", 9); #[test] fn should_list_each_pr_by_its_reference_with_its_state() { @@ -129,6 +120,52 @@ mod pr_ls { assert!(pr["repository"]["id"].is_u64(), "{pr}"); } + #[test] + fn should_list_prs_you_review_or_are_assigned_with_why_each_is_yours_with_json() { + let github = MockServer::start(); + let review = Pr { + author: "hubot", + requested: true, + ..widgets(8) + }; + let assigned = Pr { + author: "hubot", + assigned: true, + ..GADGET + }; + let env = synced(&github, &[widgets(7), review, assigned]); + + let stdout = env.ok(&["pr", "ls"]); + let prs = env.json(&["pr", "ls"]); + + assert_eq!( + stdout, + "PR STATE TITLE\n\ + acme/gadgets#9 open PR 9\n\ + acme/widgets#7 open PR 7\n\ + acme/widgets#8 open PR 8\n" + ); + let yours: Vec<(String, Value)> = (prs.as_array().expect("a list").iter()) + .map(|pr| { + ( + pr["reference"].as_str().unwrap().to_owned(), + pr["yours"].clone(), + ) + }) + .collect(); + assert_eq!( + yours, + [ + ("acme/gadgets#9".to_owned(), serde_json::json!(["assigned"])), + ("acme/widgets#7".to_owned(), serde_json::json!(["authored"])), + ( + "acme/widgets#8".to_owned(), + serde_json::json!(["review_requested"]) + ), + ] + ); + } + #[test] fn should_list_only_the_pull_requests_of_the_repositories_a_workspace_links() { let github = MockServer::start(); @@ -199,18 +236,9 @@ mod pr_close { const TOKEN: &str = "gho_test"; - const SEVEN: Pr = Pr { - repo: "acme/widgets", - number: 7, - }; - const EIGHT: Pr = Pr { - repo: "acme/widgets", - number: 8, - }; - const NINE: Pr = Pr { - repo: "acme/gadgets", - number: 9, - }; + const SEVEN: Pr = Pr::open("acme/widgets", 7); + const EIGHT: Pr = Pr::open("acme/widgets", 8); + const NINE: Pr = Pr::open("acme/gadgets", 9); /// A world whose daemon has synced `prs`. fn synced(github: &MockServer, prs: &[Pr]) -> TestEnv { diff --git a/crates/agentdeck/tests/integration/repo.rs b/crates/agentdeck/tests/integration/repo.rs index 1325739..cc8addc 100644 --- a/crates/agentdeck/tests/integration/repo.rs +++ b/crates/agentdeck/tests/integration/repo.rs @@ -38,13 +38,7 @@ mod repo_ls { fn should_list_each_repository_with_the_workspaces_linking_it() { let github = MockServer::start(); mock_repo(&github, TOKEN, WIDGETS); - let env = synced( - &github, - &[Pr { - repo: GADGETS, - number: 9, - }], - ); + let env = synced(&github, &[Pr::open(GADGETS, 9)]); env.workspace("web"); env.workspace("api"); env.ok(&["repo", "link", WIDGETS, "--ws", "web"]); @@ -213,13 +207,7 @@ mod repo_unlink { #[test] fn should_keep_a_repository_one_of_your_pull_requests_belongs_to() { let github = MockServer::start(); - let env = synced( - &github, - &[Pr { - repo: WIDGETS, - number: 7, - }], - ); + let env = synced(&github, &[Pr::open(WIDGETS, 7)]); env.workspace("web"); env.ok(&["repo", "link", WIDGETS, "--ws", "web"]); diff --git a/crates/agentdeck/tests/integration/support/github.rs b/crates/agentdeck/tests/integration/support/github.rs index f73b0f3..56825cf 100644 --- a/crates/agentdeck/tests/integration/support/github.rs +++ b/crates/agentdeck/tests/integration/support/github.rs @@ -6,14 +6,34 @@ use httpmock::prelude::*; use httpmock::{Mock, MockServer}; use serde_json::{Value, json}; +/// The signed-in login in these tests: GitHub answers each query for PRs as this viewer. +pub const ME: &str = "octocat"; + /// An open PR on `repo`, from `feat/x` into `main`. #[derive(Clone, Copy)] pub struct Pr { pub repo: &'static str, pub number: i64, + /// Who opened it. + pub author: &'static str, + /// Whether its review requests name [`ME`]. + pub requested: bool, + /// Whether it is assigned to [`ME`]. + pub assigned: bool, } impl Pr { + /// PR `number` of `repo`, opened by [`ME`], with no review requests or assignees. + pub const fn open(repo: &'static str, number: i64) -> Pr { + Pr { + repo, + number, + author: ME, + requested: false, + assigned: false, + } + } + pub fn node_id(&self) -> String { format!("PR_{}_{}", self.repo.replace('/', "_"), self.number) } @@ -34,7 +54,13 @@ impl Pr { "headRefName": "feat/x", "baseRefName": "main", "updatedAt": "2026-11-01T10:00:00Z", - "author": { "login": "octocat" }, + "author": { "login": self.author }, + "reviewRequests": { "nodes": if self.requested { + json!([{ "requestedReviewer": { "login": ME } }]) + } else { + json!([]) + } }, + "assignees": { "nodes": if self.assigned { json!([{ "login": ME }]) } else { json!([]) } }, "repository": { "fullDatabaseId": self.repository_id().to_string(), "nameWithOwner": self.repo, @@ -84,44 +110,79 @@ pub fn mock_repo_missing<'a>(server: &'a MockServer, repo: &str) -> Mock<'a> { /// The mocks [`mock_open_prs`] answers a sync with. pub struct OpenPrs<'a> { - /// The list of open PRs, which a full sync reads. + /// The list of open PRs you authored, which a full sync reads. pub list: Mock<'a>, - /// The search, which an incremental sync reads. + /// The searches for PRs updated since the last sync, which an incremental sync reads. pub search: Mock<'a>, } -/// The viewer's open PRs, `prs`, however a sync reads them for `token`: the list (a full -/// sync), the search (an incremental one) and their details by number. +/// The viewer's open PRs, `prs`, however a sync reads them for `token`: the list of those +/// [`ME`] authored and the searches for those where your review is requested and those +/// assigned to you (a full sync), the searches for PRs updated since (an incremental one, all +/// of `prs`), and the authored ones' details by number. pub fn mock_open_prs<'a>(server: &'a MockServer, token: &str, prs: &[Pr]) -> OpenPrs<'a> { - let nodes: Vec = prs.iter().map(Pr::node).collect(); + let authored: Vec = prs.iter().copied().filter(|pr| pr.author == ME).collect(); + let list_nodes: Vec = authored.iter().map(Pr::node).collect(); let list = server.mock(|when, then| { when.method(POST) .path("/graphql") .header("authorization", format!("Bearer {token}")) .body_includes("pullRequests("); then.status(200).json_body(json!({ - "data": { "viewer": { "pullRequests": { - "totalCount": nodes.len(), + "data": { "viewer": { "login": ME, "pullRequests": { + "totalCount": list_nodes.len(), "pageInfo": { "hasNextPage": false, "endCursor": null }, - "nodes": nodes + "nodes": list_nodes } } } })); }); + for (qualifier, whose) in [ + ( + "user-review-requested:@me", + (|pr: &Pr| pr.requested) as fn(&Pr) -> bool, + ), + ("assignee:@me", |pr: &Pr| pr.assigned), + ] { + let found: Vec = prs.iter().copied().filter(whose).collect(); + server.mock(|when, then| { + when.method(POST) + .path("/graphql") + .header("authorization", format!("Bearer {token}")) + .body_includes("search(") + .body_includes("is:open") + .body_includes(qualifier); + then.status(200).json_body(search_body(&found)); + }); + } let search = server.mock(|when, then| { when.method(POST) .path("/graphql") .header("authorization", format!("Bearer {token}")) - .body_includes("search("); - then.status(200).json_body(json!({ - "data": { "search": { + .body_includes("search(") + .body_includes("updated:>="); + then.status(200).json_body(search_body(prs)); + }); + if !authored.is_empty() { + by_number(server, "fragment pr on PullRequest", &authored, |pr| { + pr.node() + }); + } + OpenPrs { list, search } +} + +/// A search's response body: one page holding `prs`, as [`ME`] sees them. +fn search_body(prs: &[Pr]) -> Value { + let nodes: Vec = prs.iter().map(Pr::node).collect(); + json!({ + "data": { + "viewer": { "login": ME }, + "search": { "issueCount": nodes.len(), "pageInfo": { "hasNextPage": false, "endCursor": null }, "nodes": nodes - } } - })); - }); - by_number(server, "fragment pr on PullRequest", prs, |pr| pr.node()); - OpenPrs { list, search } + } + } + }) } /// The lookup of `prs`' node ids before a close, in one request. @@ -144,11 +205,12 @@ fn by_number<'a>( ) -> Mock<'a> { let first = prs[0]; let (owner, name) = first.repo.split_once('/').expect("owner/name"); - let data: serde_json::Map = prs + let mut data: serde_json::Map = prs .iter() .enumerate() .map(|(i, pr)| (format!("p{i}"), json!({ "pullRequest": pull_request(pr) }))) .collect(); + data.insert("viewer".into(), json!({ "login": ME })); server.mock(|when, then| { when.method(POST) .path("/graphql") diff --git a/crates/agentdeckd/src/api/mod.rs b/crates/agentdeckd/src/api/mod.rs index 179e54e..9bc384a 100644 --- a/crates/agentdeckd/src/api/mod.rs +++ b/crates/agentdeckd/src/api/mod.rs @@ -240,7 +240,7 @@ mod tests { /// `openapi.json`'s fingerprint when [`agentdeck_core::API_VERSION`] was last set, /// and that version. Clients tell an older daemon by its API version, so a route or /// field added without a bump would go unnoticed: they would call it and get a 404. - const FINGERPRINT_AT_API_VERSION: (u64, u32) = (0xd70e_7ecf_0702_a3ac, 27); + const FINGERPRINT_AT_API_VERSION: (u64, u32) = (0x3450_2b0c_1cb3_87cf, 28); /// FNV-1a: stable across Rust releases, unlike `DefaultHasher`. fn fingerprint(text: &str) -> u64 { diff --git a/crates/agentdeckd/src/db/migrations/0003_why_a_pull_request_is_yours.sql b/crates/agentdeckd/src/db/migrations/0003_why_a_pull_request_is_yours.sql new file mode 100644 index 0000000..980b2b0 --- /dev/null +++ b/crates/agentdeckd/src/db/migrations/0003_why_a_pull_request_is_yours.sql @@ -0,0 +1,8 @@ +-- Why each kept pull request is yours (spec §3, §8): PR sync keeps the PRs you authored, those +-- where your review is requested and those assigned to you, and an open one that is yours none +-- of these ways is Finished. Every PR kept before this was found as one you authored. + +ALTER TABLE pull_requests ADD COLUMN authored INTEGER NOT NULL DEFAULT 0; +ALTER TABLE pull_requests ADD COLUMN review_requested INTEGER NOT NULL DEFAULT 0; +ALTER TABLE pull_requests ADD COLUMN assigned INTEGER NOT NULL DEFAULT 0; +UPDATE pull_requests SET authored = 1; diff --git a/crates/agentdeckd/src/db/mod.rs b/crates/agentdeckd/src/db/mod.rs index 93ab436..6fc7d8b 100644 --- a/crates/agentdeckd/src/db/mod.rs +++ b/crates/agentdeckd/src/db/mod.rs @@ -27,6 +27,9 @@ const MIGRATION_LIST: &[M<'static>] = &[ M::up(include_str!( "migrations/0002_workspaces_lose_their_folder.sql" )), + M::up(include_str!( + "migrations/0003_why_a_pull_request_is_yours.sql" + )), ]; const MIGRATIONS: Migrations<'static> = Migrations::from_slice(MIGRATION_LIST); diff --git a/crates/agentdeckd/src/db/pull_requests.rs b/crates/agentdeckd/src/db/pull_requests.rs index 5db44aa..6d7e4b7 100644 --- a/crates/agentdeckd/src/db/pull_requests.rs +++ b/crates/agentdeckd/src/db/pull_requests.rs @@ -5,7 +5,7 @@ //! Repository's PRs stay the same PRs, and another Repository taking its old name never //! collides with them. A PR's name is its Repository's name now. -use agentdeck_core::{PrRef, PrState, RepositoryId}; +use agentdeck_core::{PrRef, PrState, RepositoryId, Yours}; use chrono::{DateTime, Utc}; use rusqlite::types::Value; use rusqlite::{Connection, OptionalExtension, Row, params, params_from_iter}; @@ -16,7 +16,8 @@ use crate::prsync::github::{PrKey, RemotePr, RemoteRepository}; /// Every column a stored PR is read back from, its Repository's included, for [`remote`]. const STORED: &str = "p.number, p.title, p.url, p.state, p.draft, p.head_ref, p.base_ref, - p.author, p.checks, p.review, p.updated_at, p.unreachable_at IS NOT NULL AS unreachable, + p.author, p.authored, p.review_requested, p.assigned, p.checks, p.review, p.updated_at, + p.unreachable_at IS NOT NULL AS unreachable, p.finished_at IS NOT NULL AS finished, r.id AS repository_id, r.full_name, r.url AS repository_url, r.private, r.archived"; @@ -88,6 +89,7 @@ fn listed(row: &Row<'_>) -> rusqlite::Result { head_ref: row.get("head_ref")?, base_ref: row.get("base_ref")?, author: row.get("author")?, + yours: yours(row)?, checks: opt_text(row, "checks")?, review: opt_text(row, "review")?, updated_at: row.get("updated_at")?, @@ -96,6 +98,22 @@ fn listed(row: &Row<'_>) -> rusqlite::Result { }) } +/// Why a PR row is yours, in [`Yours::ALL`]'s order, from its `authored`, `review_requested` +/// and `assigned` columns. +fn yours(row: &Row<'_>) -> rusqlite::Result> { + let mut yours = Vec::new(); + for (column, why) in [ + ("authored", Yours::Authored), + ("review_requested", Yours::ReviewRequested), + ("assigned", Yours::Assigned), + ] { + if row.get(column)? { + yours.push(why); + } + } + Ok(yours) +} + /// Every PR stored as open, as last synced, but for those Finished or unreachable. pub fn open_current(conn: &Connection) -> Result, DbError> { stored_where( @@ -304,6 +322,7 @@ fn remote(row: &Row<'_>) -> rusqlite::Result { head_ref: row.get("head_ref")?, base_ref: row.get("base_ref")?, author: row.get("author")?, + yours: yours(row)?, checks: opt_text(row, "checks")?, review: opt_text(row, "review")?, updated_at: row.get("updated_at")?, @@ -376,22 +395,26 @@ pub fn store( } /// Inserts or replaces `pr`'s row, which is no longer unreachable. GitHub showed it within -/// the cutoff, so it is Finished while merged or closed, from the first time it was stored so, -/// and not while open. +/// the cutoff, so it is Finished while merged or closed, or open but yours no way (spec §8), +/// from the first time it was stored so; not while open and yours. fn write_row(conn: &Connection, pr: &RemotePr, synced_at: &str) -> Result<(), DbError> { + let has = |why: Yours| pr.yours.contains(&why); + let kept = pr.state == PrState::Open && !pr.yours.is_empty(); conn.execute( "INSERT INTO pull_requests (repository_id, number, title, url, state, draft, head_ref, base_ref, author, checks, - review, updated_at, synced_at, finished_at) + review, updated_at, synced_at, finished_at, authored, review_requested, assigned) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, - CASE WHEN ?5 = ?14 THEN NULL ELSE ?13 END) + CASE WHEN ?14 THEN NULL ELSE ?13 END, ?15, ?16, ?17) ON CONFLICT (repository_id, number) DO UPDATE SET title = excluded.title, url = excluded.url, state = excluded.state, draft = excluded.draft, head_ref = excluded.head_ref, base_ref = excluded.base_ref, author = excluded.author, checks = excluded.checks, review = excluded.review, updated_at = excluded.updated_at, synced_at = excluded.synced_at, + authored = excluded.authored, review_requested = excluded.review_requested, + assigned = excluded.assigned, unreachable_at = NULL, - finished_at = CASE WHEN excluded.state = ?14 THEN NULL + finished_at = CASE WHEN ?14 THEN NULL ELSE COALESCE(finished_at, excluded.finished_at) END", params![ pr.repository.id.get(), @@ -407,7 +430,10 @@ fn write_row(conn: &Connection, pr: &RemotePr, synced_at: &str) -> Result<(), Db pr.review.map(|review| review.as_str()), pr.updated_at, synced_at, - PrState::Open.as_str(), + kept, + has(Yours::Authored), + has(Yours::ReviewRequested), + has(Yours::Assigned), ], )?; Ok(()) diff --git a/crates/agentdeckd/src/model.rs b/crates/agentdeckd/src/model.rs index a31c036..64d4936 100644 --- a/crates/agentdeckd/src/model.rs +++ b/crates/agentdeckd/src/model.rs @@ -3,7 +3,7 @@ use agentdeck_core::{ Agent, AgentState, ChecksState, Layout, PaneId, PaneKind, PrRef, PrState, RepositoryId, - RepositoryName, ReviewState, TabId, WorkspaceId, + RepositoryName, ReviewState, TabId, WorkspaceId, Yours, }; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; @@ -172,6 +172,11 @@ pub struct PullRequest { pub base_ref: String, /// The GitHub login of who opened it; `None` when that account is gone. pub author: Option, + /// Why it is yours, in this order: `authored`, `review_requested` (a review request names + /// you), `assigned`; empty once it is none of these, when it is Finished (spec §8). Absent + /// from an older daemon, which read only the PRs you authored. + #[serde(default)] + pub yours: Vec, /// The head commit's rolled-up checks; `None` when it has none. pub checks: Option, /// The review decision; `None` when the Repository requires no review. diff --git a/crates/agentdeckd/src/prsync/github.rs b/crates/agentdeckd/src/prsync/github.rs index fb565ec..03dec31 100644 --- a/crates/agentdeckd/src/prsync/github.rs +++ b/crates/agentdeckd/src/prsync/github.rs @@ -1,11 +1,17 @@ //! GitHub's GraphQL API (spec §8): the viewer's login and scopes, the list of the viewer's -//! open PRs with light fields, the search for PRs updated since a time, PRs by number with -//! every field, in batches, and closing a PR: its node id by number, in batches, then one -//! `closePullRequest` each. And GitHub's REST API, for a Repository by name. +//! open PRs with light fields, the searches for the viewer's open PRs and for those updated +//! since a time, PRs by number with every field, in batches, and closing a PR: its node id by +//! number, in batches, then one `closePullRequest` each. And GitHub's REST API, for a +//! Repository by name. +//! +//! Every query for PRs asks for the viewer's login beside them, so why each PR is yours +//! ([`Yours`]) is read against the login the token belongs to as GitHub answers. use std::time::Duration; -use agentdeck_core::{ChecksState, PrState, RepositoryId, RepositoryName, ReviewState}; +use agentdeck_core::{ + ChecksState, PrState, RepositoryId, RepositoryName, ReviewState, Yours, why_yours, +}; use serde::{Deserialize, Deserializer}; use serde_json::{Value, json}; @@ -18,10 +24,41 @@ pub const DEFAULT_REST_ENDPOINT: &str = "https://api.github.com"; /// The REST API version every REST request asks for. const REST_API_VERSION: &str = "2022-11-28"; -/// The incremental search: every PR the token's user authored, in any state, that changed at -/// or after `since` (RFC 3339). -pub fn updated_search(since: &str) -> String { - format!("is:pr author:@me updated:>={since}") +/// Whose PRs a search asks for: the ways a PR is yours, by GitHub's search qualifier. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Whose { + /// `author:@me`: the PRs the token's user opened. + Authored, + /// `user-review-requested:@me`: the PRs whose review requests name the token's user. Not + /// `review-requested:@me`, which also finds requests to a team the user is on: a team's + /// request names no login, so such a PR would read as not yours (spec §8). + ReviewRequested, + /// `assignee:@me`: the PRs assigned to the token's user. + Assigned, +} + +impl Whose { + /// Every way, in the order a sync searches them. + pub const ALL: [Whose; 3] = [Whose::Authored, Whose::ReviewRequested, Whose::Assigned]; + + fn qualifier(self) -> &'static str { + match self { + Whose::Authored => "author:@me", + Whose::ReviewRequested => "user-review-requested:@me", + Whose::Assigned => "assignee:@me", + } + } +} + +/// An incremental search: every PR `whose` says, in any state, that changed at or after +/// `since` (RFC 3339). +pub fn updated_search(whose: Whose, since: &str) -> String { + format!("is:pr {} updated:>={since}", whose.qualifier()) +} + +/// A full sync's search: every open PR `whose` says, most recently updated first. +pub fn open_search(whose: Whose) -> String { + format!("is:pr is:open {} sort:updated-desc", whose.qualifier()) } /// Search results per page, and how many pages one sync reads at most. @@ -49,16 +86,21 @@ const RETRY_WAITS: [Duration; 2] = [Duration::from_secs(1), Duration::from_secs( const PR_FIELDS: &str = "fragment pr on PullRequest { number title url state isDraft headRefName baseRefName updatedAt author { login } + reviewRequests(first: 50) { nodes { requestedReviewer { ... on User { login } } } } + assignees(first: 10) { nodes { login } } repository { fullDatabaseId nameWithOwner url isPrivate isArchived } reviewDecision commits(last: 1) { nodes { commit { statusCheckRollup { state } } } } }"; /// The list's light fields: no review and no checks, the costly ones (the rollup made a -/// 100-PR page time out). +/// 100-PR page time out). Review requests and assignees stay, to read why each is yours; +/// GitHub allows 10 assignees. const LIGHT_FIELDS: &str = "fragment light on PullRequest { number title url state isDraft headRefName baseRefName updatedAt author { login } + reviewRequests(first: 50) { nodes { requestedReviewer { ... on User { login } } } } + assignees(first: 10) { nodes { login } } repository { fullDatabaseId nameWithOwner url isPrivate isArchived } }"; @@ -94,6 +136,8 @@ pub struct RemotePr { pub base_ref: String, /// The login of who opened it; `None` when that account is gone. pub author: Option, + /// Why it is the token's user's, in [`Yours::ALL`]'s order; empty when it no longer is. + pub yours: Vec, /// The head commit's rolled-up checks; `None` when it has none. pub checks: Option, /// The review decision; `None` when the repo requires no review. @@ -330,7 +374,8 @@ impl Github { }) } - /// The page of the search `q` after cursor `after` (`None` for the first page). + /// The page of the search `q` after cursor `after` (`None` for the first page), each PR + /// with why it is the viewer's. pub async fn search_page( &self, token: &str, @@ -339,6 +384,7 @@ impl Github { ) -> Result { let query = format!( "query($q: String!, $first: Int!, $after: String) {{ + viewer {{ login }} search(query: $q, type: ISSUE, first: $first, after: $after) {{ issueCount pageInfo {{ hasNextPage endCursor }} @@ -352,7 +398,8 @@ impl Github { } /// The page of the viewer's open PRs after cursor `after` (`None` for the first), most - /// recently updated first, with light fields only: `checks` and `review` are `None`. + /// recently updated first, with light fields only: `checks` and `review` are `None`. Each + /// is the viewer's at least as authored. pub async fn list_page( &self, token: &str, @@ -361,6 +408,7 @@ impl Github { let query = format!( "query($first: Int!, $after: String) {{ viewer {{ + login pullRequests(states: OPEN, first: $first, after: $after, orderBy: {{ field: UPDATED_AT, direction: DESC }}) {{ totalCount pageInfo {{ hasNextPage endCursor }} @@ -374,9 +422,9 @@ impl Github { parse_list(self.query(token, &query, variables).await?) } - /// Each of `wanted` (`(repo, number)`) by number with every field, in order: `BATCH_SIZE` - /// to a request, `BATCHES_IN_FLIGHT` requests at once. `None` for one GitHub no longer - /// shows to the token's user. + /// Each of `wanted` (`(repo, number)`) by number with every field and why it is the + /// viewer's, in order: `BATCH_SIZE` to a request, `BATCHES_IN_FLIGHT` requests at once. + /// `None` for one GitHub no longer shows to the token's user. pub async fn prs( &self, token: &str, @@ -400,7 +448,7 @@ impl Github { token: &str, batch: Vec<(String, i64)>, ) -> Result>, GithubError> { - let (query, variables) = batch_query(&batch, "pr", PR_FIELDS); + let (query, variables) = batch_query(&batch, "pr", PR_FIELDS, true); let data = self.query(token, &query, variables).await?; parse_batch(data, batch.len()) } @@ -434,7 +482,7 @@ impl Github { token: &str, batch: Vec<(String, i64)>, ) -> Result>, GithubError> { - let (query, variables) = batch_query(&batch, "nodeId", NODE_ID_FIELDS); + let (query, variables) = batch_query(&batch, "nodeId", NODE_ID_FIELDS, false); match self.query_body(token, &query, variables).await { Ok((body, _)) => Ok(parse_node_ids(&body, batch.len())), Err(GithubError::Unauthorized) => Err(GithubError::Unauthorized), @@ -834,6 +882,7 @@ fn parse_list(data: Value) -> Result { #[derive(Deserialize)] #[serde(rename_all = "camelCase")] struct Viewer { + login: String, pull_requests: List, } #[derive(Deserialize)] @@ -850,12 +899,13 @@ fn parse_list(data: Value) -> Result { end_cursor: Option, } - let list = serde_json::from_value::(data)?.viewer.pull_requests; + let viewer = serde_json::from_value::(data)?.viewer; + let (login, list) = (viewer.login, viewer.pull_requests); Ok(ListPage { prs: list .nodes .into_iter() - .filter_map(LightNode::remote) + .filter_map(|node| node.remote(&login)) .collect(), next: list .page_info @@ -868,6 +918,7 @@ fn parse_list(data: Value) -> Result { fn parse_search(data: Value) -> Result { #[derive(Deserialize)] struct Data { + viewer: Login, search: Search, } #[derive(Deserialize)] @@ -899,7 +950,7 @@ fn parse_search(data: Value) -> Result { .nodes .into_iter() .filter_map(|node| match node { - SearchNode::Pr(pr) => pr.remote(), + SearchNode::Pr(pr) => pr.remote(&data.viewer.login), SearchNode::Other(_) => None, }) .collect(); @@ -912,11 +963,20 @@ fn parse_search(data: Value) -> Result { } /// The query fetching `batch` by number with fragment `fragment` (named `spread`): PR `i` as -/// alias `p`, its owner, name and number in variables `o`, `r` and `n`. A repo -/// that isn't `owner/name` is asked for under an empty owner, which GitHub doesn't show. -fn batch_query(batch: &[(String, i64)], spread: &str, fragment: &str) -> (String, Value) { +/// alias `p`, its owner, name and number in variables `o`, `r` and `n`, and the +/// viewer's login first when `viewer` is set. A repo that isn't `owner/name` is asked for +/// under an empty owner, which GitHub doesn't show. +fn batch_query( + batch: &[(String, i64)], + spread: &str, + fragment: &str, + viewer: bool, +) -> (String, Value) { let mut params = Vec::with_capacity(batch.len()); - let mut fields = Vec::with_capacity(batch.len()); + let mut fields = Vec::with_capacity(batch.len() + 1); + if viewer { + fields.push(" viewer { login }".to_owned()); + } let mut variables = serde_json::Map::new(); for (i, (repo, number)) in batch.iter().enumerate() { let (owner, name) = repo.split_once('/').unwrap_or(("", repo)); @@ -936,7 +996,8 @@ fn batch_query(batch: &[(String, i64)], spread: &str, fragment: &str) -> (String (query, Value::Object(variables)) } -/// The `len` PRs of a batch's `data`, in order; `None` for each GitHub doesn't show. +/// The `len` PRs of a batch's `data`, in order, each with why it is the viewer's; `None` for +/// each GitHub doesn't show. fn parse_batch(data: Value, len: usize) -> Result>, GithubError> { #[derive(Deserialize)] #[serde(rename_all = "camelCase")] @@ -949,13 +1010,14 @@ fn parse_batch(data: Value, len: usize) -> Result>, GithubE "a batch's data isn't an object", ))); }; + let viewer: Login = serde_json::from_value(data.remove("viewer").unwrap_or(Value::Null))?; (0..len) .map(|i| { let repository: Option = serde_json::from_value(data.remove(&format!("p{i}")).unwrap_or(Value::Null))?; Ok(repository .and_then(|repo| repo.pull_request) - .and_then(PrNode::remote)) + .and_then(|pr| pr.remote(&viewer.login))) }) .collect() } @@ -973,13 +1035,17 @@ struct LightNode { base_ref_name: String, updated_at: String, author: Option, + review_requests: Nodes, + assignees: Nodes, repository: RepositoryNode, } impl LightNode { - /// The PR, unless GitHub gave no id for its Repository, which then can't be stored. - fn remote(self) -> Option { + /// The PR, `login`'s as far as GitHub shows, unless GitHub gave no id for its Repository, + /// which then can't be stored. + fn remote(self, login: &str) -> Option { let node = self; + let yours = yours(login, &node.author, &node.review_requests, &node.assignees); Some(RemotePr { repository: node.repository.remote()?, number: node.number, @@ -990,6 +1056,7 @@ impl LightNode { head_ref: node.head_ref_name, base_ref: node.base_ref_name, author: node.author.map(|author| author.login), + yours, checks: None, review: None, updated_at: node.updated_at, @@ -1010,17 +1077,66 @@ struct PrNode { base_ref_name: String, updated_at: String, author: Option, + review_requests: Nodes, + assignees: Nodes, repository: RepositoryNode, review_decision: Option, commits: Commits, } -/// A PR's `author`; null once the account is gone. +/// A PR's `author`, or one of its assignees; an author is null once the account is gone. #[derive(Deserialize)] struct Author { login: String, } +/// The viewer of a query: whom the token belongs to. +#[derive(Deserialize)] +struct Login { + login: String, +} + +/// A connection's `nodes`. +#[derive(Deserialize)] +struct Nodes { + nodes: Vec, +} + +/// One of a PR's review requests. Its reviewer is null when GitHub hides it, and has no +/// `login` when it is a team. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct ReviewRequest { + requested_reviewer: Option, +} + +/// Whom a review request asks: a user's login, or none for a team. +#[derive(Deserialize)] +struct Reviewer { + #[serde(default)] + login: Option, +} + +/// Why a PR with `author`, `requests` and `assignees` is `login`'s (spec §8). +fn yours( + login: &str, + author: &Option, + requests: &Nodes, + assignees: &Nodes, +) -> Vec { + let requested = (requests.nodes.iter()) + .filter_map(|request| request.requested_reviewer.as_ref()?.login.as_deref()); + why_yours( + login, + author.as_ref().map(|author| author.login.as_str()), + requested, + assignees + .nodes + .iter() + .map(|assignee| assignee.login.as_str()), + ) +} + /// A PR's `repository`. #[derive(Deserialize)] #[serde(rename_all = "camelCase")] @@ -1120,10 +1236,12 @@ enum GqlRollup { } impl PrNode { - /// The PR, unless GitHub gave no id for its Repository, which then can't be stored. - fn remote(self) -> Option { + /// The PR, `login`'s as far as GitHub shows, unless GitHub gave no id for its Repository, + /// which then can't be stored. + fn remote(self, login: &str) -> Option { let node = self; let repository = node.repository.remote()?; + let yours = yours(login, &node.author, &node.review_requests, &node.assignees); let checks = node .commits .nodes @@ -1145,6 +1263,7 @@ impl PrNode { head_ref: node.head_ref_name, base_ref: node.base_ref_name, author: node.author.map(|author| author.login), + yours, checks, review: node.review_decision.map(|review| match review { GqlReview::Approved => ReviewState::Approved, @@ -1171,6 +1290,8 @@ mod tests { "baseRefName": "main", "updatedAt": "2026-11-01T10:00:00Z", "author": { "login": "octocat" }, + "reviewRequests": { "nodes": [] }, + "assignees": { "nodes": [] }, "repository": { "fullDatabaseId": "1296269", "nameWithOwner": "acme/widgets", @@ -1183,8 +1304,12 @@ mod tests { }) } + /// The viewer the tests' queries answer as. + const ME: &str = "octocat"; + fn search(nodes: Vec, next: Option<&str>) -> Value { json!({ + "viewer": { "login": ME }, "search": { "pageInfo": { "hasNextPage": next.is_some(), "endCursor": next.unwrap_or("end") }, "nodes": nodes @@ -1394,6 +1519,7 @@ mod tests { head_ref: "feat/sync".into(), base_ref: "main".into(), author: Some("octocat".into()), + yours: vec![Yours::Authored], checks: Some(ChecksState::Success), review: Some(ReviewState::Approved), updated_at: "2026-11-01T10:00:00Z".into(), @@ -1495,7 +1621,7 @@ mod tests { let mut light = node("OPEN", json!("APPROVED"), json!({ "state": "SUCCESS" })); light.as_object_mut().unwrap().remove("reviewDecision"); light.as_object_mut().unwrap().remove("commits"); - let data = json!({ "viewer": { "pullRequests": { + let data = json!({ "viewer": { "login": ME, "pullRequests": { "totalCount": 271, "pageInfo": { "hasNextPage": true, "endCursor": "c1" }, "nodes": [ light ] @@ -1511,6 +1637,7 @@ mod tests { assert_eq!((pr.checks, pr.review), (None, None)); assert_eq!(pr.base_ref, "main"); assert_eq!(pr.author.as_deref(), Some("octocat")); + assert_eq!(pr.yours, [Yours::Authored]); assert_eq!(pr.repository.id, RepositoryId::from(1_296_269)); } } @@ -1557,12 +1684,109 @@ mod tests { } } + mod yours { + use super::*; + + /// Why the PR `node` is, with `edit` applied, the viewer's as a search reads it. + fn yours(edit: impl FnOnce(&mut Value)) -> Vec { + let mut pr = node("OPEN", Value::Null, Value::Null); + edit(&mut pr); + parse_search(search(vec![pr], None)).unwrap().prs[0] + .yours + .clone() + } + + #[test] + fn should_read_a_review_request_naming_the_viewer() { + let why = yours(|pr| { + pr["author"] = json!({ "login": "hubot" }); + pr["reviewRequests"]["nodes"] = json!([ + { "requestedReviewer": { "login": "monalisa" } }, + { "requestedReviewer": { "login": ME } } + ]); + }); + + assert_eq!(why, [Yours::ReviewRequested]); + } + + #[test] + fn should_read_an_assignee_who_is_the_viewer() { + let why = yours(|pr| { + pr["author"] = json!({ "login": "hubot" }); + pr["assignees"]["nodes"] = json!([{ "login": ME }]); + }); + + assert_eq!(why, [Yours::Assigned]); + } + + #[test] + fn should_not_read_a_teams_review_request_or_a_hidden_reviewer_as_the_viewers() { + let why = yours(|pr| { + pr["author"] = json!({ "login": "hubot" }); + pr["reviewRequests"]["nodes"] = json!([ + { "requestedReviewer": {} }, + { "requestedReviewer": null } + ]); + }); + + assert_eq!(why, []); + } + + #[test] + fn should_read_each_fetched_pr_against_the_viewer_of_its_batch() { + let mut theirs = node("OPEN", Value::Null, Value::Null); + theirs["author"] = json!({ "login": "hubot" }); + theirs["assignees"]["nodes"] = json!([{ "login": "monalisa" }]); + let data = json!({ + "viewer": { "login": "monalisa" }, + "p0": { "pullRequest": theirs } + }); + + let prs = parse_batch(data, 1).unwrap(); + + assert_eq!(prs[0].as_ref().unwrap().yours, [Yours::Assigned]); + } + } + + mod searches { + use super::*; + + #[test] + fn should_ask_for_each_way_a_pr_is_yours_updated_since_a_time() { + let qs: Vec = (Whose::ALL.iter()) + .map(|whose| updated_search(*whose, "2026-11-14T10:00:00Z")) + .collect(); + + assert_eq!( + qs, + [ + "is:pr author:@me updated:>=2026-11-14T10:00:00Z", + "is:pr user-review-requested:@me updated:>=2026-11-14T10:00:00Z", + "is:pr assignee:@me updated:>=2026-11-14T10:00:00Z", + ] + ); + } + + #[test] + fn should_ask_for_open_prs_most_recently_updated_first() { + assert_eq!( + open_search(Whose::ReviewRequested), + "is:pr is:open user-review-requested:@me sort:updated-desc" + ); + assert_eq!( + open_search(Whose::Assigned), + "is:pr is:open assignee:@me sort:updated-desc" + ); + } + } + mod parse_batch { use super::*; #[test] fn should_read_each_pr_in_order() { let data = json!({ + "viewer": { "login": ME }, "p0": { "pullRequest": node("MERGED", Value::Null, Value::Null) }, "p1": { "pullRequest": node("OPEN", Value::Null, Value::Null) } }); @@ -1578,7 +1802,8 @@ mod tests { #[test] fn should_be_none_where_the_repo_or_the_pr_is_gone() { - let data = json!({ "p0": null, "p1": { "pullRequest": null } }); + let data = + json!({ "viewer": { "login": ME }, "p0": null, "p1": { "pullRequest": null } }); assert_eq!(parse_batch(data, 3).unwrap(), [None, None, None]); } @@ -1593,8 +1818,10 @@ mod tests { &[("acme/widgets".into(), 7), ("acme/gadgets".into(), 9)], "pr", PR_FIELDS, + true, ); + assert!(query.contains("viewer { login }")); assert!(query.contains( "p1: repository(owner: $o1, name: $r1) { pullRequest(number: $n1) { ...pr } }" )); diff --git a/crates/agentdeckd/src/prsync/mod.rs b/crates/agentdeckd/src/prsync/mod.rs index 6c7999e..ce58f12 100644 --- a/crates/agentdeckd/src/prsync/mod.rs +++ b/crates/agentdeckd/src/prsync/mod.rs @@ -2,16 +2,23 @@ //! PR's Repository is stored by GitHub's id, and each PR by that id and its number, so a rename //! or a transfer keeps both. //! +//! Your PRs are the ones you authored, the ones where your review is requested and the ones +//! assigned to you ([`Whose`]); each stores why it is yours ([`agentdeck_core::Yours`]), read +//! from its author, review requests and assignees against the login the token belongs to. +//! //! The first sync, and one every [`FULL_SYNC_VAR`] seconds (an hour by default), is full: it -//! lists the open PRs, most recently updated first, down to the age cutoff (`[pr_sync] -//! max_age_days`, see [`crate::config`]), and fetches the stored ones that left the list; a -//! stored one older than the cutoff is Finished instead. The rest are incremental: they -//! search only the PRs updated since the last good sync began, in any state, then refresh the -//! [`unsettled`] ones (a finished check run doesn't update a PR). +//! lists the open PRs you authored, then searches the open ones where your review is +//! requested and those assigned to you, each most recently updated first, down to the age +//! cutoff (`[pr_sync] max_age_days`, see [`crate::config`]), and fetches the stored ones that +//! none showed; a stored one older than the cutoff is Finished instead. The rest are +//! incremental: they search only the PRs updated since the last good sync began, in any +//! state, one search per way a PR is yours, then refresh the ones that may have changed +//! unseen ([`recheck`]: a finished check run doesn't update a PR, and a submitted review or +//! an unassignment takes a PR out of every search). //! -//! A PR is **Finished** from when a sync sees it merged or closed, a close from agentdeck -//! closes it, or a full sync finds it open but older than the cutoff; GitHub showing it open -//! within the cutoff again ends that. Each good sync then deletes the PRs Finished +//! A PR is **Finished** from when a sync sees it merged or closed, or open but yours no way at +//! all, a close from agentdeck closes it, or a full sync finds it open but older than the +//! cutoff; GitHub showing it open, yours and within the cutoff again ends that. Each good sync then deletes the PRs Finished //! [`FINISHED_VAR`] seconds ago or longer (7 days by default), and the Repositories nothing //! references any more. A PR the GitHub sign-in can't see is never Finished by the cutoff, //! and is never deleted. @@ -37,7 +44,7 @@ use std::sync::{Arc, Mutex, MutexGuard}; use std::time::Duration; use agentdeck_core::ws::Entity; -use agentdeck_core::{ChecksState, PrRef, PrState, ReviewState}; +use agentdeck_core::{ChecksState, PrRef, PrState, ReviewState, Yours}; use chrono::{DateTime, SecondsFormat, Utc}; use tokio::time::MissedTickBehavior; @@ -46,7 +53,7 @@ use crate::db::{self, Db}; use crate::events::Events; use crate::github_auth::GithubAuth; use crate::model::{GhLogin, PrCloseResult, PrSyncProgress, PrSyncStage, PrSyncStatus}; -use github::{Github, GithubError, PrKey, RemotePr}; +use github::{Github, GithubError, PrKey, RemotePr, Whose}; /// How often the timer syncs. const INTERVAL: Duration = Duration::from_secs(120); @@ -532,16 +539,18 @@ impl PrSync { /// A full read, in two phases. /// - /// 1. The list of open PRs, light fields only, stored page by page as it arrives. A - /// stored PR keeps its checks and review for now. The list is most recently updated - /// first, so it ends at the first PR older than `cutoff`, which isn't stored. - /// 2. Every field, fetched by number, for the PRs that need it: new ones, ones GitHub - /// updated since they were stored, and [`unsettled`] ones. + /// 1. The list of open PRs you authored, light fields only, then the searches for open + /// PRs where your review is requested and that are assigned to you, every field, each + /// stored page by page as it arrives. A stored PR keeps its checks and review from the + /// list for now. Each is most recently updated first, so it ends at the first PR older + /// than `cutoff`, which isn't stored. + /// 2. Every field, fetched by number, for the listed PRs that need it and no search read + /// whole: new ones, ones GitHub updated since they were stored, and [`unsettled`] ones. /// - /// Then the PRs stored as open that left the list are fetched by number, so a merge or - /// close 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. + /// 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. async fn read_full(&self, token: &str, cutoff: Option>) -> Result<(), SyncError> { let github = &self.inner.github; let stored = self @@ -549,9 +558,10 @@ impl PrSync { .db .call(|conn| db::pull_requests::open_prs(conn)) .await?; - let mut seen: Vec = Vec::new(); + let mut tally = Tally::default(); let mut stale: Vec = Vec::new(); let mut after: Option = None; + let mut listed: u32 = 0; for _ in 0..github::MAX_LIST_PAGES { let page = github.list_page(token, after.as_deref()).await?; let mut prs = Vec::with_capacity(page.prs.len()); @@ -561,7 +571,8 @@ impl PrSync { past_cutoff = true; break; } - seen.push(pr.key()); + tally.see(pr.key()); + listed += 1; match stored.iter().find(|old| old.key() == pr.key()) { Some(old) => { if old.updated_at != pr.updated_at || unsettled(old) { @@ -580,22 +591,25 @@ impl PrSync { } } self.store(prs, Vec::new()).await?; - let prs_done = u32::try_from(seen.len()).unwrap_or(u32::MAX); - self.set_progress(Some(PrSyncProgress { - prs_done, - // The list's count takes in the PRs past the cutoff, which this sync skips. - prs: if past_cutoff { - prs_done - } else { - page.total.max(prs_done) - }, - stage: PrSyncStage::Listing, - })); + // The list's count takes in the PRs past the cutoff, which this sync skips. + let total = if past_cutoff { listed } else { page.total }; + self.set_progress(Some(tally.progress(total))); match page.next { Some(next) if !past_cutoff => after = Some(next), - _ => break, + _ => { + tally.counted(total.max(listed)); + break; + } } } + for whose in [Whose::ReviewRequested, Whose::Assigned] { + let q = github::open_search(whose); + let read = self + .search(token, &q, cutoff, true, &mut tally, |_| true) + .await?; + // Read whole: nothing to fetch for it. + stale.retain(|pr| !read.contains(&pr.key())); + } self.details_stage(); let details = self.fetch(token, &stale).await?; @@ -609,7 +623,7 @@ impl PrSync { .await?; let (aged, left): (Vec, Vec) = stored .into_iter() - .filter(|pr| !seen.contains(&pr.key())) + .filter(|pr| !tally.seen.contains(&pr.key())) .partition(|pr| older_than(&pr.updated_at, cutoff)); self.finish_aged(aged.iter().map(RemotePr::key).collect()) .await?; @@ -617,65 +631,100 @@ impl PrSync { self.store(left.found, left.missing).await } - /// An incremental read: the PRs updated at or after `since`, in any state, keeping a - /// merged or closed one only if it's stored as open, and none last updated before - /// `cutoff`; then the stored open PRs the search left out that are [`unsettled`] and - /// GitHub updated within `cutoff`, fetched by number. Nothing is gone: only a full read - /// says so. + /// An incremental read: a search for each way a PR is yours ([`Whose`]) for the PRs + /// updated at or after `since`, in any state, keeping a merged or closed one only if it's + /// stored as open, and none last updated before `cutoff`; then the stored open PRs the + /// searches left out that GitHub updated within `cutoff` and that may have changed unseen + /// ([`recheck`]), fetched by number. Nothing is gone: only a full read says so. async fn read_since( &self, token: &str, since: DateTime, cutoff: Option>, ) -> Result<(), SyncError> { - let github = &self.inner.github; let stored = self .inner .db .call(|conn| db::pull_requests::open(conn)) .await?; - let q = github::updated_search(&since.to_rfc3339_opts(SecondsFormat::Secs, true)); - let mut seen: Vec = Vec::new(); - let mut after: Option = None; - for _ in 0..github::MAX_PAGES { - let page = github.search_page(token, &q, after.as_deref()).await?; - seen.extend(page.prs.iter().map(RemotePr::key)); - let prs: Vec = page - .prs - .into_iter() - .filter(|pr| pr.state == PrState::Open || stored.contains(&pr.key())) - .filter(|pr| !older_than(&pr.updated_at, cutoff)) - .collect(); - self.store(prs, Vec::new()).await?; - let prs_done = u32::try_from(seen.len()).unwrap_or(u32::MAX); - self.set_progress(Some(PrSyncProgress { - prs_done, - prs: page.total.max(prs_done), - stage: PrSyncStage::Listing, - })); - match page.next { - Some(next) => after = Some(next), - None => break, - } + let since = since.to_rfc3339_opts(SecondsFormat::Secs, true); + let mut tally = Tally::default(); + for whose in Whose::ALL { + let q = github::updated_search(whose, &since); + self.search(token, &q, cutoff, false, &mut tally, |pr| { + pr.state == PrState::Open || stored.contains(&pr.key()) + }) + .await?; } - let unsettled: Vec = self + let recheck: Vec = self .inner .db .call(|conn| db::pull_requests::open_current(conn)) .await? .into_iter() .filter(|pr| { - unsettled(pr) && !older_than(&pr.updated_at, cutoff) && !seen.contains(&pr.key()) + recheck(pr) + && !older_than(&pr.updated_at, cutoff) + && !tally.seen.contains(&pr.key()) }) .collect(); - if !unsettled.is_empty() { + if !recheck.is_empty() { self.details_stage(); } - let fetched = self.fetch(token, &unsettled).await?; + let fetched = self.fetch(token, &recheck).await?; self.store(fetched.found, Vec::new()).await } + /// Reads search `q` page by page, at most [`github::MAX_PAGES`], storing each page's PRs + /// that `keep` lets through and that GitHub updated within `cutoff` as it arrives, and + /// counting every PR read in `tally`. A `sorted` search, most recently updated first, ends + /// at the first PR older than `cutoff`, which isn't counted. Returns the keys of the PRs + /// it stored. + async fn search( + &self, + token: &str, + q: &str, + cutoff: Option>, + sorted: bool, + tally: &mut Tally, + keep: impl Fn(&RemotePr) -> bool, + ) -> Result, SyncError> { + let github = &self.inner.github; + let mut kept = Vec::new(); + let mut read: u32 = 0; + let mut after: Option = None; + for _ in 0..github::MAX_PAGES { + let page = github.search_page(token, q, after.as_deref()).await?; + let mut prs = Vec::with_capacity(page.prs.len()); + let mut past_cutoff = false; + for pr in page.prs { + let old = older_than(&pr.updated_at, cutoff); + if old && sorted { + past_cutoff = true; + break; + } + tally.see(pr.key()); + read += 1; + if !old && keep(&pr) { + kept.push(pr.key()); + prs.push(pr); + } + } + self.store(prs, Vec::new()).await?; + let total = if past_cutoff { read } else { page.total }; + self.set_progress(Some(tally.progress(total))); + match page.next { + Some(next) if !past_cutoff => after = Some(next), + _ => { + tally.counted(total.max(read)); + break; + } + } + } + Ok(kept) + } + /// Fetches each of `asked` by number, by the name its Repository goes by as last read. /// A PR GitHub doesn't show the token, or one it shows under another Repository (the name /// was taken by another after a rename agentdeck hasn't seen), is missing. @@ -778,6 +827,39 @@ struct Fetched { missing: Vec, } +/// How far a sync's reading has got, across the list and the searches it reads in turn. +#[derive(Default)] +struct Tally { + /// Every PR read so far, by key, each once. + seen: Vec, + /// How many PRs the lists and searches read to their end held. + counted: u32, +} + +impl Tally { + /// Counts PR `key` as read. + fn see(&mut self, key: PrKey) { + if !self.seen.contains(&key) { + self.seen.push(key); + } + } + + /// Adds `total`, how many PRs a list or search held, once it is read to its end. + fn counted(&mut self, total: u32) { + self.counted = self.counted.saturating_add(total); + } + + /// The progress while reading a list or search holding `total` PRs. + fn progress(&self, total: u32) -> PrSyncProgress { + let prs_done = u32::try_from(self.seen.len()).unwrap_or(u32::MAX); + PrSyncProgress { + prs_done, + prs: self.counted.saturating_add(total).max(prs_done), + stage: PrSyncStage::Listing, + } + } +} + /// A hash of `token`, to tell whether a sync runs with the same token as the last good one /// without keeping the token. fn token_key(token: &str) -> u64 { @@ -800,6 +882,13 @@ fn unsettled(pr: &RemotePr) -> bool { ) } +/// Whether an incremental sync fetches stored open PR `pr` by number when no search showed +/// it: it is [`unsettled`], or yours only as a reviewer or an assignee. Submitting your review +/// or being unassigned leaves every search, and is seen only by fetching the PR (spec §8). +fn recheck(pr: &RemotePr) -> bool { + unsettled(pr) || !pr.yours.contains(&Yours::Authored) +} + /// Whether a PR last updated at `updated_at` (RFC 3339) is older than `cutoff`. One whose time /// doesn't parse isn't: better synced than dropped. fn older_than(updated_at: &str, cutoff: Option>) -> bool { @@ -873,7 +962,7 @@ mod tests { mod unsettled { use super::*; - fn pr(checks: Option, review: Option) -> RemotePr { + pub(super) fn pr(checks: Option, review: Option) -> RemotePr { RemotePr { repository: github::RemoteRepository { id: agentdeck_core::RepositoryId::from(1_296_269), @@ -890,6 +979,7 @@ mod tests { head_ref: "feat/sync".into(), base_ref: "main".into(), author: None, + yours: vec![agentdeck_core::Yours::Authored], checks, review, updated_at: "2026-11-01T10:00:00Z".into(), @@ -922,6 +1012,84 @@ mod tests { } } + mod recheck { + use super::*; + + fn pr(yours: Vec, checks: Option) -> RemotePr { + RemotePr { + yours, + ..unsettled::pr(checks, None) + } + } + + #[test] + fn should_recheck_a_settled_pr_yours_only_as_a_reviewer_or_an_assignee() { + for yours in [ + vec![Yours::ReviewRequested], + vec![Yours::Assigned], + vec![Yours::ReviewRequested, Yours::Assigned], + ] { + assert!(recheck(&pr(yours, Some(ChecksState::Success)))); + } + } + + #[test] + fn should_not_recheck_a_settled_pr_you_authored() { + assert!(!recheck(&pr( + vec![Yours::Authored, Yours::ReviewRequested], + Some(ChecksState::Success) + ))); + } + + #[test] + fn should_recheck_an_unsettled_pr_you_authored() { + assert!(recheck(&pr(vec![Yours::Authored], None))); + } + } + + mod tally { + use super::*; + + fn key(number: i64) -> PrKey { + PrKey { + repository: agentdeck_core::RepositoryId::from(1), + number, + } + } + + #[test] + fn should_count_a_pr_two_searches_read_once() { + let mut tally = Tally::default(); + tally.see(key(7)); + tally.see(key(7)); + + assert_eq!(tally.progress(0).prs_done, 1); + } + + #[test] + fn should_add_the_total_of_the_one_reading_to_those_read_to_their_end() { + let mut tally = Tally::default(); + tally.see(key(1)); + tally.counted(1); + tally.see(key(2)); + + let progress = tally.progress(30); + + assert_eq!((progress.prs_done, progress.prs), (2, 31)); + assert_eq!(progress.stage, PrSyncStage::Listing); + } + + #[test] + fn should_never_say_fewer_prs_than_it_has_read() { + let mut tally = Tally::default(); + for number in 1..=3 { + tally.see(key(number)); + } + + assert_eq!(tally.progress(0).prs, 3); + } + } + mod widens { use super::*; diff --git a/crates/agentdeckd/tests/integration/migrations.rs b/crates/agentdeckd/tests/integration/migrations.rs index 27bcbab..8b6e22f 100644 --- a/crates/agentdeckd/tests/integration/migrations.rs +++ b/crates/agentdeckd/tests/integration/migrations.rs @@ -1,7 +1,8 @@ //! The database at start (spec §2, §3): a fresh data dir gets the schema from the one first //! migration, and a database from before the domain reset, one with a `tasks` table, is moved //! aside with its WAL and SHM files so the daemon starts empty. A database from the first -//! migration loses its Workspaces' folder columns and keeps the rest. +//! migration loses its Workspaces' folder columns and keeps the rest; one from the second keeps +//! its PRs, each as one you authored. use std::path::{Path, PathBuf}; @@ -213,6 +214,53 @@ mod workspace_folders { } } +/// Writes a database under `root` as the second migration left it, before each PR stored why +/// it is yours: PR 7 of `acme/widgets`, open, as PR sync then found every PR, as one you +/// authored. +fn second_migration_db(root: &Path) -> PathBuf { + let path = first_migration_db(root); + let conn = Connection::open(&path).expect("opening the database"); + conn.execute_batch(include_str!( + "../../src/db/migrations/0002_workspaces_lose_their_folder.sql" + )) + .expect("the second migration"); + conn.execute_batch( + "INSERT INTO pull_requests (repository_id, number, title, url, state, draft, head_ref, + base_ref, author, updated_at, synced_at) + VALUES (1296269, 7, 'Add PR sync', 'https://github.com/acme/widgets/pull/7', 'open', + 0, 'feat/sync', 'main', 'octocat', '2026-11-01T10:00:00Z', + '2026-11-01T10:00:00.000000Z'); + PRAGMA user_version = 2;", + ) + .expect("a kept PR"); + path +} + +mod why_yours { + use agentdeck_core::Yours; + + use super::*; + + #[tokio::test] + async fn should_keep_each_pr_as_one_you_authored() { + let dirs = tempfile::tempdir().expect("a temp dir"); + let path = second_migration_db(dirs.path()); + + let daemon = TestDaemon::start_in(dirs).await; + + let columns = columns(&path, "pull_requests"); + for column in ["authored", "review_requested", "assigned"] { + assert!(columns.contains(&column.to_owned()), "{columns:?}"); + } + let prs = (daemon.client.pr_list().send().await) + .expect("list PRs") + .into_inner(); + assert_eq!(prs.len(), 1); + assert_eq!(prs[0].yours, [Yours::Authored]); + assert!(!prs[0].finished); + } +} + mod pre_reset_database { use super::*; diff --git a/crates/agentdeckd/tests/integration/prs.rs b/crates/agentdeckd/tests/integration/prs.rs index 1c77bf6..e24352a 100644 --- a/crates/agentdeckd/tests/integration/prs.rs +++ b/crates/agentdeckd/tests/integration/prs.rs @@ -8,15 +8,17 @@ use agentdeck_client::types::{ GhLogin, NewLink, NewWorkspace, PrClose, PrCloseResult, PrSyncProgress, PrSyncStage, PrSyncStatus, PullRequest, Repository, }; -use agentdeck_core::{ChecksState, PrRef, PrState, RepositoryId, RepositoryName, ReviewState}; +use agentdeck_core::{ + ChecksState, PrRef, PrState, RepositoryId, RepositoryName, ReviewState, Yours, +}; use httpmock::{Mock, MockServer}; use agentdeck_core::ws::{Entity, ServerMessage}; use crate::support::github::{ - BATCH, Pr, days_ago, mock_close, mock_close_refused, mock_fetch, mock_hidden, mock_list, - mock_list_page, mock_node_ids, mock_search, mock_unauthorized, mock_updated_search, - mock_viewer, repository_id, set_gh_token, + BATCH, ME, Pr, days_ago, mock_close, mock_close_refused, mock_fetch, mock_hidden, mock_list, + mock_list_page, mock_node_ids, mock_open_searches, mock_search, mock_unauthorized, + mock_updated_search, mock_viewer, repository_id, set_gh_token, }; use crate::support::ws::{Frame, Ws}; use crate::support::{TestDaemon, set_daemon_env}; @@ -712,6 +714,7 @@ mod full { let daemon = full_daemon(&github, Some(TOKEN)).await; sync(&daemon.client).await; first.delete(); + mock_open_searches(&github, TOKEN, &[], &[]); let changed = Pr { updated_at: "2026-11-02T10:00:00Z", @@ -757,6 +760,7 @@ mod full { 1, Duration::ZERO, ); + mock_open_searches(&github, TOKEN, &[], &[]); github.mock(|when, then| { when.body_includes("pullRequest("); then.status(200) @@ -794,6 +798,7 @@ mod full { 1, Duration::ZERO, ); + mock_open_searches(&github, TOKEN, &[], &[]); github.mock(|when, then| { when.body_includes("pullRequest("); then.status(200) @@ -860,6 +865,7 @@ mod asked_full { 1, Duration::from_millis(800), ); + mock_open_searches(&github, TOKEN, &[], &[]); mock_fetch(&github, &[Pr::open(7)]); let updated = mock_updated_search(&github, TOKEN, &[]); let daemon = daemon(&github, Some(TOKEN)).await; @@ -1092,8 +1098,10 @@ mod max_age { TestDaemon::start_with_github(dirs, &github.url("/graphql")).await } - /// GitHub's list of open PRs, most recently updated first, as one page. + /// GitHub's list of open PRs, most recently updated first, as one page; the searches for + /// PRs where your review is requested or that are assigned to you find none. pub(super) fn mock_open<'a>(github: &'a MockServer, prs: &[Pr]) -> Mock<'a> { + mock_open_searches(github, TOKEN, &[], &[]); mock_list_page(github, TOKEN, prs, None, None, prs.len(), Duration::ZERO) } @@ -1120,6 +1128,7 @@ mod max_age { ); mock_fetch(&github, &[aged(7, 1)]); let old = mock_fetch(&github, &[aged(8, 400)]); + mock_open_searches(&github, TOKEN, &[], &[]); let daemon = TestDaemon::start_with_github(dirs_with_cutoff("90"), &github.url("/graphql")).await; @@ -1230,6 +1239,7 @@ mod progress { Duration::ZERO, ); mock_list_page(github, TOKEN, &[Pr::open(2)], Some("c1"), None, 2, delay); + mock_open_searches(github, TOKEN, &[], &[]); mock_fetch(github, &[Pr::open(1), Pr::open(2)]); daemon(github, Some(TOKEN)).await } @@ -1378,7 +1388,7 @@ mod get_v1_prs { } #[tokio::test] - async fn should_list_each_pr_with_its_reference_repository_and_fields_200() { + async fn should_list_each_pr_with_its_reference_repository_fields_and_why_it_is_yours_200() { let github = MockServer::start_async().await; let pr = Pr { private: true, @@ -1386,6 +1396,7 @@ mod get_v1_prs { head_ref: "fix/sync", base_ref: "release/1.2", author: Some("hubot"), + assignees: &[ME], checks: Some("FAILURE"), review: Some("CHANGES_REQUESTED"), ..Pr::open(7) @@ -1413,6 +1424,7 @@ mod get_v1_prs { head_ref: "fix/sync".into(), base_ref: "release/1.2".into(), author: Some("hubot".into()), + yours: vec![Yours::Assigned], checks: Some(ChecksState::Failure), review: Some(ReviewState::ChangesRequested), updated_at: pr.updated_at.into(), @@ -1425,8 +1437,10 @@ mod get_v1_prs { #[tokio::test] async fn should_list_no_author_for_a_pr_whose_account_is_gone_200() { let github = MockServer::start_async().await; + // Yours as its reviewer, since no one is its author. let ghost = Pr { author: None, + requested: &[ME], ..Pr::open(7) }; let daemon = synced(&github, &[ghost]).await; @@ -2385,3 +2399,321 @@ mod finished { assert_eq!(pr.repository.name.to_string(), "acme/secret"); } } + +/// Why each kept PR is yours (spec §8): the PRs where your review is requested and those +/// assigned to you sync beside the ones you authored, by the same full and incremental rules +/// and the same age cutoff, and one that stops being yours is Finished. +mod yours { + use super::*; + use crate::support::github::{Whose, mock_since_search, mock_yours}; + + /// Someone else's PR `number` whose review requests name you. + fn requested(number: i64) -> Pr { + Pr { + requested: &[ME], + ..Pr::theirs(number) + } + } + + /// Someone else's PR `number` assigned to you. + fn assigned(number: i64) -> Pr { + Pr { + assignees: &[ME], + ..Pr::theirs(number) + } + } + + /// `pr` with its checks passed and no review awaited, so no sync fetches it again for + /// those. + fn settled(pr: Pr) -> Pr { + Pr { + checks: Some("SUCCESS"), + ..pr + } + } + + /// `pr` last updated on GitHub `days` ago. + fn updated(pr: Pr, days: i64) -> Pr { + Pr { + updated_at: days_ago(days), + ..pr + } + } + + /// Why kept PR `number` of `acme/widgets` is yours, and whether it is Finished. + async fn why(client: &Client, number: u32) -> (Vec, bool) { + let pr = pr_numbered(client, number).await; + (pr.yours, pr.finished) + } + + /// Every incremental search finding `authored`, `requested` and `assigned`, each by its + /// own qualifier. + fn mock_since<'a>( + github: &'a MockServer, + authored: &[Pr], + requested: &[Pr], + assigned: &[Pr], + ) -> Vec> { + vec![ + mock_since_search(github, TOKEN, Whose::Authored, authored), + mock_since_search(github, TOKEN, Whose::ReviewRequested, requested), + mock_since_search(github, TOKEN, Whose::Assigned, assigned), + ] + } + + /// Temp dirs for a daemon whose `gh` prints [`TOKEN`], with `env` set too. + fn dirs_with(env: &[(&str, &str)]) -> TempDir { + let dirs = tempfile::tempdir().expect("a temp dir"); + set_gh_token(dirs.path(), Some(TOKEN)); + set_daemon_env(dirs.path(), env); + dirs + } + + mod full_sync { + use super::*; + + #[tokio::test] + async fn should_keep_prs_you_authored_are_asked_to_review_or_are_assigned_200() { + let github = MockServer::start_async().await; + mock_yours( + &github, + TOKEN, + &[Pr::open(7)], + &[requested(8)], + &[assigned(9)], + ); + let daemon = full_daemon(&github, Some(TOKEN)).await; + + let status = sync(&daemon.client).await; + + assert_eq!(status.last_error, None); + assert_eq!(why(&daemon.client, 7).await, (vec![Yours::Authored], false)); + assert_eq!( + why(&daemon.client, 8).await, + (vec![Yours::ReviewRequested], false) + ); + assert_eq!(why(&daemon.client, 9).await, (vec![Yours::Assigned], false)); + let listed: Vec = list(&daemon.client) + .await + .iter() + .map(|pr| pr.number) + .collect(); + assert_eq!(listed, [7, 8, 9]); + } + + #[tokio::test] + async fn should_give_every_way_a_pr_is_yours_once_200() { + let github = MockServer::start_async().await; + let every_way = Pr { + requested: &[ME], + assignees: &["hubot", ME], + ..Pr::open(7) + }; + let all = std::slice::from_ref(&every_way); + mock_yours(&github, TOKEN, all, all, all); + let daemon = full_daemon(&github, Some(TOKEN)).await; + + sync(&daemon.client).await; + + assert_eq!(kept_prs(&daemon.client).await.len(), 1); + assert_eq!( + why(&daemon.client, 7).await, + ( + vec![Yours::Authored, Yours::ReviewRequested, Yours::Assigned], + false + ) + ); + } + + #[tokio::test] + async fn should_leave_out_review_requests_and_assignments_older_than_the_cutoff_200() { + let github = MockServer::start_async().await; + mock_yours( + &github, + TOKEN, + &[], + &[updated(requested(8), 1), updated(requested(10), 400)], + &[updated(assigned(9), 1), updated(assigned(11), 400)], + ); + let dirs = dirs_with(&[ + ("AGENTDECK_PR_FULL_SYNC_SECS", "0"), + ("AGENTDECK_PR_MAX_AGE_DAYS", "90"), + ]); + let daemon = TestDaemon::start_with_github(dirs, &github.url("/graphql")).await; + + sync(&daemon.client).await; + + assert_eq!(numbers(&daemon.client).await, [8, 9]); + } + } + + mod incremental { + use super::*; + + /// A daemon past its first, full sync of `requested` and `assigned`, whose next sync is + /// incremental; the first sync's mocks are deleted. + async fn synced(github: &MockServer, requested: &[Pr], assigned: &[Pr]) -> TestDaemon { + let mut first = mock_yours(github, TOKEN, &[], requested, assigned); + let daemon = daemon(github, Some(TOKEN)).await; + sync(&daemon.client).await; + first.delete(); + daemon + } + + #[tokio::test] + async fn should_add_prs_you_were_asked_to_review_or_assigned_since_the_last_sync_200() { + let github = MockServer::start_async().await; + let daemon = synced(&github, &[], &[]).await; + let searches = mock_since( + &github, + &[settled(Pr::open(7))], + &[settled(requested(8))], + &[settled(assigned(9))], + ); + + let status = sync(&daemon.client).await; + + assert_eq!(status.last_error, None); + for search in &searches { + search.assert_calls(1); + } + assert_eq!(why(&daemon.client, 7).await, (vec![Yours::Authored], false)); + assert_eq!( + why(&daemon.client, 8).await, + (vec![Yours::ReviewRequested], false) + ); + assert_eq!(why(&daemon.client, 9).await, (vec![Yours::Assigned], false)); + } + + #[tokio::test] + async fn should_leave_out_review_requests_and_assignments_older_than_the_cutoff_200() { + let github = MockServer::start_async().await; + let mut first = mock_yours(&github, TOKEN, &[], &[], &[]); + let dirs = dirs_with(&[("AGENTDECK_PR_MAX_AGE_DAYS", "90")]); + let daemon = TestDaemon::start_with_github(dirs, &github.url("/graphql")).await; + sync(&daemon.client).await; + first.delete(); + mock_since( + &github, + &[], + &[updated(requested(8), 1), updated(requested(10), 400)], + &[updated(assigned(9), 1), updated(assigned(11), 400)], + ); + + sync(&daemon.client).await; + + assert_eq!(numbers(&daemon.client).await, [8, 9]); + } + } + + mod no_longer_yours { + use super::*; + + #[tokio::test] + async fn should_finish_a_pr_whose_review_you_submitted_at_the_next_sync_200() { + let github = MockServer::start_async().await; + let waiting = settled(requested(8)); + let mut first = mock_yours(&github, TOKEN, &[], std::slice::from_ref(&waiting), &[]); + let daemon = daemon(&github, Some(TOKEN)).await; + sync(&daemon.client).await; + first.delete(); + // Reviewed: the request no longer names you, so no search finds it. + mock_since(&github, &[], &[], &[]); + let fetch = mock_fetch(&github, &[settled(Pr::theirs(8))]); + + sync(&daemon.client).await; + + assert!(fetch.calls() >= 1); + assert_eq!(why(&daemon.client, 8).await, (vec![], true)); + assert_eq!(pr_numbered(&daemon.client, 8).await.state, PrState::Open); + assert!(list(&daemon.client).await.is_empty()); + } + + #[tokio::test] + async fn should_finish_a_pr_you_were_unassigned_from_at_a_full_sync_200() { + let github = MockServer::start_async().await; + let mut first = mock_yours(&github, TOKEN, &[], &[], &[assigned(9)]); + let daemon = full_daemon(&github, Some(TOKEN)).await; + sync(&daemon.client).await; + first.delete(); + mock_yours(&github, TOKEN, &[], &[], &[]); + mock_fetch(&github, &[Pr::theirs(9)]); + + sync(&daemon.client).await; + + assert_eq!(why(&daemon.client, 9).await, (vec![], true)); + } + + #[tokio::test] + async fn should_not_finish_a_pr_you_authored_when_its_review_request_goes_200() { + let github = MockServer::start_async().await; + let mine = Pr { + requested: &[ME], + ..Pr::open(7) + }; + let mut first = mock_yours( + &github, + TOKEN, + std::slice::from_ref(&mine), + std::slice::from_ref(&mine), + &[], + ); + let daemon = full_daemon(&github, Some(TOKEN)).await; + sync(&daemon.client).await; + first.delete(); + mock_yours(&github, TOKEN, &[Pr::open(7)], &[], &[]); + + sync(&daemon.client).await; + + assert_eq!(why(&daemon.client, 7).await, (vec![Yours::Authored], false)); + } + + #[tokio::test] + async fn should_delete_it_once_the_finished_window_has_passed_200() { + let github = MockServer::start_async().await; + let mut first = mock_yours(&github, TOKEN, &[], &[requested(8)], &[]); + let dirs = dirs_with(&[ + ("AGENTDECK_PR_FULL_SYNC_SECS", "0"), + ("AGENTDECK_PR_FINISHED_SECS", "0"), + ]); + let daemon = TestDaemon::start_with_github(dirs, &github.url("/graphql")).await; + sync(&daemon.client).await; + assert_eq!(numbers(&daemon.client).await, [8]); + first.delete(); + mock_yours(&github, TOKEN, &[], &[], &[]); + mock_fetch(&github, &[Pr::theirs(8)]); + + sync(&daemon.client).await; + + assert_eq!(numbers(&daemon.client).await, Vec::::new()); + let repositories = (daemon.client.repository_list().send().await) + .expect("list Repositories") + .into_inner(); + assert!(repositories.is_empty(), "{repositories:?}"); + } + + #[tokio::test] + async fn should_stop_being_finished_once_it_is_yours_again_200() { + let github = MockServer::start_async().await; + let mut first = mock_yours(&github, TOKEN, &[], &[requested(8)], &[]); + let daemon = full_daemon(&github, Some(TOKEN)).await; + sync(&daemon.client).await; + first.delete(); + let mut reviewed = mock_yours(&github, TOKEN, &[], &[], &[]); + let mut fetch = mock_fetch(&github, &[Pr::theirs(8)]); + sync(&daemon.client).await; + assert_eq!(why(&daemon.client, 8).await, (vec![], true)); + reviewed.delete(); + fetch.delete(); + // Asked again, after changes. + mock_yours(&github, TOKEN, &[], &[requested(8)], &[]); + + sync(&daemon.client).await; + + assert_eq!( + why(&daemon.client, 8).await, + (vec![Yours::ReviewRequested], false) + ); + } + } +} diff --git a/crates/agentdeckd/tests/integration/support/github.rs b/crates/agentdeckd/tests/integration/support/github.rs index 2041180..cd50d48 100644 --- a/crates/agentdeckd/tests/integration/support/github.rs +++ b/crates/agentdeckd/tests/integration/support/github.rs @@ -12,6 +12,9 @@ use httpmock::prelude::*; use httpmock::{Mock, MockServer}; use serde_json::{Value, json}; +/// The signed-in login in these tests: GitHub answers each query for PRs as this viewer. +pub const ME: &str = "octocat"; + /// A GraphQL endpoint nothing listens on, for daemons that aren't testing PR sync. pub const UNREACHABLE: &str = "http://127.0.0.1:9/graphql"; @@ -266,6 +269,10 @@ pub struct Pr { pub checks: Option<&'static str>, pub review: Option<&'static str>, pub updated_at: &'static str, + /// The logins its review requests name (a team's names none). + pub requested: &'static [&'static str], + /// Its assignees' logins. + pub assignees: &'static [&'static str], } /// The id GitHub gives Repository `repo` in these tests: the same for the same name. @@ -278,8 +285,8 @@ pub fn repository_id(repo: &str) -> u64 { } impl Pr { - /// An open PR on `acme/widgets` from `feat/sync` into `main`, opened by `octocat`, with no - /// checks and no review. + /// An open PR on `acme/widgets` from `feat/sync` into `main`, opened by [`ME`], with no + /// checks, no review, no review requests and no assignees. pub fn open(number: i64) -> Pr { Pr { repo: "acme/widgets", @@ -295,6 +302,16 @@ impl Pr { checks: None, review: None, updated_at: "2026-11-01T10:00:00Z", + requested: &[], + assignees: &[], + } + } + + /// Open PR `number` that someone else opened and that is yours only as `pr` makes it. + pub fn theirs(number: i64) -> Pr { + Pr { + author: Some("hubot"), + ..Pr::open(number) } } @@ -334,6 +351,12 @@ impl Pr { "baseRefName": self.base_ref, "updatedAt": self.updated_at, "author": self.author.map(|login| json!({ "login": login })), + "reviewRequests": { "nodes": self.requested.iter() + .map(|login| json!({ "requestedReviewer": { "login": login } })) + .collect::>() }, + "assignees": { "nodes": self.assignees.iter() + .map(|login| json!({ "login": login })) + .collect::>() }, "repository": { // A `BigInt`, which GraphQL writes as a string. "fullDatabaseId": self.repository_id().to_string(), @@ -388,13 +411,15 @@ pub fn mock_search<'a>(server: &'a MockServer, token: &str, prs: &[Pr]) -> Listi } /// The list of the viewer's open PRs, one page with `prs` for `token`, and their details by -/// number. An incremental search doesn't match it. +/// number; the full sync's searches for PRs where your review is requested or that are +/// assigned to you find none. An incremental search doesn't match it. pub fn mock_list<'a>(server: &'a MockServer, token: &str, prs: &[Pr]) -> Listing<'a> { let list = mock_list_page(server, token, prs, None, None, prs.len(), Duration::ZERO); - let others = prs + let mut others: Vec> = prs .chunks(BATCH) .map(|batch| mock_fetch(server, batch)) .collect(); + others.extend(mock_open_searches(server, token, &[], &[])); Listing { list, others } } @@ -418,7 +443,7 @@ pub fn mock_list_page<'a>( .body_includes("pullRequests(") .json_body_includes(json!({ "variables": { "after": after } }).to_string()); then.status(200).delay(delay).json_body(json!({ - "data": { "viewer": { "pullRequests": { + "data": { "viewer": { "login": ME, "pullRequests": { "totalCount": total, "pageInfo": { "hasNextPage": next.is_some(), "endCursor": next }, "nodes": nodes @@ -427,23 +452,141 @@ pub fn mock_list_page<'a>( }) } -/// The incremental search for the viewer's PRs updated since the last sync, answered with -/// `prs` for `token`. +/// Every incremental search for the viewer's PRs updated since the last sync (authored, +/// review requested and assigned alike), answered with `prs` for `token`. pub fn mock_updated_search<'a>(server: &'a MockServer, token: &str, prs: &[Pr]) -> Mock<'a> { - let nodes: Vec = prs.iter().map(Pr::node).collect(); server.mock(|when, then| { when.method(POST) .path("/graphql") .header("authorization", format!("Bearer {token}")) .body_includes("search(") .body_includes("updated:>="); - then.status(200).json_body(json!({ - "data": { "search": { + then.status(200).json_body(search_body(prs)); + }) +} + +/// Whose PRs a search asks for, by its qualifier. +#[derive(Clone, Copy, Debug)] +pub enum Whose { + /// `author:@me`. + Authored, + /// `user-review-requested:@me`. + ReviewRequested, + /// `assignee:@me`. + Assigned, +} + +impl Whose { + fn qualifier(self) -> &'static str { + match self { + Whose::Authored => "author:@me", + Whose::ReviewRequested => "user-review-requested:@me", + Whose::Assigned => "assignee:@me", + } + } +} + +/// A full sync's search for `whose` open PRs, most recently updated first, answered with +/// `prs` (one page) for `token`. +pub fn mock_open_search<'a>( + server: &'a MockServer, + token: &str, + whose: Whose, + prs: &[Pr], +) -> Mock<'a> { + server.mock(|when, then| { + when.method(POST) + .path("/graphql") + .header("authorization", format!("Bearer {token}")) + .body_includes("search(") + .body_includes("is:open") + .body_includes("sort:updated-desc") + .body_includes(whose.qualifier()); + then.status(200).json_body(search_body(prs)); + }) +} + +/// A full sync's searches for open PRs where your review is requested, answered with +/// `requested`, and assigned to you, answered with `assigned`. +pub fn mock_open_searches<'a>( + server: &'a MockServer, + token: &str, + requested: &[Pr], + assigned: &[Pr], +) -> Vec> { + vec![ + mock_open_search(server, token, Whose::ReviewRequested, requested), + mock_open_search(server, token, Whose::Assigned, assigned), + ] +} + +/// An incremental search for `whose` PRs updated since the last sync, answered with `prs` +/// for `token`. +pub fn mock_since_search<'a>( + server: &'a MockServer, + token: &str, + whose: Whose, + prs: &[Pr], +) -> Mock<'a> { + server.mock(|when, then| { + when.method(POST) + .path("/graphql") + .header("authorization", format!("Bearer {token}")) + .body_includes("search(") + .body_includes("updated:>=") + .body_includes(whose.qualifier()); + then.status(200).json_body(search_body(prs)); + }) +} + +/// The viewer's PRs, each way they are yours, however the daemon asks for `token`: the list +/// and the open searches (a full sync) with `authored`, `requested` and `assigned`, every +/// incremental search finding none, and each PR's details by number. Create it before any +/// other mock of the same searches, since the first mock that matches answers. +pub fn mock_yours<'a>( + server: &'a MockServer, + token: &str, + authored: &[Pr], + requested: &[Pr], + assigned: &[Pr], +) -> Listing<'a> { + let mut others = mock_open_searches(server, token, requested, assigned); + for whose in [Whose::Authored, Whose::ReviewRequested, Whose::Assigned] { + others.push(mock_since_search(server, token, whose, &[])); + } + // The list's new PRs are fetched together, in its order; the rest one at a time. + others.extend( + authored + .chunks(BATCH) + .map(|batch| mock_fetch(server, batch)), + ); + for pr in requested.iter().chain(assigned) { + others.push(mock_fetch(server, std::slice::from_ref(pr))); + } + let list = mock_list_page( + server, + token, + authored, + None, + None, + authored.len(), + Duration::ZERO, + ); + Listing { list, others } +} + +/// A search's response body: one page holding `prs`, as [`ME`] sees them. +fn search_body(prs: &[Pr]) -> Value { + let nodes: Vec = prs.iter().map(Pr::node).collect(); + json!({ + "data": { + "viewer": { "login": ME }, + "search": { "issueCount": nodes.len(), "pageInfo": { "hasNextPage": false, "endCursor": null }, "nodes": nodes - } } - })); + } + } }) } @@ -452,11 +595,12 @@ pub fn mock_updated_search<'a>(server: &'a MockServer, token: &str, prs: &[Pr]) pub fn mock_fetch<'a>(server: &'a MockServer, prs: &[Pr]) -> Mock<'a> { let first = &prs[0]; let (owner, name) = first.repo.split_once('/').expect("owner/name"); - let data: serde_json::Map = prs + let mut data: serde_json::Map = prs .iter() .enumerate() .map(|(i, pr)| (format!("p{i}"), json!({ "pullRequest": pr.node() }))) .collect(); + data.insert("viewer".into(), json!({ "login": ME })); server.mock(|when, then| { when.method(POST) .path("/graphql") @@ -485,7 +629,7 @@ pub fn mock_hidden<'a>(server: &'a MockServer, token: &str, pr: &Pr) -> Mock<'a> json!({ "variables": { "o0": owner, "r0": name, "n0": pr.number } }).to_string(), ); then.status(200).json_body(json!({ - "data": { "p0": null }, + "data": { "viewer": { "login": ME }, "p0": null }, "errors": [ { "type": "NOT_FOUND", "path": [ "p0" ], "message": message } ] })); }) @@ -559,7 +703,8 @@ pub fn mock_viewer<'a>( when.method(POST) .path("/graphql") .header("authorization", format!("Bearer {token}")) - .body_includes("viewer { login }"); + // The token check alone: queries for PRs ask for the viewer's login too. + .json_body_includes(json!({ "query": "query { viewer { login } }" }).to_string()); let then = then .status(200) .json_body(json!({ "data": { "viewer": { "login": login } } })); diff --git a/crates/xtask/src/client.rs b/crates/xtask/src/client.rs index 15dc077..b670313 100644 --- a/crates/xtask/src/client.rs +++ b/crates/xtask/src/client.rs @@ -22,6 +22,7 @@ const CORE_TYPES: &[&str] = &[ "PrState", "ChecksState", "ReviewState", + "Yours", "PaneKind", "Agent", "AgentState", diff --git a/docs/spec.md b/docs/spec.md index 9b928a6..bc1927b 100644 --- a/docs/spec.md +++ b/docs/spec.md @@ -88,11 +88,14 @@ CREATE TABLE pull_requests ( -- a pull request PR sync keeps (§8), name head_ref TEXT NOT NULL, -- the branch it merges from base_ref TEXT NOT NULL, -- the branch it merges into author TEXT, -- the GitHub login that opened it; NULL once that account is gone + authored INTEGER NOT NULL DEFAULT 0, -- why it's yours (§8): you opened it, + review_requested INTEGER NOT NULL DEFAULT 0, -- a review request names you, + assigned INTEGER NOT NULL DEFAULT 0, -- you're an assignee; all 0 once it's yours no way checks TEXT, -- pending|success|failure|NULL review TEXT, -- approved|changes_requested|review_required|NULL updated_at TEXT NOT NULL, -- GitHub's synced_at TEXT NOT NULL, - finished_at TEXT, -- when it became Finished (§8); NULL while open within the age cutoff + finished_at TEXT, -- when it became Finished (§8); NULL while open, yours and within the age cutoff unreachable_at TEXT, -- when a full sync found the GitHub sign-in can't see it (§8); NULL otherwise PRIMARY KEY (repository_id, number) ); @@ -102,7 +105,7 @@ CREATE TABLE pr_sync ( -- at most one row ); ``` -**Migrations:** `0001` creates the schema as the domain reset left it, with each Workspace's folder (`dir`, an absolute path, and `dir_owned`, whether agentdeck made it as a scratch folder). The domain reset squashed every earlier migration into it (they made `notes`, then `comments` and `instructions`, `tasks` with their PR rows keyed by task, and added each column above in turn); a database from before it isn't migrated but moved aside (§2). The removed code and migrations are in the tag `pre-domain-reset`. `0002` drops `dir` and `dir_owned`, keeping every Workspace with its tabs, Panes and Links, and touches nothing on disk: scratch folders stay (§2). +**Migrations:** `0001` creates the schema as the domain reset left it, with each Workspace's folder (`dir`, an absolute path, and `dir_owned`, whether agentdeck made it as a scratch folder). The domain reset squashed every earlier migration into it (they made `notes`, then `comments` and `instructions`, `tasks` with their PR rows keyed by task, and added each column above in turn); a database from before it isn't migrated but moved aside (§2). The removed code and migrations are in the tag `pre-domain-reset`. `0002` drops `dir` and `dir_owned`, keeping every Workspace with its tabs, Panes and Links, and touches nothing on disk: scratch folders stay (§2). `0003` adds why each Pull request is yours (`authored`, `review_requested`, `assigned`), marking every PR kept before it `authored`, as PR sync had found each as one you opened; the next sync reads all three from GitHub. A **Workspace** is a name, the Repositories it links (possibly none) and its Panes. It has **no folder**: no scratch folder and no attached one. Its Panes start where the client says (§6, §11) and work in whatever folder they move to, so its agents can work in any repo. Creating, renaming, archiving or deleting a Workspace makes, moves or removes nothing on disk. @@ -114,11 +117,11 @@ An agent pane runs its agent only until its process exits. An exited agent pane 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 **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. +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). A **Link** ties one Workspace to one Repository, at most once per pair; the user makes it (§4, §10), and it goes with its Workspace. A Repository row exists while a Link or a kept PR names it: linking a Repository agentdeck doesn't know stores it, as GitHub shows it (§8), and the daemon deletes it once neither names it, when its last Link goes (by an unlink or with its Workspace) and no kept PR belongs to it, or when PR sync deletes its last PR and no Link names it (below). An archived Workspace keeps its Links. -A PR is **Finished** (`finished_at` set) while it is merged or closed, or open but not updated within the age cutoff (§8). PR sync deletes it 7 days after it became Finished, then deletes its Repository when no Link and no kept PR references it any more, as an unlink does (§4). +A PR is **Finished** (`finished_at` set) while it is merged or closed, open but no longer yours (your review submitted or its request withdrawn, you unassigned), or open but not updated within the age cutoff (§8). PR sync deletes it 7 days after it became Finished, then deletes its Repository when no Link and no kept PR references it any more, as an unlink does (§4). A **Suggestion** is a Repository one of a Workspace's Panes works in that the Workspace doesn't link (§4 `GET /v1/workspaces/{id}/suggestions`, §11). The daemon works them out from what it already knows, and stores nothing: - **Which folders count:** every Pane in the Workspace's tabs at its current folder (§6), an exited one at its last known folder. Nothing else on disk is looked at: no root such as `~/Code` is scanned. @@ -134,6 +137,8 @@ v1.1 adds `channels`, `channel_members` and `messages` in their own migration. Every pane in a response (`POST` and `GET` on `/v1/panes`) carries `hosted_agent`: `claude` or `codex` while a shell pane hosts that agent (§3, §7), else null. It came with `API_VERSION` 6. Every pane also carries `folder`, its current folder (§3, §6), an absolute path; it came with `API_VERSION` 18. +`API_VERSION` 28 added why each Pull request is yours (§3, §8): every `PullRequest` carries `yours`, and `GET /v1/prs` lists the PRs where your review is requested and those assigned to you beside the ones you authored. An older daemon sends no `yours`, which the client reads as empty, and keeps only the PRs you authored; an older client ignores the field, and lists the new PRs as it lists any. + `API_VERSION` 27 added the GitHub repository list (§8) for the Link picker's All your repositories (§11): `GET /v1/github/repositories`, `POST /v1/github/repositories/refresh` and the `github_repositories` change event (§5). An older daemon answers both routes with its code-less 404, so the GUI's picker reads "Couldn't load your repositories." until its Restart banner (§2) is followed; an older client skips the event. `API_VERSION` 26 added a Workspace's Suggestions (§3): `GET /v1/workspaces/{id}/suggestions` and the `suggestions` change event (§5). An older daemon answers the route with its code-less 404, which the client reads as no Suggestions, so the GUI shows none there until its Restart banner (§2) is followed; an older client skips the event. @@ -163,7 +168,7 @@ Every pane in a response (`POST` and `GET` on `/v1/panes`) carries `hosted_agent | `POST /v1/panes/{id}/stop` | stop the pane's agent and keep the pane: its row, layout place and `session_id` stay. In an agent pane, its process gets the kill `DELETE` sends (SIGHUP to its process group and the foreground one, then SIGKILL after 3 s), and the pane reads `exited` once it has exited (§7), so **Restart agent** (`respawn` with `run: "agent"`) resumes its session later and a restarting daemon doesn't resume it (§6). In a shell pane hosting an agent (§7), only the hosted agent stops: its process group, the foreground one, gets SIGHUP, then SIGKILL after 3 s if it is still in the foreground; the shell keeps running and `hosted_agent` goes back to null. 204 once the signal is sent; the `state` and `exit` events (or `changed` for the hosted agent) follow. 409 `exited` when the process has already exited, 409 `no_agent` for a shell pane hosting no agent (the shell isn't stopped). It came with `API_VERSION` 12 | | `POST /v1/panes/{id}/input` | `{text, when: "now"|"idle", submit}` (`now` and `false` by default): without `submit`, typed into the PTY as is. With `submit: true`, `text` is a message, typed in two writes: `text` (trailing newlines are the caller's to trim) as one bracketed paste (`ESC[200~…ESC[201~`, any ESC in it removed) when the pane's program has bracketed paste on (DECSET 2004, as the daemon's `Term` tracks it), else as is; then Enter (`\r`) as a write of its own, 200 ms later, followed by another 200 ms before anything else is typed. Claude Code and Codex take text arriving with its Enter in one read as a paste and keep the Enter as a newline, so `text` ending in `\r` without `submit` is never submitted there. `idle` queues until the pane is idle, done or blocked, and is typed at once if it already is. 202 `{queued}`. Queued text is dropped if the process exits, or when an agent starts or stops being hosted in a shell pane (§7) | | `GET /v1/panes/{id}/tail?bytes=` | raw output tail (256 KiB ring) for `agentdeck tail`, as `application/octet-stream`; all of it without `bytes` | -| `GET /v1/prs?repository=&workspace=&finished=` | the pull requests PR sync keeps, each a `PullRequest`: `reference` (`owner/name#123`, by its Repository's name now), `number`, `repository` (`{ id, name, url, private, archived }`: GitHub's id, `owner/name`, its page, and whether it is private and archived), `title`, `url`, `state`, `draft`, `head_ref`, `base_ref`, `author` (the login that opened it, null once that account is gone), `checks`, `review`, `updated_at` (GitHub's), `unreachable` and `finished` (Finished, §8; it came with `API_VERSION` 20, and a client reads its absence as false), as last synced (§8). Ordered by Repository name ignoring case, then number. Finished PRs are left out unless `finished=true` (`API_VERSION` 20; an older daemon ignores it and lists every kept PR). `repository` (`owner/name`, or its GitHub URL) keeps only that Repository's, by the name GitHub gives it now, ignoring case: none for a name agentdeck doesn't know. Text that names no Repository is dropshot's own 400. `workspace` (an id) keeps only the PRs of the Repositories that Workspace links (from `API_VERSION` 19); one that doesn't exist is `unknown_workspace`. Given both, a PR must pass both. It came with `API_VERSION` 16 | +| `GET /v1/prs?repository=&workspace=&finished=` | the pull requests PR sync keeps (yours: authored, review requested or assigned, §8), each a `PullRequest`: `reference` (`owner/name#123`, by its Repository's name now), `number`, `repository` (`{ id, name, url, private, archived }`: GitHub's id, `owner/name`, its page, and whether it is private and archived), `title`, `url`, `state`, `draft`, `head_ref`, `base_ref`, `author` (the login that opened it, null once that account is gone), `yours` (why it is yours, §8: any of `authored`, `review_requested` and `assigned`, in that order; empty once it is none of these, when it is Finished; it came with `API_VERSION` 28, and a client reads its absence as empty), `checks`, `review`, `updated_at` (GitHub's), `unreachable` and `finished` (Finished, §8; it came with `API_VERSION` 20, and a client reads its absence as false), as last synced (§8). Ordered by Repository name ignoring case, then number. Finished PRs are left out unless `finished=true` (`API_VERSION` 20; an older daemon ignores it and lists every kept PR). `repository` (`owner/name`, or its GitHub URL) keeps only that Repository's, by the name GitHub gives it now, ignoring case: none for a name agentdeck doesn't know. Text that names no Repository is dropshot's own 400. `workspace` (an id) keeps only the PRs of the Repositories that Workspace links (from `API_VERSION` 19); one that doesn't exist is `unknown_workspace`. Given both, a PR must pass both. It came with `API_VERSION` 16 | | `POST /v1/prs/sync?full=` | sync now, after any sync running; with `full=true` the sync is full whatever sync is due (§8; it came with `API_VERSION` 14, and an older daemon ignores it). `GET /v1/prs/status` reports whether GitHub accepts the token (§8), the last sync, the age cutoff and `synced_as`, the login the last good sync ran as (it came with `API_VERSION` 15; absent before any sync GitHub named a login for) | | `POST /v1/prs/close` | close PRs on GitHub (§8), named by reference: `{ prs: ["owner/name#123", …] }` → `{ results: [{ pr, ok, error? }] }`, one result per reference in the order asked, each `pr` the reference asked for, in `owner/name#123` form; 200 even when some failed. A PR's GitHub URL works as a reference too. Text that names no PR is dropshot's own 400 and closes nothing. It took task ids before `API_VERSION` 16 | | `GET /v1/github/auth` | where the GitHub token comes from (§8): `{ source: "keyring"\|"env"\|"gh"\|"none", env_var?, login?, scopes?, rejected, client_id_set }`. `env_var` names `GH_TOKEN` or `GITHUB_TOKEN` whenever one is set, also while a saved token overrides it; `login` and `scopes` come from GitHub's answer to the token, `scopes` from `X-OAuth-Scopes` and absent for a token that sends none (fine-grained); `rejected` is true while GitHub rejects the token `source` gives, so a token GitHub couldn't be asked about (no `login` either) is never mistaken for one it refused (it came with `API_VERSION` 9; a client reads its absence as false); `client_id_set` is true while the keyring or `AGENTDECK_GITHUB_CLIENT_ID` gives a client ID. It never carries the token or the client ID | @@ -323,21 +328,24 @@ min_ms = 400 # a new state must hold this long before it is pu - **Keyring entries** are under the service `agentdeck`. The token's is named `github.com/`, so a later version can hold more than one account; v1 holds one, and saving a token deletes any other `github.com/` entry. The daemon finds it by searching the service's entries, so no file names the login. The OAuth client ID is a separate entry, `oauth-client-id@github.com` (no GitHub login holds an `@`). - **No keyring** (headless, or no Secret Service on the session bus): reading finds no saved token and goes on to the environment. Saving a token or a client ID, and starting a sign-in, is `503 no_keyring`: "No system keyring is running, so agentdeck can't save a token. Set GH_TOKEN in agentdeckd's environment instead." - **Pasting a token** (`PUT /v1/github/token`): the daemon checks it with `viewer { login }` before saving. A 401 is `422 invalid_token` ("GitHub didn't accept this token.") and saves nothing; any other failure is `502 github_error`. GitHub's `X-OAuth-Scopes` says what a classic token may do. One without `repo` or `public_repo` still saves, and clients warn "PR sync works; closing PRs needs repo". A fine-grained token sends no scopes header; it saves, and clients note "Closing works only on repos you own". Clients show both from `scopes`, for whichever source gives the token. +- **Whose PRs:** yours, on any repository: the ones you authored, the ones whose review requests name you, and the ones assigned to you. Each stores why it is yours (`yours`, §3, §4), any of `authored`, `review_requested` and `assigned`, read from every read of it (the list's light fields included) as its author's login, the logins its review requests name (`reviewRequests`, a user's `login`; a team's request names none) and its assignees' logins (`assignees`), each against the viewer's login, matched ignoring case. Every query for PRs (the list, each search, each fetch by number) asks for `viewer { login }` beside them, so the login is the token's as GitHub answers, with no request of its own. Review requests are found with `user-review-requested:@me`, not `review-requested:@me`, which also finds the requests to a team you're on: those name no login, so such a PR would be read as not yours and Finished at once (requests to your teams are tracked in [#408](https://github.com/bRRRITSCOLD/agentdeck/issues/407)). Only PRs you authored alert (§11); review requests and assignments don't, since GitHub already notifies them. - A sync every 120 s (the first at start), and on `POST /v1/prs/sync`. One sync runs at a time. - **Asked for:** Sync now on the Pull requests view and `agentdeck pr sync` send `?full=true`, so the sync is full whatever sync is due: a PR stored in the wrong state that GitHub hasn't updated since, which no incremental search finds, is put right at once rather than at the hourly full sync. A request that comes while a sync runs gets a full sync right after it, as a widened cutoff does, and answers once that one finishes; one that fails leaves the next sync full. Without `full`, the request runs the sync that is due. An older daemon ignores `full`. `AGENTDECK_GITHUB_API` replaces the GraphQL URL (`https://api.github.com/graphql`) and `AGENTDECK_GITHUB_REST_API` the REST API's base URL (`https://api.github.com`); tests point both at httpmock. A request gives up after 30 s; `AGENTDECK_GITHUB_TIMEOUT_MS` replaces that (tests use it). - **Age cutoff:** only PRs GitHub updated in the last `max_age_days` days sync: the setting `pr_sync.max_age_days` (§2), default `90`, `0` for no cutoff. Each sync reads it as it begins, so a PATCH applies to the next sync, and widening it (more days, or `0` where there was a cutoff) starts a full sync at once, after any sync running, so the older open PRs it now lets in arrive without waiting for the hourly full sync. Narrowing it waits for the next sync. `AGENTDECK_PR_MAX_AGE_DAYS` overrides the file (tests use it); empty is the same as unset, and a value that isn't a count of days is logged and ignored. The cutoff is that many days before the sync began. - - **Full:** the first sync, the first after an hour since the last full one (`AGENTDECK_PR_FULL_SYNC_SECS`, `0` for every sync), the next one after the age cutoff widens, one asked for with `full`, and the first with another token than the last good sync ran with or after a sync found none (a sign-in, a sign-out then a sign-in, a token pasted, `gh` logged in to another account), so every PR is checked again with what the new sign-in can see at once; in two phases. First the list `viewer.pullRequests(states: OPEN)`, 100 a page, most recently updated first, with light fields only (no review, no checks); each page is stored as it arrives, a stored PR keeping its review and checks. The list stops at the first PR updated before the cutoff: neither it nor anything after it is stored, and no later page is read. Then every field, fetched by number, for the PRs that are new, that GitHub updated since they were stored, or that are unsettled (below). - - **Incremental:** the rest search `is:pr author:@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. A merged or closed PR not stored as open is skipped, and so is any PR updated before the cutoff. Then the unsettled open PRs the search left out, 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. Each incremental sync costs one more request per 25 unsettled PRs. + - **Full:** the first sync, the first after an hour since the last full one (`AGENTDECK_PR_FULL_SYNC_SECS`, `0` for every sync), the next one after the age cutoff widens, one asked for with `full`, and the first with another token than the last good sync ran with or after a sync found none (a sign-in, a sign-out then a sign-in, a token pasted, `gh` logged in to another account), so every PR is checked again with what the new sign-in can see at once; in two phases. First the list of the PRs you authored, `viewer.pullRequests(states: OPEN)`, 100 a page, most recently updated first, with light fields only (no review, no checks); each page is stored as it arrives, a stored PR keeping its review and checks. The list stops at the first PR updated before the cutoff: neither it nor anything after it is stored, and no later page is read. Then two searches, `is:pr is:open user-review-requested:@me sort:updated-desc` and `is:pr is:open assignee:@me sort:updated-desc`, 50 a page with every field, each page stored as it arrives, each stopping at the first PR updated before the cutoff as the list does. Then every field, fetched by number, for the listed PRs that are new, that GitHub updated since they were stored, or that are unsettled (below), but for those a search has just read whole. + - **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. - `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`) and its author's login (`author`, null once the account is gone). 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" are worked out by Repository id and number after the list is 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. A PR GitHub gives no Repository id for (`fullDatabaseId` null) can't be stored and is left out. - 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:** the PR is stored as GitHub shows it. In a full sync, PRs that left the list are fetched by number, once. Fetches by number go 25 to a request, 4 requests at a time. + - **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. - - **Finished:** a kept PR becomes Finished (`finished_at` set to when the sync stored it so) once the sync stores it merged or closed, 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 was last updated before the cutoff is not fetched: it is Finished instead, still `open`, once (a `changed` event). Nothing changes on GitHub. A Finished PR stays Finished from the first time it was, until GitHub shows it open within the cutoff (in the list or a search): then it is no longer Finished. + - **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). -- A sync stores each page as it arrives, and each PR it stores for the first time or changes gets a `changed` `pull_request` event (§5) then. While it runs, the status's `progress` is `{ prs_done, prs, stage }` (`prs` from the search's count, `0` until the first page answers; `stage` is `listing`, then `details` while reviews and checks are fetched by number), and every change to it sends a `pr_sync` event. Clients show it: "Syncing… 100 of 271 PRs", then "Syncing details…". +- A sync stores each page as it arrives, and each PR it stores for the first time or changes gets a `changed` `pull_request` event (§5) then. While it runs, the status's `progress` is `{ prs_done, prs, stage }` (`prs_done` the PRs read so far, each once however many of the list and searches show it; `prs` the counts of the list and searches read to their end plus the count of the one being read, `0` until the first page answers; `stage` is `listing`, then `details` while reviews and checks are fetched by number), and every change to it sends a `pr_sync` event. Clients show it: "Syncing… 100 of 271 PRs", then "Syncing details…". - **Sign in with GitHub** is the OAuth device flow, asking for the scope `repo` once. - **Client ID:** the user registers an OAuth App on GitHub, with Enable Device Flow on and no client secret. Its client ID is never committed: the user enters it in Settings, and it is saved in the keyring (`PUT /v1/github/client-id`) like the token. `AGENTDECK_GITHUB_CLIENT_ID` gives it while none is saved; a saved one wins, as the token does. With neither, `POST /v1/github/device` is `409 no_client_id`, and clients hide Sign in. `PUT` refuses a blank one, and one shaped like a user code (`^[A-Z0-9]{4}-[A-Z0-9]{4}$`, as `WDJB-MJHT`: the sign-in's code, pasted in by mistake), with `400 invalid_client_id`: "The OAuth client ID is blank." or "That looks like the sign-in code, not a client ID.", and saves nothing. No error or log line names the client ID. - **Start:** `POST /v1/github/device` checks that the keyring can save, then asks GitHub for a device code (`POST https://github.com/login/device/code` with the `client_id` and `scope=repo`) and answers `{ user_code, verification_uri, expires_at }`. A refusal (Device Flow off) is `502 github_error` with GitHub's `error_description`, else its `error`. A client ID GitHub doesn't know gets a 404 `{"error":"Not Found"}` with no description, which tells the user nothing, so a 404 or a bare `Not Found` is `502 github_error` with "GitHub doesn't know this OAuth client ID. Check it in Settings → GitHub." `AGENTDECK_GITHUB_OAUTH` replaces `https://github.com`; tests point it at httpmock. @@ -397,7 +405,7 @@ agentdeck tail [--bytes N] - `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. -- `pr ls` lists the pull requests agentdeck keeps that aren't Finished (§8) with `GET /v1/prs` (§4), with `--repo` only that Repository's and with `--ws` only those of the Repositories that workspace links: a line per PR under `PR STATE TITLE`, the PR by its reference and its state `open`, `draft` (an open draft), `merged` or `closed`, then `, unreachable` while the GitHub sign-in can't see it (§8); "no pull requests" when there are none. With `--json` it prints the list of `PullRequest` objects. +- `pr ls` lists the pull requests agentdeck keeps that aren't Finished (§8), the ones you authored, review or are assigned alike, with `GET /v1/prs` (§4), with `--repo` only that Repository's and with `--ws` only those of the Repositories that workspace links: a line per PR under `PR STATE TITLE`, the PR by its reference and its state `open`, `draft` (an open draft), `merged` or `closed`, then `, unreachable` while the GitHub sign-in can't see it (§8); "no pull requests" when there are none. With `--json` it prints the list of `PullRequest` objects, each with `yours`, why it is yours (§4). - `pr close` closes the pull requests it names with `POST /v1/prs/close` (§8). Without `--yes` it first prints "Close N PRs on GitHub? Their repos' owners will see them closed. You can reopen a PR on GitHub." then a line per repo with its count (" acme/widgets 2 PRs"), and asks `[y/N]` on stderr; anything but `y` closes nothing, prints "Closed nothing" and exits 0. Without `--yes` and with no terminal on stdin, it is an error that names `--yes`. It prints `closed ` or `failed : ` per PR, by its reference (`closed acme/widgets#7`), then "Closed 12 of 14" when any failed, and exits 1 then; `--json` prints the results object. - `daemon restart` restarts the daemon as §2 says (starting one when none runs) and prints `restarted agentdeckd, now pid `, or `{pid, version, api_version}` with `--json`. - **Inside a Pane** `agentdeck` is on `PATH` (§6), and `$XDG_RUNTIME_DIR` from the Pane's environment leads it to the same daemon, so an agent runs it like any other command. `AGENTDECK_PANE` and `AGENTDECK_WORKSPACE` are set in every pane's environment, added on top of the allowlist (§6). No command defaults from them. @@ -552,11 +560,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), layout tree, snapshot encode/decode round-trip, env allowlist, `openapi.json` staleness; GUI views over a fake API and a fake notifier, asserting what a user sees (the Pull requests view's groups and their order, collapse and Show finished kept in the GUI state file, Finished rows hidden until Show finished and showing GitHub's state, the row's link and menu, Sync now, the banner, the empty state, Unreachable rows; Select mode: entering and leaving it, picking by row click, group checkbox (folded too) and select-all, which rows can be picked (open and reachable, Finished-but-open included; not merged, closed or Unreachable), the bar's count and order, Copy PR details joined in the list's order, Close PRs asking then closing by reference, a PR that didn't close kept picked and marked with why, a closed PR shown closed at once, "Closing N of M…", and Select disabled on the empty view; the header and the table fitting the narrowest window in Select mode, and that window's minimum fitting the narrowest PR table in Select mode; the sidebar's entries and counts, Finished PRs left out, no Inbox or Tasks entry, each Workspace's count over its linked Repositories, none on an archived row, the no-Workspaces hint and its New workspace, Pull requests the fallback selection; linked groups first, then Not in a workspace, each alphabetical, a group's header naming its linking Workspaces as links that open their Pull requests, Archived Workspaces absent from headers and order; the group `…` menu on every group of both views, in the rows' `…` column: Open on GitHub opening the Repository's page, Link to a workspace offering the Workspaces that aren't archived and don't link it in the sidebar's order then New workspace, New workspace alone when none is eligible, New workspace opening the dialog with the Repository picked, a link applied at once by GitHub's id with "Linked owner/name to " and an Undo that unlinks, Unlink from this workspace only on a Workspace's Pull requests, applied at once with "Unlinked owner/name from " and its open PRs (singular, plural, none, and where they went when no other Workspace links it), its Undo linking again by id once the unlink deleted the Repository, and failures toasted; a Workspace's side switch with its count, `secondary-shift-p`, each Workspace's side remembered across a restart and opened from its sidebar row, a new one on its Panes; a Workspace's Pull requests: only its linked Repositories, "No open PRs", Select, Show finished and Edit workspace with no sync controls, the banner, collapse kept apart from the Pull requests view's, the no-Repositories state whose Link repository opens Edit workspace with its picker focused and open; Edit workspace and New workspace: the linked rows with their Unlink, lock and Unreachable badge, staging until Save (one request with the name, applied to the fake, none before), Save enabled by a staged change alone, Undo, the leaving note and its singular and its absence at 0, Cancel discarding what was staged, a refusal under the picker keeping the dialog open, an archived workspace linked, the picker's From your pull requests (no linked, picked or Unreachable Repository; the lock), local filtering ignoring case and by a pasted URL, picking (the field cleared), Enter picking the first row, the typed row only for an unlisted name, GitHub showing it (staged under GitHub's name, private kept) or not ("GitHub can't see …" under the field, the list closed, cleared by typing), signed out (no typed row, "Sign in to GitHub to find more repositories."), and New workspace linking what was picked on create; the picker's Suggested section first, ignoring dismissals, its rows left out of From your pull requests, filtered as typed, picked by click or Enter; its All your repositories after the other sections (none listed above, linked or Unreachable; the lock), filtered as typed, picked by click or Enter, no typed row for a name it lists, a refresh asked each time it opens, the rows loaded so far with "Loading your repositories… N of about M" under them (and with no count before page 1, and still in view under rows that scroll), read again on `changed github_repositories`, "Couldn't load your repositories." with Retry (GitHub's failure or the daemon unreadable) keeping the other sections and typed names, Retry loading again, "Sign in to GitHub…" in its place signed out (PR status or the list's `signed_out`), and only the rows in view drawn for 1,100; the loading line's count and rounding; the sidebar not reading again for a `github_repositories` event; the Suggestions strip on a Workspace's Pull requests (one row alone, several stacked in one strip under the header and over the table, none on the Pull requests view, an archived Workspace or for what it links by now), Link at once by GitHub's id with "Linked owner/name to ", the row gone and the group shown once read, its Undo unlinking without dismissing and a failure toasted with the row kept, Not now taking the row away for that Workspace only and kept across a restart in the GUI state file, the strip under Link repository on a Workspace with no Repositories, and an unlink from the group menu or Edit workspace's Save recording a dismissal (a failed one none); the GUI state's dismissed pairs, written by id; the picker's offer read from a snapshot (linked ones, Unreachable included; Suggestions but what the Workspace links by now; your PRs' reachable Repositories; open PRs counted as the sidebar does; signed out only while the token is logged out); the archived screen with no switch; a pane notifying while its workspace shows its Pull requests; New workspace's Name field and optional picker; New agent's Folder select (where a new pane starts first, the other panes' folders, then `~`, each once) and a new pane starting in `~` in a workspace with none; the Delete workspace dialog's lines (its Repositories unlinked, its running panes stopped, each left out at 0); the archive toast; the top bar's name, centred, before its side switch; a Pane alert's body, " · ", and the pane header's parts; PR alerts over the fake notifier: each trigger, only PRs you authored, one alert per PR replaced on a new change, a click landing on the row with its group opened, a Finished row shown with Show finished left off, scrolled to and highlighted until the highlight fades, "N PRs changed" opening the view, an alert withdrawn once the view shows, and the mute rule with every linking Workspace muted, one unmuted, only Archived muted ones, and none); the PR alert mute rule and the GitHub remote parser (https, ssh and scp-like URLs, for Suggestions) in `agentdeck-core`; the daemon's git config reader for Suggestions (each remote's first URL by name, sections and keys ignoring case, the old dotted header, comments and quotes, `upstream` on GitHub over `origin`, no other remote; a folder deep in a repo, a worktree's `.git` file and `commondir`, a relative `gitdir`, none outside a repo) and which events make Suggestions due | -| integration | `agentdeckd/tests/integration` | temp `$XDG_*` dirs, a real daemon on a random port, a real client; PTYs run `sh`, which moves a pane with `cd` (read through `/proc`) or `printf`s an OSC 7, so a pane's current folder, its `changed` and its restore folder are tested without a shell that reports one; GitHub is httpmock (`AGENTDECK_GITHUB_API`, `AGENTDECK_GITHUB_REST_API` and `AGENTDECK_GITHUB_OAUTH`: GraphQL with `closePullRequest`, REST's `GET /repos/{owner}/{repo}` for Repository lookups, Links and Suggestions and `GET /user/repos` for the GitHub repository list, and the device flow's code and token endpoints); Suggestions run Panes (`sh`, `sleep`) in temp git repos with `upstream`, `origin` and other remotes: upstream on GitHub over origin, origin when upstream is elsewhere, other remotes ignored, none outside a repo, one per name, a Pane that `cd`s in, an exited Pane at its last folder, a name GitHub can't see never suggested, a renamed one under GitHub's name, each name asked about once per run across reads and Workspaces, signed out only kept Repositories, one other Workspaces link still suggested, one the Workspace links left out, an archived Workspace none, `404 not_found`, and `changed suggestions` when a Pane opens in or moves into a repo, a Link takes one away and a deleted Pane takes one away; the client's `repositories::suggestions` against the same daemon, none from an older one; the GitHub repository list (REST `GET /user/repos` on httpmock, pages with a `Link` header): not loaded until a refresh asks, every page in GitHub's order once loaded, one page with no `Link` header, page 1 served while the rest load (`total` estimated from the last page link), the last page read first so `total` is exact early, a `github_repositories` event as the load begins, as each page arrives and as it ends, the list kept across reads with no new request, a refresh quietly showing the list before until the new one has loaded, a refresh while a load runs left alone, a 5xx tried three times then `failed` and loaded on a retry, a 403 rate limit and a 429 failing at once, a later page failing the whole load, a 401 `failed` ("GitHub rejected the token"), a failed quiet refresh keeping the list with its `error`, `signed_out` with no token and no GitHub call, a changed token loading the new sign-in's list, and `search/repositories` never called; the client's `repositories::github_list` and `refresh_github_list` against the same daemon (loaded, signed out, the daemon's `unauthorized`); `gh` is a stub script on `PATH`, and so are `claude` and `codex`, which read input as their TUIs do, and exit on a submitted `/exit` so a shell pane's hosted agent can leave (raw, bracketed paste on, a read that is a lone `\r` submits, any other read is a paste); the keyring is an in-memory fake store (`AGENTDECK_KEYRING=memory`; without it the harness's daemon has no session bus, so no keyring). The `agentdeck_client` helpers the GUI's real API calls (`panes`, `settings`, `prs`, `repositories`, `workspaces`) are tested here through the real client (`*_client`), each new operation of the GUI's fake API with a test of the same call in the same PR, so the fake can't drift from the daemon; `prs::list` also lists none from a daemon older than `GET /v1/prs`, and lists Finished PRs, marked; `repositories::list` lists each Repository with the Workspaces linking it, Archived ones included, and none from a daemon older than `GET /v1/repositories`; `repositories::resolve` answers the Repository GitHub shows for a typed URL and fails with the daemon's "GitHub can't see …"; `repositories::link` links by GitHub's id and links again, signed out, once an unlink deleted the Repository, and `repositories::unlink` keeps one another Workspace links and fails with the daemon's `not_found` for one the Workspace doesn't link; `workspaces::create` makes a Workspace linking what was picked, or nothing, and `workspaces::update` renames, links and unlinks together, or changes nothing, failing with the daemon's words. The Workspace routes' Links are tested here too: create linking a Repository agentdeck keeps (no GitHub call) and one GitHub resolves, nothing made when GitHub can't see one; update renaming, linking and unlinking in one request (an unreferenced Repository gone), nothing changed when a link fails or the name is blank, `invalid_links`, unlinking one it doesn't link changing nothing, an archived Workspace linked, and `changed` for each Repository then the workspace. The link route's link by GitHub's `id` is tested here too: a Repository an unlink deleted stored again from the body signed out (no GitHub, where a link by name is `not_signed_in`), the Repository kept with that id linked under its name now, `changed` for the Repository then the workspace, and `404 not_found` storing nothing for a Workspace that doesn't exist. PR sync's Finished PRs are tested here too: Finished on merge, on close (from GitHub and from agentdeck) and past the cutoff, no longer Finished once GitHub shows a PR open again, deleted with their unreferenced Repositories after the window (`AGENTDECK_PR_FINISHED_SECS=0`), and Unreachable PRs kept with no window. PRs are kept by Repository and number: a renamed Repository's PR and one of another Repository that took the old name are two PRs. Workspaces without folders are tested here too: creating one makes nothing on disk and its JSON has no folder, an older client's `dir` and `force` are ignored, the dirty report route is gone (dropshot's own 404), deleting one unlinks its Repositories (a Repository nothing else names goes) and stops its panes but leaves every folder on disk (its panes' folders and an old scratch folder), the first pane of a workspace with none opens in `~` through `panes::new_shell_tab`, and `0002` drops the folder columns from a database at `0001`, keeping each Workspace and its Links. The fresh start is tested here too: a fresh data dir gets the migrations' schema (no `tasks`, `comments` or `instructions`; `pull_requests` keyed by `(repository_id, number)` with nothing unique on a name), a current database survives a restart, and a database with a `tasks` table, its last writes still in its WAL, is moved aside with its WAL and SHM files (the moved one still reads), logged, never over an earlier one, with scratch folders left alone, and the daemon starts empty | +| 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 | | integration | `mod integration_tests` in `agentdeckd/src` | a crate-private part over a real dependency, which `tests/integration` can't reach since the daemon is a binary: a `Pane` over a real PTY running `sh` reads as exited only once its exit is recorded. The integration nextest profile runs these modules; the unit one skips them | | integration | `agentdeckd/tests/integration` (keyring) | the keyring store against a real Secret Service: `gnome-keyring-daemon`, unlocked, on a private `dbus-daemon` session bus the test starts, as `agentdeck-notify`'s test does, which CI installs with `script/install-linux-deps.sh`. It saves, finds, replaces and deletes the token and client ID entries, and finds none with no Secret Service. It is the fake store's contract test: the same cases run against the fake, and a fake lands with a test of the real call in the same PR | -| integration | `agentdeck/tests/integration` | the real `agentdeck` binary in temp `$XDG_*` dirs, starting the real daemon itself, with GitHub on httpmock, GraphQL and REST, for `pr ls` (by Repository and by workspace), `pr close`, `repo ls|link|unlink` and `ws new|ls|rename|rm` (no folder made or removed, `ws ls`' REPOSITORIES in text and `--json`, `ws rm` unlinking, no `--dir`, `--repo` or `--force`); a long-lived client (the test binary re-run as a child, connecting through `agentdeck_client::daemon`, as the GUI does) for reaping and restarting the daemon it started; panes run `sh`, never a real agent CLI | +| 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-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. diff --git a/openapi.json b/openapi.json index fe595f1..023ced4 100644 --- a/openapi.json +++ b/openapi.json @@ -1031,6 +1031,14 @@ "url": { "description": "Its GitHub page.", "type": "string" + }, + "yours": { + "default": [], + "description": "Why it is yours, in this order: `authored`, `review_requested` (a review request names you), `assigned`; empty once it is none of these, when it is Finished (spec §8). Absent from an older daemon, which read only the PRs you authored.", + "items": { + "$ref": "#/components/schemas/Yours" + }, + "type": "array" } }, "required": [ @@ -1516,6 +1524,14 @@ } }, "type": "object" + }, + "Yours": { + "enum": [ + "authored", + "review_requested", + "assigned" + ], + "type": "string" } } },