Skip to content

Fix cross-worktree chat leak: key native-chat transcript cache by resolved file path - #7341

Merged
nwparker merged 2 commits into
mainfrom
nwparker/bug-agent-chat-log-panel-shows-content-from-a-di
Jul 4, 2026
Merged

nwparker merged 2 commits into
mainfrom
nwparker/bug-agent-chat-log-panel-shows-content-from-a-di

Conversation

@nwparker

@nwparker nwparker commented Jul 4, 2026 •

Copy link
Copy Markdown
Contributor

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.ts keyed its process-global transcript parse cache by `${agent}:${sessionId}` — but resolved the actual file via the hook-reported transcriptPath:

const filePath = await resolveSessionFilePath(agent, sessionId, { transcriptPath }) // real file
const key = cacheKey(agent, sessionId)                                             // ignores it

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, their mtimeMs momentarily 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_id across worktrees).

When do two worktrees share a session_id?

The realistic trigger is a session resumed into a second worktree (--resume preserves the id while the agent writes a new transcript file):

  • Codex — most reachable. Codex's session store is global (a single Orca-managed home, not cwd-scoped), and the codex-session-bridge hardlinks/symlinks/copies each session into the managed home — so one session id can resolve to two paths even without a resume. codex resume <id> in a second worktree also isn't cwd-scoped.
  • Claude. A user running 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 by paneKey).

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:

function cacheKey(agent: AgentType, filePath: string): string {
  return `${agent}:${filePath}`
}
...
const key = cacheKey(agent, filePath)

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. cacheKey is private; no caller depends on its shape. (The `${agent}:${sessionId}` cleanupToken in 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 own transcriptPath; 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:

× never serves one file's parse for a different file that shares a sessionId
AssertionError: expected 'from-worktree-A' to contain 'from-worktree-C'
Test Files  1 failed (1)
Tests  1 failed | 4 passed (5)

With the fix (cache keyed by resolved file path):

Test Files  1 passed (1)
Tests  5 passed (5)

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

  • Correctness: clean — filePath is 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.
  • Altitude: keying the file's parse by its path (which the entry's mtime already guards) is the right depth, not a bandaid.
  • Conventions/tests: the regression test genuinely fails-old/passes-new and is non-flaky (pinned mtimes, unique temp dirs, cache cleared per test).

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 isTextBlock type 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/sessionId and is not a leak source: hook attribution (agent-hooks/server.ts, tab-scoped, env ORCA_PANE_KEY validated at spawn), the renderer agent-status store (setAgentStatus keys by exact paneKey; paneKey+providerSession paired in one IPC envelope), the renderer live-session hook/subscription (per-instance state, airtight subscriptionId filter), 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 transcriptPath hint is absent or stale (file rotated/renamed/deleted, or the provider reported no transcript_path), resolveSessionFilePath falls through to a files[0] glob for <id>.jsonl (Claude) / the id-embedding rollout (Codex). For a shared session id that files[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 report transcript_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.

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

coderabbitai Bot commented Jul 4, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Changes

The transcript read cache now keys entries by resolved transcript file path instead of agent plus sessionId, while still validating cached entries by mtimeMs. The cache helper, lookup call site, and related comments were updated to match the new keying. A regression test was added that reads two different transcript files with the same (agent, sessionId) and identical mtimes, then checks that each result matches only its own file content and that the parsed objects are distinct.

Estimated code review effort: Medium
Suggested labels: bug, tests
Suggested reviewers: (none identified from provided context)

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is detailed, but it does not follow the required template and omits Summary, Screenshots, Testing, AI Review Report, Security Audit, and Notes sections. Reformat the PR description to match the template and add the missing sections, including explicit testing and cross-platform review details.
✅ Passed checks (4 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
Title check ✅ Passed The title clearly summarizes the main change: switching the native-chat transcript cache key to the resolved file path to prevent cross-worktree leaks.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

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

🧹 Nitpick comments (2)
src/main/native-chat/transcript-read-cache.ts (1)

7-18: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Long 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 value

Comment 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

📥 Commits

Reviewing files that changed from the base of the PR and between 9964d1c and 64702db.

📒 Files selected for processing (2)
  • src/main/native-chat/transcript-read-cache.test.ts
  • src/main/native-chat/transcript-read-cache.ts

}

const key = cacheKey(agent, sessionId)
const key = cacheKey(agent, filePath)

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.

🩺 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=ts

Repository: 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=ts

Repository: 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=ts

Repository: 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.

@nwparker

nwparker commented Jul 4, 2026

Copy link
Copy Markdown
Contributor Author

Investigation notes (multi-agent root-cause, 2 rounds)

Introducing commit: b916248294 ("Polish desktop native chat view", #6641) — born broken, not a regression. The cache, resolver, transcriptPath option, and live-session hook all landed together; the first version already keyed by sessionId while forwarding a transcriptPath that can name a different file. Only later touch was the non-behavioral lint autofix #6841. So this is fix-forward. main still carries the vulnerable ${agent}:${sessionId} keying — anyone on a main/older build still reproduces until this lands.

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 crypto.randomUUID; PaneManager is per-instance; paneKey = ${tabId}:${leafId} is globally unique. So the "reopening the tab fixes it" clue is the cache/resolver re-resolving once mtimes diverge or the hint refreshes — not a surface remount.

Open follow-up (the residual noted in the description): the id-glob resolver fallback returns files[0] across all Claude project slugs (session-file-resolver.ts:91) / the global Codex store (:112-113). The transcriptPath hint is honored only when existsSync(hookPath); a stale/absent hint falls through to files[0], which for a shared session id can be another worktree's file — the path-keyed cache then faithfully serves the wrong file. Suggested fix (separate PR — needs a design call): make the glob cwd/worktree-aware (derive Claude's slug from the pane's own cwd; disambiguate same-id Codex rollouts by cwd/most-recent) rather than walk-order files[0]. Test: with no/stale transcriptPath, seed worktree A's <id>.jsonl and assert resolveSessionFilePath for pane C does not return A's file.

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' ? ... : ''`.
@nwparker
nwparker merged commit 533cafd into main Jul 4, 2026
1 check passed
@nwparker
nwparker deleted the nwparker/bug-agent-chat-log-panel-shows-content-from-a-di branch July 4, 2026 09:40
@Sharpek

Sharpek commented Jul 4, 2026

Copy link
Copy Markdown

thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Agent chat/log panel shows content from a different worktree

2 participants