Skip to content

The agent that grows with you

fix(desktop): migrate in-flight turn journal across stored-id rotation

Brooklyn Nicholsonebba2ac73558
diff --git a/apps/desktop/src/app/session/hooks/use-session-state-cache.test.tsx b/apps/desktop/src/app/session/hooks/use-session-state-cache.test.tsx
index 8833c80cfc9..3edb9fc71b9 100644
--- a/apps/desktop/src/app/session/hooks/use-session-state-cache.test.tsx
+++ b/apps/desktop/src/app/session/hooks/use-session-state-cache.test.tsx
@@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { group } from '@/components/pane-shell/tree/model'
import { $layoutTree, noteActiveTreeGroup } from '@/components/pane-shell/tree/store'
import type { ChatMessage } from '@/lib/chat-messages'
+import { purgeInFlightTurnJournals, resetInFlightTurnJournalStateForTests } from '@/lib/inflight-turn-journal'
import { $activeGatewayProfile } from '@/store/profile'
import {
$activeSessionStoredIdRotation,
@@ -337,6 +338,94 @@ describe('useSessionStateCache — stored-id rotation provenance', () => {
})
})
+// #77486 review follow-up (kvnloo): the journal under a pre-rotation stored id
+// is unreachable by every id a permanent delete holds, so it used to survive
+// until MAX_AGE_MS. Rotation now migrates it to the new tip.
+describe('useSessionStateCache — journal migration on stored-id rotation', () => {
+ beforeEach(() => {
+ // The 400ms persist throttle is real timer work; fake timers make the
+ // journaled write deterministic without racing the 15s test timeout.
+ vi.useFakeTimers()
+ resetInFlightTurnJournalStateForTests()
+ window.localStorage.clear()
+ })
+
+ afterEach(() => {
+ cleanup()
+ clearAllSessionStates()
+ setActiveSessionId(null)
+ setActiveSessionStoredIdRotation(null)
+ setSelectedStoredSessionId(null)
+ setSessions([])
+ $sessionTiles.set([])
+ window.localStorage.clear()
+ resetInFlightTurnJournalStateForTests()
+ vi.useRealTimers()
+ })
+
+ it('migrates the journaled in-flight tail to the new stored id so permanent delete reaches it', () => {
+ let cache!: Cache
+
+ setActiveSessionId('runtime-A')
+ setSelectedStoredSessionId('stored-A')
+ render(
+ <Harness activeSessionId="runtime-A" onReady={value => (cache = value)} selectedStoredSessionId="stored-A" />
+ )
+
+ // Busy turn journaled under the lineage tip A.
+ act(() => {
+ cache.updateSessionState('runtime-A', state => state, 'stored-A')
+ })
+
+ const assistantStreaming = assistantText('assistant-stream-1', 'partial answer')
+
+ assistantStreaming.pending = true
+
+ act(() => {
+ cache.updateSessionState(
+ 'runtime-A',
+ state => ({
+ ...state,
+ busy: true,
+ messages: [userMessage('u1', 'sensitive prompt'), assistantStreaming],
+ streamId: 'assistant-stream-1',
+ turnStartedAt: 1000
+ }),
+ 'stored-A'
+ )
+ })
+
+ act(() => {
+ vi.advanceTimersByTime(400)
+ })
+
+ const journalKey = (storedSessionId: string) =>
+ `hermes.desktop.inflightTurnJournal.v2:${encodeURIComponent(storedSessionId)}`
+
+ expect(window.localStorage.getItem(journalKey('stored-A'))).not.toBeNull()
+
+ // Compression rotates the same runtime's stored id A -> B through the REAL
+ // ensureSessionState path (updateSessionState delegates to it).
+ act(() => {
+ cache.updateSessionState('runtime-A', state => state, 'stored-B')
+ })
+
+ // The old key is gone and the new key holds the migrated snapshot.
+ expect(window.localStorage.getItem(journalKey('stored-A'))).toBeNull()
+ expect(window.localStorage.getItem(journalKey('stored-B'))).not.toBeNull()
+
+ // Permanent delete of the surviving lineage tip B reaches every copy: no
+ // journal key for A or B remains (the delete gesture holds B plus the
+ // lineage root; A is only reachable because the rotation migrated it).
+ act(() => {
+ purgeInFlightTurnJournals(['stored-B'])
+ })
+
+ expect(window.localStorage.getItem(journalKey('stored-A'))).toBeNull()
+ expect(window.localStorage.getItem(journalKey('stored-B'))).toBeNull()
+ })
+})
+
function Harness({ activeSessionId, onReady, selectedStoredSessionId }: HarnessProps) {
const busyRef: MutableRefObject<boolean> = { current: false }
diff --git a/apps/desktop/src/app/session/hooks/use-session-state-cache.ts b/apps/desktop/src/app/session/hooks/use-session-state-cache.ts
index a8dc799a26a..9c5e2e0adb3 100644
--- a/apps/desktop/src/app/session/hooks/use-session-state-cache.ts
+++ b/apps/desktop/src/app/session/hooks/use-session-state-cache.ts
@@ -5,7 +5,7 @@ import { PRIMARY_SESSION_VIEW } from '@/app/chat/session-view'
import type { ChatMessage } from '@/lib/chat-messages'
import { preserveLocalAssistantErrors } from '@/lib/chat-messages'
import { createClientSessionState } from '@/lib/chat-runtime'
-import { persistInFlightTurnState } from '@/lib/inflight-turn-journal'
+import { migrateInFlightTurnJournal, persistInFlightTurnState } from '@/lib/inflight-turn-journal'
import { setMutableRef } from '@/lib/mutable-ref'
import {
$activeSessionId,
@@ -193,6 +193,14 @@ export function useSessionStateCache({
if (existing.storedSessionId && existing.storedSessionId !== storedSessionId) {
runtimeIdByStoredSessionIdRef.current.delete(existing.storedSessionId)
+ // The journal under the pre-rotation id is keyed by a stored id
+ // nothing will name again (the reverse mapping above is gone and
+ // lineage resolution follows the tip), so a later permanent delete
+ // could not reach it. Re-key it to the new id — copy first, then
+ // delete — so recovery survives the rotation AND the delete
+ // gesture still reaches every copy (#77486).
+ migrateInFlightTurnJournal(existing.storedSessionId, storedSessionId)
+
// Re-home any open tile keyed on the pre-rotation id (#98622).
// Ungated on the active runtime: a background tile's conversation
// rotates here too, and its pane would otherwise keep the stale id
diff --git a/apps/desktop/src/lib/inflight-turn-journal.ts b/apps/desktop/src/lib/inflight-turn-journal.ts
index ab9db4015f8..3b8ba79b71f 100644
--- a/apps/desktop/src/lib/inflight-turn-journal.ts
+++ b/apps/desktop/src/lib/inflight-turn-journal.ts
@@ -1097,12 +1097,68 @@ export function clearInFlightTurnJournal(storedSessionId: null | string): void {
* was missed, which is the #77486 journal requirement).
*
* A session has more than one id, so callers pass every id they hold: the
- * stored tip, the durable lineage root, and (the sidebar delete) the
- * closing runtime id. The store keys on the stored id, so each id drains
- * its own key in a single pass; entries written by an older build under a
- * pre-rotation tip the caller no longer holds are NOT reachable this way —
- * those age out under `MAX_AGE_MS`, which is the retention floor this file
- * already documents. */
+ * stored tip, the durable lineage root, and (the sidebar delete) the closing
+ * runtime id. The store keys on the stored id, so each id drains its own key
+ * in a single pass; entries under a stored id NO live path can still name
+ * are NOT reachable this way — those age out under `MAX_AGE_MS`, which is
+ * the retention floor this file already documents. Rotation closes that gap:
+ * `migrateInFlightTurnJournal` re-keys an entry the moment its stored id
+ * rotates, so a mid-lineage tip cannot strand its journal key. */
+function migrateSnapshot(store: Storage, oldKey: string, newKey: string, raw: string): void {
+ // Copy first, delete second. A crash between the two writes leaves BOTH
+ // keys holding the same recoverable tail — resume folds either one — and
+ // the old key is still reachable by the id the deleter holds (tip, lineage
+ // root, runtime id), so nothing escapes the delete gesture. Deleting first
+ // would instead trade recovery for a crash window.
+ if (readRaw(store, newKey) === null && !writeRaw(store, newKey, raw)) {
+ return
+ }
+
+ removeRaw(store, oldKey)
+}
+
+/** Re-key a journaled in-flight tail when its session's stored id rotates
+ * (e.g. auto-compression forks a continuation: tip A -> tip B).
+ *
+ * The old stored id leaves every live index (`runtimeIdByStoredSessionId`,
+ * tiles, lineage resolution to the tip), so the key under it would otherwise
+ * be unreachable by a later permanent delete and simply age out after
+ * MAX_AGE_MS — a sensitive prompt tail surviving its session's delete.
+ * Move the entry to the new id so recovery keeps working and deletion by
+ * the new id reaches it. A null/cleared new id is a detach, not a rotation —
+ * the old id remains the session's live tip, so its key stays reachable and
+ * is left alone. */
+export function migrateInFlightTurnJournal(oldStoredSessionId: string, newStoredSessionId: null | string): void {
+ if (!oldStoredSessionId || !newStoredSessionId || oldStoredSessionId === newStoredSessionId) {
+ return
+ }
+
+ const store = storage()
+ const oldKey = sessionStorageKey(oldStoredSessionId)
+ const newKey = sessionStorageKey(newStoredSessionId)
+
+ if (!store || !oldKey || !newKey) {
+ return
+ }
+
+ const raw = readRaw(store, oldKey)
+
+ if (raw === null) {
+ return
+ }
+
+ // A tombstone or expired entry carries nothing recoverable — retire it.
+ const snapshot = raw === DISCARDED_SNAPSHOT_RAW ? null : parseSnapshot(raw)
+
+ if (!snapshot || isExpired(snapshot)) {
+ removeRaw(store, oldKey)
+
+ return
+ }
+
+ migrateSnapshot(store, oldKey, newKey, raw)
+}
+
export function purgeInFlightTurnJournals(sessionIds: readonly (null | string | undefined)[]): void {
const store = storage()