Skip to content

[perf-remote] perf(renderer): park hidden remote session mirrors - #13621

Merged
nwparker merged 4 commits into
mainfrom
nwparker/perf-remote-park-hidden-session-mirrors
Aug 11, 2026
Merged

nwparker merged 4 commits into
mainfrom
nwparker/perf-remote-park-hidden-session-mirrors

Conversation

@nwparker

Copy link
Copy Markdown
Contributor

Summary

  • Park all renderer session-tab mirror subscriptions after Orca has been hidden for 500 ms.
  • Resume the scoped active-worktree stream immediately, then restart global host inventories active-host-first at one launch per 100 ms.
  • Reconcile each resumed host from an authoritative inventory, including removals and same-worktree collisions across hosts.
  • Skip orphan recovery and store replay for the first exact unchanged resume inventory while retaining terminal-handle wake evidence and full shared-control reconnect replay behavior.

ELI5

Each remote host was continuously mailing the hidden Orca window complete tab/session updates, sometimes several times per second. With several hosts, the hidden renderer still unpacked and reconciled all of them. This change pauses those mail deliveries after Orca has been hidden for 500 ms and asks each host for a fresh authoritative view when Orca returns. It lets the active host go first, spaces the rest out, and avoids rebuilding state when the view is unchanged.

Performance evidence

The deterministic tests exercise the resource counts that correspond to the reported renderer slowdown:

  • Hidden steady state changes from E global host streams plus A active-worktree stream to zero live renderer mirror streams after the 500 ms grace period.
  • A quick hide/show inside the grace period causes no reconnect.
  • Initial visible startup remains immediate.
  • Visibility resume starts the scoped active stream immediately, starts the active host's global inventory first, and then arms only one chained 100 ms launch timer at a time for remaining hosts.
  • An exact unchanged global inventory performs zero orphan-recovery calls and preserves store identity; it still emits accepted terminal-handle evidence.
  • A tagged shared-control reconnect replay still performs recovery and repairs renderer state.

This is deterministic count/identity evidence, not a packaged multi-host wall-clock benchmark.

Reliability contract

  • Invariant: agent-session.remote-host-authority — a visibility pause/resume must not resurrect stale sessions, remove a newer host snapshot, steal another host's same-worktree state, or strand a terminal mirror.
  • Failure source: the reported v1.4.178 renderer regression with multiple busy remote hosts, especially after returning to Orca from another window.
  • Oracle: visibility-generation, retry, cleanup, semantic freshness, omission, cross-host collision, recovery-fencing, accepted-handle, and active-first pacing tests.
  • Gate: the repository's agent-session.remote-host-authority deterministic core, transport, retirement, and orphan-adoption slices.
  • Diagnostics: existing subscribe/unsubscribe/recovery error surfaces remain intact; no high-volume telemetry or logging was added.

Provider/platform review:

  • Remote runtime is directly covered, including disconnect/replay, PTY transport, durable retirement, and mixed-version orphan behavior.
  • Local, daemon, direct SSH, WSL, relay, and folder-workspace authority are unchanged; focused provider gates passed.
  • Worktree IDs stay opaque; this adds no local-filesystem or git-worktree assumption.
  • macOS unit/build evidence is fresh. Packaged Windows/Linux and a live SSH visibility journey were not run.

Compatibility and security

  • Renderer-only behavior change: no RPC/schema/opcode/payload, persistence, migration, dependency, lockfile, native binary, or packaging changes.
  • Mixed client/host versions remain wire-compatible because the request and response shapes are unchanged.
  • No mobile-facing surface is touched.
  • No new network sink, shell/eval path, credential handling, secret, install hook, or dependency surface.
  • No visual/UI change; screenshots are not applicable.

Adversarial review

Two independent AI reviewers audited ordering, retries, teardown, memory bounds, reconnect replay, same-worktree host collisions, terminal wake behavior, and foreground fanout. Findings fixed during review included:

  • a newer active snapshot arriving before an older empty resume inventory;
  • an effect restart while already hidden losing the removal baseline;
  • exact resume skipping the shared-control reconnect replay contract;
  • exact resume omitting terminal-handle wake evidence;
  • simultaneous all-host foreground restart and multiple overdue launch timers.

Final verdict: no proven P0/P1/P2 issue remains in the submitted tree.

