Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 19 additions & 3 deletions crates/agentdeck-gui/src/pr_table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,10 @@ pub type OnToggle = Box<dyn Fn(&mut Window, &mut App) + 'static>;
/// does (archived ones link nothing).
pub const NOT_IN_A_WORKSPACE: &str = "Not in a workspace";

/// What an Unreachable Repository's group header says in place of the Workspaces linking it
/// (spec §11; Penpot "Screens · Main" → "Pull requests · unreachable repository").
pub const UNREACHABLE_REPOSITORY: &str = "Unreachable: can't sync, PRs may be out of date";

/// The table's least width: every column, the title at its least, the `space.3` gaps and the
/// rows' `space.2` padding, and with `select` the `Select` layer's. Narrower than any window
/// the sidebar leaves room for.
Expand Down Expand Up @@ -111,9 +115,10 @@ pub type OnWorkspace = Rc<dyn Fn(WorkspaceId, &mut Window, &mut App) + 'static>;
/// its checkbox, then, `space.2` after it in sm `muted-foreground`, who links the Repository:
/// each Workspace in `workspaces` by name, `·` apart, a link to its Pull requests that runs
/// `on_workspace` (underlined on hover, as a PR's reference), or [`NOT_IN_A_WORKSPACE`] with
/// none, then, pushed right into the rows' `Menu` column, its `menu`. `key` names it: tests
/// find it as `group <key>`, its workspaces as `group workspaces <key>` and each one's link as
/// `workspace link <key> <name>`.
/// none; [`UNREACHABLE_REPOSITORY`] instead of either while `unreachable`. Then, pushed right
/// into the rows' `Menu` column, its `menu`. `key` names it: tests find it as `group <key>`,
/// its workspaces as `group workspaces <key>`, each one's link as `workspace link <key>
/// <name>`, and the Unreachable words as `group unreachable <key>`.
#[allow(clippy::too_many_arguments)]
pub fn group_header(
key: SharedString,
Expand All @@ -122,6 +127,7 @@ pub fn group_header(
collapsed: bool,
select: SelectCell,
workspaces: &[Linker],
unreachable: bool,
on_toggle: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
on_workspace: OnWorkspace,
menu: Option<AnyElement>,
Expand All @@ -137,6 +143,16 @@ pub fn group_header(
.text_size(font_size::SM)
.text_color(s.muted_foreground);
let names = match workspaces {
_ if unreachable => {
let selector = format!("group unreachable {key}");
names.child(
div()
.debug_selector(move || selector)
.min_w_0()
.truncate()
.child(UNREACHABLE_REPOSITORY),
)
}
[] => names.child(NOT_IN_A_WORKSPACE),
workspaces => names.children(workspaces.iter().enumerate().flat_map(|(ix, w)| {
let id = w.id;
Expand Down
73 changes: 72 additions & 1 deletion crates/agentdeck-gui/src/pull_requests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
//! Groups go linked Repositories first, then those Not in a workspace, each alphabetically by
//! the Repository's name. A group's header names the Workspaces linking its Repository (archived
//! ones link nothing), each a link to that Workspace's Pull requests ([`OpenWorkspace`]), or
//! reads "Not in a workspace". On the Pull requests view a group with no PR to show is left out;
//! reads "Not in a workspace"; an Unreachable Repository's reads "Unreachable: can't sync, PRs
//! may be out of date" instead (Penpot "Pull requests · unreachable repository"). On the Pull requests view a group with no PR to show is left out;
//! on a Workspace's Pull requests every linked Repository shows, one with none to show over a
//! muted "No open PRs" row. A group collapses at a click, remembered per view and per
//! Repository across restarts in the GUI's own state ([`gui_state`]).
Expand Down Expand Up @@ -199,6 +200,8 @@ pub struct Group {
/// The Workspaces linking it, archived ones left out, in the sidebar's order; none while
/// it is Not in a workspace.
pub workspaces: Vec<Linker>,
/// Whether it is Unreachable: the GitHub sign-in can't see it, so its PRs can't sync.
pub unreachable: bool,
}

/// The groups of `snapshot`'s PRs a list over `scope` shows, its PRs by number: one per
Expand Down Expand Up @@ -228,6 +231,7 @@ pub fn groups(
label: name.name().to_owned().into(),
prs: Vec::new(),
workspaces: Vec::new(),
unreachable: false,
};
let mut groups: Vec<Group> = Vec::new();
for pr in (snapshot.prs.iter()).filter(shown) {
Expand All @@ -250,6 +254,8 @@ pub fn groups(
}
}
for group in &mut groups {
group.unreachable = (snapshot.repositories.iter())
.any(|links| links.id == group.repository && links.unreachable);
group.workspaces = (snapshot.linking(group.repository).into_iter())
.map(|w| Linker {
id: w.id,
Expand Down Expand Up @@ -296,6 +302,8 @@ enum Item {
selectable: Vec<PrKey>,
/// The Workspaces linking it.
workspaces: Vec<Linker>,
/// Whether it is Unreachable.
unreachable: bool,
},
/// A PR.
Row(Box<PullRequest>),
Expand All @@ -319,6 +327,7 @@ fn items(groups: &[Group], collapsed: &BTreeSet<RepositoryId>) -> Vec<Item> {
.map(PrKey::of)
.collect(),
workspaces: group.workspaces.clone(),
unreachable: group.unreachable,
});
if folded {
continue;
Expand Down Expand Up @@ -698,6 +707,7 @@ impl PullRequestsView {
collapsed,
selectable,
workspaces,
unreachable,
}) => {
let repository = *repository;
let select = close_prs::select_all(&self.close, name, selectable.clone(), cx);
Expand All @@ -713,6 +723,7 @@ impl PullRequestsView {
*collapsed,
select,
workspaces,
*unreachable,
cx.listener(move |this, _, _, cx| this.toggle(repository, cx)),
on_workspace,
menu,
Expand Down Expand Up @@ -2743,6 +2754,66 @@ mod tests {
}
}

/// An Unreachable Repository's group (spec §11): its header says it can't sync in place of
/// the Workspaces linking it, on both views.
mod unreachable_repository {
use super::*;

/// [`linked`] with `acme/widgets` and `acme/tools`, both linked by `a`, Unreachable.
fn with_unreachable() -> Snapshot {
let mut snapshot = linked();
for links in &mut snapshot.repositories {
let name = links.name.to_string();
links.unreachable = name == "acme/widgets" || name == "acme/tools";
}
snapshot
}

#[test]
fn should_mark_its_group_and_keep_it_among_the_linked_ones() {
let groups = groups(&with_unreachable(), Scope::All, false, None);

let marked: Vec<(String, bool)> = (groups.iter())
.map(|g| (g.label.to_string(), g.unreachable))
.collect();
assert_eq!(
marked,
[
("widgets".to_owned(), true),
("apples".to_owned(), false),
("gadgets".to_owned(), false),
("zebra".to_owned(), false),
]
);
}

#[gpui::test]
fn should_say_it_cannot_sync_in_place_of_the_workspaces_linking_it(
cx: &mut TestAppContext,
) {
let (_harness, cx) = Harness::open(with_unreachable(), cx);

let header = bounds("group acme/widgets".into(), cx);
let said = bounds("group unreachable acme/widgets".into(), cx);
assert!(said.left() > header.right(), "{said:?} after {header:?}");
assert!(!shows("workspace link acme/widgets a".into(), cx));
assert!(!shows("group unreachable acme/apples".into(), cx));
assert_eq!(
pr_table::UNREACHABLE_REPOSITORY,
"Unreachable: can't sync, PRs may be out of date"
);
}

#[gpui::test]
fn should_say_so_on_a_workspaces_pull_requests_too(cx: &mut TestAppContext) {
let (_harness, cx) = Harness::open_in(a(), with_unreachable(), cx);

assert!(shows("group unreachable acme/tools".into(), cx));
assert!(shows("no open prs acme/tools".into(), cx));
assert!(shows("group unreachable acme/widgets".into(), cx));
}
}

mod show_finished {
use super::*;

Expand Down
41 changes: 40 additions & 1 deletion crates/agentdeck/tests/integration/repo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ use std::ffi::OsString;
use httpmock::MockServer;
use serde_json::{Value, json};

use crate::support::github::{Pr, mock_open_prs, mock_repo, mock_repo_missing, repository_id};
use crate::support::github::{
Pr, mock_open_prs, mock_repo, mock_repo_by_id_missing, mock_repo_missing, repository_id,
};
use crate::support::{TestEnv, text};

const TOKEN: &str = "gho_test";
Expand Down Expand Up @@ -91,6 +93,43 @@ mod repo_ls {
);
}

/// A linked Repository GitHub no longer shows the sign-in, once `pr sync` read it by id.
fn unreachable_widgets(github: &MockServer) -> TestEnv {
let env = showing(github, &[WIDGETS]);
mock_open_prs(github, TOKEN, &[]);
mock_repo_by_id_missing(github, WIDGETS);
env.workspace("web");
env.ok(&["repo", "link", WIDGETS, "--ws", "web"]);
let status = env.json(&["pr", "sync"]);
assert_eq!(status["last_error"], Value::Null, "{status}");
env
}

#[test]
fn should_mark_a_repository_github_no_longer_shows_unreachable_and_keep_its_link() {
let github = MockServer::start();
let env = unreachable_widgets(&github);

let stdout = env.ok(&["repo", "ls"]);

assert_eq!(
stdout,
"REPOSITORY WORKSPACES\n\
acme/widgets (unreachable) web\n"
);
}

#[test]
fn should_say_it_is_unreachable_with_json() {
let github = MockServer::start();
let env = unreachable_widgets(&github);

let repositories = env.json(&["repo", "ls"]);

assert_eq!(repositories[0]["name"], WIDGETS);
assert_eq!(repositories[0]["unreachable"], true);
}

#[test]
fn should_say_when_there_are_none() {
let env = TestEnv::new();
Expand Down
11 changes: 11 additions & 0 deletions crates/agentdeck/tests/integration/support/github.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,17 @@ pub fn mock_repo_missing<'a>(server: &'a MockServer, repo: &str) -> Mock<'a> {
})
}

/// The REST API's `GET /repositories/{id}` for `repo`'s id, answered 404 as for a Repository
/// deleted, or one the token can no longer see.
pub fn mock_repo_by_id_missing<'a>(server: &'a MockServer, repo: &str) -> Mock<'a> {
server.mock(|when, then| {
when.method(GET)
.path(format!("/repositories/{}", repository_id(repo)));
then.status(404)
.json_body(json!({ "message": "Not Found" }));
})
}

/// The mocks [`mock_open_prs`] answers a sync with.
pub struct OpenPrs<'a> {
/// The list of open PRs you authored, which a full sync reads.
Expand Down
66 changes: 61 additions & 5 deletions crates/agentdeckd/src/db/repositories.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,21 +10,32 @@ use crate::prsync::github::RemoteRepository;

/// Stores `repository` as GitHub reports it now, by its id: a new one is created; a known one
/// takes its new name, URL, private and archived, so a rename or a transfer keeps it the same
/// Repository. Returns whether anything changed: `false` when it was stored as it is.
/// Repository, and GitHub showing it clears its Unreachable mark. Returns whether anything
/// changed: `false` when it was stored as it is.
pub fn store(conn: &Connection, repository: &RemoteRepository) -> Result<bool, DbError> {
let id = repository.id.get();
let stored: Option<(String, String, bool, bool)> = conn
let stored: Option<(String, String, bool, bool, bool)> = conn
.query_row(
"SELECT full_name, url, private, archived FROM repositories WHERE id = ?1",
"SELECT full_name, url, private, archived, unreachable_at IS NOT NULL
FROM repositories WHERE id = ?1",
[id],
|row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),
|row| {
Ok((
row.get(0)?,
row.get(1)?,
row.get(2)?,
row.get(3)?,
row.get(4)?,
))
},
)
.optional()?;
let now = (
repository.name.to_string(),
repository.url.clone(),
repository.private,
repository.archived,
false,
);
if stored.as_ref() == Some(&now) {
return Ok(false);
Expand All @@ -34,12 +45,57 @@ pub fn store(conn: &Connection, repository: &RemoteRepository) -> Result<bool, D
VALUES (?1, ?2, ?3, ?4, ?5)
ON CONFLICT (id) DO UPDATE SET
full_name = excluded.full_name, url = excluded.url, private = excluded.private,
archived = excluded.archived",
archived = excluded.archived, unreachable_at = NULL",
params![id, now.0, now.1, now.2, now.3],
)?;
Ok(true)
}

/// Marks stored Repository `id` Unreachable: GitHub doesn't show it to the sign-in. It keeps
/// what GitHub last said of it, its Links and its pull requests. Returns whether it changed:
/// `false` when it was marked already, or isn't stored.
pub fn mark_unreachable(conn: &Connection, id: RepositoryId) -> Result<bool, DbError> {
let marked = conn.execute(
"UPDATE repositories SET unreachable_at = ?2 WHERE id = ?1 AND unreachable_at IS NULL",
params![id.get(), super::now()],
)?;
Ok(marked > 0)
}

/// Stores what GitHub read by id says of stored Repositories, in one transaction: each of
/// `found` as GitHub shows it now ([`store`]), and each of `unreachable` marked Unreachable
/// ([`mark_unreachable`]). One no longer stored (unlinked while GitHub was asked) is left
/// out, so nothing is stored that nothing references. Returns those that changed.
pub fn refresh(
conn: &mut Connection,
found: &[RemoteRepository],
unreachable: &[RepositoryId],
) -> Result<Vec<RepositoryId>, DbError> {
let tx = conn.transaction()?;
let mut changed = Vec::new();
for repository in found {
if is_known(&tx, repository.id)? && store(&tx, repository)? {
changed.push(repository.id);
}
}
for id in unreachable {
if mark_unreachable(&tx, *id)? {
changed.push(*id);
}
}
tx.commit()?;
Ok(changed)
}

/// Every Repository a Workspace links, archived Workspaces' included, by id.
pub fn linked(conn: &Connection) -> Result<Vec<RepositoryId>, DbError> {
let mut stmt = conn.prepare("SELECT DISTINCT repository_id FROM links ORDER BY 1")?;
let rows = stmt.query_map([], |row| row.get::<_, u64>(0))?;
Ok(rows
.map(|id| id.map(RepositoryId::from))
.collect::<rusqlite::Result<_>>()?)
}

/// What [`link`] and [`store_and_link`] did.
#[derive(Debug)]
pub struct Linked {
Expand Down
Loading