diff --git a/crates/fctl-client/src/api.rs b/crates/fctl-client/src/api.rs index 13916555..6d1ddb15 100644 --- a/crates/fctl-client/src/api.rs +++ b/crates/fctl-client/src/api.rs @@ -619,6 +619,30 @@ impl Api { self.get(&q).await } + /// The sessions that list a pull request in `state` (`open`, `merged`, + /// `closed` or `any`), newest first: the pull requests page's, and + /// `fctl pulls`'. + pub async fn sessions_with_pulls( + &self, + workspace: Option<&str>, + project: Option<&str>, + state: &str, + mine: bool, + limit: u32, + ) -> Result { + let mut q = format!("/sessions?limit={limit}&pulls={}", enc(state)); + if let Some(w) = workspace { + q.push_str(&format!("&workspace={}", enc(w))); + } + if let Some(p) = project { + q.push_str(&format!("&project={}", enc(p))); + } + if mine { + q.push_str("&mine=1"); + } + self.get(&q).await + } + /// A project's sessions with its review agents', its archived ones and /// those its schedules hide among them, which the other lists leave /// out: to find one by its number. diff --git a/crates/fctl-control/src/api/sessions.rs b/crates/fctl-control/src/api/sessions.rs index c2a3d3f4..a49ddca0 100644 --- a/crates/fctl-control/src/api/sessions.rs +++ b/crates/fctl-control/src/api/sessions.rs @@ -356,6 +356,29 @@ pub async fn list(ctx: &Ctx, req: &Request) -> AppResult { if http::query(req, "mine").is_some_and(|v| v == "1" || v == "true") { sql.push_str(" AND s.created_by = ?1"); } + // The sessions that list a pull request, in a state, for the pull + // requests page and the sidebar: among those `pull_request_sessions` + // has, those whose own list (what their pages show, from their agents' + // lookups and GitHub's webhooks) has one in that state; sessions from + // before that list have their one. One nobody looked up counts as open. + if let Some(pulls) = http::query(req, "pulls") { + let states = match pulls.as_str() { + "any" | "1" | "true" => None, + "open" => Some("'open','draft','queued'"), + "merged" => Some("'merged'"), + "closed" => Some("'closed'"), + _ => { + return Err(validation("pulls", "Use open, merged, closed or any")); + } + }; + sql.push_str(" AND s.id IN (SELECT session_id FROM pull_request_sessions)"); + if let Some(states) = states { + sql.push_str(&format!( + " AND EXISTS (SELECT 1 FROM json_each(COALESCE(s.pull_requests, json_array(json_object('state', s.pr_state)))) j \ + WHERE COALESCE(json_extract(j.value, '$.state'), 'open') IN ({states}))" + )); + } + } // Review agents' sessions have a list of their own (the project's // reviews), and stay off the Agent Floor and the project's sessions. if !http::query(req, "reviews").is_some_and(|v| v == "1" || v == "true") { diff --git a/crates/fctl-domain/src/pulls.rs b/crates/fctl-domain/src/pulls.rs index e5fb43ac..f827b139 100644 --- a/crates/fctl-domain/src/pulls.rs +++ b/crates/fctl-domain/src/pulls.rs @@ -19,6 +19,7 @@ use fctl_proto::Millis; use fctl_proto::event::GitState; use fctl_proto::session::{PullRequestChecks, PullRequestRef, RepoRef, Session}; +use serde::Serialize; /// Most pull requests a session lists: the first its agent found. pub const MAX_PULL_REQUESTS: usize = 20; @@ -379,6 +380,92 @@ pub fn backfill(s: &mut Session) { } } +/// Whether `url` is a pull request's on GitHub, and nothing more: +/// `https://github.com///pull/`. +pub fn is_github_pull(url: &str) -> bool { + let Some(rest) = url.strip_prefix("https://github.com/") else { + return false; + }; + let parts: Vec<&str> = rest.split('/').collect(); + let name_ok = |p: &str| { + !p.is_empty() + && p.chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '-')) + }; + matches!(parts.as_slice(), [owner, name, "pull", number] + if name_ok(owner) && name_ok(name) && !number.is_empty() && number.chars().all(|c| c.is_ascii_digit())) +} + +/// A pull request as the pull requests page and `fctl pulls` list it: as +/// the session that last heard of it has it, with every session that +/// lists it, newest first. +#[derive(Clone, Debug, PartialEq, Serialize)] +pub struct Listed { + pub pull_request: PullRequestRef, + pub sessions: Vec, +} + +/// A session, as a listed pull request names it. +#[derive(Clone, Debug, PartialEq, Serialize)] +pub struct SessionRef { + pub id: fctl_proto::SessionId, + pub project_slug: String, + pub number: u32, + pub title: String, + pub status: fctl_proto::session::SessionStatus, + pub created_by: fctl_proto::session::UserRef, +} + +/// The pull requests `sessions` list (newest session first), each once: +/// the freshest of what the sessions say of it, those whose state is in +/// `states` (empty: any; a pull request nobody looked up counts as open), +/// the ones that changed last first. +pub fn listed(sessions: &[fctl_proto::session::Session], states: &[&str]) -> Vec { + let mut out: Vec = Vec::new(); + for s in sessions { + let prs: Vec<&PullRequestRef> = if s.pull_requests.is_empty() { + s.pull_request.iter().collect() + } else { + s.pull_requests.iter().collect() + }; + // Only links to GitHub's pull requests, as the web app's list has + // them: what runs in a sandbox can pose as its agent. + for pr in prs.into_iter().filter(|pr| is_github_pull(&pr.url)) { + let me = SessionRef { + id: s.id.clone(), + project_slug: s.project_slug.clone(), + number: s.number, + title: s.title.clone(), + status: s.status, + created_by: s.created_by.clone(), + }; + match out.iter_mut().find(|l| l.pull_request.url == pr.url) { + Some(l) => { + if pr.updated_at.unwrap_or(0) > l.pull_request.updated_at.unwrap_or(0) { + l.pull_request = pr.clone(); + } + l.sessions.push(me); + } + None => out.push(Listed { + pull_request: pr.clone(), + sessions: vec![me], + }), + } + } + } + out.retain(|l| { + states.is_empty() || states.contains(&l.pull_request.state.as_deref().unwrap_or("open")) + }); + let moved = |l: &Listed| { + l.pull_request + .updated_at + .or(l.pull_request.state_changed_at) + .unwrap_or(0) + }; + out.sort_by_key(|l| std::cmp::Reverse(moved(l))); + out +} + #[cfg(test)] mod tests { use super::*; @@ -973,4 +1060,70 @@ mod tests { assert_eq!(github_time(bad), None, "{bad}"); } } + + /// A session that lists `prs`, as the API sends one. + fn listing(n: u32, prs: Vec) -> Session { + let mut s: Session = serde_json::from_value(serde_json::json!({ + "id": format!("ses_{n}"), + "project_id": "prj_1", + "project_slug": "shop", + "number": n, + "title": format!("Session {n}"), + "status": "stopped", + "created_by": { "id": "usr_1", "name": "Noor Haddad" }, + "created_at": i64::from(n), + "updated_at": i64::from(n), + "stats": {}, + "archived": false + })) + .unwrap_or_else(|e| panic!("a session: {e}")); + s.pull_requests = prs; + s + } + + #[test] + fn pull_requests_are_listed_once_with_every_session_that_lists_them() { + let mut fresh = pr("acme/shop", 12); + fresh.updated_at = Some(30); + fresh.state = Some("merged".into()); + let mut stale = pr("acme/shop", 12); + stale.updated_at = Some(10); + let mut other = pr("acme/platform", 7); + other.updated_at = Some(20); + // Newest session first, as the API lists them. + let sessions = [ + listing(3, vec![stale]), + listing(2, vec![other]), + listing(1, vec![fresh]), + ]; + let all = listed(&sessions, &[]); + assert_eq!(all.len(), 2); + // The freshest of what the sessions say, the one that changed last first. + assert_eq!(all[0].pull_request.number, 12); + assert_eq!(all[0].pull_request.state.as_deref(), Some("merged")); + assert_eq!( + all[0].sessions.iter().map(|s| s.number).collect::>(), + [3, 1] + ); + assert_eq!(all[1].pull_request.number, 7); + // Only those in a state; one nobody looked up counts as open. + let open = listed(&sessions, &["open", "draft", "queued"]); + assert_eq!( + open.iter() + .map(|l| l.pull_request.number) + .collect::>(), + [7] + ); + let mut unknown = pr("acme/web", 1); + unknown.state = None; + assert_eq!(listed(&[listing(4, vec![unknown])], &["open"]).len(), 1); + // Only GitHub's pull requests: a sandbox can pose as its agent. + let mut elsewhere = pr("acme/web", 2); + elsewhere.url = "https://evil.example/acme/web/pull/2".into(); + let mut longer = pr("acme/web", 3); + longer.url.push_str("/files"); + assert!(listed(&[listing(5, vec![elsewhere, longer])], &[]).is_empty()); + assert!(is_github_pull("https://github.com/acme/web.site/pull/12")); + assert!(!is_github_pull("https://github.com/acme/web/issues/12")); + } } diff --git a/crates/fctl/src/cmd/mod.rs b/crates/fctl/src/cmd/mod.rs index 658c03d8..7f3dd87b 100644 --- a/crates/fctl/src/cmd/mod.rs +++ b/crates/fctl/src/cmd/mod.rs @@ -14,6 +14,7 @@ pub mod project_members; pub mod project_secrets; pub mod projects; pub mod publish; +pub mod pulls; pub mod resolve; pub mod retro; pub mod review; diff --git a/crates/fctl/src/cmd/pulls.rs b/crates/fctl/src/cmd/pulls.rs new file mode 100644 index 00000000..ef1892c0 --- /dev/null +++ b/crates/fctl/src/cmd/pulls.rs @@ -0,0 +1,164 @@ +//! `fctl pulls`: the pull requests agents opened or worked on in your +//! projects, each once, with the sessions that list it: the web app's pull +//! requests page, in a terminal. + +use crate::{config, style}; +use anyhow::Result; +use clap::{Args, ValueEnum}; +use fctl_domain::pulls::{Listed, listed}; + +#[derive(Args)] +pub struct PullsArgs { + /// Only this project's (slug or id). + #[arg(short, long)] + pub project: Option, + /// Only this workspace's (slug or id). + #[arg(short, long, conflicts_with = "project")] + pub workspace: Option, + /// Which ones: open (open, drafts and those in a merge queue), merged, + /// closed or all. + #[arg(long, value_enum, default_value = "open")] + pub state: State, + /// Only those of sessions you started. + #[arg(long)] + pub mine: bool, + /// Sessions to look through, newest first (at most 200). + #[arg(long, default_value_t = 100, value_parser = clap::value_parser!(u32).range(1..=200))] + pub limit: u32, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)] +pub enum State { + Open, + Merged, + Closed, + All, +} + +impl State { + /// What the API's `pulls` takes, and the states `listed` keeps. + fn query(self) -> (&'static str, &'static [&'static str]) { + match self { + Self::Open => ("open", &["open", "draft", "queued"]), + Self::Merged => ("merged", &["merged"]), + Self::Closed => ("closed", &["closed"]), + Self::All => ("any", &[]), + } + } +} + +pub async fn run(server: Option<&str>, args: PullsArgs, json: bool) -> Result<()> { + let api = config::api(server)?; + let project = match &args.workspace { + Some(_) => None, + None => args.project, + }; + // Every session that lists one, whatever its state: each pull request + // takes the state the session that heard of it last says, which one + // that heard of it earlier may not. + let (_, states) = args.state.query(); + let list = api + .sessions_with_pulls( + args.workspace.as_deref(), + project.as_deref(), + "any", + args.mine, + args.limit, + ) + .await?; + let found = listed(&list.sessions, states); + // More sessions than it looked at: older pull requests aren't in it. + let more = list.next_before.is_some(); + if json { + return style::print_json(&serde_json::json!({ + "pull_requests": found, + "next_before": list.next_before, + })); + } + if more { + eprintln!( + "{}", + style::dim(&format!( + "From the newest {} sessions with pull requests: narrow it with -p or -w, or raise --limit (at most 200), for older ones.", + args.limit + )) + ); + } + if found.is_empty() { + println!( + "{}", + match args.state { + State::Open => "No open pull requests: agents open them as they finish their work.", + State::Merged => "No merged pull requests.", + State::Closed => "No closed pull requests.", + State::All => "No pull requests yet: agents open them as they finish their work.", + } + ); + return Ok(()); + } + let now = style::now_ms(); + for l in &found { + print_line(l, now); + } + Ok(()) +} + +fn print_line(l: &Listed, now: i64) { + let pr = &l.pull_request; + let repo = pr + .repo + .clone() + .or_else(|| fctl_domain::pulls::repo_of(&pr.url)) + .map(|r| r.full_name()) + .unwrap_or_default(); + let title = style::plain(pr.title.as_deref().unwrap_or_default()); + let sessions: Vec = l + .sessions + .iter() + .map(|s| format!("{}#{}", s.project_slug, s.number)) + .collect(); + println!( + "{} {}", + style::bold(&format!("{repo}#{}", pr.number)), + truncate(&title, 60) + ); + println!( + " {}{}", + super::sessions::pull_request_state(pr, now).unwrap_or_else(|| style::dim("open")), + style::dim(&format!( + " · {} · {}", + sessions.join(", "), + style::terminal_safe(&pr.url) + )) + ); +} + +fn truncate(s: &str, n: usize) -> String { + if s.chars().count() <= n { + s.to_owned() + } else { + format!("{}…", s.chars().take(n - 1).collect::()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use clap::Parser; + + #[derive(Parser)] + struct Fctl { + #[command(flatten)] + pulls: PullsArgs, + } + + #[test] + fn open_ones_by_default_and_any_state_for_all() { + let open = Fctl::try_parse_from(["fctl"]).map(|f| f.pulls.state.query()); + assert_eq!(open.ok().map(|q| q.0), Some("open")); + let all = Fctl::try_parse_from(["fctl", "--state", "all"]).map(|f| f.pulls.state.query()); + assert_eq!(all.ok(), Some(("any", &[][..]))); + assert!(Fctl::try_parse_from(["fctl", "-p", "shop", "-w", "romanesco"]).is_err()); + assert!(Fctl::try_parse_from(["fctl", "--limit", "500"]).is_err()); + } +} diff --git a/crates/fctl/src/cmd/sessions.rs b/crates/fctl/src/cmd/sessions.rs index 0125c0b0..1855e48d 100644 --- a/crates/fctl/src/cmd/sessions.rs +++ b/crates/fctl/src/cmd/sessions.rs @@ -455,7 +455,7 @@ fn pull_request_lines(s: &Session, now: i64) -> Vec { /// checks passed`, `draft, 1 of 4 checks failed`, and how fctl's review /// of it went: `open, checks passed, fctl's review agent found 2 issues`. /// Nothing while nobody looked it up. -fn pull_request_state(pr: &PullRequestRef, now: i64) -> Option { +pub(crate) fn pull_request_state(pr: &PullRequestRef, now: i64) -> Option { let state = style::terminal_safe(pr.state.as_deref()?); if matches!(state.as_ref(), "merged" | "closed") { let when = pr diff --git a/crates/fctl/src/main.rs b/crates/fctl/src/main.rs index e125b220..6ae1df64 100644 --- a/crates/fctl/src/main.rs +++ b/crates/fctl/src/main.rs @@ -83,6 +83,13 @@ enum Command { fctl search \"database migration\" -p my-app fctl search --json flaky | jq -r '.sessions[].session.id'")] Search(cmd::search::SearchArgs), + /// The pull requests agents opened in your projects, each once, with + /// the sessions that list it: open ones unless you ask for others. + #[command(after_help = "Examples: + fctl pulls # open ones (drafts and merge queues too), in all your workspaces + fctl pulls -p shop --state merged + fctl pulls --mine --json")] + Pulls(cmd::pulls::PullsArgs), /// Show a session's details. Show { /// A session: its id (ses_…), its URL, or project#number. @@ -465,6 +472,7 @@ async fn run(cli: Cli) -> anyhow::Result<()> { Command::Edit(args) => cmd::sessions::edit(server, args, json).await, Command::Publish(args) => cmd::publish::publish(args, json).await, Command::Ask(args) => cmd::ask::run(args, json).await, + Command::Pulls(args) => cmd::pulls::run(server, args, json).await, Command::Unpublish { links } => cmd::publish::unpublish(server, &links, json).await, Command::Memory(args) => cmd::memory::run(server, args, json).await, Command::Retro(args) => cmd::retro::run(server, args, json).await, diff --git a/docs/api.md b/docs/api.md index 635c6683..fd9bab83 100644 --- a/docs/api.md +++ b/docs/api.md @@ -111,7 +111,11 @@ It answers with the session, `queued`. A session is: failed) or one status, `?active_since=` (a time in milliseconds: those that haven't ended, and those that ended since, as the app's sidebar lists the last hour's), `?mine=1` (started by the caller), `?reviews=1`, - `?archived=1`, `?hidden=1`, `?limit=` (50 unless set, at most 200), `?before=` (a + `?archived=1`, `?hidden=1`, `?pulls=open|merged|closed|any` (those that + list a pull request in that state in their `pull_requests`, as their + agents and GitHub last said; one nobody looked up counts as open: the + app's pull requests page and `fctl pulls` ask for `any` and group them, + each pull request as the session that heard of it last says), `?limit=` (50 unless set, at most 200), `?before=` (a `created_at`). Answers `{"sessions": […], "next_before": …}`. - `GET /api/v1/sessions/{id}`: one session. - `GET /api/v1/search?q=…`: the sessions whose title, description, diff --git a/docs/architecture.md b/docs/architecture.md index 71206736..0ead8a49 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1405,6 +1405,17 @@ how, where the sandbox's fctl has the command. ### Pull request state and checks +The web app's pull requests page (`/pulls`) and `fctl pulls` list the pull +requests agents opened or worked on, each once, from the sessions that +list one (`GET /api/v1/sessions?pulls=…`, by `pull_request_sessions`): +each as the session that heard of it last has it, with every session that +lists it (`web/src/lib/pull-list.ts`, `fctl_domain::pulls::listed`). The +page counts them by state, and sorts the open ones by what each needs +next: those whose agents finished and whose checks didn't fail are ready +for review, then those whose checks failed, those whose sessions are still +at work, those in a merge queue, and drafts. The feed patches the sessions +it came from, so states, checks and reviews change there as GitHub says. + Session lists, the session page and `fctl show` give each pull request its state, `open`, `draft`, `queued` (in a merge queue), `merged` or `closed`, since when, the checks of its head commit: how many passed, failed and diff --git a/docs/cli.md b/docs/cli.md index 62cd0e1e..cea2d5c3 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -87,6 +87,8 @@ fctl run -p my-app -a screenshot.png "Make the header match this" # attach fil fctl sessions # recent sessions (only the default project's, once fctl projects use set one) fctl sessions --active -p my-app fctl sessions --since 1h # at work in the last hour: those that haven't ended, and those that ended in it +fctl pulls # the open pull requests agents opened (drafts and merge queues too), each with its sessions +fctl pulls -p my-app --state merged --mine --json fctl sessions -w acme --limit 100 # a workspace's (30 unless --limit says) fctl show my-app#12 # status, branch, pull requests with their checks and review, model and effort, usage fctl edit my-app#12 --title "Fix the flaky login test" diff --git a/docs/llms.txt b/docs/llms.txt index d5ccd3f3..95916634 100644 --- a/docs/llms.txt +++ b/docs/llms.txt @@ -195,7 +195,7 @@ Each recipe says who does what: some steps take a person with a role in the proj 10. **Plan or review without changes**: `fctl run -p my-app -d --github read "Plan the move to Postgres: what changes, in what order, what can break."` or a project-wide cap: `fctl projects set -p my-app --github comment`. 11. **Set up a project** (a workspace admin): `fctl projects create "My app" --repo my-org/my-app -w acme`, then `fctl projects set -p my-app --setup-script 'npm ci' --idle-timeout 30 --pr-descriptions balanced`, more repositories with `fctl projects repos add my-org/my-lib --write -p my-app`, an image with `--image ghcr.io/acme/agent:1` or `--build Dockerfile`, size with `--cpus 8 --memory 16g`, shared package caches with `--package-caches on`, its agents' instructions, model and effort with `--instructions-file agents.md --model opus --effort high`, opening pull requests when they finish with `--auto-pull-request on|off`, how they handle pull requests and issues with `--pr-instructions-file prs.md` (`fctl projects show my-app --pr-instructions` prints fctl's rules to start from), Remote Control and claude.ai connectors with `--remote-control on|off --connectors on|off`, its name, description and default branch with `--name "Web app" --description "The storefront" --default-branch develop`, and its icon in the sidebar and on its page with `--icon store --icon-color yellow --icon-style duotone` (an [IconMCP](https://iconmcp.com) glyph's name; ink, yellow, pink or blue; outline, duotone or solid; `--icon ""` for the one that fits its name). Secrets: `fctl projects secrets set STRIPE_KEY -p my-app`, the value typed at its prompt or piped in; `fctl projects secrets -p my-app` lists their names. People: `fctl projects members add grace@example.com --role maintainer -p my-app` (`viewer`, `editor`, `maintainer`, `owner`), `fctl projects members role …`, `fctl projects members remove …`. 12. **Bring a machine online** (its owner, at its terminal): install Apple's `container` (macOS 26+, `container system start`; a host on the apple driver starts it again after the Mac restarts), Lima, or Docker (on Linux, Docker Engine with `sudo systemctl enable --now docker`; `fctl host install` offers to add the user to the `docker` group, and fctl takes the group itself, with no new login), or on Linux with KVM `passt` and `e2fsprogs` for `--driver firecracker`; then `fctl login`, `fctl host install --workspace acme` (or `--token fctl_rt_…` from the workspace's Runners tab), `fctl host doctor`, `fctl host status`. Maintenance: `fctl host drain --wait`, `fctl host undrain`. Many machines, or ones autoscaling starts: a workspace admin makes an enrollment token (`fctl runners enrollment-tokens create "Build fleet" -w acme --max-runners 20 --remove-offline-after 5m`, `--approval` to approve each), or any member one for their own sessions (`--personal`), and each machine's boot script runs `FCTL_SERVER=https://app.fctl.sh FCTL_ENROLL_TOKEN=fctl_et_… fctl host install` with no sign-in (and, for someone who keeps their Claude token on their runners, `fctl host claude set-token < /run/secrets/claude-token`); `fctl runners --pending`, `fctl runners approve `, `fctl runners reject `, `fctl runners remove `. -13. **Dashboards and reports**: a token with `--access read` lists sessions, transcripts, memory and retrospectives and starts nothing: `fctl sessions --active --json`, `fctl sessions --since 1d --json` (at work in the last day, those that ended in it too), `fctl retro list -p my-app --json`, `fctl search "flaky test" --json`, `fctl logs my-app#12 --json`, `fctl diff my-app#12` (the branch's changes as git prints them; `--json` for each file's patch). +13. **Dashboards and reports**: a token with `--access read` lists sessions, transcripts, memory and retrospectives and starts nothing: `fctl sessions --active --json`, `fctl sessions --since 1d --json` (at work in the last day, those that ended in it too), `fctl pulls --json` (the open pull requests agents opened, each once with the sessions that list it; `-p my-app`, `--state merged|closed|all`, `--mine`; the app's `/pulls` page sorts the open ones by what each needs next: ready for review, checks failing, agents at work, merge queue, drafts), `fctl retro list -p my-app --json`, `fctl search "flaky test" --json`, `fctl logs my-app#12 --json`, `fctl diff my-app#12` (the branch's changes as git prints them; `--json` for each file's patch). 14. **Keep agents informed**: `fctl memory add -p my-app "Deploys happen on Thursdays: merge migrations by Tuesday."`; read what they learned with `fctl memory -p my-app` and `fctl retro list -p my-app --outcome blocked`. 15. **Hand a session to someone** (its owners): `fctl share grace@example.com` lets someone in its workspace view it and message its agent (`--role viewer` only views it, `--role owner` also stops, resumes, archives and shares it), `fctl share ` lists who it is shared with, `fctl unshare grace@example.com` takes it back. Anyone who can message the agent can have it hand over the sandbox's secrets and tokens. `fctl archive ` takes a finished session out of the lists and stops follow-ups reaching it (`fctl unarchive`, `fctl sessions --archived`). diff --git a/web/src/components/shell/command-palette.test.tsx b/web/src/components/shell/command-palette.test.tsx index a9c3b705..2374b7d4 100644 --- a/web/src/components/shell/command-palette.test.tsx +++ b/web/src/components/shell/command-palette.test.tsx @@ -96,7 +96,19 @@ describe("⌘K", () => { it("lists the Agent Floor first, before the sessions, while nothing is typed", () => { const { entries } = palette(); expect(entries()[0]).toBe("Agent Floornew session"); - expect(entries()[1]).toBe("Fix the flaky login testweb#12"); + expect(entries()[1]).toBe("Pull requestswhat each needs next"); + expect(entries()[2]).toBe("Fix the flaky login testweb#12"); + }); + + it("goes to the pull requests, by name or what people call them", () => { + const { entries, input, press } = palette(); + act(() => { + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set?.call(input, "prs"); + input.dispatchEvent(new Event("input", { bubbles: true })); + }); + expect(entries()[0]).toBe("Pull requestswhat each needs next"); + press("Enter"); + expect(navigate).toHaveBeenCalledWith({ to: "/pulls", search: {} }); }); it("finds the Agent Floor by the name it had before, Home", () => { diff --git a/web/src/components/shell/command-palette.tsx b/web/src/components/shell/command-palette.tsx index 687a40d3..5209a490 100644 --- a/web/src/components/shell/command-palette.tsx +++ b/web/src/components/shell/command-palette.tsx @@ -8,7 +8,7 @@ import { FolderPlus, MessageSquareText, Moon, Plus, Search, Settings, Shield } f import { type ReactNode, useEffect, useMemo, useRef, useState } from "react"; import { createPortal } from "react-dom"; import { ProjectMark } from "@/components/project/project-icon"; -import { AgentFloorIcon, Spinner, StatusDot } from "@/components/ui"; +import { AgentFloorIcon, PullRequestIcon, Spinner, StatusDot } from "@/components/ui"; import { WorkspaceAvatar } from "@/components/workspace/avatar"; import type * as G from "@/gen"; import { cn } from "@/lib/cn"; @@ -109,6 +109,15 @@ export function CommandPalette({ focusTaskBox(); }), }, + { + id: "pulls", + group: "Go to", + label: "Pull requests", + hint: "what each needs next", + keywords: "prs review merge checks", + icon: , + run: go(() => void navigate({ to: "/pulls", search: {} })), + }, ]; for (const s of sessions?.sessions ?? []) { list.push({ diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts index a3ef2238..5fab860b 100644 --- a/web/src/lib/api.ts +++ b/web/src/lib/api.ts @@ -330,9 +330,12 @@ export const api = { /** Without those that ended before then (ms). */ activeSince?: number; mine?: boolean; + /** Only those that list a pull request in this state (the pull requests page). */ + pulls?: "open" | "merged" | "closed" | "any"; } = {}, ) => { const p = new URLSearchParams(); + if (q.pulls) p.set("pulls", q.pulls); if (q.project) p.set("project", q.project); if (q.workspace) p.set("workspace", q.workspace); if (q.status) p.set("status", q.status); diff --git a/web/src/lib/feed.test.ts b/web/src/lib/feed.test.ts index 884cdc1e..68506e55 100644 --- a/web/src/lib/feed.test.ts +++ b/web/src/lib/feed.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; import type * as G from "@/gen"; -import { movesLists } from "./feed"; +import { findsPulls, movesLists } from "./feed"; const summary = (more: Partial = {}) => ({ id: "ses_1", status: "running", archived: false, title: "Fix the build", ...more }) as G.Session; @@ -20,3 +20,14 @@ describe("a session's summary from the feed", () => { expect(movesLists(summary(), summary({ title: "Fix the flaky build", last_activity_at: 2 }))).toBe(false); }); }); + +describe("pull requests a session finds", () => { + const s = { id: "ses_1", status: "running", archived: false } as G.Session; + const pr = (n: number) => ({ number: n, url: `https://github.com/acme/web/pull/${n}` }); + it("bring the lists of pull requests again when one is new", () => { + expect(findsPulls(s, { ...s, pull_requests: [pr(1)] })).toBe(true); + expect(findsPulls({ ...s, pull_requests: [pr(1)] }, { ...s, pull_requests: [pr(1)] })).toBe(false); + expect(findsPulls({ ...s, pull_requests: [pr(1)] }, { ...s, pull_requests: [pr(1), pr(2)] })).toBe(true); + expect(findsPulls(undefined, s)).toBe(false); + }); +}); diff --git a/web/src/lib/feed.ts b/web/src/lib/feed.ts index be8193c0..a0cd46f3 100644 --- a/web/src/lib/feed.ts +++ b/web/src/lib/feed.ts @@ -31,6 +31,17 @@ interface FeedState { export const movesLists = (before: G.Session | undefined, after: G.Session) => !before || before.status !== after.status || before.archived !== after.archived; +/** + * Whether a session lists a pull request it didn't: the lists of sessions by their pull requests + * (`?pulls=`), which it may not be in yet, come again. + */ +export const findsPulls = (before: G.Session | undefined, after: G.Session) => { + const urls = (s: G.Session | undefined) => + new Set((s?.pull_requests ?? (s?.pull_request ? [s.pull_request] : [])).map((pr) => pr.url)); + const had = urls(before); + return [...urls(after)].some((u) => !had.has(u)); +}; + class Feed { state: FeedState = { connected: false, runners: [], sessions: new Map() }; private listeners = new Set<() => void>(); @@ -126,6 +137,15 @@ class Feed { // New sessions and status changes may move lists and change projects' counts; refresh // them lazily. Patching them has the rest, as an agent's every step changes its session's // summary, and the sidebar's list shows on every page. + if (findsPulls(before, msg.session)) + void queryClient.invalidateQueries({ + predicate: (q) => + q.queryKey[0] === "sessions" && + typeof q.queryKey[1] === "object" && + q.queryKey[1] !== null && + "pulls" in q.queryKey[1], + refetchType: "active", + }); if (movesLists(before, msg.session)) { void queryClient.invalidateQueries({ queryKey: ["sessions"], refetchType: "active" }); void queryClient.invalidateQueries({ queryKey: keys.projects, refetchType: "active" }); diff --git a/web/src/lib/pull-list.test.ts b/web/src/lib/pull-list.test.ts new file mode 100644 index 00000000..c9bbdff4 --- /dev/null +++ b/web/src/lib/pull-list.test.ts @@ -0,0 +1,87 @@ +import { describe, expect, it } from "vitest"; +import type * as G from "@/gen"; +import { countStates, listPulls, needOf, pullMatches, stateOf } from "./pull-list"; + +let n = 0; +function pr(number: number, more: Partial = {}): G.PullRequestRef { + return { + number, + url: `https://github.com/acme/shop/pull/${number}`, + title: `Change ${number}`, + state: "open", + repo: { owner: "acme", name: "shop" }, + ...more, + }; +} + +function session(prs: G.PullRequestRef[], more: Partial = {}): G.Session { + n++; + return { + id: `ses_${n}`, + project_id: "prj_shop", + project_slug: "shop", + number: n, + title: `Session ${n}`, + status: "stopped", + created_by: { id: "usr_noor", name: "Noor Haddad" }, + created_at: n, + updated_at: n, + stats: {} as G.SessionStats, + archived: false, + pull_requests: prs, + ...more, + } as G.Session; +} + +describe("the pull requests page's list", () => { + it("lists each pull request once, as the session that heard of it last has it", () => { + const later = session([pr(12, { state: "merged", updated_at: 30 })]); + const earlier = session([pr(12, { updated_at: 10 }), pr(7, { updated_at: 20 })]); + const list = listPulls([later, earlier]); + expect(list.map((l) => l.pr.number)).toEqual([12, 7]); + expect(list[0]?.pr.state).toBe("merged"); + expect(list[0]?.sessions.map((s) => s.id)).toEqual([later.id, earlier.id]); + }); + + it("says what each open one needs next", () => { + const one = (p: G.PullRequestRef, s: Partial = {}) => { + const [l] = listPulls([session([p], s)]); + return l ? needOf(l) : undefined; + }; + expect(one(pr(1))).toBe("ready"); + expect(one(pr(2), { status: "running" })).toBe("working"); + expect(one(pr(3, { state: "draft" }))).toBe("draft"); + expect(one(pr(4, { state: "queued" }))).toBe("queued"); + expect( + one(pr(5, { checks: { passed: 3, failed: 1, pending: 0 } as G.PullRequestChecks }), { + status: "running", + }), + ).toBe("failing"); + }); + + it("counts them by state, and nobody's look-up counts as open", () => { + const list = listPulls([ + session([pr(1), pr(2, { state: "merged" }), pr(3, { state: "closed" }), pr(4, { state: undefined })]), + ]); + expect(countStates(list)).toEqual({ open: 2, merged: 1, closed: 1 }); + expect(list.filter((l) => stateOf(l) === "open").map((l) => l.pr.number)).toEqual([1, 4]); + }); + + it("filters by title, repository, number and session", () => { + const [l] = listPulls([ + session([pr(843, { title: "Plan routes with time windows" })], { title: "Plan routes" }), + ]); + if (!l) throw new Error("listed"); + expect(pullMatches(l, "routes")).toBe(true); + expect(pullMatches(l, "acme/shop")).toBe(true); + expect(pullMatches(l, "#843")).toBe(true); + // As its row shows it, and as its link says it. + expect(pullMatches(l, "acme/shop#843")).toBe(true); + expect(pullMatches(l, "shop#843")).toBe(true); + expect(pullMatches(l, "https://github.com/acme/shop/pull/843")).toBe(true); + expect(pullMatches(l, "acme/shop#844")).toBe(false); + expect(pullMatches(l, "Noor")).toBe(true); + expect(pullMatches(l, "routes payments")).toBe(false); + expect(pullMatches(l, " ")).toBe(true); + }); +}); diff --git a/web/src/lib/pull-list.ts b/web/src/lib/pull-list.ts new file mode 100644 index 00000000..12a88b46 --- /dev/null +++ b/web/src/lib/pull-list.ts @@ -0,0 +1,89 @@ +// The pull requests page's list: each pull request that sessions list, once, as the session that +// heard of it last has it, with every session that lists it; what each needs next; and how many +// are in each state. fctl_domain::pulls::listed is its twin for `fctl pulls`. + +import type * as G from "@/gen"; +import { checksMark, prFullRef, prState, pullRequests } from "./pulls"; + +export interface ListedPull { + pr: G.PullRequestRef; + /** Newest first. */ + sessions: G.Session[]; +} + +/** Which tab a pull request is in. */ +export type PullState = "open" | "merged" | "closed"; +export const PULL_STATES: PullState[] = ["open", "merged", "closed"]; + +/** What an open pull request needs next, in the order the page shows them. */ +export type Need = "ready" | "failing" | "working" | "queued" | "draft"; + +export const NEEDS: { need: Need; title: string; hint: string }[] = [ + { need: "ready", title: "Ready for review", hint: "Their agents finished, and nothing failed" }, + { need: "failing", title: "Checks failing", hint: "What the agent pushed last didn't pass" }, + { need: "working", title: "Agents at work", hint: "Their sessions are still going" }, + { need: "queued", title: "In a merge queue", hint: "GitHub merges them in turn" }, + { need: "draft", title: "Drafts", hint: "Not ready for review yet" }, +]; + +/** Each pull request `sessions` list (newest session first), once. */ +export function listPulls(sessions: readonly G.Session[]): ListedPull[] { + const byUrl = new Map(); + for (const s of sessions) + for (const pr of pullRequests(s)) { + const l = byUrl.get(pr.url); + if (!l) byUrl.set(pr.url, { pr, sessions: [s] }); + else { + if ((pr.updated_at ?? 0) > (l.pr.updated_at ?? 0)) l.pr = pr; + if (!l.sessions.some((x) => x.id === s.id)) l.sessions.push(s); + } + } + return [...byUrl.values()].sort((a, b) => moved(b) - moved(a)); +} + +/** When a pull request last moved: GitHub's last change, else when it took its state. */ +export const moved = (l: ListedPull) => + l.pr.updated_at ?? l.pr.state_changed_at ?? l.sessions[0]?.updated_at ?? 0; + +/** Its tab: merged and closed, and open for the rest (drafts, merge queues, and those nobody looked up). */ +export function stateOf(l: ListedPull): PullState { + const s = prState(l.pr); + return s === "merged" || s === "closed" ? s : "open"; +} + +const AT_WORK: G.SessionStatus[] = ["queued", "provisioning", "preparing", "running", "stopping"]; + +/** What an open pull request needs next. */ +export function needOf(l: ListedPull): Need { + const s = prState(l.pr); + if (s === "queued") return "queued"; + if (s === "draft") return "draft"; + if (checksMark(l.pr) === "failed") return "failing"; + if (l.sessions.some((x) => AT_WORK.includes(x.status))) return "working"; + return "ready"; +} + +/** How many pull requests each tab has. */ +export function countStates(list: readonly ListedPull[]): Record { + const n: Record = { open: 0, merged: 0, closed: 0 }; + for (const l of list) n[stateOf(l)]++; + return n; +} + +/** + * Whether `l` has every word of `query` in its title, its reference as its row shows it + * ("acme/shop#12", which "shop#12" and "#12" find too), its link or its sessions. + */ +export function pullMatches(l: ListedPull, query: string): boolean { + const words = query.toLowerCase().split(/\s+/).filter(Boolean); + if (!words.length) return true; + const text = [ + l.pr.title ?? "", + prFullRef(l.pr), + l.pr.url, + ...l.sessions.flatMap((s) => [s.title, `${s.project_slug}#${s.number}`, s.created_by.name]), + ] + .join(" ") + .toLowerCase(); + return words.every((w) => text.includes(w)); +} diff --git a/web/src/router.tsx b/web/src/router.tsx index a15dd794..ae32a6d1 100644 --- a/web/src/router.tsx +++ b/web/src/router.tsx @@ -16,6 +16,7 @@ import { NewProject } from "@/routes/new-project"; import { NewWorkspace } from "@/routes/new-workspace"; import { NotFound } from "@/routes/not-found"; import { ProjectPage } from "@/routes/project"; +import { PullsPage, type PullsSearch } from "@/routes/pulls"; import { SessionPage } from "@/routes/session"; import { SettingsPage } from "@/routes/settings"; import { SignedInLayout } from "@/routes/two-factor"; @@ -162,6 +163,17 @@ const session = createRoute({ at: typeof s.at === "number" && Number.isSafeInteger(s.at) && s.at > 0 ? s.at : undefined, }), }); +const pulls = createRoute({ + getParentRoute: () => app, + path: "/pulls", + component: PullsPage, + validateSearch: (s: Record): PullsSearch => ({ + state: oneOf(s.state, ["open", "merged", "closed"] as const), + scope: typeof s.scope === "string" && /^[wp]:[a-z0-9-]+$/.test(s.scope) ? s.scope : undefined, + mine: flag(s.mine), + q: str(s.q), + }), +}); const settings = createRoute({ getParentRoute: () => app, path: "/settings", @@ -204,7 +216,18 @@ const tree = root.addChildren([ invite, reset, twoFactor, - app.addChildren([home, device, newProject, newWorkspace, workspace, project, session, settings, admin]), + app.addChildren([ + home, + device, + newProject, + newWorkspace, + workspace, + project, + session, + pulls, + settings, + admin, + ]), ]); export const router = createRouter({ diff --git a/web/src/routes/pulls.test.tsx b/web/src/routes/pulls.test.tsx new file mode 100644 index 00000000..176c03f2 --- /dev/null +++ b/web/src/routes/pulls.test.tsx @@ -0,0 +1,171 @@ +import { QueryClientProvider } from "@tanstack/react-query"; +import { act, type ReactNode } from "react"; +import { createRoot } from "react-dom/client"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type * as G from "@/gen"; +import { keys, queryClient } from "@/lib/queries"; +import { PullsPage } from "./pulls"; + +/** The page's search: what it lists. */ +const search = vi.hoisted(() => ({ value: {} as { scope?: string } })); + +vi.mock("@tanstack/react-router", () => ({ + useSearch: () => search.value, + useNavigate: () => vi.fn(), + Link: ({ + children, + to: _to, + params: _params, + search: _search, + ...rest + }: { children: ReactNode; to?: string; params?: unknown; search?: unknown } & Record) => ( + + {children} + + ), +})); + +(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + +/** What the sessions endpoint answers next: a list, or a failure. */ +let answer: () => Response; + +beforeEach(() => { + // Without retries, a failed request fails the query at once. + queryClient.setQueryDefaults(["sessions"], { retry: false }); + vi.stubGlobal("fetch", (url: string) => + url.startsWith("/api/v1/sessions?") ? Promise.resolve(answer()) : new Promise(() => {}), + ); +}); + +const roots: (() => void)[] = []; +afterEach(() => { + for (const unmount of roots.splice(0)) unmount(); + queryClient.clear(); + queryClient.setQueryDefaults(["sessions"], {}); + vi.unstubAllGlobals(); + search.value = {}; +}); + +/** A session that finished, with its open pull request. */ +const finished = (n: number, number: number, title: string): G.Session => ({ + id: `ses_${n}`, + project_id: "prj_shop", + project_slug: "shop", + number: n, + title: `Session ${n}`, + status: "stopped", + created_by: { id: "usr_noor", name: "Noor Haddad" }, + created_at: n, + updated_at: n, + stats: {} as G.SessionStats, + archived: false, + pull_requests: [ + { + number, + url: `https://github.com/romanesco/shop/pull/${number}`, + title, + state: "open", + repo: { owner: "romanesco", name: "shop" }, + }, + ], +}); +const listing = (): Response => Response.json({ sessions: [finished(231, 1291, "Danish for the shop")] }); +const failure = (): Response => + Response.json({ code: "internal", message: "The database is busy" }, { status: 500 }); + +async function render() { + const host = document.createElement("div"); + document.body.append(host); + const root = createRoot(host); + await act(async () => + root.render( + + + , + ), + ); + roots.push(() => { + act(() => root.unmount()); + host.remove(); + }); + return host; +} + +describe("the pull requests page", () => { + it("moves from the row the focus is in, from its link or from its GitHub arrow", async () => { + answer = () => + Response.json({ + sessions: [ + finished(232, 1292, "Danish for the box builder"), + finished(231, 1291, "Danish for the shop"), + ], + }); + const page = await render(); + await act(() => vi.waitFor(() => expect(page.querySelectorAll("[data-row]")).toHaveLength(2))); + const [first, second] = [...page.querySelectorAll("[data-row]")]; + const arrow = first?.closest("li")?.querySelector('a[aria-label$="on GitHub"]'); + const press = (key: string) => + act(() => { + document.activeElement?.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true })); + }); + const open = vi.spyOn(window, "open").mockImplementation(() => null); + arrow?.focus(); + press("o"); + expect(open).toHaveBeenCalledWith(first?.dataset.github, "_blank", "noopener,noreferrer"); + press("j"); + expect(document.activeElement).toBe(second); + second?.closest("li")?.querySelector('a[aria-label$="on GitHub"]')?.focus(); + press("k"); + expect(document.activeElement).toBe(first); + open.mockRestore(); + }); + + it("says what it lists by name", async () => { + answer = listing; + queryClient.setQueryData(keys.workspaces, { + workspaces: [{ id: "ws_r", slug: "romanesco", name: "Romanesco" }], + invitations: [], + limit: 5, + } as unknown as G.WorkspaceList); + queryClient.setQueryData(keys.projects, { + projects: [{ id: "prj_shop", slug: "shop", name: "Shop" }], + } as unknown as G.ProjectList); + const lead = async (scope?: string) => { + search.value = { scope }; + const page = await render(); + return page.querySelector("header p")?.textContent ?? ""; + }; + expect(await lead()).toContain("What agents opened in your projects,"); + expect(await lead("w:romanesco")).toContain("What agents opened in Romanesco's projects,"); + expect(await lead("p:shop")).toContain("What agents opened in Shop,"); + }); + + it("says so when the list doesn't load", async () => { + answer = failure; + const page = await render(); + await act(() => vi.waitFor(() => expect(page.textContent).toContain("didn't load"))); + expect(page.textContent).toContain("The pull requests didn't load: The database is busy"); + expect(page.textContent).toContain("Try again"); + }); + + it("keeps what loaded when a refresh fails, and says it may be behind", async () => { + answer = listing; + const page = await render(); + await act(() => vi.waitFor(() => expect(page.textContent).toContain("Danish for the shop"))); + + answer = failure; + await act(() => queryClient.refetchQueries({ queryKey: ["sessions"] })); + await act(() => vi.waitFor(() => expect(page.textContent).toContain("didn't refresh"))); + expect(page.textContent).toContain("This list didn't refresh: The database is busy"); + expect(page.textContent).toContain("Danish for the shop"); + expect(page.textContent).not.toContain("didn't load"); + + // Once a refresh works again, the note goes. + answer = listing; + const again = [...page.querySelectorAll("button")].find((b) => b.textContent === "Try again"); + await act(async () => again?.click()); + await act(() => vi.waitFor(() => expect(page.textContent).not.toContain("didn't refresh"))); + expect(page.textContent).toContain("Danish for the shop"); + }); +}); diff --git a/web/src/routes/pulls.tsx b/web/src/routes/pulls.tsx new file mode 100644 index 00000000..e0d11a76 --- /dev/null +++ b/web/src/routes/pulls.tsx @@ -0,0 +1,498 @@ +// Pull requests: what agents opened in your projects, each once, sorted by what it needs next: +// review, a fix for its checks, its agent to finish, its turn in a merge queue. The sessions +// that list them come from the sessions API (`?pulls=any`), which the feed keeps current, so +// states, checks and reviews change here as GitHub tells the control plane. +// +// The keyboard: j and k (or the arrows) move through the list, Enter opens the session, o opens +// the pull request on GitHub, and / filters. + +import { useQuery } from "@tanstack/react-query"; +import { Link, useNavigate, useSearch } from "@tanstack/react-router"; +import { ArrowUpRight, CircleAlert, FolderGit2, Layers, Search, X } from "lucide-react"; +import { type ReactNode, useMemo, useRef } from "react"; +import { + PullRequestChecksIcon, + PullRequestReviewMark, + PullRequestStateIcon, +} from "@/components/session/pull-request"; +import { + Avatar, + Banner, + Button, + Empty, + Kbd, + PullRequestIcon, + Select, + type SelectOption, + Skeleton, + StatusDot, +} from "@/components/ui"; +import { WorkspaceAvatar } from "@/components/workspace/avatar"; +import type * as G from "@/gen"; +import { api } from "@/lib/api"; +import { cn } from "@/lib/cn"; +import { agoShort, stamp } from "@/lib/format"; +import { useHotkey } from "@/lib/hotkeys"; +import { + countStates, + type ListedPull, + listPulls, + moved, + NEEDS, + type Need, + needOf, + PULL_STATES, + type PullState, + pullMatches, + stateOf, +} from "@/lib/pull-list"; +import { checksText, prFullRef, prLabel, prReview, prReviewText } from "@/lib/pulls"; +import { keys, useProjects, useWorkspaces } from "@/lib/queries"; + +/** What the page's address says it shows. */ +export interface PullsSearch { + state?: PullState; + /** `w:` for a workspace's, `p:` for a project's; none for all. */ + scope?: string; + mine?: boolean; + q?: string; +} + +/** Sessions the page looks through, newest first. */ +const LOOK_AT = 200; + +const TITLES: Record = { open: "Open", merged: "Merged", closed: "Closed" }; + +export function PullsPage() { + const search = useSearch({ from: "/app/pulls" }); + const navigate = useNavigate({ from: "/pulls" }); + const workspaces = useWorkspaces().data?.workspaces ?? []; + const projects = useProjects().data?.projects ?? []; + const state = search.state ?? "open"; + const [kind, slug] = (search.scope ?? "").split(":"); + const scope = { workspace: kind === "w" ? slug : undefined, project: kind === "p" ? slug : undefined }; + // Every session that lists one, whatever its state: each pull request takes the state the session + // that heard of it last says, which one that heard of it earlier may not. + const q = { pulls: "any" as const, limit: LOOK_AT, ...scope, mine: search.mine }; + const sessions = useQuery({ queryKey: keys.sessions(q), queryFn: () => api.sessions(q) }); + const all = useMemo(() => listPulls(sessions.data?.sessions ?? []), [sessions.data]); + const counts = useMemo(() => countStates(all), [all]); + const shown = useMemo( + () => all.filter((l) => stateOf(l) === state && pullMatches(l, search.q ?? "")), + [all, state, search.q], + ); + const set = (next: Partial) => + void navigate({ search: (s: PullsSearch) => ({ ...s, ...next }), replace: true }); + const filter = useRef(null); + const list = useRef(null); + useHotkey("/", () => filter.current?.focus()); + const onListKey = useListKeys(list); + + return ( +
+
+

