Skip to content

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

Merged
AmethystLiang merged 2 commits into
stablyai:mainfrom
kaynansc:fix/native-chat-transcript-first-flush-race
Jul 13, 2026
Merged

AmethystLiang merged 2 commits into
stablyai:mainfrom
kaynansc:fix/native-chat-transcript-first-flush-race

Conversation

@kaynansc

Copy link
Copy Markdown
Contributor

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 .jsonl lazily — from ~3s up to minutes after the process starts — and native chat raced that first flush in two places, neither of which ever recovered:

  • the initial readSession was one-shot: a miss settled into a permanent error state;
  • the live-tail subscription silently became a no-op when the file wasn't resolvable yet, so even after the transcript appeared, nothing was ever emitted.

What this PR changes:

  • transcript-reader.ts / transcript-read-cache.ts — a resolve miss is now marked notFound: true on 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 and watch()), 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 — a notFound read 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 readSession RPC 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):

loading, no error

Transcript flushed ~seconds later — the same pane hydrates live, no reload:

hydrated

(Behavior fix in an existing surface — no new UI, so light theme only; the error/loading/chat components themselves are unchanged.)

Testing

  • pnpm lint
  • pnpm typecheck
  • pnpm test
  • pnpm build
  • Added or updated high-quality tests that would catch regressions, or explained why tests were not needed