Validation

  • Focused session-mirror/visibility/parking suite: 4 files, 104 tests passed.
  • Remote-host authority core: 5 files, 144 tests passed.
  • Remote-host authority transport/PTY providers: 10 files, 433 tests passed.
  • Durable remote terminal retirement: 1 test passed.
  • Host runtime/orphan adoption: 6 files, 1,156 tests passed, 1 skipped.
  • ORCA_CROSS_VERSION_BASELINE_REF=v1.4.177 pnpm test: 4,598 files / 49,303 tests passed; 16 files / 99 tests skipped.
  • pnpm typecheck
  • pnpm lint
  • pnpm build:electron-vite
  • Changed-code quality, type-aware quality, React Doctor, max-lines ratchet, and git diff --check passed.

Residual risks

  • Chromium may delay the 500 ms park timer while background-throttled.
  • Pacing bounds host-inventory launch rate, not completion: delayed responses can still converge, and one busy host with many changed workspaces remains a large batch.
  • A subscription promise already pending across hide/reveal can settle after its stagger slot and bypass normal pacing in the offline/pending-host edge.
  • Non-active background freshness is delayed by 100 ms × (host position - 1); the active host/worktree remains immediate.
  • An unavailable inventory can retain one cardinality-bounded resume batch until the next visibility generation or teardown.
  • An unavailable same-worktree survivor conservatively defers destructive cleanup.
  • Orphan recovery is not cancellable and its pre-existing per-worktree promise chain can retain backlog behind a long request.
  • PTYs and agents continue running remotely; only renderer mirrors park.
  • The existing initial listAll plus subscribeAll hydration duplication and active/global stream duplication remain separate follow-ups.

@coderabbitai

coderabbitai Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@nwparker, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 30 seconds

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 5d4d45dd-79b9-4ff5-9d44-c5ac46a310d1

📥 Commits

Reviewing files that changed from the base of the PR and between 21d5ca6 and 34e9589.

📒 Files selected for processing (5)
  • src/renderer/src/runtime/web-session-tabs-sync-visibility-collision.test.tsx
  • src/renderer/src/runtime/web-session-tabs-sync-window-visibility.test.tsx
  • src/renderer/src/runtime/web-session-tabs-sync.ts
  • src/renderer/src/runtime/window-visibility-subscription-parking.test.ts
  • src/renderer/src/runtime/window-visibility-subscription-parking.ts
📝 Walkthrough

Walkthrough

The change adds window-visibility subscription parking with delayed shutdown, staggered restart, retry handling, generation checks, and cleanup. Web session-tab synchronization now tracks snapshot freshness, receipt frames, removals, recovery state, worktree ownership, and environment revisions. Global and active subscriptions use visibility-aware lifecycle management. Resume reconciliation handles omitted mirrors, tombstones, collisions, stale recoveries, and authoritative inventories. New tests cover parking, recovery, ordering, cleanup, and mirror reconciliation.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 1.89% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the primary renderer performance change: parking hidden remote session mirrors.
Description check ✅ Passed The description explains the change, testing, risks, security, platform coverage, and visual impact, although some template headings use equivalent names.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (4)
src/renderer/src/runtime/window-visibility-subscription-parking.ts (1)

138-179: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value

Late settlements restart outside the paced order.

When a stale pending start settles, lines 159-161 and 173-175 call startEntry directly. That entry then reconnects immediately, even while a staggered resume chain is still running. The resume pacing is therefore not honored for that entry.

Correctness holds, because startEntry still respects startTimer, desired, and generation. If you want strict pacing, re-enter through the chain instead of calling startEntry directly, for example by queueing the index and letting startNext own the start.

src/renderer/src/runtime/window-visibility-subscription-parking.test.ts (1)

342-378: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add coverage for the synchronous subscribe throw and the backoff cap.

This suite covers rejected promises only. The implementation also has a synchronous try/catch around spec.subscribe (lines 127-137 of window-visibility-subscription-parking.ts) that reports the error and schedules a retry. That branch is untested, and a regression there would silently stop reconnection.

The exponential cap at WINDOW_VISIBILITY_SUBSCRIPTION_RETRY_MAX_MS is also untested. The constant is module-private, so a cap test needs a repeated-failure sequence with Math.random pinned, or the constant exported like the other two.

💚 Suggested test for the synchronous throw branch
it('retries after a synchronous subscribe throw', async () => {
  vi.spyOn(Math, 'random').mockReturnValue(0)
  const error = new Error('synchronous start failed')
  const onSubscribeError = vi.fn()
  const subscribe = vi
    .fn<WindowVisibilitySubscriptionSpec['subscribe']>()
    .mockImplementationOnce(() => {
      throw error
    })
    .mockResolvedValueOnce({ unsubscribe: vi.fn() })
  const dispose = installWindowVisibilitySubscriptionParking([{ subscribe, onSubscribeError }])

  expect(onSubscribeError).toHaveBeenCalledWith(error)
  vi.advanceTimersByTime(WINDOW_VISIBILITY_SUBSCRIPTION_RETRY_INITIAL_MS)
  await settle()
  expect(subscribe).toHaveBeenCalledTimes(2)
  dispose()
})
src/renderer/src/runtime/web-session-tabs-sync.ts (1)

