Skip to content

fix(ai-vault): stop the scan-stamp guard from deciding merged results - #14261

Merged
nwparker merged 1 commit into
mainfrom
nwparker/ai-vault-scan-stamp-guard-hardening
Aug 13, 2026
Merged

nwparker merged 1 commit into
mainfrom
nwparker/ai-vault-scan-stamp-guard-hardening

Conversation

@nwparker

Copy link
Copy Markdown
Contributor

Summary

Follow-up to #14245, which made scannedAt load-bearing again: the all-host merge stopped reminting Date.now() and now keeps the newest leg stamp, and the renderer reconciles session rows structurally before setState. Reviewing that change surfaced three loose ends, all in the seams it created.

1. The stamp guard must not decide merged results

useAiVaultSessionRefresh skips the whole apply when scannedAt matches what it last applied:

if (lastAppliedScanRef.current?.scopeKey === scanKey &&
    lastAppliedScanRef.current.scannedAt === result.scannedAt) {
  return
}

That guard is sound only when the stamp is a content token. For a single-host scan it is — one scanner mints it at scan completion, so two real scans can never collide. For 'all' it is not, and #14245 is what made that true: the merged stamp is now the newest leg's stamp, and legs run on independent clocks.

Concretely, with the local leg's 60s cache (cached-session-list.ts:20) and the 15s per-leg cache (ai-vault-host-leg-cache.ts:8):

  • t=0 — full scan. Local leg stamps L0 off the desktop clock; a paired runtime: host stamps R0 off its own clock (runtime-session-scanner.ts:161 preserves it).
  • t=20s — the outer 15s cache expired, so the merge re-runs. The local leg is still a cache hit, so it replays L0. The runtime leg re-scans and returns genuinely new sessions stamped R1.
  • If that host's clock lags the desktop by more than the elapsed time, R1 < L0, so the merge returns L0 again — the same stamp it returned at t=0, over changed content. The renderer hard-skips, and the new remote sessions stay invisible until the local leg's 60s TTL expires.

Bounded and self-healing, and the "a session just started" path uses force: true, which bypasses every cache — which is why this is a correctness cleanup rather than a release blocker. But it is the exact failure mode #14245 argues against: treating a wall-clock stamp as a content fingerprint.

The fix restricts the guard to single-host scopes and lets the structural reconcile decide for merged ones. The scope test routes through the shared normalizeExecutionHostScope rather than comparing to the 'all' literal, because the main process also merges for an empty or unrecognized scope (execution-host.ts:108-114) — a literal compare would silently drift from what actually merges.

Cost: merged scopes now pay one deep reconcile per refocus instead of a string compare — ~0.4 ms at the default 250-session limit, ~1.8 ms at 1000. The expensive part that #14245 set out to eliminate (sessionProjectById, the session×worktree path map, and the virtual list re-render) is still skipped, because the reconcile returns the previous result object and React bails out. A test pins that: an unchanged all-host body with a repeated stamp still yields scanResult === previous.

2. latestAiVaultScannedAt compared stamps as strings

scannedAt is z.string() on the wire (session-list-result-validation.ts:91), not a pinned toISOString() shape. The merge validated it with Date.parse and then compared lexicographically, which inverts for legal ISO variants:

stamps lexicographic chronological
...:05Z vs ...:05.500Z ...:05Z wins ('Z' > '.') ...:05.500Z is 500 ms later
...:10-05:00 vs local ...:10.000Z sorts below local ('-' < '.'), so accepted as past five hours in the future

The second row is the one that bites: the future-stamp rejection this function exists for could be bypassed by an offset-form stamp, pinning the merged stamp above every later local rescan and freezing the renderer guard for real. Now it compares parsed instants, using the Date.parse result it already computed.

3. EMPTY_AI_VAULT_SESSIONS was a shared mutable array

Every mounted hook returns the same instance before its first scan lands. No consumer mutates it today (checked: filterAiVaultSessions, buildAiVaultSessionProjectById, useAiVaultSessionWorktreeMap, .length), but an in-place sort would have leaked across panels. Frozen, and the hook now returns readonly AiVaultSession[] — no ripple, all three tsc projects clean.

Tests

Each new test was verified to fail against the pre-fix logic, not just pass against the new one:

  • ai-vault-session-refresh.test.ts — an all-host result whose merged stamp stood still but whose body grew is applied (fails when the guard runs for 'all'); a scope that normalizes to all-host is treated as merged (fails against a literal !== 'all'); an unchanged all-host body with a repeated stamp still reuses scanResult and sessions identity, so removing the guard did not reintroduce the churn.
  • session-list-results.test.ts — both inverting stamp pairs above (fails under lexicographic compare).
  • ai-vault-session-identity.test.ts — the sentinel is frozen.

The existing "skips state updates when a refresh returns the applied snapshot" test runs on 'local' scope and is the regression guard for keeping the single-host fast path.

Verification

typecheck:node, typecheck:web, typecheck:cli, oxlint and react-doctor all clean; 5224 tests pass across right-sidebar/, ai-vault/, and ipc/.

No wire, schema, or persisted-state change. scannedAt stays an ISO string and is still read only by the renderer's refresh guard — mobile calls aiVault.listSessions but consumes only sessions/issues (use-mobile-agent-history-state.ts:129), so no mobile-facing surface is touched.

Made with Orca 🐋

Follow-up to #14245. That PR made `scannedAt` meaningful again by keeping
the newest leg stamp on an all-host merge instead of reminting it, and made
the renderer reconcile session rows structurally. Three loose ends:

