Repository navigation
fix(remote): stop unlabelled inventories and replayed rows authorising destruction - #17981
Conversation
…e mirror #11495 Step C. `buildMissingWebSessionTabsRemovals` synthesised a `removed: true` tombstone -- emptying a worktree's entire mirror -- for any tracked worktree absent from a single inventory frame, without ever consulting the host's own authority label. `mirror-settle` already refuses to settle an *empty* inventory that is not `authoritative` (#16414, #16546); the strictly more destructive action was ungated. An inventory the host labels `authoritative` carries a complete PTY census, so one omission is host attestation and removal stays immediate. An unlabelled inventory is a degraded or version-skewed census: `unverifiable`, not `exited`. It must now repeat before it can destroy anything, reusing the two-observation shape of `confirmSurfaceInventoryAbsence`. A legacy host that never negotiates the capability still converges after two rounds, so ghost rows cannot outlive the fence. The 14 tests from #13621 that blocked this were all written before the `authoritative` label existed (#13621 landed 2026-08-11; the capability landed 2026-08-26 in #16546). #13621's own summary says "Reconcile each resumed host from an authoritative inventory, including removals", so their fixtures are retargeted to say so explicitly rather than weakened. Refs #11495
…lock #15317 correctness half. `receivedAt` was doing two jobs: delivery order and evidence age. A relay reconnect replays every cached row, and `receivedAt` must restamp to clear the connection watermark that `clearStatusEntriesForConnection` raises -- so a pane stuck at `working` had its 30-minute deadline pushed out by another 30 minutes on every reconnect. The TTL was never reached, which is why this read as a tuning question. Two clocks, not one rewritten clock: - `receivedAt` is untouched. The transient-clear watermark and the four `<` ordering drops (`agent-status-event-applicator`, `agent-status-live-entry-builder`, `agent-status-cleanup-actions`) keep working unchanged. Restamping a replay with its original time would have made it `<= watermark` and dropped it outright, leaving the pane with no row at all. - `evidenceObservedAt` is new, optional, and read only by the staleness comparison (`isFreshNonDoneAgentStatus`, `isExplicitAgentStatusFresh`, the freshness scheduler). Main holds it per pane across the transport clear -- the clear deletes the row on purpose, but the *age* of evidence a later replay restates is not a claim about the pane. Absent means "no separate observation", and every consumer falls back to `receivedAt`/`updatedAt`, so old hosts and old rows behave exactly as today. Behaviour: a genuinely active pane keeps stamping the observation clock from its real events, so it stays `working` across a reconnect. A pane whose relay restarted replays nothing and still falls through to title evidence. A torn-down pane drops its remembered clock in `clearPaneState`, so a reused pane key cannot inherit one. `AGENT_STATUS_STALE_AFTER_MS` is deliberately unchanged -- the window length remains a product decision. Refs #15317
|
Caution Review failedAn error occurred during the review process. Please try again later. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Important
evidenceObservedAt is written to the last-status file but never read back at hydrate, so it does not survive a main restart as the type comment and PR body claim — the restart variant of #15317 is still open. See the inline comment on server-types.ts:18 for the exact path and fix.
Reviewed changes
- Staleness clock split (
evidenceObservedAt) — a new optional observation timestamp, read only by the freshness comparison, so a relay reconnect replay stops restamping the staleness deadline.receivedAtkeeps its delivery/ordering role so the connection-clear watermark and the renderer's four<drops are untouched. - Authoritative-gated mirror destruction —
buildMissingWebSessionTabsRemovalsnow readshostAuthoritative: a capable host removes on the first omission, an unlabelled/degraded census must repeat via a two-observation fence (mirroringconfirmSurfaceInventoryAbsence) before it can tombstone a worktree mirror. - Test retargeting + extraction — 14 fixtures retargeted to
authoritative: truevia anauthoritativeInventory()helper, plus new replay-clock (server-replay-evidence-clock.test.ts,agent-status-evidence-clock.test.ts) and absence (web-session-tabs-sync-window-visibility.test.tsx) tests.
ℹ️ Nitpicks
dropStatusEntriesByTabPrefixinserver-tab-cleanup.tsclears every per-pane cache thatclearPaneStatedoes but was not given the sameevidenceObservedAtByPaneKey.delete. It is bounded dead weight in practice (a closed pane's key is suppressed before it could replay), so nothing user-visible — but the asymmetry is easy to miss next time this map gains a reader.omissionKeyinsession-tabs-inventory-absence.tsre-implementssessionTabsFreshnessKey(${environmentId}:${worktreeId}) verbatim, and the cleanup paths intracking-lifecycle.tsrely on that same format matching. UsesessionTabsFreshnessKeydirectly so the two key spaces can't silently diverge.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
| * replays cached rows and `receivedAt` must restamp to clear the connection watermark, so | ||
| * only this clock can answer how old the evidence itself is. Persisted so it survives a | ||
| * main restart; absent means "never separately observed" and consumers use `receivedAt`. */ | ||
| evidenceObservedAt?: number |
There was a problem hiding this comment.
The JSDoc says evidenceObservedAt is "Persisted so it survives a main restart", but it is not actually round-tripped: serializeStatusFile writes it through the ...persistedPayload rest spread, yet sanitizeHydratedEntry reconstructs the enriched row from an explicit field list that omits it. After a restart the in-memory evidenceObservedAtByPaneKey map is empty and the hydrated row also lacks the field, so the first reconnect replay sets evidenceObservedAt = now and clears restoredUnconfirmed in applyNormalizedStatus — re-arming the 30-minute window for a genuinely stuck working pane. The reconnect fix works; the restart variant of #15317 does not.
Technical details
# evidenceObservedAt does not survive hydration
## Affected sites
- src/main/agent-hooks/server/server-persistence.ts:41 — `...persistedPayload` rest spread persists `evidenceObservedAt` into the last-status file.
- src/main/agent-hooks/server/server-persistence-validation.ts:104-125 — `sanitizeHydratedEntry` rebuilds the row from an explicit field list and never reconstructs `evidenceObservedAt`, so the persisted copy is discarded.
- src/main/agent-hooks/server/server-hydration.ts:103 — hydrated rows land in `lastStatusByPaneKey` without the field.
- src/main/agent-hooks/server/server-status-update.ts:181-200 / server-status-application.ts:59-77 — a later `isReplay` event runs `resolveEvidenceObservedAt` with an empty map and undefined `previous.evidenceObservedAt`, producing `now`, and the new enriched row drops `restoredUnconfirmed`.
## Required outcome
- Either reconstruct `evidenceObservedAt` in `sanitizeHydratedEntry` (validate `typeof === 'number' && Number.isFinite`) so the "survives a main restart" claim is true, or strip it from persistence like `isReplay` and correct the JSDoc + PR body to state it is runtime-only. The type and the code must agree.
## Suggested approach (optional)
- Mirror the existing `receivedAt`/`stateStartedAt` validation in `sanitizeHydratedEntry` and add `evidenceObservedAt` to the returned object; add a hydrate round-trip assertion to `server-replay-evidence-clock.test.ts`.
## Open questions for the human (optional)
- Is the restart scenario actually in scope for #15317, or is the reconnect-only fix sufficient and only the comment is wrong?…g destruction (stablyai#17981) * fix(remote): stop one unlabelled inventory tombstoning a live worktree mirror stablyai#11495 Step C. `buildMissingWebSessionTabsRemovals` synthesised a `removed: true` tombstone -- emptying a worktree's entire mirror -- for any tracked worktree absent from a single inventory frame, without ever consulting the host's own authority label. `mirror-settle` already refuses to settle an *empty* inventory that is not `authoritative` (stablyai#16414, stablyai#16546); the strictly more destructive action was ungated. An inventory the host labels `authoritative` carries a complete PTY census, so one omission is host attestation and removal stays immediate. An unlabelled inventory is a degraded or version-skewed census: `unverifiable`, not `exited`. It must now repeat before it can destroy anything, reusing the two-observation shape of `confirmSurfaceInventoryAbsence`. A legacy host that never negotiates the capability still converges after two rounds, so ghost rows cannot outlive the fence. The 14 tests from stablyai#13621 that blocked this were all written before the `authoritative` label existed (stablyai#13621 landed 2026-08-11; the capability landed 2026-08-26 in stablyai#16546). stablyai#13621's own summary says "Reconcile each resumed host from an authoritative inventory, including removals", so their fixtures are retargeted to say so explicitly rather than weakened. Refs stablyai#11495 * fix(agent-status): stop a reconnect replay restamping the staleness clock stablyai#15317 correctness half. `receivedAt` was doing two jobs: delivery order and evidence age. A relay reconnect replays every cached row, and `receivedAt` must restamp to clear the connection watermark that `clearStatusEntriesForConnection` raises -- so a pane stuck at `working` had its 30-minute deadline pushed out by another 30 minutes on every reconnect. The TTL was never reached, which is why this read as a tuning question. Two clocks, not one rewritten clock: - `receivedAt` is untouched. The transient-clear watermark and the four `<` ordering drops (`agent-status-event-applicator`, `agent-status-live-entry-builder`, `agent-status-cleanup-actions`) keep working unchanged. Restamping a replay with its original time would have made it `<= watermark` and dropped it outright, leaving the pane with no row at all. - `evidenceObservedAt` is new, optional, and read only by the staleness comparison (`isFreshNonDoneAgentStatus`, `isExplicitAgentStatusFresh`, the freshness scheduler). Main holds it per pane across the transport clear -- the clear deletes the row on purpose, but the *age* of evidence a later replay restates is not a claim about the pane. Absent means "no separate observation", and every consumer falls back to `receivedAt`/`updatedAt`, so old hosts and old rows behave exactly as today. Behaviour: a genuinely active pane keeps stamping the observation clock from its real events, so it stays `working` across a reconnect. A pane whose relay restarted replays nothing and still falls through to title evidence. A torn-down pane drops its remembered clock in `clearPaneState`, so a reused pane key cannot inherit one. `AGENT_STATUS_STALE_AFTER_MS` is deliberately unchanged -- the window length remains a product decision. Refs stablyai#15317 Mirror-Of: 4e35e05
…g destruction (stablyai#17981) * fix(remote): stop one unlabelled inventory tombstoning a live worktree mirror stablyai#11495 Step C. `buildMissingWebSessionTabsRemovals` synthesised a `removed: true` tombstone -- emptying a worktree's entire mirror -- for any tracked worktree absent from a single inventory frame, without ever consulting the host's own authority label. `mirror-settle` already refuses to settle an *empty* inventory that is not `authoritative` (stablyai#16414, stablyai#16546); the strictly more destructive action was ungated. An inventory the host labels `authoritative` carries a complete PTY census, so one omission is host attestation and removal stays immediate. An unlabelled inventory is a degraded or version-skewed census: `unverifiable`, not `exited`. It must now repeat before it can destroy anything, reusing the two-observation shape of `confirmSurfaceInventoryAbsence`. A legacy host that never negotiates the capability still converges after two rounds, so ghost rows cannot outlive the fence. The 14 tests from stablyai#13621 that blocked this were all written before the `authoritative` label existed (stablyai#13621 landed 2026-08-11; the capability landed 2026-08-26 in stablyai#16546). stablyai#13621's own summary says "Reconcile each resumed host from an authoritative inventory, including removals", so their fixtures are retargeted to say so explicitly rather than weakened. Refs stablyai#11495 * fix(agent-status): stop a reconnect replay restamping the staleness clock stablyai#15317 correctness half. `receivedAt` was doing two jobs: delivery order and evidence age. A relay reconnect replays every cached row, and `receivedAt` must restamp to clear the connection watermark that `clearStatusEntriesForConnection` raises -- so a pane stuck at `working` had its 30-minute deadline pushed out by another 30 minutes on every reconnect. The TTL was never reached, which is why this read as a tuning question. Two clocks, not one rewritten clock: - `receivedAt` is untouched. The transient-clear watermark and the four `<` ordering drops (`agent-status-event-applicator`, `agent-status-live-entry-builder`, `agent-status-cleanup-actions`) keep working unchanged. Restamping a replay with its original time would have made it `<= watermark` and dropped it outright, leaving the pane with no row at all. - `evidenceObservedAt` is new, optional, and read only by the staleness comparison (`isFreshNonDoneAgentStatus`, `isExplicitAgentStatusFresh`, the freshness scheduler). Main holds it per pane across the transport clear -- the clear deletes the row on purpose, but the *age* of evidence a later replay restates is not a claim about the pane. Absent means "no separate observation", and every consumer falls back to `receivedAt`/`updatedAt`, so old hosts and old rows behave exactly as today. Behaviour: a genuinely active pane keeps stamping the observation clock from its real events, so it stays `working` across a reconnect. A pane whose relay restarted replays nothing and still falls through to title evidence. A torn-down pane drops its remembered clock in `clearPaneState`, so a reused pane key cannot inherit one. `AGENT_STATUS_STALE_AFTER_MS` is deliberately unchanged -- the window length remains a product decision. Refs stablyai#15317

Two fixes from the SSH sweep's leftover list. #17915 is closed with evidence and needed no code.
1. #15317 — a correctness bug, not a tuning question. TTL untouched.
The 30-minute staleness window was never reached, which is why this read as "pick a better number."
receivedAtwas doing two jobs:clearStatusEntriesForConnectionraises a per-connection watermark, and four consumers drop anything at or below it (agent-status-event-applicator.ts:123,139,agent-status-live-entry-builder.ts:72,agent-status-cleanup-actions.ts:24);updatedAt + AGENT_STATUS_STALE_AFTER_MS.On reconnect the relay replays every cached row, main restamps
receivedAt, and every reconnect pushes the deadline out another 30 minutes. A pane stuck atworkingwas unbounded.Restamping the replay with its original time is not available — it would land at or below the watermark and be dropped outright, leaving the pane with no row at all, which is worse than a stale one. (I proposed exactly that first; it was wrong.)
So: two clocks.
receivedAtuntouched, all four guards and the watermark keep working. A new optionalevidenceObservedAtis read only by the staleness comparison, so all ~12 existing call sites inherit it without edits. Main holds it per pane, bounded at 1024, deliberately surviving the transport clear — that clear deletes the row on purpose, but the age of evidence a later replay restates is not a claim about the pane. Dropped inclearPaneState, so a reused pane key cannot inherit one.Wire: no relay-side addition needed.
buildRelayHookEnvelopecarries no timestamp andisReplay: trueis already on the wire. The new field crosses only main→renderer IPC (versioned together). Absent means "no separate observation" and every consumer falls back — old rows and hosts behave exactly as today.Behaviour: a live pane keeps stamping from its real events and stays
workingacross reconnect. A pane whose relay restarted replays nothing and falls through to title evidence atconfidence: 'fallback'. A genuinely stalled pane now decays after one window instead of never. The field can only move the deadline earlier, so it cannot fabricate liveness.Still a product decision:
AGENT_STATUS_STALE_AFTER_MS = 30 * 60 * 1000, unchanged. Shorter — a long quiet turn (a long build, a compaction, a model stall) emits no hooks and decays to "not fresh" while genuinely working; the sidebar dot dropsworking→activeand smart-attention deprioritises it. Longer — a stalled pane spins for longer, but that is now bounded by the window; before it was unbounded, which is why the number looked like the problem. Prerequisite if you move it: the constant drives two deadlines inagent-status-freshness-scheduler.ts(hook freshness and completion freshness, plussmart-attention.ts:150), so tuning one tunes both.2. #11495 Step C — the weaker action was gated on host authority; the stronger one was not
mirror-settle.tsalready refuses to settle an empty inventory that is notauthoritative. ButbuildMissingWebSessionTabsRemovals, which destroys an entire worktree mirror, never readevent.authoritativeat all.settleSessionTabsInventorysets that flag only whenisCompleteSessionTabsPtyCensuspasses — so an unlabelled inventory is the host saying my census is incomplete. That isunverifiable, and it was authorising destruction.Now:
authoritative→ one omission is attestation, removal immediate (unchanged for capable hosts). Unlabelled → must repeat, reusing the two-observation shape ofconfirmSurfaceInventoryAbsence.A genuinely gone worktree still goes: authoritative hosts remove on the first inventory as today; a legacy or degraded host removes on the second, one extra visibility resume. It cannot fail to recover, and ghosts cannot outlive the fence.
The 14 blocking tests — provenance settled, none encodes a defect
git log -Son each title: 14 of 15 come from one commit, PR #13621 "park hidden remote session mirrors" (2026-08-11). They assert that a full inventory omitting a tracked worktree retires its mirror, and that the ordering/fencing around that retirement is right.The decisive fact is the date.
SESSION_TABS_AUTHORITATIVE_INVENTORY_RUNTIME_CAPABILITYlanded 2026-08-26 in PR #16546 — fifteen days later. These fixtures could not have expressed a distinction whose vocabulary did not yet exist. They encode a contract written before the words for it existed, not a bug. All 15 were retargeted to sayauthoritative: trueexplicitly via a namedauthoritativeInventory()helper — not weakened.Negative control in the other direction: making the authoritative path also require two observations reproduces exactly those 15 failures, so the immediate-removal contract is still pinned.
max-linesforced two extractions rather than a disable — omission/tombstone logic tosession-tabs-inventory-absence.ts, and the test file's duplicated park/reveal blocks into oneparkAndReveal(multiplier)helper (net −18 lines before the new tests).Step A deliberately not implemented
Three reasons, and the third is the real one:
authoritativeis a host-wide census verdict; per-worktreesnapshot/updatedframes never carry one, so "not authoritative" would be true almost always.apply-terminal-records.tsdeletes those keys only for tabs a frame did not re-publish. Append-only leaves dead handles inptyIdsByTabId, the live-PTY index feeding doomed-PTY computation and wake/respawn (terminal-tab-retirement.ts:64-80,worktree-purge-doomed-ids.ts:29-38).web-session-terminal-orphan-recovery-inventory.ts, which already reasons abouttruncated/hostScopeUnverifiable. The specific bad disposition Step A compensated for is already fixed in fix(remote): stop a colliding path key, a dead conflict state, and a live-PTY removal from losing tabs #17948.3. #17915 — premise stale, no code change
The issue says #17914 fixes the app and daemon "but not the SSH relay," leaving a platform split. That split does not exist, because the fix does not exist anywhere: #17914 is open and unmerged, and
grep -rn "FD_CLOEXEC\|O_CLOEXEC\|cloexec" config/ src/ scripts/returns no matches — including inside thesrc/unix/pty.cchunks ofconfig/patches/[email protected], which carry only the GCC-9 floor, the winpty/conpty target removal, and console-list-agent work.The leak is uniform across app, daemon and relay. #17915 is blocked on #17914, not independently fixable. Ground truth for whoever picks it up is in the commit message; note
relay-native-dependency-coverage.test.ts:93-103pins version parity and would break under the version-bump option.User-facing regressions
None expected. Verbatim before/after in both commits; negative controls in both directions.
tc:node/tc:web/tc:cliclean,check:code-quality:changed0 findings. Sweeps:src/renderer/src/runtime1243 passed; agent-hooks + slices + ipc-events + lib 8516 passed; components + runtime + shared + ssh 32178 passed.Follow-up identified, not done
runtime-mobile-agent-status-projection.ts:151(updatedAt: live.receivedAt) is the same clock bug on the paired-runtime mirror path reaching mobile/web. Propagating the field there changesHookLiveAgentRowand the runtime wire shape — a real mixed-version surface needing full compat treatment, and it inherits the cross-authority clock skew documented inagent-status-observation.ts. Scoped follow-up rather than forced in.