Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

feat(swarm): read linked pull request status with the local GitHub account

tony893aadafba03
diff --git a/cli/e2e/services.e2e.ts b/cli/e2e/services.e2e.ts
index 457447eb7..216bb80ad 100644
--- a/cli/e2e/services.e2e.ts
+++ b/cli/e2e/services.e2e.ts
@@ -64,6 +64,31 @@ describe('a failing service never takes the core down', () => {
let daemon: IsolatedDaemon | undefined
afterEach(async () => { await daemon?.close(); daemon = undefined })
+ it('reads linked PR URLs without an agent and keeps one inaccessible PR apart', async () => {
+ daemon = await IsolatedDaemon.create({ env: { VITEST: '' } })
+ // The fake binary is in this fixture's private PATH and home. No developer login or GitHub network is used.
+ writeFileSync(join(daemon.root, 'bin', 'gh'), `#!/bin/sh
+case "$3" in
+ */2) echo 'HTTP 404: Not Found' >&2; exit 1 ;;
+esac
+printf '%s' '{"title":"A merged pull request","state":"MERGED","mergedAt":"2026-10-22T06:00:00Z","additions":32,"deletions":6,"statusCheckRollup":[{"conclusion":"SUCCESS"}]}'
+`, { mode: 0o755 })
+ await daemon.start()
+ const client = await LocalClient.connect(daemon)
+ const urls = ['https://github.com/o/r/pull/1', 'https://github.com/o/r/pull/2']
+ const answer = await until('the projects service to be ready', async () => {
+ const result = await client.request('git_pull_requests_status', { urls })
+ return result.error === 'SERVICE_UNAVAILABLE' && result.retryable ? null : result
+ }, 15_000, 100)
+ expect(answer).toMatchObject({ rows: [
+ { url: urls[0], status: 'found', title: 'A merged pull request', state: 'Merged', checks: { passed: 1, total: 1 } },
+ { url: urls[1], status: 'no_access' },
+ ] })
+ expect(await client.request('git_pull_requests_status', { urls: ['https://example.com/pull/1'] })).toMatchObject({ error: 'INVALID_URLS' })
+ expect(daemon.coresStarted()).toBe(1)
+ client.close()
+ })
+
it('with every service failing to start, in its own process or in the core, the core starts, runs an agent through turns and a restart, and says each one is unavailable', async () => {
daemon = await IsolatedDaemon.create({ env: { HARNESSD_TEST_FAULTS: EVERY_PROCESS_FAILING, ...QUICK_TO_PARK } })
const d = daemon
@@ -176,7 +201,7 @@ describe('a failing service never takes the core down', () => {
expect(await client.request('usage_read', {})).toMatchObject({ error: 'SERVICE_UNAVAILABLE', service: 'usage', retryable: false })
expect(await client.request('machine_resources', {})).toMatchObject({ error: 'SERVICE_UNAVAILABLE', service: 'monitor', retryable: false })
expect(await client.request('shell_capabilities', {})).toMatchObject({ error: 'SERVICE_UNAVAILABLE', service: 'shell', retryable: false })
- for (const type of ['git_pull_request', 'git_project_info', 'project_preview', 'fs_list_dir', 'agent_read_file']) {
+ for (const type of ['git_pull_request', 'git_pull_requests_status', 'git_project_info', 'project_preview', 'fs_list_dir', 'agent_read_file']) {
expect(await client.request(type, { agentId, path: daemon.projectsDir }), type).toMatchObject({ error: 'SERVICE_UNAVAILABLE', service: 'projects', retryable: false })
}
// A window's name off: the apps keep the names they have.
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index 8f95ab9de..cca40c9c9 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -866,7 +866,7 @@ export class BackendSocket {
private emitReply(connId: string, type: string, requestId: unknown, payload: Record<string, unknown>): void {
const resultType = rpcResultType(type)
// Before the E2EE wrap: an RPC reply is only readable here.
- if (env.LOG_FRAMES && !MESSAGE_REQUESTS.has(type) && !ROUTE_COMMAND_TYPES.has(type) && !type.startsWith('viewer_') && type !== 'phone_pair' && type !== 'api_connections' && type !== 'connectors' && type !== 'os_device' && type !== 'browser_open' && type !== 'browser_callback' && type !== 'orchestrator' && !type.startsWith('grid_fleet_') && type !== 'agent_read_file' && type !== 'project_preview' && type !== 'git_project_info' && type !== 'scm_project_info' && type !== 'git_pull_request' && type !== 'agent_handoff_prepare' && !SHARE_REQUEST_TYPES.has(type) && !type.startsWith('pair')) logFrame('→', connId ? `conn:${sid(connId)}` : 'backend', { type: resultType, payload: { requestId, ...payload } })
+ if (env.LOG_FRAMES && !MESSAGE_REQUESTS.has(type) && !ROUTE_COMMAND_TYPES.has(type) && !type.startsWith('viewer_') && type !== 'phone_pair' && type !== 'api_connections' && type !== 'connectors' && type !== 'os_device' && type !== 'browser_open' && type !== 'browser_callback' && type !== 'orchestrator' && !type.startsWith('grid_fleet_') && type !== 'agent_read_file' && type !== 'project_preview' && type !== 'git_project_info' && type !== 'scm_project_info' && type !== 'git_pull_request' && type !== 'git_pull_requests_status' && type !== 'agent_handoff_prepare' && !SHARE_REQUEST_TYPES.has(type) && !type.startsWith('pair')) logFrame('→', connId ? `conn:${sid(connId)}` : 'backend', { type: resultType, payload: { requestId, ...payload } })
if (this.localClients.has(connId)) {
this.sendTo(connId, { type: resultType, payload: { requestId, ...payload } })
return
@@ -927,7 +927,7 @@ export class BackendSocket {
// actually asked for rather than as an opaque __e2e envelope.
// Terminal frames contain raw keystrokes, paste text and screen bytes after
// unwrap. Never pass them to the frame logger, even in diagnostic mode.
- if (env.LOG_FRAMES && !MESSAGE_REQUESTS.has(type) && !ROUTE_COMMAND_TYPES.has(type) && !type.startsWith('terminal_') && !type.startsWith('viewer_') && !type.startsWith('grid_fleet_') && type !== 'agent_read_file' && type !== 'project_preview' && type !== 'git_project_info' && type !== 'scm_project_info' && type !== 'git_pull_request' && type !== 'agent_handoff_prepare' && type !== 'orchestrator' && type !== 'api_connections' && type !== 'connectors' && type !== 'os_device' && type !== 'browser_open' && type !== 'browser_callback' && type !== 'phone_pair' && !SHARE_REQUEST_TYPES.has(type) && !type.startsWith('pair')) {
+ if (env.LOG_FRAMES && !MESSAGE_REQUESTS.has(type) && !ROUTE_COMMAND_TYPES.has(type) && !type.startsWith('terminal_') && !type.startsWith('viewer_') && !type.startsWith('grid_fleet_') && type !== 'agent_read_file' && type !== 'project_preview' && type !== 'git_project_info' && type !== 'scm_project_info' && type !== 'git_pull_request' && type !== 'git_pull_requests_status' && type !== 'agent_handoff_prepare' && type !== 'orchestrator' && type !== 'api_connections' && type !== 'connectors' && type !== 'os_device' && type !== 'browser_open' && type !== 'browser_callback' && type !== 'phone_pair' && !SHARE_REQUEST_TYPES.has(type) && !type.startsWith('pair')) {
logFrame('←', connId ? `conn:${sid(connId)}` : 'backend', frame)
}
const launchMeasured = productUsageLaunch(type, (frame.payload as { creationId?: unknown } | undefined)?.creationId,
diff --git a/cli/src/core/api.spec.ts b/cli/src/core/api.spec.ts
index 1d6a99efd..01dab4508 100644
--- a/cli/src/core/api.spec.ts
+++ b/cli/src/core/api.spec.ts
@@ -6,6 +6,9 @@ import { FAIL, readFallback } from './serviceHost.js'
const row = (agentId: string) => ({ agentId, sessionId: `s-${agentId}`, engine: 'claude', cwd: '/work/app' }) as RegisteredSession
describe('the core API services stand on', () => {
+ it('allows a bounded batch of GitHub reads to finish outside the core', () => {
+ expect(LONG_ANSWERS.projects).toEqual({ git_pull_requests_status: 120_000 })
+ })
it('closes only the original Swarm-started native session and treats an absent session as gone', async () => {
const request = { agentId: 'worker', creationId: 'super-original-creation', sessionId: 'native', expiresAt: Date.now() + 120_000, createdAt: new Date(1000).toISOString() }
const session = { ...row('worker'), sessionId: 'native', registeredAt: 1000, startedBy: 'agent' as const }
diff --git a/cli/src/core/api.ts b/cli/src/core/api.ts
index cb1b01db1..c453be3e7 100644
--- a/cli/src/core/api.ts
+++ b/cli/src/core/api.ts
@@ -650,7 +650,7 @@ export const SUPER_TAB_REQUESTS = ['super_tabs'] as const
export interface SuperTabsPort { connected(): void; disconnected(): void; stop(): void }
export const SUPER_TAB_FALLBACKS: PortFallbacks<SuperTabsPort> = { connected: undefined, disconnected: undefined, stop: undefined }
/** The project and folder readers (services/projects.ts). */
-export const PROJECTS_REQUESTS = ['git_pull_request', 'git_project_info', 'scm_project_info', 'project_preview', 'fs_list_dir', 'agent_read_file'] as const
+export const PROJECTS_REQUESTS = ['git_pull_request', 'git_pull_requests_status', 'git_project_info', 'scm_project_info', 'project_preview', 'fs_list_dir', 'agent_read_file'] as const
/** A window's name for its repo and its work, by a small model in the background (services/windowNames.ts). */
export const WINDOW_NAMES_REQUESTS = ['window_name'] as const
/** Change agent's handoff file, prepared in the edge host (services/handoff.ts). */
@@ -732,6 +732,8 @@ const MINUTE = 60_000
* how long a launch on one can wait. A launch on the engine's own login asks models nothing.
*/
export const LONG_ANSWERS: Readonly<Record<string, Readonly<Record<string, number>>>> = {
+ // Fifty GitHub reads, four at a time, each with an eight-second subprocess deadline.
+ projects: { git_pull_requests_status: 120_000 },
models: {
grid_fleet_run: GRID_FLEET_MAX_TIMEOUT_MS + MINUTE,
grid_fleet_models_list: 15 * MINUTE, grid_fleet_model_download: 15 * MINUTE, grid_fleet_model_start: 15 * MINUTE,
diff --git a/cli/src/lib/cleanText.ts b/cli/src/lib/cleanText.ts
new file mode 100644
index 000000000..68834c791
--- /dev/null
+++ b/cli/src/lib/cleanText.ts
@@ -0,0 +1,4 @@
+/** Untrusted display text: remove controls and format characters (including bidi overrides), then bound its size. */
+export function cleanText(value: unknown, max: number): string {
+ return typeof value === 'string' ? value.replace(/[\p{Cc}\p{Cf}]/gu, '').slice(0, max) : ''
+}
diff --git a/cli/src/lib/e2ee/applicationFrames.ts b/cli/src/lib/e2ee/applicationFrames.ts
index e9004ed0f..26790b255 100644
--- a/cli/src/lib/e2ee/applicationFrames.ts
+++ b/cli/src/lib/e2ee/applicationFrames.ts
@@ -23,7 +23,7 @@ const FLEET_REQUESTS = new Set(['grid_fleet_capabilities', 'grid_fleet_run', 'gr
'grid_fleet_models_list', 'grid_fleet_model_download', 'grid_fleet_model_start', 'grid_fleet_model_stop'])
const FLEET_RESULTS = new Set([...FLEET_REQUESTS].map(type => `${type}_result`))
// `group_sync`: the trust-group roster exchange (groupSyncer.ts) — keys, so always sealed.
-const MACHINE_REQUESTS = new Set([...SHELL_REQUESTS, 'agent_purge', 'agent_worktree_delete', 'agents_cleanup_preview', 'agent_close', 'git_project_info', 'scm_project_info', 'git_pull_request', 'machine_resources', 'api_connections', 'connectors', 'group_sync', 'phone_pair', 'viewer_surface', 'orchestrator', 'agent_handoff_prepare',
+const MACHINE_REQUESTS = new Set([...SHELL_REQUESTS, 'agent_purge', 'agent_worktree_delete', 'agents_cleanup_preview', 'agent_close', 'git_project_info', 'scm_project_info', 'git_pull_request', 'git_pull_requests_status', 'machine_resources', 'api_connections', 'connectors', 'group_sync', 'phone_pair', 'viewer_surface', 'orchestrator', 'agent_handoff_prepare',
// A held launch's cancellation and its receipt contain the client's private request identity.
'agent_create_cancel',
// Memories (services/memory.ts): what this machine's agents remember, and About You and its on/off choice.
diff --git a/cli/src/lib/github.ts b/cli/src/lib/github.ts
new file mode 100644
index 000000000..6eb441bb4
--- /dev/null
+++ b/cli/src/lib/github.ts
@@ -0,0 +1,101 @@
+/** GitHub CLI reads shared by Tasks and the Swarm pull requests pane. No prompts; every subprocess is bounded. */
+import { execFile } from 'node:child_process'
+import { homedir } from 'node:os'
+import { delimiter, join } from 'node:path'
+import { promisify } from 'node:util'
+import { resolveBinaryOnPath } from './binaryOnPath.js'
+import { warmLoginShellEnvironment } from './loginShellEnv.js'
+import { MessageError } from '../messages/model.js'
+import { cleanText } from './cleanText.js'
+export type CiState = 'passing' | 'failing' | 'pending' | 'none'
+export type Run = (args: string[]) => Promise<{ stdout: string }>
+
+/** GitHub's `mergeStateStatus` words; anything else (a new one, a missing field) is `UNKNOWN` rather than shown as is. */
+export const MERGE_STATES = ['BEHIND', 'BLOCKED', 'CLEAN', 'DIRTY', 'DRAFT', 'HAS_HOOKS', 'UNSTABLE']
+
+const exec = promisify(execFile)
+
+/** Where gh is installed when the daemon's PATH does not have it: Homebrew on Apple silicon and on Intel, Linuxbrew, and
+ * a user install. */
+export const GH_DIRS: readonly string[] = ['/opt/homebrew/bin', '/usr/local/bin', '/home/linuxbrew/.linuxbrew/bin', join(homedir(), '.local', 'bin')]
+
+/**
+ * gh's full path, or null. The daemon is started by launchd or the app, not a shell, so its PATH is the bare system one:
+ * a Mac with gh from Homebrew was told "Install the GitHub CLI (gh) on this computer" beside a working `gh` in every
+ * terminal (2026-10-17), as tmux once was (lib/tmuxOnPath.ts). So: the daemon's PATH, then the usual install folders,
+ * then the PATH the person's own login shell gives, which is spawned only when the first two have no gh.
+ */
+export async function findGh(env: NodeJS.ProcessEnv = process.env, dirs: readonly string[] = GH_DIRS,
+ shellPath: () => Promise<string | undefined> = async () => (await warmLoginShellEnvironment()).PATH): Promise<string | null> {
+ return resolveBinaryOnPath('gh', env) ?? resolveBinaryOnPath('gh', { PATH: dirs.join(delimiter) })
+ ?? resolveBinaryOnPath('gh', { PATH: (await shellPath()) ?? '' })
+}
+
+// Found once and kept; a gh still missing is looked for again at the next read, so installing it needs no restart.
+let ghPath: string | null = null
+
+/** `gh` with no prompt and no wait for one: a terminal login question would hang the run until its timeout. */
+export const ghRun: Run = async (args) => {
+ // Refused under a test runner, whatever the caller: a real `gh` would read the developer's own GitHub login and search
+ // public GitHub with it. Tests inject a `Run`; production never has VITEST set.
+ if (process.env.VITEST) throw Object.assign(new Error('The real gh is not run in tests.'), { stderr: 'The real gh is not run in tests.' })
+ ghPath ??= await findGh()
+ if (!ghPath) throw Object.assign(new Error('gh was not found'), { code: 'ENOENT', stderr: '' })
+ return { stdout: (await exec(ghPath, args, { timeout: 8000, killSignal: 'SIGKILL', maxBuffer: 1024 * 1024,
+ env: { ...process.env, GH_PROMPT_DISABLED: '1', GIT_TERMINAL_PROMPT: '0' } })).stdout }
+}
+
+/** Test seam: forget the gh that was found. */
+export function resetGhPath(): void { ghPath = null }
+
+/** What a failed run means to the person, as a `MessageError`; the stderr shown is `gh`'s own, cleaned and cut. */
+export function ghError(error: unknown): MessageError {
+ const e = (error ?? {}) as { code?: unknown; killed?: unknown; signal?: unknown; stderr?: unknown }
+ const stderr = typeof e.stderr === 'string' ? e.stderr : ''
+ if (e.code === 'ENOENT') return new MessageError('GH_MISSING', 'The GitHub CLI (gh) is not installed on this computer.')
+ if (/gh auth login|not logged in|authentication/i.test(stderr)) return new MessageError('GH_SIGNED_OUT', 'gh is not signed in on this computer: run `gh auth login`.')
+ if (/rate limit|secondary rate|HTTP 403|HTTP 429/i.test(stderr)) return new MessageError('RATE_LIMITED', 'GitHub is limiting this computer\'s requests. Try again in a minute.')
+ // A search too large for the buffer kills the child too, but it is not a slow GitHub: asking again would fail the same way.
+ if (e.code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER') return new MessageError('GH_FAILED', 'GitHub returned too many or too large results.')
+ if (e.killed === true || e.signal === 'SIGKILL') return new MessageError('TIMEOUT', 'GitHub did not answer in time.')
+ return new MessageError('GH_FAILED', cleanText(stderr, 200) || 'gh failed.')
+}
+
+const failedCheck = (word: string): boolean => ['FAILURE', 'ERROR', 'TIMED_OUT', 'CANCELLED', 'STARTUP_FAILURE', 'ACTION_REQUIRED'].includes(word)
+const checkWord = (check: Record<string, unknown>): string => String(check.conclusion || check.state || '').toUpperCase()
+export interface CiCounts { passed: number; failed: number; pending: number; total: number }
+/** Skipped and neutral runs are not checks a person must wait for. Commit statuses have state rather than conclusion. */
+export function ciCounts(rollup: unknown): CiCounts {
+ const counts = { passed: 0, failed: 0, pending: 0, total: 0 }
+ for (const check of Array.isArray(rollup) ? rollup : []) {
+ if (!check || typeof check !== 'object') continue
+ const word = checkWord(check)
+ if (['SKIPPED', 'NEUTRAL'].includes(word)) continue
+ counts.total++
+ if (word === 'SUCCESS') counts.passed++
+ else if (failedCheck(word)) counts.failed++
+ else counts.pending++
+ }
+ return counts
+}
+
+/** One pull request's CI from its checks: a check run has `status` and `conclusion`, a commit status has `state`. */
+export function ciOf(rollup: unknown): CiState {
+ const checks = Array.isArray(rollup) ? rollup.filter((c): c is Record<string, unknown> => !!c && typeof c === 'object') : []
+ if (!checks.length) return 'none'
+ const word = (v: unknown): string => String(v ?? '').toUpperCase()
+ const failing = (c: Record<string, unknown>): boolean => failedCheck(checkWord(c))
+ // A check that says nothing we know is not yet a pass.
+ const settled = (c: Record<string, unknown>): boolean => !!c.conclusion || word(c.status) === 'COMPLETED' || ['SUCCESS', 'FAILURE', 'ERROR'].includes(word(c.state))
+ const pending = (c: Record<string, unknown>): boolean => !settled(c)
+ return checks.some(failing) ? 'failing' : checks.some(pending) ? 'pending' : 'passing'
+}
+
+/** Run `work` over `items`, at most `limit` at once. */
+export async function pooled<T>(items: T[], limit: number, work: (item: T) => Promise<void>): Promise<void> {
+ const queue = [...items]
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, async () => {
+ for (let item = queue.shift(); item !== undefined; item = queue.shift()) await work(item)
+ }))
+}
+
diff --git a/cli/src/lib/pullRequestsStatus.spec.ts b/cli/src/lib/pullRequestsStatus.spec.ts
new file mode 100644
index 000000000..e4909274e
--- /dev/null
+++ b/cli/src/lib/pullRequestsStatus.spec.ts
@@ -0,0 +1,136 @@
+import { describe, expect, it, vi } from 'vitest'
+import { ciCounts, type Run } from './github.js'
+import { createPullRequestsStatusReader, PULL_REQUESTS_FRESH_MS, PULL_REQUESTS_MAX } from './pullRequestsStatus.js'
+
+const url = (n = 1) => `https://github.com/o/r/pull/${n}`
+const view = (over = {}) => ({ title: 'Fix reconnect', state: 'OPEN', isDraft: false, mergedAt: null, closedAt: null,
+ updatedAt: '2026-10-22T07:00:00Z', additions: 32, deletions: 6, reviewDecision: 'APPROVED', mergeStateStatus: 'CLEAN',
+ autoMergeRequest: null, statusCheckRollup: [{ status: 'COMPLETED', conclusion: 'SUCCESS' }], ...over })
+const runner = (over = {}) => vi.fn<Run>(async () => ({ stdout: JSON.stringify(view(over)) }))
+
+describe('linked pull requests read directly from GitHub', () => {
+ it('reads by URL and retains title, change counts, times and merge/review inputs', async () => {
+ const run = runner(), read = createPullRequestsStatusReader(run, () => 0)
+ expect(await read([url()])).toEqual({ checkedAt: '1970-01-01T00:00:00.000Z', rows: [{
+ url: url(), status: 'found', title: 'Fix reconnect', state: 'Open', mergedAt: '', closedAt: '',
+ updatedAt: '2026-10-22T07:00:00Z', additions: 32, deletions: 6, ci: 'passing',
+ checks: { passed: 1, failed: 0, pending: 0, total: 1 }, reviewDecision: 'APPROVED', mergeStateStatus: 'CLEAN', autoMerge: false,
+ }] })
+ expect(run).toHaveBeenCalledWith(['pr', 'view', url(), '--json',
+ 'title,state,isDraft,mergedAt,closedAt,updatedAt,additions,deletions,statusCheckRollup,reviewDecision,mergeStateStatus,autoMergeRequest'])
+ })
+
+ it.each([
+ [{ isDraft: true }, 'Draft'], [{}, 'Open'], [{ state: 'MERGED' }, 'Merged'],
+ [{ state: 'CLOSED', mergedAt: '2026-10-22T06:00:00Z' }, 'Merged'], [{ state: 'CLOSED', closedAt: '2026-10-21T06:00:00Z' }, 'Closed'],
+ ])('reports the GitHub state from %o', async (over, state) => {
+ expect((await createPullRequestsStatusReader(runner(over))([url()])).rows[0]).toMatchObject({ state })
+ })
+
+ it.each(['DIRTY', 'BEHIND', 'BLOCKED', 'DRAFT', 'HAS_HOOKS', 'UNSTABLE', 'CLEAN'])('preserves merge state %s', async mergeStateStatus => {
+ const read = createPullRequestsStatusReader(runner({ mergeStateStatus }))
+ expect((await read([url()])).rows[0].mergeStateStatus).toBe(mergeStateStatus)
+ })
+ it.each(['APPROVED', 'CHANGES_REQUESTED', 'REVIEW_REQUIRED'])('preserves review decision %s', async reviewDecision => {
+ expect((await createPullRequestsStatusReader(runner({ reviewDecision }))([url()])).rows[0].reviewDecision).toBe(reviewDecision)
+ })
+ it('preserves auto-merge and sanitizes unexpected values and display text', async () => {
+ const read = createPullRequestsStatusReader(runner({ title: '\u202E' + 'x'.repeat(600), additions: -1, deletions: '2',
+ reviewDecision: 'new', mergeStateStatus: 'new', updatedAt: null, autoMergeRequest: {} }))
+ expect((await read([url()])).rows[0]).toMatchObject({ title: 'x'.repeat(512), additions: 0, deletions: 0,
+ reviewDecision: '', mergeStateStatus: 'UNKNOWN', updatedAt: '', autoMerge: true })
+ })
+
+ it('counts both check runs and commit statuses; skips neutral/skipped and keeps unknown checks pending', () => {
+ expect(ciCounts([null, 1, { conclusion: 'SUCCESS' }, { state: 'SUCCESS' }, { conclusion: 'SKIPPED' }, { conclusion: 'NEUTRAL' },
+ { conclusion: 'FAILURE' }, { state: 'ERROR' }, { conclusion: 'TIMED_OUT' }, { conclusion: 'CANCELLED' },
+ { conclusion: 'STARTUP_FAILURE' }, { conclusion: 'ACTION_REQUIRED' }, { status: 'IN_PROGRESS' }, { status: 'QUEUED' },
+ { status: 'COMPLETED', conclusion: 'FUTURE_VALUE' }])).toEqual({ passed: 2, failed: 6, pending: 3, total: 11 })
+ expect(ciCounts(undefined)).toEqual({ passed: 0, failed: 0, pending: 0, total: 0 })
+ })
+ it.each([
+ [[], 'none', 0], [[{ conclusion: 'FAILURE' }], 'failing', 1], [[{ status: 'IN_PROGRESS' }], 'pending', 1],
+ ])('retains the shared CI summary for %o', async (statusCheckRollup, ci, total) => {
+ expect((await createPullRequestsStatusReader(runner({ statusCheckRollup }))([url()])).rows[0]).toMatchObject({ ci, checks: { total } })
+ })
+
+ it.each([undefined, null, {}, 'url', [url(), 3], ['http://github.com/o/r/pull/1'], ['https://evil.com/o/r/pull/1'],
+ ['https://[email protected]/o/r/pull/1'], ['https://github.com/o/r/pull/1?q=1'], ['https://github.com/o/r/pull/0'],
+ ['https://github.com/o/r/pull/9007199254740992'], ['https://github.com/o/r/pull/1/../2'], Array(PULL_REQUESTS_MAX + 1).fill(url())])(
+ 'refuses malformed or excessive URLs before invoking gh: %o', async urls => {
+ const run = runner()
+ expect(await createPullRequestsStatusReader(run)(urls)).toMatchObject({ error: 'INVALID_URLS', rows: [] })
+ expect(run).not.toHaveBeenCalled()
+ })
+ it('answers an empty list and deduplicates a valid one', async () => {
+ const run = runner(), read = createPullRequestsStatusReader(run)
+ expect((await read([])).rows).toEqual([])
+ expect((await read([url(), url()])).rows).toHaveLength(1)
+ expect(run).toHaveBeenCalledTimes(1)
+ })
+
+ it('one inaccessible repository does not hide readable PRs or become a machine failure', async () => {
+ const run = vi.fn<Run>(async args => {
+ if (args[2] === url(2)) throw { stderr: "GraphQL: Could not resolve to a Repository with the name 'o/private'." }
+ return { stdout: JSON.stringify(view()) }
+ })
+ expect(await createPullRequestsStatusReader(run)([url(), url(2)])).toMatchObject({ rows: [
+ { status: 'found', title: 'Fix reconnect' }, { url: url(2), status: 'no_access' },
+ ] })
+ expect((await createPullRequestsStatusReader(run)([url(2)])).error).toBeUndefined()
+ })
+ it.each([
+ [{ code: 'ENOENT' }, 'GH_MISSING'], [{ stderr: 'To get started run gh auth login' }, 'GH_SIGNED_OUT'],
+ [{ stderr: 'API rate limit exceeded' }, 'RATE_LIMITED'], [{ killed: true }, 'TIMEOUT'], [{ stderr: 'bad gateway' }, 'GH_FAILED'],
+ ])('returns a machine problem once with unavailable rows: %o', async (error, code) => {
+ const run: Run = async () => { throw error }
+ expect(await createPullRequestsStatusReader(run)([url(), url(2)])).toMatchObject({ error: code, rows: [
+ { url: url(), status: 'unavailable', error: code }, { url: url(2), status: 'unavailable', error: code },
+ ] })
+ })
+ it.each(['null', '[]', '{', '{"state":"FUTURE","title":"x"}', '{"state":"OPEN"}'])('treats malformed JSON as a failed read: %s', async stdout => {
+ expect(await createPullRequestsStatusReader(async () => ({ stdout }))([url()])).toMatchObject({ error: 'GH_FAILED', rows: [{ status: 'unavailable' }] })
+ })
+
+ it('one flight per URL across callers, preserving their order', async () => {
+ let release!: (value: { stdout: string }) => void
+ const run = vi.fn<Run>(() => new Promise(resolve => { release = resolve }))
+ const read = createPullRequestsStatusReader(run)
+ const a = read([url()]), b = read([url()])
+ expect(run).toHaveBeenCalledTimes(1)
+ release({ stdout: JSON.stringify(view()) })
+ expect(await a).toEqual(await b)
+ })
+ it('caches final states permanently, open/no-access briefly, and failures for five seconds', async () => {
+ let now = 0
+ const run = vi.fn<Run>(async args => {
+ const n = Number(args[2].split('/').at(-1))
+ if (n === 4) throw { stderr: 'HTTP 404: Not Found' }
+ if (n === 5) throw { killed: true }
+ return { stdout: JSON.stringify(view({ state: n === 1 ? 'MERGED' : n === 2 ? 'CLOSED' : 'OPEN' })) }
+ })
+ const read = createPullRequestsStatusReader(run, () => now), urls = [1, 2, 3, 4, 5].map(url)
+ await read(urls); await read(urls)
+ expect(run).toHaveBeenCalledTimes(5)
+ now = 5_000; await read(urls)
+ expect(run).toHaveBeenCalledTimes(6)
+ now = PULL_REQUESTS_FRESH_MS; await read(urls)
+ expect(run).toHaveBeenCalledTimes(9)
+ now += 365 * 86400_000; await read(urls)
+ expect(run).toHaveBeenCalledTimes(12)
+ })
+ it('caps simultaneous subprocesses across overlapping lists', async () => {
+ let active = 0, peak = 0
+ const run: Run = async () => {
+ peak = Math.max(peak, ++active)
+ await new Promise(resolve => setTimeout(resolve, 1)); active--
+ return { stdout: JSON.stringify(view()) }
+ }
+ const read = createPullRequestsStatusReader(run)
+ const a = Array.from({ length: PULL_REQUESTS_MAX }, (_, i) => url(i + 1))
+ const b = Array.from({ length: PULL_REQUESTS_MAX }, (_, i) => url(i + 51))
+ const result = await Promise.all([read(a), read(b)])
+ expect(peak).toBe(4)
+ expect(result.map(r => r.rows.map(row => row.url))).toEqual([a, b])
+ })
+})
diff --git a/cli/src/lib/pullRequestsStatus.ts b/cli/src/lib/pullRequestsStatus.ts
new file mode 100644
index 000000000..1de0b628f
--- /dev/null
+++ b/cli/src/lib/pullRequestsStatus.ts
@@ -0,0 +1,79 @@
+/** Read linked PRs as this computer's own GitHub account, independent of running agents or checked-out branches. */
+import { ciCounts, ciOf, ghError, ghRun, MERGE_STATES, pooled, type CiCounts, type Run } from './github.js'
+import { validPullRequestUrl } from './sessionWorkWire.js'
+import { cleanText } from './cleanText.js'
+
+export const PULL_REQUESTS_MAX = 50
+export const PULL_REQUESTS_FRESH_MS = 30_000
+const CACHE_MAX = 500
+export interface PullRequestRow {
+ url: string; status: 'found' | 'no_access' | 'unavailable'
+ title?: string; state?: 'Draft' | 'Open' | 'Merged' | 'Closed'
+ mergedAt?: string; closedAt?: string; updatedAt?: string
+ additions?: number; deletions?: number; ci?: ReturnType<typeof ciOf>; checks?: CiCounts
+ reviewDecision?: string; mergeStateStatus?: string; autoMerge?: boolean
+ error?: string
+}
+export interface PullRequestsResult extends Record<string, unknown> { rows: PullRequestRow[]; checkedAt: string; error?: string; detail?: string }
+
+const FIELDS = 'title,state,isDraft,mergedAt,closedAt,updatedAt,additions,deletions,statusCheckRollup,reviewDecision,mergeStateStatus,autoMergeRequest'
+const text = (value: unknown, max = 40): string => cleanText(value, max)
+const lines = (value: unknown): number => Number.isSafeInteger(value) && Number(value) >= 0 ? Number(value) : 0
+
+export function createPullRequestsStatusReader(run: Run = ghRun, now: () => number = Date.now) {
+ const cache = new Map<string, { until: number; value: Promise<PullRequestRow> }>()
+ // Several panes can ask together. Their distinct URLs still share four subprocess slots.
+ let active = 0
+ const waiting: (() => void)[] = []
+ async function fetch(url: string): Promise<PullRequestRow> {
+ if (active >= 4) await new Promise<void>(resolve => waiting.push(resolve))
+ else active++
+ try {
+ const view = JSON.parse((await run(['pr', 'view', url, '--json', FIELDS])).stdout)
+ if (!view || typeof view !== 'object' || !['OPEN', 'CLOSED', 'MERGED'].includes(view.state) || typeof view.title !== 'string') {
+ return { url, status: 'unavailable', error: 'GH_FAILED' }
+ }
+ return { url, status: 'found', title: text(view.title, 512),
+ state: view.mergedAt || view.state === 'MERGED' ? 'Merged' : view.state === 'CLOSED' ? 'Closed' : view.isDraft === true ? 'Draft' : 'Open',
+ mergedAt: text(view.mergedAt), closedAt: text(view.closedAt), updatedAt: text(view.updatedAt),
+ additions: lines(view.additions), deletions: lines(view.deletions), ci: ciOf(view.statusCheckRollup), checks: ciCounts(view.statusCheckRollup),
+ reviewDecision: ['APPROVED', 'CHANGES_REQUESTED', 'REVIEW_REQUIRED'].includes(view.reviewDecision) ? view.reviewDecision : '',
+ mergeStateStatus: MERGE_STATES.includes(view.mergeStateStatus) ? view.mergeStateStatus : 'UNKNOWN',
+ autoMerge: !!view.autoMergeRequest && typeof view.autoMergeRequest === 'object' }
+ } catch (error) {
+ const e = ghError(error)
+ const stderr = String((error as { stderr?: unknown } | null)?.stderr ?? '')
+ if (e.code === 'GH_FAILED' && /could not resolve to a (?:repository|pullrequest)|could not find|not found|HTTP 404|not accessible/i.test(stderr)) {
+ return { url, status: 'no_access' }
+ }
+ return { url, status: 'unavailable', error: e.code }
+ } finally {
+ const next = waiting.shift()
+ if (next) next()
+ else active--
+ }
+ }
+ function read(url: string): Promise<PullRequestRow> {
+ const prior = cache.get(url)
+ if (prior && prior.until > now()) return prior.value
+ const entry = { until: Infinity, value: fetch(url) }
+ cache.set(url, entry)
+ void entry.value.then(row => {
+ entry.until = row.status === 'found' && ['Merged', 'Closed'].includes(row.state!) ? Infinity
+ : now() + (row.status === 'unavailable' ? 5_000 : PULL_REQUESTS_FRESH_MS)
+ // Final answers cost no more network requests, but an unbounded history must not cost unbounded memory.
+ if (cache.size > CACHE_MAX) cache.delete(cache.keys().next().value!)
+ })
+ return entry.value
+ }
+ return async (urls: unknown): Promise<PullRequestsResult> => {
+ if (!Array.isArray(urls) || urls.length > PULL_REQUESTS_MAX || !urls.every(validPullRequestUrl)) {
+ return { rows: [], checkedAt: new Date(now()).toISOString(), error: 'INVALID_URLS', detail: `Supply at most ${PULL_REQUESTS_MAX} GitHub pull request URLs.` }
+ }
+ const unique = [...new Set(urls)] as string[], rows = new Map<string, PullRequestRow>()
+ await pooled(unique, 4, async url => { rows.set(url, await read(url)) })
+ const ordered = unique.map(url => rows.get(url)!)
+ const error = ['GH_MISSING', 'GH_SIGNED_OUT', 'RATE_LIMITED', 'TIMEOUT', 'GH_FAILED'].find(code => ordered.some(row => row.error === code))
+ return { rows: ordered, checkedAt: new Date(now()).toISOString(), ...(error ? { error } : {}) }
+ }
+}
diff --git a/cli/src/messages/tabDelivery.ts b/cli/src/messages/tabDelivery.ts
index 0178c1a8f..1b1c48471 100644
--- a/cli/src/messages/tabDelivery.ts
+++ b/cli/src/messages/tabDelivery.ts
@@ -27,11 +27,8 @@ export const WIRE_NAME_MAX = 64
const SENDER_MAX = 200
const ENGINE_MAX = 40
-/** Another machine's or account's words as a person or an agent reads them: no control or format character (an escape
- * sequence, a bidi override), cut to `max`; empty for anything that is not a string. */
-export function cleanText(value: unknown, max: number): string {
- return typeof value === 'string' ? cleanName(value).slice(0, max) : ''
-}
+import { cleanText } from '../lib/cleanText.js'
+export { cleanText } from '../lib/cleanText.js'
/** A field the receiver requires to be there: cleaned, and `?` where nothing is left of it. */
const shown = (value: string, max: number): string => cleanText(value, max) || '?'
diff --git a/cli/src/messages/tasks.ts b/cli/src/messages/tasks.ts
index dce7bba43..2029a9bff 100644
--- a/cli/src/messages/tasks.ts
+++ b/cli/src/messages/tasks.ts
@@ -7,17 +7,13 @@
* sees only the repositories that person may read. GitHub's search only names candidates, since it matches text
* loosely; the marker in the body is the real filter, so an issue that merely mentions the id is not a task.
*/
-import { execFile } from 'node:child_process'
-import { homedir } from 'node:os'
-import { delimiter, join } from 'node:path'
-import { promisify } from 'node:util'
-import { resolveBinaryOnPath } from '../lib/binaryOnPath.js'
-import { warmLoginShellEnvironment } from '../lib/loginShellEnv.js'
+import { ciOf, ghError, ghRun, MERGE_STATES, pooled, type CiState, type Run } from '../lib/github.js'
+export { findGh, resetGhPath, GH_DIRS } from '../lib/github.js'
+export type { CiState, Run } from '../lib/github.js'
import { validPullRequestUrl } from '../lib/sessionWorkWire.js'
import { MessageError } from './model.js'
import { cleanText } from './tabDelivery.js'
-export type CiState = 'passing' | 'failing' | 'pending' | 'none'
export interface TaskRow {
repo: string; issue: number; title: string; url: string; state: 'open' | 'closed'
assignee: { account: string; harness: string } | null
@@ -28,7 +24,6 @@ export interface TaskRow {
}
export interface TaskResult { rows: TaskRow[]; truncated: boolean; checkedAt: string }
/** `gh` only; rejects as `execFile` does: `{ code?, killed?, signal?, stderr? }`. */
-export type Run = (args: string[]) => Promise<{ stdout: string }>
export type TaskReader = (sharedTabId: string) => Promise<TaskResult>
export const TASKS_FRESH_MS = 30_000
@@ -43,57 +38,6 @@ const TITLE_MAX = 512
const REPO = /^[\w.-]+\/[\w.-]+$/
const ISSUE_URL = /^https:\/\/github\.com\/[\w.-]+\/[\w.-]+\/issues\/[1-9]\d*$/
-/** GitHub's `mergeStateStatus` words; anything else (a new one, a missing field) is `UNKNOWN` rather than shown as is. */
-const MERGE_STATES = ['BEHIND', 'BLOCKED', 'CLEAN', 'DIRTY', 'DRAFT', 'HAS_HOOKS', 'UNSTABLE']
-
-const exec = promisify(execFile)
-
-/** Where gh is installed when the daemon's PATH does not have it: Homebrew on Apple silicon and on Intel, Linuxbrew, and
- * a user install. */
-export const GH_DIRS: readonly string[] = ['/opt/homebrew/bin', '/usr/local/bin', '/home/linuxbrew/.linuxbrew/bin', join(homedir(), '.local', 'bin')]
-
-/**
- * gh's full path, or null. The daemon is started by launchd or the app, not a shell, so its PATH is the bare system one:
- * a Mac with gh from Homebrew was told "Install the GitHub CLI (gh) on this computer" beside a working `gh` in every
- * terminal (2026-10-17), as tmux once was (lib/tmuxOnPath.ts). So: the daemon's PATH, then the usual install folders,
- * then the PATH the person's own login shell gives, which is spawned only when the first two have no gh.
- */
-export async function findGh(env: NodeJS.ProcessEnv = process.env, dirs: readonly string[] = GH_DIRS,
- shellPath: () => Promise<string | undefined> = async () => (await warmLoginShellEnvironment()).PATH): Promise<string | null> {
- return resolveBinaryOnPath('gh', env) ?? resolveBinaryOnPath('gh', { PATH: dirs.join(delimiter) })
- ?? resolveBinaryOnPath('gh', { PATH: (await shellPath()) ?? '' })
-}
-
-// Found once and kept; a gh still missing is looked for again at the next read, so installing it needs no restart.
-let ghPath: string | null = null
-
-/** `gh` with no prompt and no wait for one: a terminal login question would hang the run until its timeout. */
-const ghRun: Run = async (args) => {
- // Refused under a test runner, whatever the caller: a real `gh` would read the developer's own GitHub login and search
- // public GitHub with it. Tests inject a `Run`; production never has VITEST set.
- if (process.env.VITEST) throw Object.assign(new Error('The real gh is not run in tests.'), { stderr: 'The real gh is not run in tests.' })
- ghPath ??= await findGh()
- if (!ghPath) throw Object.assign(new Error('gh was not found'), { code: 'ENOENT', stderr: '' })
- return { stdout: (await exec(ghPath, args, { timeout: 8000, killSignal: 'SIGKILL', maxBuffer: 1024 * 1024,
- env: { ...process.env, GH_PROMPT_DISABLED: '1', GIT_TERMINAL_PROMPT: '0' } })).stdout }
-}
-
-/** Test seam: forget the gh that was found. */
-export function resetGhPath(): void { ghPath = null }
-
-/** What a failed run means to the person, as a `MessageError`; the stderr shown is `gh`'s own, cleaned and cut. */
-function ghError(error: unknown): MessageError {
- const e = (error ?? {}) as { code?: unknown; killed?: unknown; signal?: unknown; stderr?: unknown }
- const stderr = typeof e.stderr === 'string' ? e.stderr : ''
- if (e.code === 'ENOENT') return new MessageError('GH_MISSING', 'The GitHub CLI (gh) is not installed on this computer.')
- if (/gh auth login|not logged in|authentication/i.test(stderr)) return new MessageError('GH_SIGNED_OUT', 'gh is not signed in on this computer: run `gh auth login`.')
- if (/rate limit|secondary rate|HTTP 403|HTTP 429/i.test(stderr)) return new MessageError('RATE_LIMITED', 'GitHub is limiting this computer\'s requests. Try again in a minute.')
- // A search too large for the buffer kills the child too, but it is not a slow GitHub: asking again would fail the same way.
- if (e.code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER') return new MessageError('GH_FAILED', 'GitHub returned too many or too large results.')
- if (e.killed === true || e.signal === 'SIGKILL') return new MessageError('TIMEOUT', 'GitHub did not answer in time.')
- return new MessageError('GH_FAILED', cleanText(stderr, 200) || 'gh failed.')
-}
-
const rowsOf = (stdout: string): Record<string, unknown>[] => {
let parsed: unknown
try { parsed = JSON.parse(stdout) } catch { throw new MessageError('GH_FAILED', 'gh answered with something Harness cannot read.') }
@@ -122,27 +66,6 @@ function searchedPrState(row: Record<string, unknown>): PrState {
return state === 'merged' ? 'Merged' : state === 'closed' ? 'Closed' : row.isDraft === true ? 'Draft' : 'Open'
}
-/** One pull request's CI from its checks: a check run has `status` and `conclusion`, a commit status has `state`. */
-function ciOf(rollup: unknown): CiState {
- const checks = Array.isArray(rollup) ? rollup.filter((c): c is Record<string, unknown> => !!c && typeof c === 'object') : []
- if (!checks.length) return 'none'
- const word = (v: unknown): string => String(v ?? '').toUpperCase()
- const failing = (c: Record<string, unknown>): boolean => ['FAILURE', 'ERROR', 'TIMED_OUT', 'CANCELLED', 'STARTUP_FAILURE', 'ACTION_REQUIRED']
- .includes(word(c.conclusion) || word(c.state))
- // A check that says nothing we know is not yet a pass.
- const settled = (c: Record<string, unknown>): boolean => !!c.conclusion || word(c.status) === 'COMPLETED' || ['SUCCESS', 'FAILURE', 'ERROR'].includes(word(c.state))
- const pending = (c: Record<string, unknown>): boolean => !settled(c)
- return checks.some(failing) ? 'failing' : checks.some(pending) ? 'pending' : 'passing'
-}
-
-/** Run `work` over `items`, at most `limit` at once. */
-async function pooled<T>(items: T[], limit: number, work: (item: T) => Promise<void>): Promise<void> {
- const queue = [...items]
- await Promise.all(Array.from({ length: Math.min(limit, items.length) }, async () => {
- for (let item = queue.shift(); item !== undefined; item = queue.shift()) await work(item)
- }))
-}
-
export function createTaskReader(run: Run = ghRun, now: () => number = Date.now): TaskReader {
const cache = new Map<string, { until: number; value: Promise<TaskResult> }>()
diff --git a/cli/src/services/projects.spec.ts b/cli/src/services/projects.spec.ts
index dd334a2b6..92875d396 100644
--- a/cli/src/services/projects.spec.ts
+++ b/cli/src/services/projects.spec.ts
@@ -1,4 +1,5 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
+import { createPullRequestsStatusReader } from '../lib/pullRequestsStatus.js'
import { listDir } from '../lib/fsBrowse.js'
import { readGitProject } from '../lib/gitProject.js'
import { MediaPreviewError, readMediaPreviewChunk } from '../lib/mediaPreview.js'
@@ -9,6 +10,8 @@ import { detectScmProject } from '../scm/scmProjects.js'
import { fakeCore } from '../testing/fakeCore.js'
import { PROJECTS_REQUESTS, startProjects } from './projects.js'
+const readPullRequests = vi.hoisted(() => vi.fn(async (_urls: unknown) => ({ rows: [] })))
+vi.mock('../lib/pullRequestsStatus.js', () => ({ createPullRequestsStatusReader: vi.fn(() => readPullRequests) }))
vi.mock('../lib/fsBrowse.js', () => ({ listDir: vi.fn(async () => ({ path: '/home/me', entries: [], truncated: false })) }))
vi.mock('../lib/gitProject.js', () => ({ readGitProject: vi.fn(async () => ({ path: '/work/app', branch: 'main' })) }))
vi.mock('../scm/scmProjects.js', () => ({ detectScmProject: vi.fn(async () => ({ kind: 'git', git: { isGit: true } })) }))
@@ -30,6 +33,19 @@ function setup() {
}
describe('the project and folder readers', () => {
+ it('reads linked PRs with the local reader, without an agent or folder', async () => {
+ const { requests } = setup()
+ const urls = ['https://github.com/o/r/pull/12']
+ expect(await requests.git_pull_requests_status!({ urls }, { local: true, owner: true })).toEqual({ rows: [] })
+ expect(createPullRequestsStatusReader).toHaveBeenCalled()
+ expect(readPullRequests).toHaveBeenLastCalledWith(urls)
+ expect(await requests.git_pull_requests_status!({ urls }, { local: false, owner: true, accountOwner: true })).toEqual({ rows: [] })
+ for (const asker of [{ local: true, owner: false }, { local: false, owner: true }, { local: false, owner: true, accountOwner: false }]) {
+ expect(await requests.git_pull_requests_status!({ urls }, asker)).toEqual({ error: 'OWNER_REQUIRED' })
+ }
+ expect(readPullRequests).toHaveBeenCalledTimes(2)
+ })
+
it('asks core for aggregate work evidence, and falls back to unknown', async () => {
const { core, ask } = setup()
await ask('git_pull_request', { agentId: 'a1' })
diff --git a/cli/src/services/projects.ts b/cli/src/services/projects.ts
index 459cd63ac..1249f406b 100644
--- a/cli/src/services/projects.ts
+++ b/cli/src/services/projects.ts
@@ -5,6 +5,7 @@
* socket's switch as they were (docs/design/2026-10-06-core-boundary-next.md, step 4).
*/
import type { CoreApi, ServiceRequests } from '../core/api.js'
+import { createPullRequestsStatusReader } from '../lib/pullRequestsStatus.js'
import { listDir } from '../lib/fsBrowse.js'
import { readGitProject } from '../lib/gitProject.js'
import { MediaPreviewError, readMediaPreviewChunk } from '../lib/mediaPreview.js'
@@ -20,7 +21,13 @@ export function startProjects(core: CoreApi): ServiceRequests {
/** The browsable home, widened by the folders agents are running in: a repository outside both is not
* somewhere this daemon runs git. */
const knownRoots = (): string[] => core.agents.live().flatMap((agent) => agent.cwd ? [agent.cwd] : [])
+ const readPullRequests = createPullRequestsStatusReader()
return {
+ git_pull_requests_status: internalOnThrow('git_pull_requests_status', (payload, asker) => {
+ // A trusted collaborator may use terminals here, but must not borrow this computer's GitHub account.
+ if (!asker.owner || !asker.local && asker.accountOwner !== true) return { error: 'OWNER_REQUIRED' }
+ return readPullRequests(payload.urls)
+ }),
git_pull_request: internalOnThrow('git_pull_request', (payload) => {
const id = payload.agentId
const agent = typeof id === 'string' ? core.agents.resolve(id) : undefined
diff --git a/desktop/integration_test/super_tab_pull_requests_native_test.dart b/desktop/integration_test/super_tab_pull_requests_native_test.dart
new file mode 100644
index 000000000..87fad17e5
--- /dev/null
+++ b/desktop/integration_test/super_tab_pull_requests_native_test.dart
@@ -0,0 +1,139 @@
+import 'dart:io';
+import 'dart:convert';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:integration_test/integration_test.dart';
+import 'package:window_manager/window_manager.dart';
+import 'package:harness/core/test_run.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/super_tabs/pull_requests.dart';
+
+import '../test/super_tab_pull_requests_test.dart'
+ show prServer, allPrStates, prUrl;
+
+/// Native rendering of the actual pane, with protocol fixtures and no production daemon or account writes.
+void main() {
+ if (!kUnderTest) throw StateError('Requires FLUTTER_TEST=1');
+ IntegrationTestWidgetsFlutterBinding.ensureInitialized().framePolicy =
+ LiveTestWidgetsFlutterBindingFramePolicy.onlyPumps;
+ testWidgets('linked PR status, expansion and stale answers render on macOS', (
+ tester,
+ ) async {
+ await windowManager.ensureInitialized();
+ await windowManager.setSize(const Size(1100, 1100));
+ await windowManager.setAlwaysOnTop(true);
+ addTearDown(() => windowManager.setAlwaysOnTop(false));
+ await windowManager.show();
+ await windowManager.focus();
+ final rows = allPrStates();
+ final server = prServer(
+ rows.map((r) => int.parse((r['url'] as String).split('/').last)),
+ );
+ final c = await tester.runAsync(() async {
+ final c = server.controller();
+ await c.refresh();
+ return c;
+ });
+ var fail = false;
+ final boundary = GlobalKey();
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: Scaffold(
+ body: RepaintBoundary(
+ key: boundary,
+ child: SuperTabPullRequests(
+ controller: c!,
+ read: (_) async => fail ? {'error': 'TIMEOUT'} : {'rows': rows},
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(find.text('Needs you 4'), findsOneWidget);
+ expect(find.text('Ready to merge'), findsOneWidget);
+ expect(find.text('View status on GitHub'), findsNothing);
+ Future<void> shot(String name) async {
+ final folder = Platform.environment['SUPER_TAB_PR_SHOTS'];
+ if (folder == null) return;
+ final image =
+ await (boundary.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary)
+ .toImage(pixelRatio: 1);
+ final bytes = await image.toByteData(format: ui.ImageByteFormat.png);
+ await Directory(folder).create(recursive: true);
+ await File('$folder/$name.png').writeAsBytes(bytes!.buffer.asUint8List());
+ image.dispose();
+ }
+
+ await tester.runAsync(() => shot('pull-requests-all-states'));
+ await tester.tap(find.text('Show 1 more'));
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Closed 1'));
+ await tester.pumpAndSettle();
+ expect(find.byKey(ValueKey('super-pr-${prUrl(16)}')), findsOneWidget);
+ await tester.runAsync(() => shot('pull-requests-expanded'));
+ fail = true;
+ // A new linked URL triggers a read now, without waiting a wall-clock minute.
+ server.append(prUrl(18));
+ await tester.runAsync(c.refresh);
+ await tester.pumpAndSettle();
+ expect(
+ find.textContaining("GitHub didn't answer. Showing what it said"),
+ findsOneWidget,
+ );
+ expect(find.text('Pull request 1'), findsOneWidget);
+ await tester.runAsync(() => shot('pull-requests-stale'));
+ final receipt = Platform.environment['SUPER_TAB_PR_REAL_RECEIPT'];
+ if (receipt != null) {
+ final real =
+ (jsonDecode(await File(receipt).readAsString()) as Map)['rows']
+ as List;
+ await tester.pumpWidget(const SizedBox());
+ final realServer = prServer(
+ real.map((r) => int.parse((r['url'] as String).split('/').last)),
+ );
+ for (final message in realServer.messages) {
+ message['text'] = (message['text'] as String).replaceAll(
+ 'github.com/o/r/',
+ 'github.com/autonomous-ai/openharness/',
+ );
+ }
+ final realController = await tester.runAsync(() async {
+ final c = realServer.controller();
+ await c.refresh();
+ return c;
+ });
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: Scaffold(
+ body: RepaintBoundary(
+ key: boundary,
+ child: SuperTabPullRequests(
+ controller: realController!,
+ read: (_) async => {'rows': real},
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(find.text('Merged 6'), findsOneWidget);
+ expect(find.text('Nothing needs you.'), findsOneWidget);
+ expect(find.text('View status on GitHub'), findsNothing);
+ await tester.runAsync(() => shot('pull-requests-real-six'));
+ await tester.pumpWidget(const SizedBox());
+ await tester.runAsync(realController.flush);
+ realController.dispose();
+ }
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ await tester.runAsync(c.flush);
+ c.dispose();
+ });
+}
diff --git a/desktop/lib/e2ee/envelope.dart b/desktop/lib/e2ee/envelope.dart
index 55f8f342c..6d1263e7b 100644
--- a/desktop/lib/e2ee/envelope.dart
+++ b/desktop/lib/e2ee/envelope.dart
@@ -73,7 +73,7 @@ const Set<String> encryptedDownTypes = {
'git_project_info',
// The harness's branch and pull-request history is a machine RPC too (applicationFrames.ts
// `MACHINE_REQUESTS`): unsealed, the machine answers E2EE_REQUIRED.
- 'git_pull_request',
+ 'git_pull_request', 'git_pull_requests_status',
// Memories across machines (CLI services/memory.ts).
'memory_snapshot',
'memory_about_put',
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index c32189591..887305747 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -13450,6 +13450,31 @@ class AppNotifier extends ChangeNotifier {
}
}
+ /// Linked Swarm PRs are read by this window's own computer, using its GitHub login.
+ /// An agent changing branch or stopping must not change whose account reads a link.
+ Future<Map<String, dynamic>> readPullRequestsStatus(List<String> urls) async {
+ final machine = localMachineState, revision = _authRevision;
+ if (machine == null) return {'error': 'UNAVAILABLE'};
+ try {
+ final result = await _conn(machine.machine.machineId).request(
+ 'git_pull_requests_status',
+ payload: {'urls': urls},
+ timeout: const Duration(seconds: 120),
+ );
+ if (!_machineWorkCurrent(machine, revision)) {
+ return {'error': 'UNAVAILABLE'};
+ }
+ return result;
+ } on WsRequestFailure catch (error) {
+ if (!_machineWorkCurrent(machine, revision)) {
+ return {'error': 'UNAVAILABLE'};
+ }
+ return {...error.payload, 'error': error.code};
+ } catch (_) {
+ return {'error': 'UNAVAILABLE'};
+ }
+ }
+
/// PR lookup runs on the agent's machine using that machine's GitHub access.
Future<Map<String, dynamic>> readAgentPullRequest(
String machineId,
diff --git a/desktop/lib/super_tabs/pull_request_entry.dart b/desktop/lib/super_tabs/pull_request_entry.dart
new file mode 100644
index 000000000..685174ca3
--- /dev/null
+++ b/desktop/lib/super_tabs/pull_request_entry.dart
@@ -0,0 +1,155 @@
+/// GitHub facts and their presentation order in the Swarm PR pane.
+enum PullRequestKind {
+ failed,
+ conflicts,
+ changes,
+ behind,
+ ready,
+ autoMerge,
+ review,
+ running,
+ draft,
+ open,
+ merged,
+ closed,
+ unknown,
+ checking,
+}
+
+class SuperTabPullRequestEntry {
+ const SuperTabPullRequestEntry({
+ required this.url,
+ this.title = '',
+ this.state = '',
+ this.status = 'found',
+ this.updatedAt,
+ this.mergedAt,
+ this.closedAt,
+ this.additions = 0,
+ this.deletions = 0,
+ this.passed = 0,
+ this.failed = 0,
+ this.pending = 0,
+ this.total = 0,
+ this.mergeState = '',
+ this.review = '',
+ this.autoMerge = false,
+ });
+ final Uri url;
+ final String title, state, status, mergeState, review;
+ final DateTime? updatedAt, mergedAt, closedAt;
+ final int additions, deletions, passed, failed, pending, total;
+ final bool autoMerge;
+ bool get finalState => state == 'Merged' || state == 'Closed';
+ int get number => int.parse(url.pathSegments.last);
+ String get repository => url.pathSegments.take(2).join('/');
+ DateTime? get time => state == 'Merged'
+ ? mergedAt
+ : state == 'Closed'
+ ? closedAt
+ : updatedAt;
+
+ PullRequestKind get kind {
+ if (status == 'checking') return PullRequestKind.checking;
+ if (status != 'found') return PullRequestKind.unknown;
+ if (state == 'Merged') return PullRequestKind.merged;
+ if (state == 'Closed') return PullRequestKind.closed;
+ if (failed > 0) return PullRequestKind.failed;
+ if (mergeState == 'DIRTY') return PullRequestKind.conflicts;
+ if (review == 'CHANGES_REQUESTED') return PullRequestKind.changes;
+ if (mergeState == 'BEHIND') return PullRequestKind.behind;
+ if (state == 'Draft') return PullRequestKind.draft;
+ if (total > 0 &&
+ pending == 0 &&
+ mergeState == 'CLEAN' &&
+ review != 'REVIEW_REQUIRED') {
+ return PullRequestKind.ready;
+ }
+ if (autoMerge) return PullRequestKind.autoMerge;
+ if (review == 'REVIEW_REQUIRED') return PullRequestKind.review;
+ if (pending > 0) return PullRequestKind.running;
+ // No checks or an unresolved GitHub merge state is not evidence of readiness.
+ return PullRequestKind.open;
+ }
+
+ String get label => switch (kind) {
+ PullRequestKind.failed => '$failed of $total checks failed',
+ PullRequestKind.conflicts => 'Conflicts with main',
+ PullRequestKind.changes => 'Changes requested',
+ PullRequestKind.behind => 'Behind main',
+ PullRequestKind.ready => 'Ready to merge',
+ PullRequestKind.autoMerge => 'Merges when checks pass',
+ PullRequestKind.review => 'Waiting for review',
+ PullRequestKind.running =>
+ 'Checks running · ${passed + failed} of $total done',
+ PullRequestKind.draft => 'Draft',
+ PullRequestKind.open => 'Open',
+ PullRequestKind.merged => '',
+ PullRequestKind.closed => 'Not merged',
+ PullRequestKind.unknown =>
+ status == 'no_access'
+ ? "Can't read status: this computer's GitHub account has no access"
+ : 'Status unknown',
+ PullRequestKind.checking => 'Checking GitHub…',
+ };
+ String get checksLabel => total == 0
+ ? 'No checks yet'
+ : pending > 0
+ ? '${passed + failed} of $total checks done'
+ : failed > 0
+ ? '$failed of $total checks failed'
+ : '$passed ${passed == 1 ? 'check' : 'checks'} passed';
+
+ static SuperTabPullRequestEntry? fromJson(Map<String, dynamic> json) {
+ final url = Uri.tryParse(json['url'] is String ? json['url'] : '');
+ if (url == null ||
+ !RegExp(r'^https://github\.com/[\w-]+/[\w.-]+/pull/[1-9]\d*$')
+ .hasMatch(url.toString())) {
+ return null;
+ }
+ final checks = json['checks'] is Map ? json['checks'] as Map : const {};
+ int count(dynamic n) => n is int && n >= 0 ? n : 0;
+ DateTime? date(dynamic s) => s is String ? DateTime.tryParse(s) : null;
+ final state = json['state'];
+ final found =
+ json['status'] == 'found' &&
+ const ['Open', 'Draft', 'Merged', 'Closed'].contains(state) &&
+ json['title'] is String;
+ return SuperTabPullRequestEntry(
+ url: url,
+ status: found
+ ? 'found'
+ : json['status'] == 'no_access'
+ ? 'no_access'
+ : 'unavailable',
+ title: found ? json['title'] : '',
+ state: found ? state : '',
+ updatedAt: date(json['updatedAt']),
+ mergedAt: date(json['mergedAt']),
+ closedAt: date(json['closedAt']),
+ additions: count(json['additions']),
+ deletions: count(json['deletions']),
+ passed: count(checks['passed']),
+ failed: count(checks['failed']),
+ pending: count(checks['pending']),
+ total: count(checks['total']),
+ mergeState: json['mergeStateStatus'] is String
+ ? json['mergeStateStatus']
+ : '',
+ review: json['reviewDecision'] is String ? json['reviewDecision'] : '',
+ autoMerge: json['autoMerge'] == true,
+ );
+ }
+}
+
+String pullRequestAge(DateTime? time, DateTime now) {
+ if (time == null) return '';
+ final minutes = now.difference(time).inMinutes.clamp(0, 99999999);
+ return minutes < 1
+ ? 'just now'
+ : minutes < 60
+ ? '$minutes min ago'
+ : minutes < 1440
+ ? '${(minutes / 60).round()} h ago'
+ : '${(minutes / 1440).round()} d ago';
+}
diff --git a/desktop/lib/super_tabs/pull_requests.dart b/desktop/lib/super_tabs/pull_requests.dart
index a086f7bbc..3d42dd63e 100644
--- a/desktop/lib/super_tabs/pull_requests.dart
+++ b/desktop/lib/super_tabs/pull_requests.dart
@@ -4,6 +4,9 @@ import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import '../core/pull_request_status.dart';
+import '../core/open_in_browser.dart';
+import '../shared/theme/pull_request_icon.dart';
+import 'pull_request_entry.dart';
import '../shared/theme/app_icons.dart';
import '../state/app_state.dart';
import '../widgets/desktop_chrome.dart';
@@ -12,9 +15,11 @@ import 'model.dart';
List<Uri> superTabPullRequestLinks(String text) => {
for (final match in RegExp(
- r'https://github\.com/([A-Za-z0-9_.-]+)/([A-Za-z0-9_.-]+)/pull/([1-9][0-9]*)\b',
+ r'https://github\.com/([A-Za-z0-9_-]+)/([A-Za-z0-9_.-]+)/pull/([1-9][0-9]*)\b',
).allMatches(text))
- Uri.parse(match.group(0)!),
+ if (int.tryParse(match.group(3)!) case final number?
+ when number <= 9007199254740991)
+ Uri.parse(match.group(0)!),
}.toList();
class SuperTabPullRequestLinks extends StatelessWidget {
@@ -46,23 +51,38 @@ class SuperTabPullRequestLinks extends StatelessWidget {
}
}
-/// Links are evidence of a PR reference, never evidence that checks passed or
-/// that its task is finished. Only the owning machine supplies current state.
+/// Linked URLs are read by the viewer's computer, independently of the agents' branches.
class SuperTabPullRequests extends StatefulWidget {
- const SuperTabPullRequests({super.key, required this.controller, this.app});
+ const SuperTabPullRequests({
+ super.key,
+ required this.controller,
+ this.app,
+ this.read,
+ this.visible = true,
+ this.now = DateTime.now,
+ });
final SuperTabController controller;
final AppNotifier? app;
+ final Future<Map<String, dynamic>> Function(List<String>)? read;
+ final bool visible;
+ final DateTime Function() now;
@override
State<SuperTabPullRequests> createState() => _SuperTabPullRequestsState();
}
class _SuperTabPullRequestsState extends State<SuperTabPullRequests> {
- final _observed = <String, PullRequestStatus>{};
- bool _all = false, _loading = false;
- String? _scope;
+ final _entries = <String, SuperTabPullRequestEntry>{};
+ final _legacy = <String, PullRequestStatus>{};
+ bool _all = false, _loading = false, _showMerged = false, _closed = false;
+ bool _unsupported = false, _tickers = true;
+ String? _scope, _error;
+ String _linksKey = '';
+ DateTime? _checkedAt;
int _revision = 0;
- Timer? _timer;
+ Timer? _timer, _ageTimer;
SuperTabController get c => widget.controller;
+ bool get _active =>
+ widget.visible && _tickers && (widget.app?.foreground.value ?? true);
bool get _projectScope =>
_all || c.snapshot?.isProjectLead(c.selectedId) == true;
List<SuperTabConversation> get _groups =>
@@ -75,21 +95,73 @@ class _SuperTabPullRequestsState extends State<SuperTabPullRequests> {
.toList() ??
const [];
+ Map<String, ({Uri url, Set<String> groups})> get _links {
+ final links = <String, ({Uri url, Set<String> groups})>{};
+ void include(Uri url, String group) {
+ final key = url.toString();
+ links[key] = (url: url, groups: {...?links[key]?.groups, group});
+ }
+
+ for (final group in _groups) {
+ for (final message in c.messages(group.id)) {
+ for (final link in superTabPullRequestLinks(message.text)) {
+ include(link, group.title);
+ }
+ }
+ if (_unsupported) {
+ for (final id in group.agentIds) {
+ if (_legacy[id] case final pr?) {
+ include(pr.url, group.title);
+ }
+ }
+ }
+ }
+ return links;
+ }
+
@override
void initState() {
super.initState();
c.addListener(_changed);
+ widget.app?.foreground.addListener(_visibilityChanged);
_changed();
}
+ @override
+ void didChangeDependencies() {
+ super.didChangeDependencies();
+ final enabled = TickerMode.valuesOf(context).enabled;
+ if (_tickers != enabled) {
+ _tickers = enabled;
+ _visibilityChanged();
+ }
+ }
+
@override
void didUpdateWidget(SuperTabPullRequests oldWidget) {
super.didUpdateWidget(oldWidget);
+ if (oldWidget.app != widget.app) {
+ oldWidget.app?.foreground.removeListener(_visibilityChanged);
+ widget.app?.foreground.addListener(_visibilityChanged);
+ _scope = null;
+ }
if (oldWidget.controller != c) {
oldWidget.controller.removeListener(_changed);
c.addListener(_changed);
_scope = null;
- _changed();
+ }
+ if (oldWidget.visible != widget.visible) _visibilityChanged();
+ _changed();
+ }
+
+ void _visibilityChanged() {
+ _timer?.cancel();
+ _ageTimer?.cancel();
+ if (!_active) {
+ _revision++;
+ _loading = false;
+ } else {
+ unawaited(_refresh());
}
}
@@ -98,94 +170,268 @@ class _SuperTabPullRequestsState extends State<SuperTabPullRequests> {
'${c.accountId}:${c.tabId}:${c.selected?.projectId}:${_projectScope ? '*' : c.selectedId}';
if (scope != _scope) {
_scope = scope;
- _observed.clear();
+ _entries.clear();
+ _legacy.clear();
+ _error = null;
+ _checkedAt = null;
+ _showMerged = false;
+ _closed = false;
+ _linksKey = '';
unawaited(_refresh());
- } else if (mounted) {
- setState(() {});
+ } else {
+ final key = _links.keys.join('|');
+ if (!_loading && key != _linksKey) {
+ unawaited(_refresh());
+ } else if (mounted) {
+ setState(() {});
+ }
+ }
+ }
+
+ void _schedule() {
+ _timer?.cancel();
+ _ageTimer?.cancel();
+ if (!_active) return;
+ if (_checkedAt != null) {
+ _ageTimer = Timer.periodic(const Duration(seconds: 1), (_) {
+ if (mounted) setState(() {});
+ });
+ }
+ if (_unsupported ||
+ _error != null ||
+ _links.keys.any((url) => _entries[url]?.finalState != true)) {
+ _timer = Timer(const Duration(seconds: 60), _refresh);
}
}
Future<void> _refresh() async {
+ if (!_active) return;
final revision = ++_revision;
_timer?.cancel();
setState(() => _loading = true);
final groups = _groups;
- if (_projectScope) {
- // The controller owns paging and caches; this never changes selection.
- for (final group in groups) {
- if (!mounted || revision != _revision) return;
- await c.loadMessages(group.id);
+ try {
+ if (_projectScope) {
+ // The controller owns paging and caches; this never changes selection.
+ for (final group in groups) {
+ await c.loadMessages(group.id);
+ if (!mounted || revision != _revision) return;
+ }
}
- }
- final agents =
- c.snapshot?.agents
- .where((a) => groups.any((g) => g.agentIds.contains(a.id)))
- .toList() ??
- const <SuperTabAgent>[];
- final values = <String, PullRequestStatus>{};
- for (var i = 0; i < agents.length; i += 2) {
- await Future.wait(
- agents.skip(i).take(2).map((agent) async {
- try {
- final answer = await widget.app?.readAgentPullRequest(
- agent.machineId,
- agent.harnessId,
+ final links = _links;
+ _linksKey = links.keys.join('|');
+ final urls = links.keys
+ .where((url) => _entries[url]?.finalState != true)
+ .toList();
+ if (!_unsupported && urls.isNotEmpty) {
+ final values = <String, SuperTabPullRequestEntry>{};
+ String? error;
+ for (var i = 0; i < urls.length; i += 50) {
+ final answer =
+ await (widget.read ?? widget.app?.readPullRequestsStatus)?.call(
+ urls.skip(i).take(50).toList(),
+ ) ??
+ <String, dynamic>{'error': 'UNAVAILABLE'};
+ if (!mounted || revision != _revision) return;
+ if (answer['error'] == 'UNSUPPORTED') {
+ _unsupported = true;
+ break;
+ }
+ if (answer['error'] is String) error ??= answer['error'];
+ if (answer['rows'] is! List && error == null) error = 'UNAVAILABLE';
+ for (final raw
+ in answer['rows'] is List ? answer['rows'] as List : const []) {
+ if (raw is! Map) continue;
+ final entry = SuperTabPullRequestEntry.fromJson(
+ Map<String, dynamic>.from(raw),
);
- final value = PullRequestStatus.fromResult(answer);
- if (value != null) values[agent.id] = value;
- } catch (_) {
- /* Missing access is unknown, not a passed check. */
+ if (entry != null && urls.contains(entry.url.toString())) {
+ values[entry.url.toString()] = entry;
+ }
}
- }),
- );
+ }
+ if (error == 'GH_MISSING' || error == 'GH_SIGNED_OUT') {
+ // A changed login must not leave yesterday's private titles under today's account.
+ _entries.clear();
+ _checkedAt = null;
+ } else {
+ for (final item in values.entries) {
+ if (item.value.status != 'unavailable') {
+ _entries[item.key] = item.value;
+ }
+ }
+ if (error == null && !_unsupported) _checkedAt = widget.now();
+ }
+ _error = error;
+ }
+ if (_unsupported) {
+ final agents =
+ c.snapshot?.agents
+ .where((a) => groups.any((g) => g.agentIds.contains(a.id)))
+ .toList() ??
+ const <SuperTabAgent>[];
+ final values = <String, PullRequestStatus>{};
+ for (var i = 0; i < agents.length; i += 2) {
+ await Future.wait(
+ agents.skip(i).take(2).map((agent) async {
+ final pr = PullRequestStatus.fromResult(
+ await widget.app?.readAgentPullRequest(
+ agent.machineId,
+ agent.harnessId,
+ ),
+ );
+ if (pr != null) values[agent.id] = pr;
+ }),
+ );
+ if (!mounted || revision != _revision) return;
+ }
+ _legacy
+ ..clear()
+ ..addAll(values);
+ _error = null;
+ }
+ if (links.isEmpty && _error == null) _checkedAt ??= widget.now();
+ } catch (_) {
if (!mounted || revision != _revision) return;
+ _error = 'UNAVAILABLE';
}
if (!mounted || revision != _revision) return;
- setState(() {
- _observed
- ..clear()
- ..addAll(values);
- _loading = false;
- });
- if (widget.app != null && widget.app!.foreground.value) {
- _timer = Timer(const Duration(seconds: 60), _refresh);
- }
+ setState(() => _loading = false);
+ _schedule();
}
@override
void dispose() {
_revision++;
_timer?.cancel();
+ _ageTimer?.cancel();
+ widget.app?.foreground.removeListener(_visibilityChanged);
c.removeListener(_changed);
super.dispose();
}
+ String get _fresh {
+ if (_checkedAt == null) {
+ return _loading ? 'Checking GitHub…' : 'Not checked';
+ }
+ final seconds = widget
+ .now()
+ .difference(_checkedAt!)
+ .inSeconds
+ .clamp(0, 9999999);
+ return _error == null
+ ? 'Checked $seconds s ago'
+ : 'Checked ${pullRequestAge(_checkedAt, widget.now())}';
+ }
+
+ String? get _banner => switch (_error) {
+ 'GH_MISSING' => 'Install the GitHub CLI (gh) on this computer, then run gh auth login in Terminal; status shows up within a minute.',
+ 'GH_SIGNED_OUT' => "GitHub isn't signed in on this computer, so Harness can't read these pull requests. Run gh auth login in Terminal; status shows up within a minute.",
+ 'RATE_LIMITED' =>
+ "GitHub is limiting this computer's requests. Trying again in 1 min.",
+ null => null,
+ _ =>
+ _checkedAt == null
+ ? "GitHub didn't answer. Trying again in 1 min."
+ : "GitHub didn't answer. Showing what it said ${pullRequestAge(_checkedAt, widget.now())}; trying again in 1 min.",
+ };
+
@override
Widget build(BuildContext context) {
- final links = <String, ({Uri url, Set<String> groups, String? state})>{};
- void include(Uri url, String group, String? state) {
- final key = url.toString(), prior = links[url.toString()];
- links[key] = (
- url: url,
- groups: {...?prior?.groups, group},
- state: state ?? prior?.state,
+ final links = _links;
+ final entries = [
+ for (final link in links.values)
+ _entries[link.url.toString()] ??
+ SuperTabPullRequestEntry(
+ url: link.url,
+ status: _loading && _checkedAt == null && _error == null
+ ? 'checking'
+ : 'unavailable',
+ ),
+ ];
+ final checking = _checkedAt == null && _loading && _error == null;
+ final login = _error == 'GH_MISSING' || _error == 'GH_SIGNED_OUT';
+ int recent(SuperTabPullRequestEntry a, SuperTabPullRequestEntry b) =>
+ (b.time ?? DateTime(1970)).compareTo(a.time ?? DateTime(1970));
+ List<SuperTabPullRequestEntry> by(
+ bool Function(SuperTabPullRequestEntry) test,
+ ) => entries.where(test).toList()..sort(recent);
+ final needs = by((e) => e.kind.index <= PullRequestKind.behind.index);
+ final open =
+ by(
+ (e) =>
+ e.kind.index >= PullRequestKind.ready.index &&
+ e.kind.index <= PullRequestKind.open.index,
+ )..sort(
+ (a, b) => a.kind.index.compareTo(b.kind.index) == 0
+ ? recent(a, b)
+ : a.kind.index.compareTo(b.kind.index),
+ );
+ final merged = by((e) => e.kind == PullRequestKind.merged);
+ Widget section(
+ String title,
+ List<SuperTabPullRequestEntry> rows, {
+ bool always = false,
+ bool collapsed = false,
+ }) {
+ if (rows.isEmpty && !always) return const SizedBox.shrink();
+ final shown = title == 'Merged' && !_showMerged ? rows.take(5) : rows;
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Padding(
+ padding: const EdgeInsets.fromLTRB(20, 14, 20, 4),
+ child: title == 'Closed'
+ ? Align(
+ alignment: Alignment.centerLeft,
+ child: TextButton.icon(
+ onPressed: () => setState(() => _closed = !_closed),
+ icon: Icon(
+ _closed ? AppIcons.chevronDown : AppIcons.chevronRight,
+ size: 12,
+ ),
+ label: Text(
+ 'Closed ${rows.length}',
+ style: DesktopChrome.metadata(),
+ ),
+ ),
+ )
+ : Text(
+ '$title ${rows.length}',
+ style: DesktopChrome.metadata(
+ color: title == 'Needs you' && rows.isNotEmpty
+ ? Theme.of(context).colorScheme.error
+ : null,
+ ).copyWith(fontWeight: FontWeight.w600),
+ ),
+ ),
+ if (!collapsed) ...[
+ if (rows.isEmpty)
+ Padding(
+ padding: const EdgeInsets.fromLTRB(90, 2, 20, 6),
+ child: Text(
+ 'Nothing needs you.',
+ style: DesktopChrome.metadata(),
+ ),
+ ),
+ for (final entry in shown)
+ _row(entry, links[entry.url.toString()]!.groups),
+ if (title == 'Merged' && shown.length < rows.length)
+ Align(
+ alignment: Alignment.centerLeft,
+ child: Padding(
+ padding: const EdgeInsets.only(left: 78),
+ child: TextButton(
+ onPressed: () => setState(() => _showMerged = true),
+ child: Text('Show ${rows.length - shown.length} more'),
+ ),
+ ),
+ ),
+ ],
+ ],
);
}
- for (final group in _groups) {
- for (final message in c.messages(group.id)) {
- for (final match in RegExp(
- r'https://github\.com/([A-Za-z0-9_.-]+)/([A-Za-z0-9_.-]+)/pull/([1-9][0-9]*)\b',
- ).allMatches(message.text)) {
- include(Uri.parse(match.group(0)!), group.title, null);
- }
- }
- for (final agentId in group.agentIds) {
- if (_observed[agentId] case final pr?) {
- include(pr.url, group.title, pr.state);
- }
- }
- }
return Column(
children: [
Padding(
@@ -193,11 +439,22 @@ class _SuperTabPullRequestsState extends State<SuperTabPullRequests> {
child: Row(
children: [
Expanded(
- child: Text(
- 'Pull requests',
- style: DesktopChrome.text(medium: true),
+ child: Wrap(
+ crossAxisAlignment: WrapCrossAlignment.center,
+ spacing: 8,
+ runSpacing: 4,
+ children: [
+ Text(
+ 'Pull requests',
+ style: DesktopChrome.text(medium: true),
+ ),
+ Text('· ${links.length}', style: DesktopChrome.metadata()),
+ if (!_unsupported)
+ Text('· $_fresh', style: DesktopChrome.metadata()),
+ ],
),
),
+ const SizedBox(width: 8),
if (c.snapshot?.isProjectLead(c.selectedId) == true)
Text('This project', style: DesktopChrome.metadata())
else
@@ -209,63 +466,255 @@ class _SuperTabPullRequestsState extends State<SuperTabPullRequests> {
DropdownMenuItem(value: true, child: Text('This project')),
],
onChanged: (value) {
- if (value == null) return;
- setState(() => _all = value);
- _changed();
+ if (value != null) {
+ setState(() => _all = value);
+ _changed();
+ }
},
),
],
),
),
- if (_loading) const LinearProgressIndicator(minHeight: 2),
+ if (_banner case final banner?)
+ Padding(
+ padding: const EdgeInsets.fromLTRB(20, 0, 20, 6),
+ child: Semantics(
+ liveRegion: true,
+ child: Container(
+ width: double.infinity,
+ padding: const EdgeInsets.symmetric(
+ horizontal: 12,
+ vertical: 8,
+ ),
+ decoration: BoxDecoration(
+ color: Theme.of(context).colorScheme.error
+ .withValues(alpha: .1),
+ borderRadius: BorderRadius.circular(8),
+ ),
+ child: Text(
+ banner,
+ style: DesktopChrome.metadata(
+ color: DesktopChrome.foreground,
+ ),
+ ),
+ ),
+ ),
+ ),
Expanded(
child: links.isEmpty
? Center(
child: Padding(
padding: const EdgeInsets.all(24),
- child: Text(
- _loading ? 'Reading pull requests…' : 'Pull requests shared in the conversation appear here.',
- textAlign: TextAlign.center,
- style: DesktopChrome.text(color: DesktopChrome.muted),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text(
+ _loading
+ ? 'Checking GitHub…'
+ : 'No pull requests yet',
+ style: DesktopChrome.control(medium: true),
+ ),
+ const SizedBox(height: 4),
+ Text(
+ 'A GitHub pull request link posted in ${_projectScope ? 'any chat of this project' : 'this chat'} shows up here with its status.',
+ textAlign: TextAlign.center,
+ style: DesktopChrome.metadata(),
+ ),
+ ],
),
),
)
- : ListView.separated(
- padding: const EdgeInsets.symmetric(
- horizontal: 20,
- vertical: 12,
- ),
- itemCount: links.length,
- separatorBuilder: (_, _) =>
- Divider(height: 24, color: DesktopChrome.rim),
- itemBuilder: (context, i) {
- final pr = links.values.elementAt(i),
- parts = pr.url.pathSegments;
- return ListTile(
- contentPadding: EdgeInsets.zero,
- title: Text(
- '${parts[0]}/${parts[1]} #${parts[3]}',
- style: DesktopChrome.control(medium: true),
+ : ListView(
+ padding: const EdgeInsets.only(bottom: 16),
+ children: [
+ if (_unsupported)
+ for (final link in links.values)
+ _legacyRow(link.url, link.groups)
+ else if (checking)
+ section(
+ _projectScope
+ ? 'Linked in this project'
+ : 'Linked in this group',
+ entries,
+ )
+ else if (login)
+ section('Status unknown', entries)
+ else ...[
+ section('Needs you', needs, always: true),
+ section('Open', open),
+ section('Merged', merged),
+ section(
+ 'Closed',
+ by((e) => e.kind == PullRequestKind.closed),
+ collapsed: !_closed,
),
- subtitle: Text(
- [
- if (_projectScope) pr.groups.join(' '),
- pr.state ?? 'View status on GitHub',
- ].join('\n'),
- style: DesktopChrome.metadata(),
- ),
- trailing: TextButton(
- onPressed: () => launchUrl(
- pr.url,
- mode: LaunchMode.externalApplication,
- ),
- child: const Text('Open on GitHub'),
+ section(
+ 'Status unknown',
+ by((e) => e.kind == PullRequestKind.unknown),
),
- );
- },
+ ],
+ ],
),
),
],
);
}
+
+ Color _color(SuperTabPullRequestEntry entry) => switch (entry.kind) {
+ PullRequestKind.failed ||
+ PullRequestKind.conflicts ||
+ PullRequestKind.changes => Theme.of(context).colorScheme.error,
+ PullRequestKind.ready || PullRequestKind.autoMerge => pullRequestIconColor(
+ 'Open',
+ null,
+ brightness: Theme.of(context).brightness,
+ ),
+ PullRequestKind.merged => pullRequestIconColor(
+ 'Merged',
+ null,
+ brightness: Theme.of(context).brightness,
+ ),
+ PullRequestKind.review => DesktopChrome.accent,
+ PullRequestKind.behind ||
+ PullRequestKind.running => Theme.of(context).colorScheme.tertiary,
+ _ => DesktopChrome.muted,
+ };
+ Widget _row(SuperTabPullRequestEntry entry, Set<String> groups) {
+ final bits = <Widget>[];
+ void bit(String text, {Color? color, bool bold = false}) {
+ if (text.isEmpty) return;
+ if (bits.isNotEmpty) bits.add(Text('·', style: DesktopChrome.metadata()));
+ bits.add(
+ Text(
+ text,
+ style: DesktopChrome.metadata(color: color)
+ .copyWith(fontWeight: bold ? FontWeight.w600 : null),
+ ),
+ );
+ }
+
+ bit(entry.label, color: _color(entry), bold: true);
+ if (entry.status == 'found') {
+ if (entry.kind != PullRequestKind.failed &&
+ entry.kind != PullRequestKind.running) {
+ bit(entry.checksLabel);
+ }
+ bit('+${entry.additions} −${entry.deletions}');
+ }
+ bit('in ${groups.join(', ')}');
+ final time = pullRequestAge(entry.time, widget.now());
+ return Semantics(
+ link: true,
+ child: InkWell(
+ key: ValueKey('super-pr-${entry.url}'),
+ onTap: () => unawaited(openInBrowser(entry.url)),
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 7),
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Padding(
+ padding: const EdgeInsets.only(top: 5),
+ child: Container(
+ width: 8,
+ height: 8,
+ decoration: BoxDecoration(
+ shape: BoxShape.circle,
+ color:
+ const [
+ PullRequestKind.draft,
+ PullRequestKind.closed,
+ PullRequestKind.unknown,
+ PullRequestKind.checking,
+ ].contains(entry.kind)
+ ? null
+ : _color(entry),
+ border: Border.all(color: _color(entry), width: 1.5),
+ ),
+ ),
+ ),
+ const SizedBox(width: 10),
+ SizedBox(
+ width: 52,
+ child: Text(
+ '#${entry.number}',
+ style: DesktopChrome.metadata(),
+ ),
+ ),
+ const SizedBox(width: 10),
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Row(
+ children: [
+ Expanded(
+ child: entry.kind == PullRequestKind.checking
+ ? Align(
+ alignment: Alignment.centerLeft,
+ child: Container(
+ width: 280,
+ height: 10,
+ margin: const EdgeInsets.symmetric(
+ vertical: 3,
+ ),
+ decoration: BoxDecoration(
+ color: DesktopChrome.rim,
+ borderRadius: BorderRadius.circular(4),
+ ),
+ ),
+ )
+ : Text(
+ entry.title.isNotEmpty
+ ? entry.title
+ : entry.repository,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.control(
+ medium: entry.title.isNotEmpty,
+ ),
+ ),
+ ),
+ if (time.isNotEmpty) ...[
+ const SizedBox(width: 12),
+ Text(
+ '${entry.state == 'Merged'
+ ? 'merged'
+ : entry.state == 'Closed'
+ ? 'closed'
+ : 'updated'} $time',
+ style: DesktopChrome.metadata(),
+ ),
+ ],
+ ],
+ ),
+ const SizedBox(height: 2),
+ Wrap(spacing: 6, runSpacing: 2, children: bits),
+ ],
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+
+ Widget _legacyRow(Uri url, Set<String> groups) {
+ final prior = _legacy.values.where((pr) => pr.url == url).firstOrNull;
+ return ListTile(
+ onTap: () => unawaited(openInBrowser(url)),
+ title: Text(
+ '${url.pathSegments.take(2).join('/')} #${url.pathSegments.last}',
+ style: DesktopChrome.control(medium: true),
+ ),
+ subtitle: Text(
+ [
+ if (_projectScope) groups.join(' '),
+ prior?.state ?? 'View status on GitHub',
+ ].join('\n'),
+ style: DesktopChrome.metadata(),
+ ),
+ );
+ }
}
diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dart
index a046a123a..23ba53813 100644
--- a/desktop/lib/super_tabs/view.dart
+++ b/desktop/lib/super_tabs/view.dart
@@ -1568,6 +1568,7 @@ class _SuperTabViewState extends State<SuperTabView>
? SuperTabPullRequests(
controller: c,
app: widget.app,
+ visible: !_terminalsVisible,
)
: const SizedBox.shrink(),
],
diff --git a/desktop/lib/ws/ws_conn.dart b/desktop/lib/ws/ws_conn.dart
index cec26a4fd..3e6de8810 100644
--- a/desktop/lib/ws/ws_conn.dart
+++ b/desktop/lib/ws/ws_conn.dart
@@ -671,6 +671,8 @@ class WsConn {
'window_name_result',
'git_project_info',
'git_project_info_result',
+ 'git_pull_requests_status',
+ 'git_pull_requests_status_result',
'terminal_output',
'terminal_input',
'terminal_resize',
diff --git a/desktop/test/super_tab_pull_request_state_test.dart b/desktop/test/super_tab_pull_request_state_test.dart
new file mode 100644
index 000000000..3dc384a55
--- /dev/null
+++ b/desktop/test/super_tab_pull_request_state_test.dart
@@ -0,0 +1,118 @@
+import 'dart:async';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/ws/ws_conn.dart';
+
+import 'support/rename_connection.dart';
+import 'swarm_state_test.dart' show createApp;
+
+class LinkedPrConnection extends RenameConnection {
+ final requests = <Map<String, dynamic>>[];
+ final pending = <Completer<Map<String, dynamic>>>[];
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) {
+ if (type != 'git_pull_requests_status') {
+ return super.request(type, payload: payload, timeout: timeout);
+ }
+ requests.add(payload);
+ final reply = Completer<Map<String, dynamic>>();
+ pending.add(reply);
+ return reply.future;
+ }
+}
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+ test('reads with the local computer even when an unrelated remote machine is selected', () async {
+ final local = LinkedPrConnection(), remote = LinkedPrConnection();
+ final app = createApp(
+ connectionForTest: (id) => id == 'm' ? local : remote,
+ );
+ addTearDown(app.dispose);
+ app.stateOf('m')!
+ ..localOnly = true
+ ..agents = [];
+ app.machineStates['remote'] = MachineState(
+ const Machine(
+ machineId: 'remote',
+ authMode: MachineAuthMode.remote,
+ name: 'Other',
+ ),
+ );
+ app.selectedMachineId = 'remote';
+ final result = app.readPullRequestsStatus([
+ 'https://github.com/o/r/pull/1',
+ ]);
+ expect(local.requests.single, {
+ 'urls': ['https://github.com/o/r/pull/1'],
+ });
+ expect(remote.requests, isEmpty);
+ local.pending.last.complete({
+ 'rows': [
+ {'state': 'Merged', 'title': 'Already done'},
+ ],
+ });
+ expect(await result, {
+ 'rows': [
+ {'state': 'Merged', 'title': 'Already done'},
+ ],
+ });
+ });
+ test('preserves typed refusals and partial answers, including older-daemon unsupported', () async {
+ for (final code in [
+ 'UNSUPPORTED',
+ 'GH_MISSING',
+ 'GH_SIGNED_OUT',
+ 'TIMEOUT',
+ ]) {
+ final connection = LinkedPrConnection();
+ final app = createApp(connectionForTest: (_) => connection);
+ app.stateOf('m')!.localOnly = true;
+ final result = app.readPullRequestsStatus([]);
+ connection.pending.last.completeError(
+ WsRequestFailure(
+ responseType: 'git_pull_requests_status_result',
+ code: code,
+ payload: {
+ 'rows': [
+ {'title': 'Readable'},
+ ],
+ },
+ ),
+ );
+ expect(await result, {
+ 'error': code,
+ 'rows': [
+ {'title': 'Readable'},
+ ],
+ });
+ app.dispose();
+ }
+ });
+ test('does not apply an answer from a replaced machine or a disconnected request', () async {
+ final connection = LinkedPrConnection(),
+ app = createApp(connectionForTest: (_) => connection);
+ addTearDown(app.dispose);
+ app.stateOf('m')!.localOnly = true;
+ final result = app.readPullRequestsStatus([]);
+ app.machineStates['m'] = MachineState(app.stateOf('m')!.machine)
+ ..localOnly = true;
+ connection.pending.last.complete({
+ 'rows': [
+ {'title': 'Old account'},
+ ],
+ });
+ expect(await result, {'error': 'UNAVAILABLE'});
+ final failed = app.readPullRequestsStatus([]);
+ connection.pending.last.completeError(StateError('Disconnected'));
+ expect(await failed, {'error': 'UNAVAILABLE'});
+ app.stateOf('m')!.localOnly = false;
+ expect(await app.readPullRequestsStatus([]), {'error': 'UNAVAILABLE'});
+ });
+}
diff --git a/desktop/test/super_tab_pull_requests_test.dart b/desktop/test/super_tab_pull_requests_test.dart
new file mode 100644
index 000000000..d4396bee1
--- /dev/null
+++ b/desktop/test/super_tab_pull_requests_test.dart
@@ -0,0 +1,404 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/open_in_browser.dart';
+import 'package:harness/super_tabs/controller.dart';
+import 'package:harness/super_tabs/pull_request_entry.dart';
+import 'package:harness/super_tabs/pull_requests.dart';
+
+import 'support/super_tab_fixture.dart';
+
+String prUrl(int number) => 'https://github.com/o/r/pull/$number';
+Map<String, dynamic> prRow(
+ int number, [
+ Map<String, dynamic> values = const {},
+]) => {
+ 'url': prUrl(number),
+ 'title': 'Pull request $number',
+ 'status': 'found',
+ 'state': 'Open',
+ 'updatedAt': '2026-10-22T07:00:00Z',
+ 'mergedAt': '2026-10-22T07:00:00Z',
+ 'closedAt': '2026-10-22T07:00:00Z',
+ 'mergeStateStatus': 'CLEAN',
+ 'reviewDecision': 'APPROVED',
+ 'autoMerge': false,
+ 'checks': {'passed': 14, 'failed': 0, 'pending': 0, 'total': 14},
+ 'additions': 32,
+ 'deletions': 6,
+ ...values,
+};
+List<Map<String, dynamic>> allPrStates() => [
+ prRow(1, {
+ 'checks': {'passed': 12, 'failed': 2, 'pending': 0, 'total': 14},
+ }),
+ prRow(2, {'mergeStateStatus': 'DIRTY'}),
+ prRow(3, {'reviewDecision': 'CHANGES_REQUESTED'}),
+ prRow(4, {'mergeStateStatus': 'BEHIND'}),
+ prRow(5),
+ prRow(6, {
+ 'autoMerge': true,
+ 'checks': {'passed': 9, 'failed': 0, 'pending': 5, 'total': 14},
+ }),
+ prRow(7, {'reviewDecision': 'REVIEW_REQUIRED'}),
+ prRow(8, {
+ 'checks': {'passed': 6, 'failed': 0, 'pending': 8, 'total': 14},
+ }),
+ prRow(9, {
+ 'state': 'Draft',
+ 'checks': {'passed': 0, 'failed': 0, 'pending': 0, 'total': 0},
+ }),
+ for (var n = 10; n < 16; n++)
+ prRow(n, {'state': 'Merged', 'mergedAt': '2026-10-22T0${16 - n}:00:00Z'}),
+ prRow(16, {'state': 'Closed'}),
+ {'url': prUrl(17), 'status': 'no_access'},
+];
+ConversationServer prServer(Iterable<int> numbers) {
+ final server = ConversationServer();
+ server.state['projects'] = [projectFixture('lead', 'Lamp OS', 'lead')];
+ for (final group in server.state['conversations'] as List) {
+ group['projectId'] = 'lead';
+ }
+ for (final number in numbers) {
+ server.append(prUrl(number));
+ }
+ return server;
+}
+
+void main() {
+ final now = DateTime.utc(2026, 10, 22, 8);
+ Future<SuperTabController> mount(
+ WidgetTester tester,
+ ConversationServer server,
+ Future<Map<String, dynamic>> Function(List<String>) read, {
+ bool visible = true,
+ DateTime Function()? clock,
+ }) async {
+ await tester.binding.setSurfaceSize(const Size(1100, 1500));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ final c = server.controller();
+ await c.refresh();
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: SuperTabPullRequests(
+ controller: c,
+ read: read,
+ visible: visible,
+ now: clock ?? () => now,
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ addTearDown(c.dispose);
+ return c;
+ }
+
+ test('every GitHub input maps to the approved label and section, without inventing readiness', () {
+ final rows = allPrStates()
+ .map(SuperTabPullRequestEntry.fromJson)
+ .cast<SuperTabPullRequestEntry>()
+ .toList();
+ expect(rows.map((e) => e.kind), [
+ PullRequestKind.failed,
+ PullRequestKind.conflicts,
+ PullRequestKind.changes,
+ PullRequestKind.behind,
+ PullRequestKind.ready,
+ PullRequestKind.autoMerge,
+ PullRequestKind.review,
+ PullRequestKind.running,
+ PullRequestKind.draft,
+ ...List.filled(6, PullRequestKind.merged),
+ PullRequestKind.closed,
+ PullRequestKind.unknown,
+ ]);
+ expect(rows[0].label, '2 of 14 checks failed');
+ expect(rows[7].label, 'Checks running · 6 of 14 done');
+ expect(rows[8].checksLabel, 'No checks yet');
+ expect(rows.last.label, contains("Can't read status"));
+ expect(
+ SuperTabPullRequestEntry.fromJson(
+ prRow(1, {'mergeStateStatus': 'BLOCKED'}),
+ )!.kind,
+ PullRequestKind.open,
+ );
+ expect(
+ SuperTabPullRequestEntry.fromJson(prRow(1, {'checks': {}}))!.kind,
+ PullRequestKind.open,
+ );
+ expect(
+ SuperTabPullRequestEntry.fromJson({'url': 'https://evil.com/o/r/pull/1'}),
+ isNull,
+ );
+ expect(
+ SuperTabPullRequestEntry.fromJson({'url': prUrl(1), 'status': 'found'})!
+ .kind,
+ PullRequestKind.unknown,
+ );
+ });
+ testWidgets(
+ 'all states have two-line rows in the approved order, five merged, closed collapsed',
+ (tester) async {
+ final rows = allPrStates();
+ await mount(
+ tester,
+ prServer(
+ rows.map((r) => int.parse((r['url'] as String).split('/').last)),
+ ),
+ (_) async => {'rows': rows.reversed.toList()},
+ );
+ for (final text in [
+ 'Needs you 4',
+ 'Open 5',
+ 'Merged 6',
+ 'Closed 1',
+ 'Status unknown 1',
+ 'Show 1 more',
+ '2 of 14 checks failed',
+ 'Conflicts with main',
+ 'Changes requested',
+ 'Behind main',
+ 'Ready to merge',
+ 'Merges when checks pass',
+ 'Waiting for review',
+ 'Checks running · 6 of 14 done',
+ 'Draft',
+ '+32 −6',
+ 'in Lead',
+ ]) {
+ expect(find.text(text), findsWidgets, reason: text);
+ }
+ final ordered = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14];
+ for (var i = 1; i < ordered.length; i++) {
+ expect(
+ tester.getTopLeft(find.text('#${ordered[i - 1]}')).dy,
+ lessThan(tester.getTopLeft(find.text('#${ordered[i]}')).dy),
+ );
+ }
+ expect(find.text('#15'), findsNothing);
+ expect(find.text('#16'), findsNothing);
+ expect(find.text('View status on GitHub'), findsNothing);
+ expect(find.text('Open on GitHub'), findsNothing);
+ await tester.tap(find.text('Show 1 more'));
+ await tester.pumpAndSettle();
+ expect(find.text('#15'), findsOneWidget);
+ await tester.tap(find.text('Closed 1'));
+ await tester.pumpAndSettle();
+ expect(find.text('#16'), findsOneWidget);
+ expect(find.text('Not merged'), findsOneWidget);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+ testWidgets(
+ 'whole row opens the linked PR, including a merged PR whose agent stopped',
+ (tester) async {
+ final opened = <Uri>[], old = browserOpener;
+ browserOpener = (url) async {
+ opened.add(url);
+ return true;
+ };
+ addTearDown(() => browserOpener = old);
+ await mount(
+ tester,
+ prServer([1494]),
+ (_) async => {
+ 'rows': [
+ prRow(1494, {'state': 'Merged', 'title': 'Merged with no agent'}),
+ ],
+ },
+ );
+ expect(find.text('Nothing needs you.'), findsOneWidget);
+ await tester.tap(find.text('Merged with no agent'));
+ expect(opened.single.toString(), prUrl(1494));
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+ testWidgets('first load immediately lists links while GitHub is pending', (
+ tester,
+ ) async {
+ final pending = Completer<Map<String, dynamic>>();
+ await mount(tester, prServer([1, 2]), (_) => pending.future);
+ expect(find.text('#1'), findsOneWidget);
+ expect(find.text('#2'), findsOneWidget);
+ expect(find.text('Checking GitHub…'), findsNWidgets(2));
+ expect(find.text('Linked in this project 2'), findsOneWidget);
+ pending.complete({
+ 'rows': [prRow(1), prRow(2)],
+ });
+ await tester.pumpAndSettle();
+ expect(find.text('Pull request 1'), findsOneWidget);
+ });
+ testWidgets('timeout keeps the last answer and says how old it is', (
+ tester,
+ ) async {
+ var reads = 0;
+ var time = now;
+ await mount(
+ tester,
+ prServer([1]),
+ (_) async => ++reads == 1
+ ? {
+ 'rows': [prRow(1)],
+ }
+ : {'error': 'TIMEOUT'},
+ clock: () => time,
+ );
+ time = time.add(const Duration(minutes: 6));
+ await tester.pump(const Duration(seconds: 60));
+ await tester.pumpAndSettle();
+ expect(find.text('Pull request 1'), findsOneWidget);
+ expect(
+ find.textContaining(
+ "GitHub didn't answer. Showing what it said 6 min ago",
+ ),
+ findsOneWidget,
+ );
+ expect(find.text('· Checked 6 min ago'), findsOneWidget);
+ });
+ for (final code in ['GH_MISSING', 'GH_SIGNED_OUT']) {
+ testWidgets('$code shows one fix banner and keeps links as unknown', (
+ tester,
+ ) async {
+ await mount(tester, prServer([1, 2]), (_) async => {'error': code});
+ expect(find.textContaining('gh auth login'), findsOneWidget);
+ expect(find.text('Status unknown 2'), findsOneWidget);
+ expect(find.text('Status unknown'), findsNWidgets(2));
+ expect(find.text('#1'), findsOneWidget);
+ expect(find.text('· Not checked'), findsOneWidget);
+ });
+ }
+ testWidgets('an inaccessible PR is unknown without a machine banner', (
+ tester,
+ ) async {
+ await mount(
+ tester,
+ prServer([1, 2]),
+ (_) async => {
+ 'rows': [
+ prRow(1),
+ {'url': prUrl(2), 'status': 'no_access'},
+ ],
+ },
+ );
+ expect(find.text('Status unknown 1'), findsOneWidget);
+ expect(find.textContaining("Can't read status:"), findsOneWidget);
+ expect(find.textContaining('Trying again'), findsNothing);
+ });
+ testWidgets(
+ 'empty project uses the approved explanation and makes no GitHub call',
+ (tester) async {
+ var reads = 0;
+ await mount(tester, prServer([]), (_) async {
+ reads++;
+ return {'rows': []};
+ });
+ expect(reads, 0);
+ expect(find.text('No pull requests yet'), findsOneWidget);
+ expect(
+ find.text(
+ 'A GitHub pull request link posted in any chat of this project shows up here with its status.',
+ ),
+ findsOneWidget,
+ );
+ },
+ );
+ testWidgets('older daemon uses the existing agent-based fallback', (
+ tester,
+ ) async {
+ await mount(tester, prServer([1]), (_) async => {'error': 'UNSUPPORTED'});
+ expect(find.textContaining('View status on GitHub'), findsOneWidget);
+ expect(find.textContaining("GitHub didn't answer"), findsNothing);
+ });
+ testWidgets(
+ 'refreshes only open PRs every minute and stops when the pane is hidden',
+ (tester) async {
+ final asks = <List<String>>[];
+ final c = await mount(tester, prServer([1, 2]), (urls) async {
+ asks.add(urls);
+ return {
+ 'rows': [
+ for (final url in urls)
+ prRow(url == prUrl(1) ? 1 : 2, {
+ 'state': url == prUrl(1) ? 'Merged' : 'Open',
+ }),
+ ],
+ };
+ });
+ expect(asks, [
+ [prUrl(1), prUrl(2)],
+ ]);
+ await tester.pump(const Duration(seconds: 59));
+ expect(asks.length, 1);
+ await tester.pump(const Duration(seconds: 1));
+ await tester.pumpAndSettle();
+ expect(asks.last, [prUrl(2)]);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: SuperTabPullRequests(
+ controller: c,
+ visible: false,
+ read: (urls) async {
+ asks.add(urls);
+ return {'rows': []};
+ },
+ ),
+ ),
+ ),
+ );
+ final before = asks.length;
+ await tester.pump(const Duration(minutes: 2));
+ expect(asks.length, before);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+ testWidgets(
+ 'group/project scope and newly posted links update without a selection change',
+ (tester) async {
+ final server = prServer([1]);
+ server.append(prUrl(2), conversationId: 'offline');
+ final asks = <List<String>>[];
+ final c = server.controller();
+ await c.refresh();
+ c.select('offline');
+ await c.loadMessages('offline');
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: SuperTabPullRequests(
+ controller: c,
+ read: (urls) async {
+ asks.add(urls);
+ return {
+ 'rows': urls
+ .map((url) => prRow(int.parse(url.split('/').last)))
+ .toList(),
+ };
+ },
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(asks.last, [prUrl(2)]);
+ expect(find.text('#1'), findsNothing);
+ await tester.tap(find.text('This group'));
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('This project').last);
+ await tester.pumpAndSettle();
+ expect(asks.last.toSet(), {prUrl(1), prUrl(2)});
+ expect(c.selectedId, 'offline');
+ server.append(prUrl(3), conversationId: 'offline');
+ await c.refresh();
+ await tester.pumpAndSettle();
+ expect(asks.last, contains(prUrl(3)));
+ await tester.pumpWidget(const SizedBox());
+ await c.flush();
+ c.dispose();
+ },
+ );
+}
diff --git a/docs/swarms.md b/docs/swarms.md
index 58ecf1e04..0bfca0698 100644
--- a/docs/swarms.md
+++ b/docs/swarms.md
@@ -24,7 +24,15 @@ through the project lead.
The center toolbar switches between chat, terminals and pull requests. The
project's vertical menu contains rename, details, sharing, update cadence and
Swarm routing. A workgroup keeps its own details, rename and archive actions.
-Pull requests in a project lead view include that project's workgroups.
+Pull requests in a project lead view include that project's workgroups. Linked
+GitHub pull requests are read by your computer with its own `gh` login, even after
+an agent stops or changes branches. The pane groups PRs under Needs you, Open,
+Merged, Closed and Status unknown. It refreshes open PRs every minute while
+visible, keeps the last answer when GitHub is unavailable, and shows a single
+banner if `gh` needs installing or signing in. Merged shows the five newest PRs
+with an option to show more; Closed starts collapsed. Clicking a row opens GitHub.
+An older CLI keeps the previous branch-based status display; update the CLI before
+Desktop to enable direct lookups.
## People, agents and machines