Repository navigation
fix(native-chat): retry not-yet-flushed transcripts instead of settling into a permanent error - #8418
Conversation
…ng 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 stablyai#8401 Claude-Session: https://claude.ai/code/session_01HA5g3X7wCakBttBpDru9Fp
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (6)
🚧 Files skipped from review as they are similar to previous changes (4)
📝 WalkthroughWalkthroughNative chat transcript handling now distinguishes temporary missing transcript files from permanent read errors. Cached reads avoid retaining unresolved misses, transcript watchers retry resolution and installation with cancellable polling, and the renderer retries not-found session reads within a bounded window. Tests cover reader metadata, cache behavior, watcher lifecycle, renderer retries, live updates, and the first-flush end-to-end race. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
src/main/native-chat/transcript-reader.ts (1)
39-52: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick winTreat read-time ENOENT as retryable
If
createReadStream()fails withENOENTafter a path has already been resolved, this returns a plain error andreadNativeChatTranscriptCached()can keep serving that result until the file mtime changes. Mark that casenotFoundtoo so transient rotation/race misses stay retryable.🐛 Proposed fix
} catch (err) { - return { error: errorMessage(err) } + const notFound = (err as { code?: string })?.code === 'ENOENT' + return { error: errorMessage(err), ...(notFound ? { notFound: true } : {}) } }src/renderer/src/components/native-chat/use-native-chat-live-session.ts (1)
335-359: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winRelax
loadingonce live content exists. The retry loop can keepread.phase === 'loading'whileassembledMessagesalready includes appended content, andmergeNativeChatLiveSession()still turns that into a loading session unconditionally. Mirror theerrorgate here withappended.length === 0, and add a regression test for an append landing during the retry window.
🧹 Nitpick comments (1)
src/main/native-chat/transcript-watch.ts (1)
252-274: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winConsider
.unref()on the resolve-poll timer, consistent with the codebase's existing pattern.
src/main/ipc/pty.tsalready unrefs its background timers so they don't block process exit.pollTimerhere has no bound duration for a session that truly never resolves, and doesn't unref — relevant for this repo's headlessorca servemode where Node's event loop (not Electron's window lifecycle) governs shutdown.♻️ Proposed fix
function scheduleAttempt(): void { if (closed) { return } pollTimer = setTimeout(() => { pollTimer = null void runAttempt() }, delay) + if (typeof pollTimer.unref === 'function') { + pollTimer.unref() + }
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 637776f3-de29-4949-b856-b76d44a6ced6
📒 Files selected for processing (10)
src/main/native-chat/transcript-read-cache.test.tssrc/main/native-chat/transcript-read-cache.tssrc/main/native-chat/transcript-reader.test.tssrc/main/native-chat/transcript-reader.tssrc/main/native-chat/transcript-watch.test.tssrc/main/native-chat/transcript-watch.tssrc/preload/api-types.tssrc/renderer/src/components/native-chat/use-native-chat-live-session.test.tssrc/renderer/src/components/native-chat/use-native-chat-live-session.tstests/e2e/native-chat-first-flush-race.spec.ts
…nt 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
|
Addressed all four CodeRabbit findings in f5d180c:
Re-ran locally: full typecheck, the native-chat unit suites (80 passed), and the E2E spec (passed). |
Reconciles the stablyai#8418 not-yet-flushed transcript fix with this PR's transcript-watch/live-session rework — both behaviors are preserved: - transcript-watch: main's resolve-poll (attemptInstall + subscribeViaResolvePoll, 500ms→5s backoff, lifetime retry) now wraps this PR's live-tail engine. Install gates on file existence since the engine watches the parent directory, so a missing transcript defers to the poll instead of surfacing an initial-drain error; the engine moved to transcript-watch-engine.ts to stay under the max-lines cap. - use-native-chat-live-session: main's notFound readSession retry (60s window, staying in loading) merged into this PR's readSession seed; both yield to the first authoritative snapshot frame. Main's appended-gated loading/error overrides combined with this PR's stateStartedAt self-heal. - Error-snapshot tests now simulate a persistent real read error (EISDIR via a directory at the transcript path) instead of a missing file, which is a retry case under stablyai#8401 semantics. The live-session notFound tests use a transport that emits no first frame, modelling the server-side resolve poll; append assertions use this PR's frame shape.
…ng into a permanent error (stablyai#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 stablyai#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 <[email protected]>
Summary
Fixes #8401.
Opening native chat on a freshly-created session could permanently fail with "Could not load conversation — No transcript found for claude session
<uuid>" even though the session was alive. The agent writes the transcript.jsonllazily — from ~3s up to minutes after the process starts — and native chat raced that first flush in two places, neither of which ever recovered:readSessionwas one-shot: a miss settled into a permanent error state;What this PR changes:
transcript-reader.ts/transcript-read-cache.ts— a resolve miss is now markednotFound: trueon the error result, so callers can distinguish "not flushed yet" (retry-worthy) from a real parse/IO error (surfaced immediately). The miss is never cached (unchanged), so retries always re-resolve — this keeps the retry semantics below the read cache, as the issue notes.transcript-watch.ts— when the transcript isn't resolvable yet (or vanishes between resolve andwatch()), the subscription now retries resolve+install in the background (500ms → 5s capped backoff) for the subscription's lifetime instead of returning a dead no-op. First drain still reads from byte 0, so the whole file is emitted once it appears.unsubscribe()cancels the poll or closes the watcher, whichever state it's in.use-native-chat-live-session.ts— anotFoundread retries with backoff (1s/2s/4s/8s, then 10s) for up to 60s while staying in the loading state, instead of settling into an error. If the transcript takes even longer (the issue documents delays of minutes), the watcher poll above still picks it up: live appends now render over a stale initial-read error.The retry loop lives client-side, so each remote
readSessionRPC stays a single short call — no risk of hitting the runtime transport's 15s per-call timeout on SSH/remote hosts.Screenshots
E2E run of the new Playwright spec (
tests/e2e/native-chat-first-flush-race.spec.ts) on this branch — native chat opened on a session whose transcript does not exist on disk yet:Before the transcript exists — loading, no error (previously this errored):
Transcript flushed ~seconds later — the same pane hydrates live, no reload:
(Behavior fix in an existing surface — no new UI, so light theme only; the error/loading/chat components themselves are unchanged.)
Testing
pnpm lintpnpm typecheckpnpm testpnpm buildAll of the above ran locally (macOS arm64): full vitest suite (28,687 passed), all three tsconfig typechecks, oxlint + repo custom checks (styled-scrollbars, reliability-gates, max-lines-ratchet, feature-wall-assets, macOS entitlements),
build:unpack+ packaged-CLI smoke.New tests, each verified to fail on
mainand pass with the fix:transcript-reader.test.ts/transcript-read-cache.test.ts— miss carriesnotFound: true; real read errors don't; the miss is never cached.transcript-watch.test.ts— subscribing to a not-yet-created file installs the watcher once the file appears and emits its content; unsubscribing mid-poll leaves no watcher or timer alive.use-native-chat-live-session.test.ts— notFound→retry→hydrate never exposes an error; exhausting the retry window surfaces the error honestly; a late watcher append renders content over a stale initial-read error.tests/e2e/native-chat-first-flush-race.spec.ts— end-to-end regression: real Electron app, native chat toggled on a pane whose hook-reportedtranscriptPathdoesn't exist yet; asserts loading (never the error), then live hydration once the file is written.AI Review Report
Reviewed with Claude Code on two axes (repo standards + issue-as-spec), findings adjudicated and addressed:
fs/timers and renderer TS. Paths built withpath.joinin tests; production code only consumes resolved paths. No shortcuts/labels/shell behavior touched.notFoundfield rides through both transports verbatim — desktop IPC (structured clone) and runtime RPC (the handler returns the error branch unchanged; verified insrc/main/runtime/rpc/methods/native-chat.ts). Retry loops are client-side so each RPC stays one short call under the 15s transport timeout. Transport-level failures (timeout/incompatible runtime) intentionally do not carrynotFound— they are not misses, and the remote subscribe path already has its own reconnect logic.drain()); duplicated rationale comments were consolidated.Security Audit
notFound) and re-uses the existing resolver/decoder pipeline unchanged.notFoundis an additive, serializable field on an existing result shape; no new channels or RPC methods.existsSync/glob discipline is unchanged, and the watcher only ever watches a path the resolver produced.unsubscribe()(covered by the watcher-count leak test); renderer retry timers are cleared in the effect cleanup.Notes
https://claude.ai/code/session_01HA5g3X7wCakBttBpDru9Fp