Skip to content

The agent that grows with you

perf(desktop): durable transcript-tail cache — bot wakes paint at ~0ms

Tekniumf8767d1e7183
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 1ef6200e9b0..572c7e1f620 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
@@ -80,6 +80,7 @@ import {
} from '@/store/session-states'
import { broadcastSessionsChanged } from '@/store/session-sync'
import { forgetSessionUnread } from '@/store/session-unread'
+import { dropTranscriptTail, loadTranscriptTail, saveTranscriptTail } from '@/store/transcript-tail-cache'
import { isWatchWindow } from '@/store/windows'
import type { SessionCreateResponse, SessionMessage, SessionResumeResponse, UsageStats } from '@/types/hermes'
@@ -986,6 +987,9 @@ export function useSessionActions({
setBusy(running)
setAwaitingResponse(running)
syncSessionStateToView(cachedRuntimeId, activatedState)
+ // Durable tail refresh — same post-reconcile contract as the
+ // cold path's save below.
+ saveTranscriptTail(storedSessionId, activatedState.messages)
return
}
@@ -1026,6 +1030,36 @@ export function useSessionActions({
setMessages([])
}
+ // Instant paint from the durable tail cache: a cold resume (fresh app
+ // launch, reaped/respawned backend) otherwise shows a loader until the
+ // REST prefetch lands — which on a cold multi-profile boot waits behind
+ // a backend spawn. Painting the persisted tail here makes the wake
+ // visually complete at ~0ms (and satisfies the paint-first hydration
+ // wait). The paint is DISPLAY-ONLY: reconciliation below must treat the
+ // view as empty (see cachedTailPaint), because grafting the REST tail
+ // onto a stale cached tail would duplicate or misorder rows — the
+ // authoritative transcript REPLACES the cached paint when it lands.
+ // Same-selected re-resumes skip it — their transcript is already live.
+ let cachedTailPaint: ChatMessage[] | null = null
+
+ if (!resumedSameSelectedSession && $messages.get().length === 0) {
+ const cachedTail = loadTranscriptTail(storedSessionId)
+
+ if (cachedTail && selectedStoredSessionIdRef.current === storedSessionId) {
+ cachedTailPaint = cachedTail
+ setMessages(cachedTail)
+ }
+ }
+
+ // The reconciler's notion of "what was already on screen": a durable
+ // cached paint is provisional, not history — report empty so the
+ // authoritative transcript replaces it wholesale.
+ const viewMessagesForReconcile = (): ChatMessage[] => {
+ const current = $messages.get()
+
+ return cachedTailPaint !== null && current === cachedTailPaint ? [] : current
+ }
+
// A history load is not a live turn. Do not mark the incoming session
// busy — running ≠ loading, and a leftover true locked the composer.
busyRef.current = false
@@ -1055,8 +1089,8 @@ export function useSessionActions({
const watchWindow = isWatchWindow()
let localSnapshot = resumedSameSelectedSession
- ? preserveLocalPendingTurnMessages($messages.get(), resumeStartMessages)
- : $messages.get()
+ ? preserveLocalPendingTurnMessages(viewMessagesForReconcile(), resumeStartMessages)
+ : viewMessagesForReconcile()
let prefetchApplied = false
let prefetchedStoredSessionId: string | null = null
@@ -1117,8 +1151,8 @@ export function useSessionActions({
if (prefetchedResult) {
const previousMessages = resumedSameSelectedSession
- ? preserveLocalPendingTurnMessages($messages.get(), resumeStartMessages)
- : $messages.get()
+ ? preserveLocalPendingTurnMessages(viewMessagesForReconcile(), resumeStartMessages)
+ : viewMessagesForReconcile()
// Tail page + previously backfilled prefix (same-session re-resume).
const graftedPrefetch = graftRefreshedTailOntoBackfill(
@@ -1132,7 +1166,7 @@ export function useSessionActions({
prefetchedStoredSessionId = prefetchedResult.session_id || storedSessionId
}
- const currentMessages = $messages.get()
+ const currentMessages = viewMessagesForReconcile()
// Keep the local snapshot when resume would only reshuffle runtime
// projection. When the REST prefetch already hydrated the transcript,
@@ -1237,6 +1271,15 @@ export function useSessionActions({
// is safer than surfacing the in-flight turn alone). Recovery only
// ever appends, so this matches the final transcript's emptiness.
if (sessionShouldHaveTranscript(stored) && preferredMessages.length === 0) {
+ // Roll back a provisional cached-tail paint and drop its entry: the
+ // authoritative sources say this session has no transcript, so the
+ // cache no longer reflects backend truth and must not survive to
+ // mislead the retry (or the next wake).
+ if (cachedTailPaint !== null && $messages.get() === cachedTailPaint) {
+ setMessages([])
+ dropTranscriptTail(storedSessionId)
+ }
+
setActiveSessionId(null)
activeSessionIdRef.current = null
setResumeFailedSessionId(storedSessionId)
@@ -1295,6 +1338,12 @@ export function useSessionActions({
if (!chatMessageArraysEquivalent($messages.get(), messagesForView)) {
setMessages(messagesForView)
}
+
+ // Refresh the durable tail cache with the authoritative transcript so
+ // the NEXT wake of this session paints instantly (fresh launch,
+ // reaped backend). Post-reconcile only — never persist an optimistic
+ // or in-flight-recovered projection ahead of backend truth.
+ saveTranscriptTail(storedSessionId, messagesForView)
} catch (err) {
if (!isCurrentResume()) {
return
@@ -1318,8 +1367,8 @@ export function useSessionActions({
}
const previousMessages = resumedSameSelectedSession
- ? preserveLocalPendingTurnMessages($messages.get(), resumeStartMessages)
- : $messages.get()
+ ? preserveLocalPendingTurnMessages(viewMessagesForReconcile(), resumeStartMessages)
+ : viewMessagesForReconcile()
// Resume failed, so there is no live projection — the journal is the
// only carrier of a crashed turn's progress on this path.
@@ -1347,7 +1396,7 @@ export function useSessionActions({
// instead of toasting an error and hot-looping the bounded retry on a
// permanently-dead id. (Booting straight into a no-longer-existent
// last-session id is the common trigger.)
- if ($messages.get().length === 0 && isSessionGoneError(fallbackError)) {
+ if (viewMessagesForReconcile().length === 0 && isSessionGoneError(fallbackError)) {
// A 404 is only trustworthy from the backend that OWNS the session.
// A cross-profile open (Bots pane) races the gateway swap, so both
// lookups can land on a backend that never heard of the id (#88540).
@@ -1391,9 +1440,12 @@ export function useSessionActions({
return
}
- if ($messages.get().length === 0) {
+ if (viewMessagesForReconcile().length === 0) {
// Arm the self-heal ONLY when the window is still empty: the gateway
// resume rejected AND the REST fallback failed to paint a transcript.
+ // A durable cached-tail paint counts as EMPTY here — it's provisional
+ // display, not proof of a live transcript, and must not mask the
+ // stranded state from the retry machinery.
// That is the exact stranded state the loader latches on
// (messagesEmpty && !activeSessionId), and matches $resumeFailedSessionId's
// documented contract. If the REST fallback DID paint history, the
@@ -1692,6 +1744,8 @@ export function useSessionActions({
}
await deleteSession(storedSessionId, removed?.profile)
+ // A deleted session's cached tail must not resurrect on a recycled id.
+ dropTranscriptTail(storedSessionId)
// Only after the RPC lands — the optimistic eviction above can roll
// back, and a rolled-back row must keep its watermark/marker.
forgetSessionUnread(removedIds, removed?.profile)
diff --git a/apps/desktop/src/store/gateway-switch.ts b/apps/desktop/src/store/gateway-switch.ts
index 6c08cec5352..48e81381cad 100644
--- a/apps/desktop/src/store/gateway-switch.ts
+++ b/apps/desktop/src/store/gateway-switch.ts
@@ -24,6 +24,7 @@ import {
} from '@/store/session'
import { resetSessionPinMirror } from '@/store/session-pin-sync'
import { clearAllSessionStates } from '@/store/session-states'
+import { clearTranscriptTails } from '@/store/transcript-tail-cache'
// True while a soft gateway-mode apply is mid-flight (wipe → re-dial). Lets the
// boot hook suppress the backend-exit toast and keeps the cold-boot CONNECTING
@@ -86,6 +87,11 @@ export function wipeSessionListsForGatewaySwitch(): void {
// registry and any rail tab pointing into it go with them.
clearArtifactRegistry()
+ // Cached transcript tails belong to the PREVIOUS backend's sessions; a
+ // different backend can recycle stored ids, and painting another machine's
+ // conversation under a same-named id is worse than a loader. Wipe them.
+ clearTranscriptTails()
+
// Narrowed: account/marketplace/onboarding caches are global, not gateway-
// scoped, so a mode swap must not refetch them.
invalidateProfileScopedQueries()
diff --git a/apps/desktop/src/store/transcript-tail-cache.test.ts b/apps/desktop/src/store/transcript-tail-cache.test.ts
new file mode 100644
index 00000000000..6d941cd1c4c
--- /dev/null
+++ b/apps/desktop/src/store/transcript-tail-cache.test.ts
@@ -0,0 +1,94 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+
+import type { ChatMessage } from '@/lib/chat-messages'
+
+import {
+ clearTranscriptTails,
+ dropTranscriptTail,
+ loadTranscriptTail,
+ saveTranscriptTail
+} from './transcript-tail-cache'
+
+const msg = (id: string, chars = 10): ChatMessage =>
+ ({ id, parts: [{ text: 'x'.repeat(chars), type: 'text' }], role: 'assistant' }) as never
+
+beforeEach(() => {
+ window.localStorage.clear()
+})
+
+afterEach(() => {
+ window.localStorage.clear()
+})
+
+describe('transcript tail cache', () => {
+ it('round-trips a session tail keyed by stored id', () => {
+ saveTranscriptTail('sess-a', [msg('1'), msg('2')])
+
+ const loaded = loadTranscriptTail('sess-a')
+
+ expect(loaded).toHaveLength(2)
+ expect(loaded?.[0].id).toBe('1')
+ expect(loadTranscriptTail('sess-other')).toBeNull()
+ })
+
+ it('persists only the bounded tail of a long transcript', () => {
+ const long = Array.from({ length: 200 }, (_, index) => msg(`m${index}`))
+ saveTranscriptTail('sess-long', long)
+
+ const loaded = loadTranscriptTail('sess-long')
+
+ expect(loaded).toHaveLength(40)
+ expect(loaded?.[0].id).toBe('m160')
+ expect(loaded?.[39].id).toBe('m199')
+ })
+
+ it('falls back to a shorter tail rather than caching an oversized entry', () => {
+ // ~40 x 30KB ≈ 1.2MB > 256KB cap; 8 x 30KB ≈ 240KB fits.
+ const heavy = Array.from({ length: 40 }, (_, index) => msg(`h${index}`, 30_000))
+ saveTranscriptTail('sess-heavy', heavy)
+
+ const loaded = loadTranscriptTail('sess-heavy')
+
+ expect(loaded).toHaveLength(8)
+ expect(loaded?.[7].id).toBe('h39')
+ })
+
+ it('ignores empty saves and blank ids', () => {
+ saveTranscriptTail('', [msg('1')])
+ saveTranscriptTail('sess-empty', [])
+
+ expect(loadTranscriptTail('')).toBeNull()
+ expect(loadTranscriptTail('sess-empty')).toBeNull()
+ })
+
+ it('self-evicts a corrupt entry instead of returning garbage', () => {
+ window.localStorage.setItem('hermes.transcript-tail.v1:sess-bad', '{not json')
+
+ expect(loadTranscriptTail('sess-bad')).toBeNull()
+ expect(window.localStorage.getItem('hermes.transcript-tail.v1:sess-bad')).toBeNull()
+ })
+
+ it('drops a deleted session and wipes everything on a gateway re-home', () => {
+ saveTranscriptTail('sess-1', [msg('a')])
+ saveTranscriptTail('sess-2', [msg('b')])
+
+ dropTranscriptTail('sess-1')
+ expect(loadTranscriptTail('sess-1')).toBeNull()
+ expect(loadTranscriptTail('sess-2')).not.toBeNull()
+
+ clearTranscriptTails()
+ expect(loadTranscriptTail('sess-2')).toBeNull()
+ })
+
+ it('LRU-evicts the oldest sessions past the entry cap', () => {
+ for (let index = 0; index < 55; index += 1) {
+ saveTranscriptTail(`sess-${index}`, [msg(`m${index}`)])
+ }
+
+ // 50-entry cap: the first five saved are evicted, the newest survive.
+ expect(loadTranscriptTail('sess-0')).toBeNull()
+ expect(loadTranscriptTail('sess-4')).toBeNull()
+ expect(loadTranscriptTail('sess-5')).not.toBeNull()
+ expect(loadTranscriptTail('sess-54')).not.toBeNull()
+ })
+})
diff --git a/apps/desktop/src/store/transcript-tail-cache.ts b/apps/desktop/src/store/transcript-tail-cache.ts
new file mode 100644
index 00000000000..4010224d714
--- /dev/null
+++ b/apps/desktop/src/store/transcript-tail-cache.ts
@@ -0,0 +1,209 @@
+import type { ChatMessage } from '@/lib/chat-messages'
+
+// ── Durable transcript-tail cache (#89206 "feels instant" layer) ────────────
+// The in-memory warm cache (sessionStateByRuntimeIdRef) makes same-window
+// re-opens instant, but dies with the window — so every app launch, backend
+// reap, or profile respawn pays a full network round-trip before ANYTHING
+// paints, and on a cold multi-profile boot that round-trip sits behind a
+// backend spawn. This cache persists a bounded tail of each stored session's
+// transcript in localStorage: a wake paints the cached tail at ~0ms, the
+// paint-first hydration completes immediately, and the REST prefetch /
+// runtime resume reconcile the authoritative transcript when they land
+// (the existing reconcilers already treat painted content as "previous").
+//
+// Scope and bounds:
+// - TAIL ONLY (last TAIL_MESSAGES), size-capped per entry; oversized
+// 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'
+const TAIL_MESSAGES = 40
+const MAX_ENTRY_BYTES = 256 * 1024
+const MAX_ENTRIES = 50
+
+interface CacheEntry {
+ messages: ChatMessage[]
+ savedAt: number
+}
+
+function storage(): Storage | null {
+ try {
+ return window.localStorage
+ } catch {
+ return null
+ }
+}
+
+function readIndex(store: Storage): string[] {
+ try {
+ const raw = store.getItem(INDEX_KEY)
+ const parsed = raw ? JSON.parse(raw) : []
+
+ return Array.isArray(parsed) ? parsed.filter(id => typeof id === 'string') : []
+ } catch {
+ return []
+ }
+}
+
+function writeIndex(store: Storage, ids: string[]): void {
+ try {
+ store.setItem(INDEX_KEY, JSON.stringify(ids))
+ } catch {
+ // Quota — drop the index; entries become orphaned and are rewritten lazily.
+ }
+}
+
+function touchIndex(store: Storage, storedSessionId: string): void {
+ const ids = readIndex(store).filter(id => id !== storedSessionId)
+ ids.push(storedSessionId)
+
+ while (ids.length > MAX_ENTRIES) {
+ const evicted = ids.shift()
+
+ if (evicted) {
+ try {
+ store.removeItem(PREFIX + evicted)
+ } catch {
+ // best effort
+ }
+ }
+ }
+
+ writeIndex(store, ids)
+}
+
+/** Persist the tail of a session's transcript. No-op on empty/oversized. */
+export function saveTranscriptTail(storedSessionId: string, messages: ChatMessage[]): void {
+ const id = (storedSessionId ?? '').trim()
+ const store = storage()
+
+ if (!store || !id || !Array.isArray(messages) || messages.length === 0) {
+ return
+ }
+
+ const entry: CacheEntry = { messages: messages.slice(-TAIL_MESSAGES), savedAt: Date.now() }
+
+ let serialized: string
+
+ try {
+ serialized = JSON.stringify(entry)
+ } catch {
+ return // non-serializable parts (live handles) — skip, never throw
+ }
+
+ if (serialized.length > MAX_ENTRY_BYTES) {
+ // Retry with a shorter tail before giving up; a session dominated by a
+ // few huge tool results still caches its recent turns.
+ const shorter: CacheEntry = { messages: messages.slice(-8), savedAt: entry.savedAt }
+
+ try {
+ serialized = JSON.stringify(shorter)
+ } catch {
+ return
+ }
+
+ if (serialized.length > MAX_ENTRY_BYTES) {
+ return
+ }
+ }
+
+ try {
+ store.setItem(PREFIX + id, serialized)
+ touchIndex(store, id)
+ } catch {
+ // Quota exceeded — evict everything and retry once (small cache >> stale cache).
+ try {
+ clearTranscriptTails()
+ store.setItem(PREFIX + id, serialized)
+ touchIndex(store, id)
+ } 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 {
+ const id = (storedSessionId ?? '').trim()
+ const store = storage()
+
+ if (!store || !id) {
+ return null
+ }
+
+ let raw: null | string = null
+
+ try {
+ raw = store.getItem(PREFIX + id)
+ } catch {
+ return null
+ }
+
+ if (!raw) {
+ return null
+ }
+
+ try {
+ const parsed = JSON.parse(raw) as CacheEntry
+
+ if (!parsed || !Array.isArray(parsed.messages) || parsed.messages.length === 0) {
+ throw new Error('empty')
+ }
+
+ return parsed.messages
+ } catch {
+ try {
+ store.removeItem(PREFIX + id)
+ } catch {
+ // best effort
+ }
+
+ return null
+ }
+}
+
+/** Drop one session's cached tail (session deleted / cache poisoned). */
+export function dropTranscriptTail(storedSessionId: string): void {
+ const id = (storedSessionId ?? '').trim()
+ const store = storage()
+
+ if (!store || !id) {
+ return
+ }
+
+ try {
+ store.removeItem(PREFIX + id)
+ writeIndex(
+ store,
+ readIndex(store).filter(entry => entry !== id)
+ )
+ } catch {
+ // best effort
+ }
+}
+
+/** Wipe the whole cache (connection/mode re-home, quota recovery). */
+export function clearTranscriptTails(): void {
+ const store = storage()
+
+ if (!store) {
+ return
+ }
+
+ for (const id of readIndex(store)) {
+ try {
+ store.removeItem(PREFIX + id)
+ } catch {
+ // best effort
+ }
+ }
+
+ try {
+ store.removeItem(INDEX_KEY)
+ } catch {
+ // best effort
+ }
+}