Repository navigation
Fix cross-worktree chat leak: key native-chat transcript cache by resolved file path - #7341
Conversation
…olved file path
The process-global native-chat transcript parse cache keyed by
`${agent}:${sessionId}` while resolving the actual file via `transcriptPath`.
Two worktrees can present the SAME (agent, sessionId) with DIFFERENT transcript
files — e.g. the same session resumed/forked into a second worktree, re-homed
under the new cwd's project slug. Both then collide on one cache key; the mtime
guard only rescues them when the files' mtimes differ, so under concurrent agent
activity (mtimes momentarily coincide) worktree C's chat panel was served
worktree A's cached transcript.
Key the cache by the already-resolved absolute file path instead, so two
distinct files can never share an entry. The multi-client hit-rate goal is
preserved (all clients of one session resolve the same path against the same
runtime home). Adds a regression test that reproduces the leak (identical
mtimes, shared sessionId, distinct files).
Fixes #7326
📝 WalkthroughWalkthroughChangesThe transcript read cache now keys entries by resolved transcript file path instead of Estimated code review effort: Medium 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
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
🧹 Nitpick comments (2)
src/main/native-chat/transcript-read-cache.ts (1)
7-18: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueLong rationale comment exceeds guideline length.
This 12-line block explains important non-obvious history well, but the coding guideline requests short (1-2 line) comments for non-obvious behavior. Consider trimming to the essential "why" and moving the extended history/postmortem into the PR description or a linked issue reference.
As per coding guidelines, "When writing or modifying code driven by a design doc or non-obvious constraint, add a comment explaining why the code behaves the way it does. Keep comments short — one or two lines, capturing only the non-obvious reason."
Source: Coding guidelines
src/main/native-chat/transcript-read-cache.test.ts (1)
93-97: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueComment exceeds the 1-2 line guideline.
Same concern as the source file: this 5-line "Why" comment is longer than the guideline's recommended length for non-obvious-reason comments.
As per coding guidelines, "Keep comments short — one or two lines, capturing only the non-obvious reason."
Source: Coding guidelines
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: cca2459c-a104-4c12-a3ec-98f3ea89b464
📒 Files selected for processing (2)
src/main/native-chat/transcript-read-cache.test.tssrc/main/native-chat/transcript-read-cache.ts
| } | ||
|
|
||
| const key = cacheKey(agent, sessionId) | ||
| const key = cacheKey(agent, filePath) |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Inspect resolveSessionFilePath to confirm it returns an absolute/canonical path.
rg -n -A 20 'function resolveSessionFilePath' --type=tsRepository: stablyai/orca
Length of output: 151
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Locate the cache file and the path resolver, then inspect the relevant code.
git ls-files | rg 'src/main/native-chat/transcript-read-cache\.ts|resolveSessionFilePath|session.*file.*path|resolve.*file.*path'
# Show the file around the cache-key line.
if [ -f src/main/native-chat/transcript-read-cache.ts ]; then
echo '--- src/main/native-chat/transcript-read-cache.ts ---'
cat -n src/main/native-chat/transcript-read-cache.ts | sed -n '1,180p'
fi
# Search for the resolver definition and references.
rg -n -A 20 -B 10 'resolveSessionFilePath|cacheKey\(agent, filePath\)' src --type=tsRepository: stablyai/orca
Length of output: 38708
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Inspect the resolver helpers to determine the exact shape of returned paths.
cat -n src/main/native-chat/session-file-resolver.ts | sed -n '1,260p'Repository: stablyai/orca
Length of output: 5806
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Inspect the file walker and the hook plumbing that supplies transcriptPath.
rg -n -A 30 -B 10 'function walkSessionFiles|export async function walkSessionFiles|transcriptPath|providerSession\.transcriptPath|session\.transcriptPath|transcript_path' src --type=tsRepository: stablyai/orca
Length of output: 50370
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Inspect walkSessionFiles and its callers to see whether returned file paths are absolute/stable.
cat -n src/main/ai-vault/session-scanner-discovery.ts | sed -n '1,260p'Repository: stablyai/orca
Length of output: 3633
Normalize the transcript path before caching. resolveSessionFilePath can return the hook transcriptPath verbatim and otherwise whatever walkSessionFiles joined, so the same file is not guaranteed to map to one stable string. Canonicalize it before cacheKey(...) to avoid duplicate entries or stale cross-file hits.
Investigation notes (multi-agent root-cause, 2 rounds)Introducing commit: Ruled out (no second bug there): worktree surface mount/remount + React reconciliation reuse. Tab-switch doesn't remount surfaces (mounts are additive, pruned only on worktree deletion); every key is worktree-scoped or a Open follow-up (the residual noted in the description): the id-glob resolver fallback returns |
Post-review polish (no behavior change): - Correct the rationale comments: only session RESUME shares a session_id across worktrees (fork launches a fresh session id via a text prompt), and generalize away the Claude-specific "cwd slug" wording (Codex uses a global rollout store). - Drop the redundant cacheKey comment that restated the module header (AGENTS.md "Document the Why, briefly"). - Use the exported isTextBlock type guard in the regression test's text extraction instead of an inline `block.type === 'text' ? ... : ''`.
|
thanks |
Problem
Fixes #7326 — with 2+ worktrees open and concurrent agent activity, the native-chat ("agent chat/log") panel for one worktree (C) intermittently showed another worktree's (A) transcript content.
ELI5
Each worktree's chat panel asks one shared cache for its transcript, quoting a session id. Normally every session has its own id — no confusion. But if you resume the same session in a second worktree, both worktrees quote the same id, even though the agent is now writing to a different file. The cache was filed by id only, so it handed back whichever file it happened to load first. Worktree C asks for its own chat → gets worktree A's.
The fix files the cache by the file's actual path instead of the session id, so two different files can never be mixed up — even when they share a session id.
Root cause
src/main/native-chat/transcript-read-cache.tskeyed its process-global transcript parse cache by`${agent}:${sessionId}`— but resolved the actual file via the hook-reportedtranscriptPath:Two worktrees can present the same
(agent, sessionId)but different transcript files, so both collide on the single cache key<agent>:<session_id>. The mtime guard (cached.mtimeMs === mtime(fileC)) only rescues the collision when the two files' mtimes differ — under concurrent agent activity the files get written within the same millisecond bucket, theirmtimeMsmomentarily coincide, the guard passes, and pane C is served pane A's cached parse.This matches every reported symptom facet: intermittent (mtime-equality window), activity-driven (concurrent appends align the mtimes and keep the entry hot), 2+ worktrees only (needs a shared
session_idacross worktrees).When do two worktrees share a
session_id?The realistic trigger is a session resumed into a second worktree (
--resumepreserves the id while the agent writes a new transcript file):codex resume <id>in a second worktree also isn't cwd-scoped.claude --resume <id>in a second worktree's terminal (Claude transcripts nest by cwd project slug, so the resumed session re-homes to a new file while keeping the id).Ruled out as id-sharing sources: fork (builds a text prompt and launches a brand-new session → fresh id), Orca's automatic sleeping-agent/worktree-activation resume (always re-launches into
record.worktreeId, never crosses worktrees), and persisted status-snapshot replay (applied strictly bypaneKey).Not a regression — the transcriptPath-blind key shipped with the feature (#6641); the only later touch was a non-behavioral lint autofix (#6841). Fixed forward.
Fix
Key the cache by the already-resolved absolute file path (available before the key is computed), so two distinct files can never share an entry:
The multi-client hit-rate goal is preserved: all clients of one session resolve the same path against the same runtime home → same key → one shared parse.
cacheKeyis private; no caller depends on its shape. (The`${agent}:${sessionId}`cleanupTokenin the runtime RPC method is a separate subscription-cleanup identity, not this cache — unaffected.)Evidence
New regression test: same
sessionId, two distinct files (worktree-a.jsonl/worktree-c.jsonl), forced-identical mtimes so the mtime guard can't mask the collision. Each pane reads with its owntranscriptPath; the test asserts C's read never returns A's content.Without the fix (cache keyed by
${agent}:${sessionId}) — the leak reproduces, and the assertion output is the bug: reading worktree C's file returns worktree A's content:With the fix (cache keyed by resolved file path):
Also green: all native-chat main suites (read-cache, ipc, runtime RPC, session-file-resolver, transcript-watch — 30 tests), node typecheck, oxlint.
Review
Passed a 3-angle review (correctness / cross-file, cleanup / altitude, conventions / test-quality):
filePathis guarded non-null before keying; two distinct files can never collide; a same-file key mismatch (verbatim hook path vs glob path) only ever costs a re-parse, never wrong/stale content; no caller depends on the key shape.Post-review polish commit corrected the rationale comments (fork does not share an id; Codex uses a global store, not cwd slugs), dropped a comment that duplicated the module header, and used the exported
isTextBlocktype guard in the test.Scope investigated (ruled clean)
Independent multi-agent review verified the rest of the data path keys strictly by the globally-unique
paneKey/sessionIdand is not a leak source: hook attribution (agent-hooks/server.ts, tab-scoped, envORCA_PANE_KEYvalidated at spawn), the renderer agent-status store (setAgentStatuskeys by exactpaneKey;paneKey+providerSessionpaired in one IPC envelope), the renderer live-session hook/subscription (per-instance state, airtightsubscriptionIdfilter), and worktree surface mount/remount (additive, worktree-keyed — no cross-worktree instance/container/PaneManager reuse). The read cache was the single genuine cross-worktree sharing primitive.Known residual (follow-up, not fixed here)
A narrower resolver-level vector survives this fix: when a pane's
transcriptPathhint is absent or stale (file rotated/renamed/deleted, or the provider reported notranscript_path),resolveSessionFilePathfalls through to afiles[0]glob for<id>.jsonl(Claude) / the id-embedding rollout (Codex). For a shared session id thatfiles[0]can be another worktree's file, so pane C resolves to A's path and the (now path-keyed) cache faithfully serves A's content. It requires both a shared session id and a stale/absent hint; modern Claude/Codex hooks reporttranscript_path, so each pane resolves its own file in the common case. Tracking separately — the resolver has no per-pane signal beyond the hint to disambiguate two files of one session.