Skip to content

The agent that grows with you

fix(desktop): scope durable transcript-tail cache by owning profile/connection

Bruno Bza03f5302a224e
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts b/apps/desktop/src/app/session/hooks/use-session-actions/index.ts
index 436326d1dd3..57257b32740 100644
--- a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts
+++ b/apps/desktop/src/app/session/hooks/use-session-actions/index.ts
@@ -1272,7 +1272,8 @@ export function useSessionActions({
pendingClarify?.requestId ??
pendingClarifyState.cleared?.requestId ??
$clarifyRequests.get()[cachedRuntimeId]?.requestId
- )
+ ),
+ sessionRestScope
)
return
@@ -1327,7 +1328,7 @@ export function useSessionActions({
let cachedTailPaint: ChatMessage[] | null = null
if (!resumedSameSelectedSession && $messages.get().length === 0) {
- const cachedTail = loadTranscriptTail(storedSessionId)
+ const cachedTail = loadTranscriptTail(storedSessionId, sessionRestScope)
if (cachedTail && selectedStoredSessionIdRef.current === storedSessionId) {
cachedTailPaint = cachedTail
@@ -1564,7 +1565,7 @@ export function useSessionActions({
// mislead the retry (or the next wake).
if (cachedTailPaint !== null && $messages.get() === cachedTailPaint) {
setMessages([])
- dropTranscriptTail(storedSessionId)
+ dropTranscriptTail(storedSessionId, sessionRestScope)
}
setActiveSessionId(null)
@@ -1668,7 +1669,8 @@ export function useSessionActions({
pendingClarify?.requestId ??
pendingClarifyState.cleared?.requestId ??
$clarifyRequests.get()[resumed.session_id]?.requestId
- )
+ ),
+ sessionRestScope
)
} catch (err) {
if (!isCurrentResume()) {
@@ -2124,7 +2126,7 @@ export function useSessionActions({
await deleteSession(storedSessionId, removedOwner)
// A deleted session's cached tail must not resurrect on a recycled id.
- dropTranscriptTail(storedSessionId)
+ dropTranscriptTail(storedSessionId, removedOwner)
// Only after the RPC lands — the optimistic eviction above can roll
// back, and a rolled-back row must keep its watermark/marker.
forgetSessionUnread(removedIds, profile)
diff --git a/apps/desktop/src/store/transcript-tail-cache.test.ts b/apps/desktop/src/store/transcript-tail-cache.test.ts
index f889067783c..df64a0d3b9a 100644
--- a/apps/desktop/src/store/transcript-tail-cache.test.ts
+++ b/apps/desktop/src/store/transcript-tail-cache.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { ChatMessage } from '@/lib/chat-messages'
@@ -62,10 +62,10 @@ describe('transcript tail cache', () => {
})
it('self-evicts a corrupt entry instead of returning garbage', () => {
- window.localStorage.setItem('hermes.transcript-tail.v1:sess-bad', '{not json')
+ window.localStorage.setItem('hermes.transcript-tail.v2:sess-bad', '{not json')
expect(loadTranscriptTail('sess-bad')).toBeNull()
- expect(window.localStorage.getItem('hermes.transcript-tail.v1:sess-bad')).toBeNull()
+ expect(window.localStorage.getItem('hermes.transcript-tail.v2:sess-bad')).toBeNull()
})
it('drops a deleted session and wipes everything on a gateway re-home', () => {
@@ -110,7 +110,7 @@ describe('transcript tail cache', () => {
savedAt: Date.now()
}
- window.localStorage.setItem('hermes.transcript-tail.v1:sess-poisoned', JSON.stringify(poisoned))
+ window.localStorage.setItem('hermes.transcript-tail.v2:sess-poisoned', JSON.stringify(poisoned))
const loaded = loadTranscriptTail('sess-poisoned')
@@ -124,4 +124,73 @@ describe('transcript tail cache', () => {
expect(new Set(ids).size).toBe(2)
expect(ids[0]).toBe('call-b')
})
+
+ // ── Profile scoping (#94828) ─────────────────────────────────────────────
+ // Stored session ids are only unique WITHIN a profile's state.db, and
+ // localStorage survives profile switches in the same window. An unscoped
+ // key lets profile A's tail be painted against profile B's backend — the
+ // view then retries a session id that does not exist there ("session not
+ // found") on every wake. The durable cache must carry the same
+ // {connectionId, profile} scope as its in-memory twin (transcript-tail.ts).
+ describe('profile scoping (#94828)', () => {
+ it('never returns a tail cached under another profile', () => {
+ saveTranscriptTail('sess-x', [msg('a')], { profile: 'ai-energy' })
+
+ expect(loadTranscriptTail('sess-x', { profile: 'ai-energy' })).toHaveLength(1)
+ expect(loadTranscriptTail('sess-x', { profile: 'default' })).toBeNull()
+ expect(loadTranscriptTail('sess-x')).toBeNull()
+ })
+
+ it('keeps same-id tails on different connections distinct', () => {
+ saveTranscriptTail('sess-y', [msg('local-row')], { connectionId: 'local', profile: 'default' })
+ saveTranscriptTail('sess-y', [msg('remote-row')], { connectionId: 'conn:mimir', profile: 'default' })
+
+ expect(loadTranscriptTail('sess-y', { connectionId: 'local', profile: 'default' })?.[0].id).toBe('local-row')
+ expect(loadTranscriptTail('sess-y', { connectionId: 'conn:mimir', profile: 'default' })?.[0].id).toBe(
+ 'remote-row'
+ )
+ })
+
+ it('accepts a plain-profile string scope like the in-memory twin', () => {
+ saveTranscriptTail('sess-s', [msg('s')], 'rwa-africa')
+
+ expect(loadTranscriptTail('sess-s', 'rwa-africa')).toHaveLength(1)
+ expect(loadTranscriptTail('sess-s', 'other')).toBeNull()
+ })
+
+ it('drops only the scoped entry when a scope is given', () => {
+ saveTranscriptTail('sess-d', [msg('p1-row')], { profile: 'p1' })
+ saveTranscriptTail('sess-d', [msg('p2-row')], { profile: 'p2' })
+
+ dropTranscriptTail('sess-d', { profile: 'p1' })
+
+ expect(loadTranscriptTail('sess-d', { profile: 'p1' })).toBeNull()
+ expect(loadTranscriptTail('sess-d', { profile: 'p2' })).not.toBeNull()
+ })
+
+ it('purges pre-scoping v1 entries so a stale tail can never paint again', async () => {
+ const stale = {
+ messages: [{ id: 'old', parts: [{ text: 'x', type: 'text' }], role: 'assistant' }],
+ savedAt: Date.now()
+ }
+
+ window.localStorage.setItem('hermes.transcript-tail.v1:sess-legacy', JSON.stringify(stale))
+ window.localStorage.setItem('hermes.transcript-tail.v1-index', JSON.stringify(['sess-legacy']))
+
+ // Fresh module instance: the sweep runs once per window, and earlier
+ // tests in this file have already touched storage.
+ vi.resetModules()
+
+ try {
+ const fresh = await import('./transcript-tail-cache')
+
+ expect(fresh.loadTranscriptTail('sess-legacy')).toBeNull()
+ expect(fresh.loadTranscriptTail('sess-legacy', { profile: 'ai-energy' })).toBeNull()
+ expect(window.localStorage.getItem('hermes.transcript-tail.v1:sess-legacy')).toBeNull()
+ expect(window.localStorage.getItem('hermes.transcript-tail.v1-index')).toBeNull()
+ } finally {
+ vi.resetModules()
+ }
+ })
+ })
})
diff --git a/apps/desktop/src/store/transcript-tail-cache.ts b/apps/desktop/src/store/transcript-tail-cache.ts
index 5a881f00be1..40efce656d5 100644
--- a/apps/desktop/src/store/transcript-tail-cache.ts
+++ b/apps/desktop/src/store/transcript-tail-cache.ts
@@ -17,27 +17,106 @@ import { withUniqueToolCallIdsWithinMessage } from '@/lib/chat-messages'
// messages evict the entry rather than truncating a message mid-parts.
// - LRU across MAX_ENTRIES sessions; corrupt entries self-evict.
// - Same trust domain as state.db on the same disk — no new exposure.
-// - Keyed by stored session id (durable identity), never runtime id.
-
-const PREFIX = 'hermes.transcript-tail.v1:'
-const INDEX_KEY = 'hermes.transcript-tail.v1-index'
+// - Keyed by stored session id (durable identity), never runtime id,
+// SCOPED by the owning {connectionId, profile} (#94828). Stored ids are
+// only unique WITHIN one profile's state.db, and localStorage survives
+// profile switches in the same window: an unscoped key let profile A's
+// tail be painted against profile B's backend, which then retried a
+// session id that does not exist there ("session not found") on every
+// wake. The scope mirrors the in-memory twin's transcriptTailKey
+// (transcript-tail.ts). Entries persisted before scoping shipped (v1,
+// bare-id keys) carry no owner and are unreachable by construction —
+// they are swept once per window so a stale tail can never paint again.
+
+const PREFIX = 'hermes.transcript-tail.v2:'
+const LEGACY_ROOT = 'hermes.transcript-tail.v1'
+const INDEX_KEY = 'hermes.transcript-tail.v2-index'
const TAIL_MESSAGES = 40
const MAX_ENTRY_BYTES = 256 * 1024
const MAX_ENTRIES = 50
+/** Owning scope of an entry — same shape the REST layer threads through
+ * `getLatestSessionMessages(id, scope)` and the in-memory twin stores in
+ * each TranscriptTailState. */
+export type TranscriptTailScope =
+ | null
+ | string
+ | {
+ connectionId?: null | string
+ profile?: null | string
+ }
+
interface CacheEntry {
messages: ChatMessage[]
savedAt: number
}
+let legacyPurged = false
+
+/** One-time sweep of pre-scoping v1 entries (#94828): a bare-id key cannot
+ * be attributed to a profile, so it must never paint again. Best effort —
+ * worst case a stale entry lingers unread until quota eviction. */
+function purgeLegacyV1(store: Storage): void {
+ if (legacyPurged) {
+ return
+ }
+
+ legacyPurged = true
+
+ try {
+ const doomed: string[] = []
+
+ for (let index = 0; index < store.length; index += 1) {
+ const key = store.key(index)
+
+ if (key && key.startsWith(LEGACY_ROOT)) {
+ doomed.push(key)
+ }
+ }
+
+ for (const key of doomed) {
+ store.removeItem(key)
+ }
+ } catch {
+ // best effort
+ }
+}
+
function storage(): Storage | null {
try {
- return window.localStorage
+ const store = window.localStorage
+
+ purgeLegacyV1(store)
+
+ return store
} catch {
return null
}
}
+function normalizedScope(scope?: TranscriptTailScope): { connectionId: string; profile: string } | null {
+ if (typeof scope === 'string') {
+ return { connectionId: '', profile: scope.trim() || 'default' }
+ }
+
+ if (!scope) {
+ return null
+ }
+
+ return {
+ connectionId: String(scope.connectionId ?? '').trim(),
+ profile: String(scope.profile ?? '').trim() || 'default'
+ }
+}
+
+/** Index identity of an entry: the bare stored id (legacy/unscoped callers)
+ * or the JSON [connectionId, profile, storedId] composite. */
+function entrySuffix(storedSessionId: string, scope?: TranscriptTailScope): string {
+ const scoped = normalizedScope(scope)
+
+ return scoped ? JSON.stringify([scoped.connectionId, scoped.profile, storedSessionId]) : storedSessionId
+}
+
function readIndex(store: Storage): string[] {
try {
const raw = store.getItem(INDEX_KEY)
@@ -57,9 +136,9 @@ function writeIndex(store: Storage, ids: string[]): void {
}
}
-function touchIndex(store: Storage, storedSessionId: string): void {
- const ids = readIndex(store).filter(id => id !== storedSessionId)
- ids.push(storedSessionId)
+function touchIndex(store: Storage, suffix: string): void {
+ const ids = readIndex(store).filter(id => id !== suffix)
+ ids.push(suffix)
while (ids.length > MAX_ENTRIES) {
const evicted = ids.shift()
@@ -76,8 +155,14 @@ function touchIndex(store: Storage, storedSessionId: string): void {
writeIndex(store, ids)
}
-/** Persist the tail of a session's transcript. No-op on empty/oversized. */
-export function saveTranscriptTail(storedSessionId: string, messages: ChatMessage[]): void {
+/** Persist the tail of a session's transcript. No-op on empty/oversized.
+ * Pass the session's owning scope ({connectionId, profile}, or just the
+ * profile name) so the entry can only ever be read against that backend. */
+export function saveTranscriptTail(
+ storedSessionId: string,
+ messages: ChatMessage[],
+ scope?: TranscriptTailScope
+): void {
const id = (storedSessionId ?? '').trim()
const store = storage()
@@ -111,23 +196,26 @@ export function saveTranscriptTail(storedSessionId: string, messages: ChatMessag
}
}
+ const suffix = entrySuffix(id, scope)
+
try {
- store.setItem(PREFIX + id, serialized)
- touchIndex(store, id)
+ store.setItem(PREFIX + suffix, serialized)
+ touchIndex(store, suffix)
} catch {
// Quota exceeded — evict everything and retry once (small cache >> stale cache).
try {
clearTranscriptTails()
- store.setItem(PREFIX + id, serialized)
- touchIndex(store, id)
+ store.setItem(PREFIX + suffix, serialized)
+ touchIndex(store, suffix)
} catch {
// Storage genuinely unavailable; instant paint just won't happen.
}
}
}
-/** Cached tail for a stored session, or null. Corrupt entries self-evict. */
-export function loadTranscriptTail(storedSessionId: string): ChatMessage[] | null {
+/** Cached tail for a stored session, or null. Corrupt entries self-evict.
+ * Only entries saved under the SAME owning scope are returned (#94828). */
+export function loadTranscriptTail(storedSessionId: string, scope?: TranscriptTailScope): ChatMessage[] | null {
const id = (storedSessionId ?? '').trim()
const store = storage()
@@ -138,7 +226,7 @@ export function loadTranscriptTail(storedSessionId: string): ChatMessage[] | nul
let raw: null | string = null
try {
- raw = store.getItem(PREFIX + id)
+ raw = store.getItem(PREFIX + entrySuffix(id, scope))
} catch {
return null
}
@@ -163,7 +251,7 @@ export function loadTranscriptTail(storedSessionId: string): ChatMessage[] | nul
return parsed.messages.map(withUniqueToolCallIdsWithinMessage)
} catch {
try {
- store.removeItem(PREFIX + id)
+ store.removeItem(PREFIX + entrySuffix(id, scope))
} catch {
// best effort
}
@@ -172,8 +260,10 @@ export function loadTranscriptTail(storedSessionId: string): ChatMessage[] | nul
}
}
-/** Drop one session's cached tail (session deleted / cache poisoned). */
-export function dropTranscriptTail(storedSessionId: string): void {
+/** Drop one session's cached tail (session deleted / cache poisoned). With a
+ * scope, only that scope's entry is dropped — other backends' tails for the
+ * same stored id stay intact. */
+export function dropTranscriptTail(storedSessionId: string, scope?: TranscriptTailScope): void {
const id = (storedSessionId ?? '').trim()
const store = storage()
@@ -182,10 +272,12 @@ export function dropTranscriptTail(storedSessionId: string): void {
}
try {
- store.removeItem(PREFIX + id)
+ const suffix = entrySuffix(id, scope)
+
+ store.removeItem(PREFIX + suffix)
writeIndex(
store,
- readIndex(store).filter(entry => entry !== id)
+ readIndex(store).filter(entry => entry !== suffix)
)
} catch {
// best effort