From 72c77efbb866e097b405a9d6a25b9c75a789bfa2 Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" Date: Sat, 7 Nov 2026 01:14:26 +0000 Subject: [PATCH 1/8] feat: a page of pull requests, sorted by what each needs next MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit /pulls lists the pull requests agents opened or worked on, each once with the sessions that list it, as the session that heard of it last has it. Open ones come sorted by what they need: ready for review (their agents finished and nothing failed), checks failing, agents at work, in a merge queue, drafts; merged and closed ones by when. Tabs count each state, a filter finds them by title, repository, number or session, a picker narrows them to a workspace or a project, and Mine to your sessions'. j/k move through them, Enter opens the session, o the pull request on GitHub, / filters. The feed keeps it current. GET /api/v1/sessions takes ?pulls=open|merged|closed|any for it, and fctl pulls lists the same in a terminal (fctl_domain::pulls::listed). Pull requests is in ⌘K too. --- crates/fctl-client/src/api.rs | 24 + crates/fctl-control/src/api/sessions.rs | 18 + crates/fctl-domain/src/pulls.rs | 127 +++++ crates/fctl/src/cmd/mod.rs | 1 + crates/fctl/src/cmd/pulls.rs | 147 ++++++ crates/fctl/src/cmd/sessions.rs | 2 +- crates/fctl/src/main.rs | 8 + docs/api.md | 5 +- docs/architecture.md | 11 + docs/cli.md | 2 + docs/llms.txt | 2 +- .../components/shell/command-palette.test.tsx | 14 +- web/src/components/shell/command-palette.tsx | 11 +- web/src/lib/api.ts | 3 + web/src/lib/pull-list.test.ts | 82 ++++ web/src/lib/pull-list.ts | 87 ++++ web/src/router.tsx | 25 +- web/src/routes/pulls.tsx | 451 ++++++++++++++++++ 18 files changed, 1014 insertions(+), 6 deletions(-) create mode 100644 crates/fctl/src/cmd/pulls.rs create mode 100644 web/src/lib/pull-list.test.ts create mode 100644 web/src/lib/pull-list.ts create mode 100644 web/src/routes/pulls.tsx 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..3af4ebff 100644 --- a/crates/fctl-control/src/api/sessions.rs +++ b/crates/fctl-control/src/api/sessions.rs @@ -356,6 +356,24 @@ 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: what GitHub last said of each, as + // `crate::pull_requests` keeps it. One nobody looked up yet counts as + // open. + if let Some(pulls) = http::query(req, "pulls") { + let states = match pulls.as_str() { + "any" | "1" | "true" => "", + "open" => " WHERE state IS NULL OR state IN ('open','draft','queued')", + "merged" => " WHERE state = 'merged'", + "closed" => " WHERE state = 'closed'", + _ => { + return Err(validation("pulls", "Use open, merged, closed or any")); + } + }; + sql.push_str(&format!( + " AND s.id IN (SELECT session_id FROM pull_request_sessions{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..661dbccf 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,74 @@ pub fn backfill(s: &mut Session) { } } +/// 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() + }; + for pr in prs { + 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 +1042,62 @@ 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); + } } diff --git a/crates/fctl/src/cmd/mod.rs b/crates/fctl/src/cmd/mod.rs index 0d9f64a2..e516329a 100644 --- a/crates/fctl/src/cmd/mod.rs +++ b/crates/fctl/src/cmd/mod.rs @@ -13,6 +13,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..329e4573 --- /dev/null +++ b/crates/fctl/src/cmd/pulls.rs @@ -0,0 +1,147 @@ +//! `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, + }; + let (pulls, states) = args.state.query(); + let list = api + .sessions_with_pulls( + args.workspace.as_deref(), + project.as_deref(), + pulls, + args.mine, + args.limit, + ) + .await?; + let found = listed(&list.sessions, states); + if json { + return style::print_json(&serde_json::json!({ "pull_requests": found })); + } + 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 f0655b52..c9e136b9 100644 --- a/crates/fctl/src/cmd/sessions.rs +++ b/crates/fctl/src/cmd/sessions.rs @@ -446,7 +446,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 cc48986c..54784bd9 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. @@ -454,6 +461,7 @@ async fn run(cli: Cli) -> anyhow::Result<()> { Command::Show { session } => cmd::sessions::show(server, &session, json).await, Command::Edit(args) => cmd::sessions::edit(server, args, json).await, Command::Publish(args) => cmd::publish::publish(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 05db6b41..31cab91f 100644 --- a/docs/api.md +++ b/docs/api.md @@ -111,7 +111,10 @@ 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, as GitHub last said; one nobody looked + up counts as open: the app's pull requests page and `fctl pulls` group + their `pull_requests`), `?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 a79e2b2d..78ec652e 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1392,6 +1392,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 e790de7c..4fe34aef 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 a54757c0..b31a3b68 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`, and its name, description and default branch with `--name "Web app" --description "The storefront" --default-branch develop`. 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 63991caf..a1ddfa20 100644 --- a/web/src/components/shell/command-palette.tsx +++ b/web/src/components/shell/command-palette.tsx @@ -16,7 +16,7 @@ import { } from "lucide-react"; import { type ReactNode, useEffect, useMemo, useRef, useState } from "react"; import { createPortal } from "react-dom"; -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"; @@ -117,6 +117,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/pull-list.test.ts b/web/src/lib/pull-list.test.ts new file mode 100644 index 00000000..ef8a0ec4 --- /dev/null +++ b/web/src/lib/pull-list.test.ts @@ -0,0 +1,82 @@ +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); + 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..a8c99d63 --- /dev/null +++ b/web/src/lib/pull-list.ts @@ -0,0 +1,87 @@ +// 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, 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, repository, number or sessions. */ +export function pullMatches(l: ListedPull, query: string): boolean { + const words = query.toLowerCase().split(/\s+/).filter(Boolean); + if (!words.length) return true; + const repo = l.pr.repo ? `${l.pr.repo.owner}/${l.pr.repo.name}` : l.pr.url; + const text = [ + l.pr.title ?? "", + repo, + `#${l.pr.number}`, + ...l.sessions.flatMap((s) => [s.title, `${s.project_slug}#${s.number}`, s.created_by.name]), + ] + .join(" ") + .toLowerCase(); + return words.every((w) => text.includes(w.replace(/^#/, "#"))); +} 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.tsx b/web/src/routes/pulls.tsx new file mode 100644 index 00000000..53636683 --- /dev/null +++ b/web/src/routes/pulls.tsx @@ -0,0 +1,451 @@ +// 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, 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, + Empty, + Kbd, + PullRequestIcon, + Select, + type SelectOption, + Skeleton, + StatusDot, +} from "@/components/ui"; +import { WorkspaceAvatar } from "@/components/workspace/avatar"; +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 state = search.state ?? "open"; + const [kind, slug] = (search.scope ?? "").split(":"); + const scope = { workspace: kind === "w" ? slug : undefined, project: kind === "p" ? slug : undefined }; + 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)}, and what each needs next. It changes here as GitHub + says. +

+
+ +
+ +
+ + set({ scope })} /> + +
+
+ + {/* biome-ignore lint/a11y/noStaticElementInteractions: the arrows move between the rows' links. */} +
+ {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 +

+
+ ); +} + +/** "your projects", or the workspace's or project's name as the scope says. */ +function scopeName(scope: string | undefined): string { + if (!scope) return "your projects"; + const [kind, slug] = scope.split(":"); + return kind === "w" ? `${slug}'s projects` : `${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 ( +