diff --git a/docs/reference/agent-status-store.md b/docs/reference/agent-status-store.md index c82a1ea39df5..f69ba5109f75 100644 --- a/docs/reference/agent-status-store.md +++ b/docs/reference/agent-status-store.md @@ -12,7 +12,7 @@ this order, each independently shippable: 3. shared: one worktree-status rollup and one freshness rule for every reader. The PR that carries this document is PR 1a. Sections below are grouped under -the step that delivers them; PR 1a, PR 1b, PR 2a and PR 2b have landed. +the step that delivers them; PR 1a, PR 1b, PR 2a, PR 2b and PR 3 have landed. ## The problem this solves @@ -595,11 +595,99 @@ rendered one session twice and shifted the chat's elapsed clock. ## PR 3: one rollup, one clock -The worktree card status is derived three times: `lib/worktree-status.ts` in +The worktree card status was derived three times: `lib/worktree-status.ts` in the renderer, `runtime-worktree-status-projection.ts` in main, and -`agent-row-display.ts` in mobile, which hand-copies the 30-minute constant. -PR 3 moves the rollup and the decay into `src/shared` and makes all three -call it. +`agent-row-display.ts` in mobile, which hand-copied the 30-minute constant. +PR 3 moved the rollup and the decay into `src/shared`. + +### What landed + +Two modules, beside `agent-status-freshness.ts`: + +| Module | Owns | Called by | +| ------------------------------------ | ------------------------------------------------------------------------- | --------------------------------------------------------------------------- | +| `shared/agent-status-row-display.ts` | the staleness decay and where a stale row lands (`idle` / `unverifiable`) | the sidebar row builder, mobile's row dot | +| `shared/worktree-status-rollup.ts` | the priority ladder a worktree's signals are rolled up over | the renderer's `resolveWorktreeStatus`, main's `mergeWorktreeSummaryStatus` | + +The ladder is `inactive < active < done < interrupted < monitoring < working < +permission`. `RuntimeWorktreeStatus` on the wire is the subset without +`interrupted` and `monitoring`, and its relative order is unchanged, so +`worktree ps` rolls up exactly as before. The renderer's hand-ordered if-chain +became a fold over that ladder; main's private priority table was deleted. + +### The three copies did not share the same two things + +The plan implied all three copies do both jobs. They do not. Mobile has no +worktree rollup at all — it renders the `status` the host already computed on +the `worktree ps` summary — so mobile joins on the decay only. The renderer and +main join on both. + +### What changed on mobile + +Unifying was not a pure refactor for the phone. Two user-visible corrections, +both bringing mobile to the behavior the desktop has always had: + +- **A host-owned structured row no longer decays.** Mobile ignored + `structuredHostOwned`, so an owned row read as idle on the phone after 30 + minutes while the desktop kept it working. The structured host still runs + that row's provider child, so silence there is not evidence it stopped. +- **A hydrated unconfirmed row never reads as active.** Mobile ignored + `restoredUnconfirmed`. This is a contract change rather than a live one: + `collectRuntimeWorktreePtyAgentSources` drops those rows before they reach + the wire, so today's host never sends one. The rule now holds regardless. + +### The evidence clock does not reach mobile, and should not + +The plan expected mobile to start measuring against the evidence clock. It does +not, and the wire is the reason: `RuntimeWorktreeAgentRow` carries neither +`evidenceObservedAt` nor `mirroredEvidenceReceivedAt`, so the shared rule falls +through to `updatedAt` — which is the clock mobile already used. The row is +unchanged on the wire. + +Forwarding those stamps would also be the wrong fix. Mobile is a replica on a +different machine, so it subtracts host stamps from its own `now`; both +timestamps are the host's, and swapping one for the other trades the reconnect +error for the same clock-skew error. A phone-side receipt clock, not a wider +row, is what that would need. Every field the rule reads is optional and absent +degrades to the ordinary window, which is what keeps an older host safe. + +### Two things the plan got wrong + +- **Mobile was never walled off from `src/shared`.** The local constant carried + a comment claiming a runtime-value import from a root `.ts` breaks mobile's + vitest transform. It does not: `metro.config.js` already watches + `../src/shared`, about twenty mobile modules already value-import from it, + and the mobile suite passes with the real import. The comment was a + rationalisation, and it had already drifted — it cited the constant's old + home in `agent-status-types.ts`. +- **`mergeWorktreeStatus` in main was dead.** Zero callers in production or + tests. It was deleted rather than rewired. + +### A gap this found + +Nothing pinned the `worktree ps` rollup order. A ladder mutated so that +`permission` no longer outranked `working` passed the entire +`orca-runtime.test.ts` aggregator (1262 tests) and the whole sidebar suite; +only `renderer/src/lib` caught it. `runtime-worktree-status-projection.test.ts` +now pins main's side directly. + +### Still duplicated + +- The `AgentDotState` union and `agentStateLabel` are still written twice, in + `components/AgentStateDot.tsx` and in mobile's `agent-row-display.ts`. That + is presentation vocabulary living in a React component, and the desktop union + has three members mobile does not render; moving it is not this step's job. +- `selectFreshExplicitAgentStatus` in `runtime-hook-agent-row-selection.ts` + still hand-rolls the window against `updatedAt`, ignoring the evidence clock + and the host-owned exemption. It is a fourth decay site, outside the three + this step named, and routing it through the shared rule would change main's + behavior — which this step was required not to do. + +### Why this was last + +Only after PR 2b did all three read equivalent rows. Sharing the rollup before +that would have unified the arithmetic over inputs that still disagreed, which +hides the disagreement rather than removing it. ## What does not change diff --git a/mobile/src/worktree/agent-row-display.test.ts b/mobile/src/worktree/agent-row-display.test.ts index ee872e40f266..1247c5e9bbeb 100644 --- a/mobile/src/worktree/agent-row-display.test.ts +++ b/mobile/src/worktree/agent-row-display.test.ts @@ -57,6 +57,52 @@ describe('agentDotState', () => { 'interrupted' ) }) + + it('keeps a host-owned structured row active past the window', () => { + // The structured session host still runs this row's provider child, so silence is not + // evidence it stopped. Mobile ignored `structuredHostOwned` before the decay was shared + // and decayed this row to idle while the desktop kept it. + const stale = AGENT_STATUS_STALE_AFTER_MS + 1 + expect( + agentDotState(row({ state: 'working', updatedAt: 0, structuredHostOwned: true }), stale) + ).toBe('working') + expect( + agentDotState( + row({ + state: 'working', + workingMode: 'monitoring', + updatedAt: 0, + structuredHostOwned: true + }), + stale + ) + ).toBe('monitoring') + expect( + agentDotState(row({ state: 'blocked', updatedAt: 0, structuredHostOwned: true }), stale) + ).toBe('blocked') + // The exemption is the owned flag, not the age: an unowned row of the same age still decays. + expect(agentDotState(row({ state: 'working', updatedAt: 0 }), stale)).toBe('idle') + }) + + it('never shows a hydrated unconfirmed row as active, however recent', () => { + // A restored row may describe a turn that ended while nothing was listening. Today's host + // filters these out before they reach the wire, so this pins the contract, not a live path. + expect( + agentDotState(row({ state: 'working', updatedAt: 0, restoredUnconfirmed: true }), 1) + ).toBe('idle') + expect( + agentDotState(row({ state: 'blocked', updatedAt: 0, restoredUnconfirmed: true }), 1) + ).toBe('idle') + }) + + it('degrades to the plain window for a row from an older host', () => { + // An older host sends neither `structuredHostOwned` nor any evidence stamp. Absence must + // mean the ordinary updatedAt window — never "fresh", and never a throw. + const oldHostRow = row({ state: 'working', updatedAt: 0 }) + expect(oldHostRow.structuredHostOwned).toBeUndefined() + expect(agentDotState(oldHostRow, AGENT_STATUS_STALE_AFTER_MS)).toBe('working') + expect(agentDotState(oldHostRow, AGENT_STATUS_STALE_AFTER_MS + 1)).toBe('idle') + }) }) describe('agentDisplayLabel', () => { diff --git a/mobile/src/worktree/agent-row-display.ts b/mobile/src/worktree/agent-row-display.ts index c678b522a152..6499248b9431 100644 --- a/mobile/src/worktree/agent-row-display.ts +++ b/mobile/src/worktree/agent-row-display.ts @@ -1,10 +1,7 @@ import type { RuntimeWorktreeAgentRow } from '../../../src/shared/runtime-types' +import { resolveAgentRowDisplayState } from '../../../src/shared/agent-status-row-display' -// Mirrors the desktop AGENT_STATUS_STALE_AFTER_MS (src/shared/agent-status-types.ts: -// 30 min). Defined locally rather than imported because a runtime-value import -// from a root .ts breaks mobile's vitest transform (no tsconfig in the -// mobile-only checkout); root type-only imports stay fine. -export const AGENT_STATUS_STALE_AFTER_MS = 30 * 60 * 1000 +export { AGENT_STATUS_STALE_AFTER_MS } from '../../../src/shared/agent-status-freshness' // Mirrors the desktop AgentStateDot vocabulary. The wire `state` is the agent // status state; 'blocked'/'waiting' read as attention states, 'done' as @@ -18,27 +15,37 @@ export type AgentDotState = | 'idle' | 'interrupted' +/** + * The dot this row shows. The staleness decay is the shared one + * (src/shared/agent-status-row-display.ts) so the phone and the desktop agree on when an + * agent that stopped reporting stops reading as active; only the dot vocabulary is local. + * + * `worktree ps` rows carry no live-PTY evidence, so `hasLivePty` stays unset and a decayed + * row lands on `idle` — the desktop's `unverifiable` claims liveness this reader cannot see. + */ export function agentDotState( - row: Pick, + row: Pick< + RuntimeWorktreeAgentRow, + | 'state' + | 'workingMode' + | 'interrupted' + | 'updatedAt' + | 'restoredUnconfirmed' + | 'structuredHostOwned' + >, now: number ): AgentDotState { if (row.interrupted) { return 'interrupted' } - switch (row.state) { - case 'blocked': - case 'waiting': - // Why: an agent that exits without a final report would otherwise read as - // active forever. Decay a stale active state to idle, matching desktop's - // renderer-side staleness decay (worktree-agent-rows.ts). - return now - row.updatedAt > AGENT_STATUS_STALE_AFTER_MS ? 'idle' : row.state + const displayState = resolveAgentRowDisplayState(row, now) + switch (displayState) { case 'working': - if (now - row.updatedAt > AGENT_STATUS_STALE_AFTER_MS) { - return 'idle' - } return row.workingMode === 'monitoring' ? 'monitoring' : 'working' + case 'blocked': + case 'waiting': case 'done': - return 'done' + return displayState } return 'idle' } diff --git a/src/main/runtime/runtime-worktree-status-projection.test.ts b/src/main/runtime/runtime-worktree-status-projection.test.ts new file mode 100644 index 000000000000..0c1428cc4bc8 --- /dev/null +++ b/src/main/runtime/runtime-worktree-status-projection.test.ts @@ -0,0 +1,73 @@ +import { describe, expect, it } from 'vitest' +import type { RuntimeWorktreePsSummary, RuntimeWorktreeStatus } from '../../shared/runtime-types' +import { mergeWorktreeSummaryStatus } from './runtime-worktree-status-projection' + +/** The rollup reads only these two fields, so a focused summary keeps the case readable. */ +function summary( + status: RuntimeWorktreeStatus, + workingMode?: RuntimeWorktreePsSummary['workingMode'] +): RuntimeWorktreePsSummary { + return { status, ...(workingMode ? { workingMode } : {}) } as RuntimeWorktreePsSummary +} + +describe('mergeWorktreeSummaryStatus', () => { + it('promotes a worktree to the highest-ranked signal it holds', () => { + // Pins the `worktree ps` ordering against a reordered shared ladder: the user-actionable + // signal must outrank live work, and live work must outrank a terminal or idle one. + const cases: readonly [RuntimeWorktreeStatus, RuntimeWorktreeStatus, RuntimeWorktreeStatus][] = + [ + ['working', 'permission', 'permission'], + ['done', 'working', 'working'], + ['active', 'done', 'done'], + ['inactive', 'active', 'active'], + ['inactive', 'permission', 'permission'] + ] + for (const [current, next, expected] of cases) { + const s = summary(current) + mergeWorktreeSummaryStatus(s, next) + expect(s.status, `${current} + ${next}`).toBe(expected) + } + }) + + it('never demotes a worktree to a lower-ranked signal', () => { + const cases: readonly [RuntimeWorktreeStatus, RuntimeWorktreeStatus][] = [ + ['permission', 'working'], + ['working', 'done'], + ['done', 'active'], + ['active', 'inactive'] + ] + for (const [current, next] of cases) { + const s = summary(current) + mergeWorktreeSummaryStatus(s, next) + expect(s.status, `${current} + ${next}`).toBe(current) + } + }) + + it('carries workingMode only while the winning signal is monitoring work', () => { + const promoted = summary('active') + mergeWorktreeSummaryStatus(promoted, 'working', 'monitoring') + expect(promoted.workingMode).toBe('monitoring') + + const foreground = summary('active') + mergeWorktreeSummaryStatus(foreground, 'working') + expect(foreground.workingMode).toBeUndefined() + + // A promotion past working drops the discriminator with it. + const escalated = summary('working', 'monitoring') + mergeWorktreeSummaryStatus(escalated, 'permission') + expect(escalated.workingMode).toBeUndefined() + }) + + it('lets a foreground working signal clear monitoring at equal rank', () => { + // Why: two panes in one worktree both report working; one is foreground, so the worktree + // is not merely monitoring even though the rank does not move. + const s = summary('working', 'monitoring') + mergeWorktreeSummaryStatus(s, 'working') + expect(s.status).toBe('working') + expect(s.workingMode).toBeUndefined() + + const stays = summary('working', 'monitoring') + mergeWorktreeSummaryStatus(stays, 'working', 'monitoring') + expect(stays.workingMode).toBe('monitoring') + }) +}) diff --git a/src/main/runtime/runtime-worktree-status-projection.ts b/src/main/runtime/runtime-worktree-status-projection.ts index 7e8244a8836c..3359d4cd23a5 100644 --- a/src/main/runtime/runtime-worktree-status-projection.ts +++ b/src/main/runtime/runtime-worktree-status-projection.ts @@ -14,14 +14,7 @@ import type { RuntimeWorktreeStatus } from '../../shared/runtime-types' import type { TuiAgent } from '../../shared/tui-agent' - -const WORKTREE_STATUS_PRIORITY: Record = { - inactive: 0, - active: 1, - done: 2, - working: 3, - permission: 4 -} +import { worktreeStatusRank } from '../../shared/worktree-status-rollup' type LeafStatusRecord = { ptyId: string | null @@ -186,21 +179,14 @@ export function mapExplicitAgentStateToRuntimeTerminalStatus( } } -export function mergeWorktreeStatus( - current: RuntimeWorktreeStatus, - next: RuntimeWorktreeStatus -): RuntimeWorktreeStatus { - return WORKTREE_STATUS_PRIORITY[next] > WORKTREE_STATUS_PRIORITY[current] ? next : current -} - export function mergeWorktreeSummaryStatus( summary: RuntimeWorktreePsSummary, next: RuntimeWorktreeStatus, nextWorkingMode?: RuntimeWorktreePsSummary['workingMode'] ): void { - const currentPriority = WORKTREE_STATUS_PRIORITY[summary.status] - const nextPriority = WORKTREE_STATUS_PRIORITY[next] - if (nextPriority > currentPriority) { + const currentRank = worktreeStatusRank(summary.status) + const nextRank = worktreeStatusRank(next) + if (nextRank > currentRank) { summary.status = next if (next === 'working' && nextWorkingMode === 'monitoring') { summary.workingMode = 'monitoring' @@ -209,7 +195,7 @@ export function mergeWorktreeSummaryStatus( } return } - if (nextPriority === currentPriority && next === 'working') { + if (nextRank === currentRank && next === 'working') { if (nextWorkingMode === 'monitoring') { summary.workingMode = 'monitoring' } else { diff --git a/src/renderer/src/components/sidebar/worktree-agent-rows.ts b/src/renderer/src/components/sidebar/worktree-agent-rows.ts index 009c562447fd..8c81586e9a2d 100644 --- a/src/renderer/src/components/sidebar/worktree-agent-rows.ts +++ b/src/renderer/src/components/sidebar/worktree-agent-rows.ts @@ -17,7 +17,7 @@ import type { TerminalTab } from '../../../../shared/terminal-tab-types' import { resolveRuntimePaneTitleLeafId } from '@/lib/runtime-pane-title-leaf-id' -import { resolveDecayedAgentRowState } from '@/lib/agent-row-decay-state' +import { resolveAgentRowDisplayState } from '@/lib/agent-row-decay-state' import { tabHasLivePty } from '@/lib/tab-has-live-pty' import { buildTitleDerivedAgentRows } from './worktree-title-derived-agent-rows' import { buildSubagentChildRows } from './worktree-subagent-child-rows' @@ -174,11 +174,6 @@ export function buildWorktreeAgentRows(args: { for (const entry of explicitEntries) { const rowEntry = entryWithRuntimeOrchestration(entry, args.runtimeAgentOrchestrationByPaneKey) const isFresh = isExplicitAgentStatusFresh(rowEntry, args.now, AGENT_STATUS_STALE_AFTER_MS) - const shouldDecay = - !isFresh && - (rowEntry.state === 'working' || - rowEntry.state === 'blocked' || - rowEntry.state === 'waiting') const startedAt = effectiveWorktreeAgentRowStartedAt(rowEntry) rows.push({ paneKey: rowEntry.paneKey, @@ -186,7 +181,7 @@ export function buildWorktreeAgentRows(args: { tab, agentType: resolveRowAgentType(rowEntry, tab), rowSource: 'live', - state: shouldDecay ? resolveDecayedAgentRowState(rowEntry, hasLivePty) : rowEntry.state, + state: resolveAgentRowDisplayState(rowEntry, args.now, { hasLivePty }), startedAt }) rows.push(...buildSubagentChildRows({ parentEntry: rowEntry, tab, parentIsFresh: isFresh })) @@ -219,9 +214,6 @@ export function buildWorktreeAgentRows(args: { continue } const isFresh = isExplicitAgentStatusFresh(rowEntry, args.now, AGENT_STATUS_STALE_AFTER_MS) - const shouldDecay = - !isFresh && - (rowEntry.state === 'working' || rowEntry.state === 'blocked' || rowEntry.state === 'waiting') rows.push({ paneKey: rowEntry.paneKey, entry: rowEntry, @@ -230,9 +222,9 @@ export function buildWorktreeAgentRows(args: { rowSource: 'live', // Why: this row's tab is synthesized because no tab for it exists in this renderer, // so there is no live-PTY evidence to hold — the decay destination is always `idle`. - state: shouldDecay - ? resolveDecayedAgentRowState(rowEntry, tabHasLivePty(ptyIdsByTabId, tab.id)) - : rowEntry.state, + state: resolveAgentRowDisplayState(rowEntry, args.now, { + hasLivePty: tabHasLivePty(ptyIdsByTabId, tab.id) + }), startedAt }) rows.push(...buildSubagentChildRows({ parentEntry: rowEntry, tab, parentIsFresh: isFresh })) diff --git a/src/renderer/src/lib/agent-row-decay-state.ts b/src/renderer/src/lib/agent-row-decay-state.ts index 10f62a34ca6c..daa88ba3787b 100644 --- a/src/renderer/src/lib/agent-row-decay-state.ts +++ b/src/renderer/src/lib/agent-row-decay-state.ts @@ -1,34 +1,15 @@ import { agentStatusEvidenceObservedAt, - type AgentStatusEntry, - type AgentStatusState + type AgentStatusEntry } from '../../../shared/agent-status-types' -/** Row states: the hook-reported statuses plus the two Orca derives when an entry goes stale. */ -export type AgentRowState = AgentStatusState | 'idle' | 'unverifiable' - -type DecayInput = Pick - -/** - * Where a stale non-`done` entry decays to. - * - * Silence is not evidence (docs/reference/ssh-execution-boundary.md), so the destination - * splits on the liveness Orca actually holds: a pane whose PTY is still in the live-PTY map - * only lost its reporting stream (`unverifiable`), while a pane with no PTY has nothing - * running behind it (`idle`). Neither ever claims the agent finished. - * - * `restoredUnconfirmed` rows are excluded: they are stale by construction rather than by - * elapsed silence, and their last evidence predates a process boundary — so there is no - * "how long since we last heard" for `unverifiable` to report. - */ -export function resolveDecayedAgentRowState( - entry: DecayInput, - hasLivePty: boolean -): 'idle' | 'unverifiable' { - return hasLivePty && entry.state !== 'done' && entry.restoredUnconfirmed !== true - ? 'unverifiable' - : 'idle' -} +export { + resolveAgentRowDisplayState, + resolveDecayedAgentRowState, + type AgentRowDisplayInput +} from '../../../shared/agent-status-row-display' +// Renderer-local alias kept so the sidebar's row type reads in its own vocabulary. +export type { AgentRowDisplayState as AgentRowState } from '../../../shared/agent-status-row-display' /** Coarse `34m` / `2h` / `3d` duration, floored so it never overstates the gap. */ export function formatCompactDuration(deltaMs: number): string { diff --git a/src/renderer/src/lib/worktree-status.ts b/src/renderer/src/lib/worktree-status.ts index cbd6c3c82f31..9c0f9f1a5ea6 100644 --- a/src/renderer/src/lib/worktree-status.ts +++ b/src/renderer/src/lib/worktree-status.ts @@ -11,15 +11,13 @@ import type { } from '../../../shared/terminal-tab-types' import type { TuiAgent } from '../../../shared/tui-agent' import type { LiveAgentWorktreeStatus } from './worktree-activity-state' +import { + rollUpWorktreeStatus, + type WorktreeRollupStatus +} from '../../../shared/worktree-status-rollup' -export type WorktreeStatus = - | 'active' - | 'working' - | 'monitoring' - | 'permission' - | 'interrupted' - | 'done' - | 'inactive' +/** Every member of the shared rollup ladder; the sidebar card is the reader that uses all of them. */ +export type WorktreeStatus = WorktreeRollupStatus type WorktreeStatusHeuristicOptions = { liveAgentStatus?: LiveAgentWorktreeStatus @@ -197,26 +195,14 @@ export function resolveWorktreeStatus(args: { terminalLayoutRootsByTabId: args.terminalLayoutRootsByTabId } ) - if (args.hasPermission) { - return 'permission' - } - // Why: heuristic 'permission' outranks heuristic 'working' — the user-actionable signal wins when panes in one tab disagree. - if (heuristic === 'permission') { - return 'permission' - } - // Why: restored cards get the hook snapshot before panes mount; trust the explicit working row so they stay yellow on restart. - if (args.hasLiveWorking || heuristic === 'working') { - return 'working' - } - if (args.hasLiveMonitoring || heuristic === 'monitoring') { - return 'monitoring' - } - // Terminal outcomes follow live states, but an interrupted outcome must not collapse into success. - if (args.hasInterrupted) { - return 'interrupted' - } - if (args.hasLiveDone || args.hasRetainedDone) { - return 'done' - } - return heuristic + // Why: restored cards get the hook snapshot before panes mount, so an explicit row must be + // able to outrank the title heuristic — the shared ladder adjudicates both in one place + // (permission over working over monitoring over interrupted over done). + return rollUpWorktreeStatus(heuristic, [ + args.hasPermission && 'permission', + args.hasLiveWorking && 'working', + args.hasLiveMonitoring && 'monitoring', + args.hasInterrupted && 'interrupted', + (args.hasLiveDone || args.hasRetainedDone) && 'done' + ]) } diff --git a/src/shared/agent-status-row-display.test.ts b/src/shared/agent-status-row-display.test.ts new file mode 100644 index 000000000000..d2b6d88c6a27 --- /dev/null +++ b/src/shared/agent-status-row-display.test.ts @@ -0,0 +1,102 @@ +import { describe, expect, it } from 'vitest' +import { AGENT_STATUS_STALE_AFTER_MS } from './agent-status-freshness' +import { + resolveAgentRowDisplayState, + resolveDecayedAgentRowState, + type AgentRowDisplayInput +} from './agent-status-row-display' + +const STALE = AGENT_STATUS_STALE_AFTER_MS +const OBSERVED_AT = 1_000_000 + +function row(overrides: Partial = {}): AgentRowDisplayInput { + return { state: 'working', updatedAt: OBSERVED_AT, ...overrides } +} + +describe('resolveAgentRowDisplayState', () => { + it('keeps a fresh row on its reported state', () => { + for (const state of ['working', 'blocked', 'waiting'] as const) { + expect(resolveAgentRowDisplayState(row({ state }), OBSERVED_AT + 1)).toBe(state) + } + }) + + it('holds the state exactly at the window and decays strictly past it', () => { + expect(resolveAgentRowDisplayState(row(), OBSERVED_AT + STALE)).toBe('working') + expect(resolveAgentRowDisplayState(row(), OBSERVED_AT + STALE + 1)).toBe('idle') + }) + + it('splits the decay destination on live-PTY evidence', () => { + const now = OBSERVED_AT + STALE + 1 + expect(resolveAgentRowDisplayState(row(), now, { hasLivePty: true })).toBe('unverifiable') + expect(resolveAgentRowDisplayState(row(), now, { hasLivePty: false })).toBe('idle') + // A reader holding no liveness evidence at all gets the honest destination, not `unverifiable`. + expect(resolveAgentRowDisplayState(row(), now)).toBe('idle') + }) + + it('never decays done, however old', () => { + expect( + resolveAgentRowDisplayState(row({ state: 'done' }), OBSERVED_AT + STALE * 100, { + hasLivePty: true + }) + ).toBe('done') + }) + + it('exempts a host-owned structured row from the window', () => { + const ancient = OBSERVED_AT + STALE * 10 + expect(resolveAgentRowDisplayState(row({ structuredHostOwned: true }), ancient)).toBe('working') + expect(resolveAgentRowDisplayState(row(), ancient)).toBe('idle') + }) + + it('never treats a hydrated unconfirmed row as fresh, however recent', () => { + expect(resolveAgentRowDisplayState(row({ restoredUnconfirmed: true }), OBSERVED_AT + 1)).toBe( + 'idle' + ) + // …and it decays to idle even behind a live PTY: there is no "since we last heard" to report. + expect( + resolveAgentRowDisplayState(row({ restoredUnconfirmed: true }), OBSERVED_AT + 1, { + hasLivePty: true + }) + ).toBe('idle') + }) + + it('measures against the evidence clock, not the delivery clock', () => { + // A relay reconnect restamps `updatedAt`; the row is still stale on the evidence it carries. + const replayed = row({ updatedAt: OBSERVED_AT + STALE, evidenceObservedAt: OBSERVED_AT }) + expect(resolveAgentRowDisplayState(replayed, OBSERVED_AT + STALE + 1)).toBe('idle') + // A mirrored row decays against this replica's own receipt, outranking the host's stamps. + const mirrored = row({ + updatedAt: OBSERVED_AT, + evidenceObservedAt: OBSERVED_AT, + mirroredEvidenceReceivedAt: OBSERVED_AT + STALE + }) + expect(resolveAgentRowDisplayState(mirrored, OBSERVED_AT + STALE + 1)).toBe('working') + }) + + it('falls back to updatedAt when a row carries no evidence stamps', () => { + // The `worktree ps` wire row has neither field, and an old host sends no structuredHostOwned; + // absence must mean "use the ordinary window", never "fresh". + const wireRow: AgentRowDisplayInput = { state: 'working', updatedAt: OBSERVED_AT } + expect(resolveAgentRowDisplayState(wireRow, OBSERVED_AT + STALE)).toBe('working') + expect(resolveAgentRowDisplayState(wireRow, OBSERVED_AT + STALE + 1)).toBe('idle') + }) + + it('honours a caller-supplied window', () => { + expect(resolveAgentRowDisplayState(row(), OBSERVED_AT + 50, { staleAfterMs: 100 })).toBe( + 'working' + ) + expect(resolveAgentRowDisplayState(row(), OBSERVED_AT + 101, { staleAfterMs: 100 })).toBe( + 'idle' + ) + }) +}) + +describe('resolveDecayedAgentRowState', () => { + it('reports unverifiable only for a live non-done pane Orca can still see', () => { + expect(resolveDecayedAgentRowState({ state: 'working' }, true)).toBe('unverifiable') + expect(resolveDecayedAgentRowState({ state: 'working' }, false)).toBe('idle') + expect(resolveDecayedAgentRowState({ state: 'done' }, true)).toBe('idle') + expect(resolveDecayedAgentRowState({ state: 'working', restoredUnconfirmed: true }, true)).toBe( + 'idle' + ) + }) +}) diff --git a/src/shared/agent-status-row-display.ts b/src/shared/agent-status-row-display.ts new file mode 100644 index 000000000000..98c225b2af16 --- /dev/null +++ b/src/shared/agent-status-row-display.ts @@ -0,0 +1,66 @@ +import { isFreshNonDoneAgentStatus } from './agent-status-freshness' +import type { AgentStatusState } from './agent-status-types' + +/** Row states: the hook-reported statuses plus the two Orca derives when an entry goes stale. */ +export type AgentRowDisplayState = AgentStatusState | 'idle' | 'unverifiable' + +/** + * The fields the decay reads. Every optional one is genuinely absent somewhere: a + * `worktree ps` row carries none of the evidence stamps, and an older host sends no + * `structuredHostOwned`. Absence must fall back to the ordinary window, never to "fresh". + */ +export type AgentRowDisplayInput = { + state: AgentStatusState + updatedAt: number + evidenceObservedAt?: number + mirroredEvidenceReceivedAt?: number + restoredUnconfirmed?: boolean + structuredHostOwned?: true +} + +/** + * Where a stale non-`done` entry decays to. + * + * Silence is not evidence (docs/reference/ssh-execution-boundary.md), so the destination + * splits on the liveness Orca actually holds: a pane whose PTY is still in the live-PTY map + * only lost its reporting stream (`unverifiable`), while a pane with no PTY has nothing + * running behind it (`idle`). Neither ever claims the agent finished. + * + * `restoredUnconfirmed` rows are excluded: they are stale by construction rather than by + * elapsed silence, and their last evidence predates a process boundary — so there is no + * "how long since we last heard" for `unverifiable` to report. + */ +export function resolveDecayedAgentRowState( + entry: Pick, + hasLivePty: boolean +): 'idle' | 'unverifiable' { + return hasLivePty && entry.state !== 'done' && entry.restoredUnconfirmed !== true + ? 'unverifiable' + : 'idle' +} + +/** + * The one staleness decay every agent-row reader applies: the sidebar, `worktree ps`, and + * the mobile row list all render this state, not the raw reported one. + * + * `done` is an outcome, not a claim about a running process, so it never decays. Everything + * else defers to `isFreshNonDoneAgentStatus` for the freshness question — which owns the + * evidence clock, the host-owned exemption, and the hydrated-row rule — and this function + * owns only where a row goes once that answer is "no". + * + * Callers with no live-PTY evidence (a remote reader such as mobile) leave `hasLivePty` + * unset and get `idle`, which is the honest destination when liveness is unknown. + */ +export function resolveAgentRowDisplayState( + row: AgentRowDisplayInput, + now: number, + options: { hasLivePty?: boolean; staleAfterMs?: number } = {} +): AgentRowDisplayState { + if (row.state === 'done') { + return 'done' + } + if (isFreshNonDoneAgentStatus(row, now, options.staleAfterMs)) { + return row.state + } + return resolveDecayedAgentRowState(row, options.hasLivePty === true) +} diff --git a/src/shared/worktree-status-rollup.test.ts b/src/shared/worktree-status-rollup.test.ts new file mode 100644 index 000000000000..7b9cbaba73a7 --- /dev/null +++ b/src/shared/worktree-status-rollup.test.ts @@ -0,0 +1,97 @@ +import { describe, expect, it } from 'vitest' +import { + mergeWorktreeRollupStatus, + rollUpWorktreeStatus, + worktreeStatusRank, + type WorktreeRollupStatus +} from './worktree-status-rollup' + +const LADDER: readonly WorktreeRollupStatus[] = [ + 'inactive', + 'active', + 'done', + 'interrupted', + 'monitoring', + 'working', + 'permission' +] + +describe('the rollup ladder', () => { + it('ranks every status strictly, lowest first', () => { + const ranks = LADDER.map(worktreeStatusRank) + expect(ranks).toEqual([...ranks].sort((a, b) => a - b)) + expect(new Set(ranks).size).toBe(LADDER.length) + }) + + it('preserves the wire subset ordering `worktree ps` shipped before the ladder was shared', () => { + // Pin: the RuntimeWorktreeStatus members must keep permission > working > done > active > + // inactive, so folding the renderer's extra members in cannot reorder the CLI's rollup. + const wireSubset: readonly WorktreeRollupStatus[] = [ + 'inactive', + 'active', + 'done', + 'working', + 'permission' + ] + expect([...wireSubset].sort((a, b) => worktreeStatusRank(b) - worktreeStatusRank(a))).toEqual([ + 'permission', + 'working', + 'done', + 'active', + 'inactive' + ]) + }) + + it('keeps live work above a terminal outcome, and an interrupt above success', () => { + expect(mergeWorktreeRollupStatus('interrupted', 'working')).toBe('working') + expect(mergeWorktreeRollupStatus('working', 'interrupted')).toBe('working') + expect(mergeWorktreeRollupStatus('interrupted', 'monitoring')).toBe('monitoring') + expect(mergeWorktreeRollupStatus('done', 'interrupted')).toBe('interrupted') + expect(mergeWorktreeRollupStatus('interrupted', 'done')).toBe('interrupted') + }) + + it('returns the higher-ranked of any pair, whichever side it arrives on', () => { + for (const left of LADDER) { + for (const right of LADDER) { + const higher = worktreeStatusRank(left) >= worktreeStatusRank(right) ? left : right + expect(mergeWorktreeRollupStatus(left, right), `${left} + ${right}`).toBe(higher) + expect(mergeWorktreeRollupStatus(right, left), `${right} + ${left}`).toBe(higher) + } + } + }) +}) + +describe('rollUpWorktreeStatus', () => { + it('returns the base when no candidate outranks it', () => { + expect(rollUpWorktreeStatus('working', ['done', 'active'])).toBe( + 'working' + ) + }) + + it('lets a caller pass `flag && status` without an unset flag reaching the ladder', () => { + // Ergonomics, not adjudication: an unset flag must contribute nothing, so a reader can list + // its signals in any order instead of hand-writing a precedence if-chain. + const hasPermission = false + const hasDone = true + expect( + rollUpWorktreeStatus('active', [ + hasPermission && 'permission', + hasDone && 'done', + null, + undefined + ]) + ).toBe('done') + expect(rollUpWorktreeStatus('working', [false, null, undefined])).toBe( + 'working' + ) + }) + + it('takes the highest candidate regardless of the order they are passed', () => { + expect( + rollUpWorktreeStatus('inactive', ['done', 'permission', 'working']) + ).toBe('permission') + expect( + rollUpWorktreeStatus('inactive', ['permission', 'working', 'done']) + ).toBe('permission') + }) +}) diff --git a/src/shared/worktree-status-rollup.ts b/src/shared/worktree-status-rollup.ts new file mode 100644 index 000000000000..efb9db8bbfc6 --- /dev/null +++ b/src/shared/worktree-status-rollup.ts @@ -0,0 +1,58 @@ +/** + * The worktree card's status vocabulary, widest form. `RuntimeWorktreeStatus` on the wire is + * the subset an older client understands; the renderer uses every member. + */ +export type WorktreeRollupStatus = + | 'inactive' + | 'active' + | 'done' + | 'interrupted' + | 'monitoring' + | 'working' + | 'permission' + +/** + * One ladder for the whole rollup: a worktree shows its highest-ranked signal. + * + * The order is a claim about what the user needs to see, not about severity. `permission` + * outranks everything because it is the only state that cannot advance without the user. + * The two live-work states outrank `interrupted` because work that resumed after an + * interrupt is working, not interrupted; `interrupted` in turn outranks `done` so a + * cancelled run never reads as a successful one. + */ +const WORKTREE_STATUS_PRIORITY: Record = { + inactive: 0, + active: 1, + done: 2, + interrupted: 3, + monitoring: 4, + working: 5, + permission: 6 +} + +export function worktreeStatusRank(status: WorktreeRollupStatus): number { + return WORKTREE_STATUS_PRIORITY[status] +} + +/** The higher-ranked of two statuses, keeping `current` on a tie. */ +export function mergeWorktreeRollupStatus(current: T, next: T): T { + return WORKTREE_STATUS_PRIORITY[next] > WORKTREE_STATUS_PRIORITY[current] ? next : current +} + +/** + * Roll a base status up over the signals a reader holds. Falsy candidates are dropped, so a + * caller can pass `hasPermission && 'permission'` and let the ladder do the adjudication + * rather than hand-ordering an if-chain. + */ +export function rollUpWorktreeStatus( + base: T, + candidates: readonly (T | false | null | undefined)[] +): T { + let result = base + for (const candidate of candidates) { + if (candidate) { + result = mergeWorktreeRollupStatus(result, candidate) + } + } + return result +}