Repository navigation
fix(ai-vault): stop the scan-stamp guard from deciding merged results - #14261
Conversation
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.
📝 WalkthroughWalkthroughAI 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 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)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
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.
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
📒 Files selected for processing (6)
src/main/ai-vault/session-list-results.test.tssrc/main/ai-vault/session-list-results.tssrc/renderer/src/components/right-sidebar/ai-vault-session-identity.test.tssrc/renderer/src/components/right-sidebar/ai-vault-session-identity.tssrc/renderer/src/components/right-sidebar/ai-vault-session-refresh.test.tssrc/renderer/src/components/right-sidebar/ai-vault-session-refresh.ts
| // 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) | ||
| }) |
There was a problem hiding this comment.
📐 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.
…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.
Summary
Follow-up to #14245, which made
scannedAtload-bearing again: the all-host merge stopped remintingDate.now()and now keeps the newest leg stamp, and the renderer reconciles session rows structurally beforesetState. Reviewing that change surfaced three loose ends, all in the seams it created.1. The stamp guard must not decide merged results
useAiVaultSessionRefreshskips the whole apply whenscannedAtmatches what it last applied: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 stampsL0off the desktop clock; a pairedruntime:host stampsR0off its own clock (runtime-session-scanner.ts:161preserves it).t=20s— the outer 15s cache expired, so the merge re-runs. The local leg is still a cache hit, so it replaysL0. The runtime leg re-scans and returns genuinely new sessions stampedR1.R1 < L0, so the merge returnsL0again — the same stamp it returned att=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
normalizeExecutionHostScoperather 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 yieldsscanResult === previous.2.
latestAiVaultScannedAtcompared stamps as stringsscannedAtisz.string()on the wire (session-list-result-validation.ts:91), not a pinnedtoISOString()shape. The merge validated it withDate.parseand then compared lexicographically, which inverts for legal ISO variants:...:05Zvs...:05.500Z...:05Zwins ('Z'>'.')...:05.500Zis 500 ms later...:10-05:00vs local...:10.000Z'-'<'.'), so accepted as pastThe 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.parseresult it already computed.3.
EMPTY_AI_VAULT_SESSIONSwas a shared mutable arrayEvery mounted hook returns the same instance before its first scan lands. No consumer mutates it today (checked:
filterAiVaultSessions,buildAiVaultSessionProjectById,useAiVaultSessionWorktreeMap,.length), but an in-placesortwould have leaked across panels. Frozen, and the hook now returnsreadonly 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 reusesscanResultandsessionsidentity, 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 acrossright-sidebar/,ai-vault/, andipc/.No wire, schema, or persisted-state change.
scannedAtstays an ISO string and is still read only by the renderer's refresh guard — mobile callsaiVault.listSessionsbut consumes onlysessions/issues(use-mobile-agent-history-state.ts:129), so no mobile-facing surface is touched.Made with Orca 🐋