Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 93 additions & 5 deletions docs/reference/agent-status-store.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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

Expand Down
46 changes: 46 additions & 0 deletions mobile/src/worktree/agent-row-display.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down
41 changes: 24 additions & 17 deletions mobile/src/worktree/agent-row-display.ts
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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<RuntimeWorktreeAgentRow, 'state' | 'workingMode' | 'interrupted' | 'updatedAt'>,
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'
}
Expand Down
73 changes: 73 additions & 0 deletions src/main/runtime/runtime-worktree-status-projection.test.ts
Original file line number Diff line number Diff line change
@@ -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')
})
})
24 changes: 5 additions & 19 deletions src/main/runtime/runtime-worktree-status-projection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,7 @@ import type {
RuntimeWorktreeStatus
} from '../../shared/runtime-types'
import type { TuiAgent } from '../../shared/tui-agent'

const WORKTREE_STATUS_PRIORITY: Record<RuntimeWorktreeStatus, number> = {
inactive: 0,
active: 1,
done: 2,
working: 3,
permission: 4
}
import { worktreeStatusRank } from '../../shared/worktree-status-rollup'

type LeafStatusRecord = {
ptyId: string | null
Expand Down Expand Up @@ -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'
Expand All @@ -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 {
Expand Down
Loading