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: show current session branches and preserve PR history (#397)

Dee37d86d2eb7b1
diff --git a/.github/assets/session-git-context/README.md b/.github/assets/session-git-context/README.md
new file mode 100644
index 000000000..07c864f8e
--- /dev/null
+++ b/.github/assets/session-git-context/README.md
@@ -0,0 +1,13 @@
+# Session work previews
+
+Synthetic widget-test captures of the desktop work dialog and phone work page.
+The session, repository, branches and pull requests are fixtures, not live data.
+
+- [Desktop, 1000 × 720](desktop.png)
+- [Phone, 390 × 760](phone.png)
+
+Both show the offline state to demonstrate retained work and pull-request
+history. Generate fresh captures by setting `HARNESS_GIT_CONTEXT_CAPTURE_DIR`
+when running `desktop/test/session_work_dialog_test.dart` or
+`mobile/test/session_work_page_test.dart` with `flutter test` in the respective
+application directory.
diff --git a/.github/assets/session-git-context/desktop.png b/.github/assets/session-git-context/desktop.png
new file mode 100644
index 000000000..2e496cd09
Binary files /dev/null and b/.github/assets/session-git-context/desktop.png differ
diff --git a/.github/assets/session-git-context/phone.png b/.github/assets/session-git-context/phone.png
new file mode 100644
index 000000000..429ea3d3d
Binary files /dev/null and b/.github/assets/session-git-context/phone.png differ
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.ts
index e9866d161..74a526e32 100644
--- a/cli/src/backendSocket.spec.ts
+++ b/cli/src/backendSocket.spec.ts
@@ -1,4 +1,5 @@
import * as gitPullRequest from './lib/gitPullRequest.js'
+import * as sessionGitPullRequest from './lib/sessionGitPullRequest.js'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { readFileSync, mkdirSync, mkdtempSync, writeFileSync, rmSync } from 'fs'
import { homedir, tmpdir } from 'os'
@@ -821,6 +822,26 @@ describe('BackendSocket outbound queue', () => {
await socket.stop()
})
+ it('keeps session work paths and PR history inside the requesting encrypted reply', async () => {
+ const history = { status: 'unavailable' as const, context: null, gitContext: {
+ state: 'uncertain' as const, current: null, observedAt: null, locations: [], pullRequests: [], truncated: false,
+ }, history: { branches: [{ cwd: '/private/worktree', remote: null, branch: 'private-fix', at: '2026-09-27' }], pullRequests: [], truncated: false }, lookups: [], nextOffset: null }
+ vi.spyOn(registry, 'resolve').mockReturnValue({ cwd: '/remote/workspace' } as RegisteredSession)
+ vi.spyOn(sessionGitPullRequest, 'readSessionGitPullRequest').mockResolvedValue(history)
+ 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: 'history-1', agentId: 'agent1', history: true,
+ } })
+ 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-history' } } })
+ 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', 'history-1', history))
+ expect(JSON.stringify(parseSent(ws))).not.toContain('/private/worktree')
+ 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-history' } } } }))
+ 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.ts
index 39be23e3f..a7a79ab1a 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -1,4 +1,4 @@
-import { readGitPullRequest } from './lib/gitPullRequest.js'
+import { readSessionGitPullRequest } from './lib/sessionGitPullRequest.js'
import type { HarnessShareOwner } from './sharing/owner.js'
import { SHARE_REQUEST_TYPES } from './sharing/protocol.js'
import { AutonomousDeviceRelay } from './lib/autonomous-device/relay.js'
@@ -2663,7 +2663,18 @@ export class BackendSocket {
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))
+ const requested = payload.context
+ if (requested !== undefined && (!requested || typeof requested !== 'object'
+ || typeof (requested as Record<string, unknown>).cwd !== 'string'
+ || typeof (requested as Record<string, unknown>).branch !== 'string'
+ || (requested as Record<string, unknown>).remote !== null && typeof (requested as Record<string, unknown>).remote !== 'string')) {
+ reply(type, requestId, { status: 'unavailable' }); return
+ }
+ void readSessionGitPullRequest(agent, {
+ expected: requested as import('./lib/sessionGitPullRequest.js').ExpectedGitContext | undefined,
+ history: payload.history === true, offset: typeof payload.offset === 'number' ? payload.offset : undefined,
+ }).then(result => reply(type, requestId, result))
+ .catch(() => reply(type, requestId, { status: 'unavailable' }))
return
}
diff --git a/cli/src/lib/agentFrame.ts b/cli/src/lib/agentFrame.ts
index 11dcf09de..053a54d53 100644
--- a/cli/src/lib/agentFrame.ts
+++ b/cli/src/lib/agentFrame.ts
@@ -19,6 +19,8 @@
*/
import { agentProject, type AgentProject } from './agentProject.js'
+import { sessionGitContext, SessionGitContextReader, type SessionGitContext } from './sessionGitContext.js'
+import { sessionGitHistory } from './sessionGitHistory.js'
import { transcriptActivityAt } from './transcriptActivity.js'
import type { AgentTokenUsage } from './agentTokenUsage.js'
import type { AgentOutputStats } from './agentOutputStats.js'
@@ -78,6 +80,8 @@ export type AgentFrame = {
grid: GridFrameBlock | null
codexHome: string | null
project: AgentProject | null
+ /** Additive display context; project/cwd remain the registered launch workspace. */
+ gitContext: SessionGitContext
/** The domain-specific harness this agent was created as, or null for a plain engine. */
dsh: string | null
/** Its display name from the installed manifest; null when unknown here (not installed, plain engine). */
@@ -171,10 +175,19 @@ function frameTitle(s: RegisteredSession): string | null {
* half of "last used" — when a person last opened it, from any app — and a client sorts by the later
* of the two.
*/
+const gitContexts = new SessionGitContextReader()
+
export async function agentFrame(
s: RegisteredSession,
{ selectedModel, terminalAvailable, dsh, tokenUsage }: AgentFrameContext,
): Promise<AgentFrame> {
+ const home = agentProject(s.cwd)
+ const context = gitContexts.read(JSON.stringify([s.agentId, s.sessionId, s.engine, s.codexHome, s.registeredAt]), async () => {
+ const value = await sessionGitContext(await home, tokenUsage?.work)
+ value.history = await sessionGitHistory.observe(s, value)
+ return value
+ })
+ const [project, updatedAt, gitContext] = await Promise.all([home, lastActivityAt(s), context])
return {
id: s.agentId,
sessionId: s.sessionId,
@@ -184,7 +197,7 @@ export async function agentFrame(
status: s.active ? 'active' : 'offline',
launch: s.launch ?? { state: 'ready' },
createdAt: new Date(s.registeredAt).toISOString(),
- updatedAt: new Date(await lastActivityAt(s)).toISOString(),
+ updatedAt: new Date(updatedAt).toISOString(),
// Null, never omitted, for the reason the module doc gives: a push without the key would erase
// the open an earlier frame had reported.
lastOpenedAt: s.lastOpenedAt ? new Date(s.lastOpenedAt).toISOString() : null,
@@ -207,7 +220,8 @@ export async function agentFrame(
// engine's own login. Codex only; null is a real answer ("uses ~/.codex") for the same reason
// `grid: null` is above.
codexHome: s.codexHome ?? null,
- project: await agentProject(s.cwd),
+ project,
+ gitContext,
// All five are real answers when null, for the reason the module doc gives: a frame that omits
// them would erase a viewer URL or a verdict an earlier frame had reported.
dsh: dsh?.id ?? s.dsh ?? null,
diff --git a/cli/src/lib/agentProject.ts b/cli/src/lib/agentProject.ts
index cc2a2024d..f55a8bafc 100644
--- a/cli/src/lib/agentProject.ts
+++ b/cli/src/lib/agentProject.ts
@@ -35,9 +35,11 @@ export function canonicalRepository(raw: string | null): string | null {
/** Bounded subprocesses, no shell, network, or repository mutation. */
async function git(cwd: string, args: string[]): Promise<string | null> {
try {
+ const environment = { ...process.env, GIT_OPTIONAL_LOCKS: '0', GIT_TERMINAL_PROMPT: '0' }
+ for (const key of ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_COMMON_DIR', 'GIT_INDEX_FILE', 'GIT_NAMESPACE', 'GIT_PREFIX']) delete (environment as NodeJS.ProcessEnv)[key]
const { stdout } = await exec('git', ['-C', cwd, ...args], {
timeout: 1500, maxBuffer: 16 * 1024, encoding: 'utf8',
- env: { ...process.env, GIT_OPTIONAL_LOCKS: '0', GIT_TERMINAL_PROMPT: '0' },
+ env: environment,
})
return stdout.trim() || null
} catch { return null }
diff --git a/cli/src/lib/agentTokenUsage.ts b/cli/src/lib/agentTokenUsage.ts
index 82a621a6d..ec3080cf3 100644
--- a/cli/src/lib/agentTokenUsage.ts
+++ b/cli/src/lib/agentTokenUsage.ts
@@ -8,16 +8,19 @@ import { env } from '../config/env.js'
import type { RegisteredSession } from './registry.js'
import { sqliteReadAll } from './sqliteRead.js'
import { emptyOutputLedger, ingestOutput, outputSnapshot, validOutputLedger, type AgentOutputStats, type OutputLedger } from './agentOutputStats.js'
+import { emptySessionWork, ingestSessionWork, sessionWorkSnapshot, validSessionWork, type SessionWork, type SessionWorkLedger } from './sessionWork.js'
-export type AgentTokenUsage = { totalTokens: number | null; updatedAt: string; output?: AgentOutputStats }
+export type AgentTokenUsage = { totalTokens: number | null; updatedAt: string; output?: AgentOutputStats; work?: SessionWork }
type Target = Pick<RegisteredSession, 'engine' | 'sessionId' | 'transcriptPath' | 'codexHome' | 'agentId' | 'forkedFrom' | 'registeredAt'>
+ & Partial<Pick<RegisteredSession, 'cwd'>>
type Buckets = [number, number, number, number]
type CodexTotals = [number, number, number, number]
type Checkpoint = {
- version: 2; key: string; offset: number; size: number; mtime: number; inode: string;
+ version: 3; key: string; offset: number; size: number; mtime: number; inode: string;
boundary: string; total: number; observed: boolean; updatedAt: string | null;
claude: Record<string, Buckets>; codex: CodexTotals | null; seen: Record<string, true>;
output: OutputLedger;
+ work: SessionWorkLedger; sourceSession: string | null;
}
type Entry = {
target: Target; value: AgentTokenUsage | null; checked: number; pending: Promise<void> | null;
@@ -44,11 +47,12 @@ function keyFor(s: Target): string | null {
}
function targetSnapshot(s: Target): Target {
return { agentId: s.agentId, sessionId: s.sessionId, engine: s.engine, transcriptPath: s.transcriptPath,
- codexHome: s.codexHome, registeredAt: s.registeredAt, forkedFrom: s.forkedFrom ? { ...s.forkedFrom } : null }
+ codexHome: s.codexHome, cwd: s.cwd, registeredAt: s.registeredAt, forkedFrom: s.forkedFrom ? { ...s.forkedFrom } : null }
}
function empty(key: string): Checkpoint {
- return { version: 2, key, offset: 0, size: 0, mtime: 0, inode: '', boundary: '', total: 0,
- observed: false, updatedAt: null, claude: {}, codex: null, seen: {}, output: emptyOutputLedger() }
+ return { version: 3, key, offset: 0, size: 0, mtime: 0, inode: '', boundary: '', total: 0,
+ observed: false, updatedAt: null, claude: {}, codex: null, seen: {}, output: emptyOutputLedger(),
+ work: emptySessionWork(), sourceSession: null }
}
function rawCodex(value: unknown): CodexTotals | null {
const row = object(value)
@@ -61,13 +65,20 @@ function rawCodex(value: unknown): CodexTotals | null {
* already inside output, Claude streaming repeats merge, and Codex cumulative snapshots are deltas. */
function ingest(state: Checkpoint, line: string, target: Target): void {
if (!line.includes(target.engine === 'claude' ? '"usage"' : '"token_count"')
- && !line.includes('"tool_use"') && !line.includes('"tool_result"') && !line.includes('"response_item"')) return
+ && !line.includes('"tool_use"') && !line.includes('"tool_result"') && !line.includes('"response_item"')
+ && !line.includes('"session_meta"') && !line.includes('"turn_context"')) return
const row = object(JSON.parse(line))
if (!row) return
// Forks carry old messages into a new conversation. Only work after the fork belongs to it.
if (target.forkedFrom && (typeof row.timestamp !== 'string' || !Number.isFinite(Date.parse(row.timestamp))
|| Date.parse(row.timestamp) < target.registeredAt)) return
if (target.engine === 'claude' && typeof row.sessionId === 'string' && row.sessionId !== target.sessionId) return
+ if (target.engine === 'codex') {
+ const id = row.type === 'session_meta' ? object(row.payload)?.id : null
+ if (typeof id === 'string') state.sourceSession = id
+ if (state.sourceSession !== null && state.sourceSession !== target.sessionId) return
+ }
+ if (row.isSidechain !== true) ingestSessionWork(state.work, row, target.engine, target.cwd)
ingestOutput(state.output, row, target.engine)
if (target.engine === 'claude') {
if (row.type !== 'assistant') return
@@ -193,24 +204,26 @@ export class AgentTokenUsageCache {
}
private publish(entry: Entry, state: Checkpoint): void {
const output = outputSnapshot(state.output)
+ const work = sessionWorkSnapshot(state.work)
if (!state.updatedAt) return
const previous = entry.value
- if (!state.observed && !output) {
+ if (!state.observed && !output && !work) {
entry.value = null
if (previous) this.onChanged?.(entry.target)
return
}
entry.value = { totalTokens: state.observed ? state.total : null, updatedAt: state.updatedAt,
- ...(output ? { output } : {}) }
+ ...(output ? { output } : {}), ...(work ? { work } : {}) }
if (previous?.totalTokens !== entry.value.totalTokens
- || JSON.stringify(previous?.output) !== JSON.stringify(output ?? undefined)) this.onChanged?.(entry.target)
+ || JSON.stringify(previous?.output) !== JSON.stringify(output ?? undefined)
+ || JSON.stringify(previous?.work) !== JSON.stringify(work ?? undefined)) this.onChanged?.(entry.target)
}
private async load(key: string): Promise<Checkpoint> {
try {
const file = join(this.directory, `${key}.json`)
if ((await stat(file)).size > MAX_CACHE_BYTES) return empty(key)
const raw = JSON.parse(await readFile(file, 'utf8')) as Checkpoint
- if (raw.version === 2 && raw.key === key && Number.isSafeInteger(raw.total) && raw.total >= 0
+ if (raw.version === 3 && raw.key === key && Number.isSafeInteger(raw.total) && raw.total >= 0
&& typeof raw.observed === 'boolean'
&& (raw.updatedAt === null || typeof raw.updatedAt === 'string' && Number.isFinite(Date.parse(raw.updatedAt)))
&& Number.isSafeInteger(raw.size) && raw.size >= 0 && Number.isFinite(raw.mtime)
@@ -218,7 +231,8 @@ export class AgentTokenUsageCache {
&& typeof raw.inode === 'string' && typeof raw.boundary === 'string'
&& object(raw.claude) && Object.values(raw.claude).every(validBuckets)
&& object(raw.seen) && Object.values(raw.seen).every(value => value === true)
- && (raw.codex === null || validBuckets(raw.codex)) && validOutputLedger(raw.output)) return raw
+ && (raw.codex === null || validBuckets(raw.codex)) && validOutputLedger(raw.output)
+ && validSessionWork(raw.work) && (raw.sourceSession === null || typeof raw.sourceSession === 'string')) return raw
} catch { /* First run, corrupt cache, or removed cache: rebuild from the trusted transcript. */ }
return empty(key)
}
@@ -278,7 +292,16 @@ export class AgentTokenUsageCache {
return hash(buffer.subarray(0, bytesRead))
}
if (state.inode !== inode || info.size < state.size || (info.size === state.size && info.mtimeMs !== state.mtime)
- || state.offset > 0 && await boundary(state.offset) !== state.boundary) state = empty(key)
+ || state.offset > 0 && await boundary(state.offset) !== state.boundary) {
+ // A rewritten/compacted transcript can lose old tool receipts. Their recorded locations
+ // and PR links still belong to this conversation; only current execution is invalidated.
+ const history = state.work
+ state = empty(key)
+ state.work.locations = history.locations
+ state.work.pullRequests = history.pullRequests
+ state.work.uncertain = history.locations.length > 0
+ state.work.truncated = history.truncated
+ }
let offset = state.offset
let partial = Buffer.alloc(0)
while (offset < info.size) {
diff --git a/cli/src/lib/gitPullRequest.spec.ts b/cli/src/lib/gitPullRequest.spec.ts
index 61f74b539..e53d8e195 100644
--- a/cli/src/lib/gitPullRequest.spec.ts
+++ b/cli/src/lib/gitPullRequest.spec.ts
@@ -1,5 +1,5 @@
import { describe, it, expect, vi } from 'vitest'
-import { createPullRequestReader, githubRepository } from './gitPullRequest.js'
+import { boundedPullRequestRunner, createPullRequestReader, createPullRequestUrlReader, 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'
@@ -9,6 +9,39 @@ function fixture(rows: unknown = [row()]) {
return { run, read: createPullRequestReader(run), branch: (b: string) => { branch = b } }
}
describe('worktree PR status', () => {
+ it('retains the original GitHub check time when serving cached history', async () => {
+ let now = Date.parse('2026-09-27T13:00:00Z')
+ const run = vi.fn(async () => JSON.stringify(row()))
+ const read = createPullRequestUrlReader(run, () => now)
+ const first = await read('https://github.com/acme/repo/pull/12')
+ now += 30_000
+ expect(await read('https://github.com/acme/repo/pull/12')).toEqual(first)
+ now += 31_000
+ expect(await read('https://github.com/acme/repo/pull/12')).toMatchObject({ checkedAt: new Date(now).toISOString() })
+ expect(run).toHaveBeenCalledTimes(2)
+ })
+ it('bounds concurrent processes and rejects excess queued work', async () => {
+ let active = 0, maximum = 0
+ const completions: Array<() => void> = []
+ const run = boundedPullRequestRunner(async () => {
+ maximum = Math.max(maximum, ++active)
+ await new Promise<void>(resolve => completions.push(resolve))
+ active--; return 'ok'
+ }, 2, 1)
+ const pending = [run('gh', [], '/tmp'), run('gh', [], '/tmp'), run('gh', [], '/tmp')]
+ await expect(run('gh', [], '/tmp')).rejects.toThrow('busy')
+ completions.shift()!(); await pending[0]
+ completions.shift()!(); await pending[1]
+ completions.shift()!(); await pending[2]
+ expect(maximum).toBe(2)
+ })
+ it('follows a recorded PR through a GitHub repository rename to its canonical URL', async () => {
+ const read = createPullRequestUrlReader(async () => JSON.stringify(row()))
+ expect(await read('https://github.com/acme/old-name/pull/12')).toMatchObject({
+ status: 'found', url: 'https://github.com/acme/repo/pull/12', number: 12,
+ })
+ expect(await read('https://github.com/acme/old-name/pull/13')).toEqual({ status: 'unavailable' })
+ })
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 })
@@ -28,7 +61,7 @@ describe('worktree PR status', () => {
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)
+ expect(f.run.mock.calls.some(([cmd, args]) => cmd === 'gh' && args.at(-1)?.includes('head=acme%3Aanother'))).toBe(true)
})
it('uses canonical repository identity after an origin rename', async () => {
const calls: string[][] = []
@@ -40,9 +73,47 @@ describe('worktree PR status', () => {
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('resolves fork-to-parent PRs by head repository as well as branch name', async () => {
+ const read = createPullRequestReader(async (command, args) => {
+ if (command === 'git') return args[0] === 'symbolic-ref' ? 'feature' : 'https://github.com/alice/repo'
+ const path = args.at(-1)!
+ if (!path.includes('/pulls?')) return JSON.stringify({ full_name: 'alice/repo', fork: true, parent: { full_name: 'acme/repo' } })
+ if (path.startsWith('repos/alice/')) return '[]'
+ return JSON.stringify([
+ row({ number: 13, html_url: 'https://github.com/acme/repo/pull/13', head: { ref: 'feature', repo: { full_name: 'another/repo' } } }),
+ row({ title: 'Fix preview', head: { ref: 'feature', repo: { full_name: 'alice/repo' } }, base: { ref: 'main' } }),
+ ])
+ })
+ expect(await read('/worktree')).toMatchObject({ status: 'found', number: 12, headRepository: 'alice/repo', headBranch: 'feature', baseBranch: 'main' })
+ })
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()
})
+ it('rejects a badge request for an obsolete checkout identity', async () => {
+ const f = fixture()
+ expect(await f.read('/worktree', { branch: 'old', remote: 'github.com/acme/repo' })).toEqual({ status: 'unavailable' })
+ expect(f.run.mock.calls.some(([cmd]) => cmd === 'gh')).toBe(false)
+ })
+ it('discards a PR if the branch switches while GitHub is replying', async () => {
+ let branch = 'feature'
+ const read = createPullRequestReader(async (command, args) => {
+ if (command === 'git') return args[0] === 'symbolic-ref' ? branch : 'https://github.com/acme/repo'
+ if (args.at(-1)?.includes('/pulls?')) { branch = 'next-task'; return JSON.stringify([row()]) }
+ return JSON.stringify({ full_name: 'acme/repo' })
+ })
+ expect(await read('/worktree')).toEqual({ status: 'unavailable' })
+ })
+ it('resolves a saved PR URL without its deleted branch or directory', async () => {
+ const run = vi.fn(async () => JSON.stringify(row({ state: 'closed', merged_at: '2026-09-27' })))
+ const read = createPullRequestUrlReader(run)
+ expect(await read('https://github.com/acme/repo/pull/12')).toMatchObject({ status: 'found', state: 'Merged' })
+ expect(run.mock.calls).toHaveLength(1)
+ await read('https://github.com/acme/repo/pull/12')
+ expect(run.mock.calls).toHaveLength(1)
+ expect(await read('https://github.com/../repo/pull/12')).toEqual({ status: 'unavailable' })
+ expect(await read('https://github.com/acme/../pull/12')).toEqual({ status: 'unavailable' })
+ expect(run.mock.calls).toHaveLength(1)
+ })
})
diff --git a/cli/src/lib/gitPullRequest.ts b/cli/src/lib/gitPullRequest.ts
index 4ccfdf645..09f24ca67 100644
--- a/cli/src/lib/gitPullRequest.ts
+++ b/cli/src/lib/gitPullRequest.ts
@@ -1,25 +1,78 @@
import { execFile } from 'node:child_process'
import { promisify } from 'node:util'
import { validGitPath } from './gitProject.js'
+import { canonicalRepository } from './agentProject.js'
+import { validPullRequestUrl } from './sessionWork.js'
+import { tmpdir } from 'node:os'
const exec = promisify(execFile)
type Run = (command: string, args: string[], cwd: string) => Promise<string>
-const run: Run = async (command, args, cwd) => {
+/** Bound process and queue counts across simultaneous badges and history pages. */
+export function boundedPullRequestRunner(execute: Run, limit = 4, queueLimit = 64, waitMs = 2000): Run {
+ let active = 0
+ const waiting: Array<() => void> = []
+ return async (...args) => {
+ if (active >= limit) {
+ if (waiting.length >= queueLimit) throw new Error('Git context is busy')
+ await new Promise<void>((resolve, reject) => {
+ const ready = () => { clearTimeout(timer); resolve() }
+ const timer = setTimeout(() => {
+ const index = waiting.indexOf(ready)
+ if (index >= 0) waiting.splice(index, 1)
+ reject(new Error('Git context is busy'))
+ }, waitMs)
+ timer.unref?.()
+ waiting.push(ready)
+ })
+ } else active++
+ try { return await execute(...args) }
+ finally {
+ const next = waiting.shift()
+ if (next) next()
+ else active--
+ }
+ }
+}
+const run: Run = boundedPullRequestRunner(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' } | {
+ return (await exec(command, args, { cwd, env, timeout: command === 'git' ? 1500 : 5000,
+ killSignal: 'SIGKILL', maxBuffer: 256 * 1024 })).stdout.trim()
+})
+export type FoundPullRequest = {
status: 'found'; number: number; url: string; state: 'Draft' | 'Open' | 'Merged' | 'Closed'
+ title?: string; headBranch?: string; baseBranch?: string; headRepository?: string;
+ checkedAt?: string;
+ related?: FoundPullRequest[];
}
+export type PullRequestResult = { status: 'none' | 'unavailable' } | FoundPullRequest
+export type PullRequestIdentity = { branch: string; remote: string | null }
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
+ const repo = match?.[1]
+ return repo && validPullRequestUrl(`https://github.com/${repo}/pull/1`) ? repo : null
+}
+function prResult(pr: unknown, repo: string): PullRequestResult {
+ if (pr === null || typeof pr !== 'object') return { status: 'unavailable' }
+ const row = pr as Record<string, unknown>
+ if (!Number.isSafeInteger(row.number) || Number(row.number) <= 0 || !['open', 'closed'].includes(String(row.state))
+ || row.html_url !== `https://github.com/${repo}/pull/${row.number}` || !validPullRequestUrl(row.html_url)) return { status: 'unavailable' }
+ const label = (v: unknown): string | undefined => typeof v === 'string' && v.length <= 512
+ ? v.replace(/[\x00-\x1f\x7f]+/g, ' ').trim() || undefined : undefined
+ const head = row.head as { ref?: unknown; repo?: { full_name?: unknown } } | undefined
+ const base = row.base as { ref?: unknown } | undefined
+ return { status: 'found', number: Number(row.number), url: row.html_url,
+ state: row.merged_at ? 'Merged' : row.state === 'closed' ? 'Closed' : row.draft ? 'Draft' : 'Open',
+ ...(label(row.title) ? { title: label(row.title) } : {}),
+ ...(label(head?.ref) ? { headBranch: label(head?.ref) } : {}),
+ ...(label(base?.ref) ? { baseBranch: label(base?.ref) } : {}),
+ ...(label(head?.repo?.full_name) ? { headRepository: label(head?.repo?.full_name) } : {}),
+ }
}
/** 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> => {
+ return async (cwd: string, expected?: PullRequestIdentity): Promise<PullRequestResult> => {
if (!validGitPath(cwd)) return { status: 'unavailable' }
try {
const [branch, remote] = await Promise.all([
@@ -28,32 +81,91 @@ export function createPullRequestReader(execute: Run = run, now = Date.now) {
])
const repo = githubRepository(remote)
if (!repo || !branch) return { status: 'unavailable' }
+ if (expected && (expected.branch !== branch || expected.remote !== canonicalRepository(remote))) return { status: 'unavailable' }
+ const stillCurrent = async (result: PullRequestResult): Promise<PullRequestResult> => {
+ const [head, origin] = await Promise.all([
+ execute('git', ['symbolic-ref', '--quiet', '--short', 'HEAD'], cwd),
+ execute('git', ['remote', 'get-url', 'origin'], cwd),
+ ])
+ return head === branch && origin === remote ? result : { status: 'unavailable' }
+ }
const key = JSON.stringify([cwd, repo, branch])
const previous = cache.get(key)
- if (previous && previous.until > now()) return previous.value
+ if (previous && previous.until > now()) return await stillCurrent(await 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 metadata = JSON.parse(await execute('gh', ['api', '--hostname', 'github.com', '--jq', '{full_name,fork,parent:{full_name:.parent.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' }
+ const parent = metadata.fork && typeof metadata.parent?.full_name === 'string'
+ && githubRepository(`https://github.com/${metadata.parent.full_name}`) === metadata.parent.full_name
+ ? metadata.parent.full_name as string : null
+ const repositories = [...new Set([...(parent ? [parent] : []), canonical])]
+ const found: FoundPullRequest[] = []
+ let unavailable = false
+ const deadline = Date.now() + 10_000
+ for (const baseRepo of repositories) {
+ try {
+ // Ask for open work first, so a long history of closed PRs cannot hide an old open PR.
+ for (const state of ['open', 'closed']) {
+ if (Date.now() >= deadline) { unavailable = true; break }
+ const query = new URLSearchParams({ state, 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,title,state,draft,merged_at,head:{ref:.head.ref,repo:{full_name:.head.repo.full_name}},base:{ref:.base.ref}})', `repos/${baseRepo}/pulls?${query}`], cwd))
+ if (!Array.isArray(rows)) { unavailable = true; break }
+ const matches = rows.filter(p => p?.head?.ref === branch && p?.head?.repo?.full_name?.toLowerCase() === canonical.toLowerCase())
+ for (const match of matches) {
+ const result = prResult(match, baseRepo)
+ if (result.status === 'found') {
+ const duplicate = found.findIndex(p => p.url === result.url)
+ if (duplicate < 0) found.push(result)
+ else if (result.state === 'Open' || result.state === 'Draft') found[duplicate] = result
+ } else unavailable = true
+ }
+ if (matches.length) break
+ }
+ } catch { unavailable = true }
+ }
+ const pr = found.find(p => p.state === 'Open' || p.state === 'Draft') ?? found[0]
+ if (!pr) return { status: unavailable ? 'unavailable' : 'none' }
+ const checkedAt = new Date(now()).toISOString()
+ const related = found.filter(p => p !== pr).slice(0, 127).map(p => ({ ...p, checkedAt }))
+ return { ...pr, checkedAt, ...(related.length ? { related } : {}) }
} catch { return { status: 'unavailable' } }
})()
cache.set(key, { until: now() + 60_000, value })
if (cache.size > 128) cache.delete(cache.keys().next().value!)
- return value
+ return await stillCurrent(await value)
} catch { return { status: 'unavailable' } }
}
}
export const readGitPullRequest = createPullRequestReader()
+
+/** A recorded PR survives its branch and checkout. Resolve it by its durable URL on the owning
+ * machine, without setting cwd to a directory that may since have been removed. */
+export function createPullRequestUrlReader(execute: Run = run, now = Date.now) {
+ const cache = new Map<string, { until: number; value: Promise<PullRequestResult> }>()
+ return async (url: string): Promise<PullRequestResult> => {
+ if (!validPullRequestUrl(url)) return { status: 'unavailable' }
+ const previous = cache.get(url)
+ if (previous && previous.until > now()) return previous.value
+ const value = (async (): Promise<PullRequestResult> => {
+ try {
+ const [, owner, name, , number] = new URL(url).pathname.split('/')
+ const row = JSON.parse(await execute('gh', ['api', '--hostname', 'github.com',
+ '--jq', '{number,html_url,title,state,draft,merged_at,head:{ref:.head.ref,repo:{full_name:.head.repo.full_name}},base:{ref:.base.ref}}', `repos/${owner}/${name}/pulls/${number}`], tmpdir()))
+ // GitHub redirects renamed repositories. Return its canonical URL so history can
+ // merge an old saved alias with a match discovered through the renamed origin.
+ if (!validPullRequestUrl(row?.html_url) || row.number !== Number(number)) return { status: 'unavailable' }
+ const canonical = new URL(row.html_url).pathname.split('/').slice(1, 3).join('/')
+ const result = prResult(row, canonical)
+ return result.status === 'found' ? { ...result, checkedAt: new Date(now()).toISOString() } : result
+ } catch { return { status: 'unavailable' } }
+ })()
+ cache.set(url, { until: now() + 60_000, value })
+ if (cache.size > 256) cache.delete(cache.keys().next().value!)
+ return value
+ }
+}
+export const readPullRequestUrl = createPullRequestUrlReader()
diff --git a/cli/src/lib/literalToolCall.spec.ts b/cli/src/lib/literalToolCall.spec.ts
new file mode 100644
index 000000000..dd6d9e00b
--- /dev/null
+++ b/cli/src/lib/literalToolCall.spec.ts
@@ -0,0 +1,28 @@
+import { describe, expect, it } from 'vitest'
+import { literalToolCall } from './literalToolCall.js'
+
+describe('code-mode literal tool calls', () => {
+ it.each([
+ 'text(await tools.exec_command({cmd: "cargo test", workdir: "/ship-hn"}));',
+ "await tools.exec_command({cmd: 'cargo test', workdir: '/ship-hn',});",
+ 'const result = await tools.exec_command({cmd: `cargo test`, workdir: "/ship-hn", yield_time_ms: 1000}); text(result);',
+ '// @exec: {"max_output_tokens":1000}\ntext(await tools.exec_command({"cmd":"cargo test","workdir":"/ship-hn"}));',
+ ])('recognizes an unconditional call: %s', source => {
+ expect(literalToolCall(source)).toMatchObject({ name: 'exec_command', input: { cmd: 'cargo test', workdir: '/ship-hn' } })
+ })
+ it.each([
+ 'if (false) text(await tools.exec_command({cmd:"pwd",workdir:"/fake"}));',
+ 'text(await tools.exec_command({cmd: command,workdir:"/fake"}));',
+ 'text(await tools.exec_command({cmd:`cd ${path}`,workdir:"/fake"}));',
+ 'text(await tools.exec_command({cmd:"pwd",workdir:"/real",workdir:"/fake"}));',
+ 'text(await tools.exec_command({cmd:"pwd",...overrides}));',
+ 'const result=await tools.exec_command({cmd:"pwd"}); text({result, another: tool()});',
+ 'text(await tools.exec_command({cmd:"pwd"})); text(await tools.exec_command({cmd:"pwd"}));',
+ 'text(await tools.exec_command({cmd:"pwd", workdir:(()=>"/fake")()}));',
+ ])('leaves dynamic or conditional code unknown: %s', source => expect(literalToolCall(source)).toBeNull())
+ it('does not interpret strings as source, properties, or prototype setters', () => {
+ const parsed = literalToolCall('text(await tools.exec_command({cmd:"echo \\\"{workdir: \\\"/fake\\\"}\\\"", workdir:"/real", __proto__: {hidden:true}}));')
+ expect(parsed?.input).toMatchObject({ workdir: '/real' })
+ expect(Object.getPrototypeOf(parsed?.input)).toBeNull()
+ })
+})
diff --git a/cli/src/lib/literalToolCall.ts b/cli/src/lib/literalToolCall.ts
new file mode 100644
index 000000000..1389e6634
--- /dev/null
+++ b/cli/src/lib/literalToolCall.ts
@@ -0,0 +1,88 @@
+/** Read a small literal subset of code-mode calls. This never evaluates JavaScript. */
+function literal(source: string): unknown {
+ let at = 0
+ const fail = (): never => { throw new Error('Not a literal') }
+ const space = () => { while (/\s/.test(source[at] ?? '') && at < source.length) at++ }
+ function string(): string {
+ const quote = source[at++]
+ let result = ''
+ while (at < source.length) {
+ let ch = source[at++]
+ if (ch === quote) return result
+ if (quote === '`' && ch === '$' && source[at] === '{') fail()
+ if (ch === '\n' && quote !== '`') fail()
+ if (ch === '\\') {
+ ch = source[at++]
+ if (ch === undefined) fail()
+ if (ch === '\n') continue
+ if (ch === 'u' || ch === 'x') {
+ const count = ch === 'u' ? 4 : 2, digits = source.slice(at, at + count)
+ if (digits.length !== count || !/^[a-f0-9]+$/i.test(digits)) fail()
+ result += String.fromCharCode(parseInt(digits, 16)); at += count; continue
+ }
+ if (/\d/.test(ch)) fail() // Legacy octal and \0 are not needed for tool arguments.
+ result += ({ n: '\n', r: '\r', t: '\t', b: '\b', f: '\f', v: '\v' } as Record<string, string>)[ch] ?? ch
+ } else result += ch
+ }
+ return fail()
+ }
+ function value(depth = 0): unknown {
+ if (depth > 4) fail()
+ space()
+ const ch = source[at]
+ if (["'", '"', '`'].includes(ch)) return string()
+ if (ch === '{') {
+ at++; space()
+ const result: Record<string, unknown> = Object.create(null)
+ let count = 0
+ while (source[at] !== '}') {
+ if (++count > 32) fail()
+ space()
+ let key: string
+ if (["'", '"'].includes(source[at])) key = string()
+ else {
+ const identifier = /^[a-zA-Z_$][\w$]*/.exec(source.slice(at))?.[0]
+ if (!identifier) fail()
+ key = identifier!; at += key.length
+ }
+ if (Object.hasOwn(result, key)) fail()
+ space(); if (source[at++] !== ':') fail()
+ result[key] = value(depth + 1); space()
+ if (source[at] === '}') break
+ if (source[at++] !== ',') fail()
+ space()
+ }
+ at++; return result
+ }
+ if (ch === '[') {
+ at++; space()
+ const result: unknown[] = []
+ while (source[at] !== ']') {
+ if (result.length >= 32) fail()
+ result.push(value(depth + 1)); space()
+ if (source[at] === ']') break
+ if (source[at++] !== ',') fail()
+ space()
+ }
+ at++; return result
+ }
+ const primitive = /^(?:true|false|null|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)/.exec(source.slice(at))?.[0]
+ if (!primitive) fail()
+ at += primitive!.length
+ return JSON.parse(primitive!)
+ }
+ const result = value()
+ space(); if (at !== source.length) fail()
+ return result
+}
+
+export function literalToolCall(raw: string): { name: string; input: unknown } | null {
+ if (raw.length > 128 * 1024) return null
+ const source = raw.replace(/^\s*\/\/ @exec:[^\n]*\n/, '').trim()
+ const wrapped = /^text\(\s*await\s+tools\.(exec_command|apply_patch|write_stdin)\(([\s\S]*)\)\s*\)\s*;?$/.exec(source)
+ ?? /^await\s+tools\.(exec_command|apply_patch|write_stdin)\(([\s\S]*)\)\s*;?$/.exec(source)
+ const assigned = /^(?:const|let)\s+([a-zA-Z_$][\w$]*)\s*=\s*await\s+tools\.(exec_command|apply_patch|write_stdin)\(([\s\S]*)\)\s*;\s*text\(\s*\1\s*\)\s*;?$/.exec(source)
+ const name = wrapped?.[1] ?? assigned?.[2], argument = wrapped?.[2] ?? assigned?.[3]
+ if (!name || argument === undefined) return null
+ try { return { name, input: literal(argument) } } catch { return null }
+}
diff --git a/cli/src/lib/sessionGitContext.spec.ts b/cli/src/lib/sessionGitContext.spec.ts
new file mode 100644
index 000000000..e81926146
--- /dev/null
+++ b/cli/src/lib/sessionGitContext.spec.ts
@@ -0,0 +1,88 @@
+import { execFileSync } from 'node:child_process'
+import { mkdtemp, mkdir, rm } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { agentProject } from './agentProject.js'
+import { agentFrame } from './agentFrame.js'
+import type { RegisteredSession } from './registry.js'
+import { sessionGitContext, SessionGitContextReader } from './sessionGitContext.js'
+import type { SessionWork } from './sessionWork.js'
+
+const roots: string[] = []
+const at = '2026-09-27T13:00:00.000Z'
+const work = (paths: string[], extra: Partial<SessionWork> = {}): SessionWork => ({
+ current: paths.map(cwd => ({ cwd, at })), locations: paths.map(cwd => ({ cwd, at })),
+ pullRequests: [], uncertain: false, truncated: false, ...extra,
+})
+afterEach(async () => { await Promise.all(roots.splice(0).map(path => rm(path, { recursive: true, force: true }))) })
+
+describe('Git context from observed session work', () => {
+ it('orders overlapping projections and keeps unchanged polling versions stable', async () => {
+ const reader = new SessionGitContextReader()
+ const old = await sessionGitContext(null)
+ const next = { ...old, state: 'uncertain' as const }
+ let finish!: (value: typeof old) => void
+ const slow = reader.read('hn', () => new Promise(resolve => { finish = resolve }))
+ const fast = await reader.read('hn', async () => next)
+ finish(old)
+ expect(await slow).toEqual(fast)
+ expect(await reader.read('hn', async () => next)).toEqual(fast)
+ const other = await reader.read('other-session', async () => old)
+ expect(other.state).toBe('workspace')
+ expect(other.version?.revision).toBeGreaterThan(fast.version!.revision)
+ })
+ it('reads the actual branch of ship-hn while retaining silent-beacon for launch/resume', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'session-git-')); roots.push(root)
+ const home = join(root, 'silent-beacon'), ship = join(root, 'ship-hn')
+ await mkdir(home)
+ const git = (...args: string[]) => execFileSync('git', ['-C', home, ...args], { stdio: 'pipe' })
+ git('init', '-b', 'original')
+ git('-c', 'user.name=Test', '-c', '[email protected]', 'commit', '--allow-empty', '-m', 'initial')
+ git('worktree', 'add', '-b', 'hn/preview-fix', ship)
+ await mkdir(join(ship, 'tui'))
+ const observation = work([join(ship, 'tui')])
+ const launch = await agentProject(home)
+ const context = await sessionGitContext(launch, observation)
+ expect(context).toMatchObject({ state: 'observed', current: { branch: 'hn/preview-fix', worktree: true }, observedAt: at })
+ expect(context.current?.cwd).toBe(context.current?.root)
+ expect(launch?.branch).toBe('original')
+ const session = { agentId: 'hn', sessionId: 's', engine: 'claude', cwd: home,
+ registeredAt: 1, boundAt: 1, lastHookAt: 1, transcriptPath: null, runtimes: [],
+ active: true, title: 'hn' } as unknown as RegisteredSession
+ const frame = await agentFrame(session, { selectedModel: null, terminalAvailable: false,
+ tokenUsage: { totalTokens: null, updatedAt: at, work: observation } })
+ expect(frame.project?.branch).toBe('original')
+ expect(frame.gitContext.current?.branch).toBe('hn/preview-fix')
+ expect(session.cwd).toBe(home)
+ })
+
+ it('collapses different subfolders of one checkout without confusing two worktrees', async () => {
+ const home = { name: 'app', cwd: '/home', root: '/home', branch: 'launch', remote: null }
+ const read = async (cwd: string) => ({ ...home, cwd, root: cwd.startsWith('/one') ? '/one' : '/two', branch: 'topic' })
+ expect(await sessionGitContext(home, work(['/one/src', '/one/test']), read))
+ .toMatchObject({ state: 'observed', current: { cwd: '/one', branch: 'topic' } })
+ expect(await sessionGitContext(home, work(['/one/src', '/two/test']), read))
+ .toMatchObject({ state: 'multiple', current: null })
+ })
+
+ it('keeps absent, unreadable, uncertain and non-Git contexts distinct', async () => {
+ const home = { name: 'app', cwd: '/home', root: '/home', branch: 'launch', remote: null }
+ expect(await sessionGitContext(home)).toMatchObject({ state: 'workspace', current: home })
+ const read = vi.fn(async () => null)
+ expect(await sessionGitContext(home, work(['/gone']), read)).toMatchObject({ state: 'unavailable', current: null })
+ read.mockClear()
+ expect(await sessionGitContext(home, work(['/one'], { uncertain: true }), read)).toMatchObject({ state: 'uncertain', current: null })
+ expect(read).not.toHaveBeenCalled()
+ expect(await sessionGitContext(home, work(['/folder']), async () => ({ ...home, cwd: '/folder', root: null, branch: null })))
+ .toMatchObject({ state: 'observed', current: { cwd: '/folder', branch: null } })
+ })
+
+ it('bounds Git work for a compound operation and preserves durable PR links without a checkout', async () => {
+ const read = vi.fn(async () => null)
+ const pullRequests = [{ url: 'https://github.com/acme/app/pull/12', cwd: '/gone', at }]
+ const context = await sessionGitContext(null, work(Array.from({ length: 20 }, (_, i) => `/work/${i}`), { pullRequests }), read)
+ expect(context).toMatchObject({ state: 'multiple', current: null, truncated: true, pullRequests })
+ expect(read).not.toHaveBeenCalled()
+ })
+})
diff --git a/cli/src/lib/sessionGitContext.ts b/cli/src/lib/sessionGitContext.ts
new file mode 100644
index 000000000..b955469cd
--- /dev/null
+++ b/cli/src/lib/sessionGitContext.ts
@@ -0,0 +1,82 @@
+import { stat } from 'node:fs/promises'
+import { randomUUID } from 'node:crypto'
+import { agentProject, type AgentProject } from './agentProject.js'
+import type { SessionWork, WorkPullRequest } from './sessionWork.js'
+import type { GitHistory } from './sessionGitHistory.js'
+
+export type SessionGitContext = {
+ state: 'workspace' | 'observed' | 'multiple' | 'uncertain' | 'unavailable'
+ current: AgentProject | null
+ observedAt: string | null
+ /** Paths describe observed work, never worktree ownership or deletion eligibility. */
+ locations: Array<{ cwd: string; at: string }>
+ pullRequests: WorkPullRequest[]
+ truncated: boolean
+ history?: GitHistory
+ /** Changes only with the display snapshot; clients reject older list/push responses. */
+ version?: { epoch: string; revision: number }
+}
+
+/** Overlapping projections all finish with the newest requested observation. Versions survive
+ * cache eviction within a daemon, and do not advance during unchanged roster polling. */
+export class SessionGitContextReader {
+ private epoch = randomUUID()
+ private revision = 0
+ private entries = new Map<string, { pending: Promise<SessionGitContext>; users: number; json?: string; value?: SessionGitContext }>()
+ async read(key: string, resolve: () => Promise<SessionGitContext>): Promise<SessionGitContext> {
+ const pending = resolve()
+ let entry = this.entries.get(key)
+ if (!entry) {
+ entry = { pending, users: 0 }
+ this.entries.set(key, entry)
+ }
+ entry.pending = pending
+ entry.users++
+ try {
+ let selected: Promise<SessionGitContext>, value: SessionGitContext
+ do { selected = entry.pending; value = await selected } while (selected !== entry.pending)
+ const json = JSON.stringify(value)
+ if (entry.json !== json) {
+ entry.json = json
+ entry.value = { ...value, version: { epoch: this.epoch, revision: ++this.revision } }
+ }
+ return entry.value!
+ } finally {
+ entry.users--
+ // Never evict an entry while an older projection still references it.
+ for (const [oldKey, old] of this.entries) {
+ if (this.entries.size <= 512) break
+ if (!old.users) this.entries.delete(oldKey)
+ }
+ }
+ }
+}
+type Inspect = (cwd: string) => Promise<AgentProject | null>
+async function inspect(cwd: string): Promise<AgentProject | null> {
+ if (!(await stat(cwd).catch(() => null))?.isDirectory()) return null
+ return agentProject(cwd)
+}
+
+/** Display-only projection. Registry cwd and the legacy project keep their launch semantics. */
+export async function sessionGitContext(home: AgentProject | null, work?: SessionWork | null,
+ read: Inspect = inspect): Promise<SessionGitContext> {
+ const context: SessionGitContext = {
+ state: 'workspace', current: home, observedAt: null,
+ locations: work?.locations ?? [], pullRequests: work?.pullRequests ?? [], truncated: work?.truncated ?? false,
+ }
+ if (!work) return context
+ context.current = null
+ context.observedAt = work.current.reduce<string | null>((at, row) => at && at > row.at ? at : row.at, null)
+ if (work.uncertain || !work.current.length) return { ...context, state: 'uncertain' }
+ // One tool can touch many folders. Resolve only a bounded set; exceeding it cannot imply one.
+ if (work.current.length > 8) return { ...context, state: 'multiple', truncated: true }
+ const projects = await Promise.all(work.current.map(row => read(row.cwd).catch(() => null)))
+ if (projects.some(p => !p)) return { ...context, state: 'unavailable' }
+ const roots = new Map<string, AgentProject>()
+ for (const project of projects) if (project) roots.set(project.root ?? project.cwd, project)
+ if (roots.size !== 1) return { ...context, state: 'multiple' }
+ const project = [...roots.values()][0]
+ // Working on src/ or tui/ should still identify the checkout, independent of the last file tool.
+ context.current = project.root ? { ...project, cwd: project.root } : project
+ return { ...context, state: 'observed' }
+}
diff --git a/cli/src/lib/sessionGitHistory.spec.ts b/cli/src/lib/sessionGitHistory.spec.ts
new file mode 100644
index 000000000..3c79805c5
--- /dev/null
+++ b/cli/src/lib/sessionGitHistory.spec.ts
@@ -0,0 +1,76 @@
+import { mkdtemp, readFile, readdir, rm, stat } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, describe, expect, it } from 'vitest'
+import { SessionGitHistoryStore } from './sessionGitHistory.js'
+import type { RegisteredSession } from './registry.js'
+import type { SessionGitContext } from './sessionGitContext.js'
+
+const dirs: string[] = []
+const at = '2026-09-27T13:00:00.000Z'
+const target = { engine: 'claude', sessionId: 'hn', agentId: 'agent', registeredAt: 1 } as RegisteredSession
+const context = (branch: string, extra: Partial<SessionGitContext> = {}): SessionGitContext => ({
+ state: 'observed', current: { name: 'app', cwd: '/ship-hn', root: '/ship-hn', remote: 'github.com/acme/app', branch },
+ observedAt: at, locations: [], pullRequests: [], truncated: false, ...extra,
+})
+afterEach(async () => { await Promise.all(dirs.splice(0).map(p => rm(p, { recursive: true, force: true }))) })
+describe('durable session Git history', () => {
+ it('merges saved URL aliases after a repository rename without downgrading newer status', async () => {
+ const dir = await mkdtemp(join(tmpdir(), 'git-history-')); dirs.push(dir)
+ const store = new SessionGitHistoryStore(dir)
+ const alias = { url: 'https://github.com/acme/old/pull/12', cwd: '/work', at }
+ const canonical = { ...alias, url: 'https://github.com/acme/new/pull/12' }
+ await store.recordPullRequest(target, alias, { status: 'found', number: 12, url: alias.url, state: 'Open' }, at)
+ await store.recordPullRequest(target, canonical, { status: 'found', number: 12, url: canonical.url, state: 'Merged' }, '2026-09-27T16:00:00Z')
+ await store.recordPullRequest(target, alias, { status: 'found', number: 12, url: canonical.url, state: 'Open' }, at)
+ await store.recordPullRequest(target, alias, { status: 'found', number: 12, url: alias.url, state: 'Open' }, at)
+ await store.observe(target, context('feature', { pullRequests: [alias] }))
+ const saved = await store.get(target)
+ expect(saved.pullRequests).toHaveLength(1)
+ expect(saved.pullRequests[0]).toMatchObject({ url: canonical.url, result: { state: 'Merged', url: canonical.url } })
+ await store.settled()
+ })
+ it('does not evict in-flight writes or let an older lookup undo a merge', async () => {
+ const dir = await mkdtemp(join(tmpdir(), 'git-history-')); dirs.push(dir)
+ const store = new SessionGitHistoryStore(dir, 1)
+ await Promise.all(Array.from({ length: 12 }, (_, i) =>
+ store.observe({ ...target, sessionId: `other-${i}` }, context('feature'))))
+ const pr = { url: 'https://github.com/acme/app/pull/12', cwd: '/ship-hn', at }
+ await store.recordPullRequest(target, pr, { status: 'found', number: 12, url: pr.url, state: 'Merged' }, '2026-09-27T15:00:00Z')
+ await store.observe({ ...target, sessionId: 'eviction-pressure' }, context('other'))
+ await store.recordPullRequest(target, pr, { status: 'found', number: 12, url: pr.url, state: 'Open' }, at)
+ await store.settled()
+ expect((await new SessionGitHistoryStore(dir).get(target)).pullRequests[0].result).toMatchObject({ state: 'Merged' })
+ expect((await readdir(dir)).filter(p => p.endsWith('.json'))).toHaveLength(14)
+ })
+ it('retains multiple branches and PR states across daemon restart and missing checkouts', async () => {
+ const dir = await mkdtemp(join(tmpdir(), 'git-history-')); dirs.push(dir)
+ const store = new SessionGitHistoryStore(dir)
+ await store.observe(target, context('hn/nfc'))
+ await store.observe(target, context('hn/preview'))
+ await store.observe(target, context('hn/preview'))
+ const pr = { url: 'https://github.com/acme/app/pull/12', cwd: '/ship-hn', at }
+ const merged = { status: 'found' as const, number: 12, state: 'Merged' as const, url: pr.url }
+ await store.recordPullRequest(target, pr, merged, at)
+ await store.recordPullRequest(target, pr, { status: 'unavailable' }, '2026-09-27T14:00:00.000Z')
+ await store.settled()
+ const restarted = new SessionGitHistoryStore(dir)
+ const saved = await restarted.observe(target, context('', { state: 'unavailable', current: null }))
+ expect(saved.branches.map(b => b.branch).sort()).toEqual(['hn/nfc', 'hn/preview'])
+ expect(saved.pullRequests).toEqual([{ ...pr, result: merged, checkedAt: at }])
+ const file = join(dir, (await readdir(dir))[0])
+ expect((await stat(file)).mode & 0o777).toBe(0o600)
+ expect(await readFile(file, 'utf8')).not.toContain('command')
+ expect((await restarted.get({ ...target, sessionId: 'other' })).branches).toEqual([])
+ expect((await restarted.get({ ...target, forkedFrom: { agentId: 'parent', name: 'Parent' }, registeredAt: 2 })).branches).toEqual([])
+ })
+
+ it('does not claim the launch branch or uncertain work as a branch worked on', async () => {
+ const dir = await mkdtemp(join(tmpdir(), 'git-history-')); dirs.push(dir)
+ const store = new SessionGitHistoryStore(dir)
+ await store.observe(target, context('main', { state: 'workspace' }))
+ await store.observe(target, context('maybe', { state: 'uncertain', current: null }))
+ expect((await store.get(target)).branches).toEqual([])
+ expect(await readdir(dir)).toEqual([])
+ })
+})
diff --git a/cli/src/lib/sessionGitHistory.ts b/cli/src/lib/sessionGitHistory.ts
new file mode 100644
index 000000000..cf0942b3a
--- /dev/null
+++ b/cli/src/lib/sessionGitHistory.ts
@@ -0,0 +1,148 @@
+/** Durable associations, scoped to one conversation on its owning machine. Never cleanup authority. */
+import { createHash, randomUUID } from 'node:crypto'
+import { mkdir, readFile, rename, stat, unlink, writeFile } from 'node:fs/promises'
+import { join } from 'node:path'
+import { env } from '../config/env.js'
+import type { RegisteredSession } from './registry.js'
+import type { SessionGitContext } from './sessionGitContext.js'
+import { validPullRequestUrl, validWorkPath, type WorkPullRequest } from './sessionWork.js'
+import type { PullRequestResult } from './gitPullRequest.js'
+
+export type WorkBranch = { cwd: string; remote: string | null; branch: string; at: string }
+export type RecordedPullRequest = WorkPullRequest & { result?: PullRequestResult; checkedAt?: string; aliases?: string[] }
+export type GitHistory = { branches: WorkBranch[]; pullRequests: RecordedPullRequest[]; truncated: boolean }
+type Target = Pick<RegisteredSession, 'engine' | 'sessionId' | 'agentId' | 'codexHome' | 'forkedFrom' | 'registeredAt'>
+type Entry = { value: GitHistory; loaded: Promise<void>; saving: Promise<void>; readers: number; writes: number }
+const MAX = 128
+const empty = (): GitHistory => ({ branches: [], pullRequests: [], truncated: false })
+function keyFor(target: Target): string {
+ return createHash('sha256').update(JSON.stringify([target.engine, target.codexHome ?? '',
+ target.sessionId || target.agentId, target.forkedFrom ? target.registeredAt : null])).digest('hex')
+}
+const label = (v: unknown): v is string => typeof v === 'string' && v.length > 0 && v.length <= 4096 && !/[\x00-\x1f\x7f]/.test(v)
+const date = (v: unknown): v is string => typeof v === 'string' && Number.isFinite(Date.parse(v))
+/** The server pages in the same order the two clients display. Unknown precedes finished work. */
+export function comparePullRequests(a: RecordedPullRequest, b: RecordedPullRequest): number {
+ const rank = (p: RecordedPullRequest) => p.result?.status !== 'found' ? 1
+ : p.result.state === 'Open' || p.result.state === 'Draft' ? 0 : 2
+ return rank(a) - rank(b) || Date.parse(b.at) - Date.parse(a.at)
+ || (a.url === b.url ? 0 : a.url < b.url ? -1 : 1)
+}
+function valid(value: unknown): value is GitHistory {
+ if (!value || typeof value !== 'object') return false
+ const row = value as GitHistory
+ return typeof row.truncated === 'boolean' && Array.isArray(row.branches) && row.branches.length <= MAX
+ && row.branches.every(b => validWorkPath(b?.cwd) && label(b.branch) && (b.remote === null || label(b.remote)) && date(b.at))
+ && Array.isArray(row.pullRequests) && row.pullRequests.length <= MAX
+ && row.pullRequests.every(p => validPullRequestUrl(p?.url) && (p.cwd === null || validWorkPath(p.cwd)) && date(p.at)
+ && (p.aliases === undefined || Array.isArray(p.aliases) && p.aliases.length <= 16 && p.aliases.every(validPullRequestUrl))
+ && (p.checkedAt === undefined || date(p.checkedAt)) && (p.result === undefined || p.result.status === 'none'
+ || p.result.status === 'unavailable' || p.result.status === 'found' && p.result.url === p.url
+ && Number.isSafeInteger(p.result.number) && p.result.number > 0 && p.url.endsWith(`/pull/${p.result.number}`)
+ && ['Draft', 'Open', 'Merged', 'Closed'].includes(p.result.state)))
+}
+
+export class SessionGitHistoryStore {
+ private entries = new Map<string, Entry>()
+ constructor(private readonly directory: string, private readonly capacity = 512) {}
+ private trim(): void {
+ for (const [key, entry] of this.entries) {
+ if (this.entries.size <= this.capacity) break
+ if (!entry.readers && !entry.writes) this.entries.delete(key)
+ }
+ }
+ private entry(target: Target): [string, Entry] {
+ const key = keyFor(target)
+ let entry = this.entries.get(key)
+ if (!entry) {
+ entry = { value: empty(), loaded: Promise.resolve(), saving: Promise.resolve(), readers: 0, writes: 0 }
+ const current = entry
+ entry.loaded = (async () => {
+ try {
+ const path = join(this.directory, `${key}.json`)
+ if ((await stat(path)).size > 512 * 1024) return
+ const data: unknown = JSON.parse(await readFile(path, 'utf8'))
+ if (valid(data)) current.value = data
+ } catch { /* Missing/corrupt history remains unknown, never a reason to stop a session. */ }
+ })()
+ this.entries.set(key, entry)
+ }
+ entry.readers++
+ this.trim()
+ return [key, entry]
+ }
+ async get(target: Target): Promise<GitHistory> {
+ const [, entry] = this.entry(target)
+ try {
+ await entry.loaded
+ const value = structuredClone(entry.value)
+ value.pullRequests.sort(comparePullRequests)
+ return value
+ } finally { entry.readers--; this.trim() }
+ }
+ async observe(target: Target, context: SessionGitContext): Promise<GitHistory> {
+ const [key, entry] = this.entry(target)
+ try {
+ await entry.loaded
+ const before = JSON.stringify(entry.value)
+ const current = context.current
+ const branch = current?.branch
+ // The launch checkout is context, not evidence that this conversation worked on its branch.
+ if (context.state === 'observed' && current && branch && !branch.startsWith('Detached ')) {
+ const same = (b: WorkBranch) => b.cwd === (current.root ?? current.cwd) && b.branch === branch && b.remote === current.remote
+ const previous = entry.value.branches.find(same)
+ // Retrospective tool receipts cannot establish when this branch was checked out.
+ const at = previous ? context.observedAt ?? previous.at : new Date().toISOString()
+ if (!previous || previous.at < at) entry.value.branches = [
+ { cwd: current.root ?? current.cwd, branch, remote: current.remote, at }, ...entry.value.branches.filter(b => !same(b)),
+ ]
+ }
+ for (const pr of context.pullRequests) if (!entry.value.pullRequests.some(p => p.url === pr.url || p.aliases?.includes(pr.url))) entry.value.pullRequests.unshift({ ...pr })
+ entry.value.truncated ||= context.truncated || entry.value.branches.length > MAX || entry.value.pullRequests.length > MAX
+ entry.value.branches = entry.value.branches.sort((a, b) => b.at.localeCompare(a.at)).slice(0, MAX)
+ entry.value.pullRequests = entry.value.pullRequests.sort((a, b) => b.at.localeCompare(a.at)).slice(0, MAX)
+ if (before !== JSON.stringify(entry.value)) this.save(key, entry)
+ const value = structuredClone(entry.value)
+ value.pullRequests.sort(comparePullRequests)
+ return value
+ } finally { entry.readers--; this.trim() }
+ }
+ async recordPullRequest(target: Target, pr: WorkPullRequest, result: PullRequestResult, checkedAt: string): Promise<void> {
+ if (!validPullRequestUrl(pr.url)) return
+ const [key, entry] = this.entry(target)
+ try {
+ await entry.loaded
+ let url = result.status === 'found' ? result.url : pr.url
+ if (!validPullRequestUrl(url)) return
+ const matches = (p: RecordedPullRequest) => p.url === pr.url || p.url === url || !!p.aliases?.includes(pr.url)
+ const candidates = entry.value.pullRequests.filter(matches)
+ const existing = candidates.sort((a, b) => (b.checkedAt ?? '').localeCompare(a.checkedAt ?? ''))[0]
+ // Network failures preserve the last observed state, with its original observation time.
+ if (result.status === 'unavailable' && existing) return
+ const source = existing?.checkedAt && existing.checkedAt > checkedAt ? existing : { ...pr, result, checkedAt }
+ if (source === existing) url = existing.url
+ const aliases = [...new Set([pr.url, ...candidates.flatMap(p => [p.url, ...(p.aliases ?? [])])])].filter(alias => alias !== url).slice(0, 16)
+ const next = { ...source, url,
+ ...(aliases.length ? { aliases } : {}),
+ ...(source.result?.status === 'found' ? { result: { ...source.result, url } } : {}) }
+ entry.value.pullRequests = [next, ...entry.value.pullRequests.filter(p => !matches(p))]
+ if (entry.value.pullRequests.length > MAX) { entry.value.pullRequests.length = MAX; entry.value.truncated = true }
+ this.save(key, entry)
+ } finally { entry.readers--; this.trim() }
+ }
+ private save(key: string, entry: Entry): void {
+ const bytes = JSON.stringify(entry.value)
+ entry.writes++
+ entry.saving = entry.saving.then(async () => {
+ const temporary = join(this.directory, `${key}.${randomUUID()}.tmp`)
+ try {
+ await mkdir(this.directory, { recursive: true, mode: 0o700 })
+ await writeFile(temporary, bytes, { mode: 0o600, flag: 'wx' })
+ await rename(temporary, join(this.directory, `${key}.json`))
+ } finally { await unlink(temporary).catch(() => {}) }
+ }).catch(() => { /* Display keeps the in-memory observations if disk is temporarily unavailable. */ })
+ .finally(() => { entry.writes--; this.trim() })
+ }
+ async settled(): Promise<void> { await Promise.all([...this.entries.values()].map(e => e.saving)) }
+}
+export const sessionGitHistory = new SessionGitHistoryStore(join(env.ADAPTER_DATA_DIR, 'session-git-history'))
diff --git a/cli/src/lib/sessionGitPullRequest.spec.ts b/cli/src/lib/sessionGitPullRequest.spec.ts
new file mode 100644
index 000000000..1573d506b
--- /dev/null
+++ b/cli/src/lib/sessionGitPullRequest.spec.ts
@@ -0,0 +1,132 @@
+import { execFileSync } from 'node:child_process'
+import { appendFile, mkdir, mkdtemp, realpath, rm, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { AgentTokenUsageCache, agentTokenUsage } from './agentTokenUsage.js'
+import { agentFrame } from './agentFrame.js'
+import { forgetAgentProject } from './agentProject.js'
+import { SessionGitHistoryStore, sessionGitHistory } from './sessionGitHistory.js'
+import { readSessionGitPullRequest } from './sessionGitPullRequest.js'
+import * as github from './gitPullRequest.js'
+import type { RegisteredSession } from './registry.js'
+
+describe('session work from transcript through Git and PR history', () => {
+ let directory: string, home: string, ship: string, agent: RegisteredSession
+ let usage: AgentTokenUsageCache, history: SessionGitHistoryStore, now: number
+ const git = (cwd: string, ...args: string[]) => execFileSync('git', ['-C', cwd, ...args], { encoding: 'utf8', stdio: 'pipe' }).trim()
+ const line = (v: unknown) => JSON.stringify(v) + '\n'
+ const pr = (number: number, branch: string, merged = false) => ({
+ number, html_url: `https://github.com/acme/app/pull/${number}`, title: `Fix ${branch}`,
+ state: merged ? 'closed' : 'open', merged_at: merged ? '2026-09-27T15:00:00Z' : null,
+ head: { ref: branch, repo: { full_name: 'acme/app' } }, base: { ref: 'main' },
+ })
+ let rows: ReturnType<typeof pr>[]
+ const execute = async (command: string, args: string[], cwd: string) => {
+ if (command === 'git') return git(cwd, ...args)
+ const endpoint = args.at(-1)!
+ if (/\/pulls\/\d+$/.test(endpoint)) return JSON.stringify(rows.find(p => endpoint.endsWith(`/${p.number}`)))
+ if (endpoint.includes('/pulls?')) {
+ const query = new URLSearchParams(endpoint.split('?')[1])
+ return JSON.stringify(rows.filter(p => query.get('head') === `acme:${p.head.ref}` && query.get('state') === p.state))
+ }
+ return JSON.stringify({ full_name: 'acme/app' })
+ }
+ const receipt = async (id: string, cwd: string, number?: number) => {
+ const at = new Date(now += 30_000).toISOString()
+ await appendFile(agent.transcriptPath!, [
+ { timestamp: at, sessionId: 'hn', cwd: home, type: 'assistant', message: { content: [
+ { type: 'tool_use', id, name: 'Bash', input: { command: `cd '${cwd}' && ${number ? 'gh pr create --title Fix' : 'git status --short'}` } },
+ ] } },
+ { timestamp: at, sessionId: 'hn', cwd: home, type: 'user', message: { content: [
+ { type: 'tool_result', tool_use_id: id, content: number ? `https://github.com/acme/app/pull/${number}` : '' },
+ ] } },
+ ].map(line).join(''))
+ usage.changed(agent); await usage.settled()
+ for (const path of [home, ship, join(ship, 'tui')]) forgetAgentProject(path)
+ }
+ const frame = () => agentFrame(agent, { selectedModel: null, terminalAvailable: true, tokenUsage: usage.get(agent) })
+ beforeEach(async () => {
+ directory = await realpath(await mkdtemp(join(tmpdir(), 'session-work-e2e-')))
+ home = join(directory, 'silent-beacon'); ship = join(directory, 'ship-hn')
+ await mkdir(home)
+ git(home, 'init', '-b', 'original')
+ git(home, '-c', 'user.name=Test', '-c', '[email protected]', 'commit', '--allow-empty', '-m', 'Initial')
+ git(home, 'remote', 'add', 'origin', 'https://github.com/acme/app.git')
+ git(home, 'worktree', 'add', '-b', 'hn/nfc', ship)
+ await mkdir(join(ship, 'tui'))
+ agent = { agentId: 'hn-agent', sessionId: 'hn', engine: 'claude', cwd: home, registeredAt: 1,
+ boundAt: 1, lastHookAt: 1, transcriptPath: join(directory, 'hn.jsonl'), runtimes: [], active: true, title: 'hn' } as unknown as RegisteredSession
+ await writeFile(agent.transcriptPath!, '')
+ now = Date.parse('2026-09-27T13:00:00Z')
+ usage = new AgentTokenUsageCache(join(directory, 'usage'), { now: () => now })
+ history = new SessionGitHistoryStore(join(directory, 'history'))
+ vi.spyOn(agentTokenUsage, 'get').mockImplementation(target => usage.get(target))
+ vi.spyOn(sessionGitHistory, 'get').mockImplementation(target => history.get(target))
+ vi.spyOn(sessionGitHistory, 'observe').mockImplementation((target, context) => history.observe(target, context))
+ vi.spyOn(sessionGitHistory, 'recordPullRequest').mockImplementation((...args) => history.recordPullRequest(...args))
+ vi.spyOn(github, 'readGitPullRequest').mockImplementation(github.createPullRequestReader(execute))
+ vi.spyOn(github, 'readPullRequestUrl').mockImplementation(github.createPullRequestUrlReader(execute))
+ rows = [pr(12, 'hn/nfc'), pr(13, 'hn/preview')]
+ })
+ afterEach(async () => {
+ usage.dispose(); await usage.settled(); await history.settled()
+ vi.restoreAllMocks(); await rm(directory, { recursive: true, force: true })
+ })
+
+ it('shows the observed checkout, follows branch switches, and retains merged PRs after removal/restart', async () => {
+ await receipt('nfc', join(ship, 'tui'), 12)
+ const first = await frame()
+ expect(first.project?.branch).toBe('original')
+ expect(first.gitContext.current).toMatchObject({ cwd: ship, branch: 'hn/nfc', worktree: true })
+ const expected = { cwd: ship, branch: 'hn/nfc', remote: 'github.com/acme/app' }
+ expect(await readSessionGitPullRequest(agent, { expected })).toMatchObject({ status: 'found', number: 12, context: expected })
+
+ git(ship, 'switch', '-c', 'hn/preview')
+ await receipt('preview', join(ship, 'tui'), 13)
+ const second = await frame()
+ expect(second.gitContext.current?.branch).toBe('hn/preview')
+ expect(second.gitContext.version!.revision).toBeGreaterThan(first.gitContext.version!.revision)
+ expect((await readSessionGitPullRequest(agent, { expected })).status).toBe('unavailable')
+ expect(await readSessionGitPullRequest(agent)).toMatchObject({ status: 'found', number: 13 })
+ expect(agent.cwd).toBe(home)
+
+ git(home, 'worktree', 'remove', '--force', ship)
+ git(home, 'branch', '-D', 'hn/nfc', 'hn/preview')
+ rows = rows.map(p => pr(p.number, p.head.ref, true))
+ const removed = await readSessionGitPullRequest(agent, { history: true })
+ expect(removed).toMatchObject({ status: 'unavailable', gitContext: { state: 'unavailable', current: null } })
+ expect('history' in removed && removed.history.pullRequests.map(p => p.result?.status === 'found' && p.result.state)).toEqual(['Merged', 'Merged'])
+ await history.settled()
+ const restarted = await new SessionGitHistoryStore(join(directory, 'history')).get(agent)
+ expect(restarted.branches.map(b => b.branch).sort()).toEqual(['hn/nfc', 'hn/preview'])
+ expect(restarted.pullRequests).toHaveLength(2)
+ vi.mocked(github.readPullRequestUrl).mockResolvedValue({ status: 'unavailable' })
+ const offline = await readSessionGitPullRequest(agent, { history: true })
+ expect('history' in offline && offline.history.pullRequests).toEqual(restarted.pullRequests)
+ })
+
+ it('rejects a badge if work moves while GitHub is answering', async () => {
+ await receipt('nfc', ship)
+ vi.mocked(github.readGitPullRequest).mockImplementation(async () => {
+ await receipt('elsewhere', home)
+ return { status: 'found', number: 12, state: 'Open', url: rows[0].html_url }
+ })
+ expect(await readSessionGitPullRequest(agent, {
+ expected: { cwd: ship, branch: 'hn/nfc', remote: 'github.com/acme/app' },
+ })).toMatchObject({ status: 'unavailable', context: { cwd: home, branch: 'original' } })
+ })
+
+ it('refreshes the visible open-first page, including multiple PRs for one branch', async () => {
+ await receipt('nfc', ship)
+ rows = [pr(12, 'hn/nfc'), pr(14, 'hn/nfc')]
+ await readSessionGitPullRequest(agent)
+ for (const number of [20, 21, 22, 23]) {
+ const item = pr(number, 'old', true); rows.push(item)
+ await history.recordPullRequest(agent, { url: item.html_url, cwd: ship, at: '2026-09-27T16:00:00Z' },
+ { status: 'found', number, url: item.html_url, state: 'Merged' }, '2026-09-27T16:00:00Z')
+ }
+ const result = await readSessionGitPullRequest(agent, { history: true })
+ expect('lookups' in result && result.lookups.map(p => p.url)).toEqual([12, 14, 20, 21].map(n => `https://github.com/acme/app/pull/${n}`))
+ })
+})
diff --git a/cli/src/lib/sessionGitPullRequest.ts b/cli/src/lib/sessionGitPullRequest.ts
new file mode 100644
index 000000000..194619836
--- /dev/null
+++ b/cli/src/lib/sessionGitPullRequest.ts
@@ -0,0 +1,56 @@
+import type { RegisteredSession } from './registry.js'
+import { agentProject } from './agentProject.js'
+import { agentTokenUsage } from './agentTokenUsage.js'
+import { sessionGitContext } from './sessionGitContext.js'
+import { sessionGitHistory } from './sessionGitHistory.js'
+import { readGitPullRequest, readPullRequestUrl } from './gitPullRequest.js'
+
+export type ExpectedGitContext = { cwd: string; branch: string; remote: string | null }
+/** The branch badge and session history share the same resolved checkout. Existing callers may
+ * omit expected context; new clients bind their reply to the branch they displayed when asking. */
+export async function readSessionGitPullRequest(agent: RegisteredSession, options: {
+ expected?: ExpectedGitContext; history?: boolean; offset?: number;
+} = {}) {
+ const work = agentTokenUsage.get(agent)?.work
+ let context = await sessionGitContext(await agentProject(agent.cwd), work)
+ await sessionGitHistory.observe(agent, context)
+ const current = 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
+ let result = matches && current && !current.branch?.startsWith('Detached ')
+ ? identity ? await readGitPullRequest(current.cwd, identity) : await readGitPullRequest(current.cwd)
+ : { status: 'unavailable' as const }
+ const checkedAt = new Date().toISOString()
+ if (result.status === 'found' && context.state === 'observed') for (const pr of [result, ...(result.related ?? [])]) {
+ const { related: _, ...recorded } = pr
+ await sessionGitHistory.recordPullRequest(agent,
+ { url: pr.url, cwd: current!.cwd, at: context.observedAt ?? checkedAt }, recorded, pr.checkedAt ?? checkedAt)
+ }
+ const refreshMovedWork = async () => {
+ const latest = agentTokenUsage.get(agent)?.work
+ if (JSON.stringify(latest) === JSON.stringify(work)) return
+ context = await sessionGitContext(await agentProject(agent.cwd), latest)
+ await sessionGitHistory.observe(agent, context)
+ const project = context.current
+ identity = project?.branch ? { cwd: project.cwd, branch: project.branch, remote: project.remote } : null
+ result = { status: 'unavailable' }
+ }
+ if (!options.history) {
+ await refreshMovedWork()
+ return options.expected ? { ...result, context: identity } : result
+ }
+
+ const saved = await sessionGitHistory.get(agent)
+ const offset = Number.isSafeInteger(options.offset) && options.offset! >= 0 ? Math.min(options.offset!, 128) : 0
+ const page = saved.pullRequests.slice(offset, offset + 4)
+ const lookups = await Promise.all(page.map(async pr => {
+ const answer = await readPullRequestUrl(pr.url)
+ await sessionGitHistory.recordPullRequest(agent, pr, answer, answer.status === 'found' ? answer.checkedAt ?? checkedAt : checkedAt)
+ return { url: pr.url, status: answer.status }
+ }))
+ await refreshMovedWork()
+ const history = await sessionGitHistory.get(agent)
+ return { ...result, context: identity, gitContext: context, history, lookups,
+ nextOffset: offset + page.length < saved.pullRequests.length ? offset + page.length : null }
+}
diff --git a/cli/src/lib/sessionWork.spec.ts b/cli/src/lib/sessionWork.spec.ts
new file mode 100644
index 000000000..cf3025a40
--- /dev/null
+++ b/cli/src/lib/sessionWork.spec.ts
@@ -0,0 +1,189 @@
+import { describe, expect, it } from 'vitest'
+import { emptySessionWork, ingestSessionWork, sessionWorkSnapshot, shellWorkLocations, validSessionWork } from './sessionWork.js'
+
+const at = '2026-09-27T13:00:00.000Z'
+function fixture(engine = 'claude') {
+ const state = emptySessionWork()
+ const row = (value: Record<string, unknown>) => ingestSessionWork(state, { timestamp: at, ...value }, engine, '/home/silent-beacon')
+ const start = (id: string, input: unknown, name = engine === 'claude' ? 'Bash' : 'exec_command') => row(engine === 'claude'
+ ? { type: 'assistant', cwd: '/home/silent-beacon', message: { content: [{ type: 'tool_use', id, name, input }] } }
+ : { type: 'response_item', payload: { type: 'function_call', call_id: id, name, arguments: JSON.stringify(input) } })
+ const finish = (id: string, output: unknown = 'ok', failed = false) => row(engine === 'claude'
+ ? { type: 'user', message: { content: [{ type: 'tool_result', tool_use_id: id, content: output, is_error: failed }] } }
+ : { type: 'response_item', payload: { type: 'function_call_output', call_id: id, output, is_error: failed } })
+ return { state, row, start, finish, snapshot: () => sessionWorkSnapshot(state) }
+}
+
+describe('literal work location evidence', () => {
+ it('resolves the hn worktree instead of the shell reset directory', () => {
+ expect(shellWorkLocations('cd /worktrees/ship-hn/tui && cargo test --release --offline 2>&1 | grep result', '/worktrees/silent-beacon'))
+ .toEqual({ paths: ['/worktrees/ship-hn/tui'], createsPr: false })
+ })
+
+ it.each([
+ ['cd "/worktrees/ship hn/tui" && cargo test', ['/worktrees/ship hn/tui']],
+ ["cd '/worktrees/ship hn' && cd tui && cargo test", ['/worktrees/ship hn/tui']],
+ ['git -C ../ship-hn status', ['/worktrees/ship-hn']],
+ ['echo "cd /worktrees/other && gh pr create"', ['/worktrees/silent-beacon']],
+ ['# cd /not-used\npwd', ['/worktrees/silent-beacon']],
+ ['cd /one && cargo test\ncd /two && cargo test', ['/one', '/two']],
+ ["cd '/literal/$HOME' && pwd", ['/literal/$HOME']],
+ ])('understands literal command %s', (command, paths) => {
+ expect(shellWorkLocations(command, '/worktrees/silent-beacon')?.paths).toEqual(paths)
+ })
+
+ it.each([
+ 'cd "$TASK_DIR" && cargo test', 'cd /other; cargo test', 'cd /other || cargo test',
+ 'cd $(get-dir) && pwd', 'cd `get-dir` && pwd', 'cd /one && test & cd /two && test',
+ 'if true; then cd /other; fi', 'echo <<EOF\ncd /other\nEOF', 'bash -c "cd /other && test"',
+ 'env GIT_DIR=/other/.git git status', 'GIT_WORK_TREE=/other git status',
+ 'git --git-dir=/other/.git status', 'git -C /one -C /two status',
+ 'export GIT_DIR=/other/.git; git status', 'git --work-tree /other status',
+ 'pushd /other && test', '! cd /other && test', 'command cd /other && test',
+ 'cd /other && (echo hi)', 'cd "unterminated',
+ ])('keeps ambiguous execution unknown: %s', command => {
+ expect(shellWorkLocations(command, '/worktrees/silent-beacon')).toBeNull()
+ })
+
+ it('does not confuse quoted PR commands or later output with creation', () => {
+ expect(shellWorkLocations('echo "gh pr create"', '/work')?.createsPr).toBe(false)
+ expect(shellWorkLocations('gh pr create && echo https://github.com/a/b/pull/1', '/work')?.createsPr).toBe(false)
+ expect(shellWorkLocations('cd /work && gh pr create --title "A fix"', '/home')?.createsPr).toBe(true)
+ })
+})
+
+describe('per-session work receipts', () => {
+ it('joins yielded process receipts to passive waits without promoting their completion order', () => {
+ const f = fixture('codex')
+ f.start('slow', { cmd: 'gh pr create', workdir: '/one' })
+ f.finish('slow', JSON.stringify({ session_id: 14, output: '' }))
+ expect(validSessionWork(JSON.parse(JSON.stringify(f.state)))).toBe(true)
+ f.start('newer', { cmd: 'pwd', workdir: '/two' }); f.finish('newer')
+ expect(f.snapshot()?.uncertain).toBe(true)
+ f.start('poll', { session_id: 14, chars: '' }, 'write_stdin')
+ f.finish('poll', JSON.stringify({ exit_code: 0, output: 'https://github.com/acme/app/pull/12' }))
+ expect(f.snapshot()).toMatchObject({ uncertain: false, current: [{ cwd: '/two' }],
+ pullRequests: [{ url: 'https://github.com/acme/app/pull/12', cwd: '/one' }] })
+ expect(Object.keys(f.state.running)).toHaveLength(0)
+ })
+ it('joins code-mode cells and nested process waits without evaluating code', () => {
+ const f = fixture('codex')
+ f.row({ type: 'response_item', payload: { type: 'custom_tool_call', call_id: 'code', name: 'exec',
+ input: 'text(await tools.exec_command({cmd: "cargo test", workdir: "/ship-hn"}));' } })
+ f.finish('code', 'Script running with cell ID cell-123')
+ f.start('wait', { cell_id: 'cell-123' }, 'functions.wait')
+ f.finish('wait', 'Script completed\nOutput:\n{"session_id":14,"output":""}')
+ f.row({ type: 'response_item', payload: { type: 'custom_tool_call', call_id: 'poll', name: 'exec',
+ input: 'text(await tools.write_stdin({session_id: 14, chars: ""}));' } })
+ f.finish('poll', 'Script completed\nOutput:\n{"exit_code":0,"output":"ok"}')
+ expect(f.snapshot()).toMatchObject({ current: [{ cwd: '/ship-hn' }], uncertain: false })
+ })
+ it('does not infer a cwd from input sent to an interactive process', () => {
+ const f = fixture('codex')
+ f.start('shell', { cmd: 'zsh', workdir: '/old' })
+ f.finish('shell', 'Process running with session ID 14')
+ f.start('input', { session_id: 14, chars: 'cd /other\n' }, 'write_stdin')
+ f.finish('input', 'Process exited with code 0')
+ expect(f.snapshot()).toMatchObject({ current: [], uncertain: true })
+ })
+ it.each(['claude', 'codex'])('records successful %s tools, separately from launch cwd', engine => {
+ const f = fixture(engine)
+ f.start('one', { command: 'cd /worktrees/ship-hn/tui && cargo test' })
+ expect(f.snapshot()).toMatchObject({ current: [], uncertain: true })
+ f.finish('one')
+ expect(f.snapshot()).toMatchObject({ current: [{ cwd: '/worktrees/ship-hn/tui', at }], uncertain: false })
+ expect(validSessionWork(JSON.parse(JSON.stringify(f.state)))).toBe(true)
+ expect(JSON.stringify(f.snapshot())).not.toContain('cargo')
+ })
+
+ it('keeps overlapping work uncertain and does not regress to an older call completing last', () => {
+ const f = fixture()
+ f.start('slow', { command: 'cd /one && test' })
+ f.start('new', { command: 'cd /two && test' })
+ f.finish('new')
+ expect(f.snapshot()).toMatchObject({ uncertain: true })
+ f.finish('slow')
+ expect(f.snapshot()).toMatchObject({ current: [{ cwd: '/two' }], uncertain: false })
+ expect(f.snapshot()?.locations.map(p => p.cwd).sort()).toEqual(['/one', '/two'])
+ })
+
+ it.each([
+ ['failure', true], ['Process exited with code 1\nerror', false],
+ [JSON.stringify({ exit_code: 1, output: 'oops' }), false],
+ [JSON.stringify({ session_id: 14, output: '', exit_code: null }), false],
+ ['Script running with cell ID 13', false],
+ ])('never claims failed/running work was verified: %s', (output, error) => {
+ const f = fixture()
+ f.start('one', { command: 'cd /other && test' })
+ f.finish('one', output, error)
+ expect(f.snapshot()).toMatchObject({ current: [], locations: [], uncertain: true })
+ })
+
+ it('leaves known history intact after uncertain work and ignores unrelated tools', () => {
+ const f = fixture()
+ f.start('known', { command: 'cd /one && test' }); f.finish('known')
+ f.start('search', { query: 'hello' }, 'WebSearch'); f.finish('search')
+ expect(f.snapshot()?.uncertain).toBe(false)
+ f.start('unknown', { command: 'cd "$TASK" && test' }); f.finish('unknown')
+ expect(f.snapshot()).toMatchObject({ current: [], locations: [{ cwd: '/one' }], uncertain: true })
+ })
+
+ it('uses explicit Codex workdir and turn context, including code mode without evaluation', () => {
+ const f = fixture('codex')
+ f.row({ type: 'turn_context', payload: { cwd: '/turn' } })
+ f.start('explicit', { cmd: 'cargo test', workdir: '/specific' }); f.finish('explicit')
+ expect(f.snapshot()?.current[0]?.cwd).toBe('/specific')
+ f.start('default', { cmd: 'cargo test' }); f.finish('default')
+ expect(f.snapshot()?.current[0]?.cwd).toBe('/turn')
+ f.row({ type: 'response_item', payload: { type: 'custom_tool_call', call_id: 'code', name: 'exec',
+ input: 'text(await tools.exec_command({"cmd":"cargo test","workdir":"/code"}));' } })
+ f.finish('code', JSON.stringify({ exit_code: 0, output: 'ok' }))
+ expect(f.snapshot()?.current[0]?.cwd).toBe('/code')
+ f.row({ type: 'response_item', payload: { type: 'custom_tool_call', call_id: 'dynamic', name: 'exec',
+ input: 'if (false) text(await tools.exec_command({"cmd":"test","workdir":"/fake"}));' } })
+ f.finish('dynamic')
+ expect(f.snapshot()).toMatchObject({ current: [], uncertain: true })
+ })
+
+ it('tracks file tools without treating a mentioned path as a checkout', () => {
+ const f = fixture()
+ f.start('edit', { file_path: '/worktree/src/app.ts', old_string: '/another' }, 'Edit'); f.finish('edit')
+ expect(f.snapshot()?.current[0]?.cwd).toBe('/worktree/src')
+ })
+ it('tracks patch file locations, including a literal code-mode patch', () => {
+ const f = fixture('codex')
+ const patch = '*** Begin Patch\n*** Update File: /ship-hn/tui/src/main.rs\n@@\n-old\n+new\n*** End Patch'
+ f.row({ type: 'response_item', payload: { type: 'custom_tool_call', call_id: 'patch', name: 'apply_patch', input: patch } })
+ f.finish('patch', 'Success. Updated the following files:\nM /ship-hn/tui/src/main.rs')
+ expect(f.snapshot()?.current[0]?.cwd).toBe('/ship-hn/tui/src')
+ f.row({ type: 'response_item', payload: { type: 'custom_tool_call', call_id: 'code-patch', name: 'exec',
+ input: `text(await tools.apply_patch(${JSON.stringify(patch)}));` } })
+ f.finish('code-patch', 'Success. Updated the following files:\nM /ship-hn/tui/src/main.rs')
+ expect(f.snapshot()?.current[0]?.cwd).toBe('/ship-hn/tui/src')
+ })
+
+ it('records several actual PR creation URLs once and never accepts prose, failures or lookups', () => {
+ const f = fixture()
+ const url = 'https://github.com/acme/app/pull/12'
+ f.start('create', { command: 'cd /work && gh pr create --title "Fix"' }); f.finish('create', url)
+ f.start('create', { command: 'gh pr create' }); f.finish('create', url)
+ f.start('view', { command: 'gh pr view' }); f.finish('view', 'https://github.com/acme/app/pull/13')
+ f.start('failed', { command: 'gh pr create' }); f.finish('failed', 'https://github.com/acme/app/pull/14', true)
+ f.start('prose', { command: 'gh pr create' }); f.finish('prose', 'Created https://github.com/acme/app/pull/15')
+ f.start('second', { command: 'gh pr create' }); f.finish('second', 'https://github.com/acme/app/pull/16')
+ expect(f.snapshot()?.pullRequests).toEqual([
+ { url: 'https://github.com/acme/app/pull/16', cwd: '/home/silent-beacon', at },
+ { url, cwd: '/work', at },
+ ])
+ })
+
+ it('keeps checkpoints bounded and rejects corrupt or executable-looking data', () => {
+ const f = fixture()
+ for (let i = 0; i < 140; i++) { f.start(`${i}`, { command: `cd /work/${i} && test` }); f.finish(`${i}`) }
+ expect(f.snapshot()?.locations).toHaveLength(128)
+ expect(f.snapshot()?.truncated).toBe(true)
+ expect(validSessionWork(f.state)).toBe(true)
+ expect(validSessionWork({ ...f.state, current: [{ cwd: '/bad\n', at }] })).toBe(false)
+ expect(validSessionWork({ ...f.state, pullRequests: [{ url: 'javascript:bad', cwd: null, at }] })).toBe(false)
+ })
+})
diff --git a/cli/src/lib/sessionWork.ts b/cli/src/lib/sessionWork.ts
new file mode 100644
index 000000000..9f62d7f2b
--- /dev/null
+++ b/cli/src/lib/sessionWork.ts
@@ -0,0 +1,295 @@
+/** Minimal, replayable work-location evidence. No Git, I/O, shell execution or raw output storage. */
+import { createHash } from 'node:crypto'
+import { dirname, isAbsolute, resolve } from 'node:path'
+import { literalToolCall } from './literalToolCall.js'
+
+export type WorkLocation = { cwd: string; at: string }
+export type WorkPullRequest = { url: string; cwd: string | null; at: string }
+type Operation = { paths: string[]; at: string; order: number; createsPr: boolean }
+export type SessionWorkLedger = {
+ context: string | null; sequence: number; latest: number;
+ current: WorkLocation[]; locations: WorkLocation[]; pullRequests: WorkPullRequest[];
+ pending: Record<string, Operation>; running: Record<string, Operation>; completed: string[];
+ uncertain: boolean; truncated: boolean;
+}
+export type SessionWork = Pick<SessionWorkLedger, 'current' | 'locations' | 'pullRequests' | 'uncertain' | 'truncated'>
+const LIMIT = 128
+const RECEIPTS = 2048
+const object = (v: unknown): Record<string, unknown> | null =>
+ v !== null && typeof v === 'object' && !Array.isArray(v) ? v as Record<string, unknown> : null
+const hash = (s: string) => createHash('sha256').update(s).digest('hex')
+const stamp = (v: unknown): v is string => typeof v === 'string' && Number.isFinite(Date.parse(v))
+export const validWorkPath = (v: unknown): v is string =>
+ typeof v === 'string' && isAbsolute(v) && v.length <= 4096 && !/[\x00-\x1f\x7f]/.test(v)
+export const validPullRequestUrl = (v: unknown): v is string => typeof v === 'string'
+ && /^https:\/\/github\.com\/[\w-]+\/[\w.-]+\/pull\/[1-9]\d*$/.test(v)
+ && new URL(v).href === v && Number.isSafeInteger(Number(v.split('/').at(-1)))
+export const emptySessionWork = (): SessionWorkLedger => ({ context: null, sequence: 0, latest: 0,
+ current: [], locations: [], pullRequests: [], pending: {}, running: {}, completed: [], uncertain: false, truncated: false })
+
+export function validSessionWork(value: unknown): value is SessionWorkLedger {
+ const r = object(value)
+ const locations = (v: unknown) => Array.isArray(v) && v.length <= LIMIT
+ && v.every(x => validWorkPath(x?.cwd) && stamp(x?.at))
+ const integer = (v: unknown) => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0
+ return !!r && (r.context === null || validWorkPath(r.context)) && integer(r.sequence) && integer(r.latest)
+ && Number(r.latest) <= Number(r.sequence) && locations(r.current) && locations(r.locations)
+ && Array.isArray(r.pullRequests) && r.pullRequests.length <= LIMIT && r.pullRequests.every(p =>
+ validPullRequestUrl(p?.url) && (p.cwd === null || validWorkPath(p.cwd)) && stamp(p?.at))
+ && [r.pending, r.running].every(operations => !!object(operations) && Object.keys(operations as object).length <= LIMIT
+ && Object.entries(operations as Record<string, Operation>).every(([id, op]) => /^[a-f0-9]{64}$/.test(id)
+ && Array.isArray(op?.paths) && op.paths.length <= LIMIT && op.paths.every(validWorkPath)
+ && integer(op.order) && op.order <= Number(r.sequence) && stamp(op.at) && typeof op.createsPr === 'boolean'))
+ && Array.isArray(r.completed) && r.completed.length <= RECEIPTS && r.completed.every(id => /^[a-f0-9]{64}$/.test(id))
+ && typeof r.uncertain === 'boolean' && typeof r.truncated === 'boolean'
+}
+
+export function sessionWorkSnapshot(state: SessionWorkLedger): SessionWork | null {
+ if (!state.sequence && !state.pullRequests.length && !state.locations.length) return null
+ // Pending calls are intent, not successful work. Multiple simultaneous calls prevent a claim
+ // that the last completed checkout is the unique place the agent is working now.
+ const pending = [...Object.values(state.pending), ...Object.values(state.running)]
+ return { current: state.current.map(v => ({ ...v })), locations: state.locations.map(v => ({ ...v })),
+ pullRequests: state.pullRequests.map(v => ({ ...v })),
+ uncertain: state.uncertain || pending.length > 0, truncated: state.truncated }
+}
+
+type Word = { text: string; literal: boolean }
+type Command = { words: Word[]; after: string }
+/** Tokenize only straight-line shell syntax. Quoted words stay words; never evaluate expansion. */
+function commands(source: string): Command[] | null {
+ if (source.length > 128 * 1024) return null
+ const result: Command[] = []
+ let words: Word[] = [], text = '', literal = true, quote = '', started = false
+ const word = () => { if (started) words.push({ text, literal }); text = ''; literal = true; started = false }
+ const command = (after: string) => { word(); if (words.length) result.push({ words, after }); words = [] }
+ for (let i = 0; i < source.length; i++) {
+ const ch = source[i]
+ if (ch === '\\' && quote !== "'") {
+ const next = source[++i]
+ if (next === undefined) return null
+ if (quote === '"' && !['$', '`', '"', '\\', '\n'].includes(next)) text += '\\'
+ if (next !== '\n') { text += next; started = true }
+ continue
+ }
+ if (quote) {
+ if (ch === quote) quote = ''
+ else { text += ch; if (quote !== "'" && (ch === '$' || ch === '`')) literal = false }
+ continue
+ }
+ if (ch === "'" || ch === '"') { quote = ch; started = true; continue }
+ if (ch === '#' && !started) { while (i < source.length && source[i] !== '\n') i++; command(';'); continue }
+ if (ch === '>' && source[i + 1] === '&' || ch === '&' && source[i + 1] === '>') {
+ text += source.slice(i, i + 2); i++; started = true; continue
+ }
+ // Subshells, substitutions, background work and alternatives need a real execution receipt.
+ if ('()`{}'.includes(ch) || ch === '<') return null
+ if (ch === '$' || ch === '~' && !started || ch === '*' || ch === '?') literal = false
+ if (ch === '&' || ch === '|') {
+ const doubled = source[i + 1] === ch
+ if (doubled) i++
+ if (ch === '&' && !doubled || ch === '|' && doubled) return null
+ command(doubled ? '&&' : '|'); continue
+ }
+ if (ch === ';' || ch === '\n') { command(';'); continue }
+ if (/\s/.test(ch)) { word(); continue }
+ text += ch; started = true
+ }
+ if (quote) return null
+ command('')
+ return result
+}
+
+function pathFrom(word: Word | undefined, cwd: string | null): string | null {
+ if (!word?.literal || !word.text || word.text.startsWith('-') || /[\x00-\x1f\x7f]/.test(word.text)) return null
+ const path = isAbsolute(word.text) ? resolve(word.text) : cwd ? resolve(cwd, word.text) : null
+ return validWorkPath(path) ? path : null
+}
+
+export function shellWorkLocations(source: string, initial: string | null): { paths: string[]; createsPr: boolean } | null {
+ const parsed = commands(source)
+ if (!parsed?.length) return null
+ let cwd = initial
+ const paths = new Set<string>()
+ let createsPr = false
+ for (const [index, command] of parsed.entries()) {
+ const { words, after } = command
+ const name = words[0]?.text
+ if (!words[0]?.literal || /^(?:if|then|else|fi|for|while|until|case|function|eval|source|exec|command|builtin|pushd|popd|time|!|\.)$/.test(name)) return null
+ if (['sh', 'bash', 'zsh', 'fish', 'env', 'sudo'].includes(name) || name.includes('=')) return null
+ if (words.some(w => /^(?:GIT_DIR|GIT_WORK_TREE|GIT_COMMON_DIR)=|^--(?:git-dir|work-tree)(?:=|$)/.test(w.text))) return null
+ if (name === 'cd') {
+ const operand = words[1]?.text === '--' ? words[2] : words[1]
+ if (words.length !== (words[1]?.text === '--' ? 3 : 2) || index < parsed.length - 1 && after !== '&&') return null
+ cwd = pathFrom(operand, cwd)
+ if (!cwd) return null
+ if (index === parsed.length - 1) paths.add(cwd)
+ continue
+ }
+ // Environment setup does not establish a separate work location.
+ if (['export', 'unset', 'set'].includes(name)) continue
+ let location = cwd
+ if (name === 'git' && words[1]?.text === '-C') {
+ location = pathFrom(words[2], cwd)
+ if (!location || words.slice(3).some(w => w.text === '-C' || w.text === '--git-dir' || w.text === '--work-tree')) return null
+ }
+ // A pipeline's consumers inherit the shell cwd but usually only read stdin. Keep its source.
+ if (location && (index === 0 || parsed[index - 1].after !== '|')) paths.add(location)
+ if (name === 'gh' && words[1]?.text === 'pr' && words[2]?.text === 'create'
+ && index === parsed.length - 1 && words.slice(3).every(w => w.literal)) createsPr = true
+ }
+ return { paths: [...paths].slice(0, LIMIT), createsPr }
+}
+
+function parse(value: unknown): unknown {
+ if (typeof value !== 'string') return value
+ try { return JSON.parse(value) } catch { return value }
+}
+
+/** A single unconditional literal code-mode call. Anything else stays unknown, never evaluated. */
+function unwrap(name: string, input: unknown): [string, unknown] {
+ if (name !== 'exec' || typeof input !== 'string') return [name, parse(input)]
+ const call = literalToolCall(input)
+ return call ? [call.name, call.input] : [name, input]
+}
+
+function operation(name: string, raw: unknown, cwd: string | null): { paths: string[]; createsPr: boolean } | null | undefined {
+ const [tool, input] = unwrap(name.replace(/^functions\./, ''), parse(raw))
+ const args = object(input)
+ if (['Bash', 'exec_command', 'shell', 'local_shell', 'unified_exec'].includes(tool)) {
+ const explicit = args?.workdir ?? args?.cwd
+ if (explicit !== undefined && !validWorkPath(explicit)) return null
+ const base = validWorkPath(explicit) ? explicit : cwd
+ const rawCommand = args?.cmd ?? args?.command
+ const source = Array.isArray(rawCommand) && rawCommand.length === 3 && ['-c', '-lc'].includes(rawCommand[1])
+ ? rawCommand[2] : rawCommand
+ return typeof source === 'string' ? shellWorkLocations(source, base) : null
+ }
+ if (['Read', 'Edit', 'Write', 'MultiEdit'].includes(tool)) {
+ const path = pathFrom({ text: typeof args?.file_path === 'string' ? args.file_path : '', literal: true }, cwd)
+ return path ? { paths: [dirname(path)], createsPr: false } : null
+ }
+ if (tool === 'apply_patch') {
+ const patch = typeof input === 'string' ? input : args?.patch ?? args?.input
+ if (typeof patch !== 'string' || !patch.startsWith('*** Begin Patch\n') || !patch.trimEnd().endsWith('*** End Patch')) return null
+ const files = [...patch.matchAll(/^\*\*\* (?:Add File|Update File|Delete File|Move to): (.+)$/gm)]
+ const paths = files.map(match => pathFrom({ text: match[1], literal: true }, cwd)).map(path => path && dirname(path))
+ return paths.length && paths.every((p): p is string => !!p)
+ ? { paths: [...new Set(paths)].slice(0, LIMIT), createsPr: false } : null
+ }
+ // Code mode may execute anything; it invalidates confidence when unsupported. Unrelated tools
+ // such as web search and user questions do not change where a session last worked.
+ return ['exec', 'apply_patch'].includes(tool) ? null : undefined
+}
+
+function begin(state: SessionWorkLedger, id: unknown, name: unknown, input: unknown, cwd: string | null, at: string): void {
+ if (typeof id !== 'string' || typeof name !== 'string') return
+ const key = hash(id)
+ if (state.pending[key] || state.completed.includes(key)) return
+ const [tool, raw] = unwrap(name.replace(/^functions\./, ''), parse(input))
+ const args = object(raw)
+ const continuation = tool === 'write_stdin' && (typeof args?.session_id === 'number' || typeof args?.session_id === 'string')
+ ? hash(`process:${args.session_id}`) : tool === 'wait' && typeof args?.cell_id === 'string' ? hash(`cell:${args.cell_id}`) : null
+ if (continuation && state.running[continuation]) {
+ if (Object.keys(state.pending).length >= LIMIT) { state.uncertain = true; state.truncated = true; return }
+ const running = state.running[continuation]
+ delete state.running[continuation]
+ // Input could change an interactive shell's directory. Only passive waits confirm an operation.
+ state.pending[key] = args?.terminate === true || typeof args?.chars === 'string' && args.chars.length > 0
+ ? { ...running, paths: [], createsPr: false } : running
+ return
+ }
+ const found = continuation ? null : operation(name, input, cwd)
+ if (found === undefined) return
+ const order = ++state.sequence
+ if (Object.keys(state.pending).length >= LIMIT) { state.uncertain = true; state.truncated = true; return }
+ state.pending[key] = { paths: found?.paths ?? [], createsPr: found?.createsPr ?? false, order, at }
+}
+
+function outputText(raw: unknown): string {
+ if (typeof raw === 'string') return raw
+ if (Array.isArray(raw)) return raw.map(v => outputText(object(v)?.text)).join('\n')
+ const obj = object(raw)
+ return typeof obj?.output === 'string' ? obj.output : ''
+}
+
+function finish(state: SessionWorkLedger, id: unknown, raw: unknown, failed: boolean, receipt?: unknown): void {
+ if (typeof id !== 'string') return
+ const key = hash(id), op = state.pending[key]
+ if (!op) return
+ delete state.pending[key]
+ state.completed.push(key)
+ if (state.completed.length > RECEIPTS) { state.completed.shift(); state.truncated = true }
+ let text = outputText(raw)
+ const wrapper = /^Script completed[\s\S]*?\nOutput:\n([\s\S]*)$/.exec(text)
+ if (wrapper) text = wrapper[1]
+ const result = object(parse(text)) ?? object(raw)
+ const native = object(receipt)
+ const running = result?.session_id != null && result.exit_code == null
+ ? hash(`process:${result.session_id}`)
+ : /Process running with session ID ([\w-]+)/.test(text)
+ ? hash(`process:${/Process running with session ID ([\w-]+)/.exec(text)![1]}`)
+ : /Script running with cell ID ([\w-]+)/.test(text)
+ ? hash(`cell:${/Script running with cell ID ([\w-]+)/.exec(text)![1]}`) : null
+ const unsuccessful = failed || result?.isError === true || native?.interrupted === true
+ || native?.backgroundTaskId != null || running != null
+ || typeof result?.exit_code === 'number' && result.exit_code !== 0
+ || /(?:Process exited with code|"exit_code"\s*:)\s*[1-9]\d*/.test(text)
+ || /Script running with cell ID|Process running with session ID|Script terminated/.test(text)
+ if (running && !failed && result?.isError !== true) {
+ if (Object.keys(state.running).length < LIMIT) state.running[running] = op
+ else state.truncated = true
+ }
+ if (op.order >= state.latest) {
+ state.latest = op.order
+ state.current = unsuccessful ? [] : op.paths.map(cwd => ({ cwd, at: op.at }))
+ state.uncertain = unsuccessful || !op.paths.length
+ }
+ if (unsuccessful) return
+ for (const cwd of op.paths) {
+ const old = state.locations.find(p => p.cwd === cwd)
+ if (!old || old.at < op.at) {
+ state.locations = [{ cwd, at: op.at }, ...state.locations.filter(p => p.cwd !== cwd)]
+ .sort((a, b) => b.at.localeCompare(a.at))
+ }
+ }
+ if (state.locations.length > LIMIT) { state.locations.length = LIMIT; state.truncated = true }
+ if (op.createsPr) {
+ if (typeof result?.output === 'string') text = result.output
+ const urls = [...new Set(text.split('\n').map(s => s.trim()).filter(validPullRequestUrl))]
+ if (urls.length === 1 && !state.pullRequests.some(p => p.url === urls[0])) {
+ state.pullRequests.unshift({ url: urls[0], cwd: op.paths.length === 1 ? op.paths[0] : null, at: op.at })
+ if (state.pullRequests.length > LIMIT) { state.pullRequests.length = LIMIT; state.truncated = true }
+ }
+ }
+}
+
+/** Caller enforces session/fork identity before ingestion. Timestamps are transcript evidence. */
+export function ingestSessionWork(state: SessionWorkLedger, row: Record<string, unknown>, engine: string, launchCwd?: string | null): void {
+ if (!stamp(row.timestamp)) return
+ const at = new Date(row.timestamp).toISOString()
+ if (engine === 'codex' && ['session_meta', 'turn_context'].includes(String(row.type))) {
+ const cwd = object(row.payload)?.cwd
+ if (validWorkPath(cwd)) state.context = cwd
+ return
+ }
+ const cwd = validWorkPath(row.cwd) ? row.cwd : state.context ?? (validWorkPath(launchCwd) ? launchCwd : null)
+ if (engine === 'claude') {
+ const content = object(row.message)?.content
+ if (!Array.isArray(content)) return
+ for (const v of content) {
+ const item = object(v)
+ if (!item) continue
+ if (row.type === 'assistant' && item.type === 'tool_use') begin(state, item.id, item.name, item.input, cwd, at)
+ if (row.type === 'user' && item.type === 'tool_result') finish(state, item.tool_use_id, item.content, item.is_error === true,
+ content.filter(v => object(v)?.type === 'tool_result').length === 1 ? row.toolUseResult : undefined)
+ }
+ } else if (engine === 'codex' && row.type === 'response_item') {
+ const item = object(row.payload)
+ if (!item) return
+ if (item.type === 'function_call' || item.type === 'custom_tool_call')
+ begin(state, item.call_id ?? item.id, item.name, item.arguments ?? item.input, cwd, at)
+ if (item.type === 'function_call_output' || item.type === 'custom_tool_call_output')
+ finish(state, item.call_id ?? item.id, item.output, item.is_error === true || item.status === 'failed')
+ }
+}
diff --git a/cli/src/lib/sessionWorkCache.spec.ts b/cli/src/lib/sessionWorkCache.spec.ts
new file mode 100644
index 000000000..15bad19f8
--- /dev/null
+++ b/cli/src/lib/sessionWorkCache.spec.ts
@@ -0,0 +1,85 @@
+import { appendFile, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { AgentTokenUsageCache } from './agentTokenUsage.js'
+import type { RegisteredSession } from './registry.js'
+
+const at = '2026-09-27T13:00:00.000Z'
+const lines = (values: unknown[]) => values.map(v => JSON.stringify(v)).join('\n') + '\n'
+const receipt = (id: string, cwd = '/ship-hn/tui', extra = {}) => [
+ { timestamp: at, sessionId: 'session', cwd: '/silent-beacon', type: 'assistant', ...extra,
+ message: { content: [{ type: 'tool_use', id, name: 'Bash', input: { command: `cd ${cwd} && gh pr create --title Fix` } }] } },
+ { timestamp: at, sessionId: 'session', cwd: '/silent-beacon', type: 'user', ...extra,
+ message: { content: [{ type: 'tool_result', tool_use_id: id, content: `https://github.com/acme/app/pull/${id}` }] } },
+]
+describe('work evidence in the incremental transcript cache', () => {
+ let dir: string, now: number, bytes: number, cache: AgentTokenUsageCache
+ let target: Pick<RegisteredSession, 'agentId' | 'sessionId' | 'engine' | 'transcriptPath' | 'registeredAt' | 'cwd' | 'forkedFrom'>
+ const open = () => new AgentTokenUsageCache(join(dir, 'cache'), { now: () => now, onRead: n => { bytes += n } })
+ const read = async () => { now += 30_000; cache.changed(target); await cache.settled(); return cache.get(target) }
+ beforeEach(async () => {
+ dir = await mkdtemp(join(tmpdir(), 'session-work-cache-')); now = Date.parse(at); bytes = 0
+ target = { agentId: 'hn', sessionId: 'session', engine: 'claude', transcriptPath: join(dir, 'session.jsonl'), registeredAt: 1, cwd: '/silent-beacon' }
+ cache = open()
+ })
+ afterEach(async () => { cache.dispose(); await cache.settled(); await rm(dir, { recursive: true, force: true }) })
+
+ it('publishes work without token usage, persists across restart, and reads only appended bytes', async () => {
+ const changed = vi.fn(); cache.onChanged = changed
+ await writeFile(target.transcriptPath!, lines([{ type: 'user', text: 'x'.repeat(200_000) }, ...receipt('12')]))
+ expect(await read()).toMatchObject({ totalTokens: null, work: { current: [{ cwd: '/ship-hn/tui' }] } })
+ expect(changed).toHaveBeenCalledOnce()
+ const oldBytes = bytes
+ await appendFile(target.transcriptPath!, lines(receipt('13', '/another')))
+ expect((await read())?.work?.pullRequests).toHaveLength(2)
+ expect(bytes - oldBytes).toBeLessThan(2048)
+ cache.dispose(); cache = open()
+ const restartBytes = bytes
+ expect((await read())?.work?.current[0]?.cwd).toBe('/another')
+ expect(bytes).toBe(restartBytes)
+ const file = join(dir, 'cache', (await readdir(join(dir, 'cache')))[0])
+ const stored = await readFile(file, 'utf8')
+ expect(stored).not.toContain('gh pr create')
+ expect(stored).not.toContain('x'.repeat(100))
+ })
+
+ it('retains known PR links after compaction while invalidating the old current checkout', async () => {
+ await writeFile(target.transcriptPath!, lines(receipt('12'))); await read()
+ await writeFile(target.transcriptPath!, lines([{ type: 'user', text: 'compacted' }]))
+ expect((await read())?.work).toMatchObject({ current: [], uncertain: true,
+ pullRequests: [{ url: 'https://github.com/acme/app/pull/12' }] })
+ await appendFile(target.transcriptPath!, lines(receipt('13', '/new')))
+ expect((await read())?.work).toMatchObject({ current: [{ cwd: '/new' }], uncertain: false })
+ expect(cache.get(target)?.work?.pullRequests).toHaveLength(2)
+ })
+
+ it('ignores another conversation, child sidechains, and inherited fork history', async () => {
+ await writeFile(target.transcriptPath!, lines([
+ ...receipt('12', '/foreign', { sessionId: 'other' }),
+ ...receipt('13', '/child', { isSidechain: true }),
+ ...receipt('14', '/mine'),
+ ]))
+ expect((await read())?.work?.locations.map(p => p.cwd)).toEqual(['/mine'])
+ target = { ...target, forkedFrom: { agentId: 'parent', name: 'Parent' }, registeredAt: Date.parse(at) + 1 }
+ expect((await read())?.work).toBeUndefined()
+ })
+
+ it('does not import a foreign Codex transcript when its metadata disagrees with the registry', async () => {
+ target.engine = 'codex'
+ await writeFile(target.transcriptPath!, lines([
+ { timestamp: at, type: 'session_meta', payload: { id: 'foreign', cwd: '/foreign' } },
+ { timestamp: at, type: 'response_item', payload: { type: 'function_call', call_id: 'one', name: 'exec_command', arguments: '{"cmd":"pwd"}' } },
+ { timestamp: at, type: 'response_item', payload: { type: 'function_call_output', call_id: 'one', output: 'ok' } },
+ ]))
+ expect(await read()).toBeNull()
+ })
+
+ it('rebuilds an older cache to recover work associations', async () => {
+ await writeFile(target.transcriptPath!, lines(receipt('12'))); await read()
+ const file = join(dir, 'cache', (await readdir(join(dir, 'cache')))[0])
+ const stored = JSON.parse(await readFile(file, 'utf8')); stored.version = 2; delete stored.work
+ await writeFile(file, JSON.stringify(stored)); cache.dispose(); cache = open()
+ expect((await read())?.work?.current[0]?.cwd).toBe('/ship-hn/tui')
+ })
+})
diff --git a/desktop/design/terminal-workspace.md b/desktop/design/terminal-workspace.md
index 4554b698f..05c9684d0 100644
--- a/desktop/design/terminal-workspace.md
+++ b/desktop/design/terminal-workspace.md
@@ -104,9 +104,11 @@ shared app bar. A dependent viewer uses its owner's context. Keep internal
worktree paths and machinery out of everyday labels.
Machine opens the shared picker scoped to that machine. Project opens its harnesses across
-known checkouts and machines. Branch narrows that project to the exact named
-branch. Hide detached commit hashes from the bar. These are navigation actions;
-they do not check out a branch.
+known checkouts and machines. With session Git context, Branch opens Work details:
+current observed checkout, launch workspace, observed branches and PR history.
+Older daemons keep exact-branch project search. Hide detached commit hashes from
+the bar. Ambiguous or unavailable work is plain context text, without a branch
+symbol. These are navigation actions; they do not check out a branch.
The PR label opens that PR. Each field gets its own accessible link, tooltip, and
the shared hover treatment, including in joined Agnoster segments.
diff --git a/desktop/design/workspace-status-bar.md b/desktop/design/workspace-status-bar.md
index a668e3773..d316093f9 100644
--- a/desktop/design/workspace-status-bar.md
+++ b/desktop/design/workspace-status-bar.md
@@ -121,9 +121,13 @@ 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 that project filtered by its exact branch. Escape returns
-from branch to project, then to project search. Names never establish identity.
-Branch navigation does not check out or create a 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.
+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.
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
new file mode 100644
index 000000000..b8f32c735
--- /dev/null
+++ b/desktop/lib/core/agent_git_context.dart
@@ -0,0 +1,253 @@
+import 'package:flutter/foundation.dart';
+
+import 'models.dart';
+
+bool sameGitConversation(Agent a, Agent? b) =>
+ b != null &&
+ a.id == b.id &&
+ a.sessionId == b.sessionId &&
+ a.engine == b.engine &&
+ a.codexHome == b.codexHome &&
+ a.project?.cwd == b.project?.cwd;
+
+/// List and push messages can cross in flight. Scope ordering to this machine's same
+/// conversation and daemon incarnation; a restarted daemon establishes a new epoch.
+Agent retainNewerGitContext(Agent incoming, Agent? previous) {
+ final old = previous?.gitContext, next = incoming.gitContext;
+ if (sameGitConversation(incoming, previous) &&
+ old?.epoch != null &&
+ old!.epoch == next?.epoch &&
+ old.revision > next!.revision) {
+ return incoming.copyWith(gitContext: old);
+ }
+ return incoming;
+}
+
+String localWorkTime(DateTime timestamp) {
+ final at = timestamp.toLocal();
+ String two(int n) => n.toString().padLeft(2, '0');
+ return '${at.year}-${two(at.month)}-${two(at.day)} ${two(at.hour)}:${two(at.minute)}';
+}
+
+typedef AgentWorkLocation = ({String cwd, DateTime at});
+typedef AgentWorkBranch = ({
+ String cwd,
+ String? remote,
+ String branch,
+ DateTime at,
+});
+typedef AgentWorkPr = ({
+ Uri url,
+ String? cwd,
+ DateTime at,
+ String? state,
+ DateTime? checkedAt,
+ String? title,
+ String? headBranch,
+ String? baseBranch,
+});
+
+/// Display evidence from the owning machine. It never changes launch/resume cwd.
+class AgentGitContext {
+ const AgentGitContext({
+ required this.state,
+ this.current,
+ this.observedAt,
+ this.locations = const [],
+ this.branches = const [],
+ this.pullRequests = const [],
+ this.truncated = false,
+ this.epoch,
+ this.revision = 0,
+ });
+ final String state;
+ final AgentProject? current;
+ final DateTime? observedAt;
+ final List<AgentWorkLocation> locations;
+ final List<AgentWorkBranch> branches;
+ final List<AgentWorkPr> pullRequests;
+ final bool truncated;
+ final String? epoch;
+ final int revision;
+
+ String? get branchLabel => switch (state) {
+ 'multiple' => 'Multiple workspaces',
+ 'uncertain' => 'Work location unknown',
+ 'unavailable' => 'Workspace unavailable',
+ _ =>
+ current?.shownBranch ?? (current?.detached == true ? 'Detached' : null),
+ };
+
+ String get explanation => switch (state) {
+ 'observed' => 'Most recently observed work',
+ 'multiple' => 'The operation used more than one workspace.',
+ 'uncertain' => 'The current work location could not be confirmed.',
+ 'unavailable' => 'The observed workspace is no longer readable.',
+ _ => 'Session workspace; no other work location has been observed.',
+ };
+
+ AgentProject? displayProject(AgentProject? launch) {
+ if (current != null) return current;
+ if (launch == null) return null;
+ // Keep useful repository context without presenting the launch branch as current work.
+ return AgentProject(
+ name: launch.name,
+ cwd: launch.cwd,
+ root: launch.root,
+ remote: launch.remote,
+ worktree: launch.worktree,
+ );
+ }
+
+ Map<String, Object?>? get requestIdentity {
+ final project = current;
+ if (project == null || project.shownBranch == null) return null;
+ return {
+ 'cwd': project.cwd,
+ 'branch': project.branch,
+ 'remote': project.remote,
+ };
+ }
+
+ @override
+ bool operator ==(Object other) =>
+ other is AgentGitContext &&
+ state == other.state &&
+ current == other.current &&
+ observedAt == other.observedAt &&
+ truncated == other.truncated &&
+ epoch == other.epoch &&
+ revision == other.revision &&
+ listEquals(locations, other.locations) &&
+ listEquals(branches, other.branches) &&
+ listEquals(pullRequests, other.pullRequests);
+ @override
+ int get hashCode => Object.hash(
+ state,
+ current,
+ observedAt,
+ truncated,
+ epoch,
+ revision,
+ Object.hashAll(locations),
+ Object.hashAll(branches),
+ Object.hashAll(pullRequests),
+ );
+
+ static AgentGitContext? fromJson(Object? raw) {
+ if (raw is! Map ||
+ !const [
+ 'workspace',
+ 'observed',
+ 'multiple',
+ 'uncertain',
+ 'unavailable',
+ ].contains(raw['state'])) {
+ return null;
+ }
+ String? label(Object? v, [int max = 4096]) =>
+ v is String &&
+ v.isNotEmpty &&
+ v.length <= max &&
+ !RegExp(r'[\x00-\x1f\x7f]').hasMatch(v)
+ ? v
+ : null;
+ DateTime? date(Object? v) => v is String ? DateTime.tryParse(v) : null;
+ List<dynamic> rows(Object? value) =>
+ value is List ? value.take(128).toList() : const [];
+ final locations = <AgentWorkLocation>[];
+ for (final row in rows(raw['locations'])) {
+ if (row is! Map) continue;
+ final cwd = label(row['cwd']), at = date(row['at']);
+ if (cwd != null && at != null) locations.add((cwd: cwd, at: at));
+ }
+ final history = raw['history'] is Map ? raw['history'] as Map : const {};
+ final branches = <AgentWorkBranch>[];
+ for (final row in rows(history['branches'])) {
+ if (row is! Map) continue;
+ final cwd = label(row['cwd']),
+ branch = label(row['branch'], 256),
+ at = date(row['at']);
+ if (cwd != null && branch != null && at != null) {
+ branches.add((
+ cwd: cwd,
+ branch: branch,
+ remote: label(row['remote']),
+ at: at,
+ ));
+ }
+ }
+ final prs = <AgentWorkPr>[];
+ final seen = <String>{};
+ for (final row in [
+ ...rows(history['pullRequests']),
+ ...rows(raw['pullRequests']),
+ ]) {
+ if (row is! Map) continue;
+ final url = validatedPrUrl(row['url']), at = date(row['at']);
+ if (url == null || at == null || !seen.add(url.toString())) continue;
+ for (final alias in rows(row['aliases'])) {
+ final valid = validatedPrUrl(alias);
+ if (valid != null) seen.add(valid.toString());
+ }
+ final result = row['result'];
+ final state =
+ result is Map &&
+ result['status'] == 'found' &&
+ result['url'] == url.toString() &&
+ const [
+ 'Draft',
+ 'Open',
+ 'Merged',
+ 'Closed',
+ ].contains(result['state'])
+ ? result['state'] as String
+ : null;
+ prs.add((
+ url: url,
+ cwd: label(row['cwd']),
+ at: at,
+ state: state,
+ checkedAt: date(row['checkedAt']),
+ title: result is Map ? label(result['title'], 512) : null,
+ headBranch: result is Map ? label(result['headBranch'], 256) : null,
+ baseBranch: result is Map ? label(result['baseBranch'], 256) : null,
+ ));
+ if (prs.length == 128) break;
+ }
+ final version = raw['version'];
+ return AgentGitContext(
+ state: raw['state'] as String,
+ current: const ['workspace', 'observed'].contains(raw['state'])
+ ? AgentProject.fromJson(raw['current'])
+ : null,
+ observedAt: date(raw['observedAt']),
+ locations: List.unmodifiable(locations),
+ branches: List.unmodifiable(branches),
+ pullRequests: List.unmodifiable(prs),
+ truncated: raw['truncated'] == true || history['truncated'] == true,
+ epoch: version is Map ? label(version['epoch'], 128) : null,
+ revision:
+ version is Map &&
+ version['revision'] is int &&
+ version['revision'] > 0
+ ? version['revision'] as int
+ : 0,
+ );
+ }
+
+ static Uri? validatedPrUrl(Object? value) {
+ if (value is! String ||
+ !RegExp(r'^https://github\.com/[\w-]+/[\w.-]+/pull/[1-9]\d*$')
+ .hasMatch(value)) {
+ return null;
+ }
+ final uri = Uri.tryParse(value);
+ if (uri == null ||
+ uri.toString() != value ||
+ uri.pathSegments.any((part) => part == '.' || part == '..')) {
+ return null;
+ }
+ return uri;
+ }
+}
diff --git a/desktop/lib/core/models.dart b/desktop/lib/core/models.dart
index 06d3e4b25..25eecf1f4 100644
--- a/desktop/lib/core/models.dart
+++ b/desktop/lib/core/models.dart
@@ -4,6 +4,7 @@ library;
import 'package:flutter/foundation.dart' show immutable;
import 'runtime_model_name.dart';
+import 'agent_git_context.dart';
enum MachineAuthMode { managed, remote, self, provider }
@@ -326,6 +327,9 @@ class Agent {
final GridNote? gridNote;
final String? parentAgentId;
final AgentProject? project;
+ final AgentGitContext? gitContext;
+ AgentProject? get displayProject =>
+ gitContext?.displayProject(project) ?? project;
/// The CLI's transcript/hook activity time, not its registry refresh time.
final DateTime? lastActivityAt;
@@ -432,6 +436,7 @@ class Agent {
this.gridNote,
this.parentAgentId,
this.project,
+ this.gitContext,
this.lastActivityAt,
this.lastOpenedAt,
this.tokensUsed,
@@ -564,6 +569,7 @@ class Agent {
gridNote: GridNote.fromWire(grid?['note']),
parentAgentId: _safeLabel(j['parentAgentId'] ?? j['parentId']),
project: AgentProject.fromJson(j['project']),
+ gitContext: AgentGitContext.fromJson(j['gitContext']),
lastActivityAt: j['updatedAt'] is String
? DateTime.tryParse(j['updatedAt'] as String)
: null,
@@ -606,6 +612,7 @@ class Agent {
Agent copyWith({
String? name,
+ AgentGitContext? gitContext,
String? status,
bool? terminalAvailable,
DateTime? lastOpenedAt,
@@ -625,6 +632,7 @@ class Agent {
gridNote: gridNote,
parentAgentId: parentAgentId,
project: project,
+ gitContext: gitContext ?? this.gitContext,
lastActivityAt: lastActivityAt,
lastOpenedAt: lastOpenedAt ?? this.lastOpenedAt,
tokensUsed: tokensUsed,
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index f4e38e3fb..193f3138e 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -60,6 +60,7 @@ import '../widgets/engine_identity.dart';
import '../widgets/status_line.dart';
import '../widgets/workspace_status_line.dart';
import '../widgets/workspace_bar_control.dart';
+import '../widgets/session_work_dialog.dart';
import '../widgets/web_download_button.dart';
import '../widgets/grid_model_picker.dart';
import '../store/store_mark.dart';
@@ -851,7 +852,9 @@ class _SwarmScreenState extends State<SwarmScreen> {
),
if (focused.branch != null && focused.project != null)
StatusLineField.branch: (
- label: 'Find harnesses on ${focused.branch} in ${focused.projectName}',
+ label: focused.agent?.gitContext == null
+ ? 'Find harnesses on ${focused.branch} in ${focused.projectName}'
+ : 'Inspect session work · ${focused.branch}\n${focused.detail}',
onPressed: _shortcutsEnabled
? () =>
_openContextResource(StatusLineField.branch, focused.pane.id)
@@ -864,6 +867,10 @@ class _SwarmScreenState extends State<SwarmScreen> {
final focused = WorkspacePaneContext.focused(app);
if (focused == null || focused.pane.id != expectedPaneId) return;
if (field == StatusLineField.branch && focused.branch == null) return;
+ if (field == StatusLineField.branch && focused.agent?.gitContext != null) {
+ unawaited(_showSessionWork(focused));
+ return;
+ }
if (app.stateOf(focused.pane.machineId) == null) return;
final group = field == StatusLineField.machine
? 'machine:${focused.pane.machineId}'
@@ -884,6 +891,22 @@ class _SwarmScreenState extends State<SwarmScreen> {
_focusSearch();
}
+ Future<void> _showSessionWork(WorkspacePaneContext focused) =>
+ _dialog(() async {
+ final agent = focused.agent;
+ if (agent == null) return;
+ final machineId = focused.pane.machineId;
+ await showDialog<void>(
+ context: context,
+ builder: (_) => SessionWorkDialog(
+ agent: agent,
+ online: app.stateOf(machineId)?.isOffline == false,
+ read: (offset) =>
+ app.readAgentGitHistory(machineId, agent.id, offset: offset),
+ ),
+ );
+ });
+
Future<void> _openFocusedPullRequest(String? expectedUrl) async {
final pr = _pullRequest.value;
if (pr == null || expectedUrl != pr.url.toString()) return;
@@ -3699,6 +3722,10 @@ class _SwarmScreenState extends State<SwarmScreen> {
'agent.add': _addAgent,
if (kDebugSurfaceEnabled) 'app.onboarding_review': _newTab,
'agent.rename': () => _editAgent(),
+ 'agent.work': () async {
+ final focused = WorkspacePaneContext.focused(app);
+ if (focused != null) await _showSessionWork(focused);
+ },
'agent.stop': () => _editAgent(stop: true),
'agent.fork': _forkAgent,
'agent.share': _shareAgent,
@@ -3735,6 +3762,9 @@ class _SwarmScreenState extends State<SwarmScreen> {
return false;
}
if (id == 'keyboard.open_config') return _keymap.store != null;
+ if (id == 'agent.work') {
+ return WorkspacePaneContext.focused(app)?.agent != null;
+ }
if (id == 'keyboard.pause_guide') return _learning.active;
if (id == 'agent.share' || id == 'pane.toggle_viewer') {
final focused = WorkspacePaneContext.focused(app);
diff --git a/desktop/lib/shortcuts/keymap_commands.dart b/desktop/lib/shortcuts/keymap_commands.dart
index 7c2ab7a54..f07d92644 100644
--- a/desktop/lib/shortcuts/keymap_commands.dart
+++ b/desktop/lib/shortcuts/keymap_commands.dart
@@ -340,6 +340,19 @@ final harnessCommands = <HarnessCommand>[
nativeAction: 'newAgent',
),
const HarnessCommand('agent.rename', 'Rename Harness', ShortcutGroup.actions),
+ const HarnessCommand(
+ 'agent.work',
+ 'Inspect session work',
+ ShortcutGroup.actions,
+ keywords: [
+ 'branch',
+ 'branches',
+ 'pull requests',
+ 'git',
+ 'worktree',
+ 'history',
+ ],
+ ),
const HarnessCommand('agent.stop', 'Stop Harness', ShortcutGroup.actions),
const HarnessCommand('agent.fork', 'Fork Harness', ShortcutGroup.actions),
const HarnessCommand(
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index cf84a9ee9..e5701228c 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -24,6 +24,7 @@ import '../auth/cli_login.dart';
import '../bootstrap/environment_provisioner.dart';
import '../core/viewer_mode.dart';
import '../core/config.dart';
+import '../core/agent_git_context.dart';
import '../core/agent_names.dart';
import '../core/agent_preference.dart';
import '../core/dsh_catalog.dart';
@@ -371,7 +372,7 @@ class MachineState {
(!isLocalMachine && machine.reportedOnline == false);
AgentProject? projectOf(Agent agent) =>
- agent.project ??
+ agent.displayProject ??
localProjects[agent.id] ??
localEndpoint?.agentProjects[agent.id];
@@ -4705,6 +4706,7 @@ class AppNotifier extends ChangeNotifier {
prev.modelName != agent.modelName ||
prev.parentAgentId != agent.parentAgentId ||
prev.project != agent.project ||
+ prev.gitContext != agent.gitContext ||
prev.lastActivityAt != agent.lastActivityAt ||
prev.lastOpenedAt != agent.lastOpenedAt ||
prev.tokensUsed != agent.tokensUsed ||
@@ -6233,6 +6235,11 @@ class AppNotifier extends ChangeNotifier {
}
void _replaceAgents(MachineState machine, List<Agent> agents) {
+ final previousWork = {for (final agent in machine.agents) agent.id: agent};
+ agents = [
+ for (final agent in agents)
+ retainNewerGitContext(agent, previousWork[agent.id]),
+ ];
final previous = {for (final agent in machine.agents) agent.id: agent};
final nextIds = agents.map((agent) => agent.id).toSet();
machine._agentNames.removeWhere((id, _) => !nextIds.contains(id));
@@ -6290,6 +6297,7 @@ class AppNotifier extends ChangeNotifier {
void _upsertAgent(MachineState machine, Agent agent) {
final index = machine.agents.indexWhere((item) => item.id == agent.id);
final previous = index == -1 ? null : machine.agents[index];
+ agent = retainNewerGitContext(agent, previous);
if (index == -1) {
machine.agents = [...machine.agents, agent];
} else {
@@ -7210,12 +7218,63 @@ class AppNotifier extends ChangeNotifier {
String machineId,
String agentId,
) async {
+ final machine = stateOf(machineId), revision = _authRevision;
+ final agent = machine?.agents.where((a) => a.id == agentId).firstOrNull;
+ if (machine == null || agent == null) return {'status': 'unavailable'};
+ final identity = agent.gitContext?.requestIdentity;
+ if (agent.gitContext != null && identity == null) {
+ return {'status': 'unavailable'};
+ }
try {
- return await _conn(machineId).request(
+ final result = await _conn(machineId).request(
'git_pull_request',
- payload: {'agentId': agentId},
+ payload: {'agentId': agentId, 'context': ?identity},
timeout: const Duration(seconds: 30),
);
+ if (!_machineWorkCurrent(machine, revision) ||
+ !sameGitConversation(
+ agent,
+ machine.agents.where((a) => a.id == agentId).firstOrNull,
+ )) {
+ return {'status': 'unavailable'};
+ }
+ if (identity != null &&
+ !mapEquals(
+ identity,
+ result['context'] is Map
+ ? Map<String, Object?>.from(result['context'])
+ : null,
+ )) {
+ return {'status': 'unavailable'};
+ }
+ return result;
+ } catch (_) {
+ return {'status': 'unavailable'};
+ }
+ }
+
+ Future<Map<String, dynamic>> readAgentGitHistory(
+ String machineId,
+ String agentId, {
+ int offset = 0,
+ }) async {
+ final machine = stateOf(machineId), revision = _authRevision;
+ final agent = machine?.agents.where((a) => a.id == agentId).firstOrNull;
+ if (machine == null || agent == null) return {'status': 'unavailable'};
+ try {
+ final result = await _conn(machineId).request(
+ 'git_pull_request',
+ payload: {'agentId': agentId, 'history': true, 'offset': offset},
+ timeout: const Duration(seconds: 45),
+ );
+ if (!_machineWorkCurrent(machine, revision) ||
+ !sameGitConversation(
+ agent,
+ machine.agents.where((a) => a.id == agentId).firstOrNull,
+ )) {
+ return {'status': 'unavailable'};
+ }
+ return result;
} catch (_) {
return {'status': 'unavailable'};
}
@@ -8768,7 +8827,7 @@ class AppNotifier extends ChangeNotifier {
);
}
final terminal = isTerminalEngine(engine);
- final cwd = machine.projectOf(source)?.cwd;
+ final cwd = source.project?.cwd ?? machine.projectOf(source)?.cwd;
if (cwd == null && !terminal) {
return Future.value(
'${source.displayName} has no project folder to clone into.',
diff --git a/desktop/lib/state/workspace_status.dart b/desktop/lib/state/workspace_status.dart
index c39e460f3..49bbd7e02 100644
--- a/desktop/lib/state/workspace_status.dart
+++ b/desktop/lib/state/workspace_status.dart
@@ -1,4 +1,5 @@
import '../core/models.dart';
+import '../core/agent_git_context.dart';
import '../shared/theme/prompt_style.dart';
import '../shared/theme/status_line_style.dart';
import '../widgets/engine_identity.dart';
@@ -142,14 +143,34 @@ class WorkspacePaneContext {
String? get engine => agent?.engine ?? pane.session?.engineId;
String get suffix => branch == null ? '' : ' ($branch)';
String get text => '$location$suffix';
- StatusLineParts format(PromptPrefs prefs) => statusLineParts(
- provider: '',
- machine: prefs.machine ? machineName : '',
- project: prefs.project ? projectName : '',
- branch: prefs.branch ? branch : null,
- style: prefs.statusStyle,
- separateMachine: true,
- );
+ StatusLineParts format(PromptPrefs prefs) {
+ final note =
+ prefs.branch &&
+ agent?.gitContext != null &&
+ project?.shownBranch == null
+ ? branch
+ : null;
+ final parts = statusLineParts(
+ provider: '',
+ machine: prefs.machine ? machineName : '',
+ project: prefs.project ? projectName : '',
+ branch: prefs.branch && note == null ? branch : null,
+ style: prefs.statusStyle,
+ separateMachine: true,
+ );
+ if (note == null) return parts;
+ return StatusLineParts(parts.style, [
+ ...parts.segments,
+ if (!parts.style.segmented && parts.segments.isNotEmpty)
+ const StatusLineSegment(' '),
+ StatusLineSegment(
+ note,
+ foreground: StatusLineTone.muted,
+ background: parts.style.segmented ? StatusLineTone.black : null,
+ field: StatusLineField.branch,
+ ),
+ ]);
+ }
static WorkspacePaneContext? focused(AppNotifier app) {
final pane = app.focusedPane;
@@ -170,7 +191,7 @@ class WorkspacePaneContext {
_ => engineIdentity(engine).label,
};
final projectName = project?.label ?? '';
- final branch = project?.shownBranch;
+ final branch = agent?.gitContext?.branchLabel ?? project?.shownBranch;
return WorkspacePaneContext(
pane: pane,
agent: agent,
@@ -187,6 +208,9 @@ class WorkspacePaneContext {
if (project != null) 'Project: ${project.label}',
if (project != null) project.cwd,
?project?.branchDetail,
+ if (agent?.gitContext case final git?) git.explanation,
+ if (agent?.gitContext?.observedAt case final at?)
+ 'Work observed ${localWorkTime(at)}',
].join('\n'),
);
}
diff --git a/desktop/lib/widgets/session_work_dialog.dart b/desktop/lib/widgets/session_work_dialog.dart
new file mode 100644
index 000000000..f4550dfff
--- /dev/null
+++ b/desktop/lib/widgets/session_work_dialog.dart
@@ -0,0 +1,354 @@
+import 'dart:async';
+import 'dart:math' as math;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:url_launcher/url_launcher.dart';
+
+import '../core/agent_git_context.dart';
+import '../core/models.dart';
+import '../shared/theme/app_theme.dart' as grid;
+import '../terminal/terminal_text.dart';
+import '../terminal/terminal_theme.dart';
+import '../terminal/terminal_theme_store.dart';
+import 'box_chrome.dart';
+import 'terminal_text_action.dart';
+
+/// Inspection only. This surface never sends terminal input or mutates a checkout.
+class SessionWorkDialog extends StatefulWidget {
+ const SessionWorkDialog({
+ super.key,
+ required this.agent,
+ required this.read,
+ this.online = true,
+ this.open,
+ });
+ final Agent agent;
+ final Future<Map<String, dynamic>> Function(int offset) read;
+ final bool online;
+ final Future<bool> Function(Uri)? open;
+ @override
+ State<SessionWorkDialog> createState() => _SessionWorkDialogState();
+}
+
+class _SessionWorkDialogState extends State<SessionWorkDialog> {
+ AgentGitContext? _data;
+ bool _loading = false;
+ String? _error;
+ int _revision = 0, _visiblePrs = 4;
+ final _unavailable = <String>{};
+ @override
+ void initState() {
+ super.initState();
+ _data = widget.agent.gitContext;
+ if (widget.online) unawaited(_refresh(0));
+ }
+
+ Future<void> _refresh(int offset) async {
+ final revision = ++_revision;
+ setState(() {
+ _loading = true;
+ _error = null;
+ });
+ Map<String, dynamic> result;
+ try {
+ result = await widget.read(offset);
+ } catch (_) {
+ result = {'status': 'unavailable'};
+ }
+ if (!mounted || revision != _revision) return;
+ setState(() {
+ _loading = false;
+ final raw = result['gitContext'];
+ if (raw is Map && result['history'] is Map) {
+ _data =
+ AgentGitContext.fromJson({...raw, 'history': result['history']}) ??
+ _data;
+ for (final lookup
+ in result['lookups'] is List
+ ? result['lookups'] as List
+ : const []) {
+ if (lookup is! Map || lookup['url'] is! String) continue;
+ if (lookup['status'] == 'unavailable') {
+ _unavailable.add(lookup['url']);
+ } else {
+ _unavailable.remove(lookup['url']);
+ }
+ }
+ } else {
+ _error = 'Work history is unavailable. Showing saved observations.';
+ }
+ });
+ }
+
+ Future<void> _open(Uri uri) async {
+ bool opened;
+ try {
+ opened =
+ await (widget.open?.call(uri) ??
+ launchUrl(uri, mode: LaunchMode.externalApplication));
+ } catch (_) {
+ opened = false;
+ }
+ if (mounted && !opened) setState(() => _error = 'Could not open GitHub.');
+ }
+
+ @override
+ void dispose() {
+ _revision++;
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ TerminalFontScope.watch(context);
+ grid.AppTheme.watch(context);
+ return ValueListenableBuilder(
+ valueListenable: terminalThemeStore,
+ builder: (context, _, _) {
+ final theme = terminalThemeFor(
+ grid.AppTheme.palette.value,
+ terminalThemeStore.value,
+ );
+ final cell = terminalCellSizeOf(context);
+ final style = terminalContentStyle(color: theme.foreground);
+ final muted = style.copyWith(
+ color: theme.foreground.withValues(alpha: .65),
+ );
+ final data = _data;
+ final current =
+ data?.current ?? (data == null ? widget.agent.project : null);
+ final prs = [...?data?.pullRequests];
+ int rank(AgentWorkPr pr) => switch (pr.state) {
+ 'Open' || 'Draft' => 0,
+ 'Merged' || 'Closed' => 2,
+ _ => 1,
+ };
+ prs.sort((a, 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(
+ height: cell.height,
+ child: Tooltip(
+ message: text,
+ child: Text(
+ text,
+ style: dim ? muted : style,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ ),
+ ),
+ );
+ return Dialog(
+ backgroundColor: theme.background,
+ elevation: 0,
+ insetPadding: EdgeInsets.symmetric(
+ horizontal: cell.width * 2,
+ vertical: cell.height * 2,
+ ),
+ shape: RoundedRectangleBorder(
+ 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: 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} · Work'),
+ line(
+ widget.online
+ ? data?.explanation ?? 'Session workspace'
+ : 'Offline · last known work',
+ dim: true,
+ ),
+ SizedBox(height: cell.height),
+ Expanded(
+ child: ListView(
+ children: [
+ line(
+ current?.branch ??
+ data?.branchLabel ??
+ 'No branch observed',
+ ),
+ if (current != null)
+ line(current.root ?? current.cwd, dim: true),
+ if (data?.observedAt case final at?)
+ line(
+ 'Work observed ${localWorkTime(at)}',
+ dim: true,
+ ),
+ SizedBox(height: cell.height),
+ line('Launch workspace', dim: true),
+ line(widget.agent.project?.cwd ?? 'Unavailable'),
+ 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: TextButton(
+ key: ValueKey('work-pr-${pr.url}'),
+ onPressed: () => unawaited(_open(pr.url)),
+ style:
+ TextButton.styleFrom(
+ alignment: Alignment.centerLeft,
+ foregroundColor: theme.foreground,
+ textStyle: style,
+ padding: EdgeInsets.zero,
+ minimumSize: Size.zero,
+ tapTargetSize:
+ MaterialTapTargetSize.shrinkWrap,
+ shape: const RoundedRectangleBorder(),
+ splashFactory: NoSplash.splashFactory,
+ ).copyWith(
+ overlayColor:
+ WidgetStateProperty.resolveWith(
+ (states) =>
+ states.any(
+ {
+ WidgetState.focused,
+ WidgetState.hovered,
+ WidgetState.pressed,
+ }.contains,
+ )
+ ? theme.selection
+ : 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',
+ ),
+ ),
+ ),
+ ),
+ 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 (prs.length > _visiblePrs)
+ Align(
+ alignment: Alignment.centerLeft,
+ child: TerminalTextAction(
+ label: 'Show more',
+ onPressed: _loading
+ ? null
+ : () {
+ final offset = _visiblePrs;
+ setState(() => _visiblePrs += 4);
+ if (widget.online) {
+ unawaited(_refresh(offset));
+ }
+ },
+ ),
+ ),
+ SizedBox(height: cell.height),
+ line('Observed branches'),
+ if (data?.branches.isEmpty ?? true)
+ line('No branch history observed yet.', dim: true),
+ for (final branch
+ in data?.branches ?? <AgentWorkBranch>[]) ...[
+ line(
+ '${branch.branch}${branch.cwd == current?.root && branch.branch == current?.branch ? ' · current' : ''}',
+ ),
+ line(branch.cwd, dim: true),
+ ],
+ if (data?.state == 'multiple' ||
+ data?.state == 'uncertain' ||
+ data?.state == 'unavailable') ...[
+ SizedBox(height: cell.height),
+ line('Recent work locations'),
+ for (final location
+ in data?.locations ?? <AgentWorkLocation>[])
+ line(location.cwd, dim: true),
+ ],
+ SizedBox(height: cell.height),
+ line(
+ data?.truncated == true
+ ? 'Older observations are omitted.'
+ : 'History includes observed work; earlier work may be missing.',
+ dim: true,
+ ),
+ ],
+ ),
+ ),
+ if (_error != null) line(_error!),
+ SizedBox(
+ width: double.infinity,
+ child: Wrap(
+ alignment: WrapAlignment.spaceBetween,
+ children: [
+ if (widget.online)
+ TerminalTextAction(
+ label: _loading ? 'Refreshing…' : 'Refresh',
+ onPressed: _loading
+ ? null
+ : () => unawaited(_refresh(0)),
+ ),
+ 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
new file mode 100644
index 000000000..20a2df9a9
--- /dev/null
+++ b/desktop/test/session_git_context_test.dart
@@ -0,0 +1,201 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/agent_git_context.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/state/app_state.dart';
+
+Map<String, dynamic> gitFixture({
+ String state = 'observed',
+ String branch = 'hn/preview-fix',
+}) => {
+ 'state': state,
+ 'observedAt': '2026-09-27T13:00:00Z',
+ 'current': state == 'observed'
+ ? {
+ 'name': 'app',
+ 'cwd': '/ship-hn',
+ 'root': '/ship-hn',
+ 'remote': 'github.com/acme/app',
+ 'branch': branch,
+ 'worktree': true,
+ }
+ : null,
+ 'locations': [
+ {'cwd': '/ship-hn/tui', 'at': '2026-09-27T13:00:00Z'},
+ ],
+ 'history': {
+ 'branches': [
+ {
+ 'cwd': '/ship-hn',
+ 'remote': 'github.com/acme/app',
+ 'branch': branch,
+ 'at': '2026-09-27T13:00:00Z',
+ },
+ ],
+ 'pullRequests': [
+ {
+ 'url': 'https://github.com/acme/app/pull/12',
+ 'cwd': '/ship-hn',
+ 'at': '2026-09-27T13:00:00Z',
+ 'checkedAt': '2026-09-27T13:01:00Z',
+ 'result': {
+ 'status': 'found',
+ 'url': 'https://github.com/acme/app/pull/12',
+ 'number': 12,
+ 'state': 'Open',
+ },
+ },
+ ],
+ },
+};
+Agent workAgent({Map<String, dynamic>? git}) => Agent.fromJson({
+ 'id': 'hn',
+ 'name': 'hn',
+ 'engine': 'claude',
+ 'project': {
+ 'name': 'app',
+ 'cwd': '/silent-beacon',
+ 'root': '/silent-beacon',
+ 'branch': 'original',
+ },
+ 'gitContext': ?git,
+});
+
+Map<String, dynamic> manyPrFixture() {
+ final git = gitFixture(
+ branch: 'hn/fix-terminal-preview-and-nfc-session-ordering',
+ );
+ final history = git['history'] as Map;
+ history['pullRequests'] = [
+ for (var i = 0; i < 7; i++)
+ {
+ 'url': 'https://github.com/acme/app/pull/${120 + i}',
+ 'cwd': '/ship-hn',
+ 'at': '2026-09-27T13:00:00Z',
+ 'checkedAt': '2026-09-27T13:01:00Z',
+ 'result': {
+ 'status': 'found',
+ 'url': 'https://github.com/acme/app/pull/${120 + i}',
+ 'number': 120 + i,
+ 'state': ['Open', 'Draft', 'Merged', 'Closed'][i % 4],
+ 'title': [
+ 'Preserve complete session previews',
+ 'Keep concurrent NFC sessions in order',
+ 'Resolve earlier transport failures',
+ 'Replace the original UI experiment',
+ ][i % 4],
+ 'headBranch': 'hn/${['preview', 'nfc', 'transport', 'ui'][i % 4]}',
+ 'baseBranch': 'main',
+ },
+ },
+ ];
+ return git;
+}
+
+void main() {
+ test('renamed PR aliases do not duplicate the original creation receipt', () {
+ final git = gitFixture();
+ final row = (git['history']['pullRequests'] as List).single as Map;
+ row['aliases'] = ['https://github.com/acme/old-name/pull/12'];
+ git['pullRequests'] = [
+ {
+ 'url': 'https://github.com/acme/old-name/pull/12',
+ 'cwd': '/ship-hn',
+ 'at': '2026-09-27T13:00:00Z',
+ },
+ ];
+ expect(
+ AgentGitContext.fromJson(git)!.pullRequests.single.url.toString(),
+ 'https://github.com/acme/app/pull/12',
+ );
+ });
+ test(
+ 'older list/push context cannot undo newer work in the same session',
+ () {
+ Agent versioned(int revision, String branch, {String epoch = 'daemon'}) =>
+ workAgent(
+ git: {
+ ...gitFixture(branch: branch),
+ 'version': {'epoch': epoch, 'revision': revision},
+ },
+ );
+ final current = versioned(2, 'new');
+ final stale = versioned(1, 'old');
+ expect(
+ retainNewerGitContext(stale, current).displayProject!.branch,
+ 'new',
+ );
+ expect(
+ retainNewerGitContext(
+ versioned(3, 'newest'),
+ current,
+ ).displayProject!.branch,
+ 'newest',
+ );
+ expect(
+ retainNewerGitContext(
+ versioned(1, 'restart', epoch: 'new-daemon'),
+ current,
+ ).displayProject!.branch,
+ 'restart',
+ );
+ expect(retainNewerGitContext(stale, null).displayProject!.branch, 'old');
+ expect(
+ retainNewerGitContext(workAgent(), current).displayProject!.branch,
+ 'original',
+ );
+ },
+ );
+ test(
+ 'current display changes while launch and copy identity stay intact',
+ () {
+ final agent = workAgent(git: gitFixture());
+ expect(agent.displayProject!.branch, 'hn/preview-fix');
+ expect(agent.project!.branch, 'original');
+ expect(agent.copyWith(name: 'new name').gitContext, agent.gitContext);
+ expect(agent.gitContext!.requestIdentity, {
+ 'cwd': '/ship-hn',
+ 'branch': 'hn/preview-fix',
+ 'remote': 'github.com/acme/app',
+ });
+ expect(
+ AppNotifier.agentsEqual(
+ [agent],
+ [workAgent(git: gitFixture(branch: 'hn/next'))],
+ ),
+ isFalse,
+ );
+ expect(
+ AppNotifier.agentsEqual([agent], [workAgent(git: gitFixture())]),
+ isTrue,
+ );
+ },
+ );
+ test('uncertainty never presents the launch branch as current work', () {
+ for (final state in ['multiple', 'uncertain', 'unavailable']) {
+ final agent = workAgent(git: gitFixture(state: state));
+ expect(agent.displayProject!.shownBranch, isNull);
+ expect(agent.gitContext!.requestIdentity, isNull);
+ expect(agent.gitContext!.branchLabel, isNotNull);
+ }
+ expect(workAgent().displayProject!.branch, 'original');
+ });
+ test(
+ 'saved links are bounded and only validated GitHub PRs become actionable',
+ () {
+ expect(
+ AgentGitContext.fromJson(gitFixture())!.pullRequests.single.state,
+ 'Open',
+ );
+ for (final url in [
+ 'javascript:alert(1)',
+ 'https://evil.example/a/b/pull/1',
+ 'https://github.com/a/../pull/1',
+ 'https://[email protected]/a/b/pull/1',
+ 'https://github.com/a/b/pull/1?x=1',
+ ]) {
+ expect(AgentGitContext.validatedPrUrl(url), isNull);
+ }
+ expect(AgentGitContext.fromJson({'state': 'made-up'}), isNull);
+ },
+ );
+}
diff --git a/desktop/test/session_work_dialog_test.dart b/desktop/test/session_work_dialog_test.dart
new file mode 100644
index 000000000..2b4d17a08
--- /dev/null
+++ b/desktop/test/session_work_dialog_test.dart
@@ -0,0 +1,150 @@
+import 'dart:async';
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+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/widgets/session_work_dialog.dart';
+
+import 'session_git_context_test.dart';
+import 'support/real_fonts.dart';
+
+void main() {
+ setUpAll(loadRealFonts);
+ testWidgets(
+ 'opening work details preserves launch context and only follows the selected PR link',
+ (tester) async {
+ final opened = <Uri>[];
+ final git = gitFixture();
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: SessionWorkDialog(
+ agent: workAgent(git: git),
+ read: (_) async => {'gitContext': git, 'history': git['history']},
+ open: (uri) async {
+ opened.add(uri);
+ return true;
+ },
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(find.text('/silent-beacon'), findsOneWidget);
+ expect(find.text('hn/preview-fix'), findsOneWidget);
+ await tester.tap(
+ find.byKey(
+ const ValueKey('work-pr-https://github.com/acme/app/pull/12'),
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(opened, [Uri.parse('https://github.com/acme/app/pull/12')]);
+ expect(tester.takeException(), isNull);
+ },
+ );
+
+ testWidgets(
+ 'late replies after dismissal cannot reopen or replace another view',
+ (tester) async {
+ final reply = Completer<Map<String, dynamic>>();
+ final focus = FocusNode();
+ addTearDown(focus.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Builder(
+ builder: (context) => Scaffold(
+ body: TextButton(
+ focusNode: focus,
+ autofocus: true,
+ onPressed: () => showDialog<void>(
+ context: context,
+ builder: (_) => SessionWorkDialog(
+ agent: workAgent(git: gitFixture()),
+ read: (_) => reply.future,
+ ),
+ ),
+ child: const Text('Inspect'),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(find.byType(SessionWorkDialog), findsOneWidget);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(find.byType(SessionWorkDialog), findsNothing);
+ expect(focus.hasFocus, isTrue);
+ reply.complete({'status': 'unavailable'});
+ await tester.pumpAndSettle();
+ expect(tester.takeException(), isNull);
+ },
+ );
+
+ for (final brightness in Brightness.values) {
+ for (final size in [const Size(1000, 720), const Size(420, 680)]) {
+ testWidgets(
+ 'work details fit ${size.width} ${brightness.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 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),
+ ),
+ child: child!,
+ ),
+ 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 · last known work'), findsOneWidget);
+ expect(tester.takeException(), isNull);
+ 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-${size.width.toInt()}-${brightness.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
new file mode 100644
index 000000000..c406561f9
--- /dev/null
+++ b/desktop/test/session_work_navigation_test.dart
@@ -0,0 +1,93 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shared/theme/appearance_prefs_store.dart';
+import 'package:harness/shared/theme/prompt_style.dart';
+import 'package:harness/shared/theme/status_line_style.dart';
+import 'package:harness/state/workspace_status.dart';
+import 'package:harness/terminal/terminal_binary.dart';
+import 'package:harness/widgets/session_work_dialog.dart';
+
+import 'session_git_context_test.dart';
+import 'swarm_screen_test.dart' show mount, terminal;
+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)',
+ (tester) async {
+ final old = appearancePrefsStore.value;
+ appearancePrefsStore.value = old.copyWith(prompt: const PromptPrefs());
+ addTearDown(() => appearancePrefsStore.value = old);
+ final updates = <Map>[];
+ const channel = MethodChannel('harness/swarm_tabs');
+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ channel,
+ (call) async {
+ if (call.method == 'update') updates.add(call.arguments as Map);
+ return null;
+ },
+ );
+ addTearDown(
+ () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ channel,
+ null,
+ ),
+ );
+ final app = createApp();
+ addTearDown(app.dispose);
+ app.stateOf('m')!
+ ..agents = [workAgent(git: gitFixture())]
+ ..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');
+ if (native) {
+ final fields =
+ ((updates.last['focusedContext'] as Map)['fields'] as List)
+ .cast<Map>();
+ final payload = fields.singleWhere((p) => p['field'] == 'branch');
+ await tester.binding.defaultBinaryMessenger.handlePlatformMessage(
+ channel.name,
+ const StandardMethodCodec().encodeMethodCall(
+ MethodCall('focusedContext', payload),
+ ),
+ (_) {},
+ );
+ } else {
+ await tester.tap(
+ find.byKey(const ValueKey('workspace-context-branch')),
+ );
+ }
+ await tester.pumpAndSettle();
+ expect(find.byType(SessionWorkDialog), findsOneWidget);
+ expect(find.text('/silent-beacon'), findsOneWidget);
+ expect(pane.session, same(session));
+ expect(input, isEmpty);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(find.byType(SessionWorkDialog), findsNothing);
+ expect(pane.session, same(session));
+ expect(input, isEmpty);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+ }
+
+ test('ambiguous workspace text is never decorated as a real branch', () {
+ final app = createApp();
+ addTearDown(app.dispose);
+ app.stateOf('m')!.agents = [workAgent(git: gitFixture(state: 'multiple'))];
+ app.adoptSessionForTest(terminal('hn', []));
+ final context = WorkspacePaneContext.focused(app)!;
+ for (final style in StatusLineStyle.values) {
+ final parts = context.format(PromptPrefs(statusStyle: style));
+ expect(parts.text, contains('Multiple workspaces'));
+ expect(parts.segments.any((s) => s.branchSymbol), isFalse);
+ expect(parts.text, isNot(contains('original')));
+ }
+ });
+}
diff --git a/desktop/test/session_work_state_test.dart b/desktop/test/session_work_state_test.dart
new file mode 100644
index 000000000..a56eb372f
--- /dev/null
+++ b/desktop/test/session_work_state_test.dart
@@ -0,0 +1,136 @@
+import 'dart:async';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/state/app_state.dart';
+
+import 'session_git_context_test.dart';
+import 'support/rename_connection.dart';
+import 'swarm_state_test.dart' show createApp;
+
+class WorkConnection extends RenameConnection {
+ final workReplies = <Completer<Map<String, dynamic>>>[];
+ final workRequests = <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_request') {
+ return super.request(type, payload: payload, timeout: timeout);
+ }
+ workRequests.add(payload);
+ final reply = Completer<Map<String, dynamic>>();
+ workReplies.add(reply);
+ return reply.future;
+ }
+}
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+ late WorkConnection connection;
+ late AppNotifier app;
+ setUp(() {
+ connection = WorkConnection();
+ app = createApp(connectionForTest: (_) => connection);
+ app.stateOf('m')!
+ ..agents = [workAgent(git: gitFixture())]
+ ..connectionStatus = ConnectionStatus.connected
+ ..nodeOnline = true;
+ });
+ tearDown(() => app.dispose());
+
+ test('history replies cannot cross conversation replacement or a machine reconnect', () async {
+ for (final replaceMachine in [false, true]) {
+ app.stateOf('m')!.agents = [workAgent(git: gitFixture())];
+ final response = app.readAgentGitHistory('m', 'hn', offset: 4);
+ expect(connection.workRequests.last, {
+ 'agentId': 'hn',
+ 'history': true,
+ 'offset': 4,
+ });
+ if (replaceMachine) {
+ app.machineStates['m'] = MachineState(app.stateOf('m')!.machine)
+ ..agents = [workAgent(git: gitFixture())];
+ } else {
+ app.stateOf('m')!.agents = const [
+ Agent(
+ id: 'hn',
+ name: 'Reused slot',
+ engine: 'codex',
+ sessionId: 'other',
+ ),
+ ];
+ }
+ connection.workReplies.last.complete({
+ 'gitContext': gitFixture(),
+ 'history': gitFixture()['history'],
+ });
+ expect(await response, {'status': 'unavailable'});
+ }
+ });
+
+ test(
+ 'out-of-order push frames preserve new context without mixing machines',
+ () async {
+ Map<String, dynamic> wire(int revision, String branch) => {
+ 'id': 'hn',
+ 'name': 'hn',
+ 'engine': 'claude',
+ 'sessionId': 'conversation',
+ 'terminal': {'available': true},
+ 'project': {
+ 'name': 'app',
+ 'cwd': '/silent-beacon',
+ 'branch': 'original',
+ },
+ 'gitContext': {
+ ...gitFixture(branch: branch),
+ 'version': {'epoch': 'daemon', 'revision': revision},
+ },
+ };
+ final machine = Machine(
+ machineId: 'other',
+ authMode: MachineAuthMode.remote,
+ name: 'Other',
+ );
+ app.machineStates['other'] = MachineState(machine);
+ for (final target in ['m', 'other']) {
+ await app.handleMachineEventForTest(target, {
+ 'type': 'agent_synced',
+ 'payload': {
+ 'agent': wire(
+ target == 'm' ? 2 : 1,
+ target == 'm' ? 'new' : 'other-work',
+ ),
+ },
+ });
+ }
+ await app.handleMachineEventForTest('m', {
+ 'type': 'agent_synced',
+ 'payload': {'agent': wire(1, 'old')},
+ });
+ expect(app.stateOf('m')!.agents.single.displayProject!.branch, 'new');
+ expect(
+ app.stateOf('other')!.agents.single.displayProject!.branch,
+ 'other-work',
+ );
+ },
+ );
+
+ test('current PR request is bound to the displayed checkout and checks the reply identity', () async {
+ final pending = app.readAgentPullRequest('m', 'hn');
+ expect(connection.workRequests.single['context'], {
+ 'cwd': '/ship-hn',
+ 'branch': 'hn/preview-fix',
+ 'remote': 'github.com/acme/app',
+ });
+ connection.workReplies.single.complete({
+ 'status': 'found',
+ 'number': 12,
+ 'context': {'cwd': '/different'},
+ });
+ expect(await pending, {'status': 'unavailable'});
+ });
+}
diff --git a/docs/plans/2026-09-27-session-git-context.md b/docs/plans/2026-09-27-session-git-context.md
new file mode 100644
index 000000000..3ee331b2a
--- /dev/null
+++ b/docs/plans/2026-09-27-session-git-context.md
@@ -0,0 +1,186 @@
+# Session Git context
+
+## Product contract
+
+A session is a durable conversation, a worktree is a checkout, a branch is a
+mutable Git ref, and a pull request is a durable review record. These have
+different lifetimes. A session can work in several checkouts and produce many
+branches and PRs without changing its name or launch directory.
+
+The focused context shows the branch read from Git in the most recently
+observed work location. Its tooltip explains the location and observation time.
+The session's original directory remains available as “Launch workspace”.
+If several locations occur in one operation, show “Multiple workspaces” and
+let the user inspect them. Never select one by an arbitrary completion order.
+When no work location is observable, label the registered directory as the
+session workspace rather than claiming to know where a tool is executing.
+
+The branch opens session work details. The current PR remains a direct GitHub
+link. Details contain recent workspaces/branches and PRs associated with this
+session, with open work before merged/closed history. A PR opened for review,
+a successful push, and a merge are different facts. Do not call a push shipped.
+All actions on this surface are inspection/navigation; opening it cannot
+checkout, stash, merge, reset, delete, or send terminal input.
+
+## Evidence and ownership
+
+Keep registry `cwd` unchanged: launch, resume, viewers, and cleanup depend on it.
+Add display context separately. Source absolute work locations from successful
+tool receipts, including explicit tool cwd, literal `cd … && …`, `git -C …`, and
+file tools. Read actual branch names from Git; folder names and transcript
+startup `gitBranch` fields are not current branch evidence.
+
+Parse only literal, unambiguous commands. Never execute transcript text. Dynamic
+shell expressions and arbitrary code-mode scripts cannot establish a location.
+Record uncertainty rather than attaching their results to a guessed checkout.
+Handle Claude and Codex receipts through the existing incremental transcript
+reader. Other engines retain their registered workspace until they supply the
+same observations. Ignore inherited fork history and another session's rows.
+
+Persist minimal locations, timestamps, branch observations and validated PR URLs
+on the owning machine, outside the checkout. Keep raw commands, tool output,
+credentials and environment out of the record and wire response. Bound pending
+receipts, history, subprocesses, cache sizes and network work. Replays and daemon
+restarts must not duplicate associations. Git data and PR data have independent
+freshness; an unavailable lookup must not become “no PR” or erase known history.
+
+Associate PRs by successful creation receipts or a verified repository + head
+branch lookup for an observed checkout. Never infer session ownership from the
+GitHub author, branch prefix, or every branch in the shared repository. Retain
+PR identity after branch/worktree deletion. Fork PR identity includes base
+repository, head repository and head ref. Show unavailable access explicitly in
+details; keep a validated saved link usable.
+
+## Delivery and transport
+
+Every agent frame carries the same display context in list and push responses.
+Old clients continue to receive the registered `project`. New clients prefer
+the observed display context. Branch and PR must refer to the same checkout
+identity: discard replies after focus, repository, branch or workspace changes.
+Use the existing encrypted `git_pull_request` RPC with an optional history
+request, so a new protocol type is unnecessary. Readers remain on the owning
+machine and use its existing GitHub access.
+
+Desktop, native titlebar and web share the existing status formatter. Mobile
+uses the same context semantics and exposes details through its session UI.
+The terminal design system applies: plain text, measured cells, keyboard
+navigation, preserved focus, no terminal recreation. Narrow layouts truncate
+the current context while preserving the details action and accessible names.
+Offline views show last-known observations as such.
+
+## Git workflow
+
+Use one topic branch per independently reviewable change and one worktree per
+concurrently edited checkout. An agent can reuse its own worktree for sequential
+tasks and have several PRs open. Switch only with saved work and no process still
+using that checkout. Start unrelated work from updated `origin/main`; explicitly
+stack dependent changes. Put review fixes on the original PR branch. Retire
+merged topic branches and start new ones for subsequent work. PR history is the
+durable output record. Worktrees share refs and remotes, so they are isolation
+for files/index/HEAD rather than independent repositories.
+
+## Verification gates
+
+- Reproduce `silent-beacon` launch + successful work under `ship-hn/tui`; show
+ the branch of that checkout and preserve the launch directory.
+- Same worktree switching branches refreshes display and PR identity.
+- Multiple worktrees and overlapping/out-of-order tool completions cannot
+ confidently label the wrong checkout as current.
+- Quoted paths, subdirectories, detached HEAD, non-Git folders, deleted worktrees,
+ invalid paths, dynamic shell code, failed tools and running tools are covered.
+- PR creation, repeated receipts, multiple PRs, forks, merges, branch deletion,
+ permission failure and offline refresh retain correct associations.
+- Restart/checkpoint migration, append-only reads, transcript replacement,
+ foreign-session records and inherited fork history are covered.
+- Old/new wire shapes, list/push equivalence, stale async replies, independent
+ machines, dependent viewers and account/session changes are covered.
+- UI verification covers keyboard access, dismissal/focus restoration, long
+ names, narrow windows, light/dark palettes and enlarged terminal text.
+
+## Implementation
+
+- `sessionWork.ts` extracts minimal receipt evidence; `literalToolCall.ts` parses
+ a static literal subset without evaluating code. Yielded processes and cells
+ are correlated with passive waits, including waits after checkpoint reload.
+- `agentTokenUsage.ts` maintains observations in its existing append-only reader
+ and v3 private checkpoint. No new transcript scanner or idle watcher is added.
+- `sessionGitContext.ts` resolves checkout roots and branches. `agentFrame.ts`
+ includes the same additive context on list and push frames; stable daemon
+ versions and client merge rules protect against response reordering.
+- `sessionGitHistory.ts` persists bounded conversation history. Entries with
+ active readers/writes cannot be evicted, older lookups cannot undo newer state,
+ and repository-rename aliases do not duplicate receipts.
+- `gitPullRequest.ts` handles current head/fork matching, multiple PRs and saved
+ URLs independently of checkout lifetime. Caches retain the actual GitHub check
+ time. `sessionGitPullRequest.ts` and the existing encrypted RPC serve details.
+- Desktop/native/web share observed context through `WorkspacePaneContext`.
+ Branch navigation and the command picker open `SessionWorkDialog`; phone
+ offers `SessionWorkPage`. Launch, clone, resume and cleanup identities retain
+ their previous meaning.
+
+## Verification evidence
+
+Final checks on 2026-09-27:
+
+- CLI: TypeScript check, 295 tests across 12 relevant files, and production build
+ passed. The build retains an existing ESM `require` warning in the unchanged
+ `src/dsh/verdict.spec.ts`.
+- Desktop: 35 widget/model/controller regression tests passed; changed files
+ passed static analysis without issues.
+- Phone: 35 widget/model/state regression tests passed; changed files passed
+ static analysis without issues.
+- All eight synthetic renders were inspected. The final diff has no whitespace
+ errors. Two representative captures are included in
+ [the PR assets](../../.github/assets/session-git-context/README.md); generated
+ build products and the remaining captures stay outside the source diff.
+
+Pre-merge validation after rebasing onto `aae13041` (PR #396), on macOS 26.6.2
+with Node 22.23.1 and Flutter 3.47.2 / Dart 3.13.2:
+
+- Full CLI suite: 5,252 tests passed, 63 skipped; 310 files passed and 7 skipped.
+ TypeScript check and production build passed. The opt-in real-engine and
+ multiplexer suites were not enabled. The first sandboxed attempt was stopped
+ after process-access restrictions; the complete run outside that sandbox
+ passed using the suite's isolated data/runtime directories.
+- Desktop's 35 tests and changed-file analysis passed again after the rebase.
+- Phone sources were unaffected by the rebase; the 35-test and analysis results
+ above apply to the final sources.
+
+The automated Git integration uses real temporary repositories, linked worktrees
+and JSONL transcripts, with deterministic GitHub responses. It exercises the
+same readers and frame/RPC service used in production, without touching a user's
+checkout or opening a live PR.
+
+| Contract | Evidence |
+| --- | --- |
+| Original `hn` reproduction and branch switches | `sessionGitPullRequest.spec.ts`: launch in `silent-beacon`, receipts in `ship-hn/tui`, two actual Git branches, branch-bound PR replies, unchanged registered cwd |
+| Worktree/branch deletion and restart | Same integration removes the linked checkout and both branches, verifies merged PRs by URL, reloads history from disk, then simulates unavailable GitHub access |
+| Ambiguous, overlapping and yielded work | `sessionWork.spec.ts`: literal/quoted/dynamic commands, failed calls, multiple paths, out-of-order completion, code-mode cells, process polls and interactive input |
+| Git identity | `sessionGitContext.spec.ts`, `agentProject.spec.ts`: actual branch rather than folder name, linked worktree roots, subdirectories, non-Git/missing folders, detached HEAD, bounded reads and stable frame versions |
+| Durable minimal data | `sessionGitHistory.spec.ts`: two branches, restart, file mode 0600, separate conversations/forks, active-write eviction, stale state and renamed-URL deduplication |
+| Incremental replay | `sessionWorkCache.spec.ts`, `agentTokenUsage.spec.ts`, `agentOutputStats.spec.ts`: append-only reads, restart, old checkpoints, compaction, foreign session metadata and inherited/sidechain records |
+| GitHub states and forks | `gitPullRequest.spec.ts`: open/draft/closed/merged, fork collisions, parent PRs, repository renames, saved URLs, concurrency bounds, truthful cached check time and a branch switch during a lookup |
+| Transport compatibility | `agentFrame.spec.ts`, `backendSocket.spec.ts`: shared complete frame shape, legacy badge requests, encrypted requester-scoped history replies |
+| Client ordering and navigation | Desktop/mobile `session_git_context_test.dart` and `session_work_state_test.dart`: old/new data, rename aliases, reordered pushes, machine/session replacement; existing focused-PR tests cover viewer ownership and stale replies |
+| Terminal safety and appearance | Desktop `session_work_navigation_test.dart`: native and Flutter branch actions, same terminal object, zero input, Escape; dialog/page tests cover keyboard return, late replies, offline links, long names, multiple PRs, scrolling and large text |
+
+Synthetic screens were rendered and visually inspected at 1000×720 and 420×680
+on desktop, and 390×760 on phone, in both application brightness settings and
+normal/1.6× text sizes. They inherit the selected terminal palette, which can
+remain dark when the surrounding application is light. Screens use real test
+fonts and the phone's actual back-button icon font. Capture them again with
+`HARNESS_GIT_CONTEXT_CAPTURE_DIR=/tmp/session-work-captures` when running the
+respective dialog/page widget tests.
+
+### Delivery boundaries
+
+Observation history is intentionally partial. Dynamic/arbitrary code and engines
+without readable receipts show explicit uncertainty or the labeled registered
+workspace. Git and GitHub caches refresh independently (15 seconds and 60 seconds).
+The reader supports github.com origins and their fork parents; GitHub Enterprise
+and arbitrary fork-network bases are not claimed. No live GitHub credentials or
+network were needed for the deterministic tests. A release/install is a separate
+step; this change does not alter running agents' checkouts.
+
+The user-facing behavior and recommended Git workflow are documented in
+[Session work, branches, and pull requests](../worktree-pull-requests.md).
diff --git a/docs/worktree-pull-requests.md b/docs/worktree-pull-requests.md
index e74e3d990..0c87dcb74 100644
--- a/docs/worktree-pull-requests.md
+++ b/docs/worktree-pull-requests.md
@@ -1,22 +1,102 @@
-# 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 PR badge and branch context hide together when hovering
-reveals the pane controls; compact headers use `#123 · Draft` and reserve room for the badge before branch prose.
-Only very small headers (under 360 logical pixels at normal text scale) omit it.
-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.
-
-Only a validated PR result shows a badge. Loading, empty lookups and unavailable results stay hidden.
-The API still distinguishes an unavailable lookup from a successful lookup with 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.
+# Session work, branches, and pull requests
+
+A session has a stable name and launch workspace. Its current Git context follows
+the checkout where work was most recently observed. Its PR history records output
+across tasks. These identities have different lifetimes and should not be combined
+into one permanent branch label.
+
+For example, `hn` can launch in `silent-beacon`, run tools in `ship-hn/tui`, and
+work on `hn/nfc` followed by `hn/preview`. The bar shows the branch Git reports for
+`ship-hn`, while Work details retain both observed branches and their PRs.
+`silent-beacon` remains the launch/resume workspace.
+
+## Display and navigation
+
+The focused app bar shows the current named branch and a separate
+`#123 Open / Draft / Merged / Closed` link. A dependent viewer uses its owner's
+context. Native macOS and Flutter/web use the same formatter. The branch opens
+**Work** details; the PR opens GitHub. **Inspect session work** is also available
+through the command picker, including when there is no branch. Older daemons
+retain their existing branch-scoped search behavior.
+
+On phone, the session menu offers **Branches and pull requests**. Both surfaces
+show the current observation, launch workspace, observed branch history, and PRs
+with repository, title, head/base branch, state, and check time. Open/draft work
+appears before unknown and completed work. Four PRs are shown initially; Show more
+expands the history. Refresh checks a bounded page; each PR keeps its own actual
+GitHub check time, including when a cached answer is reused.
+
+| Evidence | Display |
+| --- | --- |
+| Successful tools in one checkout | Its actual current branch |
+| Several checkouts in one operation | Multiple workspaces |
+| Unresolved execution or unsupported dynamic commands | Work location unknown |
+| The observed directory has disappeared | Workspace unavailable |
+| No tool observations yet | Session workspace, explicitly labeled in details |
+| Machine offline | Last-known observations, labeled offline |
+
+Paths and long values remain inspectable in details and accessibility text.
+An unavailable lookup preserves saved PR links and their last-known status.
+Nothing on this surface checks out, pushes, merges, deletes, or sends terminal input.
+A push is not described as shipped; a merged PR is not evidence that a worktree
+can safely be deleted.
+
+## Evidence, privacy, and freshness
+
+The daemon reuses its incremental Claude/Codex transcript reader. It accepts
+successful literal shell/file/patch receipts, explicit tool workdirs, guarded
+`cd … && …`, `git -C`, and a small static subset of Codex code-mode calls. Yielded
+Codex processes/cells stay connected to passive completion polls. Concurrent
+operations are ordered by their start, so a slow earlier operation cannot replace
+newer work. Pending execution remains uncertain.
+
+It never executes transcript text. Arbitrary scripts, shell substitutions,
+interactive input, and unrecognized engine formats cannot establish a location.
+Other engines show the registered workspace. History is explicitly partial: it
+cannot reconstruct branches that were created and deleted between observations,
+or receipts removed before the daemon saw them.
+
+Registry `cwd` and the legacy `project` wire field retain launch semantics.
+The additive `gitContext` carries display evidence on both list and push frames.
+Daemon-scoped versions reject out-of-order snapshots without changing during
+unchanged polling. PR replies are bound to checkout identity; session, machine,
+focus, branch and repository changes discard stale replies.
+
+Minimal histories live under `ADAPTER_DATA_DIR/session-git-history`, outside Git
+worktrees, in private atomic JSON files. They contain validated locations, branch
+observations, PR links and lookup results, never raw commands, credentials or
+transcript output. Conversation identity separates histories and inherited fork
+receipts are excluded. Deleting a checkout does not delete its history.
+
+Histories retain at most 128 branches and 128 PRs per conversation, with an
+explicit truncation message. Git inspection uses the existing 15-second bounded
+cache. GitHub results are cached for 60 seconds; the focused badge refreshes once
+a minute. Four GitHub/Git reader subprocesses can run simultaneously, with a
+bounded queue and deadlines. History refreshes four saved PRs at a time. List
+frames never query GitHub. Private paths travel through the existing encrypted
+machine RPC.
+
+GitHub lookup uses the owning machine's installed `gh` and existing sign-in.
+Current PRs match both head repository and branch, including fork-to-parent PRs;
+an open PR wins over older completed work. Every verified match can be retained
+in history. Saved URLs resolve independently of deleted branches/worktrees and
+follow GitHub repository renames. GitHub Enterprise and arbitrary fork-network
+base repositories beyond the origin's parent are outside this reader's scope.
+
+## Branch workflow for agents
+
+Use one topic branch per independently reviewable change and one worktree per
+concurrently edited checkout. A session can reuse its worktree for sequential
+changes and keep several PRs open. Each active editing process needs its own
+checkout; a shared repository still has shared refs, remotes and Git objects.
+
+Start unrelated changes from updated `origin/main`. Deliberately stack dependent
+changes, with the intended base branch made explicit. Put review fixes on the
+original PR branch. After merging, retire the topic branch and create a new one
+for subsequent work. Switch only after saving work and finishing processes that
+still use that checkout. Keep PR history as the durable review/output record.
+
+This follows [Git worktree semantics](https://git-scm.com/docs/git-worktree) and
+[GitHub flow](https://docs.github.com/en/get-started/using-github/github-flow).
+The [implementation plan and verification evidence](plans/2026-09-27-session-git-context.md)
+cover the delivery contract and regression cases.
diff --git a/mobile/lib/core/agent_git_context.dart b/mobile/lib/core/agent_git_context.dart
new file mode 100644
index 000000000..b8f32c735
--- /dev/null
+++ b/mobile/lib/core/agent_git_context.dart
@@ -0,0 +1,253 @@
+import 'package:flutter/foundation.dart';
+
+import 'models.dart';
+
+bool sameGitConversation(Agent a, Agent? b) =>
+ b != null &&
+ a.id == b.id &&
+ a.sessionId == b.sessionId &&
+ a.engine == b.engine &&
+ a.codexHome == b.codexHome &&
+ a.project?.cwd == b.project?.cwd;
+
+/// List and push messages can cross in flight. Scope ordering to this machine's same
+/// conversation and daemon incarnation; a restarted daemon establishes a new epoch.
+Agent retainNewerGitContext(Agent incoming, Agent? previous) {
+ final old = previous?.gitContext, next = incoming.gitContext;
+ if (sameGitConversation(incoming, previous) &&
+ old?.epoch != null &&
+ old!.epoch == next?.epoch &&
+ old.revision > next!.revision) {
+ return incoming.copyWith(gitContext: old);
+ }
+ return incoming;
+}
+
+String localWorkTime(DateTime timestamp) {
+ final at = timestamp.toLocal();
+ String two(int n) => n.toString().padLeft(2, '0');
+ return '${at.year}-${two(at.month)}-${two(at.day)} ${two(at.hour)}:${two(at.minute)}';
+}
+
+typedef AgentWorkLocation = ({String cwd, DateTime at});
+typedef AgentWorkBranch = ({
+ String cwd,
+ String? remote,
+ String branch,
+ DateTime at,
+});
+typedef AgentWorkPr = ({
+ Uri url,
+ String? cwd,
+ DateTime at,
+ String? state,
+ DateTime? checkedAt,
+ String? title,
+ String? headBranch,
+ String? baseBranch,
+});
+
+/// Display evidence from the owning machine. It never changes launch/resume cwd.
+class AgentGitContext {
+ const AgentGitContext({
+ required this.state,
+ this.current,
+ this.observedAt,
+ this.locations = const [],
+ this.branches = const [],
+ this.pullRequests = const [],
+ this.truncated = false,
+ this.epoch,
+ this.revision = 0,
+ });
+ final String state;
+ final AgentProject? current;
+ final DateTime? observedAt;
+ final List<AgentWorkLocation> locations;
+ final List<AgentWorkBranch> branches;
+ final List<AgentWorkPr> pullRequests;
+ final bool truncated;
+ final String? epoch;
+ final int revision;
+
+ String? get branchLabel => switch (state) {
+ 'multiple' => 'Multiple workspaces',
+ 'uncertain' => 'Work location unknown',
+ 'unavailable' => 'Workspace unavailable',
+ _ =>
+ current?.shownBranch ?? (current?.detached == true ? 'Detached' : null),
+ };
+
+ String get explanation => switch (state) {
+ 'observed' => 'Most recently observed work',
+ 'multiple' => 'The operation used more than one workspace.',
+ 'uncertain' => 'The current work location could not be confirmed.',
+ 'unavailable' => 'The observed workspace is no longer readable.',
+ _ => 'Session workspace; no other work location has been observed.',
+ };
+
+ AgentProject? displayProject(AgentProject? launch) {
+ if (current != null) return current;
+ if (launch == null) return null;
+ // Keep useful repository context without presenting the launch branch as current work.
+ return AgentProject(
+ name: launch.name,
+ cwd: launch.cwd,
+ root: launch.root,
+ remote: launch.remote,
+ worktree: launch.worktree,
+ );
+ }
+
+ Map<String, Object?>? get requestIdentity {
+ final project = current;
+ if (project == null || project.shownBranch == null) return null;
+ return {
+ 'cwd': project.cwd,
+ 'branch': project.branch,
+ 'remote': project.remote,
+ };
+ }
+
+ @override
+ bool operator ==(Object other) =>
+ other is AgentGitContext &&
+ state == other.state &&
+ current == other.current &&
+ observedAt == other.observedAt &&
+ truncated == other.truncated &&
+ epoch == other.epoch &&
+ revision == other.revision &&
+ listEquals(locations, other.locations) &&
+ listEquals(branches, other.branches) &&
+ listEquals(pullRequests, other.pullRequests);
+ @override
+ int get hashCode => Object.hash(
+ state,
+ current,
+ observedAt,
+ truncated,
+ epoch,
+ revision,
+ Object.hashAll(locations),
+ Object.hashAll(branches),
+ Object.hashAll(pullRequests),
+ );
+
+ static AgentGitContext? fromJson(Object? raw) {
+ if (raw is! Map ||
+ !const [
+ 'workspace',
+ 'observed',
+ 'multiple',
+ 'uncertain',
+ 'unavailable',
+ ].contains(raw['state'])) {
+ return null;
+ }
+ String? label(Object? v, [int max = 4096]) =>
+ v is String &&
+ v.isNotEmpty &&
+ v.length <= max &&
+ !RegExp(r'[\x00-\x1f\x7f]').hasMatch(v)
+ ? v
+ : null;
+ DateTime? date(Object? v) => v is String ? DateTime.tryParse(v) : null;
+ List<dynamic> rows(Object? value) =>
+ value is List ? value.take(128).toList() : const [];
+ final locations = <AgentWorkLocation>[];
+ for (final row in rows(raw['locations'])) {
+ if (row is! Map) continue;
+ final cwd = label(row['cwd']), at = date(row['at']);
+ if (cwd != null && at != null) locations.add((cwd: cwd, at: at));
+ }
+ final history = raw['history'] is Map ? raw['history'] as Map : const {};
+ final branches = <AgentWorkBranch>[];
+ for (final row in rows(history['branches'])) {
+ if (row is! Map) continue;
+ final cwd = label(row['cwd']),
+ branch = label(row['branch'], 256),
+ at = date(row['at']);
+ if (cwd != null && branch != null && at != null) {
+ branches.add((
+ cwd: cwd,
+ branch: branch,
+ remote: label(row['remote']),
+ at: at,
+ ));
+ }
+ }
+ final prs = <AgentWorkPr>[];
+ final seen = <String>{};
+ for (final row in [
+ ...rows(history['pullRequests']),
+ ...rows(raw['pullRequests']),
+ ]) {
+ if (row is! Map) continue;
+ final url = validatedPrUrl(row['url']), at = date(row['at']);
+ if (url == null || at == null || !seen.add(url.toString())) continue;
+ for (final alias in rows(row['aliases'])) {
+ final valid = validatedPrUrl(alias);
+ if (valid != null) seen.add(valid.toString());
+ }
+ final result = row['result'];
+ final state =
+ result is Map &&
+ result['status'] == 'found' &&
+ result['url'] == url.toString() &&
+ const [
+ 'Draft',
+ 'Open',
+ 'Merged',
+ 'Closed',
+ ].contains(result['state'])
+ ? result['state'] as String
+ : null;
+ prs.add((
+ url: url,
+ cwd: label(row['cwd']),
+ at: at,
+ state: state,
+ checkedAt: date(row['checkedAt']),
+ title: result is Map ? label(result['title'], 512) : null,
+ headBranch: result is Map ? label(result['headBranch'], 256) : null,
+ baseBranch: result is Map ? label(result['baseBranch'], 256) : null,
+ ));
+ if (prs.length == 128) break;
+ }
+ final version = raw['version'];
+ return AgentGitContext(
+ state: raw['state'] as String,
+ current: const ['workspace', 'observed'].contains(raw['state'])
+ ? AgentProject.fromJson(raw['current'])
+ : null,
+ observedAt: date(raw['observedAt']),
+ locations: List.unmodifiable(locations),
+ branches: List.unmodifiable(branches),
+ pullRequests: List.unmodifiable(prs),
+ truncated: raw['truncated'] == true || history['truncated'] == true,
+ epoch: version is Map ? label(version['epoch'], 128) : null,
+ revision:
+ version is Map &&
+ version['revision'] is int &&
+ version['revision'] > 0
+ ? version['revision'] as int
+ : 0,
+ );
+ }
+
+ static Uri? validatedPrUrl(Object? value) {
+ if (value is! String ||
+ !RegExp(r'^https://github\.com/[\w-]+/[\w.-]+/pull/[1-9]\d*$')
+ .hasMatch(value)) {
+ return null;
+ }
+ final uri = Uri.tryParse(value);
+ if (uri == null ||
+ uri.toString() != value ||
+ uri.pathSegments.any((part) => part == '.' || part == '..')) {
+ return null;
+ }
+ return uri;
+ }
+}
diff --git a/mobile/lib/core/models.dart b/mobile/lib/core/models.dart
index 69e207111..d6f55dabe 100644
--- a/mobile/lib/core/models.dart
+++ b/mobile/lib/core/models.dart
@@ -2,6 +2,7 @@
library;
import 'agent_output_stats.dart';
+import 'agent_git_context.dart';
enum MachineAuthMode { managed, remote, self, provider }
@@ -190,6 +191,9 @@ class Agent {
final String? dshName;
final String? parentAgentId;
final AgentProject? project;
+ final AgentGitContext? gitContext;
+ AgentProject? get displayProject =>
+ gitContext?.displayProject(project) ?? project;
final String status;
final String launchState;
final String? launchError;
@@ -227,6 +231,7 @@ class Agent {
this.dshName,
this.parentAgentId,
this.project,
+ this.gitContext,
this.status = 'active',
this.launchState = 'ready',
this.launchError,
@@ -287,6 +292,7 @@ class Agent {
dshName: _safeLabel(j['dshName']),
parentAgentId: _safeLabel(j['parentAgentId'] ?? j['parentId']),
project: AgentProject.fromJson(j['project']),
+ gitContext: AgentGitContext.fromJson(j['gitContext']),
status: (j['status'] as String?) ?? 'active',
launchState: launchState,
launchError: launchState == 'failed' ? _safeLabel(launch['error']) : null,
@@ -307,7 +313,7 @@ class Agent {
);
}
- Agent copyWith({String? name}) => Agent(
+ Agent copyWith({String? name, AgentGitContext? gitContext}) => Agent(
id: id,
sessionId: sessionId,
name: name ?? this.name,
@@ -324,6 +330,7 @@ class Agent {
dshName: dshName,
parentAgentId: parentAgentId,
project: project,
+ gitContext: gitContext ?? this.gitContext,
status: status,
launchState: launchState,
launchError: launchError,
@@ -567,6 +574,7 @@ class AgentProject {
this.root,
this.remote,
this.branch,
+ this.worktree = false,
this.branchPending = false,
});
final String name;
@@ -574,6 +582,7 @@ class AgentProject {
final String? root;
final String? remote;
final String? branch;
+ final bool worktree;
/// [branch] is still the name Harness made up at Start; it is shown once the session's name
/// replaces it.
@@ -639,10 +648,11 @@ class AgentProject {
root == other.root &&
remote == other.remote &&
branch == other.branch &&
+ worktree == other.worktree &&
branchPending == other.branchPending;
@override
int get hashCode =>
- Object.hash(name, cwd, root, remote, branch, branchPending);
+ Object.hash(name, cwd, root, remote, branch, worktree, branchPending);
static AgentProject? fromJson(Object? raw) {
if (raw is! Map) return null;
@@ -665,6 +675,7 @@ class AgentProject {
root: field('root'),
remote: field('remote'),
branch: field('branch', 256),
+ worktree: raw['worktree'] == true,
branchPending: raw['branchPending'] == true,
);
}
diff --git a/mobile/lib/phone/phone_search_results.dart b/mobile/lib/phone/phone_search_results.dart
index 9b777aa1a..255f2b87d 100644
--- a/mobile/lib/phone/phone_search_results.dart
+++ b/mobile/lib/phone/phone_search_results.dart
@@ -400,7 +400,7 @@ class PhoneSearchResultsState extends State<PhoneSearchResults> {
final question = entry.machine.blockedAgents[entry.agent.id]?.prompt.trim();
final state = _stateOf(entry, openable, tty, resuming: _resuming == row.id);
final asking = question != null && question.isNotEmpty && entry.isWaiting;
- final branch = entry.agent.project?.branch;
+ final branch = entry.agent.displayProject?.branch;
// Found in what was said rather than in its own name and place: the second line shows where
// — the desktop Cmd-P's rule.
final hit = widget.controller.contentHitFor(row.id);
@@ -420,7 +420,7 @@ class PhoneSearchResultsState extends State<PhoneSearchResults> {
// `M2:site ⑂ docs-v2 · 2m` — or, while it asks, its question.
detail: asking
? '"${question.split('\n').first}"'
- : '${entry.machineName}:${entry.agent.project?.label ?? entry.project?.name ?? ''}',
+ : '${entry.machineName}:${entry.agent.displayProject?.label ?? entry.project?.name ?? ''}',
branch: asking || branch == null || branch.isEmpty ? null : branch,
tail: asking
? null
@@ -474,13 +474,13 @@ class PhoneSearchResultsState extends State<PhoneSearchResults> {
)) {
continue;
}
- final cwd = entry.agent.project?.cwd ?? entry.project?.cwd;
+ final cwd = entry.agent.displayProject?.cwd ?? entry.project?.cwd;
if (cwd == null || cwd.isEmpty) continue;
return (
machineId: entry.machineId,
folder: cwd,
label:
- '${entry.machineName}:${entry.agent.project?.label ?? project.title}',
+ '${entry.machineName}:${entry.agent.displayProject?.label ?? project.title}',
);
}
return null;
diff --git a/mobile/lib/phone/session_work_page.dart b/mobile/lib/phone/session_work_page.dart
new file mode 100644
index 000000000..796033f2d
--- /dev/null
+++ b/mobile/lib/phone/session_work_page.dart
@@ -0,0 +1,262 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:url_launcher/url_launcher.dart';
+
+import '../core/agent_git_context.dart';
+import '../core/models.dart';
+import '../terminal/terminal_font_store.dart';
+import '../terminal/terminal_theme_store.dart';
+import 'tty.dart';
+import 'tty_controls.dart';
+
+class SessionWorkPage extends StatefulWidget {
+ const SessionWorkPage({
+ super.key,
+ required this.agent,
+ required this.read,
+ this.online = true,
+ this.open,
+ });
+ final Agent agent;
+ final Future<Map<String, dynamic>> Function(int offset) read;
+ final bool online;
+ final Future<bool> Function(Uri)? open;
+ @override
+ State<SessionWorkPage> createState() => _SessionWorkPageState();
+}
+
+class _SessionWorkPageState extends State<SessionWorkPage> {
+ AgentGitContext? _data;
+ bool _loading = false;
+ String? _error;
+ int _revision = 0, _visible = 4;
+ final _unavailable = <String>{};
+ @override
+ void initState() {
+ super.initState();
+ _data = widget.agent.gitContext;
+ if (widget.online) unawaited(_refresh(0));
+ }
+
+ @override
+ void dispose() {
+ _revision++;
+ super.dispose();
+ }
+
+ Future<void> _refresh(int offset) async {
+ final revision = ++_revision;
+ setState(() {
+ _loading = true;
+ _error = null;
+ });
+ Map<String, dynamic> result;
+ try {
+ result = await widget.read(offset);
+ } catch (_) {
+ result = {'status': 'unavailable'};
+ }
+ if (!mounted || revision != _revision) return;
+ setState(() {
+ _loading = false;
+ final context = result['gitContext'];
+ if (context is Map && result['history'] is Map) {
+ _data =
+ AgentGitContext.fromJson({
+ ...context,
+ 'history': result['history'],
+ }) ??
+ _data;
+ for (final lookup
+ in result['lookups'] is List
+ ? result['lookups'] as List
+ : const []) {
+ if (lookup is! Map || lookup['url'] is! String) continue;
+ if (lookup['status'] == 'unavailable') {
+ _unavailable.add(lookup['url']);
+ } else {
+ _unavailable.remove(lookup['url']);
+ }
+ }
+ } else {
+ _error = 'Work history is unavailable. Showing saved observations.';
+ }
+ });
+ }
+
+ Future<void> _open(Uri uri) async {
+ bool opened;
+ try {
+ opened =
+ await (widget.open?.call(uri) ??
+ launchUrl(uri, mode: LaunchMode.externalApplication));
+ } catch (_) {
+ opened = false;
+ }
+ if (mounted && !opened) setState(() => _error = 'Could not open GitHub.');
+ }
+
+ @override
+ Widget build(BuildContext context) => ListenableBuilder(
+ listenable: Listenable.merge([terminalFontStore, terminalThemeStore]),
+ builder: (context, _) {
+ final tty = Tty.of(context), data = _data;
+ final current =
+ data?.current ?? (data == null ? widget.agent.project : null);
+ final prs = [...?data?.pullRequests];
+ int rank(AgentWorkPr pr) => switch (pr.state) {
+ 'Open' || 'Draft' => 0,
+ 'Merged' || 'Closed' => 2,
+ _ => 1,
+ };
+ prs.sort((a, 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 text(String value, {bool dim = false}) => SelectableText(
+ value,
+ style: tty.style(color: dim ? tty.faint : tty.text),
+ );
+ Widget action(String label, VoidCallback? pressed, {Key? key}) =>
+ TextButton(
+ key: key,
+ style: TextButton.styleFrom(
+ alignment: Alignment.centerLeft,
+ foregroundColor: tty.text,
+ minimumSize: Size(0, tty.tapRow),
+ padding: EdgeInsets.zero,
+ textStyle: tty.style(),
+ shape: const RoundedRectangleBorder(),
+ splashFactory: NoSplash.splashFactory,
+ ),
+ onPressed: pressed,
+ child: Text(label),
+ );
+ return Scaffold(
+ backgroundColor: tty.ground,
+ body: SafeArea(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Row(
+ children: [
+ TtyBackButton(
+ onPressed: () => Navigator.of(context).maybePop(),
+ ),
+ Expanded(
+ child: TtyText(
+ '${widget.agent.displayName} · Work',
+ size: TtySize.title,
+ ),
+ ),
+ ],
+ ),
+ Expanded(
+ child: ListView(
+ padding: const EdgeInsets.symmetric(horizontal: Tty.origin),
+ children: [
+ text(
+ widget.online
+ ? data?.explanation ?? 'Session workspace'
+ : 'Offline · last known work',
+ dim: true,
+ ),
+ SizedBox(height: tty.row),
+ text(
+ current?.branch ??
+ data?.branchLabel ??
+ 'No branch observed',
+ ),
+ if (current != null)
+ text(current.root ?? current.cwd, dim: true),
+ if (data?.observedAt case final at?)
+ text('Work observed ${localWorkTime(at)}', dim: true),
+ SizedBox(height: tty.row),
+ text('Launch workspace', dim: true),
+ text(widget.agent.project?.cwd ?? 'Unavailable'),
+ SizedBox(height: tty.row),
+ text('Pull requests (${prs.length})'),
+ if (prs.isEmpty)
+ text(
+ 'No pull requests observed for this session.',
+ dim: true,
+ ),
+ for (final pr in prs.take(_visible)) ...[
+ action(
+ '#${pr.url.pathSegments.last} ${pr.state ?? 'State unknown'} ${pr.title ?? pr.url.pathSegments.take(2).join('/')}',
+ () => unawaited(_open(pr.url)),
+ key: ValueKey('work-pr-${pr.url}'),
+ ),
+ if (pr.headBranch case final branch?)
+ text(
+ '${pr.url.pathSegments.take(2).join('/')} · $branch${pr.baseBranch == null ? '' : ' → ${pr.baseBranch}'}',
+ dim: true,
+ ),
+ if (_unavailable.contains(pr.url.toString()))
+ text(
+ 'GitHub unavailable · showing last known state',
+ dim: true,
+ )
+ else if (pr.checkedAt case final at?)
+ text('Checked ${localWorkTime(at)}', dim: true),
+ ],
+ if (prs.length > _visible)
+ action(
+ 'Show more',
+ _loading
+ ? null
+ : () {
+ final offset = _visible;
+ setState(() => _visible += 4);
+ if (widget.online) unawaited(_refresh(offset));
+ },
+ ),
+ SizedBox(height: tty.row),
+ text('Observed branches'),
+ if (data?.branches.isEmpty ?? true)
+ text('No branch history observed yet.', dim: true),
+ for (final branch
+ in data?.branches ?? <AgentWorkBranch>[]) ...[
+ text(
+ '${branch.branch}${branch.cwd == current?.root && branch.branch == current?.branch ? ' · current' : ''}',
+ ),
+ text(branch.cwd, dim: true),
+ SizedBox(height: tty.row),
+ ],
+ if (data?.state == 'multiple' ||
+ data?.state == 'uncertain' ||
+ data?.state == 'unavailable') ...[
+ text('Recent work locations'),
+ for (final location
+ in data?.locations ?? <AgentWorkLocation>[])
+ text(location.cwd, dim: true),
+ ],
+ SizedBox(height: tty.row),
+ text(
+ data?.truncated == true
+ ? 'Older observations are omitted.'
+ : 'History includes observed work; earlier work may be missing.',
+ dim: true,
+ ),
+ if (_error != null) text(_error!),
+ if (widget.online)
+ action(
+ _loading ? 'Refreshing…' : 'Refresh',
+ _loading ? null : () => unawaited(_refresh(0)),
+ ),
+ SizedBox(height: tty.row),
+ ],
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ },
+ );
+}
diff --git a/mobile/lib/phone/terminal_page.dart b/mobile/lib/phone/terminal_page.dart
index 623c3f9e3..e6b373bd8 100644
--- a/mobile/lib/phone/terminal_page.dart
+++ b/mobile/lib/phone/terminal_page.dart
@@ -15,7 +15,8 @@ import 'package:flutter/scheduler.dart';
import 'package:xterm/xterm.dart' show Terminal, TerminalKey, TerminalStyle;
import 'package:harness_mobile/logging/app_log.dart';
-import 'package:harness_mobile/core/models.dart' show Agent, AgentProject;
+import 'package:harness_mobile/core/models.dart'
+ show Agent, AgentProject, ConnectionStatus;
import 'package:harness_mobile/shared/theme/app_theme.dart';
import 'package:harness_mobile/shared/widgets/skeleton.dart';
import 'package:harness_mobile/state/app_state.dart';
@@ -40,6 +41,7 @@ import 'held_height.dart';
import 'phone_sheet.dart';
import 'phone_status.dart';
import 'settings_page.dart';
+import 'session_work_page.dart';
import 'terminal_action_column.dart';
import 'terminal_chrome_scroll.dart';
import 'terminal_header.dart';
@@ -677,7 +679,7 @@ class _TerminalPageState extends State<TerminalPage>
rendered: session?.hasRenderedFrame ?? false,
agentName: agent?.displayName,
agentEngine: agent?.engine,
- agentProject: agent?.project,
+ agentProject: agent?.displayProject,
agentPresent: agent != null,
agentsFromCache: machine?.agentsFromCache ?? true,
agentLoadStatus: machine?.agentLoadStatus,
@@ -905,7 +907,7 @@ class _TerminalPageState extends State<TerminalPage>
/// `machine:folder` for the title — where the agent works.
static String? _placeOf(Agent? agent, MachineState? machine) {
- final folder = agent?.project?.name;
+ final folder = agent?.displayProject?.name;
final name = machine?.machine.displayName;
if (folder == null || folder.isEmpty) return name;
return name == null ? folder : '$name:$folder';
@@ -2096,7 +2098,9 @@ class _TerminalPageState extends State<TerminalPage>
name:
agent?.displayName ?? _cachedAgentName ?? '',
place: _placeOf(agent, machine),
- branch: agent?.project?.branch,
+ branch:
+ agent?.gitContext?.branchLabel ??
+ agent?.displayProject?.branch,
// In the sample the guide line says it, once is enough.
asking: SampleMode.maybeOf(context) != null
? null
@@ -2351,9 +2355,10 @@ class _TerminalPageState extends State<TerminalPage>
// Where it runs, written as everywhere else: `hn` over `M2:autonomous-harness ⑂ main`.
title: [
'$agentName · $machineName',
- if (agent.project?.label case final folder?) ':$folder',
+ if (agent.displayProject?.label case final folder?) ':$folder',
].join(),
- titleBranch: agent.project?.shownBranch,
+ titleBranch:
+ agent.gitContext?.branchLabel ?? agent.displayProject?.shownBranch,
// The agent, then where it runs — the machine, then the folder with its parent beside the
// branch — each behind its icon. The header has no room for the path.
titleParts: [agentName],
@@ -2374,7 +2379,7 @@ class _TerminalPageState extends State<TerminalPage>
),
titleDetail: AgentPlaceLines(
machineName: machineName,
- project: agent.project,
+ project: agent.displayProject,
),
// Three cards: what acts on THIS agent, the screens the app itself has, and — alone at the
// end — the one act that cannot be undone. No caption over the first: the name above it
@@ -2437,6 +2442,28 @@ class _TerminalPageState extends State<TerminalPage>
}
List<PhoneSheetAction> _agentActions(Agent agent) => [
+ PhoneSheetAction(
+ icon: LucideIcons.gitBranch300,
+ label: 'Branches and pull requests',
+ chevron: true,
+ onTap: () => Navigator.of(context).push(
+ phoneRoute(
+ (_) => SessionWorkPage(
+ agent: agent,
+ online:
+ widget.notifier.stateOf(widget.machineId)?.nodeOnline !=
+ false &&
+ widget.notifier.stateOf(widget.machineId)?.connectionStatus ==
+ ConnectionStatus.connected,
+ read: (offset) => widget.notifier.readAgentGitHistory(
+ widget.machineId,
+ agent.id,
+ offset: offset,
+ ),
+ ),
+ ),
+ ),
+ ),
PhoneSheetAction(
icon: LucideIcons.clipboardPaste300,
label: 'Paste from clipboard',
diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dart
index 44c5a6170..de00f2e2a 100644
--- a/mobile/lib/state/app_state.dart
+++ b/mobile/lib/state/app_state.dart
@@ -20,6 +20,7 @@ import '../auth/cli_login.dart';
import '../bootstrap/environment_provisioner.dart';
import '../core/viewer_mode.dart';
import '../core/config.dart';
+import '../core/agent_git_context.dart';
import '../core/agent_preference.dart';
import '../core/engine_availability.dart';
import '../core/device_name.dart';
@@ -271,7 +272,7 @@ class MachineState {
bool get usesLocalTransport => localEndpoint != null;
AgentProject? projectOf(Agent agent) =>
- agent.project ??
+ agent.displayProject ??
localProjects[agent.id] ??
localEndpoint?.agentProjects[agent.id];
@@ -3412,6 +3413,7 @@ class AppNotifier extends ChangeNotifier {
prev.codexHome != agent.codexHome ||
prev.parentAgentId != agent.parentAgentId ||
prev.project != agent.project ||
+ prev.gitContext != agent.gitContext ||
prev.launchState != agent.launchState ||
prev.launchError != agent.launchError ||
prev.launchDetail != agent.launchDetail ||
@@ -4412,6 +4414,11 @@ class AppNotifier extends ChangeNotifier {
}
void _replaceAgents(MachineState machine, List<Agent> agents) {
+ final previousWork = {for (final agent in machine.agents) agent.id: agent};
+ agents = [
+ for (final agent in agents)
+ retainNewerGitContext(agent, previousWork[agent.id]),
+ ];
// Whatever was here before, this list came from the machine itself — see
// [MachineState.agentsFromCache]. Cleared before the loops below, which are
// exactly the code that retires an agent the cache was wrong about.
@@ -4463,6 +4470,7 @@ class AppNotifier extends ChangeNotifier {
void _upsertAgent(MachineState machine, Agent agent) {
final index = machine.agents.indexWhere((item) => item.id == agent.id);
final previous = index == -1 ? null : machine.agents[index];
+ agent = retainNewerGitContext(agent, previous);
if (index == -1) {
machine.agents = [...machine.agents, agent];
} else {
@@ -4946,6 +4954,33 @@ class AppNotifier extends ChangeNotifier {
}
}
+ Future<Map<String, dynamic>> readAgentGitHistory(
+ String machineId,
+ String agentId, {
+ int offset = 0,
+ }) async {
+ final machine = stateOf(machineId), revision = _authRevision;
+ final agent = machine?.agents.where((a) => a.id == agentId).firstOrNull;
+ if (machine == null || agent == null) return {'status': 'unavailable'};
+ try {
+ final result = await _conn(machineId).request(
+ 'git_pull_request',
+ payload: {'agentId': agentId, 'history': true, 'offset': offset},
+ timeout: const Duration(seconds: 45),
+ );
+ if (!_machineWorkCurrent(machine, revision) ||
+ !sameGitConversation(
+ agent,
+ machine.agents.where((a) => a.id == agentId).firstOrNull,
+ )) {
+ return {'status': 'unavailable'};
+ }
+ return result;
+ } catch (_) {
+ return {'status': 'unavailable'};
+ }
+ }
+
Future<Map<String, dynamic>> readGitProject(
String machineId,
String path,
@@ -5295,10 +5330,10 @@ class AppNotifier extends ChangeNotifier {
// Created HERE, so it joins the tab this phone is in — the way an agent
// created in a window joins that window's tab. See [PhoneDesk.adopt] for
// what happens when the phone is in no tab.
- _desk.adopt(
- (machineId: machineId, agentId: agent.id),
- name: agent.displayName,
- );
+ _desk.adopt((
+ machineId: machineId,
+ agentId: agent.id,
+ ), name: agent.displayName);
await assignAgentToPane(
null,
machineId,
@@ -7036,10 +7071,7 @@ class AppNotifier extends ChangeNotifier {
if (!_canAttachPane(pane)) return;
final session = pane.session;
if (session == null) {
- await _attachSession(
- pane,
- takeControl: intent == AttachIntent.person,
- );
+ await _attachSession(pane, takeControl: intent == AttachIntent.person);
} else {
if (intent == AttachIntent.person) session.takeover = true;
await session.reopen();
diff --git a/mobile/test/session_git_context_test.dart b/mobile/test/session_git_context_test.dart
new file mode 100644
index 000000000..0bfede7ad
--- /dev/null
+++ b/mobile/test/session_git_context_test.dart
@@ -0,0 +1,201 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/core/agent_git_context.dart';
+import 'package:harness_mobile/core/models.dart';
+import 'package:harness_mobile/state/app_state.dart';
+
+Map<String, dynamic> gitFixture({
+ String state = 'observed',
+ String branch = 'hn/preview-fix',
+}) => {
+ 'state': state,
+ 'observedAt': '2026-09-27T13:00:00Z',
+ 'current': state == 'observed'
+ ? {
+ 'name': 'app',
+ 'cwd': '/ship-hn',
+ 'root': '/ship-hn',
+ 'remote': 'github.com/acme/app',
+ 'branch': branch,
+ 'worktree': true,
+ }
+ : null,
+ 'locations': [
+ {'cwd': '/ship-hn/tui', 'at': '2026-09-27T13:00:00Z'},
+ ],
+ 'history': {
+ 'branches': [
+ {
+ 'cwd': '/ship-hn',
+ 'remote': 'github.com/acme/app',
+ 'branch': branch,
+ 'at': '2026-09-27T13:00:00Z',
+ },
+ ],
+ 'pullRequests': [
+ {
+ 'url': 'https://github.com/acme/app/pull/12',
+ 'cwd': '/ship-hn',
+ 'at': '2026-09-27T13:00:00Z',
+ 'checkedAt': '2026-09-27T13:01:00Z',
+ 'result': {
+ 'status': 'found',
+ 'url': 'https://github.com/acme/app/pull/12',
+ 'number': 12,
+ 'state': 'Open',
+ },
+ },
+ ],
+ },
+};
+Agent workAgent({Map<String, dynamic>? git}) => Agent.fromJson({
+ 'id': 'hn',
+ 'name': 'hn',
+ 'engine': 'claude',
+ 'project': {
+ 'name': 'app',
+ 'cwd': '/silent-beacon',
+ 'root': '/silent-beacon',
+ 'branch': 'original',
+ },
+ 'gitContext': ?git,
+});
+
+Map<String, dynamic> manyPrFixture() {
+ final git = gitFixture(
+ branch: 'hn/fix-terminal-preview-and-nfc-session-ordering',
+ );
+ final history = git['history'] as Map;
+ history['pullRequests'] = [
+ for (var i = 0; i < 7; i++)
+ {
+ 'url': 'https://github.com/acme/app/pull/${120 + i}',
+ 'cwd': '/ship-hn',
+ 'at': '2026-09-27T13:00:00Z',
+ 'checkedAt': '2026-09-27T13:01:00Z',
+ 'result': {
+ 'status': 'found',
+ 'url': 'https://github.com/acme/app/pull/${120 + i}',
+ 'number': 120 + i,
+ 'state': ['Open', 'Draft', 'Merged', 'Closed'][i % 4],
+ 'title': [
+ 'Preserve complete session previews',
+ 'Keep concurrent NFC sessions in order',
+ 'Resolve earlier transport failures',
+ 'Replace the original UI experiment',
+ ][i % 4],
+ 'headBranch': 'hn/${['preview', 'nfc', 'transport', 'ui'][i % 4]}',
+ 'baseBranch': 'main',
+ },
+ },
+ ];
+ return git;
+}
+
+void main() {
+ test('renamed PR aliases do not duplicate the original creation receipt', () {
+ final git = gitFixture();
+ final row = (git['history']['pullRequests'] as List).single as Map;
+ row['aliases'] = ['https://github.com/acme/old-name/pull/12'];
+ git['pullRequests'] = [
+ {
+ 'url': 'https://github.com/acme/old-name/pull/12',
+ 'cwd': '/ship-hn',
+ 'at': '2026-09-27T13:00:00Z',
+ },
+ ];
+ expect(
+ AgentGitContext.fromJson(git)!.pullRequests.single.url.toString(),
+ 'https://github.com/acme/app/pull/12',
+ );
+ });
+ test(
+ 'older list/push context cannot undo newer work in the same session',
+ () {
+ Agent versioned(int revision, String branch, {String epoch = 'daemon'}) =>
+ workAgent(
+ git: {
+ ...gitFixture(branch: branch),
+ 'version': {'epoch': epoch, 'revision': revision},
+ },
+ );
+ final current = versioned(2, 'new');
+ final stale = versioned(1, 'old');
+ expect(
+ retainNewerGitContext(stale, current).displayProject!.branch,
+ 'new',
+ );
+ expect(
+ retainNewerGitContext(
+ versioned(3, 'newest'),
+ current,
+ ).displayProject!.branch,
+ 'newest',
+ );
+ expect(
+ retainNewerGitContext(
+ versioned(1, 'restart', epoch: 'new-daemon'),
+ current,
+ ).displayProject!.branch,
+ 'restart',
+ );
+ expect(retainNewerGitContext(stale, null).displayProject!.branch, 'old');
+ expect(
+ retainNewerGitContext(workAgent(), current).displayProject!.branch,
+ 'original',
+ );
+ },
+ );
+ test(
+ 'current display changes while launch and copy identity stay intact',
+ () {
+ final agent = workAgent(git: gitFixture());
+ expect(agent.displayProject!.branch, 'hn/preview-fix');
+ expect(agent.project!.branch, 'original');
+ expect(agent.copyWith(name: 'new name').gitContext, agent.gitContext);
+ expect(agent.gitContext!.requestIdentity, {
+ 'cwd': '/ship-hn',
+ 'branch': 'hn/preview-fix',
+ 'remote': 'github.com/acme/app',
+ });
+ expect(
+ AppNotifier.agentsEqual(
+ [agent],
+ [workAgent(git: gitFixture(branch: 'hn/next'))],
+ ),
+ isFalse,
+ );
+ expect(
+ AppNotifier.agentsEqual([agent], [workAgent(git: gitFixture())]),
+ isTrue,
+ );
+ },
+ );
+ test('uncertainty never presents the launch branch as current work', () {
+ for (final state in ['multiple', 'uncertain', 'unavailable']) {
+ final agent = workAgent(git: gitFixture(state: state));
+ expect(agent.displayProject!.shownBranch, isNull);
+ expect(agent.gitContext!.requestIdentity, isNull);
+ expect(agent.gitContext!.branchLabel, isNotNull);
+ }
+ expect(workAgent().displayProject!.branch, 'original');
+ });
+ test(
+ 'saved links are bounded and only validated GitHub PRs become actionable',
+ () {
+ expect(
+ AgentGitContext.fromJson(gitFixture())!.pullRequests.single.state,
+ 'Open',
+ );
+ for (final url in [
+ 'javascript:alert(1)',
+ 'https://evil.example/a/b/pull/1',
+ 'https://github.com/a/../pull/1',
+ 'https://[email protected]/a/b/pull/1',
+ 'https://github.com/a/b/pull/1?x=1',
+ ]) {
+ expect(AgentGitContext.validatedPrUrl(url), isNull);
+ }
+ expect(AgentGitContext.fromJson({'state': 'made-up'}), isNull);
+ },
+ );
+}
diff --git a/mobile/test/session_work_page_test.dart b/mobile/test/session_work_page_test.dart
new file mode 100644
index 000000000..83fc14fc0
--- /dev/null
+++ b/mobile/test/session_work_page_test.dart
@@ -0,0 +1,143 @@
+import 'dart:async';
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/services.dart';
+import 'package:harness_mobile/shared/theme/app_theme.dart' as grid;
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/phone/session_work_page.dart';
+
+import 'session_git_context_test.dart';
+import '../../desktop/test/support/real_fonts.dart';
+
+void main() {
+ setUpAll(() async {
+ await loadRealFonts();
+ await (FontLoader('packages/lucide_icons_flutter/Lucide300')..addFont(
+ rootBundle.load(
+ 'packages/lucide_icons_flutter/assets/build_font/LucideVariable-w300.ttf',
+ ),
+ ))
+ .load();
+ });
+ testWidgets(
+ 'phone shows current work and launch location and opens only the selected PR',
+ (tester) async {
+ final git = gitFixture(), opened = <Uri>[];
+ await tester.pumpWidget(
+ MaterialApp(
+ home: SessionWorkPage(
+ agent: workAgent(git: git),
+ read: (_) async => {'gitContext': git, 'history': git['history']},
+ open: (uri) async {
+ opened.add(uri);
+ return true;
+ },
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(find.text('/silent-beacon'), findsOneWidget);
+ expect(find.text('hn/preview-fix'), findsOneWidget);
+ final pr = find.byKey(
+ const ValueKey('work-pr-https://github.com/acme/app/pull/12'),
+ );
+ await tester.ensureVisible(pr);
+ await tester.tap(pr);
+ await tester.pumpAndSettle();
+ expect(opened, [Uri.parse('https://github.com/acme/app/pull/12')]);
+ expect(tester.takeException(), isNull);
+ },
+ );
+
+ for (final brightness in Brightness.values) {
+ for (final scale in [1.0, 1.6]) {
+ testWidgets('phone work fits ${brightness.name} at $scale text scale', (
+ tester,
+ ) async {
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = const Size(390, 760);
+ addTearDown(tester.view.reset);
+ final previous = grid.AppTheme.brightness.value;
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = previous);
+ 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(scale)),
+ child: child!,
+ ),
+ home: SessionWorkPage(
+ agent: workAgent(git: manyPrFixture()),
+ online: false,
+ read: (_) => throw StateError(
+ 'An offline page must not read the daemon',
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(find.text('Offline · last known work'), findsOneWidget);
+ expect(tester.takeException(), isNull);
+ 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/phone-${brightness.name}-$scale.png')
+ .writeAsBytes(bytes!.buffer.asUint8List());
+ picture.dispose();
+ });
+ }
+ // The footer and remaining history stay reachable at large accessibility sizes.
+ await tester.scrollUntilVisible(
+ find.text('Show more'),
+ 250,
+ scrollable: find.byType(Scrollable).first,
+ );
+ await tester.tap(find.text('Show more'));
+ await tester.pumpAndSettle();
+ await tester.scrollUntilVisible(
+ find.text('Observed branches'),
+ 250,
+ scrollable: find.byType(Scrollable).first,
+ );
+ expect(tester.takeException(), isNull);
+ });
+ }
+ }
+
+ testWidgets('late phone refresh after leaving the page is discarded', (
+ tester,
+ ) async {
+ final reply = Completer<Map<String, dynamic>>();
+ await tester.pumpWidget(
+ MaterialApp(
+ home: SessionWorkPage(
+ agent: workAgent(git: gitFixture()),
+ read: (_) => reply.future,
+ ),
+ ),
+ );
+ await tester.pump();
+ await tester.pumpWidget(const SizedBox());
+ reply.complete({'status': 'unavailable'});
+ await tester.pumpAndSettle();
+ expect(tester.takeException(), isNull);
+ });
+}
diff --git a/mobile/test/session_work_state_test.dart b/mobile/test/session_work_state_test.dart
new file mode 100644
index 000000000..56c8ec670
--- /dev/null
+++ b/mobile/test/session_work_state_test.dart
@@ -0,0 +1,120 @@
+import 'dart:async';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/core/models.dart';
+import 'package:harness_mobile/state/app_state.dart';
+
+import 'session_git_context_test.dart';
+import 'agent_pager_fixture.dart';
+
+class WorkConnection extends PagerConn {
+ final workReplies = <Completer<Map<String, dynamic>>>[];
+ final workRequests = <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_request') {
+ return super.request(type, payload: payload, timeout: timeout);
+ }
+ workRequests.add(payload);
+ final reply = Completer<Map<String, dynamic>>();
+ workReplies.add(reply);
+ return reply.future;
+ }
+}
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+ late WorkConnection connection;
+ late AppNotifier app;
+ setUp(() {
+ connection = WorkConnection();
+ app = pagerApp(connection);
+ app.stateOf('m')!
+ ..agents = [workAgent(git: gitFixture())]
+ ..connectionStatus = ConnectionStatus.connected
+ ..nodeOnline = true;
+ });
+ tearDown(() => app.dispose());
+
+ test('history replies cannot cross conversation replacement or a machine reconnect', () async {
+ for (final replaceMachine in [false, true]) {
+ app.stateOf('m')!.agents = [workAgent(git: gitFixture())];
+ final response = app.readAgentGitHistory('m', 'hn', offset: 4);
+ expect(connection.workRequests.last, {
+ 'agentId': 'hn',
+ 'history': true,
+ 'offset': 4,
+ });
+ if (replaceMachine) {
+ app.machineStates['m'] = MachineState(app.stateOf('m')!.machine)
+ ..agents = [workAgent(git: gitFixture())];
+ } else {
+ app.stateOf('m')!.agents = const [
+ Agent(
+ id: 'hn',
+ name: 'Reused slot',
+ engine: 'codex',
+ sessionId: 'other',
+ ),
+ ];
+ }
+ connection.workReplies.last.complete({
+ 'gitContext': gitFixture(),
+ 'history': gitFixture()['history'],
+ });
+ expect(await response, {'status': 'unavailable'});
+ }
+ });
+
+ test(
+ 'out-of-order push frames preserve new context without mixing machines',
+ () async {
+ Map<String, dynamic> wire(int revision, String branch) => {
+ 'id': 'hn',
+ 'name': 'hn',
+ 'engine': 'claude',
+ 'sessionId': 'conversation',
+ 'terminal': {'available': true},
+ 'project': {
+ 'name': 'app',
+ 'cwd': '/silent-beacon',
+ 'branch': 'original',
+ },
+ 'gitContext': {
+ ...gitFixture(branch: branch),
+ 'version': {'epoch': 'daemon', 'revision': revision},
+ },
+ };
+ final machine = Machine(
+ machineId: 'other',
+ authMode: MachineAuthMode.remote,
+ name: 'Other',
+ );
+ app.machineStates['other'] = MachineState(machine);
+ for (final target in ['m', 'other']) {
+ await app.handleMachineEventForTest(target, {
+ 'type': 'agent_synced',
+ 'payload': {
+ 'agent': wire(
+ target == 'm' ? 2 : 1,
+ target == 'm' ? 'new' : 'other-work',
+ ),
+ },
+ });
+ }
+ await app.handleMachineEventForTest('m', {
+ 'type': 'agent_synced',
+ 'payload': {'agent': wire(1, 'old')},
+ });
+ expect(app.stateOf('m')!.agents.single.displayProject!.branch, 'new');
+ expect(
+ app.stateOf('other')!.agents.single.displayProject!.branch,
+ 'other-work',
+ );
+ },
+ );
+}