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.

Polish session branches and lead with recent Git work (#411)

Dee0eeef83b5e17
diff --git a/cli/src/lib/sessionGitContext.spec.ts b/cli/src/lib/sessionGitContext.spec.ts
index db29e76cb..0a53726fa 100644
--- a/cli/src/lib/sessionGitContext.spec.ts
+++ b/cli/src/lib/sessionGitContext.spec.ts
@@ -46,6 +46,7 @@ describe('Git context from observed session work', () => {
const context = await sessionGitContext(launch, observation)
expect(context).toMatchObject({ state: 'multiple', current: null })
expect(context.checkouts?.map(p => p.branch)).toEqual(['original', 'hn/preview-fix'])
+ expect(context.recentWork).toMatchObject({ project: { branch: 'hn/preview-fix' }, at })
expect(launch?.branch).toBe('original')
const session = { agentId: 'hn', sessionId: 's', engine: 'claude', cwd: home,
registeredAt: 1, boundAt: 1, lastHookAt: 1, transcriptPath: null, runtimes: [],
@@ -54,6 +55,7 @@ describe('Git context from observed session work', () => {
tokenUsage: { totalTokens: null, updatedAt: at, work: observation } })
expect(frame.project?.branch).toBe('original')
expect(frame.gitContext.checkouts?.map(p => p.branch)).toEqual(['original', 'hn/preview-fix'])
+ expect(frame.gitContext.recentWork?.project.branch).toBe('hn/preview-fix')
expect(session.cwd).toBe(home)
})
@@ -103,4 +105,16 @@ describe('Git context from observed session work', () => {
expect(context).toMatchObject({ state: 'unavailable', current: null, truncated: true, pullRequests })
expect(read).toHaveBeenCalledTimes(8)
})
+
+ it('retains recent Git work across unrelated non-Git activity without claiming parallel work has one branch', async () => {
+ const home = { name: 'app', cwd: '/home', root: '/home', branch: 'original', remote: null }
+ const read = async (cwd: string) => ({ ...home, cwd, root: cwd === '/notes' ? null : cwd,
+ branch: cwd === '/notes' ? null : cwd === '/ship' ? 'shipping' : 'other' })
+ const locations = [{ cwd: '/notes', at: '2026-09-28T01:00:00Z' }, { cwd: '/ship', at }]
+ const recent = await sessionGitContext(home, work(['/notes'], { locations, uncertain: true }), read)
+ expect(recent.recentWork).toMatchObject({ project: { branch: 'shipping' }, at })
+ expect((await sessionGitContext(home, work(['/ship', '/other']), read)).recentWork).toBeUndefined()
+ expect((await sessionGitContext(home, work(['/ship', '/missing']), async cwd => cwd === '/missing' ? null : read(cwd))).recentWork).toBeUndefined()
+ expect((await sessionGitContext(home)).recentWork).toBeUndefined()
+ })
})
diff --git a/cli/src/lib/sessionGitContext.ts b/cli/src/lib/sessionGitContext.ts
index 259f3e2b4..d997cf746 100644
--- a/cli/src/lib/sessionGitContext.ts
+++ b/cli/src/lib/sessionGitContext.ts
@@ -10,6 +10,8 @@ export type SessionGitContext = {
current: AgentProject | null
/** Git snapshots of session-associated checkouts. Paths are internal identity, not UI labels. */
checkouts?: AgentProject[]
+ /** Branch in the most recently confirmed Git location, not a claim of live execution. */
+ recentWork?: { project: AgentProject; at: string }
observedAt: string | null
/** The location is confirmed historical work; newer tool activity could not yet be resolved. */
activityUncertain?: boolean
@@ -71,6 +73,7 @@ export async function sessionGitContext(home: AgentProject | null, work?: Sessio
checkouts: [],
}
const roots = new Map<string, AgentProject>()
+ const resolved = new Map<string, AgentProject | null>()
const add = (project: AgentProject | null) => {
if (project?.root && !roots.has(project.root)) roots.set(project.root, { ...project, cwd: project.root })
}
@@ -84,11 +87,35 @@ export async function sessionGitContext(home: AgentProject | null, work?: Sessio
])]
let reads = 0
for (const cwd of paths) {
- if (roots.has(cwd)) continue
+ if (roots.has(cwd)) { resolved.set(cwd, roots.get(cwd)!); continue }
// A subdirectory can itself be a nested repository/worktree. Resolve it through Git,
// never assume path containment proves checkout identity. Bound additional lookups.
if (reads++ === 8) { context.truncated = true; break }
- add(await read(cwd).catch(() => null))
+ const project = await read(cwd).catch(() => null)
+ resolved.set(cwd, project)
+ add(project)
+ }
+ // A later command outside Git does not erase the last useful coding context.
+ // Same-time locations are one operation: never select one member of parallel work,
+ // or a partially inspected group, as the session's unique recent branch.
+ const activity = [...(work?.current ?? []), ...(work?.locations ?? [])]
+ const times = [...new Set(activity.map(row => row.at))].sort((a, b) => Date.parse(b) - Date.parse(a))
+ for (const at of times) {
+ const locations = activity.filter(row => row.at === at)
+ const projects = locations.map(row => resolved.get(row.cwd))
+ const git = new Map<string, AgentProject>()
+ for (const project of projects) {
+ const fresh = project?.root ? roots.get(project.root) : null
+ if (fresh?.branch && !fresh.branchPending && !fresh.branch.startsWith('Detached ')) {
+ git.set(JSON.stringify([fresh.remote ?? fresh.root, fresh.branch]), fresh)
+ }
+ }
+ if (!git.size) continue
+ if (git.size === 1 && projects.every(project => project != null && !project.branchPending
+ && (!project.root || project.branch && !project.branch.startsWith('Detached ')))) {
+ context.recentWork = { project: [...git.values()][0], at }
+ }
+ break
}
// Different files in one checkout are one useful workspace in the details view. Only collapse
// paths under roots Git actually resolved; similarly named sibling worktrees remain distinct.
diff --git a/cli/src/lib/sessionGitPullRequest.spec.ts b/cli/src/lib/sessionGitPullRequest.spec.ts
index ad24798fc..07d262fc7 100644
--- a/cli/src/lib/sessionGitPullRequest.spec.ts
+++ b/cli/src/lib/sessionGitPullRequest.spec.ts
@@ -181,7 +181,19 @@ describe('session work from transcript through Git and PR history', () => {
})
expect(await readSessionGitPullRequest(agent, {
expected: { cwd: ship, branch: 'hn/nfc', remote: 'github.com/acme/app' },
- })).toMatchObject({ status: 'unavailable', context: null })
+ })).toMatchObject({ status: 'unavailable', context: { cwd: home, branch: 'original', remote: 'github.com/acme/app' } })
+ })
+
+ it('binds the header PR to recent work while retaining the assigned checkout and other branches', async () => {
+ await receipt('ship', join(ship, 'tui'))
+ const value = await frame()
+ expect(value.project?.branch).toBe('original')
+ expect(value.gitContext).toMatchObject({ state: 'multiple', current: null,
+ recentWork: { project: { cwd: ship, branch: 'hn/nfc' } } })
+ const expected = { cwd: ship, branch: 'hn/nfc', remote: 'github.com/acme/app' }
+ expect(await readSessionGitPullRequest(agent, { expected })).toMatchObject({ status: 'found', number: 12, context: expected })
+ expect((await readSessionGitPullRequest(agent, { expected: { ...expected, cwd: home, branch: 'original' } })).status).toBe('unavailable')
+ expect(agent.cwd).toBe(home)
})
it('refreshes the visible open-first page, including multiple PRs for one branch', async () => {
diff --git a/cli/src/lib/sessionGitPullRequest.ts b/cli/src/lib/sessionGitPullRequest.ts
index 8a5216f05..968b9f6f0 100644
--- a/cli/src/lib/sessionGitPullRequest.ts
+++ b/cli/src/lib/sessionGitPullRequest.ts
@@ -21,7 +21,7 @@ export async function readSessionGitPullRequest(agent: RegisteredSession, option
}
let context = await resolve()
await sessionGitHistory.observe(agent, context)
- const current = context.current
+ const current = context.recentWork?.project ?? context.current
let identity = current?.branch ? { cwd: current.cwd, branch: current.branch, remote: current.remote } : null
const matches = !options.expected || identity && options.expected.cwd === identity.cwd
&& options.expected.branch === identity.branch && options.expected.remote === identity.remote
@@ -39,7 +39,7 @@ export async function readSessionGitPullRequest(agent: RegisteredSession, option
if (JSON.stringify(latest) === JSON.stringify(work)) return
context = await resolve(latest)
await sessionGitHistory.observe(agent, context)
- const project = context.current
+ const project = context.recentWork?.project ?? context.current
identity = project?.branch ? { cwd: project.cwd, branch: project.branch, remote: project.remote } : null
result = { status: 'unavailable' }
}
diff --git a/desktop/design/images/session-branches-completed.png b/desktop/design/images/session-branches-completed.png
new file mode 100644
index 000000000..6402ab49f
Binary files /dev/null and b/desktop/design/images/session-branches-completed.png differ
diff --git a/desktop/design/images/session-branches.png b/desktop/design/images/session-branches.png
new file mode 100644
index 000000000..b93fec99f
Binary files /dev/null and b/desktop/design/images/session-branches.png differ
diff --git a/desktop/design/workspace-status-bar.md b/desktop/design/workspace-status-bar.md
index d316093f9..fd6298397 100644
--- a/desktop/design/workspace-status-bar.md
+++ b/desktop/design/workspace-status-bar.md
@@ -121,13 +121,33 @@ empty tab.
Each field is independently clickable, with the same bold hover/keyboard-focus
text and hand cursor as the status symbols. Machine opens the shared picker scoped by machine
identity; project opens its harnesses across matching remote checkouts; branch
-opens the focused session's Work details when the daemon supplies `gitContext`.
-Details distinguish current observed work from the launch workspace and retain
-observed branches and PRs across tasks. Escape returns focus to the terminal.
+opens the focused session's branches and PRs when the daemon supplies `gitContext`.
+When recent successful work identifies one Git branch, show its name followed
+by the count of other checked-out branches, for example `ship-hn · +3`. The
+tooltip explains that this is recent confirmed work and gives its observation
+time. Git remains the source of branch names for every engine. When several
+branches have equal recent evidence, show the count instead of selecting one.
+
+Details group each branch with its PRs, put recent work and open PRs first, and
+fold completed work behind one action. Show a shared repository once, align PR
+states on the right, and keep head/base names and check times in inspection
+details. Size the dialog to its contents with bounded scrolling. Escape returns
+focus to the terminal.
Older daemons keep exact-branch project search, with Escape returning through its
scopes. Names never establish identity. Branch navigation does not check out or
create a branch. Unknown/multiple/unavailable work uses plain muted context text,
-without a Git branch symbol; the same action remains inspectable.
+without a Git branch symbol when no single branch is displayed; the same action
+remains inspectable.
+
+![Session branches with synthetic data](images/session-branches.png)
+
+![Completed PRs expanded](images/session-branches-completed.png)
+
+Render these fixtures with `HARNESS_GIT_CONTEXT_CAPTURE_DIR=/tmp/work-dialog
+flutter test test/session_work_dialog_test.dart`. Local macOS captures load the
+system SF Mono face at 18 pt; the dialog itself follows the selected terminal
+font, size and palette. The same suite checks narrow windows, enlarged text,
+alternate palettes, and retained keyboard focus when appearance changes.
Customize Harness → Status offers twelve saved themes, grouped into Minimal
and Powerline, with a preview of the same sample pane beneath each choice.
diff --git a/desktop/lib/core/agent_git_context.dart b/desktop/lib/core/agent_git_context.dart
index 03985b57e..60936ce9c 100644
--- a/desktop/lib/core/agent_git_context.dart
+++ b/desktop/lib/core/agent_git_context.dart
@@ -51,6 +51,7 @@ typedef AgentWorkPr = ({
typedef AgentBranchRow = ({
String branch,
String? repository,
+ String repositoryKey,
bool checkedOut,
List<AgentWorkPr> pullRequests,
});
@@ -61,6 +62,8 @@ class AgentGitContext {
required this.state,
this.current,
this.checkouts,
+ this.recentWork,
+ this.recentWorkAt,
this.observedAt,
this.activityUncertain = false,
this.locations = const [],
@@ -73,6 +76,8 @@ class AgentGitContext {
final String state;
final AgentProject? current;
final List<AgentProject>? checkouts;
+ final AgentProject? recentWork;
+ final DateTime? recentWorkAt;
final DateTime? observedAt;
final bool activityUncertain;
final List<AgentWorkLocation> locations;
@@ -83,6 +88,12 @@ class AgentGitContext {
final int revision;
List<AgentProject> get checkedOut => checkouts ?? [?current];
+ AgentProject? get focusedProject => recentWork ?? current;
+ bool isRecentBranch(AgentBranchRow row) =>
+ recentWork != null &&
+ row.branch == recentWork!.shownBranch &&
+ row.repositoryKey ==
+ (recentWork!.remote ?? recentWork!.root ?? recentWork!.cwd);
/// Repository + branch is the visible identity. Paths only disambiguate local
/// repositories without a remote; temporary folder names never become labels.
@@ -94,6 +105,7 @@ class AgentGitContext {
rows[key] = (
branch: branch,
repository: repository,
+ repositoryKey: key.$1,
checkedOut: checkedOut || previous?.checkedOut == true,
pullRequests: previous?.pullRequests ?? <AgentWorkPr>[],
);
@@ -121,6 +133,9 @@ class AgentGitContext {
String? get branchLabel {
final checked = branchRows.where((row) => row.checkedOut).toList();
+ if (recentWork?.shownBranch case final branch?) {
+ return checked.length > 1 ? '$branch · +${checked.length - 1}' : branch;
+ }
if (checked.length > 1) return '${checked.length} branches';
if (checked.length == 1) return checked.single.branch;
if (current?.detached == true) return 'Detached';
@@ -130,15 +145,17 @@ class AgentGitContext {
return state == 'unavailable' ? 'Git unavailable' : null;
}
- String get explanation => switch (state) {
- 'multiple' => 'Branches checked out for this session.',
- 'uncertain' || 'unavailable' =>
- 'Git is unavailable. Showing saved branches and pull requests.',
- _ => 'Branch checked out for this session.',
- };
+ String get explanation => recentWork != null
+ ? 'Branch in the most recent confirmed work location${recentWorkAt == null ? '.' : ' · ${localWorkTime(recentWorkAt!)}'}'
+ : switch (state) {
+ 'multiple' => 'Branches checked out for this session.',
+ 'uncertain' || 'unavailable' =>
+ 'Git is unavailable. Showing saved branches and pull requests.',
+ _ => 'Branch checked out for this session.',
+ };
AgentProject? displayProject(AgentProject? launch) {
- if (current != null) return current;
+ if (focusedProject != null) return focusedProject;
if (launch == null) return null;
// Keep useful repository context without presenting the launch branch as current work.
return AgentProject(
@@ -151,7 +168,7 @@ class AgentGitContext {
}
Map<String, Object?>? get requestIdentity {
- final project = current;
+ final project = focusedProject;
if (project == null || project.shownBranch == null) return null;
return {
'cwd': project.cwd,
@@ -166,6 +183,8 @@ class AgentGitContext {
state == other.state &&
current == other.current &&
listEquals(checkouts, other.checkouts) &&
+ recentWork == other.recentWork &&
+ recentWorkAt == other.recentWorkAt &&
observedAt == other.observedAt &&
activityUncertain == other.activityUncertain &&
truncated == other.truncated &&
@@ -179,6 +198,8 @@ class AgentGitContext {
state,
current,
checkouts == null ? null : Object.hashAll(checkouts!),
+ recentWork,
+ recentWorkAt,
observedAt,
activityUncertain,
truncated,
@@ -274,18 +295,30 @@ class AgentGitContext {
if (prs.length == 128) break;
}
final version = raw['version'];
+ final checkouts = raw['checkouts'] is List
+ ? List<AgentProject>.unmodifiable(
+ rows(raw['checkouts'])
+ .map(AgentProject.fromJson)
+ .whereType<AgentProject>(),
+ )
+ : null;
+ final recent = raw['recentWork'];
+ final recentProject = recent is Map
+ ? AgentProject.fromJson(recent['project'])
+ : null;
+ final recentAt = recent is Map ? date(recent['at']) : null;
+ final verifiedRecent =
+ recentProject?.shownBranch != null &&
+ recentAt != null &&
+ (checkouts?.any((project) => project == recentProject) ?? false);
return AgentGitContext(
state: raw['state'] as String,
current: const ['workspace', 'observed'].contains(raw['state'])
? AgentProject.fromJson(raw['current'])
: null,
- checkouts: raw['checkouts'] is List
- ? List.unmodifiable(
- rows(raw['checkouts'])
- .map(AgentProject.fromJson)
- .whereType<AgentProject>(),
- )
- : null,
+ checkouts: checkouts,
+ recentWork: verifiedRecent ? recentProject : null,
+ recentWorkAt: verifiedRecent ? recentAt : null,
observedAt: date(raw['observedAt']),
activityUncertain: raw['activityUncertain'] == true,
locations: List.unmodifiable(locations),
diff --git a/desktop/lib/widgets/session_work_dialog.dart b/desktop/lib/widgets/session_work_dialog.dart
index 9de88dee9..a72b01de2 100644
--- a/desktop/lib/widgets/session_work_dialog.dart
+++ b/desktop/lib/widgets/session_work_dialog.dart
@@ -33,7 +33,7 @@ class SessionWorkDialog extends StatefulWidget {
class _SessionWorkDialogState extends State<SessionWorkDialog> {
AgentGitContext? _data;
- bool _loading = false;
+ bool _loading = false, _showCompleted = false;
String? _error;
int? _nextOffset;
int _revision = 0, _visiblePrs = 4;
@@ -80,7 +80,7 @@ class _SessionWorkDialogState extends State<SessionWorkDialog> {
}
}
} else {
- _error = 'Work history is unavailable. Showing saved observations.';
+ _error = 'History unavailable · showing saved data';
}
});
}
@@ -120,35 +120,97 @@ class _SessionWorkDialogState extends State<SessionWorkDialog> {
color: theme.foreground.withValues(alpha: .65),
);
final data = _data;
- final branchRows = data?.branchRows ?? <AgentBranchRow>[];
- final showRepositories =
- branchRows.map((row) => row.repository).toSet().length > 1;
+ final branches = [...?data?.branchRows];
+ branches.sort((a, b) {
+ final recent =
+ (data?.isRecentBranch(b) == true ? 1 : 0) -
+ (data?.isRecentBranch(a) == true ? 1 : 0);
+ if (recent != 0) return recent;
+ bool open(AgentBranchRow row) => row.pullRequests.any(
+ (pr) => pr.state == 'Open' || pr.state == 'Draft',
+ );
+ final review = (open(b) ? 1 : 0) - (open(a) ? 1 : 0);
+ if (review != 0) return review;
+ final checked = (b.checkedOut ? 1 : 0) - (a.checkedOut ? 1 : 0);
+ return checked != 0 ? checked : a.branch.compareTo(b.branch);
+ });
+ final repositories = branches.map((row) => row.repository).toSet();
+ final commonRepository = repositories.length == 1
+ ? repositories.single
+ : null;
+ String repositoryName(String repository) =>
+ repository.replaceFirst(RegExp(r'^github\.com/'), '');
final prs = [...?data?.pullRequests];
int rank(AgentWorkPr pr) => switch (pr.state) {
'Open' || 'Draft' => 0,
'Merged' || 'Closed' => 2,
_ => 1,
};
- prs.sort((a, b) {
+ int comparePrs(AgentWorkPr a, AgentWorkPr b) {
final order = rank(a).compareTo(rank(b));
if (order != 0) return order;
final recency = b.at.compareTo(a.at);
return recency != 0
? recency
: a.url.toString().compareTo(b.url.toString());
- });
- Widget line(String text, {bool dim = false}) => SizedBox(
+ }
+
+ prs.sort(comparePrs);
+ bool completed(AgentWorkPr pr) =>
+ pr.state == 'Merged' || pr.state == 'Closed';
+ final recentUrls = branches
+ .where((b) => data?.isRecentBranch(b) == true)
+ .expand((b) => b.pullRequests.map((pr) => pr.url))
+ .toSet();
+ final completedCount = prs
+ .where((pr) => completed(pr) && !recentUrls.contains(pr.url))
+ .length;
+ bool completedBranch(AgentBranchRow branch) =>
+ data?.isRecentBranch(branch) != true &&
+ branch.pullRequests.isNotEmpty &&
+ branch.pullRequests.every(completed);
+ final ongoingPrs =
+ prs
+ .where((pr) => !completed(pr) || recentUrls.contains(pr.url))
+ .toList()
+ ..sort((a, b) {
+ final recent =
+ (recentUrls.contains(b.url) ? 1 : 0) -
+ (recentUrls.contains(a.url) ? 1 : 0);
+ return recent != 0 ? recent : comparePrs(a, b);
+ });
+ final completedPrs = prs
+ .where((pr) => completed(pr) && !recentUrls.contains(pr.url))
+ .toList();
+ final visibleUrls = {
+ ...ongoingPrs.take(_visiblePrs).map((pr) => pr.url),
+ if (_showCompleted)
+ ...completedPrs.take(_visiblePrs).map((pr) => pr.url),
+ };
+ final groupedUrls = branches
+ .expand((branch) => branch.pullRequests.map((pr) => pr.url))
+ .toSet();
+ final ungrouped = prs.where(
+ (pr) => visibleUrls.contains(pr.url) && !groupedUrls.contains(pr.url),
+ );
+ Widget text(String value, {bool dim = false}) => Text(
+ value,
+ style: dim ? muted : style,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ );
+ Widget line(String value, {bool dim = false}) => SizedBox(
height: cell.height,
child: Tooltip(
- message: text,
- child: Text(
- text,
- style: dim ? muted : style,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- ),
+ message: value,
+ child: text(value, dim: dim),
),
);
+ final summary = [
+ if (commonRepository != null) repositoryName(commonRepository),
+ '${branches.length} ${branches.length == 1 ? 'branch' : 'branches'}',
+ '${prs.length} ${prs.length == 1 ? 'PR' : 'PRs'}',
+ ].join(' · ');
return Dialog(
backgroundColor: theme.background,
elevation: 0,
@@ -160,84 +222,56 @@ class _SessionWorkDialogState extends State<SessionWorkDialog> {
borderRadius: BorderRadius.circular(kTerminalCornerRadius),
side: terminalPaneBorder(focused: true),
),
- child: SizedBox(
- width: cell.width * 84,
- height: math.max(
- 0,
- math.min(
- MediaQuery.sizeOf(context).height - cell.height * 4,
- cell.height * 30,
+ child: ConstrainedBox(
+ key: const ValueKey('work-dialog-surface'),
+ constraints: BoxConstraints(
+ maxHeight: math.max(
+ 0,
+ math.min(
+ MediaQuery.sizeOf(context).height - cell.height * 4,
+ cell.height * 28,
+ ),
),
),
- child: Padding(
- padding: EdgeInsets.symmetric(
- horizontal: cell.width * 2,
- vertical: cell.height,
- ),
- child: Focus(
- onKeyEvent: (node, event) {
- if (event is! KeyDownEvent) return KeyEventResult.ignored;
- if (event.logicalKey == LogicalKeyboardKey.arrowDown) {
- FocusScope.of(context).nextFocus();
- return KeyEventResult.handled;
- }
- if (event.logicalKey == LogicalKeyboardKey.arrowUp) {
- FocusScope.of(context).previousFocus();
- return KeyEventResult.handled;
- }
- return KeyEventResult.ignored;
- },
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- line(
- '${widget.agent.displayName} · Branches and pull requests',
- ),
- line(
- widget.online
- ? data?.explanation ??
- 'Branches and pull requests for this session.'
- : 'Offline · saved branches and pull requests',
- dim: true,
- ),
- SizedBox(height: cell.height),
- Expanded(
- child: ListView(
- children: [
- line('Branches (${branchRows.length})'),
- if (branchRows.isEmpty)
- line(
- data?.branchLabel ?? 'No branches recorded yet.',
- dim: true,
- ),
- for (final branch in branchRows) ...[
- line(
- '${branch.branch}${branch.checkedOut ? ' · Checked out' : ''}',
- ),
- if (showRepositories && branch.repository != null)
- line(branch.repository!, dim: true),
- if (branch.pullRequests.isNotEmpty)
- line(
- branch.pullRequests
- .map(
- (pr) =>
- '#${pr.url.pathSegments.last} ${pr.state ?? 'State unknown'}',
- )
- .join(' · '),
- dim: true,
- ),
- ],
- SizedBox(height: cell.height),
- line('Pull requests (${prs.length})'),
- if (prs.isEmpty)
- line(
- 'No pull requests observed for this session.',
- dim: true,
- ),
- for (final pr in prs.take(_visiblePrs)) ...[
- SizedBox(
- key: ValueKey('work-pr-row-${pr.url}'),
- height: cell.height,
+ child: SizedBox(
+ width: cell.width * 80,
+ child: Padding(
+ padding: EdgeInsets.symmetric(
+ horizontal: cell.width * 2,
+ vertical: cell.height,
+ ),
+ child: LayoutBuilder(
+ builder: (context, constraints) {
+ final compact = constraints.maxWidth < cell.width * 52;
+ final rows = <Widget>[];
+ void separate() {
+ if (rows.isNotEmpty) {
+ rows.add(SizedBox(height: cell.height));
+ }
+ }
+
+ void addPr(AgentWorkPr pr) {
+ final number = '#${pr.url.pathSegments.last}';
+ final state = pr.state ?? 'Unknown';
+ final title =
+ pr.title ?? pr.url.pathSegments.take(2).join('/');
+ final details = [
+ '$number · $title · $state',
+ pr.url.pathSegments.take(2).join('/'),
+ if (pr.headBranch != null)
+ '${pr.headBranch}${pr.baseBranch == null ? '' : ' → ${pr.baseBranch}'}',
+ if (pr.checkedAt != null)
+ 'Checked ${localWorkTime(pr.checkedAt!)}',
+ 'Open on GitHub',
+ ].join('\n');
+ rows.add(
+ Padding(
+ key: ValueKey('work-pr-row-${pr.url}'),
+ padding: EdgeInsets.only(left: cell.width * 2),
+ child: SizedBox(
+ height: cell.height,
+ child: Tooltip(
+ message: details,
child: TextButton(
key: ValueKey('work-pr-${pr.url}'),
onPressed: () => unawaited(_open(pr.url)),
@@ -267,79 +301,273 @@ class _SessionWorkDialogState extends State<SessionWorkDialog> {
: Colors.transparent,
),
),
- child: Tooltip(
- message: '${pr.title ?? ''} · ${pr.url}',
- child: Text(
- '#${pr.url.pathSegments.last} ${pr.state ?? 'State unknown'} ${pr.title ?? pr.url.pathSegments.take(2).join('/')}',
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- semanticsLabel:
- '${pr.title ?? ''} · ${pr.url} · ${pr.state ?? 'State unknown'} · Open on GitHub',
+ child: Semantics(
+ label: details.replaceAll('\n', ' · '),
+ excludeSemantics: true,
+ child: Row(
+ children: [
+ if (compact)
+ Expanded(child: text(number))
+ else ...[
+ SizedBox(
+ width: cell.width * 7,
+ child: text(number, dim: true),
+ ),
+ Expanded(child: text(title)),
+ ],
+ SizedBox(width: cell.width * 2),
+ text(state, dim: true),
+ ],
),
),
),
),
- if (pr.headBranch case final branch?)
- line(
- '${pr.url.pathSegments.take(2).join('/')} · $branch${pr.baseBranch == null ? '' : ' → ${pr.baseBranch}'}',
- dim: true,
- ),
- if (_unavailable.contains(pr.url.toString()))
- line(
- 'GitHub unavailable · showing last known state',
- dim: true,
- )
- else if (pr.checkedAt case final at?)
- line('Checked ${localWorkTime(at)}', dim: true),
- ],
- if (_nextOffset != null || prs.length > _visiblePrs)
- Align(
- alignment: Alignment.centerLeft,
- child: TerminalTextAction(
- label: 'Show more',
- onPressed: _loading
- ? null
- : () {
- final offset =
- _nextOffset ?? _visiblePrs;
- setState(() => _visiblePrs += 4);
- if (widget.online) {
- unawaited(_refresh(offset));
- }
- },
+ ),
+ ),
+ );
+ if (compact) {
+ rows.add(
+ Padding(
+ padding: EdgeInsets.only(left: cell.width * 2),
+ child: MouseRegion(
+ cursor: SystemMouseCursors.click,
+ child: GestureDetector(
+ onTap: () => unawaited(_open(pr.url)),
+ child: ExcludeSemantics(
+ child: line(title, dim: true),
+ ),
),
),
- SizedBox(height: cell.height),
+ ),
+ );
+ }
+ if (_unavailable.contains(pr.url.toString())) {
+ rows.add(
+ Padding(
+ padding: EdgeInsets.only(left: cell.width * 2),
+ child: line(
+ 'GitHub unavailable · saved status',
+ dim: true,
+ ),
+ ),
+ );
+ }
+ }
+
+ void addBranch(AgentBranchRow branch) {
+ final visiblePrs =
+ branch.pullRequests
+ .where((pr) => visibleUrls.contains(pr.url))
+ .toList()
+ ..sort(comparePrs);
+ // Keep checked-out and PR-less branches visible. Completed groups
+ // outside this page appear with their PRs when Show more is chosen.
+ if (!branch.checkedOut &&
+ branch.pullRequests.isNotEmpty &&
+ visiblePrs.isEmpty) {
+ return;
+ }
+ separate();
+ if (commonRepository == null &&
+ branch.repository != null) {
+ rows.add(
+ line(repositoryName(branch.repository!), dim: true),
+ );
+ }
+ rows.add(
+ SizedBox(
+ height: cell.height,
+ child: Row(
+ children: [
+ Expanded(
+ child: Tooltip(
+ message: branch.branch,
+ child: text(branch.branch),
+ ),
+ ),
+ if (branch.checkedOut && !compact) ...[
+ SizedBox(width: cell.width * 2),
+ Tooltip(
+ message: data?.isRecentBranch(branch) == true
+ ? data!.explanation
+ : 'Branch currently checked out in a location associated with this session.',
+ child: text(
+ data?.isRecentBranch(branch) == true
+ ? 'Recent work'
+ : 'Checked out',
+ dim: true,
+ ),
+ ),
+ ],
+ ],
+ ),
+ ),
+ );
+ if (branch.checkedOut && compact) {
+ rows.add(
line(
- data?.truncated == true
- ? 'Older observations are omitted.'
- : 'History includes recorded branches and PRs; earlier activity may be missing.',
+ data?.isRecentBranch(branch) == true
+ ? 'Recent work'
+ : 'Checked out',
dim: true,
),
- ],
- ),
- ),
- if (_error != null) line(_error!),
- SizedBox(
- width: double.infinity,
- child: Wrap(
- alignment: WrapAlignment.spaceBetween,
+ );
+ }
+ for (final pr in visiblePrs) {
+ addPr(pr);
+ }
+ }
+
+ for (final branch in branches.where(
+ (b) => !completedBranch(b),
+ )) {
+ addBranch(branch);
+ }
+ final otherOpenPrs = ungrouped.where(
+ (pr) => !completed(pr),
+ );
+ if (otherOpenPrs.isNotEmpty) {
+ separate();
+ rows.add(line('Pull requests', dim: true));
+ for (final pr in otherOpenPrs) {
+ addPr(pr);
+ }
+ }
+ if (completedCount > 0) {
+ separate();
+ rows.add(
+ Align(
+ alignment: Alignment.centerLeft,
+ child: TerminalTextAction(
+ key: const ValueKey('work-completed'),
+ label: _showCompleted
+ ? 'Hide completed'
+ : 'Completed ($completedCount)',
+ padding: EdgeInsets.zero,
+ onPressed: () => setState(
+ () => _showCompleted = !_showCompleted,
+ ),
+ ),
+ ),
+ );
+ if (_showCompleted) {
+ for (final branch in branches.where(completedBranch)) {
+ addBranch(branch);
+ }
+ final completedPrs = ungrouped.where(completed);
+ if (completedPrs.isNotEmpty) {
+ separate();
+ for (final pr in completedPrs) {
+ addPr(pr);
+ }
+ }
+ }
+ }
+ if (rows.isEmpty) {
+ rows.add(
+ line(
+ _loading
+ ? 'Reading session history…'
+ : 'No branches or pull requests recorded.',
+ dim: true,
+ ),
+ );
+ }
+ if (_nextOffset != null ||
+ ongoingPrs.length > _visiblePrs ||
+ _showCompleted && completedPrs.length > _visiblePrs) {
+ separate();
+ rows.add(
+ Align(
+ alignment: Alignment.centerLeft,
+ child: TerminalTextAction(
+ label: 'Show more',
+ padding: EdgeInsets.zero,
+ onPressed: _loading
+ ? null
+ : () {
+ final offset = _nextOffset ?? _visiblePrs;
+ setState(() => _visiblePrs += 4);
+ if (widget.online) {
+ unawaited(_refresh(offset));
+ }
+ },
+ ),
+ ),
+ );
+ }
+ return Focus(
+ onKeyEvent: (node, event) {
+ if (event is! KeyDownEvent) {
+ return KeyEventResult.ignored;
+ }
+ if (event.logicalKey == LogicalKeyboardKey.arrowDown) {
+ FocusScope.of(context).nextFocus();
+ return KeyEventResult.handled;
+ }
+ if (event.logicalKey == LogicalKeyboardKey.arrowUp) {
+ FocusScope.of(context).previousFocus();
+ return KeyEventResult.handled;
+ }
+ return KeyEventResult.ignored;
+ },
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
children: [
- if (widget.online)
- TerminalTextAction(
- label: _loading ? 'Refreshing…' : 'Refresh',
- onPressed: _loading
- ? null
- : () => unawaited(_refresh(0)),
+ line('${widget.agent.displayName} · Branches & PRs'),
+ if (compact && commonRepository != null) ...[
+ line(repositoryName(commonRepository), dim: true),
+ line(
+ '${branches.length} branches · ${prs.length} PRs',
+ dim: true,
+ ),
+ ] else
+ line(summary, dim: true),
+ if (!widget.online)
+ line('Offline · saved data', dim: true)
+ else if (data?.state == 'unavailable' ||
+ data?.state == 'uncertain')
+ line('Git unavailable · saved history', dim: true),
+ SizedBox(height: cell.height),
+ Flexible(
+ child: ListView.builder(
+ key: const ValueKey('work-branch-list'),
+ shrinkWrap: true,
+ itemExtent: cell.height,
+ itemCount: rows.length,
+ itemBuilder: (_, index) => rows[index],
+ ),
+ ),
+ if (data?.truncated == true)
+ line('Some earlier history is omitted.', dim: true),
+ if (_error != null) line(_error!),
+ SizedBox(height: cell.height),
+ SizedBox(
+ width: double.infinity,
+ child: Wrap(
+ alignment: WrapAlignment.spaceBetween,
+ children: [
+ if (widget.online)
+ TerminalTextAction(
+ label: _loading ? 'Refreshing…' : 'Refresh',
+ padding: EdgeInsets.zero,
+ onPressed: _loading
+ ? null
+ : () => unawaited(_refresh(0)),
+ ),
+ TerminalTextAction(
+ label: 'Close',
+ padding: EdgeInsets.zero,
+ onPressed: () => Navigator.of(context).pop(),
+ ),
+ ],
),
- TerminalTextAction(
- label: 'Close',
- onPressed: () => Navigator.of(context).pop(),
),
],
),
- ),
- ],
+ );
+ },
),
),
),
diff --git a/desktop/test/session_git_context_test.dart b/desktop/test/session_git_context_test.dart
index 5f07b1933..f335d4c96 100644
--- a/desktop/test/session_git_context_test.dart
+++ b/desktop/test/session_git_context_test.dart
@@ -92,6 +92,30 @@ Map<String, dynamic> manyPrFixture() {
}
void main() {
+ test('the recent Git branch leads the header and binds its PR request', () {
+ final fixture = gitFixture();
+ final recent = fixture['current'] as Map<String, dynamic>;
+ fixture['state'] = 'multiple';
+ fixture['current'] = null;
+ fixture['checkouts'] = [
+ {...recent, 'cwd': '/home', 'root': '/home', 'branch': 'original'},
+ recent,
+ ];
+ fixture['recentWork'] = {'project': recent, 'at': '2026-09-27T13:00:00Z'};
+ final context = AgentGitContext.fromJson(fixture)!;
+ expect(context.branchLabel, 'hn/preview-fix · +1');
+ expect(context.displayProject(null)?.branch, 'hn/preview-fix');
+ expect(context.requestIdentity?['cwd'], '/ship-hn');
+ expect(
+ context.branchRows.where(context.isRecentBranch).single.branch,
+ 'hn/preview-fix',
+ );
+ fixture['recentWork'] = {
+ 'project': {...recent, 'branch': 'unverified'},
+ 'at': '2026-09-27T13:00:00Z',
+ };
+ expect(AgentGitContext.fromJson(fixture)!.branchLabel, '2 branches');
+ });
test('multiple checked-out branches are named without exposing temporary folders', () {
final fixture = gitFixture();
final project = fixture['current'] as Map<String, dynamic>;
diff --git a/desktop/test/session_work_dialog_test.dart b/desktop/test/session_work_dialog_test.dart
index 48f38c063..9391c1322 100644
--- a/desktop/test/session_work_dialog_test.dart
+++ b/desktop/test/session_work_dialog_test.dart
@@ -7,19 +7,68 @@ import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/shared/theme/color_palette.dart';
+import 'package:harness/terminal/terminal_text.dart';
+import 'package:harness/terminal/terminal_theme_store.dart';
import 'package:harness/widgets/session_work_dialog.dart';
+import 'package:xterm/xterm.dart' show TerminalStyle;
import 'session_git_context_test.dart';
import 'support/real_fonts.dart';
+Future<void> captureDialog(
+ WidgetTester tester,
+ GlobalKey boundary,
+ String name,
+) async {
+ final output = Platform.environment['HARNESS_GIT_CONTEXT_CAPTURE_DIR'];
+ if (output == null) return;
+ await tester.runAsync(() async {
+ final render =
+ boundary.currentContext!.findRenderObject()! as RenderRepaintBoundary;
+ final picture = await render.toImage(pixelRatio: 1);
+ final bytes = await picture.toByteData(format: ui.ImageByteFormat.png);
+ await Directory(output).create(recursive: true);
+ await File('$output/$name.png').writeAsBytes(bytes!.buffer.asUint8List());
+ picture.dispose();
+ });
+}
+
void main() {
- setUpAll(loadRealFonts);
+ final capture = Platform.environment['HARNESS_GIT_CONTEXT_CAPTURE_DIR'];
+ setUpAll(() async {
+ await loadRealFonts();
+ // Optional local captures use the actual macOS terminal face. Portable
+ // regression runs retain the shared metric-compatible test fonts.
+ if (capture != null && Platform.isMacOS) {
+ final bytes = await File('/System/Library/Fonts/SFNSMono.ttf')
+ .readAsBytes();
+ await (FontLoader(
+ 'WorkDialogPreviewMono',
+ )..addFont(Future.value(ByteData.sublistView(bytes)))).load();
+ }
+ });
+ setUp(() {
+ final old = terminalFontStore.value;
+ if (capture != null && Platform.isMacOS) {
+ terminalFontStore.value = const TerminalStyle(
+ fontFamily: 'WorkDialogPreviewMono',
+ fontSize: 18,
+ );
+ }
+ addTearDown(() => terminalFontStore.value = old);
+ });
testWidgets(
'opening work details preserves launch context and only follows the selected PR link',
(tester) async {
final opened = <Uri>[];
final git = gitFixture();
git['activityUncertain'] = true;
+ git['checkouts'] = [git['current']];
+ git['recentWork'] = {
+ 'project': git['current'],
+ 'at': '2026-09-27T13:00:00Z',
+ };
git['history']['pullRequests'][0]['result'].addAll({
'headBranch': 'hn/preview-fix',
'baseBranch': 'main',
@@ -77,26 +126,23 @@ void main() {
await tester.pumpAndSettle();
expect(find.textContaining('/silent-beacon'), findsNothing);
expect(find.textContaining('/ship-hn'), findsNothing);
- expect(find.text('hn/preview-fix · Checked out'), findsOneWidget);
- expect(find.text('Branch checked out for this session.'), findsOneWidget);
+ expect(find.text('hn/preview-fix'), findsOneWidget);
+ expect(find.text('Recent work'), findsOneWidget);
+ expect(find.text('acme/app · 2 branches · 2 PRs'), findsOneWidget);
+ expect(find.text('#12'), findsOneWidget);
+ expect(find.text('Keep complete session previews'), findsOneWidget);
+ expect(find.text('#119'), findsNothing);
+ expect(find.text('[ Completed (1) ]'), findsOneWidget);
+ expect(find.textContaining('Checked 2026'), findsNothing);
+ expect(
+ tester
+ .getSize(find.byKey(const ValueKey('work-dialog-surface')))
+ .height,
+ lessThan(360),
+ );
expect(find.text('Work location unknown'), findsNothing);
- final output = Platform.environment['HARNESS_GIT_CONTEXT_CAPTURE_DIR'];
- if (output != null) {
- await tester.runAsync(() async {
- final render =
- boundary.currentContext!.findRenderObject()!
- as RenderRepaintBoundary;
- final picture = await render.toImage(pixelRatio: 1);
- final bytes = await picture.toByteData(
- format: ui.ImageByteFormat.png,
- );
- await Directory(output).create(recursive: true);
- await File('$output/work-last-observed.png')
- .writeAsBytes(bytes!.buffer.asUint8List());
- picture.dispose();
- });
- }
+ await captureDialog(tester, boundary, 'work-last-observed');
await tester.tap(
find.byKey(
const ValueKey('work-pr-https://github.com/acme/app/pull/12'),
@@ -104,6 +150,80 @@ void main() {
);
await tester.pumpAndSettle();
expect(opened, [Uri.parse('https://github.com/acme/app/pull/12')]);
+ await tester.tap(find.byKey(const ValueKey('work-completed')));
+ await tester.pumpAndSettle();
+ expect(find.text('hn/nfc'), findsOneWidget);
+ expect(find.text('#119'), findsOneWidget);
+ expect(find.text('Keep NFC conversations in order'), findsOneWidget);
+ expect(tester.takeException(), isNull);
+ await captureDialog(tester, boundary, 'work-completed');
+ },
+ );
+
+ testWidgets(
+ 'completed history remains reachable beside a full open PR page',
+ (tester) async {
+ final git = manyPrFixture();
+ final opened = <Uri>[];
+ await tester.pumpWidget(
+ grid.BrightnessScope(
+ child: MaterialApp(
+ home: Scaffold(
+ body: SessionWorkDialog(
+ agent: workAgent(git: git),
+ online: false,
+ read: (_) async => throw StateError('Offline'),
+ open: (uri) async {
+ opened.add(uri);
+ return true;
+ },
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(find.text('#122'), findsNothing);
+ await tester.tap(find.byKey(const ValueKey('work-completed')));
+ await tester.pumpAndSettle();
+ final target = find.byKey(
+ const ValueKey('work-pr-https://github.com/acme/app/pull/122'),
+ );
+ await tester.scrollUntilVisible(
+ target,
+ 100,
+ scrollable: find.descendant(
+ of: find.byKey(const ValueKey('work-branch-list')),
+ matching: find.byType(Scrollable),
+ ),
+ );
+ await tester.tap(target);
+ await tester.pumpAndSettle();
+ expect(opened, [Uri.parse('https://github.com/acme/app/pull/122')]);
+ final buttonContext = tester.element(
+ find.descendant(of: target, matching: find.byType(Row)).first,
+ );
+ Focus.of(buttonContext).requestFocus();
+ await tester.pumpAndSettle();
+ final focus = FocusManager.instance.primaryFocus;
+ final palette = grid.AppTheme.palette.value;
+ final theme = terminalThemeStore.value;
+ final font = terminalFontStore.value;
+ addTearDown(() {
+ grid.AppTheme.palette.value = palette;
+ terminalThemeStore.value = theme;
+ terminalFontStore.value = font;
+ });
+ grid.AppTheme.palette.value = HarnessPalette.midnight;
+ terminalThemeStore.value = TerminalThemeChoice.tango;
+ terminalFontStore.value = TerminalStyle(
+ fontFamily: font.fontFamily,
+ fontSize: font.fontSize + 1,
+ );
+ await tester.pumpAndSettle();
+ expect(FocusManager.instance.primaryFocus, same(focus));
+ expect(target.hitTestable(), findsOneWidget);
+ expect(find.text('[ Hide completed ]'), findsOneWidget);
expect(tester.takeException(), isNull);
},
);
@@ -148,46 +268,45 @@ void main() {
},
);
- for (final brightness in Brightness.values) {
+ for (final palette in [HarnessPalette.graphite, HarnessPalette.midnight]) {
for (final size in [const Size(1000, 720), const Size(420, 680)]) {
testWidgets(
- 'work details fit ${size.width} ${brightness.name}, including enlarged text',
+ 'work details fit ${size.width} ${palette.name}, including enlarged text',
(tester) async {
tester.view.devicePixelRatio = 1;
tester.view.physicalSize = size;
addTearDown(tester.view.reset);
- final old = grid.AppTheme.brightness.value;
- grid.AppTheme.brightness.value = brightness;
- addTearDown(() => grid.AppTheme.brightness.value = old);
+ final old = grid.AppTheme.palette.value;
+ grid.AppTheme.palette.value = palette;
+ addTearDown(() => grid.AppTheme.palette.value = old);
final boundary = GlobalKey();
await tester.pumpWidget(
- RepaintBoundary(
- key: boundary,
- child: MaterialApp(
- debugShowCheckedModeBanner: false,
- theme: grid.buildAppTheme(brightness: brightness),
- builder: (context, child) => MediaQuery(
- data: MediaQuery.of(context).copyWith(
- textScaler: TextScaler.linear(size.width < 500 ? 1.6 : 1),
+ grid.BrightnessScope(
+ child: RepaintBoundary(
+ key: boundary,
+ child: MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context).copyWith(
+ textScaler: TextScaler.linear(size.width < 500 ? 1.6 : 1),
+ ),
+ child: child!,
),
- child: child!,
- ),
- home: Scaffold(
- body: SessionWorkDialog(
- agent: workAgent(git: manyPrFixture()),
- online: false,
- read: (_) =>
- throw StateError('Offline must not request data'),
+ home: Scaffold(
+ body: SessionWorkDialog(
+ agent: workAgent(git: manyPrFixture()),
+ online: false,
+ read: (_) =>
+ throw StateError('Offline must not request data'),
+ ),
),
),
),
),
);
await tester.pumpAndSettle();
- expect(
- find.text('Offline · saved branches and pull requests'),
- findsOneWidget,
- );
+ expect(find.text('Offline · saved data'), findsOneWidget);
expect(tester.takeException(), isNull);
final output =
Platform.environment['HARNESS_GIT_CONTEXT_CAPTURE_DIR'];
@@ -202,7 +321,7 @@ void main() {
);
await Directory(output).create(recursive: true);
await File(
- '$output/work-${size.width.toInt()}-${brightness.name}.png',
+ '$output/work-${size.width.toInt()}-${palette.name}.png',
).writeAsBytes(bytes!.buffer.asUint8List());
picture.dispose();
});
diff --git a/desktop/test/session_work_navigation_test.dart b/desktop/test/session_work_navigation_test.dart
index aca4a34b2..fa9a451a7 100644
--- a/desktop/test/session_work_navigation_test.dart
+++ b/desktop/test/session_work_navigation_test.dart
@@ -15,7 +15,7 @@ import 'swarm_state_test.dart' show createApp;
void main() {
for (final native in [false, true]) {
testWidgets(
- 'current branch opens work history without touching its terminal (native=$native)',
+ 'recent branch opens work history without touching its terminal (native=$native)',
(tester) async {
final old = appearancePrefsStore.value;
appearancePrefsStore.value = old.copyWith(prompt: const PromptPrefs());
@@ -37,14 +37,31 @@ void main() {
);
final app = createApp();
addTearDown(app.dispose);
+ final git = gitFixture();
+ final recent = git['current'] as Map;
+ git['state'] = 'multiple';
+ git['current'] = null;
+ git['checkouts'] = [
+ recent,
+ {
+ ...recent,
+ 'cwd': '/launch',
+ 'root': '/launch',
+ 'branch': 'original',
+ },
+ ];
+ git['recentWork'] = {'project': recent, 'at': '2026-09-27T13:00:00Z'};
app.stateOf('m')!
- ..agents = [workAgent(git: gitFixture())]
+ ..agents = [workAgent(git: git)]
..nodeOnline = false;
final input = <TerminalBinaryFrame>[];
final pane = app.adoptSessionForTest(terminal('hn', input));
final session = pane.session;
await mount(tester, app, nativeTabs: native);
- expect(WorkspacePaneContext.focused(app)?.branch, 'hn/preview-fix');
+ expect(
+ WorkspacePaneContext.focused(app)?.branch,
+ 'hn/preview-fix · +1',
+ );
if (native) {
final fields =
((updates.last['focusedContext'] as Map)['fields'] as List)
diff --git a/docs/worktree-pull-requests.md b/docs/worktree-pull-requests.md
index f9da23bda..d33a9801a 100644
--- a/docs/worktree-pull-requests.md
+++ b/docs/worktree-pull-requests.md
@@ -6,21 +6,30 @@ for locating code, not user-facing identities.
## Display and navigation
-The focused bar shows the branch checked out for the session, plus its matching
-PR link when there is one. If more than one branch is checked out in associated
-checkouts, it shows `2 branches` (or the corresponding count). A historical branch
-does not increase this count. A dependent viewer uses its owner's context.
+The focused bar shows the branch at the most recent confirmed Git work location,
+plus its matching PR link when there is one. Other checked-out branches appear
+as a compact count, for example `ship-hn · +3`. This is recent work, not a claim
+that an agent is executing there now. Hovering explains the observation time.
+Without a unique recent location, one checked-out branch appears by name and
+multiple branches appear as `2 branches` (or the corresponding count). Historical
+branches do not increase this count. A dependent viewer uses its owner's context.
-Click the branch, or use **Branches and pull requests** in the desktop command picker. Details list checked-out and previously recorded branches, followed
-by their PR links, titles, head/base branches and GitHub states. Open and draft
-PRs precede completed work. Temporary folder names and subdirectory lists are
-not shown. Matching repository and branch names are one visible branch even
-when several local copies exist; different repositories remain distinct.
+Click the branch, or use **Branches and pull requests** in the desktop command
+picker. Each branch appears once, with its PR links, titles and GitHub states
+directly beneath it. Recent work leads, followed by branches with open or draft
+PRs. Completed work folds into **Completed**, except PRs on the recent work
+branch, whose state remains visible. The repository appears once when shared.
+Hover or accessibility inspection exposes full titles, head/base branches and
+GitHub check times. Short lists fit their content; long lists scroll within a
+bounded dialog. Temporary folder names and subdirectory lists are not shown.
+Matching repository and branch names are one visible branch even when several
+local copies exist; different repositories remain distinct.
| Fact | Source |
| --- | --- |
| Session's assigned checkout | Harness's saved launch/resume association |
| Checked-out branch | Git, read directly on the owning machine |
+| Recent work branch | Most recent successful location observation, resolved through current Git facts |
| Branch history | Saved Git observations for this conversation |
| Additional checkout association | Previously verified observations or successful tool activity |
| PR identity and state | GitHub, matched by head repository and branch, or a recorded PR URL |
@@ -36,6 +45,10 @@ every branch in the shared repository to every agent, infer ownership from a
branch prefix or GitHub author, or pretend that the last command's directory is
the session's one current branch. Engine activity can add associations and PR
URLs. Formats the reader cannot understand add nothing and remove nothing.
+Recent work is an optional refinement: missing activity never hides known Git
+branches. A later command outside Git retains the last useful Git context.
+One observation spanning different branches or partially unresolved locations
+does not choose an arbitrary branch.
## Freshness and history
@@ -63,7 +76,8 @@ executing transcript text. Existing v3 checkpoints replay available transcripts
once to recover missed batched receipts; later v4 reads stay incremental.
Registry `cwd` and the legacy `project` field keep their launch/resume meaning.
-The additive `gitContext.checkouts` contains verified Git snapshots. List and
+The additive `gitContext.checkouts` contains verified Git snapshots; optional
+`gitContext.recentWork` selects one of them with its observation time. List and
push frames use the same projection and versions. Older clients remain readable;
the desktop groups the snapshots into branch identities. PR badge responses
are bound to the displayed repository, branch and checkout, and stale replies