Skip to content

The agent that grows with you

fix(desktop): skip transcript reads for a session with no row yet

chelsealongddd0cc694490
diff --git a/apps/desktop/src/app/contrib/hooks/use-background-sync.test.ts b/apps/desktop/src/app/contrib/hooks/use-background-sync.test.ts
index a2803a25552..0efb4e23736 100644
--- a/apps/desktop/src/app/contrib/hooks/use-background-sync.test.ts
+++ b/apps/desktop/src/app/contrib/hooks/use-background-sync.test.ts
@@ -1,6 +1,7 @@
import { act, cleanup, renderHook, waitFor } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { markSessionCreatedThisRun } from '@/app/session/hooks/use-session-actions/created-this-run'
import { type ChatMessage, toChatMessages } from '@/lib/chat-messages'
import { createClientSessionState } from '@/lib/chat-runtime'
import { sessionListFingerprint, sessionMessagesSignature } from '@/lib/session-signatures'
@@ -355,6 +356,23 @@ describe('active transcript refresh', () => {
expect(updateSessionState).toHaveBeenCalledTimes(1)
})
+ it('skips a freshly minted, still-empty draft tile instead of 404ing on its unpersisted row (#123622)', async () => {
+ const runtimeId = 'runtime-draft-tile-123622'
+ const storedId = 'stored-draft-tile-123622'
+
+ publishSessionState(runtimeId, createClientSessionState(storedId))
+ markSessionCreatedThisRun(storedId)
+
+ await reconcileTileTranscriptsForTest({
+ tiles: [{ runtimeId, storedSessionId: storedId }],
+ requestSequenceRef: { current: 0 },
+ signatureRef: { current: new Map() },
+ updateSessionState: vi.fn()
+ })
+
+ expect(getLatestSessionMessages).not.toHaveBeenCalled()
+ })
+
it('does not reconcile a busy tile when the main pane is idle', async () => {
const runtimeId = 'runtime-busy-tile'
const storedId = 'stored-busy-tile'
@@ -805,6 +823,20 @@ describe('reconcileActiveTranscript', () => {
expect(messages.map(message => message.id)).toContain(optimisticId)
})
+ it('skips a freshly minted, still-empty draft instead of 404ing on its unpersisted row (#123622)', async () => {
+ // A dedicated id, never reused by another test, so marking it "created this
+ // run" cannot leak into an unrelated case sharing ACTIVE_STORED_ID.
+ const draftStoredId = 'stored-draft-123622'
+ const fixture = makeRefresh()
+
+ fixture.selectedStoredSessionIdRef.current = draftStoredId
+ markSessionCreatedThisRun(draftStoredId)
+
+ await fixture.refresh()
+
+ expect(getLatestSessionMessages).not.toHaveBeenCalled()
+ })
+
it('keeps one failed assistant bubble when refresh rebuilds the same tail turn under a new id', async () => {
const fixture = makeRefresh()
fixture.state.messages = [
diff --git a/apps/desktop/src/app/contrib/hooks/use-background-sync.ts b/apps/desktop/src/app/contrib/hooks/use-background-sync.ts
index 31531fdade1..c9c6b3ffe0d 100644
--- a/apps/desktop/src/app/contrib/hooks/use-background-sync.ts
+++ b/apps/desktop/src/app/contrib/hooks/use-background-sync.ts
@@ -6,6 +6,7 @@ import {
graftRefreshedTailOntoBackfill,
olderPageReader
} from '@/app/chat/transcript-backfill'
+import { sessionCreatedThisRun } from '@/app/session/hooks/use-session-actions/created-this-run'
import { preserveLocalPendingTurnMessages } from '@/app/session/hooks/use-session-actions/utils'
import { getLatestSessionMessages, type ProfileScope } from '@/hermes'
import {
@@ -291,6 +292,14 @@ export async function reconcileTileTranscripts({
}
const messagesAtRequest = $sessionStates.get()[runtimeSessionId]?.messages
+
+ // A freshly minted draft tile has no state.db row until the first prompt
+ // persists it (#123622) — reading its transcript before anything was ever
+ // sent only ever 404s.
+ if (!messagesAtRequest?.length && sessionCreatedThisRun(storedSessionId)) {
+ continue
+ }
+
// Passive: a hidden tile's refresh must never cold-start its owner
// backend or hold a pool slot (#103375); no warm backend = retry next tick.
const latest = await getLatestSessionMessages(storedSessionId, profileScope, { passive: true })
@@ -545,6 +554,13 @@ export async function reconcileActiveTranscript({
// while HTTP was in flight. Never let that older read replace newer text.
const messagesAtRequest = $sessionStates.get()[runtimeSessionId]?.messages
+ // A freshly minted draft has no state.db row until the first prompt persists it
+ // (#123622) — reading its transcript before anything was ever sent only ever
+ // 404s, since an empty local view already IS the correct (empty) render.
+ if (!messagesAtRequest?.length && sessionCreatedThisRun(storedSessionId)) {
+ return
+ }
+
try {
const profileScope: ProfileScope = profileScopeForTranscriptSession(stored)
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/created-this-run.ts b/apps/desktop/src/app/session/hooks/use-session-actions/created-this-run.ts
new file mode 100644
index 00000000000..7fb48ee79d3
--- /dev/null
+++ b/apps/desktop/src/app/session/hooks/use-session-actions/created-this-run.ts
@@ -0,0 +1,24 @@
+// Stored ids created in THIS renderer run. A brand-new session lives only in the
+// gateway's in-memory map until its first turn persists a state.db row — so if a
+// respawning/flapping backend drops it, both resume RPC and the REST transcript
+// 404 even though the user just made it. We must NOT treat that as "gone" (which
+// yanks them to a fresh draft — the "new sessions clear themselves" bug); the
+// bounded retry rebinds it when the backend returns. Boot-into-a-stale-last-id
+// (NOT in this set) still legitimately drops to a draft.
+//
+// Split into its own module (rather than living inside use-session-actions/index.ts)
+// so a lean transcript-reading hook can check it without pulling in the whole
+// session-actions import graph.
+const createdThisRun = new Set<string>()
+
+export function markSessionCreatedThisRun(storedSessionId: string): void {
+ createdThisRun.add(storedSessionId)
+}
+
+/** True while `storedSessionId` was minted by this window this run and may still have
+ * no state.db row (drafts persist lazily on the first prompt, #123622) — callers about
+ * to read its transcript before anything was ever sent should skip the request instead
+ * of 404ing against a row that cannot exist yet. */
+export function sessionCreatedThisRun(storedSessionId: string): boolean {
+ return createdThisRun.has(storedSessionId)
+}
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 283281427fa..07512d36a06 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
@@ -159,6 +159,7 @@ import { sessionContextDrift } from '../session-context-drift'
import { singleFlightSessionResume } from '../use-prompt-actions/single-flight-resume'
import { sessionCreateOverrideParams, type SessionCreateOverrides, type SessionSeedMessage } from './create-overrides'
+import { markSessionCreatedThisRun, sessionCreatedThisRun } from './created-this-run'
import { captureDisplayHydration } from './display-hydration'
import { reconcilePersistedLiveTurn } from './persisted-live-turn'
import { provisionalTranscriptPaint, transcriptRestScope } from './provisional-transcript'
@@ -224,15 +225,6 @@ interface SessionActionsOptions {
) => ClientSessionState
}
-// Stored ids created in THIS renderer run. A brand-new session lives only in the
-// gateway's in-memory map until its first turn persists a state.db row — so if a
-// respawning/flapping backend drops it, both resume RPC and the REST transcript
-// 404 even though the user just made it. We must NOT treat that as "gone" (which
-// yanks them to a fresh draft — the "new sessions clear themselves" bug); the
-// bounded retry rebinds it when the backend returns. Boot-into-a-stale-last-id
-// (NOT in this set) still legitimately drops to a draft.
-const createdThisRun = new Set<string>()
-
const branchMessagesFingerprint = (messages: BranchMessage[]): string =>
JSON.stringify(messages.map(({ content, role }) => [role, content]))
@@ -815,7 +807,7 @@ export function useSessionActions({
ensureSessionState(created.session_id, stored)
if (stored) {
- createdThisRun.add(stored)
+ markSessionCreatedThisRun(stored)
// Seed the sidebar preview with the user's first message so the row
// reads meaningfully while the turn is in flight, instead of flashing
// "Untitled session" until the turn persists and auto-title runs. The
@@ -1069,7 +1061,7 @@ export function useSessionActions({
return
}
- createdThisRun.add(stored)
+ markSessionCreatedThisRun(stored)
// Seed the per-runtime cache so the tile renders immediately without a
// redundant resume. Only add the row to the SIDEBAR when `listed` — an
@@ -2445,7 +2437,7 @@ export function useSessionActions({
}
const verdict = goneSessionVerdict({
- createdThisRun: createdThisRun.has(storedSessionId),
+ createdThisRun: sessionCreatedThisRun(storedSessionId),
stillListed,
switchInFlight:
$gatewaySwitching.get() ||
diff --git a/apps/desktop/src/components/assistant-ui/thread/use-timeline-history.test.tsx b/apps/desktop/src/components/assistant-ui/thread/use-timeline-history.test.tsx
index 0d982e47359..c88a437185a 100644
--- a/apps/desktop/src/components/assistant-ui/thread/use-timeline-history.test.tsx
+++ b/apps/desktop/src/components/assistant-ui/thread/use-timeline-history.test.tsx
@@ -21,6 +21,10 @@ vi.mock('@/store/profile', () => ({ $activeGatewayProfile: atom('default') }))
vi.mock('@/store/session', () => ({ $connection: atom({ mode: 'local' }), getSessionOwnerHint: () => undefined }))
vi.mock('@/store/transcript-tail', () => ({ pageHonorsLatestOrder: () => true, transcriptTailState: () => undefined }))
+const { sessionCreatedThisRun } = vi.hoisted(() => ({ sessionCreatedThisRun: vi.fn(() => false) }))
+
+vi.mock('@/app/session/hooks/use-session-actions/created-this-run', () => ({ sessionCreatedThisRun }))
+
const page = (ids: number[], more = false) => ({
entries: ids.map(id => ({ row_id: id, preview: `Prompt ${id}` })),
pagination: { next_cursor: more ? ids.at(-1) : null, has_more: more }
@@ -30,6 +34,7 @@ beforeEach(() => {
vi.resetModules()
vi.useFakeTimers()
api.mockReset()
+ sessionCreatedThisRun.mockReset().mockReturnValue(false)
})
afterEach(() => {
@@ -73,4 +78,19 @@ describe('timeline history index', () => {
})
expect(api).toHaveBeenCalledTimes(2)
})
+
+ it('does not fetch a freshly minted, still-empty draft (#123622)', async () => {
+ view.$messages = atom<Array<{ id: string; role: string; rowId?: number }>>([])
+ sessionCreatedThisRun.mockReturnValue(true)
+ const { useTimelineHistory } = await import('./use-timeline-history')
+
+ renderHook(() => useTimelineHistory())
+
+ await act(async () => {
+ vi.advanceTimersByTime(200)
+ await Promise.resolve()
+ })
+
+ expect(api).not.toHaveBeenCalled()
+ })
})
diff --git a/apps/desktop/src/components/assistant-ui/thread/use-timeline-history.ts b/apps/desktop/src/components/assistant-ui/thread/use-timeline-history.ts
index 282cd06f730..6c373fdf5ae 100644
--- a/apps/desktop/src/components/assistant-ui/thread/use-timeline-history.ts
+++ b/apps/desktop/src/components/assistant-ui/thread/use-timeline-history.ts
@@ -1,6 +1,7 @@
import { useCallback, useEffect, useState } from 'react'
import { useSessionView } from '@/app/chat/session-view'
+import { sessionCreatedThisRun } from '@/app/session/hooks/use-session-actions/created-this-run'
import { useStoreSelector } from '@/lib/use-session-slice'
import { $activeGatewayProfile } from '@/store/profile'
import { $connection, getSessionOwnerHint } from '@/store/session'
@@ -39,6 +40,13 @@ export function useTimelineHistory() {
return
}
+ // A freshly minted draft has no state.db row until the first prompt persists
+ // it (#123622) — fetching its timeline before then only ever 404s, since an
+ // empty local view already IS the correct (empty) render.
+ if (sessionCreatedThisRun(storedId) && view.$messages.get().length === 0) {
+ return
+ }
+
try {
const value = await fetchTimelineIndex(storedId, scope, beyondRowId)