fix(native-chat): retry not-yet-flushed transcripts instead of settling into a permanent error (#8418)

* fix(native-chat): retry not-yet-flushed transcripts instead of settling into a permanent error

A freshly-created session's transcript .jsonl lands on disk seconds to
minutes after the process starts. Native chat's one-shot read raced that
first flush: a miss became a permanent "No transcript found" error and
the live-tail subscription silently degraded to a no-op, so the pane
never recovered even after the file appeared.

- transcript-reader/read-cache: mark the miss with notFound so callers
  can tell "not flushed yet" from a real parse/IO error (never cached).
- transcript-watch: poll resolve+install (500ms backoff, 5s cap) for the
  subscription's lifetime instead of returning a dead no-op watcher.
- use-native-chat-live-session: retry a notFound read with backoff for
  up to 60s while staying in the loading state, and let live appends
  render over a stale initial-read error.

Fixes #8401

Claude-Session: https://claude.ai/code/session_01HA5g3X7wCakBttBpDru9Fp

* fix(native-chat): address CodeRabbit review — ENOENT retryable, content over spinner, blank-id guard, unref poll timer

- transcript-reader: an ENOENT after a successful resolve is the same
  first-flush/rotation race as an unresolved path — mark it notFound.
- use-native-chat-live-session: live appends landing mid-retry render
  instead of the loading state (mirrors the stale-error gate).
- transcript-watch: bail out for a blank session id with no explicit
  file (nothing to resolve-poll), and unref the poll timer so headless
  serve shutdown is never held open by an unresolvable session.

Claude-Session: https://claude.ai/code/session_01HA5g3X7wCakBttBpDru9Fp

---------

Co-authored-by: kaynan <kaynan.camargo@terceiro-sky.com.br>
This commit is contained in:
Kaynan Sampaio de Camargo
2026-07-13 12:45:46 -07:00
committed by GitHub
co-authored by kaynan
parent 527c692b71
commit dc4fb2aa03
10 changed files with 649 additions and 51 deletions
@@ -293,3 +293,129 @@ describe('useNativeChatLiveSession — transport routing', () => {
expect(latest?.messages.map((m) => m.id)).not.toContain('stale')
})
})
// Regression for #8401: a just-created Claude Code session's transcript can
// take up to minutes to exist on disk, so the first readSession commonly
// misses. Before this fix, the hook settled into a permanent 'error' phase
// on that first miss and never recovered.
describe('useNativeChatLiveSession — notFound retry (#8401)', () => {
const AGENT = 'claude' as const
const SESSION = 'sess-notfound'
const PANE = 'pane-notfound'
const roots: Root[] = []
let latest: NativeChatLiveSession | null = null
function Probe(props: UseNativeChatLiveSessionArgs): null {
latest = useNativeChatLiveSession(props)
return null
}
async function render(props: UseNativeChatLiveSessionArgs): Promise<Root> {
const container = document.createElement('div')
const root = createRoot(container)
roots.push(root)
await act(async () => {
root.render(createElement(Probe, props))
await Promise.resolve()
await Promise.resolve()
})
return root
}
beforeEach(() => {
useAppStore.setState({ agentStatusByPaneKey: {} })
})
afterEach(() => {
for (const root of roots.splice(0)) {
act(() => root.unmount())
}
latest = null
vi.clearAllMocks()
resetMockTransports()
vi.useRealTimers()
})
it('retries a notFound miss with backoff and settles into ready without ever exposing an error', async () => {
vi.useFakeTimers()
const transport = getMockTransport('env-1')
transport.readSession
.mockResolvedValueOnce({ error: 'No transcript found', notFound: true })
.mockResolvedValueOnce({ messages: [assistant('a-1', 'hello')] })
await render({ paneKey: PANE, agent: AGENT, sessionId: SESSION, runtimeEnvironmentId: 'env-1' })
expect(latest?.status).toBe('loading')
// First backoff step (1s) fires the second readSession, which resolves.
await act(async () => {
await vi.advanceTimersByTimeAsync(1_000)
})
expect(latest?.status).not.toBe('error')
expect(transport.readSession).toHaveBeenCalledTimes(2)
expect(latest?.messages.map((m) => m.id)).toContain('a-1')
})
it('surfaces an error once the ~60s retry window is exhausted', async () => {
vi.useFakeTimers()
const transport = getMockTransport('env-1')
transport.readSession.mockResolvedValue({ error: 'No transcript found', notFound: true })
await render({ paneKey: PANE, agent: AGENT, sessionId: SESSION, runtimeEnvironmentId: 'env-1' })
expect(latest?.status).toBe('loading')
await act(async () => {
await vi.advanceTimersByTimeAsync(70_000)
})
expect(latest?.status).toBe('error')
expect(latest?.error).toBe('No transcript found')
})
it('renders live-appended content instead of loading while the read is still retrying', async () => {
vi.useFakeTimers()
const transport = getMockTransport('env-1')
transport.readSession.mockResolvedValue({ error: 'No transcript found', notFound: true })
let onAppended: ((messages: NativeChatMessage[]) => void) | null = null
transport.subscribe.mockImplementationOnce(
(_args: unknown, cb: (m: NativeChatMessage[]) => void) => {
onAppended = cb
return transport.unsubscribe
}
)
await render({ paneKey: PANE, agent: AGENT, sessionId: SESSION, runtimeEnvironmentId: 'env-1' })
expect(latest?.status).toBe('loading')
// The watcher's first drain lands mid-retry — content must win over the spinner.
await act(async () => {
onAppended?.([assistant('a-early', 'landed during retry')])
})
expect(latest?.status).not.toBe('loading')
expect(latest?.messages.map((m) => m.id)).toContain('a-early')
})
it('renders live-appended content even when the initial read settled into a permanent error', async () => {
const transport = getMockTransport('env-1')
transport.readSession.mockResolvedValueOnce({ error: 'unreadable transcript' })
let onAppended: ((messages: NativeChatMessage[]) => void) | null = null
transport.subscribe.mockImplementationOnce(
(_args: unknown, cb: (m: NativeChatMessage[]) => void) => {
onAppended = cb
return transport.unsubscribe
}
)
await render({ paneKey: PANE, agent: AGENT, sessionId: SESSION, runtimeEnvironmentId: 'env-1' })
expect(latest?.status).toBe('error')
await act(async () => {
onAppended?.([assistant('a-late', 'landed late')])
})
expect(latest?.status).not.toBe('error')
expect(latest?.error).toBeUndefined()
expect(latest?.messages.map((m) => m.id)).toContain('a-late')
})
})
@@ -76,6 +76,17 @@ function nextSubscriptionId(): string {
return `native-chat-${subscriptionCounter}-${Date.now()}`
}
// Why: a brand-new session's transcript can take seconds to minutes to appear
// on disk (#8401), so a `notFound` miss retries — 1s/2s/4s/8s then every 10s —
// until the window below elapses.
const NOTFOUND_RETRY_DELAYS_MS = [1_000, 2_000, 4_000, 8_000]
const NOTFOUND_RETRY_FIXED_DELAY_MS = 10_000
const NOTFOUND_RETRY_WINDOW_MS = 60_000
function notFoundRetryDelayMs(attempt: number): number {
return NOTFOUND_RETRY_DELAYS_MS[attempt] ?? NOTFOUND_RETRY_FIXED_DELAY_MS
}
type ReadState =
| { phase: 'loading' }
| { phase: 'ready'; messages: NativeChatMessage[] }
@@ -161,31 +172,50 @@ export function useNativeChatLiveSession(
}
let cancelled = false
let retryTimer: ReturnType<typeof setTimeout> | null = null
const retryStartedAt = Date.now()
// Re-bound as a plain const: TS doesn't retain the `!sessionId` narrowing
// above inside a nested function declaration (it's hoisted, so the
// narrowing can't be proven to hold at every call site).
const activeSessionId = sessionId
limitRef.current = NATIVE_CHAT_INITIAL_LIMIT
setRead({ phase: 'loading' })
replaceList(appendMergerRef.current, [])
setAppended([])
setHasMore(false)
void transport
.readSession(agent, sessionId, limitRef.current, transcriptPath ?? undefined)
.then((result) => {
if (cancelled) {
return
}
if (result && 'error' in result) {
setRead({ phase: 'error', error: result.error })
return
}
const messages = result?.messages ?? []
setRead({ phase: 'ready', messages })
setHasMore(hasMoreNativeChatHistory(messages.length, limitRef.current))
})
.catch((err: unknown) => {
if (!cancelled) {
setRead({ phase: 'error', error: err instanceof Error ? err.message : String(err) })
}
})
function loadSession(attempt: number): void {
void transport
.readSession(agent, activeSessionId, limitRef.current, transcriptPath ?? undefined)
.then((result) => {
if (cancelled) {
return
}
if (result && 'error' in result) {
// A not-yet-flushed transcript: stay in 'loading' and retry with
// backoff instead of settling into a permanent error (#8401).
if (result.notFound && Date.now() - retryStartedAt < NOTFOUND_RETRY_WINDOW_MS) {
retryTimer = setTimeout(() => {
retryTimer = null
loadSession(attempt + 1)
}, notFoundRetryDelayMs(attempt))
return
}
setRead({ phase: 'error', error: result.error })
return
}
const messages = result?.messages ?? []
setRead({ phase: 'ready', messages })
setHasMore(hasMoreNativeChatHistory(messages.length, limitRef.current))
})
.catch((err: unknown) => {
if (!cancelled) {
setRead({ phase: 'error', error: err instanceof Error ? err.message : String(err) })
}
})
}
loadSession(0)
const subscriptionId = nextSubscriptionId()
const unsubscribe = transport.subscribe(
@@ -208,6 +238,10 @@ export function useNativeChatLiveSession(
return () => {
cancelled = true
if (retryTimer) {
clearTimeout(retryTimer)
retryTimer = null
}
// Desktop returns a sync unsubscribe fn; the web RPC bridge returns a
// Promise instead (and can't deliver streaming callbacks). Calling a
// Promise as a function crashed the whole chat view, so resolve it first
@@ -304,9 +338,23 @@ export function useNativeChatLiveSession(
sessionId,
agent,
hookState,
loading: read.phase === 'loading',
...(read.phase === 'error' ? { error: read.error } : {})
// Why: a watcher append (fix for #8401) can land content while the read is
// still retrying ('loading') or after it settled into 'error' — in both
// cases showing the live content beats a spinner or a stale error, so each
// override only applies while there is nothing appended to render.
loading: read.phase === 'loading' && appended.length === 0,
...(read.phase === 'error' && appended.length === 0 ? { error: read.error } : {})
})
return { ...session, hasMore, loadingEarlier, loadEarlier }
}, [assembledMessages, read, sessionId, agent, hookState, hasMore, loadingEarlier, loadEarlier])
}, [
assembledMessages,
read,
sessionId,
agent,
hookState,
hasMore,
loadingEarlier,
loadEarlier,
appended
])
}