+ Pull requests +

+

+ What agents opened in {scopeName(search.scope, workspaces, projects)}, sorted by what each needs + next. Their states and checks change here as GitHub reports them. +

+
+ +
+ +
+ + set({ scope })} /> + +
+
+ + {/* biome-ignore lint/a11y/noStaticElementInteractions: the arrows move between the rows' links. */} +
+ {sessions.isError && sessions.data && ( + // A refresh that failed keeps what loaded on screen, and says it may be behind. +

+ + This list didn't refresh: {sessions.error.message} + +

+ )} + {sessions.isError && !sessions.data ? ( + + + The pull requests didn't load: {sessions.error.message} + + + + ) : sessions.isPending ? ( +
+ {[0, 1, 2].map((i) => ( + + ))} +
+ ) : shown.length === 0 ? ( + + ) : state === "open" ? ( + NEEDS.map(({ need, title, hint }) => { + const these = shown.filter((l) => needOf(l) === need); + return these.length ? ( +
+ {these.map((l) => ( + + ))} +
+ ) : null; + }) + ) : ( + byWhen(shown).map(([title, these]) => ( +
+ {these.map((l) => ( + + ))} +
+ )) + )} + {sessions.data?.next_before && ( +

+ From the newest {LOOK_AT} sessions with pull requests. Narrow it to a project for older ones. +

+ )} +
+