- An 'all' result is a merge of legs on independent clocks stamped with the
  newest leg, so the renderer's `scannedAt` equality guard could hard-skip a
  real change: a paired host whose clock lags the desktop can return new
  sessions while the merged stamp repeats, hiding them for up to the local
  leg's 60s TTL. Restrict the guard to single-host scopes, where the stamp is
  minted by one scanner at scan completion and equality does imply equal
  content. Merged scopes now let the structural reconcile decide, which costs
  one deep compare per refocus and keeps the identity reuse intact.
  The scope test routes through `normalizeExecutionHostScope` so it matches
  what the main process merges on, including an empty or unrecognized scope.

- `latestAiVaultScannedAt` compared stamps lexicographically after only
  checking `Date.parse` validity. `scannedAt` is `z.string()` on the wire, so
  a legal ISO variant orders wrongly: '...:05Z' sorts after '...:05.500Z',
  and a '-05:00' offset five hours in the future sorts below the local stamp
  and would have been accepted. Compare parsed instants instead.

- `EMPTY_AI_VAULT_SESSIONS` is shared by every mounted hook; freeze it and
  return `readonly AiVaultSession[]` so no consumer can mutate the sentinel.

Each test fails against the pre-fix logic.
@coderabbitai

coderabbitai Bot commented Aug 13, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

AI Vault timestamp merging now compares parsed instants, rejects invalid or future timestamps, and uses a captured current time for fallback values. Session refresh now structurally reconciles merged all-host results even when their scan timestamp is unchanged. The refresh hook returns readonly session collections. The shared empty session sentinel is frozen and tested. Tests cover timestamp formats, merged-scope normalization, changed session data, and object identity preservation.

Mergeability Score: ⚪ Minimal · up to 77fab

The PR hardens merged-session refresh handling, timestamp comparisons, and shared-state safety. No actionable merge-blocking risk remains; it is merge-ready after normal checks and review.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the changes and testing well, but it omits several required template sections, including the Linked Issue, Visual Proof, Review, and Checklist sections. Add the required template sections, include a valid linked issue, provide visual proof or an explicit N/A reason, and complete the testing, review, and checklist items.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the primary fix: preventing the scan-stamp guard from incorrectly deciding merged AI Vault results.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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
📝 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: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 24b4bd4f-3729-4833-a4ab-b527058cb987

📥 Commits

Reviewing files that changed from the base of the PR and between 2e8cf58 and 77fabc0.

📒 Files selected for processing (6)
  • src/main/ai-vault/session-list-results.test.ts
  • src/main/ai-vault/session-list-results.ts
  • src/renderer/src/components/right-sidebar/ai-vault-session-identity.test.ts
  • src/renderer/src/components/right-sidebar/ai-vault-session-identity.ts
  • src/renderer/src/components/right-sidebar/ai-vault-session-refresh.test.ts
  • src/renderer/src/components/right-sidebar/ai-vault-session-refresh.ts

Comment on lines +471 to +494
// The main process routes an empty or unrecognized scope to the same all-host
// merge, so the renderer has to read those as merged too or the guard returns
// for exactly the results it cannot reason about.
it('treats a scope that normalizes to all-host as merged', async () => {
const pinned = '2026-07-01T00:00:00.000Z'
listSessionsMock.mockResolvedValueOnce({
sessions: [makeVaultSession(1)],
issues: [],
scannedAt: pinned
})
await renderHook([], '' as ExecutionHostScope)
await flushMicrotasks()
expect(latest?.sessions).toHaveLength(1)

listSessionsMock.mockResolvedValueOnce({
sessions: [makeVaultSession(1), makeVaultSession(2)],
issues: [],
scannedAt: pinned
})
await advance(THROTTLE_MS + 1)
await fireWindowFocused()

expect(latest?.sessions).toHaveLength(2)
})

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Add an unrecognized-scope regression case.

Lines 471-473 require empty and unrecognized scopes to use merged reconciliation. This test exercises only ''. Add a repeated-scannedAt case for an unrecognized scope such as 'unknown-host' as ExecutionHostScope.

@nwparker
nwparker merged commit 298c765 into main Aug 13, 2026
45 checks passed
@nwparker
nwparker deleted the nwparker/ai-vault-scan-stamp-guard-hardening branch August 13, 2026 09:26
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…stablyai#14261)

Follow-up to stablyai#14245. That PR made `scannedAt` meaningful again by keeping
the newest leg stamp on an all-host merge instead of reminting it, and made
the renderer reconcile session rows structurally. Three loose ends:

- An 'all' result is a merge of legs on independent clocks stamped with the
  newest leg, so the renderer's `scannedAt` equality guard could hard-skip a
  real change: a paired host whose clock lags the desktop can return new
  sessions while the merged stamp repeats, hiding them for up to the local
  leg's 60s TTL. Restrict the guard to single-host scopes, where the stamp is
  minted by one scanner at scan completion and equality does imply equal
  content. Merged scopes now let the structural reconcile decide, which costs
  one deep compare per refocus and keeps the identity reuse intact.
  The scope test routes through `normalizeExecutionHostScope` so it matches
  what the main process merges on, including an empty or unrecognized scope.

- `latestAiVaultScannedAt` compared stamps lexicographically after only
  checking `Date.parse` validity. `scannedAt` is `z.string()` on the wire, so
  a legal ISO variant orders wrongly: '...:05Z' sorts after '...:05.500Z',
  and a '-05:00' offset five hours in the future sorts below the local stamp
  and would have been accepted. Compare parsed instants instead.

- `EMPTY_AI_VAULT_SESSIONS` is shared by every mounted hook; freeze it and
  return `readonly AiVaultSession[]` so no consumer can mutate the sentinel.

Each test fails against the pre-fix logic.
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