The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Fix stale Working status and align Harness opening shortcuts (#536)
Deeaedd3b5c415e
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex 51772606e..1e0fdf21f 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -1,3 +1,4 @@+import type { ActivityFrame } from './lib/turnActivity.js'import { readSessionGitPullRequest } from './lib/sessionGitPullRequest.js'import type { HarnessShareOwner } from './sharing/owner.js'import { SHARE_REQUEST_TYPES } from './sharing/protocol.js'@@ -549,6 +550,7 @@ export class BackendSocket {harnessSharing: HarnessShareOwner | null = null/** Answers the trust group's roster exchange (`group_sync`); null until the daemon wires it. */groupSync: { handle: (peerPub: string, payload: Record<string, unknown>) => Record<string, unknown> } | null = null+ activityFrameProvider: ((session: RegisteredSession) => ActivityFrame | null) | null = nulldshFrameProvider: ((session: RegisteredSession) => AgentDshContext | null) | null = nullviewerTargetProvider: ((agentId: string) => string | null) | null = nullreadonly interactiveViewers = new InteractiveViewers(agentId => this.viewerTargetProvider?.(agentId) ?? null)@@ -3395,6 +3397,7 @@ export class BackendSocket {selectedModel: this.runtimeProfileProvider?.(s) ?? null,terminalAvailable: registry.terminalAvailable(s.agentId),dsh: this.dshFrameProvider?.(s) ?? null,+ activity: () => this.activityFrameProvider?.(s) ?? null,})}}diff --git a/cli/src/cable/terminalActivity.ts b/cli/src/cable/terminalActivity.tsindex 18d9f4f6d..5745860ea 100644--- a/cli/src/cable/terminalActivity.ts+++ b/cli/src/cable/terminalActivity.ts@@ -1,5 +1,11 @@/** Read only an engine's live footer. No generated status words or transcript inference. */export function terminalActivity(engine: string, screen: string | null): string | null {+ return terminalActivityReading(engine, screen)?.label ?? null+}++/** Keep the live indicator as well as its label: successive changes to its+ * timer/spinner prove the UI is alive; an abandoned static screen does not. */+export function terminalActivityReading(engine: string, screen: string | null): { label: string; indicator: string } | null {if (!screen || (engine !== 'claude' && engine !== 'codex')) return nullconst lines = screen.replace(/\x1b\][^\x07]*(?:\x07|\x1b\\)/g, '').replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, '').split(/\r?\n/)@@ -21,7 +27,7 @@ export function terminalActivity(engine: string, screen: string | null): stringconst match = engine === 'codex'? /^[•◦⠁-⣿]\s+(.{1,60}?)\s+\([^\n]*\besc to interrupt\b[^\n]*\)\s*$/i.exec(line): /^[✢✳✶✻✽·*]\s+([\p{L}][\p{L}\p{N} '\u2019-]{0,55}(?:…|\.{3}))(?:\s+\([^\n]*\))?\s*$/u.exec(line)- if (match) return match[1].trim().replace(/…/g, '...')+ if (match) return { label: match[1].trim().replace(/…/g, '...'), indicator: line }}return null}diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex b462133fa..b12b3fccc 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -258,6 +258,8 @@ import { startTuiUpdater } from './tui/update.js'import { ensureHnLauncher, ensureLauncher, ensureManagedGrid, ensureManagedRuntime, startGridPinRecheck } from './lib/runtimeInstall.js'import { readdir, stat } from 'fs/promises'import { CodexNormalizer, codexTaskError, lastCodexTurnText } from './engines/codex/normalizer.js'+import { TurnActivity, type ActivityFrame } from './lib/turnActivity.js'+import { CodexActivityReader, RuntimeActivityReader, activityRuntimeKey } from './lib/runtimeActivity.js'import { codexSubagentResolverFor } from './engines/codex/subagent.js'import { CursorNormalizer, lastCursorTurnText } from './engines/cursor/normalizer.js'import { CursorTranscriptDiscovery, findCursorTranscript } from './engines/cursor/discovery.js'@@ -1579,6 +1581,7 @@ function mergedLaunchEnv(}/** Set by runForeground once the DSH companions exist; a frame projected before that carries none. */+let activityFrameContextRef: ((s: RegisteredSession) => ActivityFrame | null) | null = nulllet dshFrameContextRef: ((s: RegisteredSession) => AgentDshContext | null) | null = nullfunction projectFrame(s: RegisteredSession, selectedModel: string | null): Promise<AgentFrame> {@@ -1587,6 +1590,7 @@ function projectFrame(s: RegisteredSession, selectedModel: string | null): PromiselectedModel,terminalAvailable: registry.terminalAvailable(s.agentId),dsh: dshFrameContextRef?.(s) ?? null,+ activity: () => activityFrameContextRef?.(s) ?? null,})}@@ -2412,6 +2416,28 @@ async function runForeground(session: AuthSession | null): Promise<void> {?? commandcodeNormalizers.get(sessionId)?.turnOpenconst sessionTurnOpen = (sessionId: string): boolean => sessionTurnState(sessionId) ?? falseconst watcher = new Watcher()+ const codexActivity = new CodexActivityReader()+ const runtimeActivity = new RuntimeActivityReader({+ codex: session => codexActivity.read(session),+ capture: async session => {+ const screen = await terminals.capture(session, { mode: 'visible', ansi: true })+ return screen.state === 'succeeded' ? screen.value : null+ },+ })+ const turnActivity = new TurnActivity({+ runtime: sessionId => {+ const session = registry.bySession(sessionId)+ return session?.active ? { key: activityRuntimeKey(session), turnOpen: sessionTurnOpen(sessionId) } : undefined+ },+ drain: sessionId => watcher.pollSession(sessionId),+ probe: async sessionId => {+ const session = registry.bySession(sessionId)+ return session?.active ? runtimeActivity.read(session) : 'unknown'+ },+ })+ activityFrameContextRef = session => isTerminalEngine(session.engine) ? null : turnActivity.snapshot(session.sessionId) ?? null+ backend.activityFrameProvider = activityFrameContextRef+const queuedSessionEvents: Array<{sessionId: stringevents: ReturnType<CursorNormalizer['ingest']>@@ -3005,6 +3031,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {const mirror = new CommanderMirror({notifications: agentNotifications,notifyWithoutDevice: true,+ verifiedWorking: sessionId => turnActivity.snapshot(sessionId)?.state === 'working',send: (frame) => backend.sendCommander(frame),sendWeb: (frame) => backend.send(frame), // turn_summary_pending / turn_summary → web indicatorhasDevice: () => deviceIsWatching(), // device-gate the LLM recap (mirror node)@@ -3177,51 +3204,34 @@ async function runForeground(session: AuthSession | null): Promise<void> {companionProfileChanged()}- // Turn heartbeat (5s): pushes `turn_heartbeat` to the web while the turn is open (keeps its 10s- // turn-watchdog armed through a quiet stretch — a long tool, thinking with no new JSONL line), AND fans a- // busy heartbeat to the device via mirror.heartbeat() so the device's busy tile stays fresh. Unlike the- // web send, the device fan-out spans the WHOLE busy window — the turn AND the trailing summarize (up to- // the 60s one-shot timeout) — because the device clears busy only on a live terminal and has a- // busy-timeout watchdog that would otherwise cut a long "Summarizing…". So the timer self-cancels only- // once BOTH the turn is closed and mirror.heartbeat() reports idle (turn done + summary done). Mirrors the- // the hosted runtime brain (TURN_HEARTBEAT_MS=5000), per-session, one timer per session.+ // A timer is an opportunity to inspect work, not proof that work is happening.+ // Keep polling unfinished transcripts even when their activity lease expires:+ // a missed file notification or a later completion must still be discovered.const TURN_HEARTBEAT_MS = 5000const heartbeats = new Map<string, NodeJS.Timeout>()- const turnStartedAt = new Map<string, number>() // sessionId → turn_started wall clock, for [turn] duration+ const turnStartedAt = new Map<string, number>()const stopHeartbeat = (sessionId: string): void => {- const t = heartbeats.get(sessionId)- if (t) { clearInterval(t); heartbeats.delete(sessionId) }+ runtimeActivity.forget(sessionId)+ const timer = heartbeats.get(sessionId)+ if (timer) { clearInterval(timer); heartbeats.delete(sessionId) }}const startHeartbeat = (sessionId: string): void => {- stopHeartbeat(sessionId) // restart → guarantee a single timer per session- const timer = setInterval(() => {- if (!registry.has(sessionId)) { stopHeartbeat(sessionId); return }- const turnOpen = sessionTurnOpen(sessionId)- // A TURN THAT IS OPEN GETS ITS TRANSCRIPT RE-READ, every beat.- //- // The engines whose turn ends in a FILE — codex writes `task_complete`,- // and the other JSONL readers are the same shape — depend on chokidar- // delivering that last write. MEASURED twice, on two sessions an hour- // apart: it did not. Codex finished at 15:31:38 and the turn closed at- // 15:35:29, to the second, because the only thing that noticed was the- // five-minute reconciliation sweep. The web client never saw it because- // it renders the terminal stream; the device waits on `turn_ended` for- // its recap, so it sat spinning for 3m51s on a question answered in 18s.- //- // Reading to EOF here costs one stat and a short read of a file that is- // already open, and it bounds that failure at one heartbeat instead of- // at whatever is left of a five-minute window.- if (turnOpen) void watcher.pollSession(sessionId)- // Device: keep the busy tile alive through the turn AND the summarize window. Returns false when idle.- const deviceBusy = mirror.heartbeat(sessionId)- // Web: unchanged — heartbeat only while the turn itself is open (summarizing uses turn_summary_pending).- if (turnOpen) {- const agentId = agentIdFor(sessionId)- backend.send(turnHeartbeatFrame(sessionId, agentId))+ stopHeartbeat(sessionId)+ const beat = async () => {+ if (!registry.bySession(sessionId)?.active) {+ stopHeartbeat(sessionId); turnActivity.forget(sessionId); return}- // Self-cancel only once the turn is closed AND the summarize is done (no more device heartbeat needed).- if (!turnOpen && !deviceBusy) stopHeartbeat(sessionId)- }, TURN_HEARTBEAT_MS)+ if (sessionTurnOpen(sessionId)) await turnActivity.check(sessionId)+ if (!heartbeats.has(sessionId)) return+ const activity = turnActivity.snapshot(sessionId)+ if (activity) {+ backend.send(correlateAgentEvent({ type: 'agent_activity', payload: { activity } }, sessionId, agentIdFor(sessionId)))+ if (activity.state === 'working') backend.send(turnHeartbeatFrame(sessionId, agentIdFor(sessionId), activity))+ }+ const deviceBusy = mirror.heartbeat(sessionId)+ if (!sessionTurnOpen(sessionId) && !deviceBusy) stopHeartbeat(sessionId)+ }+ const timer = setInterval(() => { void beat().catch(error => console.error('[activity] probe failed:', String(error))) }, TURN_HEARTBEAT_MS)heartbeats.set(sessionId, timer)}@@ -3266,13 +3276,15 @@ async function runForeground(session: AuthSession | null): Promise<void> {if (usageSession?.engine === 'opencode') agentTokenUsage.changed(usageSession)for (const [eventIndex, event] of events.entries()) {const agentId = agentIdFor(sessionId)- const frame = correlateAgentEvent(event, sessionId, agentId)+ const replay = !!(opts?.resumed || opts?.replay)+ turnActivity.observe(sessionId, event.type, replay)+ const frame = correlateAgentEvent({ ...event, payload: { ...event.payload, activity: turnActivity.snapshot(sessionId) } }, sessionId, agentId)// A `turn_started` that is not a turn starting NOW — a turn picked back up at attach, or a prompt// re-read from a transcript that was already on disk — says so in the clear, beside `agentId`// (the payload is E2EE; the backend can only read the envelope). The backend's daily turn count// skips these; every other consumer ignores an unknown field. Measured before this existed: one// agent credited with 42 turns in a single second, all re-reads.- if (event.type === 'turn_started' && (opts?.resumed || opts?.replay)) frame.replay = true+ if (replay) { frame.replay = true; frame.payload.replay = true }// The end of a turn carries the two facts an app needs to decide whether it is NEWS, in the clear// beside `agentId` for the same reason `replay` is — the payload is E2EE and the apps read this// without opening it:@@ -5570,11 +5582,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {console.error(`[cli] line handler error (session ${evt.sessionId}):`, err instanceof Error ? err.message : err)}})- // Lines that were on disk before the tail began (watcher.ts `HistoryEvent`). They still stream — the- // clients render them the way they always have — but every `turn_started` among them is a prompt- // already answered, except the last one if the batch ends inside a turn: that turn is running now,- // and it is the one an `unseen` re-attach exists to catch (its first prompt landed before the path- // was known). Everything else is marked `replay` so the backend does not count it as a turn today.+ // A transcript catch-up is history, including an unfinished last turn.+ // Its content still streams, but only fresh events or live inspection can+ // establish Working; replay cannot create a new completion notification.watcher.on('history', (batch: HistoryEvent) => {try {type Events = ReturnType<CursorNormalizer['ingest']>@@ -5584,18 +5594,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {if (events) all.push(...events)}if (!all.length) return- const liveTail = sessionTurnOpen(batch.sessionId)- ? all.map((e) => e.type).lastIndexOf('turn_started')- : -1- const starts = all.filter((e, i) => e.type === 'turn_started' && i !== liveTail).length- if (starts) console.log(`[watcher] ${sid(batch.sessionId)} re-read ${batch.lines.length} lines already on disk · ${starts} past turn_started marked replay${liveTail >= 0 ? ' · last turn still open, kept live' : ''}`)- // Order is preserved: the live tail (if any) is emitted in place, between what surrounds it.- if (liveTail < 0) { emitSessionEvents(batch.sessionId, all, { replay: true }); return }- const before = all.slice(0, liveTail)- const after = all.slice(liveTail + 1)- if (before.length) emitSessionEvents(batch.sessionId, before, { replay: true })- emitSessionEvents(batch.sessionId, [all[liveTail]])- if (after.length) emitSessionEvents(batch.sessionId, after, { replay: true })+ // Every line in this batch was already on disk. An unclosed last turn+ // is not a fresh prompt; live runtime inspection can establish activity.+ emitSessionEvents(batch.sessionId, all, { replay: true })} catch (err) {console.error(`[cli] history handler error (session ${batch.sessionId}):`, err instanceof Error ? err.message : err)}@@ -7051,6 +7052,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {await localWsServer.close()hookServer.close()await localSocket?.close()+ codexActivity.close()shutdownSummaryPool()shutdownVoiceRouter()// The new daemon starts its own viewers for the agents it restores; ours must not hold the ports.@@ -7159,6 +7161,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {await localWsServer.close()hookServer.close()await localSocket?.close()+ codexActivity.close()shutdownSummaryPool()shutdownVoiceRouter()await dshViewers.stopAll()diff --git a/cli/src/lib/agentEvent.ts b/cli/src/lib/agentEvent.tsindex c64c57b9e..92ab46d51 100644--- a/cli/src/lib/agentEvent.ts+++ b/cli/src/lib/agentEvent.ts@@ -1,3 +1,4 @@+import type { ActivityFrame } from './turnActivity.js'export interface AgentEvent extends Record<string, unknown> {type: stringpayload: Record<string, unknown>@@ -20,6 +21,7 @@ export function correlateAgentEvent(export function turnHeartbeatFrame(sessionId: string,agentId: string,+ activity?: ActivityFrame,): AgentEvent & { agentId: string; dbSessionId: string } {- return correlateAgentEvent({ type: 'turn_heartbeat', payload: {} }, sessionId, agentId)+ return correlateAgentEvent({ type: 'turn_heartbeat', payload: activity ? { activity } : {} }, sessionId, agentId)}diff --git a/cli/src/lib/agentFrame.ts b/cli/src/lib/agentFrame.tsindex 737b3a93d..ce03ec2dd 100644--- a/cli/src/lib/agentFrame.ts+++ b/cli/src/lib/agentFrame.ts@@ -1,3 +1,4 @@+import type { ActivityFrame } from './turnActivity.js'/*** The one shape an agent takes on the wire.*@@ -59,6 +60,7 @@ export type AgentFrame = {*/title: string | nullstatus: string+ activity: ActivityFrame | nullclosePlan: { state: 'waiting' | 'failed'; detail?: string } | nullcloseSupported: booleanlaunch: NonNullable<RegisteredSession['launch']>@@ -134,6 +136,8 @@ export interface AgentDshContext {/** What the caller knows and this module deliberately does not look up for itself. */export interface AgentFrameContext {+ /** Evaluated after asynchronous projection, so old snapshots cannot revive work. */+ activity?: () => ActivityFrame | null/** The runtime profile's answer for this session, or null when there is none. */selectedModel: string | null/** `registry.terminalAvailable(agentId)` — the caller already holds the registry. */@@ -181,7 +185,7 @@ const gitContexts = new SessionGitContextReader()export async function agentFrame(s: RegisteredSession,- { selectedModel, terminalAvailable, dsh, tokenUsage }: AgentFrameContext,+ { selectedModel, terminalAvailable, dsh, tokenUsage, activity: contextActivity }: 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 () => {@@ -198,6 +202,7 @@ export async function agentFrame(name: projectDisplayName(s),title: frameTitle(s),status: s.active ? 'active' : 'offline',+ activity: contextActivity?.() ?? null,closePlan: s.closePlan ? { state: s.closePlan.state, ...(s.closePlan.detail ? { detail: s.closePlan.detail } : {}) } : null,closeSupported: true,launch: s.launch ?? { state: 'ready' },diff --git a/cli/src/lib/codexTurnRecovery.spec.ts b/cli/src/lib/codexTurnRecovery.spec.tsnew file mode 100644index 000000000..4fcc51359--- /dev/null+++ b/cli/src/lib/codexTurnRecovery.spec.ts@@ -0,0 +1,29 @@+import { describe, expect, it } from 'vitest'+import { codexStoppedGoal } from './codexTurnRecovery.js'++// The live footer from the interrupted cmd p session on M2. Its rollout ended+// with token_count and thread_settings_applied, never task_complete/turn_aborted.+const screen = [+ '■ Conversation interrupted - use /feedback if something went wrong',+ ' ↳ Recap: Previous work is saved.', '',+ '\x1b[1m\x1b[38;5;215m›\x1b[0m \x1b[2mAsk Codex to do anything\x1b[0m', '',+ ' \x1b[38;5;223mGPT-6-Astra max\x1b[39m · ~/work \x1b[38;5;5mGoal stalled (/goal resume)\x1b[39m',+ ' \x1b[1m?\x1b[0m for shortcuts ⚠ 1 warning · f2 to view',+].join('\n')+describe('Codex stopped-goal footer', () => {+ it('recognizes the live interrupted goal and its paused equivalent', () => {+ expect(codexStoppedGoal(screen)).toBe(true)+ expect(codexStoppedGoal(screen.replace('stalled', 'paused'))).toBe(true)+ })+ it.each([+ null, '', screen.replace('Goal stalled (/goal resume)', 'Goal active'),+ screen.replace('Goal stalled (/goal resume)', ''),+ screen.replace('\x1b[2mAsk Codex to do anything\x1b[0m', 'please continue'),+ screen + '\nSelect Model and Effort',+ screen.replace('■ Conversation interrupted', '• Working (1h · esc to interrupt)\n■ Conversation interrupted'),+ 'Goal stalled (/goal resume)\n› \x1b[2mAsk Codex to do anything\x1b[0m\n? for shortcuts',+ screen.replace('?\x1b[0m for shortcuts', '?\x1b[0m something else'),+ ])('does not treat active, unknown, historical or draft UI as stopped', value => {+ expect(codexStoppedGoal(value)).toBe(false)+ })+})diff --git a/cli/src/lib/codexTurnRecovery.ts b/cli/src/lib/codexTurnRecovery.tsnew file mode 100644index 000000000..89d208fae--- /dev/null+++ b/cli/src/lib/codexTurnRecovery.ts@@ -0,0 +1,20 @@+/** Some Codex goal interruptions never write task_complete/turn_aborted to the+ * rollout. An open transcript is then only historical evidence of work. The+ * live footer is one positive idle reading, never a synthetic turn end. */+import { stripVTControlCharacters } from 'node:util'+import { inspectRuntimePane } from './runtimeProfileController.js'++/** Read only the UI below the current empty composer, never output/history.+ * An empty composer alone says nothing: Codex accepts drafts while working. */+export function codexStoppedGoal(screen: string | null): boolean {+ if (!screen || !inspectRuntimePane('codex', screen).idle) return false+ const lines = stripVTControlCharacters(screen).split(/\r?\n/)+ const prompt = lines.findLastIndex(line => /^\s*›(?:\s|$)/u.test(line))+ if (prompt < 0) return false+ // A live turn can still display the previous goal state during a redraw.+ if (lines.slice(-16).some(line => /\besc to interrupt\b/i.test(line))) return false+ const footer = lines.slice(prompt + 1).filter(line => line.trim())+ return footer.length <= 4+ && footer.some(line => /\bGoal (?:stalled|paused) \(\/goal resume\)\s*$/.test(line))+ && footer.some(line => /\? for shortcuts\b/.test(line))+}diff --git a/cli/src/lib/commander.spec.ts b/cli/src/lib/commander.spec.tsindex 1c18144c7..8ee1739a4 100644--- a/cli/src/lib/commander.spec.ts+++ b/cli/src/lib/commander.spec.ts@@ -509,6 +509,23 @@ describe('CommanderMirror recap events', () => {])})+ it('withdraws unverified busy heartbeats without reporting a completed turn', () => {+ const frames: CommanderFrame[] = []+ let verified = false+ const mirror = new CommanderMirror({ send: frame => frames.push(frame), sendWeb: () => {},+ hasDevice: () => true, summarize: async () => null, dataDir,+ verifiedWorking: () => verified })+ mirror.ingest([{ type: 'turn_started', payload: { userMessage: 'old unfinished turn' } }] as LiveEvent[], 'stale')+ frames.length = 0+ expect(mirror.heartbeat('stale')).toBe(true)+ mirror.replayAll()+ expect(frames).toEqual([])+ expect(mirror.isBusy('stale')).toBe(true)+ verified = true+ mirror.heartbeat('stale')+ expect(frames[0].payload.kind).toBe('processing')+ })+it('heartbeat re-emits processing while a turn is open, nothing when idle', () => {const deviceFrames: CommanderFrame[] = []const mirror = new CommanderMirror({diff --git a/cli/src/lib/commander.ts b/cli/src/lib/commander.tsindex 77d8a8be5..7704edd9a 100644--- a/cli/src/lib/commander.ts+++ b/cli/src/lib/commander.ts@@ -32,6 +32,8 @@ export type CommanderFrame = {}export interface CommanderMirrorOpts {+ /** Presentation lease only. Unverified work stays open for its real completion. */+ verifiedWorking?: (sessionId: string) => boolean/** Shared with QuestionWatcher; both screens receive this policy's decision. */notifications?: AgentNotifications/** Produce desktop results without a device, using a free local excerpt. */@@ -824,6 +826,7 @@ export class CommanderMirror {const st = this.states.get(sessionId)if (!st) return falseif (st.turnOpen) {+ if (this.opts.verifiedWorking?.(sessionId) === false) return truethis.emit(sessionId, st.lastTodos? { kind: 'processing', text: 'Processing', todos: st.lastTodos }: { kind: 'processing', text: 'Processing' })diff --git a/cli/src/lib/runtimeActivity.spec.ts b/cli/src/lib/runtimeActivity.spec.tsnew file mode 100644index 000000000..a684dc912--- /dev/null+++ b/cli/src/lib/runtimeActivity.spec.ts@@ -0,0 +1,81 @@+import { afterEach, describe, expect, it, vi } from 'vitest'+import { CodexActivityReader, RuntimeActivityReader } from './runtimeActivity.js'+import { registry, type RegisteredSession } from './registry.js'++function session(): RegisteredSession {+ const row = registry.openPendingAgent({ engine: 'codex', runtimes: [{ backend: 'tmux', paneId: '%600' }], cwd: '/tmp', codexHome: '/tmp/activity-fixture' })!+ Object.assign(row, { sessionId: 'conversation', processIdentity: { pid: 78, startMarker: 'start', executable: 'codex' } })+ return row+}+afterEach(() => { for (const row of registry.list()) registry.removeAgent(row.agentId) })+function control() {+ let now = 1000+ const row = session()+ const request = vi.fn(async (_method: string, _params: Record<string, unknown>): Promise<any> => ({ thread: { id: row.sessionId, status: { type: 'active' } } }))+ const close = vi.fn()+ const rows = vi.fn(async () => [{ ...row.processIdentity!, parentPid: 1, args: 'codex resume conversation' }])+ const connect = vi.fn(async () => ({ request, close }))+ const reader = new CodexActivityReader({ connect, rows, now: () => now })+ return { reader, row, request, close, rows, connect, advance: () => { now += 60_001 } }+}+describe('Codex activity RPC', () => {+ it.each([['active', 'working'], ['idle', 'idle'], ['notLoaded', 'unknown'], ['systemError', 'unknown']])(+ 'reads %s without mutating or resuming the conversation', async (state, expected) => {+ const t = control(); t.request.mockResolvedValue({ thread: { id: t.row.sessionId, status: { type: state } } })+ expect(await t.reader.read(t.row)).toBe(expected)+ expect(t.request.mock.calls).toEqual([['thread/read', { threadId: t.row.sessionId }]])+ t.reader.close(); await Promise.resolve(); expect(t.close).toHaveBeenCalledOnce()+ })+ it.each(['--no-daemon', '--remote=ws://example.invalid'])('does not query the wrong server for %s', async option => {+ const t = control(); t.rows.mockResolvedValue([{ ...t.row.processIdentity!, parentPid: 1, args: `codex ${option} resume conversation` }])+ expect(await t.reader.read(t.row)).toBe('unknown'); expect(t.connect).not.toHaveBeenCalled()+ })+ it('rejects PID reuse and a different thread', async () => {+ const t = control(); t.rows.mockResolvedValueOnce([{ ...t.row.processIdentity!, startMarker: 'different', parentPid: 1, args: 'codex' }])+ expect(await t.reader.read(t.row)).toBe('unknown'); expect(t.connect).not.toHaveBeenCalled()+ t.advance(); t.request.mockResolvedValue({ thread: { id: 'other', status: { type: 'active' } } })+ expect(await t.reader.read(t.row)).toBe('unknown'); t.reader.close()+ })+ it('shares connections and backs off unavailable servers', async () => {+ const t = control()+ await Promise.all([t.reader.read(t.row), t.reader.read(t.row)])+ expect(t.connect).toHaveBeenCalledOnce(); expect(t.rows).toHaveBeenCalledOnce()+ t.request.mockRejectedValueOnce(new Error('socket hangup'))+ expect(await t.reader.read(t.row)).toBe('unknown')+ expect(await t.reader.read(t.row)).toBe('unknown'); expect(t.connect).toHaveBeenCalledOnce()+ t.advance(); expect(await t.reader.read(t.row)).toBe('working'); expect(t.connect).toHaveBeenCalledTimes(2)+ t.reader.close()+ })+})+describe('live terminal fallback', () => {+ it('requires changing busy indicators and refuses a frozen footer or prose', async () => {+ const row = session()+ const capture = vi.fn(async () => '• Working (30s · esc to interrupt)\n› \x1b[2mAsk Codex to do anything\x1b[0m\n? for shortcuts')+ const reader = new RuntimeActivityReader({ codex: async () => 'unknown', capture })+ expect(await reader.read(row)).toBe('unknown')+ expect(await reader.read(row)).toBe('unknown')+ capture.mockResolvedValue('• Working (35s · esc to interrupt)\n› \x1b[2mAsk Codex to do anything\x1b[0m\n? for shortcuts')+ expect(await reader.read(row)).toBe('working')+ capture.mockResolvedValue('The answer says Working (40s · esc to interrupt).')+ expect(await reader.read(row)).toBe('unknown')+ })+ it('recognizes the actual cmd p stopped goal without requiring or generating a transcript end', async () => {+ const row = session()+ const capture = vi.fn(async () => '■ Conversation interrupted\n› \x1b[2mAsk Codex to do anything\x1b[0m\n GPT-6-Astra max · ~/work Goal stalled (/goal resume)\n? for shortcuts')+ const reader = new RuntimeActivityReader({ codex: async () => 'unknown', capture })+ expect(await reader.read(row)).toBe('unknown')+ expect(await reader.read(row)).toBe('idle')+ row.processIdentity = { ...row.processIdentity!, startMarker: 'replacement' }+ expect(await reader.read(row)).toBe('unknown')+ capture.mockResolvedValue('› draft text\nGoal stalled (/goal resume)\n? for shortcuts')+ expect(await reader.read(row)).toBe('unknown')+ })+ it('prefers structured status and leaves unsupported engines unknown', async () => {+ const row = session(); const capture = vi.fn(async () => null)+ const codex = vi.fn(async () => 'working' as const)+ const reader = new RuntimeActivityReader({ codex, capture })+ expect(await reader.read(row)).toBe('working'); expect(capture).not.toHaveBeenCalled()+ const unsupported = new RuntimeActivityReader({ codex: async () => 'unknown', capture })+ row.engine = 'pi'; expect(await unsupported.read(row)).toBe('unknown'); expect(capture).not.toHaveBeenCalled()+ })+})diff --git a/cli/src/lib/runtimeActivity.ts b/cli/src/lib/runtimeActivity.tsnew file mode 100644index 000000000..88be5ebc1--- /dev/null+++ b/cli/src/lib/runtimeActivity.ts@@ -0,0 +1,84 @@+import { basename } from 'node:path'+import { env } from '../config/env.js'+import { terminalActivityReading } from '../cable/terminalActivity.js'+import { connectCodexControl, type CodexControl } from './codexSessionLifecycle.js'+import { codexStoppedGoal } from './codexTurnRecovery.js'+import { argvTokens, processRows, type ProcessRow } from './tmux.js'+import type { RegisteredSession } from './registry.js'+import type { ActivityState } from './turnActivity.js'++export function activityRuntimeKey(session: RegisteredSession): string {+ return JSON.stringify([session.agentId, session.sessionId, session.primaryRuntimeKey, session.processIdentity])+}++/** Read-only connections, shared by profile. Never launch/resume a thread or+ * start an app-server to inspect it. An unrelated server's notLoaded is unknown. */+export class CodexActivityReader {+ private readonly controls = new Map<string, Promise<CodexControl>>()+ private readonly retryAt = new Map<string, number>()+ private rowsAt = -Infinity+ private rows?: Promise<ProcessRow[] | null>+ constructor(private readonly deps = { connect: connectCodexControl, rows: processRows, now: () => performance.now() }) {}+ async read(session: RegisteredSession): Promise<ActivityState> {+ if (session.engine !== 'codex' || !session.processIdentity) return 'unknown'+ const home = session.codexHome || env.CODEX_HOME+ if ((this.retryAt.get(home) ?? 0) > this.deps.now()) return 'unknown'+ if (!this.rows || this.deps.now() - this.rowsAt > 2_000) {+ this.rowsAt = this.deps.now(); this.rows = this.deps.rows()+ }+ const rows = await this.rows+ const owner = rows?.find(row => row.pid === session.processIdentity!.pid+ && row.startMarker === session.processIdentity!.startMarker && row.executable === session.processIdentity!.executable)+ if (!owner) return 'unknown'+ const args = argvTokens(owner.args)+ const option = /^node(?:\.exe)?$/.test(basename(args[0] ?? '')) && /(?:^|\/)codex(?:\.js)?$/.test(args[1] ?? '') ? 2 : 1+ if (args[option] === '--no-daemon' || args.slice(option).some(arg => arg === '--remote' || arg.startsWith('--remote='))) return 'unknown'+ let connection = this.controls.get(home)+ if (!connection) { connection = this.deps.connect(home); this.controls.set(home, connection) }+ try {+ const control = await connection+ const read = await control.request('thread/read', { threadId: session.sessionId })+ if (read?.thread?.id !== session.sessionId) return 'unknown'+ if (read.thread.status?.type === 'active') return 'working'+ if (read.thread.status?.type === 'idle') return 'idle'+ return 'unknown'+ } catch {+ // An old/process-owned engine may share its profile with another server.+ // Do not keep spawning a failed proxy for every session every five seconds.+ if (this.controls.get(home) === connection) this.controls.delete(home)+ void connection.then(control => control.close()).catch(() => {})+ this.retryAt.set(home, this.deps.now() + 60_000)+ return 'unknown'+ }+ }+ close(): void {+ for (const control of this.controls.values()) void control.then(value => value.close()).catch(() => {})+ this.controls.clear()+ }+}++/** A positive, changing live busy indicator can confirm an otherwise quiet+ * process-owned engine. Missing/unrecognized UI is always unknown. */+export class RuntimeActivityReader {+ private readonly footers = new Map<string, { runtime: string; indicator: string | null; stopped: boolean }>()+ constructor(private readonly deps: {+ codex(session: RegisteredSession): Promise<ActivityState>+ capture(session: RegisteredSession): Promise<string | null>+ }) {}+ forget(sessionId: string): void { this.footers.delete(sessionId) }+ async read(session: RegisteredSession): Promise<ActivityState> {+ const state = await this.deps.codex(session)+ if (state !== 'unknown') return state+ if (session.engine !== 'claude' && session.engine !== 'codex') return 'unknown'+ const screen = await this.deps.capture(session)+ const runtime = activityRuntimeKey(session)+ const previous = this.footers.get(session.sessionId)+ const indicator = terminalActivityReading(session.engine, screen)?.indicator ?? null+ const stopped = session.engine === 'codex' && codexStoppedGoal(screen)+ this.footers.set(session.sessionId, { runtime, indicator, stopped })+ if (previous?.runtime !== runtime) return 'unknown'+ if (stopped && previous.stopped) return 'idle'+ if (indicator && previous.indicator && indicator !== previous.indicator) return 'working'+ return 'unknown'+ }+}diff --git a/cli/src/lib/turnActivity.spec.ts b/cli/src/lib/turnActivity.spec.tsnew file mode 100644index 000000000..699a98005--- /dev/null+++ b/cli/src/lib/turnActivity.spec.ts@@ -0,0 +1,93 @@+import { describe, expect, it } from 'vitest'+import { TurnActivity, WORK_EVIDENCE_MS, type ActivityRuntime, type ActivityState } from './turnActivity.js'++function setup() {+ let now = 0+ let runtime: ActivityRuntime | undefined = { key: 'agent:session:pid:start', turnOpen: true }+ let answer: ActivityState = 'unknown'+ let probe = async () => answer+ let drain = async () => {}+ const activity = new TurnActivity({ now: () => now, runtime: () => runtime,+ probe: () => probe(), drain: () => drain() })+ return { activity, frame: () => activity.snapshot('s'),+ advance: (ms = WORK_EVIDENCE_MS) => { now += ms },+ answer: (value: ActivityState) => { answer = value },+ runtime: (value?: ActivityRuntime) => { runtime = value },+ probe: (value: typeof probe) => { probe = value }, drain: (value: typeof drain) => { drain = value } }+}++describe('verified turn activity', () => {+ it('never promotes an unfinished replay to Working, even after thousands of beats', async () => {+ const t = setup()+ t.activity.observe('s', 'turn_started', true)+ for (let i = 0; i < 2000; i++) { t.advance(5000); await t.activity.check('s'); expect(t.frame()?.state).toBe('unknown') }+ })+ it('expires a missing end into unknown without changing the runtime turn or manufacturing completion', () => {+ const t = setup()+ t.activity.observe('s', 'turn_started')+ expect(t.frame()?.state).toBe('working')+ t.advance(WORK_EVIDENCE_MS - 1)+ expect(t.frame()?.validForMs).toBe(1)+ t.advance(1)+ expect(t.frame()?.state).toBe('unknown')+ t.activity.observe('s', 'text_delta')+ expect(t.frame()?.state).toBe('working')+ t.activity.observe('s', 'turn_ended')+ expect(t.frame()?.state).toBe('idle')+ })+ it.each(['turn_started', 'text_delta', 'thinking_delta', 'thinking_title', 'tool_start', 'tool_end', 'subagent_finished'])(+ 'renews evidence for live %s, but not a replay of it', type => {+ const t = setup(); t.activity.observe('s', type)+ t.advance(20_000); t.activity.observe('s', type, true)+ t.advance(10_000); expect(t.frame()?.state).toBe('unknown')+ t.activity.observe('s', type); expect(t.frame()?.state).toBe('working')+ })+ it('does not renew evidence from metadata, snapshots, or heartbeat generation', () => {+ const t = setup(); t.activity.observe('s', 'turn_started')+ const version = t.frame()?.revision+ for (let i = 0; i < 5; i++) { t.advance(5000); t.activity.observe('s', 'token_count'); expect(t.frame()?.revision).toBe(version) }+ t.advance(5000); expect(t.frame()?.state).toBe('unknown')+ })+ it('keeps quiet tools/thinking Working for hours with fresh positive runtime readings', async () => {+ const t = setup(); t.answer('working')+ for (let i = 0; i < 3000; i++) { t.advance(5000); await t.activity.check('s'); expect(t.frame()?.state).toBe('working') }+ })+ it('treats failed and unavailable probes as unknown, never idle', async () => {+ const t = setup(); t.activity.observe('s', 'turn_started')+ t.probe(async () => { throw new Error('disconnected') })+ await t.activity.check('s'); expect(t.frame()?.state).toBe('working')+ t.advance(); await t.activity.check('s'); expect(t.frame()?.state).toBe('unknown')+ })+ it.each(['progress', 'end', 'replacement', 'removed', 'forget'])(+ 'rejects a delayed probe after %s', async change => {+ const t = setup()+ let resolve!: (s: ActivityState) => void+ t.probe(() => new Promise(r => { resolve = r }))+ const pending = t.activity.check('s'); await Promise.resolve()+ if (change === 'progress') t.activity.observe('s', 'text_delta')+ if (change === 'end') t.activity.observe('s', 'turn_ended')+ if (change === 'replacement') t.runtime({ key: 'replacement', turnOpen: true })+ if (change === 'removed') t.runtime()+ if (change === 'forget') t.activity.forget('s')+ resolve(change === 'progress' ? 'idle' : 'working'); await pending+ expect(t.frame()?.state).toBe(change === 'progress' ? 'working' : change === 'end' ? 'idle' : change === 'removed' ? undefined : 'unknown')+ })+ it('drains missed completion writes before and after a live probe', async () => {+ const t = setup(); let calls = 0+ t.drain(async () => { if (++calls === 2) t.activity.observe('s', 'turn_ended') })+ t.answer('working'); await t.activity.check('s')+ expect(calls).toBe(2); expect(t.frame()?.state).toBe('idle')+ })+ it('does not let a probe override recent live engine progress', async () => {+ const t = setup(); t.activity.observe('s', 'text_delta'); t.answer('idle')+ await t.activity.check('s'); expect(t.frame()?.state).toBe('working')+ t.advance(); await t.activity.check('s'); expect(t.frame()?.state).toBe('idle')+ })+ it('coalesces overlapping checks', async () => {+ const t = setup(); let calls = 0; let resolve!: (s: ActivityState) => void+ t.probe(() => { calls++; return new Promise(r => { resolve = r }) })+ const first = t.activity.check('s'); await Promise.resolve()+ const second = t.activity.check('s'); expect(calls).toBe(1)+ resolve('working'); await Promise.all([first, second]); expect(t.frame()?.state).toBe('working')+ })+})diff --git a/cli/src/lib/turnActivity.ts b/cli/src/lib/turnActivity.tsnew file mode 100644index 000000000..ca842b37b--- /dev/null+++ b/cli/src/lib/turnActivity.ts@@ -0,0 +1,90 @@+/** Connectivity and an unfinished transcript are not evidence of current work.+ * This lease is renewed only by live engine events or a fresh runtime reading.+ * Expiry withdraws the Working claim; it never completes or cancels a turn. */+import { randomUUID } from 'node:crypto'++export type ActivityState = 'working' | 'idle' | 'unknown'+export interface ActivityFrame {+ state: ActivityState+ epoch: string+ revision: number+ /** Remaining lease, not a remote wall clock. Zero for idle/unknown. */+ validForMs: number+}+export interface ActivityRuntime { key: string; turnOpen: boolean }+interface Entry {+ runtime: string+ state: ActivityState+ revision: number+ until: number+ pending?: Promise<void>+}+export const WORK_EVIDENCE_MS = 30_000+export const WORK_HEARTBEAT_LEASE_MS = WORK_EVIDENCE_MS+const PROGRESS = new Set(['turn_started', 'text_delta', 'thinking_delta', 'thinking_title', 'tool_start', 'tool_end', 'subagent_finished'])++export class TurnActivity {+ private readonly entries = new Map<string, Entry>()+ private readonly epoch = randomUUID()+ private revision = 0+ constructor(private readonly deps: {+ runtime(sessionId: string): ActivityRuntime | undefined+ probe(sessionId: string): Promise<ActivityState>+ drain(sessionId: string): Promise<void>+ now?: () => number+ }) {}+ private now(): number { return this.deps.now?.() ?? performance.now() }+ private entry(sessionId: string): Entry | undefined {+ const runtime = this.deps.runtime(sessionId)+ if (!runtime) { this.entries.delete(sessionId); return undefined }+ let entry = this.entries.get(sessionId)+ if (!entry || entry.runtime !== runtime.key) {+ entry = { runtime: runtime.key, state: runtime.turnOpen ? 'unknown' : 'idle', revision: ++this.revision, until: 0 }+ this.entries.set(sessionId, entry)+ }+ if (entry.state === 'working' && this.now() >= entry.until) this.set(entry, 'unknown')+ return entry+ }+ private set(entry: Entry, state: ActivityState): void {+ entry.state = state+ entry.until = state === 'working' ? this.now() + WORK_EVIDENCE_MS : 0+ entry.revision = ++this.revision+ }+ observe(sessionId: string, type: string, replay = false): void {+ const entry = this.entry(sessionId)+ if (!entry) return+ if (replay) {+ // A completed history is a baseline. An unfinished history has no live+ // claim; subsequent polling must establish it independently.+ if (type === 'turn_started' && entry.state !== 'working') this.set(entry, 'unknown')+ if (type === 'turn_ended' && entry.state !== 'working') this.set(entry, 'idle')+ return+ }+ if (type === 'turn_ended') this.set(entry, 'idle')+ else if (PROGRESS.has(type)) this.set(entry, 'working')+ }+ snapshot(sessionId: string): ActivityFrame | undefined {+ const entry = this.entry(sessionId)+ if (!entry) return undefined+ return { state: entry.state, epoch: this.epoch, revision: entry.revision,+ validForMs: entry.state === 'working' ? Math.max(0, Math.min(WORK_HEARTBEAT_LEASE_MS, entry.until - this.now())) : 0 }+ }+ forget(sessionId: string): void { this.entries.delete(sessionId) }+ async check(sessionId: string): Promise<void> {+ const entry = this.entry(sessionId)+ if (!entry || entry.pending) return entry?.pending+ const run = async () => {+ await this.deps.drain(sessionId)+ if (this.entry(sessionId) !== entry) return+ const revision = entry.revision+ const result = await this.deps.probe(sessionId)+ await this.deps.drain(sessionId)+ // A completion, a new prompt, or a replaced process wins over a probe+ // started before it. Failed reads never mean idle.+ if (this.entry(sessionId) !== entry || entry.revision !== revision) return+ if (result === 'working' || (result === 'idle' && entry.state !== 'working')) this.set(entry, result)+ }+ entry.pending = run().catch(() => {}).finally(() => { entry.pending = undefined })+ await entry.pending+ }+}diff --git a/desktop/design/desktop-ui-migration.md b/desktop/design/desktop-ui-migration.mdindex baeeeb138..065ee97b4 100644--- a/desktop/design/desktop-ui-migration.md+++ b/desktop/design/desktop-ui-migration.md@@ -20,7 +20,7 @@ on 2026-09-30; the unmerged checkpoints below describe earlier review stages.| Sharing | Access/people/options, comments, observer sidebar, and viewer access/error states use desktop surfaces; existing sharing and authentication rules retained || Add Phone | Desktop QR/device layout implemented; pairing lifecycle tests and light/dark enlarged-text renders pass || Machine recovery/linking | Desktop linking/password layouts implemented; bounded selectable errors, fixed actions, and 32-point reveal controls tested/rendered |-| Notifications | Native name/message rows share the tab/pane activity marks and colors. Working starts expanded; compact headers and clear icon replace repeated labels. Synthetic light/dark, collapsed, empty, long, selected and unavailable states inspected; live menu interaction still needs review |+| Notifications | Native name/message rows share the tab/pane activity marks, with colors adapted to menu contrast. Ready and Working use compact headers; all working sessions stay visible. Synthetic light/dark, all-working, empty, long, selected and unavailable states inspected; live menu interaction still needs review || Branches / pull requests | Desktop lists and shared modal veil implemented; colored icons, readable status words, honest load failures, Page Up/Down tested and rendered || Settings / customization | Desktop status customization, natural-height controls, error contrast, keyboard focus and passive native footer preview implemented; actual status previews preserve the selected renderer || Store | Existing graphical discovery/detail/launch routes retained; ordinary labels, search and counts use system typography; desktop and narrow/enlarged previews inspected |@@ -43,29 +43,38 @@ counted as completed user journeys. Shared controls still serve their tests.The earlier overview repeated a status caption and tab/machine context undernearly every title. It now pairs the harness name directly with the message,uses the existing tab/pane activity marks and colors, and keeps full context-in tooltips and accessibility. Working starts expanded as 28-point rows; the-section disappears when empty. Clear is a quiet icon with a 32-point target.+in tooltips and accessibility. The first section is Ready, which includes both+completed replies and questions awaiting input. Working always shows all of its+28-point rows, without a disclosure arrow or overflow submenu; the section+disappears when empty. Clear is a quiet icon with a 32-point target.The menu keeps native actions, keyboard navigation and receipt validation.+Status hues adapt to the menu's light or dark appearance independently of the+terminal theme, so a bright yellow question mark remains legible on a light+translucent menu. Monochrome status preferences remain monochrome.[Apple notification research](macos-design-research.md#notification-menu-refinement--2026-10-01)informed the hierarchy, not a claim of system Notification Center equivalence.Native captures use synthetic sessions and the production AppKit views:[light](images/notification-overview-light.png),[dark](images/notification-overview-dark.png), and-[collapsed Working](images/notification-overview-collapsed.png). The six-session-expanded sample is 360×465 points, down from 360×597. Empty is 360×184; long+[all seven working sessions](images/notification-overview-all-working.png).+The six-session sample is 360×465 points, down from 360×597. The all-working+sample is 360×423. Empty is 360×184; longnames preserve the 360-point menu width. These are view renders on neutralsurfaces; they do not simulate window-server blur. The fixture also coverslong/truncated, highlighted and offline rows. Reproduce with`tool/check_swarm_titlebar.sh <flutter-sdk> --status-menu-preview`.-Validation: 15 targeted Flutter tests, 50 native menu checks, and 4,405 native-tab/layout checks; changed-file static analysis and the icon audit pass. A-signed Intel Skia debug build is ready for local review. Menu and tab bridge payloads match for glyph, label and-color. Tests cover receipt-bound previews, stale clicks, snapshot clearing,-tab moves, existing-pane navigation, expanded defaults, disclosure keys,-shortcut hints, sign-out and the animation lifecycle. The native glyph drawing-is shared without changing tab geometry. Physical pointer/keyboard tracking+Validation for this refinement: 39 targeted Flutter tests and 48 native menu+checks; changed-file static analysis and the icon audit pass. Menu and tab bridge+payloads match for glyph, label and source color. Tests cover receipt-bound+previews, stale clicks, snapshot clearing, tab moves, existing-pane navigation,+all working rows, shortcut hints, sign-out, menu contrast and the animation+lifecycle. Activity from stopped or replaced conversations is rejected, and a+working row expires when its heartbeats stop. This does not suppress a machine+that continues to send heartbeats for its current conversation; that upstream+case still requires investigation. The native glyph drawing is shared without+changing tab geometry. Physical pointer/keyboard trackingand VoiceOver in the user's running app remain manual review items; thesefixtures are not that evidence.diff --git a/desktop/design/icon-design-system.md b/desktop/design/icon-design-system.mdindex 928692706..3a5565801 100644--- a/desktop/design/icon-design-system.md+++ b/desktop/design/icon-design-system.md@@ -162,3 +162,7 @@ Review captures use synthetic fixtures: [repeated pane controls](review/2026-09-The historical toolbar SVG assets are still bundled for existing identityreferences; app toolbar controls now render catalogue symbols. New UI mustnot use those legacy assets as action icons.++Activity whose live evidence expired uses the existing neutral `◌` mark with the+accessible label “Status unavailable” in desktop and TUI. It is neither Working+nor a new Ready result; no notification is generated by this state change.diff --git a/desktop/design/images/notification-overview-all-working.png b/desktop/design/images/notification-overview-all-working.pngnew file mode 100644index 000000000..eb4429473Binary files /dev/null and b/desktop/design/images/notification-overview-all-working.png differdiff --git a/desktop/design/images/notification-overview-dark.png b/desktop/design/images/notification-overview-dark.pngindex f06c4f3de..7712de380 100644Binary files a/desktop/design/images/notification-overview-dark.png and b/desktop/design/images/notification-overview-dark.png differdiff --git a/desktop/design/images/notification-overview-light.png b/desktop/design/images/notification-overview-light.pngindex c1731ebc8..53b4e3a4f 100644Binary files a/desktop/design/images/notification-overview-light.png and b/desktop/design/images/notification-overview-light.png differdiff --git a/desktop/design/picker-verification.md b/desktop/design/picker-verification.mdindex 24c54daec..72d070683 100644--- a/desktop/design/picker-verification.md+++ b/desktop/design/picker-verification.md@@ -1,6 +1,6 @@# Picker verification — 2026-09-23-Scope: Cmd-N New Harness and Cmd-O Open Harness redesign, plus Cmd-P command+Scope: Cmd-N New Harness and Cmd-P Open Harness, Cmd-O Open Project, plus Cmd-Shift-P commandexecution, editing and focus regressions.This is a scenario audit, not a claim that every possible runtime state hasbeen tested. Line coverage is measured separately from native UI testing.diff --git a/desktop/design/search-freshness.md b/desktop/design/search-freshness.mdindex 8caf37669..466733a8b 100644--- a/desktop/design/search-freshness.md+++ b/desktop/design/search-freshness.md@@ -10,7 +10,7 @@ and update the data without making typing wait for another machine.| New Harness → New Project | Refresh the parent folder on entry/revisit so a project created elsewhere becomes an “Open existing” choice. || Remote folder browser | Read the directory on navigation. Refresh or ⌘/Ctrl+R updates the current directory while preserving its rows, selection, and typed path. || Recent projects | Combine saved project history with live harness project metadata. This is a list of used projects, not a recursive disk index. Open Folder discovers other folders. |-| Open Harness (⌘O), project/machine groups, and Harnesses | Filter the live harness inventory, including its branch metadata. These surfaces do not query every repository's Git branches. |+| Open Harness (⌘P), Open Project (⌘O), and machine groups | Filter the live harness inventory, including its branch metadata. These surfaces do not query every repository's Git branches. |## Cost and failure behaviordiff --git a/desktop/lib/core/agent_activity.dart b/desktop/lib/core/agent_activity.dartnew file mode 100644index 000000000..a9634b111--- /dev/null+++ b/desktop/lib/core/agent_activity.dart@@ -0,0 +1,62 @@+/// A daemon's evidence of work, separate from terminal connectivity. Repeated+/// packets and snapshots carry the same revision and cannot renew the lease.+class AgentActivity {+ const AgentActivity(this.state, this.epoch, this.revision, this.validForMs);+ final String state;+ final String epoch;+ final int revision;+ final int validForMs;++ static AgentActivity? fromJson(Object? value) {+ if (value is! Map) return null;+ final state = value['state'];+ final epoch = value['epoch'];+ final revision = value['revision'];+ final lease = value['validForMs'];+ if (!const ['working', 'idle', 'unknown'].contains(state) ||+ epoch is! String ||+ epoch.isEmpty ||+ revision is! int ||+ revision < 0 ||+ lease is! num ||+ !lease.isFinite ||+ lease < 0) {+ return null;+ }+ return AgentActivity(+ state as String,+ epoch,+ revision,+ lease.clamp(0, 30000).toInt(),+ );+ }++ @override+ bool operator ==(Object other) =>+ other is AgentActivity &&+ state == other.state &&+ epoch == other.epoch &&+ revision == other.revision;+ @override+ int get hashCode => Object.hash(state, epoch, revision);+}++class AgentActivityOrder {+ AgentActivity? latest;+ final _retired = <String>{};+ bool isOlder(AgentActivity next) =>+ _retired.contains(next.epoch) ||+ (latest?.epoch == next.epoch && next.revision < latest!.revision);+ bool accept(AgentActivity next) {+ final prior = latest;+ if (_retired.contains(next.epoch)) return false;+ if (prior != null) {+ if (next.epoch == prior.epoch && next.revision <= prior.revision) {+ return false;+ }+ if (next.epoch != prior.epoch) _retired.add(prior.epoch);+ }+ latest = next;+ return true;+ }+}diff --git a/desktop/lib/core/models.dart b/desktop/lib/core/models.dartindex 58e92e64a..b5f55d47b 100644--- a/desktop/lib/core/models.dart+++ b/desktop/lib/core/models.dart@@ -3,6 +3,7 @@ library;import 'package:flutter/foundation.dart' show immutable, listEquals;+import 'agent_activity.dart';import 'runtime_model_name.dart';import 'agent_git_context.dart';@@ -289,6 +290,7 @@ class AgentOutputStats {}class Agent {+ final AgentActivity? activity;final String id;final String? sessionId;final String name;@@ -432,6 +434,7 @@ class Agent {final String? namedAgent;const Agent({+ this.activity,required this.id,this.sessionId,required this.name,@@ -572,6 +575,7 @@ class Agent {engine: _safeEngine(j['engine']),);return Agent(+ activity: AgentActivity.fromJson(j['activity']),id: j['id'] as String,sessionId: _safeLabel(j['sessionId']),name: j['name'] as String? ?? 'harness',@@ -650,6 +654,7 @@ class Agent {DateTime? lastOpenedAt,bool clearClosePlan = false,}) => Agent(+ activity: activity,id: id,sessionId: sessionId,name: name ?? this.name,diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dartindex 78531f81a..49b131f5d 100644--- a/desktop/lib/screens/swarm_screen.dart+++ b/desktop/lib/screens/swarm_screen.dart@@ -1776,7 +1776,7 @@ class _SwarmScreenState extends State<SwarmScreen> {'enabled': _routeIsCurrent && !_dialogOpen && !_spokenPaletteOpen,'reduceMotion': _reduceMotion,'activeId': app.activeSwarmId,- 'searchTooltip': _commandTooltip('Search harnesses', 'harnesses.list'),+ 'searchTooltip': _commandTooltip('Open Harness', 'harnesses.list'),'storeTooltip': _commandTooltip('Explore Harness Store', 'app.store'),// The selected tab is drawn with keyboard focus: ⏎ goes into it.'tabsFocused': app.tabStripFocused && _tabStripFocus.hasPrimaryFocus,@@ -6325,7 +6325,7 @@ class _SwarmScreenState extends State<SwarmScreen> {?mode('app.daemon_talk', 'Talk to daemon', 'Ask your paired daemon'),?mode('harnesses.list',- 'Harnesses',+ 'Open Harness','Manage running and paused harnesses',),?mode('terminal.new', 'New terminal', 'A shell where you are'),@@ -7516,8 +7516,8 @@ class _SwarmScreenState extends State<SwarmScreen> {Widget _searchButton(TerminalTheme theme) => WorkspaceBarControl(key: const ValueKey('swarm-search-button'),- label: 'Search harnesses',- tooltip: _commandTooltip('Search harnesses', 'harnesses.list'),+ label: 'Open Harness',+ tooltip: _commandTooltip('Open Harness', 'harnesses.list'),onPressed: _shortcutsEnabled ? _toggleSessions : null,builder: (context, emphasized) => SizedBox(width: workspaceBarCellSizeOf(context).width * 4,diff --git a/desktop/lib/shortcuts/app_shortcuts.dart b/desktop/lib/shortcuts/app_shortcuts.dartindex a5bf01897..3c88be039 100644--- a/desktop/lib/shortcuts/app_shortcuts.dart+++ b/desktop/lib/shortcuts/app_shortcuts.dart@@ -494,7 +494,7 @@ const kSwarmShortcuts = [AppShortcut(action: ShortcutAction.addAgent,activator: SingleActivator(LogicalKeyboardKey.keyO, meta: true),- label: 'Open Harness',+ label: 'Open Project',group: ShortcutGroup.actions,),AppShortcut(diff --git a/desktop/lib/shortcuts/keyboard_practice.dart b/desktop/lib/shortcuts/keyboard_practice.dartindex e120edb4d..a9386d152 100644--- a/desktop/lib/shortcuts/keyboard_practice.dart+++ b/desktop/lib/shortcuts/keyboard_practice.dart@@ -39,7 +39,7 @@ class KeyboardLesson {.join(' / ');String get result => switch (command) {'swarm.new' => '[work] [new tab]\nFind a harness, or create one',- 'agent.open' ||+ 'agent.open' => '# Projects\nChoose a project to see its harnesses.','agent.add' => '[harness 1] │ [harness 2]\nBoth harnesses share this tab.','agent.new' => 'Codex · This Mac · payments\nHarness anything (optional)\nNew harness is selected. Return starts with these settings; Tab reaches each control. Model, approvals, and Codex profile are below the message.','pane.zoom' => '[harness 2 — full workspace]\nPress the same key to restore the other panes.',diff --git a/desktop/lib/shortcuts/keymap_commands.dart b/desktop/lib/shortcuts/keymap_commands.dartindex 22dab60ac..1d4c6f5ed 100644--- a/desktop/lib/shortcuts/keymap_commands.dart+++ b/desktop/lib/shortcuts/keymap_commands.dart@@ -329,12 +329,13 @@ final harnessCommands = <HarnessCommand>[repeatable: true,),const HarnessCommand(+ // Keep this existing command ID for saved keybindings; it opens # Projects.'agent.open',- 'Open Harness',+ 'Open Project',ShortcutGroup.actions,action: ShortcutAction.addAgent,nativeAction: 'addAgent',- keywords: ['resume', 'existing', 'pane'],+ keywords: ['project', 'folder', 'repository', 'pane'],),const HarnessCommand('agent.add', 'New Pane', ShortcutGroup.actions),const HarnessCommand(@@ -433,11 +434,11 @@ final harnessCommands = <HarnessCommand>[),const HarnessCommand('harnesses.list',- 'Harnesses',+ 'Open Harness',ShortcutGroup.actions,nativeAction: 'sessions',extraKeys: ['cmd+p'],- keywords: ['manage', 'running', 'paused', 'sessions'],+ keywords: ['open', 'resume', 'existing', 'running', 'paused', 'sessions'],),const HarnessCommand('project.add',diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex a08af3105..eecb93dbd 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -42,6 +42,7 @@ import '../core/browser_label.dart';import '../core/local_hostname.dart';import '../core/local_git_projects.dart';import '../core/test_run.dart';+import '../core/agent_activity.dart';import '../core/models.dart';import '../core/harness_resources.dart';import '../core/machine_resources.dart';@@ -358,6 +359,9 @@ class MachineState {// opening a terminal stream against an unavailable node.String? pendingOfflineAgentId;final Set<String> processingAgentIds = {};+ final Set<String> unknownActivityAgentIds = {};+ final Map<String, AgentActivityOrder> activityOrder = {};+ final Set<String> legacyHeartbeatSeen = {};/// Successful turn events from work opened in this workspace: the daemon's/// `turn` and `store` habits (read only while daemons are on). Capture the@@ -5842,6 +5846,7 @@ class AppNotifier extends ChangeNotifier {prev.name != agent.name ||prev.title != agent.title ||prev.sessionId != agent.sessionId ||+ prev.activity != agent.activity ||prev.engine != agent.engine ||prev.engineDisplayName != agent.engineDisplayName ||prev.engineIconHint != agent.engineIconHint ||@@ -7756,7 +7761,14 @@ class AppNotifier extends ChangeNotifier {final previousWork = {for (final agent in machine.agents) agent.id: agent};agents = [for (final agent in agents)- retainNewerGitContext(agent, previousWork[agent.id]),+ if (previousWork[agent.id] case final previous?+ when previous.sessionId != agent.sessionId &&+ agent.activity != null &&+ machine.activityOrder[agent.id]?.isOlder(agent.activity!) ==+ true)+ previous+ else+ retainNewerGitContext(agent, previousWork[agent.id]),];final previous = {for (final agent in machine.agents) agent.id: agent};final nextIds = agents.map((agent) => agent.id).toSet();@@ -7779,6 +7791,7 @@ class AppNotifier extends ChangeNotifier {}machine.agents = agents;for (final agent in agents) {+ _reconcileAgentActivity(machine, agent, previous[agent.id]);if (previous[agent.id]?.name != agent.name) {_recordAgentName(machine, agent);}@@ -7799,6 +7812,9 @@ class AppNotifier extends ChangeNotifier {machine.activeAgentId = null;}machine.processingAgentIds.removeWhere((id) => !nextIds.contains(id));+ machine.unknownActivityAgentIds.removeWhere((id) => !nextIds.contains(id));+ machine.activityOrder.removeWhere((id, _) => !nextIds.contains(id));+ machine.legacyHeartbeatSeen.removeWhere((id) => !nextIds.contains(id));machine.sessionAgentIds.clear();for (final agent in agents) {final sessionId = agent.sessionId;@@ -7808,7 +7824,9 @@ class AppNotifier extends ChangeNotifier {final agentId = machine.sessionAgentIds[sessionId];if (agentId == null) continue;machine.pendingProcessingSessions.remove(sessionId);- _markAgentProcessing(machine, agentId);+ if (!machine.activityOrder.containsKey(agentId)) {+ _markAgentProcessing(machine, agentId);+ }}_warmPreviews(machine);for (final agent in agents) {@@ -7816,9 +7834,37 @@ class AppNotifier extends ChangeNotifier {}}+ void _reconcileAgentActivity(+ MachineState machine,+ Agent agent,+ Agent? previous,+ ) {+ // Busy belongs to one conversation, not to the reusable harness ID. A+ // stopped or replaced conversation cannot keep its old working signal.+ if (agent.isStopped ||+ (previous?.sessionId != null &&+ previous!.sessionId != agent.sessionId)) {+ _cancelTurnActivity(machine.machine.machineId, agent.id);+ machine.liveTurnAgents.remove(agent.id);+ machine.legacyHeartbeatSeen.remove(agent.id);+ machine.pendingProcessingSessions.remove(previous?.sessionId);+ if (agent.isStopped) {+ machine.pendingProcessingSessions.remove(agent.sessionId);+ }+ }+ if (!agent.isStopped && agent.activity != null) {+ _applyReportedActivity(machine, agent.id, agent.activity!);+ }+ }+bool _upsertAgent(MachineState machine, Agent agent) {final index = machine.agents.indexWhere((item) => item.id == agent.id);final previous = index == -1 ? null : machine.agents[index];+ if (previous?.sessionId != agent.sessionId &&+ agent.activity != null &&+ machine.activityOrder[agent.id]?.isOlder(agent.activity!) == true) {+ return false;+ }agent = retainNewerGitContext(agent, previous);// Discovery repeatedly sends the same snapshot. Preserve the existing// object (pane presentation keys include it), and do not refetch previews@@ -7837,6 +7883,7 @@ class AppNotifier extends ChangeNotifier {} else {machine.agents = [...machine.agents]..[index] = agent;}+ _reconcileAgentActivity(machine, agent, previous);if (previous?.name != agent.name) _recordAgentName(machine, agent);_syncAgentName(machine, agent);sessionPreviews.retainAgent(@@ -7849,7 +7896,8 @@ class AppNotifier extends ChangeNotifier {final sessionId = agent.sessionId;if (sessionId != null) {machine.sessionAgentIds[sessionId] = agent.id;- if (machine.pendingProcessingSessions.remove(sessionId)) {+ if (machine.pendingProcessingSessions.remove(sessionId) &&+ !machine.activityOrder.containsKey(agent.id)) {_markAgentProcessing(machine, agent.id);}}@@ -8421,11 +8469,16 @@ class AppNotifier extends ChangeNotifier {String _turnActivityKey(String machineId, String agentId) =>'$machineId\u0000$agentId';- bool _markAgentProcessing(MachineState machine, String agentId) {- final changed = machine.processingAgentIds.add(agentId);+ bool _markAgentProcessing(+ MachineState machine,+ String agentId, {+ Duration? lease,+ }) {+ var changed = machine.unknownActivityAgentIds.remove(agentId);+ changed = machine.processingAgentIds.add(agentId) || changed;final key = _turnActivityKey(machine.machine.machineId, agentId);_turnActivityWatchdogs.remove(key)?.cancel();- _turnActivityWatchdogs[key] = Timer(turnActivityTimeout, () {+ _turnActivityWatchdogs[key] = Timer(lease ?? turnActivityTimeout, () {_turnActivityWatchdogs.remove(key);// Closed even when the machine has been replaced under us: this path is// the only end a stalled turn ever gets, and a stats turn left open would@@ -8433,11 +8486,44 @@ class AppNotifier extends ChangeNotifier {harnessStats.onTurnEnded(key);final current = machineStates[machine.machine.machineId];if (!identical(current, machine)) return;+ machine.unknownActivityAgentIds.add(agentId);if (machine.processingAgentIds.remove(agentId)) notifyListeners();});return changed;}+ ({bool accepted, bool changed}) _applyReportedActivity(+ MachineState machine,+ String agentId,+ AgentActivity activity,+ ) {+ final order = machine.activityOrder.putIfAbsent(+ agentId,+ AgentActivityOrder.new,+ );+ if (!order.accept(activity)) return (accepted: false, changed: false);+ if (activity.state == 'working' && activity.validForMs > 0) {+ return (+ accepted: true,+ changed: _markAgentProcessing(+ machine,+ agentId,+ lease: Duration(milliseconds: activity.validForMs),+ ),+ );+ }+ final wasWorking = machine.processingAgentIds.contains(agentId);+ final wasUnknown = machine.unknownActivityAgentIds.contains(agentId);+ _cancelTurnActivity(+ machine.machine.machineId,+ agentId,+ clearQuestion: false,+ );+ final unknown = activity.state != 'idle';+ if (unknown) machine.unknownActivityAgentIds.add(agentId);+ return (accepted: true, changed: wasWorking || wasUnknown != unknown);+ }+/// Whether this agent is mid-turn, by the app's own reckoning.////// Fed by `turn_started`/`turn_heartbeat`/`turn_ended` and by the same watchdog that clears a@@ -8531,6 +8617,7 @@ class AppNotifier extends ChangeNotifier {modelStarts.end(machineId, agentId);final machine = machineStates[machineId];machine?.processingAgentIds.remove(agentId);+ machine?.unknownActivityAgentIds.remove(agentId);// Raw turn endings do not decide whether a question is answered. The// shared daemon question-close event does. Disconnect/deletion still clear.if (clearQuestion) machine?.blockedAgents.remove(agentId);@@ -8541,6 +8628,9 @@ class AppNotifier extends ChangeNotifier {_cancelTurnActivity(machine.machine.machineId, agentId);}machine.processingAgentIds.clear();+ machine.unknownActivityAgentIds.clear();+ machine.activityOrder.clear();+ machine.legacyHeartbeatSeen.clear();machine.pendingProcessingSessions.clear();machine.blockedAgents.clear();}@@ -8553,6 +8643,9 @@ class AppNotifier extends ChangeNotifier {modelStarts.clear();for (final machine in machineStates.values) {machine.processingAgentIds.clear();+ machine.unknownActivityAgentIds.clear();+ machine.activityOrder.clear();+ machine.legacyHeartbeatSeen.clear();machine.pendingProcessingSessions.clear();machine.blockedAgents.clear();}@@ -13531,6 +13624,56 @@ class AppNotifier extends ChangeNotifier {}return;}+ if (type == 'agent_activity' ||+ _modelAnswerEvents.contains(type) ||+ payload.containsKey('activity') ||+ type == 'turn_started' ||+ type == 'turn_heartbeat' ||+ type == 'turn_ended') {+ final agentId = _eventAgentId(machine, event, payload);+ final agent = machine.agents+ .where((agent) => agent.id == agentId)+ .firstOrNull;+ final sessionId = _eventSessionId(event, payload);+ // Heartbeats need the same conversation check as transcript events.+ // Late work from a previous conversation must neither revive this+ // harness nor end a newer turn after it has been resumed or replaced.+ if ((agent?.isStopped == true && type != 'turn_ended') ||+ (sessionId != null &&+ agent?.sessionId != null &&+ sessionId != agent!.sessionId)) {+ return;+ }+ }+ final reportedActivity = AgentActivity.fromJson(payload['activity']);+ if (reportedActivity != null) {+ final id = _eventAgentId(machine, event, payload);+ if (id != null) {+ final applied = _applyReportedActivity(machine, id, reportedActivity);+ if (applied.changed) notifyListeners();+ if (!applied.accepted &&+ (type == 'turn_ended' || type == 'turn_started')) {+ return;+ }+ }+ }+ if (type == 'agent_activity') return;+ if (reportedActivity == null &&+ event['replay'] != true &&+ const {+ 'text_delta',+ 'thinking_delta',+ 'thinking_title',+ 'tool_start',+ 'tool_end',+ }.contains(type)) {+ final id = _eventAgentId(machine, event, payload);+ if (id != null && !machine.activityOrder.containsKey(id)) {+ machine.legacyHeartbeatSeen.remove(id);+ if (_markAgentProcessing(machine, id)) notifyListeners();+ }+ }+// Before the preview's early returns: several first-output kinds (`thinking_delta`) are not// preview events at all.if (type == 'turn_started' || _modelAnswerEvents.contains(type)) {@@ -13992,22 +14135,36 @@ class AppNotifier extends ChangeNotifier {var changed = false;final agentId = _eventAgentId(machine, event, payload);if (agentId != null) {- if (type == 'turn_started') {+ if (type == 'turn_started' && event['replay'] != true) {machine.liveTurnAgents.add(agentId);changed = machine.failedTurnAgents.remove(agentId);}- changed = _markAgentProcessing(machine, agentId) || changed;+ if (reportedActivity == null &&+ event['replay'] != true &&+ !machine.activityOrder.containsKey(agentId)) {+ if (type == 'turn_started') {+ machine.legacyHeartbeatSeen.remove(agentId);+ }+ // Older daemons renew historical turn flags forever. One unverified+ // heartbeat is bounded; only real new work can establish it again.+ if (type == 'turn_started' ||+ machine.legacyHeartbeatSeen.add(agentId)) {+ changed = _markAgentProcessing(machine, agentId) || changed;+ }+ }// Only a START opens a stats turn, for the reason above: a heartbeat// is a turn already under way, and counting one would report an agent// this app merely reconnected to as work somebody just asked for.- if (type == 'turn_started') {+ if (type == 'turn_started' && event['replay'] != true) {final key = _turnActivityKey(machine.machine.machineId, agentId);changed = harnessStats.turnStartedAt(key) == null || changed;harnessStats.onTurnStarted(key);}} else {final sessionId = _eventSessionId(event, payload);- if (sessionId != null) {+ if (sessionId != null &&+ event['replay'] != true &&+ reportedActivity == null) {changed = machine.pendingProcessingSessions.add(sessionId);}}diff --git a/desktop/lib/state/harness_activity.dart b/desktop/lib/state/harness_activity.dartindex b00deda55..c3ecea145 100644--- a/desktop/lib/state/harness_activity.dart+++ b/desktop/lib/state/harness_activity.dart@@ -12,6 +12,7 @@ enum HarnessActivity {done('✓', 'Finished · unread'),working('⠋', 'Working'),starting('◌', 'Starting'),+ unknown('◌', 'Status unavailable'),idle('', 'Idle'),paused('||', 'Paused'),offline('⊘', 'Offline');@@ -85,6 +86,9 @@ HarnessActivity? harnessActivity(if (app.agentUnread.kindFor(machineId, agentId) == AlertKind.done) {return HarnessActivity.done;}+ if (machine.unknownActivityAgentIds.contains(agentId)) {+ return HarnessActivity.unknown;+ }return HarnessActivity.idle;}diff --git a/desktop/lib/widgets/linux_menu_bar.dart b/desktop/lib/widgets/linux_menu_bar.dartindex 3a57d59a6..7c1308bb5 100644--- a/desktop/lib/widgets/linux_menu_bar.dart+++ b/desktop/lib/widgets/linux_menu_bar.dart@@ -301,6 +301,12 @@ class _LinuxMenuBarState extends State<LinuxMenuBar> {key: 'menu-bar-open-harness',icon: AppIcons.folderOpen,label: 'Open Harness',+ action: 'sessions',+ ),+ _swarmRow(+ key: 'menu-bar-open-project',+ icon: AppIcons.folderOpen,+ label: 'Open Project',action: 'addAgent',),_swarmRow(@@ -457,12 +463,6 @@ class _LinuxMenuBarState extends State<LinuxMenuBar> {},),const AppMenuDivider(),- _swarmRow(- key: 'menu-bar-sessions',- icon: AppIcons.terminal,- label: 'Harnesses',- action: 'sessions',- ),_swarmRow(key: 'menu-bar-notifications',icon: AppIcons.bell,diff --git a/desktop/macos/Runner/HarnessStatusMenu.swift b/desktop/macos/Runner/HarnessStatusMenu.swiftindex 70d49b6a5..ed2354eb8 100644--- a/desktop/macos/Runner/HarnessStatusMenu.swift+++ b/desktop/macos/Runner/HarnessStatusMenu.swift@@ -8,14 +8,11 @@ final class HarnessStatusMenu: NSObject, NSMenuDelegate {private(set) var statusItem: NSStatusItem?private var entries: [[String: Any]] = []private var working: [[String: Any]] = []- private var workingExpanded = true- private var workingItems: [NSMenuItem] = []private var activityTimer: Timer?private var motionObserver: NSObjectProtocol?private var reduceMotion = falseprivate var keymap: HarnessNativeKeymap?private var keyContext = "workspace"- private var menuKeys: Any?private var enabled = falseprivate var workspaceAvailable = falseprivate var tracking = false@@ -47,7 +44,6 @@ final class HarnessStatusMenu: NSObject, NSMenuDelegate {deinit {activityTimer?.invalidate()if let motionObserver { NSWorkspace.shared.notificationCenter.removeObserver(motionObserver) }- if let menuKeys { NSEvent.removeMonitor(menuKeys) }if let statusItem { NSStatusBar.system.removeStatusItem(statusItem) }}@@ -69,7 +65,6 @@ final class HarnessStatusMenu: NSObject, NSMenuDelegate {workspaceAvailable = nextAvailableentries = nextEntriesworking = nextAvailable ? nextWorking : []- if !workspaceAvailable { workingExpanded = true }let count = entries.countstatusItem?.button?.image = Self.badgeImage(logo: NSImage(named: "HarnessStatusIcon"),count: workspaceAvailable ? count : nil)@@ -96,40 +91,16 @@ final class HarnessStatusMenu: NSObject, NSMenuDelegate {refreshTimes()tracking = truesyncActivityAnimation()- if menuKeys == nil {- menuKeys = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { [weak self] event in- guard let self, self.tracking, let item = self.menu.highlightedItem,- self.handleWorkingKey(event, item: item) else { return event }- return nil- }- }}func menuDidClose(_ menu: NSMenu) {guard menu === self.menu else { return }tracking = falsesyncActivityAnimation()- if let menuKeys { NSEvent.removeMonitor(menuKeys); self.menuKeys = nil }// AppKit dispatches the selected item after closing. Rebuild on next open// or update so its receipt remains the snapshot the person selected.}- /// AppKit normally closes a menu on Return. This disclosure stays open for- /// keyboard users too; all other keys keep native menu navigation.- func handleWorkingKey(_ event: NSEvent, item: NSMenuItem) -> Bool {- guard item.menu === menu, item.identifier?.rawValue == "toggleWorking", item.isEnabled,- event.modifierFlags.intersection([.command, .control, .option]).isEmpty,- let row = item.view as? HarnessStatusMenuRow else { return false }- switch event.keyCode {- case 36, 76, 49: return row.accessibilityPerformPress() // Return, keypad Enter, Space- case 124: // Right opens; Left closes an already expanded section.- if !workingExpanded { _ = row.accessibilityPerformPress() }- return true- case 123 where workingExpanded: return row.accessibilityPerformPress()- default: return false- }- }-func menu(_ menu: NSMenu, willHighlight item: NSMenuItem?) {for row in menu.items {(row.view as? HarnessStatusMenuRow)?.highlighted = row === item@@ -158,7 +129,7 @@ final class HarnessStatusMenu: NSObject, NSMenuDelegate {}private func syncActivityAnimation() {- let moving = tracking && enabled && workingExpanded && !reduceMotion &&+ let moving = tracking && enabled && !reduceMotion &&!NSWorkspace.shared.accessibilityDisplayShouldReduceMotion && !activityRows.isEmptyguard moving else {activityTimer?.invalidate()@@ -177,20 +148,19 @@ final class HarnessStatusMenu: NSObject, NSMenuDelegate {}activityTimer = timer// Tracking is itself foreground interaction, even when another app owns- // the key window. Closing or collapsing the menu stops this local clock.+ // the key window. Closing the menu stops this local clock.RunLoop.main.add(timer, forMode: .common)}private func rebuild() {dirty = falsemenu.removeAllItems()- workingItems.removeAll()menu.minimumWidth = 360let clear = add("Mark all read", "clearStatusNotifications", enabled: enabled && !entries.isEmpty)clear.representedObject = entries- clear.view = HarnessStatusMenuRow(item: clear, heading: "Notifications", count: entries.count)+ clear.view = HarnessStatusMenuRow(item: clear, heading: "Ready", count: entries.count)if entries.isEmpty {- let empty = NSMenuItem(title: workspaceAvailable ? "No unread notifications" : "Open Harness to get started",+ let empty = NSMenuItem(title: workspaceAvailable ? "All caught up" : "Open Harness to get started",action: nil, keyEquivalent: "")empty.isEnabled = falsemenu.addItem(empty)@@ -202,25 +172,16 @@ final class HarnessStatusMenu: NSObject, NSMenuDelegate {}if workspaceAvailable && !working.isEmpty {menu.addItem(.separator())- let toggle = add("Working (\(working.count))", "toggleWorking", enabled: !working.isEmpty)- toggle.view = HarnessStatusMenuRow(item: toggle, heading: "Working", count: working.count, expanded: workingExpanded)- for entry in working.prefix(5) {- workingItems.append(addSession(entry, to: menu))- }- if working.count > 5 {- let more = add("More working sessions (\(working.count - 5))", "moreWorking", enabled: enabled)- let submenu = NSMenu(title: "Working")- submenu.autoenablesItems = false- submenu.delegate = self- for entry in working.dropFirst(5) { addSession(entry, to: submenu) }- more.submenu = submenu- workingItems.append(more)- }- for item in workingItems { item.isHidden = !workingExpanded }+ let heading = NSMenuItem(title: "Working (\(working.count))", action: nil, keyEquivalent: "")+ heading.identifier = NSUserInterfaceItemIdentifier("workingHeading")+ heading.isEnabled = false+ heading.view = HarnessStatusMenuRow(item: heading, heading: "Working", count: working.count)+ menu.addItem(heading)+ for entry in working { addSession(entry, to: menu) }}menu.addItem(.separator())add("New Harness…", HarnessKeymapMenu.actionPrefix + "newAgent", enabled: enabled)- add("Open Harness…", HarnessKeymapMenu.actionPrefix + "addAgent", enabled: enabled)+ add("Open Harness…", HarnessKeymapMenu.actionPrefix + "sessions", enabled: enabled)menu.addItem(.separator())add("Show Harness", "openWindow")add("Quit", "quit")@@ -255,14 +216,6 @@ final class HarnessStatusMenu: NSObject, NSMenuDelegate {switch action {case "openWindow": showWindow()case "quit": NSApp.terminate(nil)- case "toggleWorking":- workingExpanded.toggle()- (item.view as? HarnessStatusMenuRow)?.expanded = workingExpanded- // Expand the already displayed snapshot. New arrivals and their receipts- // stay deferred until the next opening, just like the notification rows.- for row in workingItems { row.isHidden = !workingExpanded }- syncActivityAnimation()- menu.update()case "openStatusHarness":guard enabled, let receipt = item.representedObject as? [String: Any],(receipt["unread"] as? Bool == true ? entries : working).contains(where: {@@ -353,19 +306,17 @@ private final class HarnessStatusMenuRow: NSView {let activity: HarnessNativeActivity?private var time = ""var highlighted = false { didSet { needsDisplay = true } }- var expanded: Bool? { didSet { updateAccessibility(); needsDisplay = true } }var activityFrame = 0 {didSet { if oldValue != activityFrame { setNeedsDisplay(activityRect) } }}override var isFlipped: Bool { true }init(item: NSMenuItem, entry: [String: Any]? = nil, heading: String? = nil,- count: Int = 0, expanded: Bool? = nil) {+ count: Int = 0) {self.item = itemself.entry = entryself.heading = headingself.count = count- self.expanded = expandedactivity = HarnessNativeActivity(entry?["activity"] as? [String: Any])let unread = entry?["unread"] as? Bool == truelet message = unread ? entry?["message"] as? String ?? "" : ""@@ -376,7 +327,7 @@ private final class HarnessStatusMenuRow: NSView {super.init(frame: NSRect(x: 0, y: 0, width: 360, height: height))autoresizingMask = [.width]setAccessibilityElement(true)- setAccessibilityRole(.menuItem)+ setAccessibilityRole(heading != nil && !isClearControl ? .staticText : .menuItem)refreshTime()}@@ -420,13 +371,12 @@ private final class HarnessStatusMenuRow: NSView {entry["message"] as? String, context, age, entry["unread"] as? Bool == true ? "Unread" : nil].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: ", ")toolTip = [text, entry["detail"] as? String].compactMap { $0 }.joined(separator: " · ")- } else if let expanded {- text = "\(item.title), \(expanded ? "expanded" : "collapsed")"- setAccessibilityExpanded(expanded)- toolTip = expanded ? "Hide working sessions" : "Show working sessions"- } else {- text = "\(heading ?? "Notifications") (\(count)), Mark all read"+ } else if isClearControl {+ text = "\(heading ?? "Ready") (\(count)), Mark all read"toolTip = "Mark all read. Pending questions stay unanswered."+ } else {+ text = item.title+ toolTip = nil}setAccessibilityLabel(text)setAccessibilityEnabled(item.isEnabled)@@ -438,6 +388,10 @@ private final class HarnessStatusMenuRow: NSView {NSRect(x: bounds.width - 44, y: 0, width: 32, height: bounds.height)}+ private var isClearControl: Bool {+ item?.identifier?.rawValue == "clearStatusNotifications"+ }+private var activityRect: NSRect {NSRect(x: 16, y: entry?["unread"] as? Bool == true ? 7 : 6, width: 16, height: 16)}@@ -447,7 +401,7 @@ private final class HarnessStatusMenuRow: NSView {let selected = highlighted && item.isEnabledif selected {NSColor.selectedContentBackgroundColor.setFill()- NSBezierPath(roundedRect: heading != nil && expanded == nil+ NSBezierPath(roundedRect: isClearControl? clearRect.insetBy(dx: 2, dy: 2) : bounds.insetBy(dx: 4, dy: 1), xRadius: 5, yRadius: 5).fill()}let primary: NSColor = !item.isEnabled ? .disabledControlTextColor@@ -457,16 +411,15 @@ private final class HarnessStatusMenuRow: NSView {if let heading {let font = NSFont.systemFont(ofSize: 12, weight: .semibold)let labelWidth = ceil((heading as NSString).size(withAttributes: [.font: font]).width)- let headingInk: NSColor = selected && expanded != nil ? .selectedMenuItemTextColor : .secondaryLabelColor+ let headingInk = NSColor.secondaryLabelColortext(heading, x: 16, y: 8, width: labelWidth, height: 18,size: 12, weight: .semibold, color: headingInk)if count > 0 {text("\(count)", x: 16 + labelWidth + 7, y: 8, width: clearRect.minX - labelWidth - 27,height: 18, size: 12, color: headingInk)}- if item.isEnabled {- symbol(expanded.map { $0 ? "chevron.down" : "chevron.right" } ?? "xmark",- in: clearRect, color: secondary)+ if isClearControl && item.isEnabled {+ symbol("xmark", in: clearRect, color: secondary)}return}@@ -475,7 +428,7 @@ private final class HarnessStatusMenuRow: NSView {let message = entry["message"] as? String ?? ""if let activity {HarnessNativeActivity.draw(activity.symbol(frame: activityFrame), in: activityRect,- color: !item.isEnabled || selected ? primary : activity.color)+ color: !item.isEnabled || selected ? primary : statusMenuActivityColor(activity.color, appearance: effectiveAppearance))}let titleY: CGFloat = unread ? 6 : 5let timeWidth = ceil((time as NSString).size(withAttributes: [.font: NSFont.systemFont(ofSize: 12)]).width)@@ -518,13 +471,13 @@ private final class HarnessStatusMenuRow: NSView {override func resetCursorRects() {if item?.isEnabled == true {- addCursorRect(heading != nil && expanded == nil ? clearRect : bounds, cursor: .pointingHand)+ addCursorRect(isClearControl ? clearRect : bounds, cursor: .pointingHand)}}override func mouseUp(with event: NSEvent) {let point = convert(event.locationInWindow, from: nil)- guard (heading != nil && expanded == nil ? clearRect : bounds).contains(point) else { return }+ guard (isClearControl ? clearRect : bounds).contains(point) else { return }activate()}@@ -533,8 +486,33 @@ private final class HarnessStatusMenuRow: NSView {guard let item, item.isEnabled, let menu = item.menu else { return false }let index = menu.index(of: item)guard index >= 0 else { return false }- if expanded == nil { menu.cancelTracking() }+ menu.cancelTracking()menu.performActionForItem(at: index)return true}}++/// The terminal palette can be dark while the system menu is light (or vice+/// versa). Keep its status hues, with enough contrast for these small glyphs+/// on the menu's translucent surface. Monochrome colors stay monochrome.+private func statusMenuActivityColor(_ color: NSColor, appearance: NSAppearance) -> NSColor {+ guard let source = color.usingColorSpace(.sRGB) else { return .labelColor }+ let dark = appearance.bestMatch(from: [.darkAqua, .aqua]) == .darkAqua+ let background = NSColor(srgbRed: dark ? 0.16 : 0.72, green: dark ? 0.16 : 0.72,+ blue: dark ? 0.16 : 0.72, alpha: 1)+ func luminance(_ color: NSColor) -> CGFloat {+ func linear(_ c: CGFloat) -> CGFloat { c <= 0.04045 ? c / 12.92 : pow((c + 0.055) / 1.055, 2.4) }+ return 0.2126 * linear(color.redComponent) + 0.7152 * linear(color.greenComponent) + 0.0722 * linear(color.blueComponent)+ }+ let base = luminance(background)+ let target: CGFloat = dark ? 1 : 0+ for step in 0...20 {+ let amount = CGFloat(step) / 20+ let ink = NSColor(srgbRed: source.redComponent * (1 - amount) + target * amount,+ green: source.greenComponent * (1 - amount) + target * amount,+ blue: source.blueComponent * (1 - amount) + target * amount, alpha: 1)+ let light = luminance(ink)+ if (max(light, base) + 0.05) / (min(light, base) + 0.05) >= 4.5 { return ink }+ }+ return dark ? .white : .black+}diff --git a/desktop/macos/Runner/SwarmTitlebar.swift b/desktop/macos/Runner/SwarmTitlebar.swiftindex 2b726bdc4..2b4dc6a8c 100644--- a/desktop/macos/Runner/SwarmTitlebar.swift+++ b/desktop/macos/Runner/SwarmTitlebar.swift@@ -299,7 +299,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {item.representedObject = actionitem.identifier = NSUserInterfaceItemIdentifier(HarnessKeymapMenu.actionPrefix + action)let symbols = [- "new": "plus.square", "newAgent": "plus", "addAgent": "arrow.up.right.square", "newTerminal": "terminal",+ "new": "plus.square", "newAgent": "plus", "sessions": "arrow.up.right.square", "addAgent": "folder", "newTerminal": "terminal","cloneAgent": "plus.square.on.square", "restartAgent": "arrow.clockwise","shareAgent": "square.and.arrow.up","renameActive": "pencil", "closeActive": "xmark",@@ -323,7 +323,8 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {// ellipsis (owner, 2026-09-22). The Dart keymap decides every chord below — applyMenuKeys// rewrites each equivalent here from it. New Terminal (⇧⌘T) stays in the keymap, off the menu.add(file, "New Harness", "n", "newAgent")- add(file, "Open Harness", "o", "addAgent")+ add(file, "Open Harness", "p", "sessions")+ add(file, "Open Project", "o", "addAgent")// ⌘⇧N: another agent like the focused pane's, fresh conversation (Dart: `agent.clone`).add(file, "Clone Harness", "n", "cloneAgent", [.command, .shift])// ⌘⇧E: the pane's harness starts again where it is (Dart: `agent.restart`).@@ -352,7 +353,6 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {}if let view = main.item(withTitle: "View")?.submenu {view.addItem(.separator())- add(view, "Harnesses", "p", "sessions")add(view, "Harnesses Needing Input…", "i", "notifications", [.command, .shift])add(view, "Machines", "m", "machineList")add(view, "Models", "i", "models")@@ -1867,7 +1867,7 @@ private final class SwarmTabStrip: NSView {searchButton.isEnabled = falsesearchButton.target = selfsearchButton.action = #selector(openSearch)- searchButton.setAccessibilityLabel("Search harnesses")+ searchButton.setAccessibilityLabel("Open Harness")addSubview(searchButton)storeButton.isBordered = falsestoreButton.title = "Harness Store"@@ -2034,7 +2034,7 @@ private final class SwarmTabStrip: NSView {storeButton.isEnabled = actionsEnabledsearchButton.foreground = palette.navigationForegroundsearchButton.isEnabled = actionsEnabled- searchButton.toolTip = state["searchTooltip"] as? String ?? "Search harnesses"+ searchButton.toolTip = state["searchTooltip"] as? String ?? "Open Harness"searchButton.setAccessibilityHelp(searchButton.toolTip)storeButton.toolTip = state["storeTooltip"] as? String ?? "Explore Harness Store"storeButton.setAccessibilityHelp(storeButton.toolTip)diff --git a/desktop/test/activity_evidence_test.dart b/desktop/test/activity_evidence_test.dartnew file mode 100644index 000000000..e21eb3b28--- /dev/null+++ b/desktop/test/activity_evidence_test.dart@@ -0,0 +1,175 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/agent_activity.dart';+import 'package:harness/state/app_state.dart';+import 'package:harness/state/harness_activity.dart';+import 'package:harness/state/status_menu.dart';++import 'swarm_state_test.dart' show createApp;++const row = {+ 'id': 'a0',+ 'sessionId': 's',+ 'name': 'cmd p',+ 'engine': 'codex',+ 'terminal': {'available': true},+};+Map<String, Object> evidence(+ String state,+ int revision, {+ String epoch = 'daemon',+ int ms = 1000,+}) => {+ 'state': state,+ 'epoch': epoch,+ 'revision': revision,+ 'validForMs': state == 'working' ? ms : 0,+};+Future<void> sync(AppNotifier app, [Map<String, Object>? activity]) =>+ app.handleMachineEventForTest('m', {+ 'type': 'agent_synced',+ 'payload': {+ 'agent': {...row, if (activity != null) 'activity': activity},+ },+ });+Future<void> frame(+ AppNotifier app,+ String type, {+ Map<String, Object>? activity,+ bool replay = false,+ String session = 's',+}) => app.handleMachineEventForTest('m', {+ 'type': type,+ 'replay': replay,+ 'payload': {+ 'agentId': 'a0',+ 'sessionId': session,+ if (activity != null) 'activity': activity,+ },+});++void main() {+ TestWidgetsFlutterBinding.ensureInitialized();+ testWidgets('duplicate packets and snapshots never extend a working lease', (+ tester,+ ) async {+ final app = createApp(connected: true);+ addTearDown(app.dispose);+ app.rememberOpenedHarness('m', 'a0');+ final working = evidence('working', 1);+ await sync(app, working);+ expect(statusMenuWorkingEntries(app), hasLength(1));+ await tester.pump(const Duration(milliseconds: 600));+ await frame(app, 'turn_heartbeat', activity: working);+ await sync(app, working);+ await tester.pump(const Duration(milliseconds: 401));+ expect(statusMenuWorkingEntries(app), isEmpty);+ expect(harnessActivity(app, 'm', 'a0'), HarnessActivity.unknown);+ expect(app.stateOf('m')!.agents.first.terminalAvailable, isTrue);+ expect(app.agentUnread.kindFor('m', 'a0'), isNull);+ await frame(app, 'agent_activity', activity: evidence('working', 2));+ expect(statusMenuWorkingEntries(app), hasLength(1));+ await tester.pump(const Duration(seconds: 2));+ });+ testWidgets(+ 'legacy daemon heartbeats cannot keep an abandoned transcript working',+ (tester) async {+ final app = createApp(connected: true);+ addTearDown(app.dispose);+ await sync(app);+ await frame(app, 'turn_started', replay: true);+ expect(app.agentIsProcessing('m', 'a0'), isFalse);+ await frame(app, 'turn_heartbeat');+ for (var i = 0; i < 6; i++) {+ await tester.pump(const Duration(seconds: 5));+ await frame(app, 'turn_heartbeat');+ }+ expect(harnessActivity(app, 'm', 'a0'), HarnessActivity.unknown);+ await frame(app, 'text_delta');+ expect(harnessActivity(app, 'm', 'a0'), HarnessActivity.working);+ await frame(app, 'turn_ended');+ expect(harnessActivity(app, 'm', 'a0'), HarnessActivity.idle);+ await tester.pump(const Duration(milliseconds: 100));+ },+ );+ test(+ 'replay, old daemon epochs and late ends cannot overwrite new work',+ () async {+ final app = createApp(connected: true);+ addTearDown(app.dispose);+ await sync(app, evidence('unknown', 10));+ await frame(+ app,+ 'turn_started',+ replay: true,+ activity: evidence('unknown', 11),+ );+ expect(harnessActivity(app, 'm', 'a0'), HarnessActivity.unknown);+ await frame(app, 'turn_started', activity: evidence('working', 12));+ await frame(app, 'turn_ended', activity: evidence('idle', 9));+ expect(app.agentIsProcessing('m', 'a0'), isTrue);+ await sync(app, evidence('idle', 1, epoch: 'restarted'));+ await frame(app, 'turn_heartbeat', activity: evidence('working', 999));+ expect(app.agentIsProcessing('m', 'a0'), isFalse);+ await frame(+ app,+ 'turn_started',+ activity: evidence('working', 2, epoch: 'restarted'),+ );+ expect(app.agentIsProcessing('m', 'a0'), isTrue);+ await frame(+ app,+ 'agent_activity',+ session: 'old-session',+ activity: evidence('idle', 3, epoch: 'restarted'),+ );+ expect(app.agentIsProcessing('m', 'a0'), isTrue);+ },+ );+ test(+ 'a delayed snapshot cannot restore the conversation it replaced',+ () async {+ final app = createApp(connected: true);+ addTearDown(app.dispose);+ await sync(app, evidence('working', 1));+ await app.handleMachineEventForTest('m', {+ 'type': 'agent_synced',+ 'payload': {+ 'agent': {+ ...row,+ 'sessionId': 'replacement',+ 'activity': evidence('idle', 2),+ },+ },+ });+ await sync(app, evidence('working', 1));+ expect(+ app+ .stateOf('m')!+ .agents+ .firstWhere((agent) => agent.id == 'a0')+ .sessionId,+ 'replacement',+ );+ expect(app.agentIsProcessing('m', 'a0'), isFalse);+ },+ );+ test('malformed evidence is ignored and excessive leases are bounded', () {+ expect(+ AgentActivity.fromJson({+ 'state': 'working',+ 'epoch': 'e',+ 'revision': 1,+ 'validForMs': double.infinity,+ }),+ isNull,+ );+ expect(+ AgentActivity.fromJson(evidence('working', 1, ms: 999999))!.validForMs,+ 30000,+ );+ expect(+ AgentActivity.fromJson({...evidence('idle', 1), 'state': 'mystery'}),+ isNull,+ );+ });+}diff --git a/desktop/test/agent_event_invalidation_test.dart b/desktop/test/agent_event_invalidation_test.dartindex b27cb9c61..d04655407 100644--- a/desktop/test/agent_event_invalidation_test.dart+++ b/desktop/test/agent_event_invalidation_test.dart@@ -1,6 +1,7 @@import 'package:flutter_test/flutter_test.dart';import 'package:harness/core/models.dart';import 'package:harness/state/app_state.dart';+import 'package:harness/state/status_menu.dart';import 'swarm_state_test.dart' show createApp;@@ -21,6 +22,61 @@ Future<void> _sync(AppNotifier app, Map<String, dynamic> raw) =>void main() {TestWidgetsFlutterBinding.ensureInitialized();+ test(+ 'old conversation activity cannot revive a replaced or stopped harness',+ () async {+ final app = createApp(connected: true);+ addTearDown(app.dispose);+ app.rememberOpenedHarness('m', 'a0');+ await _sync(app, _snapshot);+ Future<void> activity(String type, String session) =>+ app.handleMachineEventForTest('m', {+ 'type': type,+ 'agentId': 'a0',+ 'payload': {'agentId': 'a0', 'sessionId': session},+ });++ await activity('turn_heartbeat', 'conversation');+ expect(statusMenuWorkingEntries(app).single['agentId'], 'a0');+ await _sync(app, {..._snapshot, 'sessionId': 'replacement'});+ expect(statusMenuWorkingEntries(app), isEmpty);+ await activity('turn_heartbeat', 'conversation');+ await activity('turn_started', 'conversation');+ expect(statusMenuWorkingEntries(app), isEmpty);++ await activity('turn_started', 'replacement');+ await activity('turn_ended', 'conversation');+ expect(statusMenuWorkingEntries(app).single['sessionId'], 'replacement');+ await _sync(app, {+ ..._snapshot,+ 'sessionId': 'replacement',+ 'status': 'stopped',+ });+ expect(app.agentIsProcessing('m', 'a0'), isFalse);+ await activity('turn_heartbeat', 'replacement');+ expect(app.agentIsProcessing('m', 'a0'), isFalse);+ expect(statusMenuWorkingEntries(app), isEmpty);+ },+ );++ testWidgets(+ 'a working row expires without fresh activity even if the terminal remains open',+ (tester) async {+ final app = createApp(connected: true);+ addTearDown(app.dispose);+ app.rememberOpenedHarness('m', 'a0');+ await _sync(app, _snapshot);+ await app.handleMachineEventForTest('m', {+ 'type': 'turn_heartbeat',+ 'payload': {'agentId': 'a0', 'sessionId': 'conversation'},+ });+ expect(statusMenuWorkingEntries(app), hasLength(1));+ await tester.pump(const Duration(seconds: 13));+ expect(statusMenuWorkingEntries(app), isEmpty);+ expect(app.stateOf('m')!.agents.first.terminalAvailable, isTrue);+ },+ );+test('repeated discovery snapshots keep pane presentation stable', () async {final app = createApp();addTearDown(app.dispose);diff --git a/desktop/test/keymap_host_test.dart b/desktop/test/keymap_host_test.dartindex aac4fb53d..f67c0021b 100644--- a/desktop/test/keymap_host_test.dart+++ b/desktop/test/keymap_host_test.dart@@ -67,6 +67,8 @@ void main() {);});test('the command catalog retains the current direct workspace keys', () {+ expect(harnessCommandById['harnesses.list']!.label, 'Open Harness');+ expect(harnessCommandById['agent.open']!.label, 'Open Project');String? command(String keys, [KeymapContext context = KeymapContext.terminal,diff --git a/desktop/test/linux_menu_bar_test.dart b/desktop/test/linux_menu_bar_test.dartindex bf7f99bba..57cbd3350 100644--- a/desktop/test/linux_menu_bar_test.dart+++ b/desktop/test/linux_menu_bar_test.dart@@ -136,6 +136,10 @@ void main() {await tap(tester, 'menu-bar-file');await tap(tester, 'menu-bar-open-harness');+ expect(swarmCalls.last.method, 'sessions');++ await tap(tester, 'menu-bar-file');+ await tap(tester, 'menu-bar-open-project');expect(swarmCalls.last.method, 'addAgent');await tap(tester, 'menu-bar-file');@@ -169,7 +173,6 @@ void main() {expect(appActions.last, 'increaseTerminalFontSize');for (final (key, action) in [- ('menu-bar-sessions', 'sessions'),('menu-bar-machines', 'machineList'),('menu-bar-models', 'models'),('menu-bar-machine-monitor', 'manageMachines'),diff --git a/desktop/tool/status_menu_checks.swift b/desktop/tool/status_menu_checks.swiftindex aab97f31c..79ad4d70a 100644--- a/desktop/tool/status_menu_checks.swift+++ b/desktop/tool/status_menu_checks.swift@@ -52,7 +52,7 @@ private extension HarnessStatusMenu {try check(activityTimer == nil && view.activity?.mark == "⠋", "Closed menus have the shared Working mark and no clock")menuWillOpen(menu)if !NSWorkspace.shared.accessibilityDisplayShouldReduceMotion {- try check(activityTimer != nil, "Opening expanded Working starts the native clock")+ try check(activityTimer != nil, "Opening Working starts the native clock")}let rect = view.framelet label = view.accessibilityLabel()@@ -64,9 +64,6 @@ private extension HarnessStatusMenu {menuDidClose(menu)update(["enabled": true, "statusMenuEntries": [], "statusMenuWorkingEntries": [running]])menuWillOpen(menu)- click(item("toggleWorking"))- try check(activityTimer == nil && row("Running").isHidden, "Collapsing Working stops its clock")- click(item("toggleWorking"))menuDidClose(menu)try check(activityTimer == nil, "Closing the menu releases its clock")update([:])@@ -80,6 +77,16 @@ let status = HarnessStatusMenu(installStatusItem: false, showWindow: { reveals +emit: { emitted.append(($0, $1)) })do {try status.checkActivityLifecycle()+ let yellow = NSColor(srgbRed: 0.9, green: 0.9, blue: 0.06, alpha: 1)+ let lightQuestion = statusMenuActivityColor(yellow, appearance: NSAppearance(named: .aqua)!).usingColorSpace(.sRGB)!+ let darkQuestion = statusMenuActivityColor(yellow, appearance: NSAppearance(named: .darkAqua)!).usingColorSpace(.sRGB)!+ try check(lightQuestion.redComponent < 0.4 && lightQuestion.greenComponent < 0.4 &&+ abs(darkQuestion.redComponent - yellow.redComponent) < 0.001,+ "The same question hue darkens on a light menu and stays bright on a dark menu")+ let monochrome = statusMenuActivityColor(.white, appearance: NSAppearance(named: .aqua)!).usingColorSpace(.sRGB)!+ try check(abs(monochrome.redComponent - monochrome.greenComponent) < 0.001 &&+ abs(monochrome.greenComponent - monochrome.blueComponent) < 0.001,+ "Adapting menu contrast preserves the monochrome preference")var rows = [fixture("General chat conversation"),fixture("DeepSeek model", project: "No Project", unread: false),fixture("Math addition inquiry", project: "No Project", tabId: nil, offline: true)]@@ -90,7 +97,7 @@ do {(status.row("General chat conversation").view?.frame.height ?? 0) <= 70 &&status.row("General chat conversation").view?.accessibilityLabel()?.contains("reconnect fix") == true,"Compact rows expose the actual message to accessibility")- try check(status.item("clearStatusNotifications").view?.accessibilityLabel()?.contains("Notifications (2)") == true &&+ try check(status.item("clearStatusNotifications").view?.accessibilityLabel()?.contains("Ready (2)") == true &&!status.menu.items.contains { $0.title == "Build" }, "One notification section replaces tab headings")try check(!status.row("Math addition inquiry").isEnabled, "Offline conversations stay visible but disabled")try check(status.row("Math addition inquiry").toolTip?.contains("Offline") == true, "Unavailable state is explained")@@ -98,8 +105,8 @@ do {status.click(status.row("General chat conversation"))try check(emitted.last?.0 == "openStatusHarness" && reveals == 0, "Navigation is sent before revealing the window")status.click(status.item("newAgent"))- status.click(status.item("addAgent"))- try check(emitted.suffix(2).map { $0.0 } == ["newAgent", "addAgent"] && reveals == 2,+ status.click(status.item("sessions"))+ try check(emitted.suffix(2).map { $0.0 } == ["newAgent", "sessions"] && reveals == 2,"New and Open Harness reveal the window and reuse existing actions")try check(!status.menu.items.contains { $0.identifier?.rawValue == "settings" } &&status.item("quit").title == "Quit", "Settings is absent and the exit command is simply Quit")@@ -140,18 +147,18 @@ do {"The next opening reflects the new tab context")status.update(["enabled": false, "statusMenuEntries": rows])- try check(!status.item("newAgent").isEnabled && !status.item("addAgent").isEnabled &&+ try check(!status.item("newAgent").isEnabled && !status.item("sessions").isEnabled &&!status.item("clearStatusNotifications").isEnabled, "A modal disables workspace actions")status.click(status.item("openWindow"))try check(reveals == 3, "Show Harness remains available during a modal")status.update(["enabled": true, "statusMenuEntries": []])- try check(status.menu.items.contains { $0.title == "No unread notifications" } &&+ try check(status.menu.items.contains { $0.title == "All caught up" } &&!status.item("clearStatusNotifications").isEnabled &&- !status.menu.items.contains { $0.identifier?.rawValue == "toggleWorking" },+ !status.menu.items.contains { $0.identifier?.rawValue == "workingHeading" },"An empty inbox is explicit, cannot be cleared and has no empty Working section")let open = status.menu.items.first { $0.title == "Open Harness…" }!status.click(open)- try check(emitted.last?.0 == "addAgent" && reveals == 4,+ try check(emitted.last?.0 == "sessions" && reveals == 4,"Open Harness reveals the window and opens the existing-session picker even with no notifications")let beforeShow = emitted.countstatus.click(status.menu.items.first { $0.title == "Show Harness" }!)@@ -160,7 +167,7 @@ do {status.update([:])try check(!status.menu.items.contains { $0.identifier?.rawValue == "openStatusHarness" }, "Sign-out removes all conversation data")try check(status.item("openWindow").isEnabled && status.item("quit").isEnabled &&- !status.item("addAgent").isEnabled,+ !status.item("sessions").isEnabled,"The signed-out menu still offers Show and Quit, but cannot open the session picker")// Exercise the actual AppKit status button: the displayed number must agree// with the notification rows, with a bare icon after the last read.@@ -215,37 +222,28 @@ do {var working = (0..<7).map { fixture("Working \($0)", unread: false) }status.update(["enabled": true, "statusMenuEntries": (0..<8).map { fixture("News \($0)") },"statusMenuWorkingEntries": working])- try check(status.menu.items.filter { $0.identifier?.rawValue == "openStatusHarness" && !$0.isHidden }.count == 10 &&+ try check(status.menu.items.filter { $0.identifier?.rawValue == "openStatusHarness" && !$0.isHidden }.count == 12 &&status.item("notificationInbox").title == "View all 8 notifications…",- "The glance is bounded, with a route to every unread notification")- let toggle = status.item("toggleWorking")- try check(toggle.title == "Working (7)" && !status.row("Working 0").isHidden,- "Working starts expanded, including after an empty bootstrap")+ "Every working session is inline, alongside the notification inbox route")+ let heading = status.item("workingHeading")+ try check(heading.title == "Working (7)" && !heading.isEnabled && heading.action == nil &&+ heading.view?.accessibilityRole() == .staticText && heading.view?.accessibilityLabel() == "Working (7)" &&+ heading.view?.accessibilityPerformPress() == false,+ "Working is a static heading, with no disclosure action or accessibility hint")+ try check(working.allSatisfy { !status.row($0["agentId"] as! String).isHidden } &&+ status.menu.items.allSatisfy { $0.submenu == nil } &&+ !status.menu.items.contains { ["toggleWorking", "moreWorking"].contains($0.identifier?.rawValue ?? "") },+ "All working rows are visible with no overflow menu")status.menuWillOpen(status.menu)- try check(toggle.view?.accessibilityPerformPress() == true && status.row("Working 0").isHidden,- "Disclosure collapses inline through the accessible native control")- _ = toggle.view?.accessibilityPerformPress()- let overflow = status.item("moreWorking")- try check(overflow.submenu?.items.count == 2, "Additional work stays available without flooding the overview")- func keyEvent(_ code: UInt16) -> NSEvent {- NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: [], timestamp: 0,- windowNumber: 0, context: nil, characters: "", charactersIgnoringModifiers: "", isARepeat: false, keyCode: code)!- }- try check(status.handleWorkingKey(keyEvent(123), item: toggle) && status.row("Working 0").isHidden &&- status.handleWorkingKey(keyEvent(124), item: toggle) && !status.row("Working 0").isHidden,- "Left and Right collapse and expand the working section")- try check(!status.handleWorkingKey(keyEvent(125), item: toggle), "Arrow navigation remains AppKit's")let workingRow = status.row("Working 0")let beforeWorking = emitted.countworking.removeFirst()status.update(["enabled": true, "statusMenuEntries": [fixture("Newer news")], "statusMenuWorkingEntries": working])status.click(workingRow)try check(emitted.count == beforeWorking, "A session that stopped working cannot dispatch a stale working click")- _ = toggle.view?.accessibilityPerformPress()- _ = toggle.view?.accessibilityPerformPress()try check(status.menu.items.contains { $0.title == "News 0" } &&!status.menu.items.contains { $0.title == "Newer news" },- "Toggling Working preserves the open notification snapshot")+ "Live updates preserve the open notification snapshot")let currentWorking = status.row("Working 1")try check(currentWorking.view?.accessibilityPerformPress() == true && emitted.last?.0 == "openStatusHarness" &&(emitted.last?.1 as? [String: Any])?["unread"] as? Bool == false,@@ -253,20 +251,20 @@ do {status.menuDidClose(status.menu)status.menuNeedsUpdate(status.menu)status.update([:])- try check(!status.menu.items.contains { $0.identifier?.rawValue == "toggleWorking" },+ try check(!status.menu.items.contains { $0.identifier?.rawValue == "workingHeading" },"Sign-out removes working data as well as unread messages")let bindings: [[String: Any]] = [- ["keys": ["cmd+shift+k"], "command": "agent.open", "hint": "⇧⌘K", "repeatable": false, "menuAction": "addAgent"],+ ["keys": ["cmd+shift+k"], "command": "harnesses.list", "hint": "⇧⌘K", "repeatable": false, "menuAction": "sessions"],]let map = HarnessNativeKeymap(["version": 1, "contexts": ["workspace": bindings, "terminal": [], "picker": [], "project": []]])!status.updateKeymap(map, context: "workspace")status.update(["enabled": true, "statusMenuEntries": []])- try check(status.item("addAgent").keyEquivalent == "k" &&- status.item("addAgent").keyEquivalentModifierMask == [.command, .shift] &&+ try check(status.item("sessions").keyEquivalent == "k" &&+ status.item("sessions").keyEquivalentModifierMask == [.command, .shift] &&status.item("newAgent").keyEquivalent.isEmpty,"Footer shortcuts follow remapping and unbinding, including after a rebuild")- status.click(status.item("addAgent"))- try check(emitted.last?.0 == "addAgent", "Keymap identifiers preserve the existing Open Harness action")+ status.click(status.item("sessions"))+ try check(emitted.last?.0 == "sessions", "Keymap identifiers preserve the existing Open Harness action")print("Harness status menu passed \(checks) checks")} catch {fputs("Harness status menu failed: \(error)\n", stderr)diff --git a/desktop/tool/status_menu_preview.swift b/desktop/tool/status_menu_preview.swiftindex 78630f60b..cdbc9100f 100644--- a/desktop/tool/status_menu_preview.swift+++ b/desktop/tool/status_menu_preview.swift@@ -24,11 +24,11 @@ let working: [[String: Any]] = []let bindings: [[String: Any]] = [["keys": ["cmd+n"], "command": "agent.new", "hint": "⌘N", "repeatable": false, "menuAction": "newAgent"],- ["keys": ["cmd+o"], "command": "agent.open", "hint": "⌘O", "repeatable": false, "menuAction": "addAgent"],+ ["keys": ["cmd+p"], "command": "harnesses.list", "hint": "⌘P", "repeatable": false, "menuAction": "sessions"],]let map = HarnessNativeKeymap(["version": 1, "contexts": ["workspace": bindings, "terminal": [], "picker": [], "project": []]])!-func render(_ name: String, dark: Bool, entries: [[String: Any]], work: [[String: Any]], expanded: Bool = true,+func render(_ name: String, dark: Bool, entries: [[String: Any]], work: [[String: Any]],highlight: Bool = false) {app.appearance = NSAppearance(named: dark ? .darkAqua : .aqua)let status = HarnessStatusMenu(installStatusItem: false, showWindow: {}, emit: { _, _ in })@@ -38,16 +38,15 @@ func render(_ name: String, dark: Bool, entries: [[String: Any]], work: [[Stringvar row = rowvar activity = row["activity"] as? [String: Any] ?? ["mark": "⠋", "label": "Working", "working": true]let mark = activity["mark"] as? String- activity["color"] = mark == "?" ? (dark ? 0xffe5e510 : 0xff4d2d00)- : working ? (dark ? 0xff11a8cd : 0xff1b7c83) : (dark ? 0xff0dbc79 : 0xff116329)+ // Terminal status colors may come from a dark theme even in a light menu.+ // The native row adapts these same colors to its own effective appearance.+ activity["color"] = mark == "?" ? 0xffe5e510+ : working ? 0xff11a8cd : 0xff0dbc79row["activity"] = activityreturn row}status.update(["enabled": true, "statusMenuEntries": entries.map { styled($0) },"statusMenuWorkingEntries": work.map { styled($0, working: true) }])- if !expanded, let toggle = status.menu.items.first(where: { $0.identifier?.rawValue == "toggleWorking" }) {- _ = toggle.view?.accessibilityPerformPress()- }var captured = falselet timer = Timer(timeInterval: 0.2, repeats: false) { _ inif highlight {@@ -87,7 +86,13 @@ func render(_ name: String, dark: Bool, entries: [[String: Any]], work: [[Stringrender("notification-overview-light", dark: false, entries: notifications, work: working)render("notification-overview-dark", dark: true, entries: notifications, work: working)-render("notification-overview-collapsed", dark: false, entries: notifications, work: working, expanded: false)+let fullWorking = (0..<7).map { index -> [String: Any] in+ var row = working[index % working.count]+ row["agentId"] = "working-\(index)"+ row["title"] = "\(row["title"] as! String) \(index + 1)"+ return row+}+render("notification-overview-all-working", dark: false, entries: [], work: fullWorking)render("notification-overview-empty", dark: false, entries: [], work: [])let long = news("long", String(repeating: "Long session title ", count: 6),String(repeating: "A lengthy question that must wrap and then truncate without covering its time or status mark. ", count: 8),diff --git a/desktop/tool/swarm_titlebar_checks.swift b/desktop/tool/swarm_titlebar_checks.swiftindex d3924bffe..3eaf24279 100644--- a/desktop/tool/swarm_titlebar_checks.swift+++ b/desktop/tool/swarm_titlebar_checks.swift@@ -79,7 +79,7 @@ private extension NSView {private func checkIconTooltipTracking() throws {let button = SwarmIconButton(frame: NSRect(x: 0, y: 0, width: 40, height: 28))- button.toolTip = "Search harnesses · ⌘P"+ button.toolTip = "Open Harness · ⌘P"let tooltipAreas = button.trackingAreastry checkTitlebar(!tooltipAreas.isEmpty, "AppKit installs tooltip tracking for an icon button")for _ in 0..<3 {@@ -1075,7 +1075,7 @@ private extension SwarmTabStrip {func checkTopActions() throws {var state: [String: Any] = ["enabled": true,- "searchTooltip": "Search harnesses · ⌘P", "storeTooltip": "Explore Harness Store · ⌘S",+ "searchTooltip": "Open Harness · ⌘P", "storeTooltip": "Explore Harness Store · ⌘S","tabs": [["id": "work", "name": "Desktop"]], "activeId": "work","focusedContext": ["text": "Office project", "segments": [["text": "Office project"]]]]var calls: [String] = []@@ -1873,7 +1873,7 @@ private extension SwarmTitlebar {try checkTitlebar(newSwarm.keyEquivalent == "t" && newSwarm.toolTip == nil,"Native shortcuts display in the menu without duplicate hover hints")try checkTitlebar(addHarness.keyEquivalent == "o" && addHarness.keyEquivalentModifierMask == [.command],- "The exported keymap keeps Open Harness on Command-O")+ "The exported keymap keeps Open Project on Command-O")for (action, key) in [("splitRight", "r"), ("splitDown", "d")] {let split = agent.items.first(where: { $0.representedObject as? String == action })!try checkTitlebar(split.keyEquivalent == key && split.keyEquivalentModifierMask == [.command],@@ -2082,13 +2082,13 @@ private extension SwarmTitlebar {try checkTitlebar(settings.title == "Settings…" && settings.representedObject as? String == "settings", "Settings stays in the application menu")let agent = main.item(withTitle: "File")!.submenu!let addHarness = agent.items.first(where: { $0.representedObject as? String == "addAgent" })!- try checkTitlebar(addHarness.title == "Open Harness" && addHarness.keyEquivalent == "o" && addHarness.keyEquivalentModifierMask == [.command],- "Open Harness advertises Command-O")+ try checkTitlebar(addHarness.title == "Open Project" && addHarness.keyEquivalent == "o" && addHarness.keyEquivalentModifierMask == [.command],+ "Open Project advertises Command-O")try checkTitlebar(!agent.items.contains { $0.representedObject as? String == "newTerminal" },"New Terminal stays off the File menu; its chord lives in the keymap")let historyMenu = main.item(withTitle: "History")!.submenu!try checkTitlebar(agent.items.contains { $0.title == "Clone Harness" && $0.representedObject as? String == "cloneAgent" }, "Clone Harness preserves its action")- try checkTitlebar(agent.items.map { $0.isSeparatorItem ? "separator" : ($0.representedObject as? String ?? "") } == ["newAgent", "addAgent", "cloneAgent", "restartAgent", "shareAgent", "separator", "new", "renameActive", "closeActive", "separator", "splitRight", "splitDown", "zoomPane", "movePaneToTab", "closePane"], "File groups harness, tab and pane actions, harnesses first")+ try checkTitlebar(agent.items.map { $0.isSeparatorItem ? "separator" : ($0.representedObject as? String ?? "") } == ["newAgent", "sessions", "addAgent", "cloneAgent", "restartAgent", "shareAgent", "separator", "new", "renameActive", "closeActive", "separator", "splitRight", "splitDown", "zoomPane", "movePaneToTab", "closePane"], "File groups harness, tab and pane actions, harnesses first")for (action, title, menu) in [("restartAgent", "Restart Harness", agent),("shareAgent", "Share Harness", agent),@@ -2139,8 +2139,8 @@ private extension SwarmTitlebar {try checkTitlebar(closePaneShortcut.keyEquivalent == "w" && closePaneShortcut.keyEquivalentModifierMask == [.command, .shift], "Close Pane defaults to Command-Shift-W")let commands = edit.submenu!.items.first(where: { $0.representedObject as? String == "commands" })!try checkTitlebar(commands.keyEquivalent == "p" && commands.keyEquivalentModifierMask == [.command, .shift], "Command search keeps its native menu owner")- let harnesses = main.item(withTitle: "View")!.submenu!.items.first { $0.representedObject as? String == "sessions" }!- try checkTitlebar(harnesses.keyEquivalent == "p" && harnesses.keyEquivalentModifierMask == [.command],+ let harnesses = agent.items.first { $0.representedObject as? String == "sessions" }!+ try checkTitlebar(harnesses.title == "Open Harness" && harnesses.keyEquivalent == "p" && harnesses.keyEquivalentModifierMask == [.command],"Command-P keeps harness search; commands use Command-Shift-P")try checkTitlebar(edit.submenu!.items.allSatisfy { $0.representedObject as? String != "jump" }, "Edit has no Navigate action")try checkTitlebar(agent.items.contains { $0.title == "New Tab" && $0.keyEquivalent == "t" && $0.representedObject as? String == "new" }, "New Tab opens the chooser with Command-T")diff --git a/docs/app.md b/docs/app.mdindex 9368f98af..42a585b67 100644--- a/docs/app.md+++ b/docs/app.md@@ -25,10 +25,13 @@ Closing a pane is a view operation; the agent keeps running. **Stop Harness** enand asks first. **Restart Harness** relaunches it in the same pane with the same id, resuming theconversation where the engine supports it.-**Open Harness (⌘O)** is the search: harnesses, tabs, projects, machines, history and commands, fuzzy+**Open Harness (⌘P)** is the search: harnesses, tabs, projects, machines, history and commands, fuzzymatched, with a session preview on the right built from cached recent turns. Type `>` for commandsonly (also ⇧⌘P).+**Open Project (⌘O)** opens the same picker in Projects mode so you can choose a folder and its+harnesses directly.+The **Harness Store** keeps search at the top while you browse. Discover opens with threeillustrated features, then icon collections for coding, new and updated harnesses in thisrelease, and other crafts. A Top rated collection appears once at least two tools havediff --git a/docs/keyboard.md b/docs/keyboard.mdindex 39b6e8ac0..8c47c4e4b 100644--- a/docs/keyboard.md+++ b/docs/keyboard.md@@ -10,8 +10,8 @@ The defaults, in the workspace:| Keys | Action ||---|---|| ⌘T | New Swarm — opens the same quiet welcome page shown at startup. Use ⌘N to create a harness, ⌘P to open one, or ⌘S for the store |-| ⌘O / Ctrl+O (Linux) | Open projects — the unified picker starts in projects (`#`), with projects containing open panes first and alphabetical order within each group |-| ⌘P / Ctrl+P (Linux) | Search harnesses — the unified picker for harnesses, machines (`@`), projects (`#`), models (`:`), and Store (`*`). Opens in the current swarm and tiles its panes, or focuses the harness if already here |+| ⌘O / Ctrl+O (Linux) | Open Project — the unified picker starts in projects (`#`), with projects containing open panes first and alphabetical order within each group |+| ⌘P / Ctrl+P (Linux) | Open Harness — the unified picker for harnesses, machines (`@`), projects (`#`), models (`:`), and Store (`*`). Opens in the current tab and tiles its panes, or focuses the harness if already here || ⇧⌘P / Ctrl+Shift+P (Linux) | Search commands; from a selected picker result, search actions for that item || ⌘R / ⌘D | Split right / down — open the New Pane picker with the requested direction, then choose an existing harness or create one || ⌘N | New Harness — choose an Agent or Harness, Project, and Options, then activate New Harness. Lists filter as you type; Return chooses and Escape returns to the form. Project accepts a folder, a new project name, or a repository. Options include model, permissions, agent profile, branch, and worktree |diff --git a/docs/performance/2026-09-22-desktop-latency.md b/docs/performance/2026-09-22-desktop-latency.mdindex 5c0025676..a44138083 100644--- a/docs/performance/2026-09-22-desktop-latency.md+++ b/docs/performance/2026-09-22-desktop-latency.md@@ -32,7 +32,7 @@ Two complete runs per revision, pooled: 80 measured samples per operation. Milli| Action | Baseline median | Final median | Baseline p95 | Final p95 ||---|---:|---:|---:|---:|| Cmd+N — New Harness | 13.49 | 13.37 | 14.56 | 18.49 |-| Cmd+O — Open Harness | 15.67 | 16.05 | 18.35 | 19.70 |+| Cmd+O picker (now Open Project) | 15.67 | 16.05 | 18.35 | 19.70 || Cmd+P — command picker | 14.68 | 14.85 | 15.24 | 15.22 || Cmd+, — Settings | 12.20 | 12.33 | 13.09 | 13.05 || Cmd+/ — shortcut browser | 153.28 | 18.99 | 154.52 | 22.52 |diff --git a/docs/performance/2026-09-22-primary-workflows.md b/docs/performance/2026-09-22-primary-workflows.mdindex 6290110e4..566146ac8 100644--- a/docs/performance/2026-09-22-primary-workflows.md+++ b/docs/performance/2026-09-22-primary-workflows.md@@ -26,7 +26,7 @@ Three complete runs per revision, pooled: **120 measured samples per action**, p| Action | Baseline median | Picker median | Baseline p95 | Picker p95 ||---|---:|---:|---:|---:|| Cmd+N — New Harness | 13.593 ms | 13.834 ms | 16.067 ms | 16.746 ms |-| Cmd+O — Open Harness | 16.332 ms | 15.675 ms | 20.043 ms | 16.463 ms |+| Cmd+O picker (now Open Project) | 16.332 ms | 15.675 ms | 20.043 ms | 16.463 ms || Cmd+T — New tab | 11.711 ms | 12.190 ms | 16.673 ms | 18.348 ms || Next workspace tab | 19.331 ms | 19.556 ms | 26.742 ms | 26.827 ms |diff --git a/tui/src/activity.rs b/tui/src/activity.rsnew file mode 100644index 000000000..a591012e2--- /dev/null+++ b/tui/src/activity.rs@@ -0,0 +1,84 @@+//! Work evidence has a finite lease. A daemon heartbeat is not, by itself,+//! evidence that its engine is still working.+use std::{collections::HashSet, time::{Duration, Instant}};+use serde_json::Value;++#[derive(Clone, Debug, Default)]+pub struct Activity {+ epoch: Option<String>,+ revision: u64,+ retired: HashSet<String>,+ pub unknown: bool,+ pub until: Option<Instant>,+ pub legacy_heartbeat_seen: bool,+}++impl Activity {+ pub fn reported(&self) -> bool { self.epoch.is_some() }+ pub fn older(&self, value: &Value) -> bool {+ let (Some(epoch), Some(revision)) = (value["epoch"].as_str(), value["revision"].as_u64()) else { return false };+ self.retired.contains(epoch) || (self.epoch.as_deref() == Some(epoch) && revision < self.revision)+ }+ /// None means malformed, duplicate or out of order. Some(bool) is the+ /// accepted working state; unknown does not mean a turn just completed.+ pub fn accept(&mut self, value: &Value, now: Instant) -> Option<bool> {+ let state = value["state"].as_str()?;+ if !matches!(state, "working" | "idle" | "unknown") { return None }+ let epoch = value["epoch"].as_str().filter(|s| !s.is_empty())?;+ let revision = value["revision"].as_u64()?;+ let ms = value["validForMs"].as_f64().filter(|v| v.is_finite() && *v >= 0.0)?.min(30_000.0) as u64;+ if self.retired.contains(epoch) { return None }+ if let Some(prior) = &self.epoch {+ if prior == epoch && revision <= self.revision { return None }+ if prior != epoch { self.retired.insert(prior.clone()); }+ }+ self.epoch = Some(epoch.into()); self.revision = revision;+ let working = state == "working" && ms > 0;+ self.until = working.then(|| now + Duration::from_millis(ms));+ self.unknown = state == "unknown" || (state == "working" && ms == 0);+ Some(working)+ }+ pub fn expired(&mut self, now: Instant) -> bool {+ if self.until.is_some_and(|end| now >= end) {+ self.until = None; self.unknown = true; return true+ }+ false+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;+ fn reading(state: &str, epoch: &str, revision: u64) -> Value {+ json!({"state":state,"epoch":epoch,"revision":revision,"validForMs":1000})+ }+ #[test]+ fn repeated_packets_cannot_renew_work_or_invent_completion() {+ let mut activity = Activity::default(); let now = Instant::now();+ let work = reading("working", "daemon", 1);+ assert_eq!(activity.accept(&work, now), Some(true));+ assert_eq!(activity.accept(&work, now + Duration::from_millis(900)), None);+ assert!(activity.expired(now + Duration::from_millis(1000))); assert!(activity.unknown);+ assert_eq!(activity.accept(&reading("working", "daemon", 2), now), Some(true));+ assert!(!activity.unknown);+ }+ #[test]+ fn old_ends_and_retired_daemons_cannot_replace_current_activity() {+ let mut activity = Activity::default(); let now = Instant::now();+ assert_eq!(activity.accept(&reading("working", "daemon", 9), now), Some(true));+ assert_eq!(activity.accept(&reading("idle", "daemon", 8), now), None);+ assert_eq!(activity.accept(&reading("unknown", "restart", 1), now), Some(false));+ assert_eq!(activity.accept(&reading("working", "daemon", 999), now), None);+ assert!(activity.unknown);+ }+ #[test]+ fn malformed_or_excessive_leases_cannot_hold_work_forever() {+ let mut activity = Activity::default(); let now = Instant::now();+ let mut value = reading("working", "daemon", 1);+ value["validForMs"] = json!(999999);+ assert_eq!(activity.accept(&value, now), Some(true));+ assert!(activity.expired(now + Duration::from_secs(30)));+ assert_eq!(activity.accept(&json!({"state":"working"}), now), None);+ }+}diff --git a/tui/src/app.rs b/tui/src/app.rsindex 32ed48bf1..36acc4c44 100644--- a/tui/src/app.rs+++ b/tui/src/app.rs@@ -1280,6 +1280,12 @@ impl App {for id in ids { self.open_stream(id, false) }}MachineEvent::Failed(error) | MachineEvent::Closed(error) => {+ for agent in self.fleet.agents.values_mut().filter(|a| a.machine_id == machine_id) {+ let unknown = agent.working || agent.activity.unknown;+ agent.working = false;+ agent.activity = crate::activity::Activity::default();+ agent.activity.unknown = unknown;+ }let needs_link = error.code == "NO_PEER_LINK";if let Some(machine) = self.fleet.machine_mut(&machine_id) {machine.reach = if needs_link { Reach::NeedsLink } else if machine.online() { Reach::Error(error.to_string()) } else { Reach::Offline };@@ -1351,6 +1357,14 @@ impl App {fn on_frame(&mut self, machine_id: &str, ty: &str, payload: Value) {// The dial's frames come from this computer's daemon, to the windows on it.if machine_id == self.fleet.local_id && crate::dial::on_frame(self, ty, &payload) { return }+ if payload.get("activity").is_some() {+ if let Some(agent) = self.fleet.event_agent(machine_id, &payload) {+ if let Some(working) = agent.activity.accept(&payload["activity"], Instant::now()) {+ agent.working = working;+ } else if matches!(ty, "turn_ended" | "turn_started") { return }+ }+ }+ if ty == "agent_activity" { return }// ── models: a message to a resting model starts its pane's "Starting up…" ──crate::models::watch_turn(self, machine_id, ty, &payload);match ty {@@ -1375,7 +1389,7 @@ impl App {let id = payload.get("agentId").or_else(|| payload.get("id")).and_then(Value::as_str).unwrap_or("");if let Some(agent) = self.fleet.agents.get_mut(&(machine_id.to_string(), id.to_string())) {agent.status = "stopped".into();- agent.working = false;+ agent.working = false; agent.activity.unknown = false;agent.question = None;}self.relist(machine_id);@@ -1385,8 +1399,14 @@ impl App {let now = fleet::now_ms();// A turn begun (or found running): the state's clock starts, what it says anew.if ty == "turn_started" || !agent.working { agent.since = now; agent.doing = None; agent.said.clear() }- agent.working = true;- agent.last_beat = Some(Instant::now());+ if !agent.activity.reported() && payload["replay"] != true {+ if ty != "turn_heartbeat" { agent.activity.legacy_heartbeat_seen = false; }+ if ty != "turn_heartbeat" || !agent.activity.legacy_heartbeat_seen {+ agent.working = true; agent.activity.unknown = false;+ agent.last_beat = Some(Instant::now());+ agent.activity.legacy_heartbeat_seen = ty == "turn_heartbeat";+ }+ }agent.active_at = now;if ty == "turn_started" {agent.unread = false; agent.errored = false;@@ -1425,7 +1445,7 @@ impl App {let (replay, subagent) = (flag("replay"), flag("subagent"));let aborted = payload.get("aborted").and_then(Value::as_bool).unwrap_or(false);if let Some(agent) = self.fleet.event_agent(machine_id, &payload) {- agent.working = false;+ agent.working = false; agent.activity.unknown = false; agent.activity.until = None;if !subagent { agent.subagents.clear() }agent.active_at = fleet::now_ms();agent.since = agent.active_at;@@ -5717,7 +5737,10 @@ impl App {for pane in self.panes.values_mut() { pane.settle_predictions() }let now = Instant::now();for agent in self.fleet.agents.values_mut() {- if agent.working && agent.last_beat.map(|t| now.duration_since(t) > Duration::from_secs(90)).unwrap_or(true) { agent.working = false }+ if agent.activity.expired(now) { agent.working = false; }+ if !agent.activity.reported() && agent.working && agent.last_beat.map(|t| now.duration_since(t) > Duration::from_secs(30)).unwrap_or(true) {+ agent.working = false; agent.activity.unknown = true;+ }}let due: Vec<String> = self.links.iter().filter(|(_, s)| s.link.is_none() && s.retry_at.map(|t| t <= now).unwrap_or(false)).map(|(id, _)| id.clone()).collect();for id in due {diff --git a/tui/src/fleet.rs b/tui/src/fleet.rsindex b7aaae2c5..3da77969f 100644--- a/tui/src/fleet.rs+++ b/tui/src/fleet.rs@@ -64,6 +64,7 @@ pub struct Agent {pub known_at: Instant,pub active_at: u64,pub working: bool,+ pub activity: crate::activity::Activity,pub last_beat: Option<Instant>,pub question: Option<Question>,pub unread: bool,@@ -213,6 +214,7 @@ pub enum State {Working,Done,Ready,+ Unknown,Starting,Failed,Paused,@@ -234,6 +236,7 @@ impl Agent {if self.working { return State::Working }if self.errored { return State::Failed }if self.unread { return State::Done }+ if self.activity.unknown { return State::Unknown }State::Ready}@@ -282,6 +285,11 @@ pub fn parse_iso(text: &str) -> Option<u64> {}pub fn agent_from(machine_id: &str, row: &Value, previous: Option<&Agent>) -> Agent {+ if let Some(agent) = previous {+ if agent.session_id != s(row, "sessionId") && agent.activity.older(&row["activity"]) { return agent.clone() }+ }+ let activity = previous.map(|p| p.activity.clone()).unwrap_or_default();+ let previous = previous.filter(|agent| agent.session_id == s(row, "sessionId"));let project = row.get("project").cloned().unwrap_or(Value::Null);let launch = row.get("launch").cloned().unwrap_or(Value::Null);let title = s(row, "title");@@ -289,7 +297,7 @@ pub fn agent_from(machine_id: &str, row: &Value, previous: Option<&Agent>) -> Agif name.is_empty() { name = if !title.is_empty() { title } else { s(&project, "name") } }if name.is_empty() { name = s(row, "engine") }let dsh = { let n = s(row, "dshName"); if n.is_empty() { s(row, "dsh") } else { n } };- Agent {+ let mut agent = Agent {machine_id: machine_id.to_string(),id: s(row, "id"),session_id: s(row, "sessionId"),@@ -305,6 +313,7 @@ pub fn agent_from(machine_id: &str, row: &Value, previous: Option<&Agent>) -> Agknown_at: previous.map(|p| p.known_at).unwrap_or_else(Instant::now),// Not `updatedAt`: the daemon restamps every row on each reconcile.active_at: previous.map(|p| p.active_at).unwrap_or(0),+ activity,working: previous.map(|p| p.working).unwrap_or(false),last_beat: previous.and_then(|p| p.last_beat),question: previous.and_then(|p| p.question.clone()),@@ -342,7 +351,10 @@ pub fn agent_from(machine_id: &str, row: &Value, previous: Option<&Agent>) -> Aggrid_base_url: s(&row["grid"], "baseUrl"),grid_state: s(&row["grid"], "state"),grid_note: grid_note(&row["grid"]["note"]),- }+ };+ if let Some(working) = agent.activity.accept(&row["activity"], Instant::now()) { agent.working = working; }+ if matches!(agent.status.as_str(), "stopped" | "offline") { agent.working = false; agent.activity.unknown = false; }+ agent}/// TodoWrite's list: each item's words (its present-tense form while it is in progress) and state.@@ -530,7 +542,10 @@ impl Fleet {pub fn event_agent(&mut self, machine_id: &str, payload: &Value) -> Option<&mut Agent> {let id = s(payload, "agentId");if !id.is_empty() && self.agents.contains_key(&(machine_id.to_string(), id.clone())) {- return self.agents.get_mut(&(machine_id.to_string(), id));+ let agent = self.agents.get_mut(&(machine_id.to_string(), id))?;+ let session = payload.get("sessionId").or_else(|| payload.get("dbSessionId")).and_then(Value::as_str);+ if agent.status == "stopped" || session.is_some_and(|s| !agent.session_id.is_empty() && s != agent.session_id) { return None }+ return Some(agent);}let session = { let x = s(payload, "sessionId"); if x.is_empty() { s(payload, "dbSessionId") } else { x } };if session.is_empty() { return None }@@ -542,7 +557,7 @@ impl Fleet {/// starting, idle, paused, offline — within the first three and working, the one that has/// waited (or run) longest first; the rest most recent first.pub fn ranked(&self) -> Vec<&Agent> {- let bucket = |st: State| match st { State::NeedsInput => 0, State::Failed => 1, State::Done => 2, State::Working => 3, State::Starting => 4, State::Ready => 5, State::Paused => 6, State::Offline => 7 };+ let bucket = |st: State| match st { State::NeedsInput => 0, State::Failed => 1, State::Done => 2, State::Working => 3, State::Starting => 4, State::Unknown => 5, State::Ready => 6, State::Paused => 7, State::Offline => 8 };// Each one's key once (the clock read once for all: a comparison that read it again could// order two alike harnesses both ways, which a sort must never see).let now = now_ms();@@ -729,3 +744,24 @@ mod answer_tests {assert_eq!(answer_text(&q(false), " "), None);}}++#[cfg(test)]+mod activity_evidence_tests {+ use super::*;+ use serde_json::json;+ #[test]+ fn late_snapshot_cannot_restore_an_old_conversation() {+ let old = json!({"id":"agent","sessionId":"old","activity":{"state":"working","epoch":"daemon","revision":1,"validForMs":30000}});+ let new = json!({"id":"agent","sessionId":"new","activity":{"state":"idle","epoch":"daemon","revision":2,"validForMs":0}});+ let first = agent_from("m", &old, None);+ let replacement = agent_from("m", &new, Some(&first));+ let late = agent_from("m", &old, Some(&replacement));+ assert_eq!(late.session_id, "new"); assert!(!late.working);+ }+ #[test]+ fn unavailable_activity_is_neither_working_nor_done() {+ let row = json!({"id":"agent","sessionId":"s","activity":{"state":"unknown","epoch":"daemon","revision":1,"validForMs":0}});+ let agent = agent_from("m", &row, None);+ assert_eq!(agent.state(None), State::Unknown); assert!(!agent.unread);+ }+}diff --git a/tui/src/format.rs b/tui/src/format.rsindex 14a2a9d6e..e3ed76cdb 100644--- a/tui/src/format.rs+++ b/tui/src/format.rs@@ -1687,7 +1687,7 @@ fn harness_value(app: &App, machine: &str, id: &str, key: &str) -> Option<Val> {/// failed, paused, offline.fn state_word(s: crate::fleet::State) -> &'static str {use crate::fleet::State::*;- match s { NeedsInput => "needs", Working => "working", Done => "done", Ready => "idle", Starting => "starting", Failed => "failed", Paused => "paused", Offline => "offline" }+ match s { NeedsInput => "needs", Working => "working", Done => "done", Unknown => "unknown", Ready => "idle", Starting => "starting", Failed => "failed", Paused => "paused", Offline => "offline" }}/// `#{window_raw_flags}`: `#` activity, `!` bell, `~` silence, `*` current, `-` last, `M` thediff --git a/tui/src/main.rs b/tui/src/main.rsindex 9612ccaba..7b40c74c0 100644--- a/tui/src/main.rs+++ b/tui/src/main.rs@@ -2,6 +2,7 @@//! uses: every harness on every machine (relay + P2P live in the daemon), in tabs and panes that//! are the account's desk, driven with tmux's keys.+mod activity;mod app;mod capture;mod tree;diff --git a/tui/src/modal.rs b/tui/src/modal.rsindex f3b6625f4..fcebdb55a 100644--- a/tui/src/modal.rs+++ b/tui/src/modal.rs@@ -273,7 +273,7 @@ pub fn agent_rows(app: &App, filter: Filter, machine: Option<&str>, project: Opt// request, and its state in words ('failed, 'done, 'waiting, 'working, 'idle).let words = match state {State::NeedsInput => "waiting needs-you", State::Failed => "failed", State::Done => "done finished", State::Working => "working",- State::Starting => "starting", State::Ready => "idle", State::Paused => "paused", State::Offline => "offline",+ State::Starting => "starting", State::Unknown => "status unavailable", State::Ready => "idle", State::Paused => "paused", State::Offline => "offline",};// Its pull request's state in words too: 'pr, 'open, 'merged.let pr_words = a.pr.as_ref().map(|p| format!("pr {}", p.state.to_lowercase())).unwrap_or_default();diff --git a/tui/src/preview.rs b/tui/src/preview.rsindex eecede671..0fd593f93 100644--- a/tui/src/preview.rs+++ b/tui/src/preview.rs@@ -42,7 +42,7 @@ fn harness(app: &App, machine_id: &str, agent_id: &str) -> Vec<Line<'static>> {let state = app.fleet.state_of(a);let (word, color) = match state {State::NeedsInput => ("waiting on you", Color::Yellow), State::Working => ("working", Color::Cyan), State::Done => ("finished a turn", Color::Green),- State::Ready => ("idle", Color::Green), State::Starting => ("starting", Color::Yellow), State::Failed => (if a.launch == "failed" { "failed to start" } else { "failed" }, Color::Red),+ State::Unknown => ("status unavailable", Color::DarkGray), State::Ready => ("idle", Color::Green), State::Starting => ("starting", Color::Yellow), State::Failed => (if a.launch == "failed" { "failed to start" } else { "failed" }, Color::Red),State::Paused => ("paused — enter resumes it", Color::DarkGray), State::Offline => ("offline", Color::DarkGray),};let home = app.homes.get(machine_id).cloned().unwrap_or_else(|| std::env::var("HOME").unwrap_or_default());diff --git a/tui/src/theme.rs b/tui/src/theme.rsindex 7d49371c8..d1bca09d3 100644--- a/tui/src/theme.rs+++ b/tui/src/theme.rs@@ -1290,6 +1290,7 @@ fn state_mark_raw(state: State, tick: u64) -> (&'static str, &'static str, ColorState::NeedsInput => ("?", "needs you", ATTENTION),State::Working => (spinner(tick), "working", ACCENT_SOFT),State::Done => ("✓", "done", ONLINE),+ State::Unknown => ("◌", "status unavailable", MUTED),State::Ready => ("·", "idle", MUTED),State::Starting => (spinner(tick), "starting", WARN),State::Failed => ("✗", "failed", DANGER),@@ -1301,7 +1302,7 @@ fn state_mark_raw(state: State, tick: u64) -> (&'static str, &'static str, Color/// The most urgent of several states (a window's panes): needs you, failed, done, working,/// starting, idle, paused, offline.pub fn most_urgent(states: impl Iterator<Item = State>) -> Option<State> {- let rank = |s: &State| match s { State::NeedsInput => 0, State::Failed => 1, State::Done => 2, State::Working => 3, State::Starting => 4, State::Ready => 5, State::Paused => 6, State::Offline => 7 };+ let rank = |s: &State| match s { State::NeedsInput => 0, State::Failed => 1, State::Done => 2, State::Working => 3, State::Starting => 4, State::Unknown => 5, State::Ready => 6, State::Paused => 7, State::Offline => 8 };states.min_by_key(rank)}