+ j k move · ↵ opens the session · o opens it on GitHub ·{" "} + / filters +

+
+ ); +} + +/** What the page lists, by name: "your projects", "Romanesco's projects", "Shop". */ +function scopeName( + scope: string | undefined, + workspaces: readonly G.Workspace[], + projects: readonly G.Project[], +): string { + if (!scope) return "your projects"; + const [kind, slug = ""] = scope.split(":"); + if (kind === "w") return `${workspaces.find((w) => w.slug === slug)?.name ?? slug}'s projects`; + return projects.find((p) => p.slug === slug)?.name ?? slug; +} + +/** Which workspace or project the page shows: one list, its workspaces' projects under each. */ +function ScopeSelect({ value, onChange }: { value?: string; onChange: (v: string | undefined) => void }) { + const workspaces = useWorkspaces().data?.workspaces ?? []; + const projects = useProjects().data?.projects ?? []; + const options: SelectOption[] = [ + { value: "all", label: "All projects", icon: }, + ...workspaces.flatMap((w) => [ + { + value: `w:${w.slug}`, + label: w.name, + item: `All of ${w.name}`, + icon: , + section: { key: w.id, label: w.name }, + }, + ...projects + .filter((p) => p.workspace?.id === w.id) + .map((p) => ({ + value: `p:${p.slug}`, + label: `${w.name} / ${p.name}`, + item: p.name, + short: p.name, + icon: , + section: { key: w.id, label: w.name }, + })), + ]), + ]; + return ( +