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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
feat(desktop): show PR status beside worktree branch (#257)
Leoa9fe7e5800dd
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.tsindex 6b126797e..a941c35be 100644--- a/cli/src/backendSocket.spec.ts+++ b/cli/src/backendSocket.spec.ts@@ -1,3 +1,4 @@+import * as gitPullRequest from './lib/gitPullRequest.js'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { readFileSync } from 'fs'import { homedir } from 'os'@@ -544,6 +545,33 @@ describe('BackendSocket outbound queue', () => {await socket.stop()})+ it('returns PR status only to the requesting encrypted connection', async () => {+ const preview = { status: 'found' as const, number: 12, state: 'Merged' as const, url: 'https://github.com/private/repo/pull/12' }+ vi.spyOn(registry, 'resolve').mockReturnValue({ cwd: '/remote/workspace' } as RegisteredSession)+ const read = vi.spyOn(gitPullRequest, 'readGitPullRequest').mockResolvedValue(preview)+ const socket = new BackendSocket('token')+ socket.connect()+ const ws = wsMock.instances[0]+ ws.open()+ vi.spyOn(socket.e2ee, 'unwrapDown').mockReturnValue({ type: 'git_pull_request', payload: {+ requestId: 'preview-1', agentId: 'agent1',+ } })+ vi.spyOn(socket.e2ee, 'hasSession').mockReturnValue(true)+ const wrap = vi.spyOn(socket.e2ee, 'wrapRpcReply').mockReturnValue({+ type: 'git_pull_request_result', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'encrypted-preview' } },+ })+ ws.message({ t: 'down', connId: 'viewer-a', frame: {+ type: 'git_pull_request', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'encrypted-request' } },+ } })+ await vi.waitFor(() => expect(wrap).toHaveBeenCalledWith('viewer-a', 'git_pull_request_result', 'preview-1', preview))+ expect(read).toHaveBeenCalledWith('/remote/workspace')+ expect(parseSent(ws)).toContainEqual(expect.objectContaining({ targetConnId: 'viewer-a', frame: {+ type: 'git_pull_request_result', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'encrypted-preview' } },+ } }))+ expect(JSON.stringify(parseSent(ws))).not.toContain('github.com/private')+ await socket.stop()+ })+it('returns a correlated Git error when discovery rejects or the path is malformed', async () => {const read = vi.spyOn(gitProject, 'readGitProject').mockRejectedValue(new Error('unavailable'))const socket = new BackendSocket('token')diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex b8d2a34f4..aff639508 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -1,3 +1,4 @@+import { readGitPullRequest } from './lib/gitPullRequest.js'import type { HarnessShareOwner } from './sharing/owner.js'import { SHARE_REQUEST_TYPES } from './sharing/protocol.js'import { AutonomousDeviceRelay } from './lib/autonomous-device/relay.js'@@ -1284,7 +1285,7 @@ export class BackendSocket {private emitReply(connId: string, type: string, requestId: unknown, payload: Record<string, unknown>): void {const resultType = `${type}_result`// Before the E2EE wrap: an RPC reply is only readable here.- if (env.LOG_FRAMES && !type.startsWith('grid_fleet_') && type !== 'agent_read_file' && type !== 'project_preview' && type !== 'git_project_info' && !SHARE_REQUEST_TYPES.has(type)) logFrame('→', connId ? `conn:${sid(connId)}` : 'backend', { type: resultType, payload: { requestId, ...payload } })+ if (env.LOG_FRAMES && !type.startsWith('grid_fleet_') && type !== 'agent_read_file' && type !== 'project_preview' && type !== 'git_project_info' && type !== 'git_pull_request' && !SHARE_REQUEST_TYPES.has(type)) 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@@ -1387,7 +1388,7 @@ export class BackendSocket {// 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 && !type.startsWith('terminal_') && !type.startsWith('viewer_') && !type.startsWith('grid_fleet_') && type !== 'agent_read_file' && type !== 'project_preview' && type !== 'git_project_info' && type !== 'orchestrator' && !SHARE_REQUEST_TYPES.has(type)) {+ if (env.LOG_FRAMES && !type.startsWith('terminal_') && !type.startsWith('viewer_') && !type.startsWith('grid_fleet_') && type !== 'agent_read_file' && type !== 'project_preview' && type !== 'git_project_info' && type !== 'git_pull_request' && type !== 'orchestrator' && !SHARE_REQUEST_TYPES.has(type)) {logFrame('←', connId ? `conn:${sid(connId)}` : 'backend', frame)}const reply = (t: string, rid: unknown, p: Record<string, unknown>): void => this.emitReply(connId, t, rid, p)@@ -2399,6 +2400,14 @@ export class BackendSocket {return}+ case 'git_pull_request': {+ const id = payload.agentId+ const agent = typeof id === 'string' ? registry.resolve(id) : undefined+ if (!agent?.cwd) { reply(type, requestId, { status: 'unavailable' }); return }+ void readGitPullRequest(agent.cwd).then(result => reply(type, requestId, result))+ return+ }+case 'git_project_info': {const path = typeof payload.path === 'string' ? payload.path : ''void readGitProject(path)diff --git a/cli/src/lib/e2ee/applicationFrames.ts b/cli/src/lib/e2ee/applicationFrames.tsindex 057fbc047..31e818d96 100644--- a/cli/src/lib/e2ee/applicationFrames.ts+++ b/cli/src/lib/e2ee/applicationFrames.ts@@ -14,6 +14,6 @@ import { VIEWER_DOWN_TYPES } from '../viewerWire.js'const FLEET_REQUESTS = new Set(['grid_fleet_capabilities', 'grid_fleet_run', 'grid_fleet_cancel'])const FLEET_RESULTS = new Set([...FLEET_REQUESTS].map(type => `${type}_result`))export const encryptDownFrame = (type: string): boolean =>- isEncryptedDownType(type) || type === 'git_project_info' || FLEET_REQUESTS.has(type) || SHARE_REQUEST_TYPES.has(type) || VIEWER_DOWN_TYPES.has(type)+ isEncryptedDownType(type) || (type === 'git_project_info' || type === 'git_pull_request') || FLEET_REQUESTS.has(type) || SHARE_REQUEST_TYPES.has(type) || VIEWER_DOWN_TYPES.has(type)export const encryptRpcResult = (type: string): boolean =>- ENCRYPTED_RPC_RESULT_TYPES.has(type) || type === 'git_project_info_result' || FLEET_RESULTS.has(type) || SHARE_RESULT_TYPES.has(type)+ ENCRYPTED_RPC_RESULT_TYPES.has(type) || (type === 'git_project_info_result' || type === 'git_pull_request_result') || FLEET_RESULTS.has(type) || SHARE_RESULT_TYPES.has(type)diff --git a/cli/src/lib/gitPullRequest.spec.ts b/cli/src/lib/gitPullRequest.spec.tsnew file mode 100644index 000000000..61f74b539--- /dev/null+++ b/cli/src/lib/gitPullRequest.spec.ts@@ -0,0 +1,48 @@+import { describe, it, expect, vi } from 'vitest'+import { createPullRequestReader, githubRepository } from './gitPullRequest.js'+const row = (extra = {}) => ({ number: 12, html_url: 'https://github.com/acme/repo/pull/12', state: 'open', draft: false, merged_at: null, head: { ref: 'feature', repo: { full_name: 'acme/repo' } }, ...extra })+function fixture(rows: unknown = [row()]) {+ let branch = 'feature'+ const run = vi.fn(async (cmd: string, args: string[]) => cmd === 'git'+ ? args[0] === 'symbolic-ref' ? branch : '[email protected]:acme/repo.git'+ : JSON.stringify(args.at(-1)?.includes('/pulls?') ? rows : { full_name: 'acme/repo' }))+ return { run, read: createPullRequestReader(run), branch: (b: string) => { branch = b } }+}+describe('worktree PR status', () => {+ it.each([['https://github.com/acme/repo.git', 'acme/repo'], ['[email protected]:acme/repo.git', 'acme/repo'], ['https://[email protected]/acme/repo', null], ['https://example.com/acme/repo', null]])('validates repository %s', (remote, expected) => expect(githubRepository(remote!)).toBe(expected))+ it.each([['Open', {}], ['Draft', { draft: true }], ['Closed', { state: 'closed' }], ['Merged', { state: 'closed', merged_at: '2026-09-23' }]])('reports %s', async (state, extra) => {+ expect(await fixture([row(extra)]).read('/worktree')).toMatchObject({ status: 'found', state })+ })+ it('distinguishes no PR from missing auth/tool/network', async () => {+ expect(await fixture([]).read('/worktree')).toEqual({ status: 'none' })+ expect(await createPullRequestReader(async () => { throw Error('auth') })('/worktree')).toEqual({ status: 'unavailable' })+ })+ it('prefers an open PR, filters fork collisions, and refuses untrusted URLs', async () => {+ expect(await fixture([row({ state: 'closed', merged_at: 'date' }), row({ draft: true })]).read('/worktree')).toMatchObject({ state: 'Draft' })+ expect(await fixture([row({ head: { ref: 'feature', repo: { full_name: 'other/repo' } } })]).read('/worktree')).toEqual({ status: 'none' })+ expect(await fixture([row({ html_url: 'https://evil.example/pull/12' })]).read('/worktree')).toEqual({ status: 'unavailable' })+ })+ it('coalesces lookups and invalidates when the checked-out branch changes', async () => {+ const f = fixture()+ await Promise.all([f.read('/worktree'), f.read('/worktree')])+ expect(f.run.mock.calls.filter(([cmd, args]) => cmd === 'gh' && args.at(-1)?.includes('/pulls?'))).toHaveLength(1)+ f.branch('another')+ await f.read('/worktree')+ expect(f.run.mock.calls.filter(([cmd, args]) => cmd === 'gh' && args.at(-1)?.includes('/pulls?'))).toHaveLength(2)+ })+ it('uses canonical repository identity after an origin rename', async () => {+ const calls: string[][] = []+ const read = createPullRequestReader(async (cmd, args) => {+ if (cmd === 'git') return args[0] === 'symbolic-ref' ? 'feature' : 'https://github.com/acme/old-name.git'+ calls.push(args)+ return JSON.stringify(args.at(-1)?.includes('/pulls?') ? [row()] : { full_name: 'acme/repo' })+ })+ expect(await read('/worktree')).toMatchObject({ status: 'found', url: 'https://github.com/acme/repo/pull/12' })+ expect(calls[1].at(-1)).toContain('repos/acme/repo/pulls?')+ })+ it('does not execute anything for invalid paths', async () => {+ const f = fixture()+ expect(await f.read('relative')).toEqual({ status: 'unavailable' })+ expect(f.run).not.toHaveBeenCalled()+ })+})diff --git a/cli/src/lib/gitPullRequest.ts b/cli/src/lib/gitPullRequest.tsnew file mode 100644index 000000000..4ccfdf645--- /dev/null+++ b/cli/src/lib/gitPullRequest.ts@@ -0,0 +1,59 @@+import { execFile } from 'node:child_process'+import { promisify } from 'node:util'+import { validGitPath } from './gitProject.js'++const exec = promisify(execFile)+type Run = (command: string, args: string[], cwd: string) => Promise<string>+const run: Run = async (command, args, cwd) => {+ const env = { ...process.env, GH_PROMPT_DISABLED: '1', GIT_TERMINAL_PROMPT: '0', GIT_OPTIONAL_LOCKS: '0' }+ for (const key of ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_COMMON_DIR', 'GIT_INDEX_FILE', 'GIT_NAMESPACE', 'GIT_PREFIX']) delete (env as NodeJS.ProcessEnv)[key]+ return (await exec(command, args, { cwd, env, timeout: 8000, killSignal: 'SIGKILL', maxBuffer: 256 * 1024 })).stdout.trim()+}+export type PullRequestResult = { status: 'none' | 'unavailable' } | {+ status: 'found'; number: number; url: string; state: 'Draft' | 'Open' | 'Merged' | 'Closed'+}+export function githubRepository(remote: string): string | null {+ const match = /^(?:https:\/\/github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)([\w.-]+\/[\w.-]+?)(?:\.git)?\/?$/.exec(remote)+ return match?.[1] ?? null+}+/** Read-only, on the machine owning the checkout. No shell, browser login, fetch or checkout. */+export function createPullRequestReader(execute: Run = run, now = Date.now) {+ const cache = new Map<string, { until: number; value: Promise<PullRequestResult> }>()+ return async (cwd: string): Promise<PullRequestResult> => {+ if (!validGitPath(cwd)) return { status: 'unavailable' }+ try {+ const [branch, remote] = await Promise.all([+ execute('git', ['symbolic-ref', '--quiet', '--short', 'HEAD'], cwd),+ execute('git', ['remote', 'get-url', 'origin'], cwd),+ ])+ const repo = githubRepository(remote)+ if (!repo || !branch) return { status: 'unavailable' }+ const key = JSON.stringify([cwd, repo, branch])+ const previous = cache.get(key)+ if (previous && previous.until > now()) return previous.value+ const value = (async (): Promise<PullRequestResult> => {+ try {+ // GitHub redirects renamed repositories; compare against its canonical identity,+ // not a stale origin spelling (for example autonomous-harness → openharness).+ const metadata = JSON.parse(await execute('gh', ['api', '--hostname', 'github.com', '--jq', '{full_name}', `repos/${repo}`], cwd))+ const canonical = typeof metadata?.full_name === 'string' ? metadata.full_name : ''+ if (!canonical || githubRepository(`https://github.com/${canonical}`) !== canonical) return { status: 'unavailable' }+ const query = new URLSearchParams({ state: 'all', head: `${canonical.split('/')[0]}:${branch}`, sort: 'updated', direction: 'desc', per_page: '100' })+ const rows: unknown = JSON.parse(await execute('gh', ['api', '--hostname', 'github.com', '--jq', 'map({number,html_url,state,draft,merged_at,head:{ref:.head.ref,repo:{full_name:.head.repo.full_name}}})', `repos/${canonical}/pulls?${query}`], cwd))+ if (!Array.isArray(rows)) return { status: 'unavailable' }+ const matches = rows.filter(p => p?.head?.ref === branch && p?.head?.repo?.full_name?.toLowerCase() === canonical.toLowerCase())+ const pr = matches.find(p => p.state === 'open') ?? matches[0]+ if (!pr) return { status: 'none' }+ if (!Number.isSafeInteger(pr.number) || pr.number <= 0 || !['open', 'closed'].includes(pr.state)+ || pr.html_url !== `https://github.com/${canonical}/pull/${pr.number}`) return { status: 'unavailable' }+ return { status: 'found', number: pr.number, url: pr.html_url,+ state: pr.merged_at ? 'Merged' : pr.state === 'closed' ? 'Closed' : pr.draft ? 'Draft' : 'Open' }+ } catch { return { status: 'unavailable' } }+ })()+ cache.set(key, { until: now() + 60_000, value })+ if (cache.size > 128) cache.delete(cache.keys().next().value!)+ return value+ } catch { return { status: 'unavailable' } }+ }+}+export const readGitPullRequest = createPullRequestReader()diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 3840fef62..db0aaf30c 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -6194,6 +6194,14 @@ class AppNotifier extends ChangeNotifier {}}+ /// PR lookup runs on the agent's machine using that machine's GitHub access.+ Future<Map<String, dynamic>> readAgentPullRequest(String machineId, String agentId) async {+ try {+ return await _conn(machineId).request('git_pull_request',+ payload: {'agentId': agentId}, timeout: const Duration(seconds: 30));+ } catch (_) { return {'status': 'unavailable'}; }+ }+/// Reads source material only on the machine that owns the selected path.Future<Map<String, dynamic>> readProjectPreview(String machineId,diff --git a/desktop/lib/widgets/pane_header_actions.dart b/desktop/lib/widgets/pane_header_actions.dartindex 560f8a535..782c642d0 100644--- a/desktop/lib/widgets/pane_header_actions.dart+++ b/desktop/lib/widgets/pane_header_actions.dart@@ -25,6 +25,7 @@ class PaneHeaderActions extends StatelessWidget {this.viewerVisible = false,this.viewerColor,this.details,+ this.trailing,this.modelPicker,this.terminal = false,this.compact = false,@@ -57,6 +58,9 @@ class PaneHeaderActions extends StatelessWidget {/// layers keep their size so hovering never changes the title's width.final Widget? details;+ /// A status link that stays interactive while hover reveals the controls.+ final Widget? trailing;+/// Where this agent runs, shown with the controls rather than beside the name.////// It belongs here for the same reason the icons do: a header this narrow has room for the agent's@@ -198,7 +202,7 @@ class PaneHeaderActions extends StatelessWidget {),);if (details == null) return controls;- return Stack(+ final layers = Stack(alignment: Alignment.centerRight,children: [IgnorePointer(@@ -215,6 +219,15 @@ class PaneHeaderActions extends StatelessWidget {controls,],);+ return trailing == null+ ? layers+ : Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ Flexible(child: layers),+ trailing!,+ ],+ );}}diff --git a/desktop/lib/widgets/pull_request_badge.dart b/desktop/lib/widgets/pull_request_badge.dartnew file mode 100644index 000000000..836d7c675--- /dev/null+++ b/desktop/lib/widgets/pull_request_badge.dart@@ -0,0 +1,117 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:url_launcher/url_launcher.dart';++import '../shared/theme/app_theme.dart' as grid;++/// A separate PR label: branch colour does not encode review state.+class PullRequestBadge extends StatefulWidget {+ const PullRequestBadge({+ super.key,+ required this.identity,+ required this.read,+ this.open,+ });+ final Object identity;+ final Future<Map<String, dynamic>> Function() read;+ final Future<bool> Function(Uri)? open;+ @override+ State<PullRequestBadge> createState() => _PullRequestBadgeState();+}++class _PullRequestBadgeState extends State<PullRequestBadge> {+ Timer? _timer;+ int _revision = 0;+ Map<String, dynamic>? _result;+ @override+ void initState() {+ super.initState();+ _restart();+ }++ @override+ void didUpdateWidget(PullRequestBadge oldWidget) {+ super.didUpdateWidget(oldWidget);+ if (oldWidget.identity != widget.identity) _restart();+ }++ void _restart() {+ _timer?.cancel();+ _result = null;+ final revision = ++_revision;+ unawaited(_refresh(revision));+ }++ Future<void> _refresh(int revision) async {+ Map<String, dynamic> result;+ try {+ result = await widget.read();+ } catch (_) {+ result = {'status': 'unavailable'};+ }+ if (!mounted || revision != _revision) return;+ setState(() => _result = result);+ _timer = Timer(const Duration(seconds: 60), () => _refresh(revision));+ }++ @override+ void dispose() {+ _revision++;+ _timer?.cancel();+ super.dispose();+ }++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ final result = _result;+ if (result?['status'] == 'none') return const SizedBox.shrink();+ final number = result?['number'];+ final state = result?['state'];+ final uri = Uri.tryParse(+ result?['url'] is String ? result!['url'] as String : '',+ );+ final found =+ result?['status'] == 'found' &&+ number is int &&+ number > 0 &&+ const ['Draft', 'Open', 'Merged', 'Closed'].contains(state) &&+ uri?.scheme == 'https' &&+ uri?.host == 'github.com' &&+ uri!.userInfo.isEmpty &&+ uri.path.endsWith('/pull/$number');+ final label = found+ ? 'PR #$number · $state'+ : result == null+ ? 'PR …'+ : 'PR unavailable';+ return Tooltip(+ message: found+ ? 'Open pull request on GitHub'+ : result == null+ ? 'Checking pull request status'+ : 'Could not check GitHub. Check gh installation, sign-in and repository access on the agent’s machine. This does not mean there is no PR.',+ child: TextButton(+ style: TextButton.styleFrom(+ minimumSize: const Size(0, 28),+ padding: const EdgeInsets.symmetric(horizontal: 6),+ textStyle: grid.AppType.monoLabel(),+ ),+ onPressed: found+ ? () async {+ final opened =+ await (widget.open?.call(uri) ??+ launchUrl(uri, mode: LaunchMode.externalApplication));+ if (!opened && context.mounted) {+ ScaffoldMessenger.maybeOf(context)?.showSnackBar(+ const SnackBar(content: Text('Could not open GitHub.')),+ );+ }+ }+ : null,+ child: Text(label, maxLines: 1, overflow: TextOverflow.ellipsis),+ ),+ );+ }+}diff --git a/desktop/lib/widgets/terminal_panel.dart b/desktop/lib/widgets/terminal_panel.dartindex 9133c6e10..f493b2887 100644--- a/desktop/lib/widgets/terminal_panel.dart+++ b/desktop/lib/widgets/terminal_panel.dart@@ -1,3 +1,4 @@+import 'pull_request_badge.dart';import '../shared/theme/prompt_style.dart';import 'prompt_context.dart';import '../sharing/share_harness_dialog.dart';@@ -2063,6 +2064,27 @@ class _TerminalHeader extends StatelessWidget {ConstrainedBox(constraints: BoxConstraints(maxWidth: rightWidth),child: PaneHeaderActions(+ trailing:+ !narrow &&+ rightWidth >= actionsWidth + 180 &&+ agent != null &&+ project?.shownBranch != null+ ? ConstrainedBox(+ constraints: const BoxConstraints(maxWidth: 180),+ child: PullRequestBadge(+ identity: (+ session.machineId,+ agent.id,+ project?.cwd,+ project?.shownBranch,+ ),+ read: () => notifier.readAgentPullRequest(+ session.machineId,+ agent.id,+ ),+ ),+ )+ : null,compact: narrow,// Where this agent runs, with the controls rather than beside the name — the// header has room for one of the two, and this is the half you only read whilediff --git a/desktop/test/pull_request_badge_test.dart b/desktop/test/pull_request_badge_test.dartnew file mode 100644index 000000000..faf6febe3--- /dev/null+++ b/desktop/test/pull_request_badge_test.dart@@ -0,0 +1,114 @@+import 'dart:ui' show PointerDeviceKind;++import 'package:harness/widgets/pane_header_actions.dart';++import 'dart:async';++import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/widgets/pull_request_badge.dart';++void main() {+ Widget frame(+ Object id,+ Future<Map<String, dynamic>> Function() read, {+ Future<bool> Function(Uri)? open,+ }) => MaterialApp(+ home: Scaffold(+ body: PullRequestBadge(identity: id, read: read, open: open),+ ),+ );+ testWidgets('PR remains clickable when hovering reveals header controls', (+ tester,+ ) async {+ var opened = false;+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: SizedBox(+ width: 500,+ child: PaneHeaderHover(+ child: PaneHeaderActions(+ zoomed: false,+ onZoom: () {},+ details: const Text('branch-name'),+ trailing: PullRequestBadge(+ identity: 'branch',+ read: () async => {+ 'status': 'found',+ 'number': 12,+ 'state': 'Open',+ 'url': 'https://github.com/acme/repo/pull/12',+ },+ open: (_) async {+ opened = true;+ return true;+ },+ ),+ ),+ ),+ ),+ ),+ ),+ );+ await tester.pump();+ final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);+ await mouse.addPointer(location: Offset.zero);+ await mouse.moveTo(tester.getCenter(find.text('PR #12 · Open')));+ await tester.pumpAndSettle();+ await tester.tap(find.text('PR #12 · Open'));+ expect(opened, isTrue);+ await mouse.removePointer();+ await tester.pumpWidget(const SizedBox());+ });+ for (final state in ['Draft', 'Open', 'Merged', 'Closed']) {+ testWidgets('labels $state and opens the PR URL', (tester) async {+ Uri? opened;+ await tester.pumpWidget(+ frame(+ 'branch',+ () async => {+ 'status': 'found',+ 'number': 12,+ 'state': state,+ 'url': 'https://github.com/acme/repo/pull/12',+ },+ open: (uri) async {+ opened = uri;+ return true;+ },+ ),+ );+ await tester.pump();+ await tester.tap(find.text('PR #12 · $state'));+ expect(opened.toString(), 'https://github.com/acme/repo/pull/12');+ await tester.pumpWidget(const SizedBox());+ });+ }+ testWidgets('none is hidden but failures are not called no PR', (+ tester,+ ) async {+ await tester.pumpWidget(frame('one', () async => {'status': 'none'}));+ await tester.pump();+ expect(find.byType(TextButton), findsNothing);+ await tester.pumpWidget(+ frame('two', () async => throw Exception('offline')),+ );+ await tester.pump();+ expect(find.text('PR unavailable'), findsOneWidget);+ await tester.pumpWidget(const SizedBox());+ });+ testWidgets(+ 'late result from a previous branch cannot overwrite current status',+ (tester) async {+ final old = Completer<Map<String, dynamic>>();+ await tester.pumpWidget(frame('old', () => old.future));+ await tester.pumpWidget(frame('new', () async => {'status': 'none'}));+ await tester.pump();+ old.complete({'status': 'unavailable'});+ await tester.pump();+ expect(find.text('PR unavailable'), findsNothing);+ await tester.pumpWidget(const SizedBox());+ },+ );+}diff --git a/docs/vi/worktree-pull-requests_vi.md b/docs/vi/worktree-pull-requests_vi.mdnew file mode 100644index 000000000..230683f70--- /dev/null+++ b/docs/vi/worktree-pull-requests_vi.md@@ -0,0 +1,16 @@+# PR bên cạnh branch++Header terminal đủ rộng có link riêng `PR #123 · Draft / Open / Merged / Closed`, giữ nguyên màu+branch. Link vẫn click được khi hover hiện các nút điều khiển. Header hẹp ẩn nhãn để tránh chật.+Click mở GitHub; không merge, checkout hay xoá worktree.++CLI đọc branch và remote `origin` tại thư mục của agent, kể cả linked worktree, rồi dùng `gh` và+phiên đăng nhập GitHub trên máy đó. Đây là truy vấn chỉ đọc, có timeout, không tự mở login. Request+và response được mã hoá khi chuyển tới máy remote.++Tra cứu thành công và không có PR thì ẩn nhãn. Thiếu hỗ trợ CLI, gh, đăng nhập, mạng hoặc quyền repo+thì hiện `PR unavailable`; không được coi là chưa có PR. Refresh mỗi phút, cache CLI 60 giây có giới+hạn, bỏ kết quả cũ khi đổi agent/branch. Ưu tiên PR đang mở; nếu không có, lấy PR cập nhật gần nhất.++Phạm vi ban đầu: repo github.com trong `origin`, khớp cả branch lẫn repository nguồn. Chưa tìm PR từ+fork sang upstream hay GitHub Enterprise. Đã merge không có nghĩa worktree sạch hoặc có thể xoá.diff --git a/docs/worktree-pull-requests.md b/docs/worktree-pull-requests.mdnew file mode 100644index 000000000..887d675e8--- /dev/null+++ b/docs/worktree-pull-requests.md@@ -0,0 +1,21 @@+# Pull requests beside the branch++Wide terminal headers show a separate `PR #123 · Draft / Open / Merged / Closed` link next to+branch context. The branch keeps its existing colour. The link remains clickable when hovering+reveals the pane controls; compact headers omit it to preserve room for the agent and controls.+Clicking opens GitHub. Nothing merges a PR, changes a checkout, or deletes a worktree.++The CLI resolves the current branch and `origin` of the registered agent's working directory,+including linked worktrees. It uses the existing `gh` installation and GitHub sign-in on that+machine, via a bounded read-only subprocess (no interactive login). Both request and response are+encrypted when relayed to another machine. Device/admin operations are not exposed.++A successful empty lookup hides the badge. Missing CLI support, `gh`, authentication, network or+repository access shows `PR unavailable`, with an explanation; it must not be treated as no PR.+The widget refreshes once a minute and discards replies from previous agent/branch identities.+CLI requests share a bounded 60-second cache. An open PR wins over an older closed/merged PR for+the same branch; otherwise the most recently updated matching PR is shown.++Initial scope: github.com repositories referenced by `origin`, matching both head branch and head+repository. Fork-to-upstream PRs and GitHub Enterprise are not resolved. Merge status says nothing+about uncommitted local changes or whether deleting the worktree is safe.