All 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 main and pass with the fix:

  • transcript-reader.test.ts / transcript-read-cache.test.ts — miss carries notFound: 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-reported transcriptPath doesn'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:

  • Cross-platform (macOS/Linux/Windows): no platform branches introduced; pure Node fs/timers and renderer TS. Paths built with path.join in tests; production code only consumes resolved paths. No shortcuts/labels/shell behavior touched.
  • Remote/SSH/local: the notFound field rides through both transports verbatim — desktop IPC (structured clone) and runtime RPC (the handler returns the error branch unchanged; verified in src/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 carry notFound — they are not misses, and the remote subscribe path already has its own reconnect logic.
  • Agent/integration compatibility: the change is agnostic to which agent writes the transcript (claude/codex/grok all flow through the same resolver/reader/watcher); no provider-specific behavior added.
  • Performance: the resolve poll is one cheap glob per 5s (after backoff) per open native-chat pane, bounded by the subscription's lifetime; the read retry is bounded to a 60s window. Hot paths (drain/append/assembler) are untouched.
  • Review flags addressed: a transient resolve failure inside the poll loop is caught and treated as a miss (so the loop can't die to an unhandled rejection — same discipline as the existing drain()); duplicated rationale comments were consolidated.

Security Audit

  • No new input parsing: the change gates on an internally-produced boolean (notFound) and re-uses the existing resolver/decoder pipeline unchanged.
  • No command execution, no new IPC surface: notFound is an additive, serializable field on an existing result shape; no new channels or RPC methods.
  • Path handling: no user-controlled paths introduced; the resolver's existing existsSync/glob discipline is unchanged, and the watcher only ever watches a path the resolver produced.
  • Resource cleanup: the new poll timer and the installed watcher are both owned by the subscription and torn down synchronously in unsubscribe() (covered by the watcher-count leak test); renderer retry timers are cleared in the effect cleanup.
  • No dependencies added; no secrets/auth touched.

Notes

  • The issue suggests a dedicated "starting session…" string; this PR keeps the existing generic loading state during the retry window to avoid new localized UI strings in an experimental surface — happy to add one as a follow-up if you'd like.
  • If the first flush takes longer than the 60s read-retry window, the pane briefly shows the load error but self-heals the moment the transcript appears (watcher poll + live-append precedence) — no tab reload needed, which is the failure mode the issue reports.
  • X handle: @KaynanSampaio1

https://claude.ai/code/session_01HA5g3X7wCakBttBpDru9Fp

…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
@coderabbitai

coderabbitai Bot commented Jul 12, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: db8d4d1d-2826-4aa6-b934-d602036b0dd3

📥 Commits

Reviewing files that changed from the base of the PR and between 4e41fd2 and f5d180c.

📒 Files selected for processing (6)
  • src/main/native-chat/transcript-reader.test.ts
  • src/main/native-chat/transcript-reader.ts
  • src/main/native-chat/transcript-watch.test.ts
  • src/main/native-chat/transcript-watch.ts
  • src/renderer/src/components/native-chat/use-native-chat-live-session.test.ts
  • src/renderer/src/components/native-chat/use-native-chat-live-session.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • src/main/native-chat/transcript-watch.ts
  • src/main/native-chat/transcript-watch.test.ts
  • src/renderer/src/components/native-chat/use-native-chat-live-session.test.ts
  • src/renderer/src/components/native-chat/use-native-chat-live-session.ts

📝 Walkthrough

Walkthrough

Native 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)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 44.44% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: retrying not-yet-flushed native-chat transcripts instead of turning them into permanent errors.
Description check ✅ Passed The description includes all required sections and covers screenshots, testing, AI review, security, and notes, with cross-platform review explicitly addressed.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 win

Treat read-time ENOENT as retryable

If createReadStream() fails with ENOENT after a path has already been resolved, this returns a plain error and readNativeChatTranscriptCached() can keep serving that result until the file mtime changes. Mark that case notFound too 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 win

Relax loading once live content exists. The retry loop can keep read.phase === 'loading' while assembledMessages already includes appended content, and mergeNativeChatLiveSession() still turns that into a loading session unconditionally. Mirror the error gate here with appended.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 win

Consider .unref() on the resolve-poll timer, consistent with the codebase's existing pattern.

src/main/ipc/pty.ts already unrefs its background timers so they don't block process exit. pollTimer here has no bound duration for a session that truly never resolves, and doesn't unref — relevant for this repo's headless orca serve mode 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

📥 Commits

Reviewing files that changed from the base of the PR and between 7b12d38 and 4e41fd2.

📒 Files selected for processing (10)
  • src/main/native-chat/transcript-read-cache.test.ts
  • src/main/native-chat/transcript-read-cache.ts
  • src/main/native-chat/transcript-reader.test.ts
  • src/main/native-chat/transcript-reader.ts
  • src/main/native-chat/transcript-watch.test.ts
  • src/main/native-chat/transcript-watch.ts
  • src/preload/api-types.ts
  • src/renderer/src/components/native-chat/use-native-chat-live-session.test.ts
  • src/renderer/src/components/native-chat/use-native-chat-live-session.ts
  • tests/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
@kaynansc

Copy link
Copy Markdown
Contributor Author

Addressed all four CodeRabbit findings in f5d180c:

  • ENOENT at read time is now notFound — same first-flush/rotation race as an unresolved path, so it stays retry-worthy (and the cache never stores it: a vanished file has no finite mtime).
  • Live appends now render over the loading state too, mirroring the stale-error gate — a watcher drain landing mid-retry shows content instead of a spinner. Added a regression test.
  • Blank sessionId (with no explicit file) short-circuits to a no-op instead of resolve-polling an unresolvable target forever. Added a regression test.
  • pollTimer.unref() — consistent with src/main/ipc/pty.ts, so headless orca serve shutdown is never held open by a session that never resolves.

Re-ran locally: full typecheck, the native-chat unit suites (80 passed), and the E2E spec (passed).

@AmethystLiang
AmethystLiang merged commit dc4fb2a into stablyai:main Jul 13, 2026
1 check passed
brennanb2025 added a commit to gsxdsm/orca-stably that referenced this pull request Jul 13, 2026
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.
@AmethystLiang AmethystLiang added the orca-remote-server Remote Orca Server / orca serve / paired remote runtime label Jul 22, 2026
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

orca-remote-server Remote Orca Server / orca serve / paired remote runtime

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Native chat "No transcript found" on a just-created session that is actually alive

4 participants