diff --git a/crates/agentdeck-client/src/generated.rs b/crates/agentdeck-client/src/generated.rs index 6c63c86..457f81a 100644 --- a/crates/agentdeck-client/src/generated.rs +++ b/crates/agentdeck-client/src/generated.rs @@ -4404,6 +4404,23 @@ impl Client { pub fn link_delete(&self) -> builder::LinkDelete<'_> { builder::LinkDelete::new(self) } + ///Workspace `id`'s Suggestions (spec §3): the Repositories its Panes work in that it doesn't + /// + ///link, each as GitHub showed it when this run first asked about its name, by name ignoring case. A Pane counts at its current folder, an exited one at its last known folder; its git repo's `upstream` remote counts when it is on GitHub, else its `origin`. A Repository other Workspaces link is still suggested; one GitHub can't see never is; signed out, only one agentdeck keeps is. An archived Workspace has none. Not filtered by what the GUI was told Not now. A Workspace that doesn't exist is 404 `not_found`. + /// + ///Sends a `GET` request to `/v1/workspaces/{id}/suggestions` + /// + ///Arguments: + ///- `id`: The entity's id. + ///```ignore + ///let response = client.suggestion_list() + /// .id(id) + /// .send() + /// .await; + ///``` + pub fn suggestion_list(&self) -> builder::SuggestionList<'_> { + builder::SuggestionList::new(self) + } ///A workspace's tabs, in position order /// ///Sends a `GET` request to `/v1/workspaces/{id}/tabs` @@ -6758,6 +6775,76 @@ pub mod builder { } } } + ///Builder for [`Client::suggestion_list`] + /// + ///[`Client::suggestion_list`]: super::Client::suggestion_list + #[derive(Debug, Clone)] + pub struct SuggestionList<'a> { + client: &'a super::Client, + id: Result, + } + impl<'a> SuggestionList<'a> { + pub fn new(client: &'a super::Client) -> Self { + Self { + client: client, + id: Err("id was not initialized".to_string()), + } + } + pub fn id(mut self, value: V) -> Self + where + V: std::convert::TryInto, + { + self.id = value.try_into().map_err(|_| { + "conversion to `agentdeck_core :: WorkspaceId` for id failed".to_string() + }); + self + } + ///Sends a `GET` request to `/v1/workspaces/{id}/suggestions` + pub async fn send( + self, + ) -> Result>, Error> + { + let Self { client, id } = self; + let id = id.map_err(Error::InvalidRequest)?; + let url = format!( + "{}/v1/workspaces/{}/suggestions", + client.baseurl, + encode_path(&id.to_string()), + ); + let mut header_map = ::reqwest::header::HeaderMap::with_capacity(1usize); + header_map.append( + ::reqwest::header::HeaderName::from_static("api-version"), + ::reqwest::header::HeaderValue::from_static(super::Client::api_version()), + ); + #[allow(unused_mut)] + let mut request = client + .client + .get(url) + .header( + ::reqwest::header::ACCEPT, + ::reqwest::header::HeaderValue::from_static("application/json"), + ) + .headers(header_map) + .build()?; + let info = OperationInfo { + operation_id: "suggestion_list", + }; + client.pre(&mut request, &info).await?; + let result = client.exec(request, &info).await; + client.post(&result, &info).await?; + let response = result?; + match response.status().as_u16() { + 200u16 => ResponseValue::from_response(response).await, + 400u16..=499u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + 500u16..=599u16 => Err(Error::ErrorResponse( + ResponseValue::from_response(response).await?, + )), + _ => Err(Error::UnexpectedResponse(response)), + } + } + } ///Builder for [`Client::tab_list`] /// ///[`Client::tab_list`]: super::Client::tab_list diff --git a/crates/agentdeck-client/src/repositories.rs b/crates/agentdeck-client/src/repositories.rs index f637765..2aa9087 100644 --- a/crates/agentdeck-client/src/repositories.rs +++ b/crates/agentdeck-client/src/repositories.rs @@ -1,6 +1,7 @@ //! Repositories as the GUI reads them (spec §4 `GET /v1/repositories`, §11 Notifications), //! and the Links a Repository group's `…` menu makes and takes away (spec §4 -//! `/v1/workspaces/{id}/links`, §11 Pull requests view). +//! `/v1/workspaces/{id}/links`, §11 Pull requests view), and each Workspace's Suggestions +//! (`/v1/workspaces/{id}/suggestions`). use agentdeck_core::{RepositoryId, RepositoryName, WorkspaceId}; @@ -24,6 +25,26 @@ pub async fn list(client: &Client) -> Result, ApiError> { } } +/// Workspace `workspace`'s Suggestions (spec §3): the Repositories its Panes work in that it +/// doesn't link, by name, each as GitHub showed it, so the GUI links one by its id. Not +/// filtered by what the GUI was told Not now. A daemon older than the route has none to give, +/// and lists none rather than failing. +pub async fn suggestions( + client: &Client, + workspace: WorkspaceId, +) -> Result, ApiError> { + match client.suggestion_list().id(workspace).send().await { + Ok(suggestions) => Ok(suggestions.into_inner()), + Err(err) => match ApiError::from(err) { + ApiError { + message, + code: None, + } if message == OLDER_DAEMON => Ok(Vec::new()), + err => Err(err), + }, + } +} + /// The Repository GitHub shows by `name` now (`owner/name` or its URL), as the picker's typed /// row looks one up. One GitHub can't see is the daemon's `unknown_repository`, whose message /// is what the GUI shows: "GitHub can't see owner/name. Check the name or your token's diff --git a/crates/agentdeck-core/src/daemon.rs b/crates/agentdeck-core/src/daemon.rs index c59673a..db52acc 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 = 25; +pub const API_VERSION: u32 = 26; /// What `$XDG_RUNTIME_DIR/agentdeck/daemon.json` holds. The daemon writes it once it serves; /// the GUI and the CLI read it to reach the daemon. diff --git a/crates/agentdeck-core/src/ws.rs b/crates/agentdeck-core/src/ws.rs index 0a29d06..0d308a6 100644 --- a/crates/agentdeck-core/src/ws.rs +++ b/crates/agentdeck-core/src/ws.rs @@ -212,6 +212,12 @@ pub enum Entity { /// its number, `1296269#7`, so a rename keeps it. It came with `API_VERSION` 22, when the /// `task` it replaces went; an older client skips the message. PullRequest, + /// `/v1/workspaces/{id}/suggestions`: a Workspace's Suggestions differ from the last ones + /// the daemon worked out for it, after a Pane of it opened, exited, moved or was deleted, + /// a Link of it changed, it was archived or brought back, or the GitHub sign-in changed. + /// Its id is the Workspace's. It came with `API_VERSION` 26; an older client skips the + /// message. + Suggestions, } #[cfg(test)] @@ -386,6 +392,14 @@ mod tests { }, json!({"t": "changed", "entity": "repository", "id": "1296269"}), ), + ( + ServerMessage::Changed { + entity: Entity::Suggestions, + id: "019a0000-0000-7000-8000-000000000001".into(), + }, + json!({"t": "changed", "entity": "suggestions", + "id": "019a0000-0000-7000-8000-000000000001"}), + ), ( ServerMessage::Lagged { channel: 3 }, json!({"t": "lagged", "channel": 3}), diff --git a/crates/agentdeck-gui/src/api.rs b/crates/agentdeck-gui/src/api.rs index 14fd31c..8ddec28 100644 --- a/crates/agentdeck-gui/src/api.rs +++ b/crates/agentdeck-gui/src/api.rs @@ -456,15 +456,20 @@ async fn panes(client: Client, workspace: WorkspaceId) -> anyhow::Result anyhow::Result { let workspaces = (client.workspace_list().send().await) .map_err(ApiError::from)? .into_inner(); let mut panes = Vec::new(); + let mut suggestions = std::collections::HashMap::new(); for workspace in workspaces.iter().filter(|w| w.archived_at.is_none()) { + suggestions.insert( + workspace.id, + agentdeck_client::repositories::suggestions(&client, workspace.id).await?, + ); let tabs = client .tab_list() .id(workspace.id) @@ -498,6 +503,7 @@ async fn snapshot(client: Client) -> anyhow::Result { ), prs: agentdeck_client::prs::list(&client).await?, repositories: agentdeck_client::repositories::list(&client).await?, + suggestions, }) } @@ -823,6 +829,11 @@ pub(crate) mod fake { repository.workspaces.retain(|w| *w != workspace); } } + if let Some(suggested) = snapshot.suggestions.get_mut(&workspace) { + suggested.retain(|r| { + !(link.iter()).any(|n| n.to_string().eq_ignore_ascii_case(&r.name.to_string())) + }); + } let prs = snapshot.prs.clone(); snapshot.repositories.retain(|repository| { !repository.workspaces.is_empty() @@ -1178,6 +1189,9 @@ pub(crate) mod fake { if let Some(held) = held.filter(|r| !r.workspaces.contains(&workspace)) { held.workspaces.push(workspace); } + if let Some(suggested) = snapshot.suggestions.get_mut(&workspace) { + suggested.retain(|r| r.id != repository.id); + } Task::ready(Ok(())) } diff --git a/crates/agentdeck-gui/src/edit_workspace.rs b/crates/agentdeck-gui/src/edit_workspace.rs index a3a8a17..1fa44d7 100644 --- a/crates/agentdeck-gui/src/edit_workspace.rs +++ b/crates/agentdeck-gui/src/edit_workspace.rs @@ -6,8 +6,9 @@ //! one request; Cancel discards them, and nothing asks to confirm. Save, and Enter in the name, //! go ahead once the name isn't blank and something changed. A blank name, or the daemon's //! `invalid_name`, shows under the name; a Repository the daemon can't link shows under the -//! picker, and any other failure toasts. Once saved it closes and emits [`Saved`]. The slug -//! stays as it is. An archived workspace can be edited too. +//! picker, and any other failure toasts. Once saved it closes and emits [`Saved`]; each +//! Repository it unlinked counts as Not now for the workspace's Suggestions. The slug stays as +//! it is. An archived workspace can be edited too. use std::sync::Arc; @@ -26,6 +27,7 @@ use gpui::{ use gpui_base::input::InputEvent; use crate::api::{Api, Change}; +use crate::gui_state; use crate::link_picker::{LinkPicker, Offer, Staging}; use crate::workspace::failed; @@ -185,6 +187,7 @@ impl EditWorkspaceDialog { }; let typed = self.name.read(cx).value(); let (link, unlink) = self.picker.read(cx).change(); + let unlinked = unlink.clone(); let change = Change { name: new_name(&typed, &target.name).map(str::to_owned), link, @@ -199,6 +202,12 @@ impl EditWorkspaceDialog { this.saving = false; match saved { Ok(()) => { + // An unlink in the GUI counts as Not now for the Workspace's Suggestions. + gui_state::update(cx, |state| { + for repository in unlinked { + state.dismiss(target.id, repository); + } + }); this.handle.close(window, cx); cx.emit(Saved(target.id)); } @@ -713,6 +722,49 @@ mod tests { assert_eq!(harness.rows(cx), [(WIDGETS.to_owned(), Staged::Unlinking)]); } + #[gpui::test] + fn should_count_a_saved_unlink_as_not_now(cx: &mut TestAppContext) { + let (harness, cx) = Harness::open(cx); + harness.click("unlink acme/widgets", cx); + + harness.save(cx); + + let dismissed = cx.update(|_, cx| { + gui_state::read(cx, |s| s.is_dismissed(id(1), repository_id(WIDGETS))) + }); + assert!(dismissed); + } + + #[gpui::test] + fn should_not_count_an_unlink_cancelled_or_refused(cx: &mut TestAppContext) { + let (harness, cx) = Harness::open(cx); + harness.click("unlink acme/widgets", cx); + harness.api.fail_next("the daemon went away"); + + harness.save(cx); + + let dismissed = cx.update(|_, cx| { + gui_state::read(cx, |s| s.is_dismissed(id(1), repository_id(WIDGETS))) + }); + assert!(!dismissed); + } + + #[gpui::test] + fn should_suggest_in_the_picker_what_was_told_not_now(cx: &mut TestAppContext) { + let mut snapshot = snapshot(); + snapshot.suggestions.insert( + id(1), + vec![crate::overview::fixtures::suggestion("acme/infra")], + ); + cx.update(|cx| { + gui_state::update(cx, |s| s.dismiss(id(1), repository_id("acme/infra"))) + }); + + let (_harness, cx) = Harness::open_on(snapshot, true, cx); + + assert!(cx.debug_bounds("suggested acme/infra").is_some()); + } + #[gpui::test] fn should_link_on_an_archived_workspace(cx: &mut TestAppContext) { let mut snapshot = snapshot(); diff --git a/crates/agentdeck-gui/src/group_menu.rs b/crates/agentdeck-gui/src/group_menu.rs index 8b5ae58..771de6b 100644 --- a/crates/agentdeck-gui/src/group_menu.rs +++ b/crates/agentdeck-gui/src/group_menu.rs @@ -30,6 +30,7 @@ use gpui::{ }; use crate::api::Api; +use crate::gui_state; use crate::notice::{Notice, NoticeAction}; use crate::overview::Snapshot; use crate::pr_table::Linker; @@ -184,6 +185,7 @@ pub fn menu( api.clone(), workspace.clone(), repository.clone(), + |_, _| {}, window, cx, ); @@ -230,11 +232,14 @@ pub fn menu( .into_any_element() } -/// Links `workspace` to `repository` at once and toasts it, with an Undo that unlinks it. +/// Links `workspace` to `repository` at once and toasts it, with an Undo that unlinks it; +/// `linked` runs once it is linked. Undo doesn't dismiss a Suggestion: it puts things back as +/// they were. pub fn link( api: Arc, workspace: Linker, repository: Repository, + linked: impl FnOnce(&mut Window, &mut App) + 'static, window: &mut Window, cx: &mut App, ) { @@ -243,6 +248,7 @@ pub fn link( let name = repository.name.to_string(); match done { Ok(()) => { + linked(window, cx); let undo = NoticeAction::new("Undo", { let (workspace, id) = (workspace.clone(), repository.id); move |window, cx| { @@ -266,7 +272,8 @@ pub fn link( } /// Unlinks the Workspace whose Pull requests `target` is on from its Repository at once, and -/// toasts it with an Undo that links it again by GitHub's id. +/// toasts it with an Undo that links it again by GitHub's id. The unlink counts as Not now: +/// the Workspace's Suggestions leave the Repository out from then on. pub fn unlink(api: Arc, target: Target, window: &mut Window, cx: &mut App) { let Some(workspace) = target.workspace.clone() else { return; @@ -276,6 +283,8 @@ pub fn unlink(api: Arc, target: Target, window: &mut Window, cx: &mut A let name = target.repository.name.to_string(); match done { Ok(()) => { + let (id, repository) = (workspace.id, target.repository.id); + gui_state::update(cx, |state| state.dismiss(id, repository)); let undo = NoticeAction::new("Undo", { let (workspace, repository) = (workspace.clone(), target.repository.clone()); move |window, cx| { diff --git a/crates/agentdeck-gui/src/gui_state.rs b/crates/agentdeck-gui/src/gui_state.rs index 06782f3..0953a2f 100644 --- a/crates/agentdeck-gui/src/gui_state.rs +++ b/crates/agentdeck-gui/src/gui_state.rs @@ -1,11 +1,12 @@ //! The GUI's own state, kept across restarts in `$XDG_STATE_HOME/agentdeck/gui.json`, beside //! `window.json` (spec §11): GUI-only, never the daemon's. It holds which Repository groups //! are collapsed, per view (the Pull requests view, and each Workspace's Pull requests), whether -//! Show finished is on, and the side each Workspace last showed. +//! Show finished is on, the side each Workspace last showed, and the Suggestions dismissed for +//! each Workspace: told Not now, or unlinked in the GUI. //! //! Every field is optional in the file, and a field the GUI doesn't know is skipped, so a later -//! version adds its own (dismissed Suggestions) without breaking an older file, and an older GUI -//! reads a newer file. A missing or broken file reads as the defaults. +//! version adds its own without breaking an older file, and an older GUI reads a newer file. A +//! missing or broken file reads as the defaults. //! //! The state is a GPUI [`Global`] that `main` sets with [`init`]; a view reads it with //! [`read`] and changes it with [`update`], which writes the file at once. Without [`init`] @@ -32,6 +33,9 @@ pub struct GuiState { pub show_finished: bool, /// The side each Workspace showed last; a Workspace not named here opens on its Panes. pub last_side: BTreeMap, + /// The Repositories each Workspace's Suggestions leave out, by GitHub's id: told Not now, + /// or unlinked in the GUI. Never forgotten; the picker's Suggested section ignores them. + pub dismissed: BTreeMap>, } /// A Workspace's two sides, switched in its top bar (spec §11). @@ -68,6 +72,19 @@ impl GuiState { Side::PullRequests => self.last_side.insert(workspace, side), }; } + + /// Leaves `repository` out of `workspace`'s Suggestions from now on. + pub fn dismiss(&mut self, workspace: WorkspaceId, repository: RepositoryId) { + self.dismissed + .entry(workspace) + .or_default() + .insert(repository); + } + + /// Whether `workspace`'s Suggestions leave `repository` out. + pub fn is_dismissed(&self, workspace: WorkspaceId, repository: RepositoryId) -> bool { + (self.dismissed.get(&workspace)).is_some_and(|ids| ids.contains(&repository)) + } } /// The Repository groups collapsed in each view that groups PRs by Repository. A group is @@ -223,7 +240,7 @@ mod tests { #[test] fn should_skip_what_a_later_version_adds() { - let state = parse(r#"{"dismissed":[],"collapsed":{"pull_requests":[7],"ws":{}}}"#); + let state = parse(r#"{"later":[],"collapsed":{"pull_requests":[7],"ws":{}}}"#); assert_eq!(state, collapsed(&[7])); } @@ -300,6 +317,39 @@ mod tests { } } + mod dismissed { + use super::*; + + fn ws(n: u32) -> WorkspaceId { + format!("00000000-0000-7000-8000-{n:012}").parse().unwrap() + } + + #[test] + fn should_dismiss_a_repository_for_one_workspace_only() { + let mut state = GuiState::default(); + + state.dismiss(ws(1), RepositoryId::from(7)); + + assert!(state.is_dismissed(ws(1), RepositoryId::from(7))); + assert!(!state.is_dismissed(ws(2), RepositoryId::from(7))); + assert!(!state.is_dismissed(ws(1), RepositoryId::from(8))); + } + + #[test] + fn should_write_each_workspaces_pairs_by_id() { + let mut state = GuiState::default(); + state.dismiss(ws(1), RepositoryId::from(1296269)); + + let json = serde_json::to_string(&state).unwrap(); + + assert!( + json.contains(r#""dismissed":{"00000000-0000-7000-8000-000000000001":[1296269]}"#), + "{json}" + ); + assert_eq!(parse(&json), state); + } + } + mod collapsed { use super::*; diff --git a/crates/agentdeck-gui/src/link_picker.rs b/crates/agentdeck-gui/src/link_picker.rs index d70baed..651b6b4 100644 --- a/crates/agentdeck-gui/src/link_picker.rs +++ b/crates/agentdeck-gui/src/link_picker.rs @@ -8,8 +8,9 @@ //! request ([`LinkPicker::change`]): an unlinked row stays crossed out with Undo, and a note //! counts the open PRs that would leave the Workspace. //! -//! The picker lists From your pull requests (the Repositories of your kept PRs), leaving out -//! what the Workspace links and Unreachable ones; typing filters it. Typed text naming a +//! The picker lists Suggested (the Workspace's Suggestions, Not now or not), then From your +//! pull requests (the Repositories of your kept PRs, but for those Suggested), leaving out what +//! the Workspace links and Unreachable ones; typing filters both. Typed text naming a //! Repository (`owner/name` or its GitHub URL) that isn't listed offers a "Link owner/name" row, //! which asks GitHub ([`Api::resolve_repository`]); signed out, typed names are off. @@ -41,6 +42,9 @@ use crate::workspace::failed; /// The picker's placeholder. pub const PLACEHOLDER: &str = "Link a repository…"; +/// The heading over the Workspace's Suggestions, first in the list. +pub const SUGGESTED: &str = "Suggested"; + /// The heading over the Repositories of your kept PRs. pub const FROM_PRS: &str = "From your pull requests"; @@ -71,6 +75,8 @@ pub struct Choice { pub struct Offer { /// The Repositories it links now, by name ignoring case. pub linked: Vec, + /// Its Suggestions, by name, dismissed ones included: opening the picker is deliberate. + pub suggested: Vec, /// The Repositories of your kept PRs, by name ignoring case. pub from_prs: Vec, /// Each Repository's open PRs, counted as the sidebar counts them: drafts in, Unreachable @@ -105,11 +111,21 @@ impl Offer { .filter(|r| snapshot.prs.iter().any(|pr| pr.repository.id == r.id)) .map(|r| choice(r)) .collect(); + let suggested = (workspace.into_iter()) + .flat_map(|w| snapshot.suggested(w)) + .map(|r| Choice { + id: r.id, + name: r.name.clone(), + private: r.private, + unreachable: false, + }) + .collect(); // Unknown until PR status is read: let GitHub answer for the token. let signed_in = (snapshot.pr_sync.as_ref()) .is_none_or(|s| s.login != agentdeck_client::types::GhLogin::LoggedOut); Offer { linked, + suggested, from_prs, open_prs, signed_in, @@ -140,6 +156,8 @@ pub struct Row { /// An entry of the open list, in order. #[derive(Debug, Clone, PartialEq, Eq)] pub enum Entry { + /// One of the Workspace's Suggestions. + Suggested(Choice), /// A Repository of your kept PRs. Pick(Choice), /// "Link owner/name": a typed Repository the list doesn't hold. @@ -267,14 +285,21 @@ impl LinkPicker { .as_ref() .map_or_else(|| typed.to_lowercase(), |n| n.to_string().to_lowercase()); let held = |id: RepositoryId| self.rows.iter().any(|r| r.repository.id == id); + let offered = |c: &&Choice| { + !c.unreachable && !held(c.id) && c.name.to_string().to_lowercase().contains(&filter) + }; + let suggested: Vec<&Choice> = self.offer.suggested.iter().filter(offered).collect(); let picks: Vec<&Choice> = (self.offer.from_prs.iter()) - .filter(|c| !c.unreachable && !held(c.id)) - .filter(|c| c.name.to_string().to_lowercase().contains(&filter)) + .filter(|c| !self.offer.suggested.iter().any(|s| s.id == c.id)) + .filter(offered) + .collect(); + let mut entries: Vec = (suggested.iter()) + .map(|c| Entry::Suggested((*c).clone())) + .chain(picks.iter().map(|c| Entry::Pick((*c).clone()))) .collect(); - let mut entries: Vec = picks.iter().map(|c| Entry::Pick((*c).clone())).collect(); if let Some(named) = named.filter(|_| self.offer.signed_in) { let same = |name: &RepositoryName| same_name(name, &named); - let listed = picks.iter().any(|c| same(&c.name)) + let listed = (suggested.iter().chain(&picks)).any(|c| same(&c.name)) || self.rows.iter().any(|r| same(&r.repository.name)); if !listed { entries.push(Entry::Typed(named)); @@ -442,7 +467,7 @@ impl LinkPicker { /// Enter in the field: picks the list's first entry. fn pick_first(&mut self, window: &mut Window, cx: &mut Context) { match self.entries(cx).into_iter().next() { - Some(Entry::Pick(choice)) => self.pick(choice, window, cx), + Some(Entry::Suggested(choice) | Entry::Pick(choice)) => self.pick(choice, window, cx), Some(Entry::Typed(name)) => self.pick_typed(name, window, cx), None => {} } @@ -538,19 +563,26 @@ impl LinkPicker { } /// The open list (Penpot `agentdeck/LinkPickerList`), drawn as core-gpui's - /// `ComboboxContent`: From your pull requests, the typed row, then the last line. + /// `ComboboxContent`: Suggested, From your pull requests, the typed row, then the last + /// line. fn list(&self, cx: &mut Context) -> impl IntoElement { let s = cx.theme().semantic(); let entries = self.entries(cx); + let suggested: Vec = (entries.iter()) + .filter_map(|e| match e { + Entry::Suggested(choice) => Some(choice.clone()), + Entry::Pick(_) | Entry::Typed(_) => None, + }) + .collect(); let picks: Vec = (entries.iter()) .filter_map(|e| match e { Entry::Pick(choice) => Some(choice.clone()), - Entry::Typed(_) => None, + Entry::Suggested(_) | Entry::Typed(_) => None, }) .collect(); let typed = entries.iter().find_map(|e| match e { Entry::Typed(name) => Some(name.clone()), - Entry::Pick(_) => None, + Entry::Suggested(_) | Entry::Pick(_) => None, }); let mut shadows = vec![BoxShadow { color: s.foreground.opacity(0.1), @@ -602,6 +634,20 @@ impl LinkPicker { .bg(s.popover) .text_color(s.popover_foreground) .shadow(shadows) + .when(!suggested.is_empty(), |list| { + list.child(line(SUGGESTED, "suggested")) + .children(suggested.into_iter().map(|choice| { + let name = choice.name.to_string(); + let selector = format!("suggested {name}"); + item(SharedString::from(format!("suggested-{}", choice.id))) + .debug_selector(move || selector.clone()) + .when(choice.private, |d| d.child(lock(&name, s.muted_foreground))) + .child(name) + .on_click(cx.listener(move |this, _, window, cx| { + this.pick(choice.clone(), window, cx) + })) + })) + }) .when(!picks.is_empty(), |list| { list.child(line(FROM_PRS, "from your pull requests")) .children(picks.into_iter().map(|choice| { @@ -765,7 +811,7 @@ pub(crate) mod tests { use super::*; use crate::api::fake::FakeApi; - use crate::overview::fixtures::{id, links, pr_sync, pull_request, repository_id}; + use crate::overview::fixtures::{id, links, pr_sync, pull_request, repository_id, suggestion}; const WIDGETS: &str = "acme/widgets"; const GADGETS: &str = "acme/gadgets"; @@ -860,6 +906,31 @@ pub(crate) mod tests { assert_eq!(offer.open_prs.get(&repository_id(GADGETS)), None); } + #[test] + fn should_offer_the_workspaces_suggestions_but_what_it_links_by_now() { + let mut snapshot = snapshot(); + snapshot + .workspaces + .push(crate::overview::fixtures::workspace(1, "web")); + let private = agentdeck_client::types::Repository { + private: true, + ..suggestion("acme/infra") + }; + snapshot.suggestions.insert( + id(1), + vec![private, suggestion("acme/website"), suggestion(WIDGETS)], + ); + + let offer = Offer::read(&snapshot, Some(id(1))); + + let infra = Choice { + private: true, + ..choice("acme/infra") + }; + assert_eq!(offer.suggested, [infra, choice("acme/website")]); + assert_eq!(Offer::read(&snapshot, None).suggested, []); + } + #[test] fn should_be_signed_out_only_while_github_rejects_the_token() { let mut snapshot = snapshot(); @@ -885,6 +956,7 @@ pub(crate) mod tests { }; Offer { linked: vec![private(GADGETS), choice(WIDGETS)], + suggested: Vec::new(), from_prs: vec![ private(GADGETS), Choice { @@ -979,6 +1051,7 @@ pub(crate) mod tests { fn picks(entries: &[Entry]) -> Vec { (entries.iter()) .map(|e| match e { + Entry::Suggested(choice) => format!("Suggested {}", choice.name), Entry::Pick(choice) => choice.name.to_string(), Entry::Typed(name) => format!("Link {name}"), }) @@ -1255,6 +1328,102 @@ pub(crate) mod tests { } } + mod suggested { + use super::*; + + /// [`offer`] with the Suggestions website, then infra, which you also have PRs in. + fn suggesting() -> Offer { + Offer { + suggested: vec![choice("acme/infra"), choice("acme/website")], + from_prs: [offer().from_prs, vec![choice("acme/infra")]].concat(), + ..offer() + } + } + + fn shows(selector: &str, cx: &mut VisualTestContext) -> bool { + cx.debug_bounds(selector.to_owned().leak()).is_some() + } + + #[gpui::test] + fn should_list_the_suggestions_first_then_your_prs_repositories(cx: &mut TestAppContext) { + let (harness, cx) = Harness::open(suggesting(), cx); + + assert_eq!( + harness.entries(cx), + [ + Entry::Suggested(choice("acme/infra")), + Entry::Suggested(choice("acme/website")), + Entry::Pick(Choice { + private: true, + ..choice(SECRETS) + }), + Entry::Pick(choice("acme/tools")), + ] + ); + } + + #[gpui::test] + fn should_head_them_suggested_above_from_your_pull_requests(cx: &mut TestAppContext) { + let (harness, cx) = Harness::open(suggesting(), cx); + harness.type_in("", cx); + + let suggested = cx.debug_bounds("suggested").expect("the Suggested heading"); + let first = cx.debug_bounds("suggested acme/infra").expect("infra"); + let from_prs = cx + .debug_bounds("from your pull requests") + .expect("its heading"); + assert!(suggested.bottom() <= first.top()); + assert!(first.bottom() <= from_prs.top()); + assert!(!shows("pick acme/infra", cx), "listed once, as Suggested"); + } + + #[gpui::test] + fn should_stage_a_suggestion_picked_from_the_list(cx: &mut TestAppContext) { + let (harness, cx) = Harness::open(suggesting(), cx); + harness.type_in("", cx); + + let at = cx.debug_bounds("suggested acme/website").expect("website"); + cx.simulate_click(at.center(), Modifiers::default()); + harness.settle(cx); + + assert_eq!( + harness.rows(cx).last(), + Some(&("acme/website".to_owned(), Staged::Linking)) + ); + assert!( + !harness + .entries(cx) + .contains(&Entry::Suggested(choice("acme/website"))) + ); + } + + #[gpui::test] + fn should_filter_them_as_you_type(cx: &mut TestAppContext) { + let (harness, cx) = Harness::open(suggesting(), cx); + + harness.type_in("WEB", cx); + + assert_eq!( + harness.entries(cx), + [Entry::Suggested(choice("acme/website"))] + ); + } + + #[gpui::test] + fn should_pick_the_first_suggestion_on_enter(cx: &mut TestAppContext) { + let (harness, cx) = Harness::open(suggesting(), cx); + harness.type_in("acme", cx); + + cx.simulate_keystrokes("enter"); + harness.settle(cx); + + assert_eq!( + harness.rows(cx).last(), + Some(&("acme/infra".to_owned(), Staged::Linking)) + ); + } + } + mod signed_out { use super::*; diff --git a/crates/agentdeck-gui/src/main.rs b/crates/agentdeck-gui/src/main.rs index b48ceff..ff3b282 100644 --- a/crates/agentdeck-gui/src/main.rs +++ b/crates/agentdeck-gui/src/main.rs @@ -35,6 +35,7 @@ mod shell; mod sidebar; mod state_dir; mod state_dot; +mod suggestion_strip; mod sync_parts; mod table; mod terminal; diff --git a/crates/agentdeck-gui/src/overview.rs b/crates/agentdeck-gui/src/overview.rs index 82eb39d..f566795 100644 --- a/crates/agentdeck-gui/src/overview.rs +++ b/crates/agentdeck-gui/src/overview.rs @@ -6,7 +6,9 @@ //! a pure function the views render. Live `state` and `exit` messages patch the snapshot's //! pane states in place; anything else that changes is read again. -use agentdeck_client::types::{PrSyncStatus, PullRequest, RepositoryLinks, Workspace}; +use std::collections::HashMap; + +use agentdeck_client::types::{PrSyncStatus, PullRequest, Repository, RepositoryLinks, Workspace}; use agentdeck_core::{Agent, AgentState, PaneId, PrState, RepositoryId, WorkspaceId}; use chrono::{DateTime, Utc}; use gpui::SharedString; @@ -41,6 +43,9 @@ pub struct Snapshot { /// Every Repository the daemon keeps, with the Workspaces linking it, archived ones /// included: what the PR alert mute rule reads (spec §11). pub repositories: Vec, + /// Each unarchived Workspace's Suggestions, by name, as the daemon works them out: not + /// filtered by what was dismissed (spec §11). + pub suggestions: HashMap>, } /// A row's counts; a zero hides its count. @@ -172,6 +177,19 @@ impl Snapshot { .collect() } + /// `workspace`'s Suggestions, by name, but for any it links by now: the daemon's next + /// word on them may not be read yet. None while it is archived. + pub fn suggested(&self, workspace: WorkspaceId) -> Vec<&Repository> { + let archived = + (self.workspaces.iter()).any(|w| w.id == workspace && w.archived_at.is_some()); + if archived { + return Vec::new(); + } + (self.suggestions.get(&workspace).into_iter().flatten()) + .filter(|r| !self.links(workspace, r.id)) + .collect() + } + /// Whether `workspace` links `repository` and isn't archived. pub fn links(&self, workspace: WorkspaceId, repository: RepositoryId) -> bool { self.linking(repository).iter().any(|w| w.id == workspace) @@ -359,6 +377,18 @@ pub(crate) mod fixtures { } } + /// Repository `repo` (`owner/name`) as a Suggestion carries it, public, with the id + /// [`repository_id`] gives it. + pub fn suggestion(repo: &str) -> Repository { + Repository { + archived: false, + id: repository_id(repo), + name: repo.parse().expect("owner/name"), + private: false, + url: format!("https://github.com/{repo}"), + } + } + /// Repository `repo` (`owner/name`), with the id [`repository_id`] gives it, linked by /// `workspaces`. pub fn links(repo: &str, workspaces: &[WorkspaceId]) -> RepositoryLinks { diff --git a/crates/agentdeck-gui/src/pull_requests.rs b/crates/agentdeck-gui/src/pull_requests.rs index f981bda..2514bb9 100644 --- a/crates/agentdeck-gui/src/pull_requests.rs +++ b/crates/agentdeck-gui/src/pull_requests.rs @@ -38,6 +38,12 @@ //! and **Edit workspace**. With no Repository linked it says so, with **Link repository**, //! which opens Edit workspace with its "Link a repository…" picker focused. //! +//! Under its header, a Workspace's Pull requests shows its Suggestions in one strip +//! ([`suggestion_strip`]), but for those dismissed in the GUI's state: **Link** links one at +//! once by GitHub's id with a toast and Undo, its row going and its group appearing; **Not +//! now** dismisses it for good. With no Repository linked, the strip sits under Link +//! repository. +//! //! The Pull requests view's header ends in Select, Show finished, when PRs last synced and //! **Sync now**, which runs a full sync and emits //! [`Synced`] once done, so the window can have the sidebar read again: a sync that changes no @@ -53,7 +59,7 @@ use std::rc::Rc; use std::sync::Arc; use std::time::Duration; -use agentdeck_client::types::{GhLogin, PullRequest}; +use agentdeck_client::types::{GhLogin, PullRequest, Repository}; use agentdeck_core::{PrState, RepositoryId, WorkspaceId, pr_details, prs_details}; use brrritscold_core_gpui::{ ActiveTheme as _, Button, ButtonSize, ButtonVariant, DropdownMenu, DropdownMenuAlign, @@ -75,6 +81,7 @@ use crate::gui_state; use crate::open_pr; use crate::overview::Snapshot; use crate::pr_table::{self, Linker}; +use crate::suggestion_strip; use crate::sync_parts::{self, OpenSettings, SETTINGS_TAIL, cutoff, logged_out_title}; use crate::table::{self, Header, RowParts, SelectCell}; use crate::top_bar::{EditWorkspace, LinkRepository}; @@ -347,6 +354,8 @@ pub struct PullRequestsView { highlight: Option<(PrKey, bool)>, /// Fades the highlight, then takes it off. _highlighting: Option>, + /// Suggestions linked from the strip, left out until the next snapshot shows the Link. + linked_here: BTreeSet, /// Redraws "Synced N min ago" as time passes. _tick: Task<()>, } @@ -390,6 +399,7 @@ impl PullRequestsView { reveal_pending: false, highlight: None, _highlighting: None, + linked_here: BTreeSet::new(), _tick: tick, } } @@ -487,9 +497,81 @@ impl PullRequestsView { self.close .update(cx, |close, cx| close.saw_closed(closed, cx)); self.snapshot = snapshot; + self.linked_here.clear(); + cx.notify(); + } + + /// The Suggestions the strip shows: on a Workspace's Pull requests, its Suggestions as last + /// read but for those dismissed or just linked from the strip; none on the Pull requests + /// view. + pub fn suggestions(&self, cx: &App) -> Vec { + let Scope::Workspace(workspace) = self.scope else { + return Vec::new(); + }; + gui_state::read(cx, |state| { + (self.snapshot.suggested(workspace).into_iter()) + .filter(|r| !state.is_dismissed(workspace, r.id)) + .filter(|r| !self.linked_here.contains(&r.id)) + .cloned() + .collect() + }) + } + + /// Links the Workspace to Suggestion `repository` at once by GitHub's id, with a toast and + /// Undo ([`group_menu::link`]); its row goes once it is linked. + pub fn link_suggestion( + &mut self, + repository: Repository, + window: &mut Window, + cx: &mut Context, + ) { + let Scope::Workspace(id) = self.scope else { + return; + }; + let workspace = Linker { + id, + name: self.workspace_name().unwrap_or_default(), + }; + let this = cx.entity().downgrade(); + let linked = repository.id; + group_menu::link( + self.api.clone(), + workspace, + repository, + move |_, cx| { + let _ = this.update(cx, |this, cx| { + this.linked_here.insert(linked); + cx.notify(); + }); + }, + window, + cx, + ); + } + + /// Not now: leaves `repository` out of the Workspace's Suggestions for good, remembered + /// across restarts. + pub fn not_now(&mut self, repository: RepositoryId, cx: &mut Context) { + let Scope::Workspace(workspace) = self.scope else { + return; + }; + gui_state::update(cx, |state| state.dismiss(workspace, repository)); cx.notify(); } + /// The strip of [`Self::suggestions`], if any. + fn suggestion_strip(&self, cx: &mut Context) -> Option { + let this = cx.entity().downgrade(); + let on_link: suggestion_strip::OnLink = Rc::new(move |repository, window, cx| { + let _ = this.update(cx, |this, cx| this.link_suggestion(repository, window, cx)); + }); + let this = cx.entity().downgrade(); + let on_not_now: suggestion_strip::OnNotNow = Rc::new(move |repository, _, cx| { + let _ = this.update(cx, |this, cx| this.not_now(repository, cx)); + }); + suggestion_strip::strip(&self.suggestions(cx), on_link, on_not_now, cx) + } + /// The groups shown. pub fn groups(&self, cx: &App) -> Vec { groups(&self.snapshot, self.scope, show_finished(cx), self.revealed) @@ -1036,6 +1118,9 @@ impl Render for PullRequestsView { .when_some(banner, |content, title| { content.child(sync_parts::logged_out_banner("pull-requests", title, cx)) }) + // Penpot "Workspace · Pull requests · suggestions": the strip under the header, + // under Link repository while nothing is linked. + .children(self.suggestion_strip(cx)) .map(|content| { if self.shown.is_empty() && self.scope != Scope::All { // Penpot "Workspace · no repositories": the header says it all. @@ -1859,6 +1944,288 @@ mod tests { } } + /// The Suggestions strip on a Workspace's Pull requests (spec §11): Link at once with Undo, + /// Not now remembered, and the dismissals a GUI unlink records. + mod suggestions { + use super::*; + use crate::overview::fixtures::suggestion; + + /// [`linked`], with `a` suggested website and infra, and `b` gadgets. + fn suggesting() -> Snapshot { + let mut snapshot = linked(); + snapshot.suggestions.insert( + id(1), + vec![suggestion("acme/infra"), suggestion("acme/website")], + ); + snapshot + .suggestions + .insert(id(2), vec![suggestion("acme/gadgets")]); + snapshot + } + + fn last_notice(cx: &mut VisualTestContext) -> crate::notice::Notice { + cx.update(|_, cx| crate::notice::shown(cx).last().cloned().expect("a toast")) + } + + fn dismissed(workspace: u32, repo: &str, cx: &mut VisualTestContext) -> bool { + cx.update(|_, cx| { + gui_state::read(cx, |state| { + state.is_dismissed(id(workspace), repository_id(repo)) + }) + }) + } + + #[gpui::test] + fn should_stack_a_row_per_suggestion_in_one_strip(cx: &mut TestAppContext) { + let (_harness, cx) = Harness::open_in(a(), suggesting(), cx); + + let strip = bounds("suggestions".into(), cx); + let infra = bounds("suggestion acme/infra".into(), cx); + let website = bounds("suggestion acme/website".into(), cx); + assert!(strip.contains(&infra.center()) && strip.contains(&website.center())); + assert!( + infra.bottom() <= website.top(), + "in order, one under the other" + ); + assert!(shows("link suggestion acme/infra".into(), cx)); + assert!(shows("not now acme/website".into(), cx)); + assert!(!shows("suggestion acme/gadgets".into(), cx), "b's, not a's"); + } + + #[gpui::test] + fn should_sit_under_the_header_over_the_table(cx: &mut TestAppContext) { + let (_harness, cx) = Harness::open_in(a(), suggesting(), cx); + + let strip = bounds("suggestions".into(), cx); + assert!(bounds("edit workspace".into(), cx).bottom() <= strip.top()); + assert!(strip.bottom() <= bounds("pull requests table".into(), cx).top()); + } + + #[gpui::test] + fn should_show_one_suggestion_alone(cx: &mut TestAppContext) { + let (_harness, cx) = Harness::open_in(Scope::Workspace(id(2)), suggesting(), cx); + + let strip = bounds("suggestions".into(), cx); + let row = bounds("suggestion acme/gadgets".into(), cx); + assert!(strip.contains(&row.center())); + assert!(strip.size.height < row.size.height * 2.); + } + + #[gpui::test] + fn should_show_none_without_suggestions(cx: &mut TestAppContext) { + let (_harness, cx) = Harness::open_in(a(), linked(), cx); + + assert!(!shows("suggestions".into(), cx)); + } + + #[gpui::test] + fn should_show_none_on_the_pull_requests_view(cx: &mut TestAppContext) { + let (_harness, cx) = Harness::open(suggesting(), cx); + + assert!(!shows("suggestions".into(), cx)); + } + + #[gpui::test] + fn should_leave_out_what_the_workspace_links_by_now(cx: &mut TestAppContext) { + let mut snapshot = suggesting(); + snapshot.repositories.push(links("acme/infra", &[id(1)])); + let (_harness, cx) = Harness::open_in(a(), snapshot, cx); + + assert!(!shows("suggestion acme/infra".into(), cx)); + assert!(shows("suggestion acme/website".into(), cx)); + } + + mod link { + use super::*; + + #[gpui::test] + fn should_link_at_once_by_id_with_a_toast(cx: &mut TestAppContext) { + let (harness, cx) = Harness::open_in(a(), suggesting(), cx); + + click("link suggestion acme/website".into(), cx); + + let links = harness.api.links.lock().unwrap().clone(); + assert_eq!(links, [(id(1), suggestion("acme/website"))]); + assert_eq!(last_notice(cx).title, "Linked acme/website to a"); + assert!(!shows("suggestion acme/website".into(), cx), "its row goes"); + assert!(shows("suggestion acme/infra".into(), cx)); + assert!(!dismissed(1, "acme/website", cx)); + } + + #[gpui::test] + fn should_show_its_group_once_the_link_is_read(cx: &mut TestAppContext) { + let (harness, cx) = Harness::open_in(a(), suggesting(), cx); + click("link suggestion acme/website".into(), cx); + + harness.show(harness.api.snapshot_now(), cx); + + assert!(shows("group acme/website".into(), cx)); + assert!(!shows("suggestion acme/website".into(), cx)); + } + + #[gpui::test] + fn should_unlink_it_on_undo_and_offer_it_again(cx: &mut TestAppContext) { + let (harness, cx) = Harness::open_in(a(), suggesting(), cx); + click("link suggestion acme/website".into(), cx); + + let undo = last_notice(cx).action.expect("an Undo"); + cx.update(|window, cx| undo.run(window, cx)); + cx.run_until_parked(); + // The daemon works its Suggestions out again once the Link has gone. + harness.show(suggesting(), cx); + + assert_eq!( + *harness.api.unlinks.lock().unwrap(), + [(id(1), repository_id("acme/website"))] + ); + assert!(!dismissed(1, "acme/website", cx), "Undo isn't Not now"); + assert!(shows("suggestion acme/website".into(), cx)); + } + + #[gpui::test] + fn should_toast_why_a_link_failed_and_keep_the_row(cx: &mut TestAppContext) { + let (harness, cx) = Harness::open_in(a(), suggesting(), cx); + harness.api.fail_next("the daemon went away"); + + click("link suggestion acme/website".into(), cx); + + assert_eq!(last_notice(cx).title, "Couldn't link acme/website to a"); + assert!(shows("suggestion acme/website".into(), cx)); + } + } + + mod not_now { + use super::*; + + #[gpui::test] + fn should_take_the_row_away_for_this_workspace_only(cx: &mut TestAppContext) { + let (harness, cx) = Harness::open_in(a(), suggesting(), cx); + + click("not now acme/website".into(), cx); + + assert!(!shows("suggestion acme/website".into(), cx)); + assert!(shows("suggestion acme/infra".into(), cx)); + assert!(harness.api.links.lock().unwrap().is_empty()); + assert!(dismissed(1, "acme/website", cx)); + assert!(!dismissed(2, "acme/website", cx)); + } + + #[gpui::test] + fn should_be_remembered_across_restarts(cx: &mut TestAppContext) { + let dir = tempfile::tempdir().expect("a temp dir"); + let path = dir.path().join(gui_state::FILE); + cx.update(|cx| gui_state::init(Some(path.clone()), cx)); + let (_harness, window) = Harness::open_in(a(), suggesting(), cx); + click("not now acme/website".into(), window); + + // The next start reads the file again. + let saved = gui_state::load(&path); + assert!(saved.is_dismissed(id(1), repository_id("acme/website"))); + cx.update(|cx| gui_state::init(Some(path), cx)); + let (_harness, cx) = Harness::open_in(a(), suggesting(), cx); + + assert!(!shows("suggestion acme/website".into(), cx)); + assert!(shows("suggestion acme/infra".into(), cx)); + } + + #[gpui::test] + fn should_take_the_strip_away_with_its_last_row(cx: &mut TestAppContext) { + let (_harness, cx) = Harness::open_in(Scope::Workspace(id(2)), suggesting(), cx); + + click("not now acme/gadgets".into(), cx); + + assert!(!shows("suggestions".into(), cx)); + } + } + + #[gpui::test] + fn should_count_an_unlink_from_the_group_menu_as_not_now(cx: &mut TestAppContext) { + let (_harness, cx) = Harness::open_in(a(), linked(), cx); + + click("group menu acme/widgets".into(), cx); + cx.simulate_keystrokes("down down down enter"); + cx.run_until_parked(); + + assert!(dismissed(1, "acme/widgets", cx)); + assert!(!dismissed(2, "acme/widgets", cx)); + } + + #[gpui::test] + fn should_not_count_a_failed_unlink(cx: &mut TestAppContext) { + let (harness, cx) = Harness::open_in(a(), linked(), cx); + harness.api.fail_next("the daemon went away"); + + click("group menu acme/widgets".into(), cx); + cx.simulate_keystrokes("down down down enter"); + cx.run_until_parked(); + + assert!(!dismissed(1, "acme/widgets", cx)); + } + + mod no_repositories { + use super::*; + + /// Workspace `c` (4), linking nothing, suggested website and infra. + fn c() -> (Scope, Snapshot) { + let mut snapshot = linked(); + snapshot.workspaces.push(workspace(4, "c")); + snapshot.suggestions.insert( + id(4), + vec![suggestion("acme/infra"), suggestion("acme/website")], + ); + (Scope::Workspace(id(4)), snapshot) + } + + #[gpui::test] + fn should_list_them_under_link_repository(cx: &mut TestAppContext) { + let (scope, snapshot) = c(); + let (harness, cx) = Harness::open_in(scope, snapshot, cx); + + let button = bounds("link repository".into(), cx); + let strip = bounds("suggestions".into(), cx); + assert!(button.bottom() <= strip.top()); + assert!(shows("suggestion acme/infra".into(), cx)); + assert!(shows("suggestion acme/website".into(), cx)); + let lines = harness.view.read_with(cx, |view, cx| view.description(cx)); + assert_eq!(lines, NO_REPOSITORIES); + } + + #[gpui::test] + fn should_leave_out_those_told_not_now(cx: &mut TestAppContext) { + let (scope, snapshot) = c(); + let (_harness, cx) = Harness::open_in(scope, snapshot, cx); + + click("not now acme/infra".into(), cx); + + assert!(!shows("suggestion acme/infra".into(), cx)); + assert!(shows("suggestion acme/website".into(), cx)); + } + + #[gpui::test] + fn should_link_one_with_link(cx: &mut TestAppContext) { + let (scope, snapshot) = c(); + let (harness, cx) = Harness::open_in(scope, snapshot, cx); + + click("link suggestion acme/infra".into(), cx); + harness.show(harness.api.snapshot_now(), cx); + + assert_eq!(last_notice(cx).title, "Linked acme/infra to c"); + assert!(shows("group acme/infra".into(), cx)); + assert!(!shows("link repository".into(), cx)); + } + } + + #[gpui::test] + fn should_show_none_for_an_archived_workspace(cx: &mut TestAppContext) { + let mut snapshot = suggesting(); + snapshot.workspaces[0].archived_at = Some("2026-11-20T00:00:00Z".into()); + + let (_harness, cx) = Harness::open_in(a(), snapshot, cx); + + assert!(!shows("suggestions".into(), cx)); + } + } + mod groups { use super::*; diff --git a/crates/agentdeck-gui/src/suggestion_strip.rs b/crates/agentdeck-gui/src/suggestion_strip.rs new file mode 100644 index 0000000..e1a510d --- /dev/null +++ b/crates/agentdeck-gui/src/suggestion_strip.rs @@ -0,0 +1,132 @@ +//! The Suggestions strip on a Workspace's Pull requests (spec §11), Penpot "Screens · Main" → +//! "Workspace · Pull requests · suggestion", "· suggestions" and "Workspace · no repositories · +//! suggestions": one row per Suggestion, stacked in one strip drawn as core-gpui's default +//! `Alert` box. An app-local composition (Penpot `agentdeck/SuggestionRow`), since an `Alert` +//! holds one title and one action. +//! +//! A row reads "Panes here work in **owner/name**. Link it to this workspace?", then **Link** · +//! **Not now**. What each does is the view's: this only draws them. + +use std::rc::Rc; + +use agentdeck_client::types::Repository; +use agentdeck_core::RepositoryId; +use brrritscold_core_gpui::{ActiveTheme as _, Button, ButtonSize, ButtonVariant, Icon, IconName}; +use brrritscold_core_gpui_tokens::primitive::{font_size, font_weight, space}; +use gpui::{ + AnyElement, App, InteractiveElement as _, IntoElement, ParentElement as _, SharedString, + Styled as _, Window, div, px, +}; + +/// What a row says before the Repository's name. +pub const LEAD: &str = "Panes here work in"; + +/// What a row says after the Repository's name. +pub const TAIL: &str = ". Link it to this workspace?"; + +/// What Link does with a row's Repository. +pub type OnLink = Rc; + +/// What Not now does with a row's Repository. +pub type OnNotNow = Rc; + +/// The strip of `suggestions`, one row each, in order; nothing when there are none. Tests find +/// it as `suggestions`, each row as `suggestion `, its text as `suggestion text ` +/// and its buttons as `link suggestion ` and `not now `. +pub fn strip( + suggestions: &[Repository], + on_link: OnLink, + on_not_now: OnNotNow, + cx: &App, +) -> Option { + if suggestions.is_empty() { + return None; + } + let s = cx.theme().semantic(); + // Penpot `Suggestions`: the default Alert's box (rounded-lg border bg-card), its rows + // `space.2` from the top and bottom, as each row's buttons pad themselves. + let rows = suggestions + .iter() + .map(|repository| row(repository, on_link.clone(), on_not_now.clone(), cx)); + Some( + div() + .debug_selector(|| "suggestions".into()) + .flex_none() + .flex() + .flex_col() + .px(space::S4) + .py(space::S2) + .rounded(s.radius_lg) + .border_1() + .border_color(s.border) + .bg(s.card) + .text_color(s.card_foreground) + .children(rows) + .into_any_element(), + ) +} + +/// Penpot `agentdeck/SuggestionRow`: a 16px `GitBranch`, the sentence with the name in +/// medium, then Link · Not now at the end, `space.2-5` apart, as an Alert's icon and text. +fn row(repository: &Repository, on_link: OnLink, on_not_now: OnNotNow, cx: &App) -> AnyElement { + let s = cx.theme().semantic(); + let name = repository.name.to_string(); + let selector = |what: &str| { + let selector = format!("{what}{name}"); + move || selector.clone() + }; + let (held, id) = (repository.clone(), repository.id); + div() + .debug_selector(selector("suggestion ")) + .flex() + .items_center() + .gap(space::S2_5) + .h(space::S8) + .text_size(font_size::SM) + .child( + Icon::new(IconName::GitBranch) + .size(px(16.)) + .text_color(s.foreground), + ) + .child( + div() + .debug_selector(selector("suggestion text ")) + .min_w_0() + .flex() + .whitespace_nowrap() + .child(format!("{LEAD}\u{a0}")) + .child( + div() + .font_weight(font_weight::MEDIUM) + .child(SharedString::from(name.clone())), + ) + .child(TAIL), + ) + .child(div().flex_1()) + .child( + div() + .flex_none() + .flex() + .items_center() + .child( + div().debug_selector(selector("link suggestion ")).child( + Button::new(SharedString::from(format!("link-suggestion-{id}"))) + .variant(ButtonVariant::Link) + .size(ButtonSize::Sm) + .label("Link") + .on_click(move |_, window, cx| on_link(held.clone(), window, cx)), + ), + ) + .child(div().text_color(s.muted_foreground).child("·")) + .child( + div().debug_selector(selector("not now ")).child( + Button::new(SharedString::from(format!("not-now-{id}"))) + .variant(ButtonVariant::Link) + .size(ButtonSize::Sm) + .label("Not now") + .on_click(move |_, window, cx| on_not_now(id, window, cx)), + ), + ), + ) + .into_any_element() +} diff --git a/crates/agentdeckd/src/api/mod.rs b/crates/agentdeckd/src/api/mod.rs index eb7d1df..1c9c387 100644 --- a/crates/agentdeckd/src/api/mod.rs +++ b/crates/agentdeckd/src/api/mod.rs @@ -32,6 +32,7 @@ use crate::events::Events; use crate::github_auth::GithubAuth; use crate::prsync::PrSync; use crate::prsync::github::Github; +use crate::suggestions::Suggestions; use crate::terminal::Terminals; /// The version `openapi.json` declares: the API is `/v1`. @@ -57,6 +58,8 @@ pub struct ApiContext { pub terminals: Terminals, /// The events every WebSocket client gets. pub events: Events, + /// Each Workspace's Suggestions, for `/v1/workspaces/{id}/suggestions`. + pub suggestions: Suggestions, } /// Every endpoint. @@ -83,6 +86,7 @@ pub fn api() -> ApiDescription { api.register(repositories::repository_resolve), api.register(repositories::link_create), api.register(repositories::link_delete), + api.register(repositories::suggestion_list), api.register(github::github_auth_get), api.register(github::github_token_put), api.register(github::github_token_delete), @@ -231,7 +235,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) = (0x4933_5dbf_cf35_14c9, 25); + const FINGERPRINT_AT_API_VERSION: (u64, u32) = (0xc935_79a3_d8ff_d5cc, 26); /// FNV-1a: stable across Rust releases, unlike `DefaultHasher`. fn fingerprint(text: &str) -> u64 { diff --git a/crates/agentdeckd/src/api/repositories.rs b/crates/agentdeckd/src/api/repositories.rs index b32c892..9b06f12 100644 --- a/crates/agentdeckd/src/api/repositories.rs +++ b/crates/agentdeckd/src/api/repositories.rs @@ -183,6 +183,24 @@ pub(crate) async fn link_delete( Ok(HttpResponseDeleted()) } +/// Workspace `id`'s Suggestions (spec §3): the Repositories its Panes work in that it doesn't +/// link, each as GitHub showed it when this run first asked about its name, by name ignoring +/// case. A Pane counts at its current folder, an exited one at its last known folder; its git +/// repo's `upstream` remote counts when it is on GitHub, else its `origin`. A Repository other +/// Workspaces link is still suggested; one GitHub can't see never is; signed out, only one +/// agentdeck keeps is. An archived Workspace has none. Not filtered by what the GUI was told +/// Not now. A Workspace that doesn't exist is 404 `not_found`. +#[endpoint { method = GET, path = "/v1/workspaces/{id}/suggestions" }] +pub(crate) async fn suggestion_list( + rqctx: RequestContext, + _auth: Authorized, + path: Path>, +) -> Result>, HttpError> { + let workspace = path.into_inner().id; + let suggestions = rqctx.context().suggestions.list(workspace).await?; + Ok(HttpResponseOk(suggestions)) +} + /// What linking each of `names` takes, in order: a Repository agentdeck keeps by that name /// now, ignoring case, or else the one GitHub shows by it, looked up as /// `GET /v1/repositories/resolve` does. The first that fails fails them all, before anything is diff --git a/crates/agentdeckd/src/daemon.rs b/crates/agentdeckd/src/daemon.rs index f4e0925..a1f2905 100644 --- a/crates/agentdeckd/src/daemon.rs +++ b/crates/agentdeckd/src/daemon.rs @@ -17,6 +17,7 @@ use crate::github_auth::{self, GithubAuth, device, keyring}; use crate::instance::Instance; use crate::paths::Paths; use crate::prsync::{self, PrSync}; +use crate::suggestions::Suggestions; use crate::terminal::Terminals; use crate::{agents, auth, logging}; @@ -97,6 +98,13 @@ async fn serve(paths: &Paths, instance: &Instance) -> anyhow::Result<()> { agents::resume::resume_panes(&restarter) .await .map_err(|err| anyhow::anyhow!("resuming panes: {err}"))?; + let suggestions = Suggestions::new( + db.clone(), + events.clone(), + credentials.clone(), + github.clone(), + ); + suggestions.watch(); let token = auth::new_token(); let context = ApiContext { db, @@ -108,6 +116,7 @@ async fn serve(paths: &Paths, instance: &Instance) -> anyhow::Result<()> { settings, terminals: terminals.clone(), events, + suggestions, }; let config = ConfigDropshot { bind_address: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)), diff --git a/crates/agentdeckd/src/db/panes.rs b/crates/agentdeckd/src/db/panes.rs index 11e93cd..605e0ff 100644 --- a/crates/agentdeckd/src/db/panes.rs +++ b/crates/agentdeckd/src/db/panes.rs @@ -2,7 +2,7 @@ use std::collections::HashSet; -use agentdeck_core::{Agent, AgentState, PaneId, WorkspaceId}; +use agentdeck_core::{Agent, AgentState, PaneId, TabId, WorkspaceId}; use rusqlite::{Connection, OptionalExtension, Row, params}; use super::{DbError, new_id, now, opt_text, text}; @@ -60,6 +60,28 @@ pub fn workspace_of(conn: &Connection, id: PaneId) -> Result Result, DbError> { + let mut stmt = conn.prepare( + "SELECT DISTINCT COALESCE(p.folder, p.cwd) FROM panes p JOIN tabs t ON t.id = p.tab_id + WHERE t.workspace_id = ?1 ORDER BY 1", + )?; + let rows = stmt.query_map([workspace.to_string()], |row| row.get(0))?; + Ok(rows.collect::>()?) +} + +/// The Workspace tab `id` is in; `None` once the tab is gone. +pub fn workspace_of_tab(conn: &Connection, id: TabId) -> Result, DbError> { + Ok(conn + .query_row( + "SELECT workspace_id FROM tabs WHERE id = ?1", + [id.to_string()], + |row| text(row, "workspace_id"), + ) + .optional()?) +} + /// Adds a pane to its tab, before its process starts: `argv` is what will be launched and /// `session_id` the agent session it starts on. Returns it with the workspace its tab is in. pub fn create( diff --git a/crates/agentdeckd/src/main.rs b/crates/agentdeckd/src/main.rs index bcef721..046c900 100644 --- a/crates/agentdeckd/src/main.rs +++ b/crates/agentdeckd/src/main.rs @@ -18,6 +18,7 @@ mod logging; mod model; mod paths; mod prsync; +mod suggestions; mod terminal; use std::process::ExitCode; diff --git a/crates/agentdeckd/src/suggestions/mod.rs b/crates/agentdeckd/src/suggestions/mod.rs new file mode 100644 index 0000000..6c184fc --- /dev/null +++ b/crates/agentdeckd/src/suggestions/mod.rs @@ -0,0 +1,387 @@ +//! Suggestions (spec §3, §4): the Repositories a Workspace's Panes work in that it doesn't +//! link, offered for linking. +//! +//! For each unarchived Workspace, every Pane's current folder (an exited one's last known +//! folder) gives the Repository of its git repo ([`remotes`]); the Repositories the Workspace +//! links are left out, those other Workspaces link aren't. Nothing scans the disk beyond those +//! folders. +//! +//! Each `owner/name` is confirmed with GitHub once per run, which gives its id; the answer, +//! GitHub's Repository or that GitHub can't see one by that name, is kept in memory, so one +//! GitHub can't see is never suggested. A failed call keeps nothing, and is tried again on the +//! next read. Signed out, only a Repository agentdeck keeps by that name, and the sign-in could +//! still see when it last looked, is suggested. +//! +//! [`Suggestions::watch`] works them out again whenever something they depend on changes (a +//! Pane opening, exiting, moving or going, a Link or the Workspace changing, a Repository +//! stored or renamed, the GitHub sign-in changing) and sends `changed suggestions` for each +//! Workspace whose Suggestions differ from the last ones it worked out. + +pub mod remotes; + +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::path::PathBuf; +use std::sync::Arc; + +use agentdeck_core::ws::{Entity, ServerMessage}; +use agentdeck_core::{PaneId, RepositoryName, TabId, WorkspaceId}; +use tokio::sync::{Mutex, broadcast}; + +use crate::db::{self, Db, DbError}; +use crate::events::Events; +use crate::github_auth::GithubAuth; +use crate::model::Repository; +use crate::prsync::github::{Github, GithubError, RemoteRepository}; + +/// Works out each Workspace's Suggestions; clones share the GitHub answers kept. +#[derive(Clone)] +pub struct Suggestions { + inner: Arc, +} + +struct Inner { + db: Db, + events: Events, + auth: GithubAuth, + github: Github, + /// GitHub's answer for each `owner/name` asked about this run, by the name in lower case: + /// the Repository, or `None` when GitHub can't see one by that name. Held across the call, + /// so two reads never ask about one name twice. + confirmed: Mutex>>, +} + +impl Suggestions { + /// Suggestions read from `db`, confirmed with `github` as `auth` signs in, announced on + /// `events`. + pub fn new(db: Db, events: Events, auth: GithubAuth, github: Github) -> Suggestions { + Suggestions { + inner: Arc::new(Inner { + db, + events, + auth, + github, + confirmed: Mutex::new(HashMap::new()), + }), + } + } + + /// Workspace `workspace`'s Suggestions, by name ignoring case, then id; none while it is + /// archived. One that doesn't exist is [`DbError::NotFound`]. + pub async fn list(&self, workspace: WorkspaceId) -> Result, DbError> { + let read = self + .inner + .db + .call(move |c| { + let archived = db::workspaces::get(c, workspace)?.archived_at.is_some(); + if archived { + return Ok(None); + } + let folders = db::panes::folders_in(c, workspace)?; + let linked = db::repositories::linked_by(c, workspace)?; + Ok(Some((folders, linked))) + }) + .await?; + let Some((folders, linked)) = read else { + return Ok(Vec::new()); + }; + let names = tokio::task::spawn_blocking(move || worked_in(&folders)) + .await + .unwrap_or_default(); + let linked: HashSet<_> = linked.into_iter().collect(); + let mut found: BTreeMap<_, Repository> = BTreeMap::new(); + for name in names.into_values() { + if let Some(repository) = self.confirm(&name).await? + && !linked.contains(&repository.id) + { + let key = (repository.name.to_string().to_lowercase(), repository.id); + found.insert(key, repository); + } + } + Ok(found.into_values().collect()) + } + + /// The Repository GitHub calls `name`, as this run first heard; signed out, the one + /// agentdeck keeps by that name while the sign-in could still see it. + async fn confirm(&self, name: &RepositoryName) -> Result, DbError> { + let key = name.to_string().to_lowercase(); + let mut confirmed = self.inner.confirmed.lock().await; + if let Some(answer) = confirmed.get(&key) { + return Ok(answer.clone().map(repository)); + } + let Some(token) = self.inner.auth.token() else { + drop(confirmed); + return self.known(name).await; + }; + let github = &self.inner.github; + let answer = match github.repository(&token, name).await { + Err(GithubError::Unauthorized) => match self.inner.auth.reread().await { + Ok(fresh) => github.repository(&fresh, name).await, + Err(_) => Err(GithubError::Unauthorized), + }, + answer => answer, + }; + match answer { + Ok(answer) => { + confirmed.insert(key, answer.clone()); + Ok(answer.map(repository)) + } + Err(err) => { + if matches!(err, GithubError::Unauthorized) { + self.inner.auth.rejected(); + } + tracing::warn!("confirming {name} for Suggestions: {err}"); + drop(confirmed); + self.known(name).await + } + } + } + + /// The Repository agentdeck keeps by `name`, ignoring case, unless the sign-in can't see + /// it any more. + async fn known(&self, name: &RepositoryName) -> Result, DbError> { + let name = name.clone(); + self.inner + .db + .call(move |c| { + let Some(id) = db::repositories::by_name(c, &name)? else { + return Ok(None); + }; + let kept = db::repositories::get(c, id)?; + Ok((!kept.unreachable).then_some(Repository { + id: kept.id, + name: kept.name, + url: kept.url, + private: kept.private, + archived: kept.archived, + })) + }) + .await + } + + /// Works Suggestions out again whenever `events` says something they depend on changed, + /// and sends `changed suggestions` for each Workspace whose Suggestions differ from the last + /// worked out. Runs until the runtime stops. + pub fn watch(&self) { + let this = self.clone(); + let mut feed = self.inner.events.subscribe(); + tokio::spawn(async move { + let mut last: HashMap> = HashMap::new(); + loop { + let mut due = Due::default(); + match feed.recv().await { + Ok(event) => due.add(&event), + Err(broadcast::error::RecvError::Lagged(_)) => due.all = true, + Err(broadcast::error::RecvError::Closed) => return, + } + // A burst (a PR sync's pages, a tab's panes going) is worked out once. + loop { + match feed.try_recv() { + Ok(event) => due.add(&event), + Err(broadcast::error::TryRecvError::Lagged(_)) => due.all = true, + Err(_) => break, + } + } + if due.is_empty() { + continue; + } + if let Err(err) = this.recompute(due, &mut last).await { + tracing::warn!("working out Suggestions: {err}"); + } + } + }); + } + + /// Works out the Suggestions of the Workspaces `due` names and announces those that + /// changed since `last`. + async fn recompute( + &self, + due: Due, + last: &mut HashMap>, + ) -> Result<(), DbError> { + let Due { + all, + workspaces, + panes, + tabs, + } = due; + let workspaces: Vec = self + .inner + .db + .call(move |c| { + if all { + return Ok(db::workspaces::list(c)?.into_iter().map(|w| w.id).collect()); + } + let mut ids: Vec = workspaces.into_iter().collect(); + let mut gone = false; + for pane in panes { + match db::panes::workspace_of(c, pane) { + Ok(id) => ids.push(id), + Err(DbError::NotFound(_)) => gone = true, + Err(err) => return Err(err), + } + } + for tab in tabs { + match db::panes::workspace_of_tab(c, tab)? { + Some(id) => ids.push(id), + None => gone = true, + } + } + // A Pane or tab deleted names no Workspace any more: look at them all. + if gone { + return Ok(db::workspaces::list(c)?.into_iter().map(|w| w.id).collect()); + } + ids.sort(); + ids.dedup(); + Ok(ids) + }) + .await?; + for workspace in workspaces { + let now = match self.list(workspace).await { + Ok(now) => now, + Err(DbError::NotFound(_)) => { + last.remove(&workspace); + continue; + } + Err(err) => return Err(err), + }; + if last + .get(&workspace) + .map_or(!now.is_empty(), |was| *was != now) + { + last.insert(workspace, now); + self.inner.events.changed(Entity::Suggestions, workspace); + } + } + Ok(()) + } +} + +/// The Repository a git repo's remote names, by the name in lower case, for each of `folders` +/// that is in one. +fn worked_in(folders: &[String]) -> BTreeMap { + (folders.iter()) + .filter_map(|folder| remotes::repository_of(&PathBuf::from(folder))) + .map(|name| (name.to_string().to_lowercase(), name)) + .collect() +} + +fn repository(found: RemoteRepository) -> Repository { + Repository { + id: found.id, + name: found.name, + url: found.url, + private: found.private, + archived: found.archived, + } +} + +/// Which Workspaces' Suggestions to work out again. +#[derive(Default)] +struct Due { + /// Every Workspace's. + all: bool, + workspaces: HashSet, + /// Those of the Workspaces these Panes are in. + panes: HashSet, + /// Those of the Workspaces these tabs are in. + tabs: HashSet, +} + +impl Due { + fn is_empty(&self) -> bool { + !self.all && self.workspaces.is_empty() && self.panes.is_empty() && self.tabs.is_empty() + } + + /// What `event` makes due: a Pane's Workspace when it opened, moved, exited or went; a + /// tab's when its layout changed; a Workspace when its Links or itself changed; every one + /// when a Repository was stored, renamed or deleted, or the sign-in changed. + fn add(&mut self, event: &ServerMessage) { + match event { + ServerMessage::Exit { pane, .. } => { + self.panes.insert(*pane); + } + ServerMessage::Changed { entity, id } => match entity { + Entity::Pane => match id.parse() { + Ok(pane) => { + self.panes.insert(pane); + } + Err(_) => self.all = true, + }, + Entity::Tab => match id.parse() { + Ok(tab) => { + self.tabs.insert(tab); + } + Err(_) => self.all = true, + }, + Entity::Workspace => match id.parse() { + Ok(workspace) => { + self.workspaces.insert(workspace); + } + Err(_) => self.all = true, + }, + Entity::Repository => self.all = true, + Entity::PrSync | Entity::Settings | Entity::PullRequest | Entity::Suggestions => {} + }, + ServerMessage::GithubAuth { .. } => self.all = true, + _ => {} + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + mod due { + use super::*; + + fn changed(entity: Entity, id: &str) -> ServerMessage { + ServerMessage::Changed { + entity, + id: id.into(), + } + } + + const PANE: &str = "019a0000-0000-7000-8000-000000000001"; + + #[test] + fn should_follow_a_panes_changes_and_its_exit() { + let mut due = Due::default(); + + due.add(&changed(Entity::Pane, PANE)); + due.add(&ServerMessage::Exit { + pane: PANE.parse().unwrap(), + code: Some(0), + }); + + assert_eq!(due.panes.len(), 1); + assert!(!due.all); + } + + #[test] + fn should_work_out_every_workspace_after_a_repository_or_sign_in_change() { + for event in [ + changed(Entity::Repository, "1296269"), + ServerMessage::GithubAuth { + device: None, + message: None, + }, + ] { + let mut due = Due::default(); + due.add(&event); + assert!(due.all); + } + } + + #[test] + fn should_ignore_its_own_announcements_and_pr_changes() { + let mut due = Due::default(); + + due.add(&changed(Entity::Suggestions, PANE)); + due.add(&changed(Entity::PullRequest, "1296269#7")); + due.add(&changed(Entity::PrSync, "status")); + + assert!(due.is_empty()); + } + } +} diff --git a/crates/agentdeckd/src/suggestions/remotes.rs b/crates/agentdeckd/src/suggestions/remotes.rs new file mode 100644 index 0000000..61ec0dc --- /dev/null +++ b/crates/agentdeckd/src/suggestions/remotes.rs @@ -0,0 +1,336 @@ +//! Which Repository a folder's git repo works in (spec §3 Suggestions): its `upstream` remote +//! when that is on GitHub, else its `origin`; any other remote is ignored. +//! +//! The remotes are read straight from the repo's `config` file, with no `git` process: the +//! folder or the nearest folder above it holding `.git`, a directory, or a file naming the +//! git dir (`gitdir: …`, as a worktree or a submodule has), whose `commondir` leads a worktree +//! to the main repo's config. `include` and `includeIf` files, and `url..insteadOf` +//! rewrites, aren't followed: a remote that only they make a GitHub URL suggests nothing. + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; + +use agentdeck_core::RepositoryName; + +/// The Repository the git repo holding `folder` works in: its `upstream` remote when that is on +/// GitHub, else its `origin` when that is. `None` outside a git repo, or when neither is. +pub fn repository_of(folder: &Path) -> Option { + let config = std::fs::read_to_string(config_file(folder)?).ok()?; + pick(&remote_urls(&config)) +} + +/// `upstream` when it is on GitHub, else `origin` when it is. +fn pick(remotes: &HashMap) -> Option { + ["upstream", "origin"] + .into_iter() + .find_map(|remote| RepositoryName::from_remote_url(remotes.get(remote)?)) +} + +/// The `config` file of the git repo holding `folder`, looking up from it. +fn config_file(folder: &Path) -> Option { + folder.ancestors().find_map(|dir| { + let dot_git = dir.join(".git"); + let git_dir = if dot_git.is_dir() { + dot_git + } else if dot_git.is_file() { + linked_git_dir(dir, &std::fs::read_to_string(&dot_git).ok()?)? + } else { + return None; + }; + // A worktree's git dir names the main repo's, which holds the config, in `commondir`. + let common = match std::fs::read_to_string(git_dir.join("commondir")) { + Ok(common) => git_dir.join(common.trim()), + Err(_) => git_dir, + }; + Some(common.join("config")) + }) +} + +/// The git dir a `.git` file in `dir` names (`gitdir: `, relative to `dir` or absolute). +fn linked_git_dir(dir: &Path, dot_git: &str) -> Option { + let path = dot_git + .lines() + .find_map(|line| line.strip_prefix("gitdir:"))?; + Some(dir.join(path.trim())) +} + +/// Each remote's URL in git config `text`, by the remote's name: its first `url`. +pub fn remote_urls(text: &str) -> HashMap { + let mut urls = HashMap::new(); + let mut remote: Option = None; + for line in text.lines() { + let line = line.trim(); + if line.is_empty() || line.starts_with(['#', ';']) { + continue; + } + if let Some(header) = line.strip_prefix('[') { + remote = remote_section(header); + // `[remote "origin"] url = …`: a key may follow its header on the line. + let Some((_, rest)) = header.split_once(']') else { + continue; + }; + if rest.trim().is_empty() { + continue; + } + if let (Some(name), Some(url)) = (&remote, url_value(rest.trim())) { + urls.entry(name.clone()).or_insert(url); + } + continue; + } + if let (Some(name), Some(url)) = (&remote, url_value(line)) { + urls.entry(name.clone()).or_insert(url); + } + } + urls +} + +/// The remote a section header names (the text after its `[`): `remote "origin"]`, or the old +/// `remote.origin]`, whose name git reads in lower case. `None` for any other section. +fn remote_section(header: &str) -> Option { + let (header, _) = header.split_once(']')?; + let header = header.trim(); + if let Some((section, sub)) = header.split_once(char::is_whitespace) { + let sub = sub.trim().strip_prefix('"')?.strip_suffix('"')?; + return section + .eq_ignore_ascii_case("remote") + .then(|| unescape(sub)); + } + let (section, sub) = header.split_once('.')?; + section + .eq_ignore_ascii_case("remote") + .then(|| sub.to_lowercase()) +} + +/// The value of a `url = …` line; `None` for another key. Quotes are taken off and an +/// unquoted `#` or `;` starts a comment. +fn url_value(line: &str) -> Option { + let (key, value) = line.split_once('=')?; + if !key.trim().eq_ignore_ascii_case("url") { + return None; + } + let mut out = String::new(); + let mut quoted = false; + let mut chars = value.trim().chars(); + while let Some(c) = chars.next() { + match c { + '"' => quoted = !quoted, + '\\' => out.extend(chars.next()), + '#' | ';' if !quoted => break, + c => out.push(c), + } + } + let url = out.trim().to_owned(); + (!url.is_empty()).then_some(url) +} + +/// A subsection name with git's `\"` and `\\` escapes undone. +fn unescape(sub: &str) -> String { + let mut out = String::new(); + let mut chars = sub.chars(); + while let Some(c) = chars.next() { + match c { + '\\' => out.extend(chars.next()), + c => out.push(c), + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn names(text: &str) -> Vec<(String, String)> { + let mut urls: Vec<_> = remote_urls(text).into_iter().collect(); + urls.sort(); + urls + } + + fn picked(text: &str) -> Option { + pick(&remote_urls(text)).map(|name| name.to_string()) + } + + mod remote_urls { + use super::*; + + #[test] + fn should_read_each_remotes_url_by_its_name() { + let config = "[core]\n\trepositoryformatversion = 0\n\ + [remote \"origin\"]\n\turl = git@github.com:me/widgets.git\n\ + \tfetch = +refs/heads/*:refs/remotes/origin/*\n\ + [remote \"upstream\"]\n\turl = https://github.com/acme/widgets.git\n\ + [branch \"main\"]\n\tremote = origin\n"; + + assert_eq!( + names(config), + [ + ("origin".into(), "git@github.com:me/widgets.git".into()), + ( + "upstream".into(), + "https://github.com/acme/widgets.git".into() + ), + ] + ); + } + + #[test] + fn should_keep_a_remotes_first_url() { + let config = "[remote \"origin\"]\nurl = https://github.com/a/one\n\ + url = https://github.com/a/two\n"; + + assert_eq!( + names(config), + [("origin".into(), "https://github.com/a/one".into())] + ); + } + + #[test] + fn should_ignore_case_in_section_and_key_but_not_in_the_remotes_name() { + let config = "[Remote \"Origin\"]\n URL = https://github.com/a/b\n"; + + assert_eq!( + names(config), + [("Origin".into(), "https://github.com/a/b".into())] + ); + } + + #[test] + fn should_read_the_old_dotted_header_in_lower_case() { + let config = "[remote.Upstream]\nurl = https://github.com/a/b\n"; + + assert_eq!( + names(config), + [("upstream".into(), "https://github.com/a/b".into())] + ); + } + + #[test] + fn should_skip_comments_and_take_off_quotes() { + let config = "# a comment\n; another\n[remote \"origin\"]\n\ + url = \"https://github.com/a/b\" # trailing\n"; + + assert_eq!( + names(config), + [("origin".into(), "https://github.com/a/b".into())] + ); + } + + #[test] + fn should_read_a_url_on_its_headers_line() { + let config = "[remote \"origin\"] url = https://github.com/a/b\n"; + + assert_eq!( + names(config), + [("origin".into(), "https://github.com/a/b".into())] + ); + } + + #[test] + fn should_not_take_a_url_from_another_section() { + let config = "[submodule \"lib\"]\nurl = https://github.com/a/lib\n\ + [url \"git@github.com:\"]\ninsteadOf = https://github.com/\n"; + + assert_eq!(names(config), []); + } + } + + mod pick { + use super::*; + + #[test] + fn should_prefer_upstream_on_github() { + let config = "[remote \"origin\"]\nurl = git@github.com:me/widgets.git\n\ + [remote \"upstream\"]\nurl = https://github.com/acme/widgets.git\n"; + + assert_eq!(picked(config).as_deref(), Some("acme/widgets")); + } + + #[test] + fn should_take_origin_when_upstream_is_not_on_github() { + let config = "[remote \"origin\"]\nurl = git@github.com:me/widgets.git\n\ + [remote \"upstream\"]\nurl = https://gitlab.com/acme/widgets.git\n"; + + assert_eq!(picked(config).as_deref(), Some("me/widgets")); + } + + #[test] + fn should_ignore_every_other_remote() { + let config = "[remote \"fork\"]\nurl = https://github.com/me/widgets\n\ + [remote \"origin\"]\nurl = https://gitlab.com/acme/widgets\n"; + + assert_eq!(picked(config), None); + } + } + + mod repository_of { + use super::*; + + fn write(path: &Path, text: &str) { + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, text).unwrap(); + } + + const ORIGIN: &str = "[remote \"origin\"]\n\turl = https://github.com/acme/widgets\n"; + + #[test] + fn should_read_the_repo_holding_a_folder_deep_inside_it() { + let dir = tempfile::tempdir().unwrap(); + write(&dir.path().join("repo/.git/config"), ORIGIN); + let deep = dir.path().join("repo/src/bin"); + std::fs::create_dir_all(&deep).unwrap(); + + assert_eq!( + repository_of(&deep).map(|n| n.to_string()).as_deref(), + Some("acme/widgets") + ); + } + + #[test] + fn should_follow_a_worktrees_git_file_to_the_main_repos_config() { + let dir = tempfile::tempdir().unwrap(); + write(&dir.path().join("main/.git/config"), ORIGIN); + write( + &dir.path().join("main/.git/worktrees/wt/commondir"), + "../..\n", + ); + write( + &dir.path().join("wt/.git"), + &format!( + "gitdir: {}\n", + dir.path().join("main/.git/worktrees/wt").display() + ), + ); + + assert_eq!( + repository_of(&dir.path().join("wt")) + .map(|n| n.to_string()) + .as_deref(), + Some("acme/widgets") + ); + } + + #[test] + fn should_follow_a_relative_git_file() { + let dir = tempfile::tempdir().unwrap(); + write(&dir.path().join("store/modules/lib/config"), ORIGIN); + write( + &dir.path().join("lib/.git"), + "gitdir: ../store/modules/lib\n", + ); + + assert_eq!( + repository_of(&dir.path().join("lib")) + .map(|n| n.to_string()) + .as_deref(), + Some("acme/widgets") + ); + } + + #[test] + fn should_find_none_outside_a_repo() { + let dir = tempfile::tempdir().unwrap(); + + assert_eq!(repository_of(dir.path()), None); + } + } +} diff --git a/crates/agentdeckd/tests/integration/main.rs b/crates/agentdeckd/tests/integration/main.rs index 1f49b59..1882b7f 100644 --- a/crates/agentdeckd/tests/integration/main.rs +++ b/crates/agentdeckd/tests/integration/main.rs @@ -21,6 +21,7 @@ mod repositories; mod repositories_client; mod settings; mod settings_client; +mod suggestions; mod support; mod tabs; mod version; diff --git a/crates/agentdeckd/tests/integration/repositories_client.rs b/crates/agentdeckd/tests/integration/repositories_client.rs index 2293a3a..b2c7302 100644 --- a/crates/agentdeckd/tests/integration/repositories_client.rs +++ b/crates/agentdeckd/tests/integration/repositories_client.rs @@ -247,3 +247,105 @@ mod unlink { assert_eq!(err.code.as_deref(), Some("not_found")); } } + +mod suggestions { + use agentdeck_client::repositories::suggestions; + use agentdeck_client::types::{NewPane, NewTab}; + use agentdeck_core::PaneKind; + + use super::*; + use crate::support::git::git; + + #[tokio::test] + async fn should_list_what_the_workspaces_panes_work_in_and_it_does_not_link() { + let github = MockServer::start_async().await; + mock_viewer(&github, TOKEN, "octocat", None); + mock_rest_repo( + &github, + TOKEN, + "acme/widgets", + RestRepo::new("acme/widgets"), + ); + let dirs = tempfile::tempdir().expect("a temp dir"); + set_gh_token(dirs.path(), Some(TOKEN)); + let daemon = TestDaemon::start_with_github(dirs, &github.url("/graphql")).await; + let dir = daemon.new_dir("widgets"); + git(&dir, &["init", "--quiet"]); + git( + &dir, + &["remote", "add", "origin", "git@github.com:acme/widgets.git"], + ); + let web = (daemon.client.workspace_create()) + .body(NewWorkspace { + name: "web".into(), + link: Vec::new(), + }) + .send() + .await + .expect("create a workspace") + .into_inner(); + let tab = (daemon.client.tab_create()) + .id(web.id) + .body(NewTab { + title: "tab".into(), + layout: None, + }) + .send() + .await + .expect("create a tab") + .into_inner(); + (daemon.client.pane_create()) + .body(NewPane { + tab_id: tab.id, + kind: PaneKind::Shell, + agent: None, + argv: Some(vec!["sleep".into(), "600".into()]), + cwd: dir.to_str().expect("a UTF-8 path").to_owned(), + }) + .send() + .await + .expect("spawn a pane"); + + let suggested = suggestions(&daemon.client, web.id) + .await + .expect("list Suggestions"); + + assert_eq!( + suggested, + [Repository { + id: RepositoryId::from(repository_id("acme/widgets")), + name: "acme/widgets".parse().unwrap(), + url: "https://github.com/acme/widgets".into(), + private: false, + archived: false, + }] + ); + } + + #[tokio::test] + async fn should_list_none_on_a_daemon_older_than_the_route() { + let daemon = TestDaemon::start().await; + let older = agentdeck_client::authenticated( + &format!("{}/later", daemon.base_url()), + &daemon.info.token, + ) + .expect("a client"); + let workspace: WorkspaceId = "019a0000-0000-7000-8000-000000000001".parse().unwrap(); + + let suggested = suggestions(&older, workspace).await.expect("no failure"); + + assert_eq!(suggested, []); + } + + #[tokio::test] + async fn should_fail_with_the_daemons_words_for_a_workspace_that_does_not_exist() { + let daemon = TestDaemon::start().await; + let workspace: WorkspaceId = "019a0000-0000-7000-8000-000000000001".parse().unwrap(); + + let err = suggestions(&daemon.client, workspace) + .await + .expect_err("a refusal"); + + assert_eq!(err.code.as_deref(), Some("not_found")); + } +} diff --git a/crates/agentdeckd/tests/integration/suggestions.rs b/crates/agentdeckd/tests/integration/suggestions.rs new file mode 100644 index 0000000..05be0d6 --- /dev/null +++ b/crates/agentdeckd/tests/integration/suggestions.rs @@ -0,0 +1,583 @@ +//! Suggestions: `GET /v1/workspaces/{id}/suggestions` and `changed suggestions` (spec §3, §4, +//! §5), with Panes running `sh` in temp git repos whose remotes name GitHub Repositories, and +//! httpmock as GitHub's REST API. + +use std::path::{Path, PathBuf}; + +use agentdeck_client::Client; +use agentdeck_client::types::{ + InputWhen, NewLink, NewPane, NewTab, NewWorkspace, Pane, PaneInput, Repository, Workspace, +}; +use agentdeck_core::ws::{Entity, ServerMessage}; +use agentdeck_core::{AgentState, PaneKind, RepositoryId, TabId, WorkspaceId}; +use httpmock::MockServer; + +use crate::support::git::git; +use crate::support::github::{ + RestRepo, mock_rest_repo, mock_rest_repo_missing, mock_viewer, set_gh_token, +}; +use crate::support::terminal::{eventually, in_state, sh}; +use crate::support::ws::{Frame, Ws}; +use crate::support::{TestDaemon, error_response}; + +const TOKEN: &str = "gho_test"; +const WIDGETS: &str = "acme/widgets"; +const GADGETS: &str = "acme/gadgets"; + +/// A daemon whose `gh` prints [`TOKEN`] and whose GitHub is `github`. +async fn signed_in(github: &MockServer) -> TestDaemon { + mock_viewer(github, TOKEN, "octocat", None); + let dirs = tempfile::tempdir().expect("a temp dir"); + set_gh_token(dirs.path(), Some(TOKEN)); + TestDaemon::start_with_github(dirs, &github.url("/graphql")).await +} + +/// A git repo `name` under the daemon's temp root with these remotes, by name and URL. +fn repo(daemon: &TestDaemon, name: &str, remotes: &[(&str, &str)]) -> PathBuf { + let dir = daemon.new_dir(name); + git(&dir, &["init", "--quiet"]); + for (remote, url) in remotes { + git(&dir, &["remote", "add", remote, url]); + } + dir +} + +/// A Workspace `name` with one tab, for Panes to go in. +async fn workspace(client: &Client, name: &str) -> (Workspace, TabId) { + let workspace = client + .workspace_create() + .body(NewWorkspace { + name: name.into(), + link: Vec::new(), + }) + .send() + .await + .expect("create a workspace") + .into_inner(); + let tab = client + .tab_create() + .id(workspace.id) + .body(NewTab { + title: "tab".into(), + layout: None, + }) + .send() + .await + .expect("create a tab") + .into_inner(); + (workspace, tab.id) +} + +/// A shell Pane in `tab` running `argv` in `dir`. +async fn spawn(client: &Client, tab: TabId, dir: &Path, argv: &[&str]) -> Pane { + client + .pane_create() + .body(NewPane { + tab_id: tab, + kind: PaneKind::Shell, + agent: None, + argv: Some(argv.iter().map(|arg| (*arg).to_owned()).collect()), + cwd: dir.to_str().expect("a UTF-8 path").to_owned(), + }) + .send() + .await + .expect("spawn a pane") + .into_inner() +} + +/// A Pane in `tab` that starts in `dir` and stays. +async fn working_in(client: &Client, tab: TabId, dir: &Path) -> Pane { + spawn(client, tab, dir, &["sleep", "600"]).await +} + +async fn suggestions(client: &Client, workspace: WorkspaceId) -> Vec { + let response = client.suggestion_list().id(workspace).send().await; + response.expect("list Suggestions").into_inner() +} + +async fn names(client: &Client, workspace: WorkspaceId) -> Vec { + (suggestions(client, workspace).await.iter()) + .map(|r| r.name.to_string()) + .collect() +} + +/// Waits until `workspace`'s Suggestions are `wanted`, by name. +async fn until_names(client: &Client, workspace: WorkspaceId, wanted: &[&str]) { + eventually(&format!("Suggestions {wanted:?}"), || async { + (names(client, workspace).await == wanted).then_some(()) + }) + .await; +} + +/// The Repository GitHub shows for `repo`, as a Suggestion carries it. +fn suggested(repo: RestRepo) -> Repository { + Repository { + id: RepositoryId::from(repo.id), + name: repo.name.parse().unwrap(), + url: repo.url(), + private: repo.private, + archived: false, + } +} + +/// Waits for `changed suggestions` naming `workspace`. +async fn changed_suggestions(ws: &mut Ws, workspace: WorkspaceId) { + ws.until(|frame| match frame { + Frame::Message(ServerMessage::Changed { + entity: Entity::Suggestions, + id, + }) if id == workspace.to_string() => Some(()), + _ => None, + }) + .await; +} + +/// Links `workspace` to `repo` by GitHub's id, as the GUI does, so it works signed out. +async fn link_held(client: &Client, workspace: WorkspaceId, repo: RestRepo) { + client + .link_create() + .id(workspace) + .body(NewLink { + repository: repo.name.parse().unwrap(), + id: Some(RepositoryId::from(repo.id)), + url: Some(repo.url()), + private: Some(repo.private), + archived: Some(false), + }) + .send() + .await + .expect("link"); +} + +mod get_v1_workspaces_suggestions { + use super::*; + + mod remotes { + use super::*; + + #[tokio::test] + async fn should_suggest_the_upstream_remote_when_it_is_on_github_200() { + let github = MockServer::start_async().await; + mock_rest_repo(&github, TOKEN, WIDGETS, RestRepo::new(WIDGETS)); + let daemon = signed_in(&github).await; + let dir = repo( + &daemon, + "fork", + &[ + ("origin", "git@github.com:octocat/widgets.git"), + ("upstream", "https://github.com/acme/widgets.git"), + ], + ); + let (web, tab) = workspace(&daemon.client, "web").await; + + working_in(&daemon.client, tab, &dir).await; + + assert_eq!( + suggestions(&daemon.client, web.id).await, + [suggested(RestRepo::new(WIDGETS))] + ); + } + + #[tokio::test] + async fn should_take_origin_when_upstream_is_not_on_github_200() { + let github = MockServer::start_async().await; + mock_rest_repo(&github, TOKEN, WIDGETS, RestRepo::new(WIDGETS)); + let daemon = signed_in(&github).await; + let dir = repo( + &daemon, + "mirror", + &[ + ("origin", "git@github.com:acme/widgets.git"), + ("upstream", "https://gitlab.com/acme/widgets.git"), + ], + ); + let (web, tab) = workspace(&daemon.client, "web").await; + + working_in(&daemon.client, tab, &dir).await; + + assert_eq!(names(&daemon.client, web.id).await, [WIDGETS]); + } + + #[tokio::test] + async fn should_ignore_every_other_remote_200() { + let github = MockServer::start_async().await; + let lookups = mock_rest_repo(&github, TOKEN, WIDGETS, RestRepo::new(WIDGETS)); + let daemon = signed_in(&github).await; + let dir = repo( + &daemon, + "other", + &[("fork", "https://github.com/acme/widgets.git")], + ); + let (web, tab) = workspace(&daemon.client, "web").await; + + working_in(&daemon.client, tab, &dir).await; + + assert_eq!(names(&daemon.client, web.id).await, Vec::::new()); + assert_eq!(lookups.calls(), 0); + } + + #[tokio::test] + async fn should_suggest_nothing_for_a_folder_outside_a_repo_200() { + let daemon = TestDaemon::start().await; + let (web, tab) = workspace(&daemon.client, "web").await; + + working_in(&daemon.client, tab, &daemon.new_dir("plain")).await; + + assert_eq!(names(&daemon.client, web.id).await, Vec::::new()); + } + + #[tokio::test] + async fn should_suggest_each_repository_once_by_name_200() { + let github = MockServer::start_async().await; + mock_rest_repo(&github, TOKEN, WIDGETS, RestRepo::new(WIDGETS)); + mock_rest_repo(&github, TOKEN, GADGETS, RestRepo::new(GADGETS)); + let daemon = signed_in(&github).await; + let widgets = repo( + &daemon, + "widgets", + &[("origin", "https://github.com/acme/widgets")], + ); + let gadgets = repo( + &daemon, + "gadgets", + &[("origin", "https://github.com/acme/gadgets")], + ); + let (web, tab) = workspace(&daemon.client, "web").await; + + working_in(&daemon.client, tab, &widgets).await; + working_in(&daemon.client, tab, &gadgets).await; + working_in(&daemon.client, tab, &widgets.join(".git")).await; + + assert_eq!(names(&daemon.client, web.id).await, [GADGETS, WIDGETS]); + } + } + + mod folders { + use super::*; + + #[tokio::test] + async fn should_follow_a_pane_that_moves_into_a_repo_200() { + let github = MockServer::start_async().await; + mock_rest_repo(&github, TOKEN, WIDGETS, RestRepo::new(WIDGETS)); + let daemon = signed_in(&github).await; + let dir = repo( + &daemon, + "widgets", + &[("origin", "https://github.com/acme/widgets")], + ); + let (web, tab) = workspace(&daemon.client, "web").await; + let script = format!("cd '{}' && echo moved && exec sleep 600", dir.display()); + + spawn(&daemon.client, tab, &daemon.new_dir("plain"), &sh(&script)).await; + + until_names(&daemon.client, web.id, &[WIDGETS]).await; + } + + #[tokio::test] + async fn should_keep_an_exited_panes_last_known_folder_200() { + let github = MockServer::start_async().await; + mock_rest_repo(&github, TOKEN, WIDGETS, RestRepo::new(WIDGETS)); + let daemon = signed_in(&github).await; + let dir = repo( + &daemon, + "widgets", + &[("origin", "https://github.com/acme/widgets")], + ); + let (web, tab) = workspace(&daemon.client, "web").await; + let script = format!("cd '{}' && echo moved && read line", dir.display()); + let pane = spawn(&daemon.client, tab, &daemon.new_dir("plain"), &sh(&script)).await; + until_names(&daemon.client, web.id, &[WIDGETS]).await; + + daemon + .client + .pane_input() + .id(pane.id) + .body(PaneInput { + text: "\r".into(), + when: InputWhen::Now, + submit: false, + }) + .send() + .await + .expect("type into the pane"); + in_state(&daemon.client, pane.id, AgentState::Exited).await; + + assert_eq!(names(&daemon.client, web.id).await, [WIDGETS]); + } + } + + mod github { + use super::*; + + #[tokio::test] + async fn should_never_suggest_a_repository_github_cannot_see_200() { + let github = MockServer::start_async().await; + mock_rest_repo_missing(&github, WIDGETS); + let daemon = signed_in(&github).await; + let dir = repo( + &daemon, + "widgets", + &[("origin", "https://github.com/acme/widgets")], + ); + let (web, tab) = workspace(&daemon.client, "web").await; + + working_in(&daemon.client, tab, &dir).await; + + assert_eq!(names(&daemon.client, web.id).await, Vec::::new()); + } + + #[tokio::test] + async fn should_suggest_a_renamed_repository_under_the_name_github_gives_200() { + let github = MockServer::start_async().await; + let renamed = RestRepo::new("acme/widgets-v2"); + mock_rest_repo(&github, TOKEN, WIDGETS, renamed); + let daemon = signed_in(&github).await; + let dir = repo( + &daemon, + "widgets", + &[("origin", "https://github.com/acme/widgets")], + ); + let (web, tab) = workspace(&daemon.client, "web").await; + + working_in(&daemon.client, tab, &dir).await; + + assert_eq!( + suggestions(&daemon.client, web.id).await, + [suggested(renamed)] + ); + } + + #[tokio::test] + async fn should_ask_github_about_each_name_once_per_run_200() { + let github = MockServer::start_async().await; + let lookups = mock_rest_repo(&github, TOKEN, WIDGETS, RestRepo::new(WIDGETS)); + let missing = mock_rest_repo_missing(&github, GADGETS); + let daemon = signed_in(&github).await; + let widgets = repo( + &daemon, + "widgets", + &[("origin", "https://github.com/acme/widgets")], + ); + let gadgets = repo( + &daemon, + "gadgets", + &[("origin", "https://github.com/acme/gadgets")], + ); + let (web, web_tab) = workspace(&daemon.client, "web").await; + let (api, api_tab) = workspace(&daemon.client, "api").await; + working_in(&daemon.client, web_tab, &widgets).await; + working_in(&daemon.client, web_tab, &gadgets).await; + working_in(&daemon.client, api_tab, &widgets).await; + + for _ in 0..3 { + assert_eq!(names(&daemon.client, web.id).await, [WIDGETS]); + assert_eq!(names(&daemon.client, api.id).await, [WIDGETS]); + } + + assert_eq!(lookups.calls(), 1, "acme/widgets asked about once"); + assert_eq!(missing.calls(), 1, "acme/gadgets asked about once"); + } + } + + mod signed_out { + use super::*; + + #[tokio::test] + async fn should_suggest_only_repositories_agentdeck_keeps_200() { + let daemon = TestDaemon::start().await; + let kept = RestRepo::new(WIDGETS); + let (other, _) = workspace(&daemon.client, "other").await; + link_held(&daemon.client, other.id, kept).await; + let widgets = repo( + &daemon, + "widgets", + &[("origin", "https://github.com/acme/widgets")], + ); + let gadgets = repo( + &daemon, + "gadgets", + &[("origin", "https://github.com/acme/gadgets")], + ); + let (web, tab) = workspace(&daemon.client, "web").await; + + working_in(&daemon.client, tab, &widgets).await; + working_in(&daemon.client, tab, &gadgets).await; + + assert_eq!(suggestions(&daemon.client, web.id).await, [suggested(kept)]); + } + } + + mod links { + use super::*; + + #[tokio::test] + async fn should_suggest_a_repository_other_workspaces_link_200() { + let github = MockServer::start_async().await; + mock_rest_repo(&github, TOKEN, WIDGETS, RestRepo::new(WIDGETS)); + let daemon = signed_in(&github).await; + let (api, _) = workspace(&daemon.client, "api").await; + link_held(&daemon.client, api.id, RestRepo::new(WIDGETS)).await; + let dir = repo( + &daemon, + "widgets", + &[("origin", "https://github.com/acme/widgets")], + ); + let (web, tab) = workspace(&daemon.client, "web").await; + + working_in(&daemon.client, tab, &dir).await; + + assert_eq!(names(&daemon.client, web.id).await, [WIDGETS]); + } + + #[tokio::test] + async fn should_leave_out_what_the_workspace_links_200() { + let github = MockServer::start_async().await; + mock_rest_repo(&github, TOKEN, WIDGETS, RestRepo::new(WIDGETS)); + let daemon = signed_in(&github).await; + let dir = repo( + &daemon, + "widgets", + &[("origin", "https://github.com/acme/widgets")], + ); + let (web, tab) = workspace(&daemon.client, "web").await; + working_in(&daemon.client, tab, &dir).await; + assert_eq!(names(&daemon.client, web.id).await, [WIDGETS]); + + link_held(&daemon.client, web.id, RestRepo::new(WIDGETS)).await; + + assert_eq!(names(&daemon.client, web.id).await, Vec::::new()); + } + } + + #[tokio::test] + async fn should_give_an_archived_workspace_none_200() { + let daemon = TestDaemon::start().await; + let kept = RestRepo::new(WIDGETS); + let (other, _) = workspace(&daemon.client, "other").await; + link_held(&daemon.client, other.id, kept).await; + let dir = repo( + &daemon, + "widgets", + &[("origin", "https://github.com/acme/widgets")], + ); + let (web, tab) = workspace(&daemon.client, "web").await; + let pane = spawn(&daemon.client, tab, &dir, &["true"]).await; + in_state(&daemon.client, pane.id, AgentState::Exited).await; + assert_eq!(names(&daemon.client, web.id).await, [WIDGETS]); + + daemon + .client + .workspace_archive() + .id(web.id) + .send() + .await + .expect("archive"); + + assert_eq!(names(&daemon.client, web.id).await, Vec::::new()); + } + + #[tokio::test] + async fn should_not_find_a_workspace_that_does_not_exist_404() { + let daemon = TestDaemon::start().await; + let missing: WorkspaceId = "019a0000-0000-7000-8000-000000000001".parse().unwrap(); + + let (status, body) = + error_response(daemon.client.suggestion_list().id(missing).send().await); + + assert_eq!(status, 404); + assert_eq!(body.error_code.as_deref(), Some("not_found")); + } +} + +mod changed_suggestions { + use super::*; + + #[tokio::test] + async fn should_be_sent_when_a_pane_opens_in_a_repo() { + let github = MockServer::start_async().await; + mock_rest_repo(&github, TOKEN, WIDGETS, RestRepo::new(WIDGETS)); + let daemon = signed_in(&github).await; + let dir = repo( + &daemon, + "widgets", + &[("origin", "https://github.com/acme/widgets")], + ); + let (web, tab) = workspace(&daemon.client, "web").await; + let mut ws = Ws::connect(&daemon).await; + + working_in(&daemon.client, tab, &dir).await; + + changed_suggestions(&mut ws, web.id).await; + } + + #[tokio::test] + async fn should_be_sent_when_a_pane_moves_into_a_repo() { + let github = MockServer::start_async().await; + mock_rest_repo(&github, TOKEN, WIDGETS, RestRepo::new(WIDGETS)); + let daemon = signed_in(&github).await; + let dir = repo( + &daemon, + "widgets", + &[("origin", "https://github.com/acme/widgets")], + ); + let (web, tab) = workspace(&daemon.client, "web").await; + let mut ws = Ws::connect(&daemon).await; + let script = format!( + "sleep 1 && cd '{}' && echo moved && exec sleep 600", + dir.display() + ); + + spawn(&daemon.client, tab, &daemon.new_dir("plain"), &sh(&script)).await; + + changed_suggestions(&mut ws, web.id).await; + assert_eq!(names(&daemon.client, web.id).await, [WIDGETS]); + } + + #[tokio::test] + async fn should_be_sent_when_a_link_takes_a_suggestion_away() { + let github = MockServer::start_async().await; + mock_rest_repo(&github, TOKEN, WIDGETS, RestRepo::new(WIDGETS)); + let daemon = signed_in(&github).await; + let dir = repo( + &daemon, + "widgets", + &[("origin", "https://github.com/acme/widgets")], + ); + let (web, tab) = workspace(&daemon.client, "web").await; + let mut ws = Ws::connect(&daemon).await; + working_in(&daemon.client, tab, &dir).await; + changed_suggestions(&mut ws, web.id).await; + + link_held(&daemon.client, web.id, RestRepo::new(WIDGETS)).await; + + changed_suggestions(&mut ws, web.id).await; + assert_eq!(names(&daemon.client, web.id).await, Vec::::new()); + } + + #[tokio::test] + async fn should_be_sent_when_the_last_pane_in_a_repo_is_deleted() { + let github = MockServer::start_async().await; + mock_rest_repo(&github, TOKEN, WIDGETS, RestRepo::new(WIDGETS)); + let daemon = signed_in(&github).await; + let dir = repo( + &daemon, + "widgets", + &[("origin", "https://github.com/acme/widgets")], + ); + let (web, tab) = workspace(&daemon.client, "web").await; + let mut ws = Ws::connect(&daemon).await; + let pane = working_in(&daemon.client, tab, &dir).await; + changed_suggestions(&mut ws, web.id).await; + + daemon + .client + .pane_delete() + .id(pane.id) + .send() + .await + .expect("delete the pane"); + + changed_suggestions(&mut ws, web.id).await; + assert_eq!(names(&daemon.client, web.id).await, Vec::::new()); + } +} diff --git a/docs/spec.md b/docs/spec.md index cb5cbb3..e0e0290 100644 --- a/docs/spec.md +++ b/docs/spec.md @@ -120,6 +120,12 @@ A **Link** ties one Workspace to one Repository, at most once per pair; the user 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 **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. +- **Which remote counts:** the git repo holding the folder (the folder or the nearest one above it with `.git`) gives its `upstream` remote when that is a GitHub URL (`RepositoryName::from_remote_url`: https, ssh and scp-like), else its `origin` when that is; any other remote is ignored. In a fork setup that gives the base repo, where your PRs live. The remotes are read from the repo's own `config` file, with no `git` process: `.git` is a directory, or a file naming the git dir (`gitdir: …`, as a worktree or submodule has), whose `commondir` leads a worktree to the main repo's config. `include`, `includeIf` and `url..insteadOf` aren't followed. +- **Which Repositories count:** each `owner/name` is confirmed with GitHub once per run (REST `GET /repos/{owner}/{repo}`, as a lookup, §8), which gives its id and its name now; the answer, the Repository or that GitHub can't see one, is kept in memory for the run, so a name is asked about once however many Panes and Workspaces work in it. One GitHub can't see is never suggested. A failed call keeps nothing and is tried again on the next read. Signed out (no token, or one GitHub rejects), only a Repository agentdeck keeps by that name (§3), ignoring case, and that isn't Unreachable is suggested. Then the Repositories the Workspace links go; one other Workspaces link stays. An archived Workspace has none. +- **Dismissals** (Not now, and unlinks made in the GUI) are GUI state (§11), never the daemon's: the daemon's Suggestions aren't filtered by them. + v1.1 adds `channels`, `channel_members` and `messages` in their own migration. ## 4. HTTP API (`/v1`, dropshot) @@ -128,6 +134,8 @@ v1.1 adds `channels`, `channel_members` and `messages` in their own migration. Every pane in a response (`POST` and `GET` on `/v1/panes`) carries `hosted_agent`: `claude` or `codex` while a shell pane hosts that agent (§3, §7), else null. It came with `API_VERSION` 6. Every pane also carries `folder`, its current folder (§3, §6), an absolute path; it came with `API_VERSION` 18. +`API_VERSION` 26 added a Workspace's Suggestions (§3): `GET /v1/workspaces/{id}/suggestions` and the `suggestions` change event (§5). An older daemon answers the route with its code-less 404, which the client reads as no Suggestions, so the GUI shows none there until its Restart banner (§2) is followed; an older client skips the event. + `API_VERSION` 25 let `POST /v1/workspaces/{id}/links` link a Repository by GitHub's id (§11 Pull requests view, Group menu): it takes `id`, `url`, `private` and `archived` beside `repository`, and with `id` it never asks GitHub. An older daemon ignores them and looks the name up, so Undo after an unlink that deleted the Repository fails there while signed out; the GUI's Restart banner (§2) comes first. `API_VERSION` 24 let a Workspace's create and update carry its Links (§11 Edit workspace and New workspace): `POST /v1/workspaces` takes `link`, and `PATCH /v1/workspaces/{id}` takes `link` and `unlink`, beside `name` and `muted`. An older daemon ignores both fields, so the GUI's Restart banner (§2) comes first. @@ -145,6 +153,7 @@ Every pane in a response (`POST` and `GET` on `/v1/panes`) carries `hosted_agent | `GET /v1/repositories?workspace=` | every Repository agentdeck keeps (§3), each a `RepositoryLinks`: `{ id, name, url, private, archived, unreachable, workspaces }`, GitHub's id, `owner/name`, its page, whether it is private and archived as GitHub last said, whether the GitHub sign-in can no longer see it, and the ids of the Workspaces that link it, oldest first, archived ones included (empty for one kept only for its PRs). Ordered by name ignoring case, then id. `workspace` (an id) keeps only the Repositories that Workspace links; one that doesn't exist is `unknown_workspace`. It came with `API_VERSION` 19 | | `GET /v1/repositories/resolve?repository=` | look a typed Repository up on GitHub (§8): `repository` is `owner/name` or its GitHub URL (text that names none is dropshot's own 400). Answers the `Repository` (`{ id, name, url, private, archived }`) as GitHub shows it now, an old name finding a renamed one under its new name. Stores no new Repository; a known one takes GitHub's name, URL, private and archived (a `changed` event when they differ). `400 unknown_repository` when GitHub doesn't show it, `409 not_signed_in`, `502 github_error`. It came with `API_VERSION` 19 | | `POST /v1/workspaces/{id}/links`, `DELETE /v1/workspaces/{id}/links/{repository}` | link the Workspace to a Repository, and unlink it. POST `{ repository: "owner/name" }` (or its GitHub URL) finds a Repository agentdeck keeps by its name now, ignoring case, without asking GitHub; one it doesn't is resolved first, as above, and stored with the Link, so one GitHub doesn't show is `400 unknown_repository` and links nothing (`409 not_signed_in` and `502 github_error` as above). POST `{ repository, id, url?, private?, archived? }` links by GitHub's `id` instead, as a client holds the Repository (the GUI always does, so a group's Link and an unlink's Undo work signed out): the Repository agentdeck keeps with that id is linked as it is, whatever its name now, and one it no longer keeps (an unlink deleted it, §3) is stored again from the body, `url` defaulting to `https://github.com/` and `private` and `archived` to false, never asking GitHub; PR sync corrects what GitHub says differently. Linking a pair already linked changes nothing. It answers 200 with the `RepositoryLinks`. DELETE names the Repository by its id and answers 204; the Repository goes too when no other Link names it and no stored PR belongs to it (§3). Both are `404 not_found` for a Workspace that doesn't exist, DELETE also for a Repository the Workspace doesn't link. Each sends `changed` for the Repository, then the Workspace, when a Link was added or removed. They came with `API_VERSION` 19, linking by `id` with 25 | +| `GET /v1/workspaces/{id}/suggestions` | the Workspace's Suggestions (§3), each a `Repository` (`{ id, name, url, private, archived }`) as GitHub showed it when this run first asked about its name (signed out, as agentdeck keeps it), ordered by name ignoring case, then id; `[]` for an archived Workspace. Not filtered by what the GUI was told Not now. Worked out as it answers, so it never lags a Pane's move. `404 not_found` for a Workspace that doesn't exist. It came with `API_VERSION` 26 | | `GET/POST /v1/workspaces/{id}/tabs`, `PATCH/DELETE /v1/tabs/{id}` | tabs and their layout tree, listed in `position` order | | `POST /v1/panes` | spawn: `{tab_id, kind, agent?, argv?, cwd}`; see §6. `cwd` must be an existing absolute dir (`invalid_dir`); a shell without `argv` runs `$SHELL`, else `/bin/sh`; a program that can't start is `invalid_argv`. An agent pane names its `agent` and a shell names none (`unsupported_kind`); `other` needs `argv`, `claude` and `codex` take none (`invalid_argv`). The PTY starts at 80×24. The client places the pane in the tab's `layout` | | `GET /v1/panes/{id}`, `DELETE /v1/panes/{id}` | read (live title, state, exit code and `hosted_agent` while the process runs in this daemon, and `folder`, read again as it answers: a pane that moved is saved there first and gets `changed`, §6); kill (SIGHUP to its process group and the foreground one, then SIGKILL after 3 s) and delete. Deleting a tab or workspace kills its panes too | @@ -184,6 +193,7 @@ Daemon → client: {"t":"exit","pane":"","code":0} {"t":"changed","entity":"pull_request","id":"1296269#7"} {"t":"changed","entity":"repository","id":"1296269"} +{"t":"changed","entity":"suggestions","id":""} {"t":"github_auth","device":"signed_in"} {"t":"lagged","channel":3} {"t":"resync"} @@ -199,7 +209,7 @@ The message types are `agentdeck_core::ws::{ClientMessage, ServerMessage}`. - **Resize:** the **primary** client's size wins. The most recent client to send `primary` (the focused GUI window) is primary; until one does, or after it detaches, any client's resize applies. A resize from any other client is ignored and answered with `resize` carrying the size the pane keeps. Sending `primary` applies the size that client last asked for. Other attached clients get `resize` when the size changes; bytes after it were written at the new size. - **Terminal queries** (DA, cursor position, …) are answered only by the daemon's `Term`. Clients drop the replies their own `Term` generates. - **Backpressure:** a client more than 1 MiB behind on a channel gets `lagged`. It then re-attaches for a fresh snapshot. -- **Data events:** `changed` tells clients to refetch an entity over REST: `workspace`, `tab` or `pane`, after it is created, changed or deleted (a pane also when an agent starts or stops being hosted in it, §7, and when its current folder moves, §6); `pr_sync` (id `status`) means `GET /v1/prs/status`, when a PR sync begins, reads a page or ends, or a PATCH changes the age cutoff; `settings` (id `settings`) means `GET /v1/settings`, after every PATCH; `repository` (id GitHub's repository id) means `GET /v1/repositories` and `GET /v1/prs`, when PR sync or a lookup stores a Repository it didn't have or GitHub renamed, transferred or otherwise changed one (§8), when a Link to it is added or removed, the Repository deleted with it included (§4), and when PR sync deletes it once no Link and no kept PR references it (§8; it came with `API_VERSION` 16, and an older client skips it); `pull_request` (id its Repository's GitHub id and its number, `1296269#7`, so a rename keeps it) means `GET /v1/prs`, when PR sync stores a PR it didn't have, stores one changed, marks one unreachable or Finished, or deletes one, and when a close from agentdeck stores one closed (§8; it came with `API_VERSION` 22, replacing `task`, and an older client skips it); a Link change sends `workspace` for its Workspace after it. `state` and `exit` are sent to every client, attached or not. The daemon subscribes a connection to these events before it answers the upgrade, so every event published after the client sees the 101 reaches it. +- **Data events:** `changed` tells clients to refetch an entity over REST: `workspace`, `tab` or `pane`, after it is created, changed or deleted (a pane also when an agent starts or stops being hosted in it, §7, and when its current folder moves, §6); `pr_sync` (id `status`) means `GET /v1/prs/status`, when a PR sync begins, reads a page or ends, or a PATCH changes the age cutoff; `settings` (id `settings`) means `GET /v1/settings`, after every PATCH; `repository` (id GitHub's repository id) means `GET /v1/repositories` and `GET /v1/prs`, when PR sync or a lookup stores a Repository it didn't have or GitHub renamed, transferred or otherwise changed one (§8), when a Link to it is added or removed, the Repository deleted with it included (§4), and when PR sync deletes it once no Link and no kept PR references it (§8; it came with `API_VERSION` 16, and an older client skips it); `pull_request` (id its Repository's GitHub id and its number, `1296269#7`, so a rename keeps it) means `GET /v1/prs`, when PR sync stores a PR it didn't have, stores one changed, marks one unreachable or Finished, or deletes one, and when a close from agentdeck stores one closed (§8; it came with `API_VERSION` 22, replacing `task`, and an older client skips it); a Link change sends `workspace` for its Workspace after it; `suggestions` (id a Workspace's id) means `GET /v1/workspaces/{id}/suggestions`, sent when the daemon works that Workspace's Suggestions out again and they differ from the last ones it worked out for it this run (none, at start): it works them out again after a `changed` for a Pane (opened, moved, deleted; its Workspace's), an `exit` (its Workspace's), a tab or a Workspace (a Link added or removed, archived or brought back), a Repository or a `github_auth` (every Workspace's), coalescing a burst into one pass; a Pane's exit alone keeps its last folder, so it changes nothing to send (it came with `API_VERSION` 26, and an older client skips it). `state` and `exit` are sent to every client, attached or not. The daemon subscribes a connection to these events before it answers the upgrade, so every event published after the client sees the 101 reaches it. - **Resync:** a connection that falls more than 1024 events behind misses some. It gets `resync` in their place (and the daemon logs it at info), then the events after. A client reads everything it shows again over REST, as on a `changed` for each entity, and compares what it reads with what it had, so a change made meanwhile still notifies (§11). - **GitHub auth:** `github_auth` means `GET /v1/github/auth` (§8), sent to every client after a token or client ID is saved or deleted, after a re-read changes the token's source, login or `rejected`, when PR sync finds GitHub rejecting a token it accepted a moment ago, and when a sign-in ends. Only then does it carry `device`: `signed_in`, `expired`, `denied`, or `failed` with GitHub's `message`. It never carries the token, the client ID or the user code. - **Errors:** a message the daemon can't act on gets `error` with a `code`: `not_found` (attach to a pane that isn't live), `not_attached` (a channel with nothing attached), `invalid_message`. @@ -329,7 +339,7 @@ min_ms = 400 # a new state must hold this long before it is pu - **Polling:** the daemon then polls `POST https://github.com/login/oauth/access_token` (`grant_type=urn:ietf:params:oauth:grant-type:device_code`) at GitHub's `interval`, 5 s slower after each `slow_down`. On a token it saves it as a pasted one is (without the scope notes, since it has `repo`), re-reads, and sends `github_auth` with `device: "signed_in"`. `expired_token`, or `expires_at` passing, sends `device: "expired"`; `access_denied`, `device: "denied"`; any other error, `device: "failed"` with GitHub's message. Each of those ends the polling. A poll that fails in transit is tried again at the next interval, until `expires_at`. An `interval` under 1 s counts as 1 s. - **Log:** the start, with the code's expiry and the interval, at info; each poll that fails in transit at warn, with why; each `authorization_pending` at debug, with the count so far; and how the sign-in ended, or that it was cancelled (by `DELETE`, or a new `POST`), at info, with the count of polls, pending answers and transit failures. No line carries the client ID, the device code, the user code or the token. - **Cancel:** one sign-in runs at a time, so a new `POST` cancels the one before. `DELETE /v1/github/device` cancels it (204, also with none running) and sends no event. -- **Looking up a Repository** (`GET /v1/repositories/resolve`, and linking one agentdeck doesn't know, §4) is agentdeck's REST call to GitHub: `GET /repos/{owner}/{repo}` with the token as a bearer, `Accept: application/vnd.github+json` and `X-GitHub-Api-Version: 2022-11-28`, reading `id`, `full_name`, `html_url`, `private` and `archived`. GitHub redirects an old name to the renamed Repository, so the answer carries its name now. It uses the token as PR sync does (a `gh` token is checked first, a 401 reads the sources again and tries once more, then counts as rejected), the same 30 s timeout, the same retries (after 1 s and 2 s, on a 5xx or a request that failed in transit) and the same wording for a failure. A 404 is a Repository GitHub doesn't show the sign-in (no such repository, or no access): `400 unknown_repository`, "GitHub can't see owner/name. Check the name or your token's access." No token, or one GitHub still rejects, is `409 not_signed_in` ("Sign in to GitHub to look up owner/name.", or "GitHub rejected the token, so agentdeck can't look up owner/name."); any other failure is `502 github_error`. +- **Looking up a Repository** (`GET /v1/repositories/resolve`, and linking one agentdeck doesn't know, §4) is agentdeck's REST call to GitHub: `GET /repos/{owner}/{repo}` with the token as a bearer, `Accept: application/vnd.github+json` and `X-GitHub-Api-Version: 2022-11-28`, reading `id`, `full_name`, `html_url`, `private` and `archived`. GitHub redirects an old name to the renamed Repository, so the answer carries its name now. It uses the token as PR sync does (a `gh` token is checked first, a 401 reads the sources again and tries once more, then counts as rejected), the same 30 s timeout, the same retries (after 1 s and 2 s, on a 5xx or a request that failed in transit) and the same wording for a failure. A 404 is a Repository GitHub doesn't show the sign-in (no such repository, or no access): `400 unknown_repository`, "GitHub can't see owner/name. Check the name or your token's access." No token, or one GitHub still rejects, is `409 not_signed_in` ("Sign in to GitHub to look up owner/name.", or "GitHub rejected the token, so agentdeck can't look up owner/name."); any other failure is `502 github_error`. Confirming a Suggestion's name (§3) is the same call, with two differences: it takes the token as last read, never running `gh` or reading the sources while there is none (signed out, it only reads what agentdeck keeps), and its answers, a 404 included, are kept in memory for the run, while a failure is kept by no one and only logged. - **Closing PRs** (`POST /v1/prs/close`) closes them only: no comment, no branch delete. - Each PR is named by its reference, `owner/name#123` (or its GitHub URL, which clients turn into one), and found by its Repository's name and its number, ignoring case as GitHub does; the name follows the Repository's renames, so the name GitHub gives it now finds it. It must be stored `open`, Finished ones included, and not unreachable; any other, and one agentdeck doesn't keep, fails with "Not an open PR" and never reaches GitHub. With no token, every one fails with "Not signed in to GitHub". The results come back one per reference, in the order asked, each naming the reference asked for. - The daemon reads the PRs' node ids by Repository name and number, 25 to a request as fetches by number go. Then it closes each PR on its own, one at a time, with its own GraphQL `closePullRequest` mutation, since GitHub has no batch close. @@ -393,7 +403,7 @@ Built on `brrritscold-core-gpui` (`init`, `Root`, theme preference, toasts). Scr - **Older daemon:** while the daemon is older than the app (§2), a banner sits over the window's body, under the title bar: the Pull requests view's logged-out banner (a default alert with the `Info` icon, `space.6` across and `space.4` down, a separator under it) with an outline sm **Restart** as its action, the failure alert's. "agentdeck's background service is older than this app" / "Restart it to use new features. Your agents resume after the restart." Restart restarts the daemon (§2); meanwhile the window shows "Restarting agentdeck's background service…" in place of its body, then the new daemon's views. A failed restart shows the connection failure alert, "Couldn't restart agentdeckd: ", with Retry. Penpot "Screens · Daemon" → "Older daemon". - **Title bar:** the window asks for the compositor's frame. Where the compositor draws none (GNOME's Mutter on Wayland), the app draws a 32px title bar across the top: drag to move, double-click to maximize, right-click for the window menu, minimize / maximize / close at the right. 4px resize strips run along the window's inside edges, except on a tiled side. Everything else sits under it. - **Window:** it opens at 1440×900, the design's size, centred on the primary display and shrunk to fit its work area, but never below its minimum size, 1030×600. That is the narrowest layout that fits without clipping, derived from the narrowest PR table in Select mode: the sidebar (260) and its separator, the Pull requests view's `space.6` padding either side and its table in Select mode at its least (716: every column, the title at 160), 1025 rounded up (Penpot "Screens · Main" → "Pull requests · select · 1030"). The Pull requests view's header fits there too, its description wrapping, and so does a workspace view's 560px pane header. 600 high holds the tallest dialog under the title bar. The window can't be resized below it, and saved bounds smaller than it grow to it. Its size, position and maximized state are kept across restarts in `$XDG_STATE_HOME/agentdeck/window.json` (GUI-only, apart from `config.toml`), written once a resize or move settles and on quit. A missing or unreadable file, or saved bounds whose centre is on no connected display, opens at the default instead. -- **GUI state:** what the GUI remembers of itself, beside `window.json` in `$XDG_STATE_HOME/agentdeck/gui.json` (GUI-only too): the Repository groups collapsed per view, by GitHub's Repository id, so a rename keeps a group collapsed: on the Pull requests view (`{"collapsed": {"pull_requests": [1296269]}}`) and on each Workspace's Pull requests, by the Workspace's id (`{"collapsed": {"workspaces": {"": [1296269]}}}`); Show finished (`{"show_finished": true}`), one preference for every PR list, off by default; and each Workspace's last side, by its id (`{"last_side": {"": "pull_requests"}}`), Panes, the default, written as nothing. It is written at once, through a temp file, on each change. Every field is optional and a field the GUI doesn't know is skipped, so later versions add theirs (dismissed Suggestions) beside it, and a missing or broken file reads as nothing remembered. Without a state dir it is kept in memory only. +- **GUI state:** what the GUI remembers of itself, beside `window.json` in `$XDG_STATE_HOME/agentdeck/gui.json` (GUI-only too): the Repository groups collapsed per view, by GitHub's Repository id, so a rename keeps a group collapsed: on the Pull requests view (`{"collapsed": {"pull_requests": [1296269]}}`) and on each Workspace's Pull requests, by the Workspace's id (`{"collapsed": {"workspaces": {"": [1296269]}}}`); Show finished (`{"show_finished": true}`), one preference for every PR list, off by default; and each Workspace's last side, by its id (`{"last_side": {"": "pull_requests"}}`), Panes, the default, written as nothing; and the dismissed Suggestions, by Workspace id and GitHub's Repository id (`{"dismissed": {"": [1296269]}}`), each added by Not now on the Suggestions strip or by an unlink made in the GUI (Edit workspace's Save, a group's Unlink from this workspace), never by `agentdeck repo unlink`, and never forgotten. It is written at once, through a temp file, on each change. Every field is optional and a field the GUI doesn't know is skipped, so later versions add theirs beside it, and a missing or broken file reads as nothing remembered. Without a state dir it is kept in memory only. - **Quitting while agents run** (Penpot "Screens · Dialogs" → "Quit · agents running"): agents keep running after the GUI quits (§2, §8), so closing the window (the title bar's close button or the compositor's) and Quit ask first while at least one agent runs: an agent pane whose process hasn't exited, or a shell pane hosting an agent. Plain shells don't count. With none running, or `gui.confirm_quit` off (§2), they quit at once. - An `AlertDialog` titled "Quit agentdeck?", with "1 agent is still running. They keep running in the background, and reopening agentdeck reconnects to them." ("N agents are still running" for more). Under it, two horizontal Fields, `space.3` apart: a Checkbox "Don't ask again", then a Checkbox "Stop the agents" (Penpot "Quit · agents running · stop ticked" shows it ticked), each unticked each time the dialog opens; clicking a label ticks its box too. While Stop the agents is ticked the description reads "N agents are still running. They'll be stopped; Restart agent on each pane starts them again." ("1 agent is still running. It'll be stopped; Restart agent on its pane starts it again." for one). The footer is Cancel (outline) and **Quit** (default), `space.6` below the Fields. - Quit, or Enter, quits; with Don't ask again ticked it first saves `gui.confirm_quit = false` with `PATCH /v1/settings` and quits once that lands, whether or not it saved. Cancel, or Escape, keeps the app. Settings' General section turns it back on. @@ -456,11 +466,12 @@ Built on `brrritscold-core-gpui` (`init`, `Root`, theme preference, toasts). Scr - **Unreachable** PRs (§8, Penpot "Pull requests · unreachable PR") are listed as last synced, the whole row at half opacity, with a tooltip above the title ("Your GitHub sign-in can't see this PR. It's shown as it was last synced."). They are left out of the sidebar's count, and their menu has Open on GitHub and Copy PR details but no Close PR. - **Empty:** with no PR to show, the header and the banner as above, then "No open PRs. PRs you open on GitHub show here." (sm `muted-foreground`, padded `space.2` across) in place of the columns and the list, with Select disabled (Penpot "Pull requests · empty"). - It draws only the rows in view, and redraws "Synced …" every 30 s. -- **A Workspace's Pull requests** (Penpot "Screens · Main" → "Workspace · Pull requests", "Workspace · no repositories", "Workspace · Pull requests · group menu", "· unlinked", "· unlinked · not in a workspace"): a workspace's Pull requests side, the Pull requests view's list over the Repositories the workspace links, with the same groups, order, rows, row menu, group menu, Select mode, Show finished, Unreachable rows and logged-out banner, which sits above it too. - - **Unlink from this workspace**, last in a group's menu after a separator, applies at once, with no dialog (`DELETE /v1/workspaces/{id}/links/{repository}`, §4): the group leaves once the daemon's `changed` is read. The toast "Unlinked owner/name from " says "Its N open PRs no longer show here." ("Its 1 open PR no longer shows here."), N counted as the sidebar counts (§11 Sidebar), and adds "They're in the Pull requests view, under Not in a workspace." ("It's …" for one) when no other Workspace that isn't archived links the Repository; with no open PR it says only the title. Its **Undo** links the Repository again by GitHub's id with what the view held of it (`id`, name, `url`, `private`, `archived`), so it works even when the unlink deleted the Repository (§3), signed out included. A failure toasts "Couldn't unlink owner/name from " with why; a failed Undo, "Couldn't link …" or "Couldn't unlink …". +- **A Workspace's Pull requests** (Penpot "Screens · Main" → "Workspace · Pull requests", "Workspace · no repositories", "Workspace · Pull requests · group menu", "· unlinked", "· unlinked · not in a workspace", "Workspace · Pull requests · suggestion", "· suggestions", "Workspace · no repositories · suggestions"): a workspace's Pull requests side, the Pull requests view's list over the Repositories the workspace links, with the same groups, order, rows, row menu, group menu, Select mode, Show finished, Unreachable rows and logged-out banner, which sits above it too. + - **Unlink from this workspace**, last in a group's menu after a separator, applies at once, with no dialog (`DELETE /v1/workspaces/{id}/links/{repository}`, §4): the group leaves once the daemon's `changed` is read. Once done it counts as Not now for the workspace's Suggestions (GUI state, above), so a Pane still in that folder doesn't bring the offer straight back; its Undo leaves the dismissal. The toast "Unlinked owner/name from " says "Its N open PRs no longer show here." ("Its 1 open PR no longer shows here."), N counted as the sidebar counts (§11 Sidebar), and adds "They're in the Pull requests view, under Not in a workspace." ("It's …" for one) when no other Workspace that isn't archived links the Repository; with no open PR it says only the title. Its **Undo** links the Repository again by GitHub's id with what the view held of it (`id`, name, `url`, `private`, `archived`), so it works even when the unlink deleted the Repository (§3), signed out included. A failure toasts "Couldn't unlink owner/name from " with why; a failed Undo, "Couldn't link …" or "Couldn't unlink …". - **Header:** no heading, since the top bar names the workspace: two sm `muted-foreground` lines, "Your open PRs from the repositories links." ("Your open and finished PRs …" while Show finished is on) over "Link or unlink repositories in Edit workspace.", then, pushed right, **Select**, **Show finished** and an outline **Edit workspace**, which opens the edit workspace dialog as the `…` menu's does. It has no sync controls. - **Groups:** every Repository the workspace links shows a group, PRs or none, collapsed or open apart from the Pull requests view's, remembered per Repository for each workspace (GUI state, above). A linked Repository with no PR to show reads "No open PRs" (sm `muted-foreground`, padded `space.2` across, a row's height) under its header. - - **No Repositories:** a workspace linking none shows only its header, reading "No repositories linked yet. Link one to see its PRs here." over "They stay in Pull requests too.", with an outline **Link repository** in place of Select, Show finished and Edit workspace; it opens the edit workspace dialog with its "Link a repository…" picker focused and its list open (Dialogs, below). + - **No Repositories:** a workspace linking none shows only its header, reading "No repositories linked yet. Link one to see its PRs here." over "They stay in Pull requests too.", with an outline **Link repository** in place of Select, Show finished and Edit workspace; it opens the edit workspace dialog with its "Link a repository…" picker focused and its list open (Dialogs, below). Its Suggestions strip (below) sits under it, so the first Link is one click. + - **Suggestions** (Penpot `agentdeck/SuggestionRow`; an app-local composition, since an `Alert` holds one title and one action): the workspace's Suggestions (§3, read with the sidebar's snapshot from `GET /v1/workspaces/{id}/suggestions`, again on every `changed`) but for those it links by now and those dismissed (GUI state, above), in one strip under the header and the logged-out banner, over the columns, with no toast and no badge; none at all on an archived workspace or the Pull requests view. The strip is the default `Alert`'s box (`rounded-lg`, a `border` line, `card` fill), padded `space.4` across and `space.2` down, one row per Suggestion stacked in the daemon's order: each row (h-8, `space.2-5` gaps, sm `card-foreground`) is a 16px lucide `GitBranch` in `foreground`, "Panes here work in **owner/name**. Link it to this workspace?" with the name in `font-weight.medium`, then, pushed right, a link sm **Link**, a `muted-foreground` "·" and a link sm **Not now**. **Link** links at once by GitHub's id with what the view holds of the Repository (`POST /v1/workspaces/{id}/links`, §4, so it works signed out), as a group's Link to a workspace does: the toast "Linked owner/name to " with an Undo that unlinks it (and doesn't dismiss it), the row going once linked and the group appearing once the daemon's `changed` is read; a failure toasts "Couldn't link owner/name to " with why and keeps the row. **Not now** takes the row away for that workspace for good, across restarts. The strip goes with its last row. - A PR alert's click still lands on the Pull requests view, and only the Pull requests view withdraws PR alerts. - **Table width:** the Pull requests table fits its columns to the width instead of scrolling sideways: every row ends in a 24px column for its `…` menu and, in Select mode, starts with a 16px one for its checkbox, and the title column takes what's left, down to 160px, its text wrapping. No column drops: the window's least width fits the table whole in Select mode (Window, above). Only below that layout would the table scroll sideways. - **Opening PRs:** a PR's GitHub page opens in the default browser at its stored `url` (§3), from a Pull requests view row's reference or its Open on GitHub (above); a Repository's, from its group menu's Open on GitHub. @@ -478,8 +489,8 @@ Built on `brrritscold-core-gpui` (`init`, `Root`, theme preference, toasts). Scr - Enter in a dialog's single-line field does what its primary button does, and only that: when the form can't go ahead, or the daemon refuses it, the dialog stays open. - **New agent** (Penpot "Screens · Dialogs" → "New agent", "New agent · folder open") offers a Folder select, each folder once and labelled by its path with `~` for the home folder: first where a new pane starts (Workspace view, above: the focused pane's current folder, else `~`), preset; then the current folder of each other pane in the workspace, in tab and layout order, as the view last read them; then `~`. Its description reads "Where the focused pane is, another pane's folder, or your home folder." A workspace not shown (none of its panes read) offers `~` alone. There is no typed path or folder browser; `agentdeck agent new --cwd` starts one anywhere. The agent starts with no prompt (§6). - **New workspace** (Penpot "Screens · Dialogs" → "New workspace", "New workspace · picker") is titled "New workspace", with "An area of work, such as one product, for any number of repos and agents.", and holds a Field, "Name" ("Names the sidebar entry."), then, `space.4` below, the optional **Repositories** with the "Link a repository…" picker (below): a workspace has no folder. Picked Repositories show as rows with their `×` and are linked by the create itself, `POST /v1/workspaces` `{ name, link }`. Opened from a Repository group's New workspace (Pull requests view, Group menu), it holds that Repository as a picked row already. Enter in the name creates. A blank name ("Give the workspace a name.") or the daemon's `invalid_name` shows under the name field, a Repository the daemon can't link (`unknown_repository`, `not_signed_in`) under the picker, and nothing is made; any other failure toasts "Couldn't make the workspace". Once made it closes. - - **Edit workspace** (Penpot "Screens · Dialogs" → "Edit workspace", "Edit workspace · error" for a blank name, "Edit workspace · unlinked", "· picker", "· typed repo", "· GitHub can't see it" and "· signed out") is titled "Edit ", with "Its pull requests come from the repositories it links.". It holds (Penpot `agentdeck/EditWorkspaceForm`) the "Name" field, which opens holding the name, selected and focused, its error under it, then the **Repositories** the workspace links and the "Link a repository…" picker (below), `space.4` apart. Opened from the no-Repositories state's **Link repository** (`LinkRepository`), the picker takes the keyboard instead, its list open. The footer is Cancel and **Save**; Save is disabled while the name is blank, while nothing changed (the name, trimmed, as it was and nothing staged) and while a typed Repository is being looked up, and Enter in the name does the same. Links and unlinks are staged until Save, which applies them with the name in one request, `PATCH /v1/workspaces/{id}` `{ name?, link, unlink }` (the name only when it changed), and closes; the changes come back through `changed` to the sidebar, the views and the dialogs that list workspaces. Cancel and Escape discard what was staged, and there is no confirm dialog. The slug stays as it is, so running panes are unaffected and the CLI still finds the workspace by its old slug; nothing on disk changes. Two workspaces may share a name. A blank name shows "Give the workspace a name." under the field as soon as it is blank, its input `aria-invalid`; the daemon's `invalid_name` shows there too and keeps the dialog open. A Repository the daemon can't link (`unknown_repository`, `not_signed_in`, `invalid_links`) shows its message under the picker and keeps the dialog open, with nothing applied. Any other failure keeps it open and toasts "Couldn't save " with why. An archived workspace can be edited too. - - **Repositories** (Penpot `agentdeck/LinkedRepository` rows, `agentdeck/LinkPickerList`, `agentdeck/PickerItem`; an app-local composition, since core-gpui's Combobox draws text-only items): a "Repositories" Label, then a row per Repository the workspace links, by name ignoring case, `space.2` apart from the label, note and field. A row (h-8, `space.2` gaps, sm) is a 14px lucide `Lock` in `muted-foreground` for a private Repository (page-local `agentdeck/icon/Lock` in Penpot until the library has it), its `owner/name` in `foreground`, an outline "Unreachable" Badge while the GitHub sign-in can't see it, then, pushed right, a ghost icon-xs `X`, Unlink. Unlink crosses the row out (`muted-foreground`, line-through) and swaps its `X` for a link xs **Undo**, which puts it back; a picked row's `X` just drops it. Under the rows a sm `muted-foreground` note counts the open PRs the staged unlinks take out of the workspace, counted as its sidebar count is (drafts in, Unreachable and Finished out): "2 open PRs will leave this workspace", "1 open PR will leave this workspace", omitted at 0. Then the picker, an Input with the placeholder "Link a repository…", whose list opens 6px below it, as wide, while it has the keyboard or is typed into, and closes on Escape, a click outside or a pick. The list, drawn as core-gpui's `ComboboxContent`, holds **From your pull requests** (a Combobox label over the Repositories of your kept PRs, Finished ones' included, by name, each row with the lock when private), leaving out every Repository the dialog's rows hold and Unreachable ones; typing filters it locally, by name ignoring case, a pasted GitHub URL by the name it holds. Text that parses as `owner/name` or a GitHub URL and names no listed or linked Repository adds a "Link owner/name" row (lucide `Plus`), which asks GitHub (`GET /v1/repositories/resolve`; it reads "Looking up owner/name…" meanwhile) and, once GitHub shows it, stages it as a row under the name GitHub gives; if GitHub can't see it, the list closes and the daemon's "GitHub can't see owner/name. Check the name or your token's access." shows under the field, the field `aria-invalid`, until the next keystroke. Nothing matching reads "No repositories match.". After a separator the list ends in "Not listed? Type owner/name or paste its URL.", or, signed out (PR status reads the token logged out), "Sign in to GitHub to find more repositories." with no typed row: only Repositories agentdeck keeps can be picked. Enter in the field picks the list's first row. All your repositories (`/user/repos`) is tracked in [#371](https://github.com/bRRRITSCOLD/agentdeck/issues/371) and Suggested in [#373](https://github.com/bRRRITSCOLD/agentdeck/issues/373). + - **Edit workspace** (Penpot "Screens · Dialogs" → "Edit workspace", "Edit workspace · error" for a blank name, "Edit workspace · unlinked", "· picker", "· picker · suggested", "· typed repo", "· GitHub can't see it" and "· signed out") is titled "Edit ", with "Its pull requests come from the repositories it links.". It holds (Penpot `agentdeck/EditWorkspaceForm`) the "Name" field, which opens holding the name, selected and focused, its error under it, then the **Repositories** the workspace links and the "Link a repository…" picker (below), `space.4` apart. Opened from the no-Repositories state's **Link repository** (`LinkRepository`), the picker takes the keyboard instead, its list open. The footer is Cancel and **Save**; Save is disabled while the name is blank, while nothing changed (the name, trimmed, as it was and nothing staged) and while a typed Repository is being looked up, and Enter in the name does the same. Links and unlinks are staged until Save, which applies them with the name in one request, `PATCH /v1/workspaces/{id}` `{ name?, link, unlink }` (the name only when it changed), and closes; each Repository it unlinked then counts as Not now for the workspace's Suggestions (GUI state, above), and a failed Save dismisses nothing. The changes come back through `changed` to the sidebar, the views and the dialogs that list workspaces. Cancel and Escape discard what was staged, and there is no confirm dialog. The slug stays as it is, so running panes are unaffected and the CLI still finds the workspace by its old slug; nothing on disk changes. Two workspaces may share a name. A blank name shows "Give the workspace a name." under the field as soon as it is blank, its input `aria-invalid`; the daemon's `invalid_name` shows there too and keeps the dialog open. A Repository the daemon can't link (`unknown_repository`, `not_signed_in`, `invalid_links`) shows its message under the picker and keeps the dialog open, with nothing applied. Any other failure keeps it open and toasts "Couldn't save " with why. An archived workspace can be edited too. + - **Repositories** (Penpot `agentdeck/LinkedRepository` rows, `agentdeck/LinkPickerList`, `agentdeck/PickerItem`; an app-local composition, since core-gpui's Combobox draws text-only items): a "Repositories" Label, then a row per Repository the workspace links, by name ignoring case, `space.2` apart from the label, note and field. A row (h-8, `space.2` gaps, sm) is a 14px lucide `Lock` in `muted-foreground` for a private Repository (page-local `agentdeck/icon/Lock` in Penpot until the library has it), its `owner/name` in `foreground`, an outline "Unreachable" Badge while the GitHub sign-in can't see it, then, pushed right, a ghost icon-xs `X`, Unlink. Unlink crosses the row out (`muted-foreground`, line-through) and swaps its `X` for a link xs **Undo**, which puts it back; a picked row's `X` just drops it. Under the rows a sm `muted-foreground` note counts the open PRs the staged unlinks take out of the workspace, counted as its sidebar count is (drafts in, Unreachable and Finished out): "2 open PRs will leave this workspace", "1 open PR will leave this workspace", omitted at 0. Then the picker, an Input with the placeholder "Link a repository…", whose list opens 6px below it, as wide, while it has the keyboard or is typed into, and closes on Escape, a click outside or a pick. The list, drawn as core-gpui's `ComboboxContent`, holds **Suggested** first (a Combobox label over Edit workspace's workspace's Suggestions, §3, in the daemon's order, dismissed ones included, since opening the picker is deliberate; each row with the lock when private; New workspace has none, its workspace not made yet), then **From your pull requests** (a Combobox label over the Repositories of your kept PRs, Finished ones' included, by name, each row with the lock when private, but for those Suggested, so each Repository shows once), each leaving out every Repository the dialog's rows hold and Unreachable ones; typing filters both locally, by name ignoring case, a pasted GitHub URL by the name it holds. A Suggested row is picked as any other: staged by name, linked on Save (Penpot "Edit workspace · picker · suggested"). Text that parses as `owner/name` or a GitHub URL and names no listed or linked Repository adds a "Link owner/name" row (lucide `Plus`), which asks GitHub (`GET /v1/repositories/resolve`; it reads "Looking up owner/name…" meanwhile) and, once GitHub shows it, stages it as a row under the name GitHub gives; if GitHub can't see it, the list closes and the daemon's "GitHub can't see owner/name. Check the name or your token's access." shows under the field, the field `aria-invalid`, until the next keystroke. Nothing matching reads "No repositories match.". After a separator the list ends in "Not listed? Type owner/name or paste its URL.", or, signed out (PR status reads the token logged out), "Sign in to GitHub to find more repositories." with no typed row: only Repositories agentdeck keeps can be picked. Enter in the field picks the list's first row. All your repositories (`/user/repos`) is tracked in [#371](https://github.com/bRRRITSCOLD/agentdeck/issues/371). - **Delete workspace** is titled "Delete ?", with "This can't be undone. Archive it instead to keep its panes and linked Repositories." Deleting touches no folder, so there is nothing on disk to warn about. - Its body (Penpot "Screens · Dialogs" → "Delete workspace", "Delete workspace · panes running") says what deleting does, a muted line each, `space.3` apart: "Its N Repositories are unlinked. Their PRs stay in Pull requests." ("Its 1 Repository is unlinked. Its PRs stay in Pull requests."; left out when it links none), counting the Repositories that link it as the sidebar last read them (`GET /v1/repositories`); then "Its N running panes will be stopped." ("1 running pane"; left out with none); then "Type to confirm" over an input. Running panes are the workspace's panes whose process hasn't exited, as Archive counts them; deleting stops them (§4). - The footer is **Archive instead** (absent once archived), which closes it and archives as the menu does, **Cancel** and the destructive **Delete workspace**. Delete is disabled until the input is the name exactly; Enter does the same, and Escape cancels. @@ -531,8 +542,8 @@ Built on `brrritscold-core-gpui` (`init`, `Root`, theme preference, toasts). Scr | Tier | Where | What | |---|---|---| -| unit | `agentdeck-core`, GUI views (`#[gpui::test]`), daemon pure parts | rules with recorded output (the Copy PR details text among them, one PR's and several joined by a blank line), layout tree, snapshot encode/decode round-trip, env allowlist, `openapi.json` staleness; GUI views over a fake API and a fake notifier, asserting what a user sees (the Pull requests view's groups and their order, collapse and Show finished kept in the GUI state file, Finished rows hidden until Show finished and showing GitHub's state, the row's link and menu, Sync now, the banner, the empty state, Unreachable rows; Select mode: entering and leaving it, picking by row click, group checkbox (folded too) and select-all, which rows can be picked (open and reachable, Finished-but-open included; not merged, closed or Unreachable), the bar's count and order, Copy PR details joined in the list's order, Close PRs asking then closing by reference, a PR that didn't close kept picked and marked with why, a closed PR shown closed at once, "Closing N of M…", and Select disabled on the empty view; the header and the table fitting the narrowest window in Select mode, and that window's minimum fitting the narrowest PR table in Select mode; the sidebar's entries and counts, Finished PRs left out, no Inbox or Tasks entry, each Workspace's count over its linked Repositories, none on an archived row, the no-Workspaces hint and its New workspace, Pull requests the fallback selection; linked groups first, then Not in a workspace, each alphabetical, a group's header naming its linking Workspaces as links that open their Pull requests, Archived Workspaces absent from headers and order; the group `…` menu on every group of both views, in the rows' `…` column: Open on GitHub opening the Repository's page, Link to a workspace offering the Workspaces that aren't archived and don't link it in the sidebar's order then New workspace, New workspace alone when none is eligible, New workspace opening the dialog with the Repository picked, a link applied at once by GitHub's id with "Linked owner/name to " and an Undo that unlinks, Unlink from this workspace only on a Workspace's Pull requests, applied at once with "Unlinked owner/name from " and its open PRs (singular, plural, none, and where they went when no other Workspace links it), its Undo linking again by id once the unlink deleted the Repository, and failures toasted; a Workspace's side switch with its count, `secondary-shift-p`, each Workspace's side remembered across a restart and opened from its sidebar row, a new one on its Panes; a Workspace's Pull requests: only its linked Repositories, "No open PRs", Select, Show finished and Edit workspace with no sync controls, the banner, collapse kept apart from the Pull requests view's, the no-Repositories state whose Link repository opens Edit workspace with its picker focused and open; Edit workspace and New workspace: the linked rows with their Unlink, lock and Unreachable badge, staging until Save (one request with the name, applied to the fake, none before), Save enabled by a staged change alone, Undo, the leaving note and its singular and its absence at 0, Cancel discarding what was staged, a refusal under the picker keeping the dialog open, an archived workspace linked, the picker's From your pull requests (no linked, picked or Unreachable Repository; the lock), local filtering ignoring case and by a pasted URL, picking (the field cleared), Enter picking the first row, the typed row only for an unlisted name, GitHub showing it (staged under GitHub's name, private kept) or not ("GitHub can't see …" under the field, the list closed, cleared by typing), signed out (no typed row, "Sign in to GitHub to find more repositories."), and New workspace linking what was picked on create; the picker's offer read from a snapshot (linked ones, Unreachable included; 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` | -| 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 and Links, and the device flow's code and token endpoints); `gh` is a stub script on `PATH`, and so are `claude` and `codex`, which read input as their TUIs do, and exit on a submitted `/exit` so a shell pane's hosted agent can leave (raw, bracketed paste on, a read that is a lone `\r` submits, any other read is a paste); the keyring is an in-memory fake store (`AGENTDECK_KEYRING=memory`; without it the harness's daemon has no session bus, so no keyring). The `agentdeck_client` helpers the GUI's real API calls (`panes`, `settings`, `prs`, `repositories`, `workspaces`) are tested here through the real client (`*_client`), each new operation of the GUI's fake API with a test of the same call in the same PR, so the fake can't drift from the daemon; `prs::list` also lists none from a daemon older than `GET /v1/prs`, and lists Finished PRs, marked; `repositories::list` lists each Repository with the Workspaces linking it, Archived ones included, and none from a daemon older than `GET /v1/repositories`; `repositories::resolve` answers the Repository GitHub shows for a typed URL and fails with the daemon's "GitHub can't see …"; `repositories::link` links by GitHub's id and links again, signed out, once an unlink deleted the Repository, and `repositories::unlink` keeps one another Workspace links and fails with the daemon's `not_found` for one the Workspace doesn't link; `workspaces::create` makes a Workspace linking what was picked, or nothing, and `workspaces::update` renames, links and unlinks together, or changes nothing, failing with the daemon's words. The Workspace routes' Links are tested here too: create linking a Repository agentdeck keeps (no GitHub call) and one GitHub resolves, nothing made when GitHub can't see one; update renaming, linking and unlinking in one request (an unreferenced Repository gone), nothing changed when a link fails or the name is blank, `invalid_links`, unlinking one it doesn't link changing nothing, an archived Workspace linked, and `changed` for each Repository then the workspace. The link route's link by GitHub's `id` is tested here too: a Repository an unlink deleted stored again from the body signed out (no GitHub, where a link by name is `not_signed_in`), the Repository kept with that id linked under its name now, `changed` for the Repository then the workspace, and `404 not_found` storing nothing for a Workspace that doesn't exist. PR sync's Finished PRs are tested here too: Finished on merge, on close (from GitHub and from agentdeck) and past the cutoff, no longer Finished once GitHub shows a PR open again, deleted with their unreferenced Repositories after the window (`AGENTDECK_PR_FINISHED_SECS=0`), and Unreachable PRs kept with no window. PRs are kept by Repository and number: a renamed Repository's PR and one of another Repository that took the old name are two PRs. Workspaces without folders are tested here too: creating one makes nothing on disk and its JSON has no folder, an older client's `dir` and `force` are ignored, the dirty report route is gone (dropshot's own 404), deleting one unlinks its Repositories (a Repository nothing else names goes) and stops its panes but leaves every folder on disk (its panes' folders and an old scratch folder), the first pane of a workspace with none opens in `~` through `panes::new_shell_tab`, and `0002` drops the folder columns from a database at `0001`, keeping each Workspace and its Links. The fresh start is tested here too: a fresh data dir gets the migrations' schema (no `tasks`, `comments` or `instructions`; `pull_requests` keyed by `(repository_id, number)` with nothing unique on a name), a current database survives a restart, and a database with a `tasks` table, its last writes still in its WAL, is moved aside with its WAL and SHM files (the moved one still reads), logged, never over an earlier one, with scratch folders left alone, and the daemon starts empty | +| unit | `agentdeck-core`, GUI views (`#[gpui::test]`), daemon pure parts | rules with recorded output (the Copy PR details text among them, one PR's and several joined by a blank line), layout tree, snapshot encode/decode round-trip, env allowlist, `openapi.json` staleness; GUI views over a fake API and a fake notifier, asserting what a user sees (the Pull requests view's groups and their order, collapse and Show finished kept in the GUI state file, Finished rows hidden until Show finished and showing GitHub's state, the row's link and menu, Sync now, the banner, the empty state, Unreachable rows; Select mode: entering and leaving it, picking by row click, group checkbox (folded too) and select-all, which rows can be picked (open and reachable, Finished-but-open included; not merged, closed or Unreachable), the bar's count and order, Copy PR details joined in the list's order, Close PRs asking then closing by reference, a PR that didn't close kept picked and marked with why, a closed PR shown closed at once, "Closing N of M…", and Select disabled on the empty view; the header and the table fitting the narrowest window in Select mode, and that window's minimum fitting the narrowest PR table in Select mode; the sidebar's entries and counts, Finished PRs left out, no Inbox or Tasks entry, each Workspace's count over its linked Repositories, none on an archived row, the no-Workspaces hint and its New workspace, Pull requests the fallback selection; linked groups first, then Not in a workspace, each alphabetical, a group's header naming its linking Workspaces as links that open their Pull requests, Archived Workspaces absent from headers and order; the group `…` menu on every group of both views, in the rows' `…` column: Open on GitHub opening the Repository's page, Link to a workspace offering the Workspaces that aren't archived and don't link it in the sidebar's order then New workspace, New workspace alone when none is eligible, New workspace opening the dialog with the Repository picked, a link applied at once by GitHub's id with "Linked owner/name to " and an Undo that unlinks, Unlink from this workspace only on a Workspace's Pull requests, applied at once with "Unlinked owner/name from " and its open PRs (singular, plural, none, and where they went when no other Workspace links it), its Undo linking again by id once the unlink deleted the Repository, and failures toasted; a Workspace's side switch with its count, `secondary-shift-p`, each Workspace's side remembered across a restart and opened from its sidebar row, a new one on its Panes; a Workspace's Pull requests: only its linked Repositories, "No open PRs", Select, Show finished and Edit workspace with no sync controls, the banner, collapse kept apart from the Pull requests view's, the no-Repositories state whose Link repository opens Edit workspace with its picker focused and open; Edit workspace and New workspace: the linked rows with their Unlink, lock and Unreachable badge, staging until Save (one request with the name, applied to the fake, none before), Save enabled by a staged change alone, Undo, the leaving note and its singular and its absence at 0, Cancel discarding what was staged, a refusal under the picker keeping the dialog open, an archived workspace linked, the picker's From your pull requests (no linked, picked or Unreachable Repository; the lock), local filtering ignoring case and by a pasted URL, picking (the field cleared), Enter picking the first row, the typed row only for an unlisted name, GitHub showing it (staged under GitHub's name, private kept) or not ("GitHub can't see …" under the field, the list closed, cleared by typing), signed out (no typed row, "Sign in to GitHub to find more repositories."), and New workspace linking what was picked on create; the picker's Suggested section first, ignoring dismissals, its rows left out of From your pull requests, filtered as typed, picked by click or Enter; the Suggestions strip on a Workspace's Pull requests (one row alone, several stacked in one strip under the header and over the table, none on the Pull requests view, an archived Workspace or for what it links by now), Link at once by GitHub's id with "Linked owner/name to ", the row gone and the group shown once read, its Undo unlinking without dismissing and a failure toasted with the row kept, Not now taking the row away for that Workspace only and kept across a restart in the GUI state file, the strip under Link repository on a Workspace with no Repositories, and an unlink from the group menu or Edit workspace's Save recording a dismissal (a failed one none); the GUI state's dismissed pairs, written by id; the picker's offer read from a snapshot (linked ones, Unreachable included; Suggestions but what the Workspace links by now; your PRs' reachable Repositories; open PRs counted as the sidebar does; signed out only while the token is logged out); the archived screen with no switch; a pane notifying while its workspace shows its Pull requests; New workspace's Name field and optional picker; New agent's Folder select (where a new pane starts first, the other panes' folders, then `~`, each once) and a new pane starting in `~` in a workspace with none; the Delete workspace dialog's lines (its Repositories unlinked, its running panes stopped, each left out at 0); the archive toast; the top bar's name, centred, before its side switch; a Pane alert's body, " · ", and the pane header's parts; PR alerts over the fake notifier: each trigger, only PRs you authored, one alert per PR replaced on a new change, a click landing on the row with its group opened, a Finished row shown with Show finished left off, scrolled to and highlighted until the highlight fades, "N PRs changed" opening the view, an alert withdrawn once the view shows, and the mute rule with every linking Workspace muted, one unmuted, only Archived muted ones, and none); the PR alert mute rule and the GitHub remote parser (https, ssh and scp-like URLs, for Suggestions) in `agentdeck-core`; the daemon's git config reader for Suggestions (each remote's first URL by name, sections and keys ignoring case, the old dotted header, comments and quotes, `upstream` on GitHub over `origin`, no other remote; a folder deep in a repo, a worktree's `.git` file and `commondir`, a relative `gitdir`, none outside a repo) and which events make Suggestions due | +| integration | `agentdeckd/tests/integration` | temp `$XDG_*` dirs, a real daemon on a random port, a real client; PTYs run `sh`, which moves a pane with `cd` (read through `/proc`) or `printf`s an OSC 7, so a pane's current folder, its `changed` and its restore folder are tested without a shell that reports one; GitHub is httpmock (`AGENTDECK_GITHUB_API`, `AGENTDECK_GITHUB_REST_API` and `AGENTDECK_GITHUB_OAUTH`: GraphQL with `closePullRequest`, REST's `GET /repos/{owner}/{repo}` for Repository lookups, Links and Suggestions, and the device flow's code and token endpoints); Suggestions run Panes (`sh`, `sleep`) in temp git repos with `upstream`, `origin` and other remotes: upstream on GitHub over origin, origin when upstream is elsewhere, other remotes ignored, none outside a repo, one per name, a Pane that `cd`s in, an exited Pane at its last folder, a name GitHub can't see never suggested, a renamed one under GitHub's name, each name asked about once per run across reads and Workspaces, signed out only kept Repositories, one other Workspaces link still suggested, one the Workspace links left out, an archived Workspace none, `404 not_found`, and `changed suggestions` when a Pane opens in or moves into a repo, a Link takes one away and a deleted Pane takes one away; the client's `repositories::suggestions` against the same daemon, none from an older one; `gh` is a stub script on `PATH`, and so are `claude` and `codex`, which read input as their TUIs do, and exit on a submitted `/exit` so a shell pane's hosted agent can leave (raw, bracketed paste on, a read that is a lone `\r` submits, any other read is a paste); the keyring is an in-memory fake store (`AGENTDECK_KEYRING=memory`; without it the harness's daemon has no session bus, so no keyring). The `agentdeck_client` helpers the GUI's real API calls (`panes`, `settings`, `prs`, `repositories`, `workspaces`) are tested here through the real client (`*_client`), each new operation of the GUI's fake API with a test of the same call in the same PR, so the fake can't drift from the daemon; `prs::list` also lists none from a daemon older than `GET /v1/prs`, and lists Finished PRs, marked; `repositories::list` lists each Repository with the Workspaces linking it, Archived ones included, and none from a daemon older than `GET /v1/repositories`; `repositories::resolve` answers the Repository GitHub shows for a typed URL and fails with the daemon's "GitHub can't see …"; `repositories::link` links by GitHub's id and links again, signed out, once an unlink deleted the Repository, and `repositories::unlink` keeps one another Workspace links and fails with the daemon's `not_found` for one the Workspace doesn't link; `workspaces::create` makes a Workspace linking what was picked, or nothing, and `workspaces::update` renames, links and unlinks together, or changes nothing, failing with the daemon's words. The Workspace routes' Links are tested here too: create linking a Repository agentdeck keeps (no GitHub call) and one GitHub resolves, nothing made when GitHub can't see one; update renaming, linking and unlinking in one request (an unreferenced Repository gone), nothing changed when a link fails or the name is blank, `invalid_links`, unlinking one it doesn't link changing nothing, an archived Workspace linked, and `changed` for each Repository then the workspace. The link route's link by GitHub's `id` is tested here too: a Repository an unlink deleted stored again from the body signed out (no GitHub, where a link by name is `not_signed_in`), the Repository kept with that id linked under its name now, `changed` for the Repository then the workspace, and `404 not_found` storing nothing for a Workspace that doesn't exist. PR sync's Finished PRs are tested here too: Finished on merge, on close (from GitHub and from agentdeck) and past the cutoff, no longer Finished once GitHub shows a PR open again, deleted with their unreferenced Repositories after the window (`AGENTDECK_PR_FINISHED_SECS=0`), and Unreachable PRs kept with no window. PRs are kept by Repository and number: a renamed Repository's PR and one of another Repository that took the old name are two PRs. Workspaces without folders are tested here too: creating one makes nothing on disk and its JSON has no folder, an older client's `dir` and `force` are ignored, the dirty report route is gone (dropshot's own 404), deleting one unlinks its Repositories (a Repository nothing else names goes) and stops its panes but leaves every folder on disk (its panes' folders and an old scratch folder), the first pane of a workspace with none opens in `~` through `panes::new_shell_tab`, and `0002` drops the folder columns from a database at `0001`, keeping each Workspace and its Links. The fresh start is tested here too: a fresh data dir gets the migrations' schema (no `tasks`, `comments` or `instructions`; `pull_requests` keyed by `(repository_id, number)` with nothing unique on a name), a current database survives a restart, and a database with a `tasks` table, its last writes still in its WAL, is moved aside with its WAL and SHM files (the moved one still reads), logged, never over an earlier one, with scratch folders left alone, and the daemon starts empty | | 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 | diff --git a/openapi.json b/openapi.json index 6c5608a..87469d1 100644 --- a/openapi.json +++ b/openapi.json @@ -2550,6 +2550,46 @@ "summary": "Unlinks the Workspace from a Repository. The Repository goes too when no other Workspace" } }, + "/v1/workspaces/{id}/suggestions": { + "get": { + "description": "link, each as GitHub showed it when this run first asked about its name, by name ignoring case. A Pane counts at its current folder, an exited one at its last known folder; its git repo's `upstream` remote counts when it is on GitHub, else its `origin`. A Repository other Workspaces link is still suggested; one GitHub can't see never is; signed out, only one agentdeck keeps is. An archived Workspace has none. Not filtered by what the GUI was told Not now. A Workspace that doesn't exist is 404 `not_found`.", + "operationId": "suggestion_list", + "parameters": [ + { + "description": "The entity's id.", + "in": "path", + "name": "id", + "required": true, + "schema": { + "$ref": "#/components/schemas/WorkspaceId" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "items": { + "$ref": "#/components/schemas/Repository" + }, + "title": "Array_of_Repository", + "type": "array" + } + } + }, + "description": "successful operation" + }, + "4XX": { + "$ref": "#/components/responses/Error" + }, + "5XX": { + "$ref": "#/components/responses/Error" + } + }, + "summary": "Workspace `id`'s Suggestions (spec §3): the Repositories its Panes work in that it doesn't" + } + }, "/v1/workspaces/{id}/tabs": { "get": { "operationId": "tab_list",