3210-3561: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚖️ Poor tradeoff

Consider extracting the resume reconciliation state machine into its own module.

The mirror effect body now holds three local types and eight closures that implement a reconciliation state machine. The state machine depends only on visibilityResumeOmissionsByKey and the module-level freshness maps, so it does not need the effect closure.

Move VisibilityResumeBatch, VisibilityResumeEnvironment, VisibilityResumeMissing, and the operations from recordVisibilityResumeSnapshotReceipt through beginVisibilityResume into a module such as session-tabs-visibility-resume-reconciliation.ts. Return a small handle that the effect wires into the subscription specs. This keeps the effect focused on subscription lifecycle and makes the reconciliation logic directly unit-testable without rendering the hook.

Defer this if you prefer to land the behavior first.

src/renderer/src/runtime/web-session-tabs-sync-window-visibility.test.tsx (1)

11-49: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚖️ Poor tradeoff

Consider extracting the shared test fixtures into a helper module.

This file and src/renderer/src/runtime/web-session-tabs-sync-visibility-collision.test.tsx duplicate ENV_A, ENV_B, WORKTREE, MIRROR_KEY, createDeferred, settle, setDocumentVisibility, seedRemoteMirrorState, the RuntimeSubscription types, and the runtimeSubscribe recorder. MIRROR_KEY also encodes the private \u0001/\u0000 wire format of useRuntimeSessionMirrorEnvironmentKey in both files, so a format change requires two edits.

Move the constants, fixture builders, and subscription recorder into a module such as web-session-tabs-sync-mirror-test-fixtures.ts. Keep the vi.mock factories in each test file, because they must hoist per file.

Defer this if you prefer to land the coverage first.

Also applies to: 126-193


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 3975a3e8-d78e-4930-ab8f-ebc520d72146

📥 Commits

Reviewing files that changed from the base of the PR and between 56b6d84 and c94db07.

📒 Files selected for processing (5)
  • src/renderer/src/runtime/web-session-tabs-sync-visibility-collision.test.tsx
  • src/renderer/src/runtime/web-session-tabs-sync-window-visibility.test.tsx
  • src/renderer/src/runtime/web-session-tabs-sync.ts
  • src/renderer/src/runtime/window-visibility-subscription-parking.test.ts
  • src/renderer/src/runtime/window-visibility-subscription-parking.ts

nwparker and others added 3 commits August 11, 2026 00:16
- Back off the park delay after a park the user undoes quickly; each resume
  re-enumerates every paired host, so short hide/reveal churn now stops
  parking instead of paying that cost per cycle.
- Expire the active-worktree omission fence one visibility generation after
  the inventory that set it, and name the unfiltered-inventory invariant it
  depends on.
- Never skip the unchanged resume inventory for a worktree whose repair
  replay is already armed.

Co-authored-by: Orca <[email protected]>
# Conflicts:
#	src/renderer/src/runtime/web-session-tabs-sync.ts
@nwparker
nwparker merged commit 94a4756 into main Aug 11, 2026
44 checks passed
nwparker added a commit that referenced this pull request Aug 11, 2026
The stream-gating hook (#13608) and the subscription parking installer
(#13621) each reimplemented `isWindowVisible() || isDocumentVisibilityProvenStale()`
plus its visibilitychange + stale-recovery subscription, and each carried
its own 500ms park delay that agreed only by coincidence.

Extract both into `lib/window-park-visibility.ts` and leave the two
consumers as thin wrappers: `useWindowStreamVisible` feeds the snapshot
and subscribe into `useSyncExternalStore`, the parking installer calls
them imperatively. The subscribe now always uses the defensive
`typeof document` guard the parking side already had, and registers
stale recovery before the visibilitychange listener so the stale latch
is cleared before the callback reads it.

Both park delays now derive from one `WINDOW_HIDE_PARK_GRACE_MS`: they
debounce the same signal against the same user behaviour (a quick
app-switch round trip). The parking side's 8x reveal-side backoff stays
where it is - that models its own resume cost, not the grace window.

Renderer-authoritative gating (#13622 native chat, #13634 editor panels)
is deliberately left alone; it keys off Zustand routing state, not OS
visibility.

Also switch the active-runtime ref writes in web-session-tabs-sync to
`useLayoutEffect` so no resume event can land between paint and the
passive flush, and correct the stale comment above them - the install
effect reads neither ref (both readers are gated on `isVisibilityResume`).
nwparker added a commit that referenced this pull request Sep 2, 2026
…g destruction (#17981)

* fix(remote): stop one unlabelled inventory tombstoning a live worktree 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

* fix(agent-status): stop a reconnect replay restamping the staleness clock

#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
nwparker added a commit that referenced this pull request Sep 2, 2026
…rifiable, not idle (#18012)

* fix(remote): stop one unlabelled inventory tombstoning a live worktree 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

* fix(agent-status): stop a reconnect replay restamping the staleness clock

#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

* fix(sidebar): stop a stale agent row claiming the pane is empty

A stale non-`done` entry decayed to `idle` whether or not Orca still held the
pane's PTY, so "we lost the reporting stream" and "nothing is running here" were
the same display class. Split the destination on evidence already computed: with
a live PTY the row is `unverifiable` and reports the observer's own fact — how
long the silence has run — so the user can apply context Orca has no way to know.
With no PTY it stays `idle`.

Smart sort gains class 4 for it, between working (3) and idle (now 5): still
plausibly the most important pane, never outranking one that is reporting, and
never a claim that the agent finished. `unverifiable` stays renderer-local; the
dashboard card projection publishes today's `idle` because that vocabulary is
validated against a fixed allowlist in main and read by older pop-outs.

AGENT_STATUS_STALE_AFTER_MS is unchanged.

* fix(agent-status): decay a mirrored remote row on the replica's own clock

A paired client mirrored a remote host's status rows verbatim, host wall clock
included, and the staleness gate then computed `rendererNow - hostStamp`. The
effective window was 30 minutes plus or minus the two machines' skew: a host
running fast held every remote row permanently fresh, a host running slow decayed
them on arrival. The constant was never the lever there — the subtraction
straddled two clocks.

The replica now stamps `mirroredEvidenceReceivedAt` from its own clock when the
authority's observation advances, carries it forward across an exact repaint (a
restated observation is not a new one), and decays against it. Both sides of the
subtraction come from one machine; locally observed rows carry no stamp and are
unchanged.

The alternative the type comment named — carrying the authority's freshness
verdict — was rejected: a verdict is computed at publish time and cannot age
between snapshots, so once the host goes quiet the replica would hold `fresh`
forever. That is precisely the loss-of-contact case the window exists for.
AGENT_STATUS_STALE_AFTER_MS is unchanged; the clock rules move to
agent-status-freshness.ts to keep agent-status-types.ts under its line budget.
paidaxingyo666 pushed a commit to paidaxingyo666/Manta that referenced this pull request Sep 3, 2026
…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
paidaxingyo666 pushed a commit to paidaxingyo666/Manta that referenced this pull request Sep 3, 2026
…rifiable, not idle (stablyai#18012)

* 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

* fix(sidebar): stop a stale agent row claiming the pane is empty

A stale non-`done` entry decayed to `idle` whether or not Orca still held the
pane's PTY, so "we lost the reporting stream" and "nothing is running here" were
the same display class. Split the destination on evidence already computed: with
a live PTY the row is `unverifiable` and reports the observer's own fact — how
long the silence has run — so the user can apply context Orca has no way to know.
With no PTY it stays `idle`.

Smart sort gains class 4 for it, between working (3) and idle (now 5): still
plausibly the most important pane, never outranking one that is reporting, and
never a claim that the agent finished. `unverifiable` stays renderer-local; the
dashboard card projection publishes today's `idle` because that vocabulary is
validated against a fixed allowlist in main and read by older pop-outs.

AGENT_STATUS_STALE_AFTER_MS is unchanged.

* fix(agent-status): decay a mirrored remote row on the replica's own clock

A paired client mirrored a remote host's status rows verbatim, host wall clock
included, and the staleness gate then computed `rendererNow - hostStamp`. The
effective window was 30 minutes plus or minus the two machines' skew: a host
running fast held every remote row permanently fresh, a host running slow decayed
them on arrival. The constant was never the lever there — the subtraction
straddled two clocks.

The replica now stamps `mirroredEvidenceReceivedAt` from its own clock when the
authority's observation advances, carries it forward across an exact repaint (a
restated observation is not a new one), and decays against it. Both sides of the
subtraction come from one machine; locally observed rows carry no stamp and are
unchanged.

The alternative the type comment named — carrying the authority's freshness
verdict — was rejected: a verdict is computed at publish time and cannot age
between snapshots, so once the host goes quiet the replica would hold `fresh`
forever. That is precisely the loss-of-contact case the window exists for.
AGENT_STATUS_STALE_AFTER_MS is unchanged; the clock rules move to
agent-status-freshness.ts to keep agent-status-types.ts under its line budget.

Mirror-Of: 266b2ea
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…blyai#13621)

* perf(remote): park hidden session mirrors

* perf(renderer): bound visibility resume cost and repair fences

- Back off the park delay after a park the user undoes quickly; each resume
  re-enumerates every paired host, so short hide/reveal churn now stops
  parking instead of paying that cost per cycle.
- Expire the active-worktree omission fence one visibility generation after
  the inventory that set it, and name the unfiltered-inventory invariant it
  depends on.
- Never skip the unchanged resume inventory for a worktree whose repair
  replay is already armed.

Co-authored-by: Orca <[email protected]>

* fix(renderer): move active-runtime ref writes out of render

Co-authored-by: Orca <[email protected]>

---------

Co-authored-by: Orca <[email protected]>
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…yai#13778)

The stream-gating hook (stablyai#13608) and the subscription parking installer
(stablyai#13621) each reimplemented `isWindowVisible() || isDocumentVisibilityProvenStale()`
plus its visibilitychange + stale-recovery subscription, and each carried
its own 500ms park delay that agreed only by coincidence.

Extract both into `lib/window-park-visibility.ts` and leave the two
consumers as thin wrappers: `useWindowStreamVisible` feeds the snapshot
and subscribe into `useSyncExternalStore`, the parking installer calls
them imperatively. The subscribe now always uses the defensive
`typeof document` guard the parking side already had, and registers
stale recovery before the visibilitychange listener so the stale latch
is cleared before the callback reads it.

Both park delays now derive from one `WINDOW_HIDE_PARK_GRACE_MS`: they
debounce the same signal against the same user behaviour (a quick
app-switch round trip). The parking side's 8x reveal-side backoff stays
where it is - that models its own resume cost, not the grace window.

Renderer-authoritative gating (stablyai#13622 native chat, stablyai#13634 editor panels)
is deliberately left alone; it keys off Zustand routing state, not OS
visibility.

Also switch the active-runtime ref writes in web-session-tabs-sync to
`useLayoutEffect` so no resume event can land between paint and the
passive flush, and correct the stale comment above them - the install
effect reads neither ref (both readers are gated on `isVisibilityResume`).
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…rifiable, not idle (stablyai#18012)

* 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

* fix(sidebar): stop a stale agent row claiming the pane is empty

A stale non-`done` entry decayed to `idle` whether or not Orca still held the
pane's PTY, so "we lost the reporting stream" and "nothing is running here" were
the same display class. Split the destination on evidence already computed: with
a live PTY the row is `unverifiable` and reports the observer's own fact — how
long the silence has run — so the user can apply context Orca has no way to know.
With no PTY it stays `idle`.

Smart sort gains class 4 for it, between working (3) and idle (now 5): still
plausibly the most important pane, never outranking one that is reporting, and
never a claim that the agent finished. `unverifiable` stays renderer-local; the
dashboard card projection publishes today's `idle` because that vocabulary is
validated against a fixed allowlist in main and read by older pop-outs.

AGENT_STATUS_STALE_AFTER_MS is unchanged.

* fix(agent-status): decay a mirrored remote row on the replica's own clock

A paired client mirrored a remote host's status rows verbatim, host wall clock
included, and the staleness gate then computed `rendererNow - hostStamp`. The
effective window was 30 minutes plus or minus the two machines' skew: a host
running fast held every remote row permanently fresh, a host running slow decayed
them on arrival. The constant was never the lever there — the subtraction
straddled two clocks.

The replica now stamps `mirroredEvidenceReceivedAt` from its own clock when the
authority's observation advances, carries it forward across an exact repaint (a
restated observation is not a new one), and decays against it. Both sides of the
subtraction come from one machine; locally observed rows carry no stamp and are
unchanged.

The alternative the type comment named — carrying the authority's freshness
verdict — was rejected: a verdict is computed at publish time and cannot age
between snapshots, so once the host goes quiet the replica would hold `fresh`
forever. That is precisely the loss-of-contact case the window exists for.
AGENT_STATUS_STALE_AFTER_MS is unchanged; the clock rules move to
agent-status-freshness.ts to keep agent-status-types.ts under its line budget.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant