Skip to content

fix(native-chat): read SSH worktree transcripts on the execution host - #15672

Closed
brennanb2025 wants to merge 14 commits into
mainfrom
brennanb2025/sta-3846-ssh-chat-transcript
Closed

brennanb2025 wants to merge 14 commits into
mainfrom
brennanb2025/sta-3846-ssh-chat-transcript

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 30 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​2263 $\color{#cf222e}{\Huge{\mathbf{−}}}$​273 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1990
Prod 51 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​2096 $\color{#cf222e}{\Huge{\mathbf{−}}}$​468 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1628

ELI5

Native chat for an agent running through SSH was sometimes looking for the transcript on the laptop. The transcript belongs to the host that ran the agent, so Orca now remembers that ownership across disconnects and restarts and refuses to substitute a same-looking local file when the remote host cannot be verified.

What Changed

  • Persist transcript-owner evidence in the agent-hook last-status.json ledger independently of the seven-day hook-row retention window. The evidence records pane, agent, provider session, transcript path, execution connection, and observation time.
  • Migrate pre-ledger SSH commitments conservatively with an unresolved-remote marker. Disconnect keeps ownership evidence, pane transfer moves it, and authoritative reassignment or pane retirement clears it.
  • Resolve native-chat reads and subscriptions only after owner hydration, including retained aliases and legacy locator-free requests. Remote loss is unverifiable; it never authorizes local fallback or implies the process exited.
  • Keep the existing SSH ranged-read provider and transcript decoder/watch machinery. Provider replacement, reconnection, bounded range pagination, and rewritten-file invalidation remain supported.
  • Add the optional runtime capability native-chat.transcript-owner.v1. Mobile, renderer remote-runtime, and web paths prove both ownership and host capability before issuing native-chat RPCs; unknown/old-host states make zero native-chat calls.
  • Bind mobile capability proof to the stable client's transport generation. A logical subscription is recreated only after the replacement generation is reprobed, and the stable client itself does not replay native-chat subscriptions onto a new transport.

Why

The transcript lives where the agent runs. A disconnected SSH host is not evidence that its process or transcript disappeared, and a local file with the same session id must never become a substitute. Durable host-owned evidence and fail-closed capability gates preserve that boundary across restart, reconnect, web pairing changes, and mixed client/host versions.

Linked Issue

Fixes #13663
STA-3846

Supersedes #13687 and #15515.

Visual Proof

N/A — no UI chrome changed. The existing native-chat view receives the same snapshot/append frames after ownership is proven; unknown or incompatible ownership remains gated without transcript IO.

Testing

  • pnpm typecheck
  • node config/scripts/check-changed-code-quality.mjs
  • node config/scripts/check-react-doctor-changed.mjs
  • Focused root Vitest: 12 files / 143 tests, covering agent-hook persistence and migration, SSH routing/ranged reads/relay errors, pane ownership, provider-session invalidation, renderer transport and pane resolution, live-session gating, and web preload gating
  • Split regression suites after the line-limit check: 3 files / 24 tests
  • Mobile Vitest: 458 files / 3,677 passed / 3 skipped
  • git diff --check
  • mobile/pnpm-lock.yaml unchanged

Non-vacuity was proved by temporarily changing the SSH owner verdict to legacy-local: the receiver-sensitive test failed because it expected [{ id: 'bound-remote' }] and received { error: 'Transcript unavailable', notFound: true }. Restoring the owner verdict made the same test pass; the temporary mutation is not present in this branch.

AI Disclosure

Internal contributor.

Remote wire compatibility

  • native-chat.transcript-owner.v1 is an optional status capability, so older decoders ignore it safely.
  • No new stream opcode was added and existing native-chat RPC/frame shapes are unchanged.
  • New clients do not send ownership-sensitive native-chat RPCs until the paired host advertises support; capability proof is invalidated and reprobed when the host generation changes.
  • The host may publish durable owner evidence only in its local agent-hook status file; it is not a new client/host payload.

SSH / folder workspaces / mobile

Ownership follows the execution connection and pane identity, so SSH folder workspaces are covered without assuming a git worktree. WSL relay ownership remains local/UNC-backed, while SSH transport loss remains unverifiable. Mobile and web use the same gated native-chat RPC surface as desktop remote runtimes.

Checklist

  • The change stays focused on transcript host ownership, persistence, and compatibility gating
  • No new relay opcode or provider-specific transcript decoder was introduced
  • Cross-platform, SSH, folder-workspace, restart, reconnect, and mixed-version behavior are covered
  • Automated tests prove the acceptance path fails when the routing fix is neutered

@coderabbitai

coderabbitai Bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The change adds pane-aware native chat transcript routing across preload, RPC, renderer, mobile, and runtime layers. It records and resolves local and SSH transcript ownership, persists owner evidence, and prevents unsafe fallback. SSH transcripts use bounded ranged reads with provider-generation and stability checks. Remote subscriptions retry provider changes and use reconciliation watchers. Runtime capability checks and structured relay errno handling are added with supporting tests and reliability documentation.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The changes address SSH transcript routing, persistence, fail-closed behavior, local and WSL compatibility, and client capability gating required by issue #13663.
Out of Scope Changes check ✅ Passed The changes remain focused on native-chat transcript ownership, SSH routing, persistence, compatibility gating, and related tests and documentation.
Docstring Coverage ✅ Passed Docstring check was indeterminate for this PR — some files could not be analyzed in time. Not blocking.
Title check ✅ Passed The title clearly and concisely identifies the primary change: reading SSH worktree transcripts from the execution host.
Description check ✅ Passed The description covers the change, rationale, issue, testing, compatibility, and visual proof, with sufficient detail for review.
✨ 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: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: b3114719-be0b-49b7-b73a-078fa0f740ae

📥 Commits

Reviewing files that changed from the base of the PR and between 012e9f4 and 5da448d.

📒 Files selected for processing (22)
  • src/main/ipc/native-chat.ts
  • src/main/native-chat/ssh-transcript-owner.test.ts
  • src/main/native-chat/ssh-transcript-owner.ts
  • src/main/native-chat/ssh-transcript-range-fs.test.ts
  • src/main/native-chat/ssh-transcript-range-fs.ts
  • src/main/native-chat/ssh-transcript-read.ts
  • src/main/native-chat/ssh-transcript-routing.test.ts
  • src/main/native-chat/ssh-transcript-subscription.ts
  • src/main/native-chat/transcript-file-version.ts
  • src/main/native-chat/transcript-host-verdict.ts
  • src/main/native-chat/transcript-incremental-reader.ts
  • src/main/native-chat/transcript-native-watcher.ts
  • src/main/native-chat/transcript-range-fs.ts
  • src/main/native-chat/transcript-tail-boundary.ts
  • src/main/native-chat/transcript-tail-reader.ts
  • src/main/native-chat/transcript-watch-contract.ts
  • src/main/native-chat/transcript-watch-engine.ts
  • src/main/native-chat/transcript-watch-probe.ts
  • src/main/native-chat/transcript-watch.ts
  • src/main/runtime/rpc/methods/native-chat.ts
  • src/preload/api/native-chat-api.ts
  • src/renderer/src/components/native-chat/native-chat-runtime-contract.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 1 remains after this review.

Comment on lines +29 to +36
} catch (error) {
// Why: "not flushed yet" degrades to resolve-polling, but a stalled distro
// or unreachable SSH host must reach the caller so it can surface a
// retryable message instead of stranding the client at `loading`.
if (error instanceof WslTranscriptFsError || error instanceof TranscriptHostUnverifiableError) {
throw error
}
return false

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Preserve remote probe failures for SSH classification.

When rangeFs.stat() rejects with a raw provider error, this catch returns false. installTranscriptWatcher() then returns null, so subscribeSshNativeChatTranscript() retries without calling classifySshTranscriptReadError(). A disconnected host or unsupported ranged read can remain in retry state instead of emitting unverifiable.

When rangeFs is set, rethrow the error and let the SSH subscription classify it. Keep the local missing-file fallback unchanged. Also normalize later SSH range-read failures to TranscriptHostUnverifiableError, because the active drain only preserves that typed verdict.

Proposed fix
   } catch (error) {
+    if (rangeFs) {
+      throw error
+    }
     // Why: "not flushed yet" degrades to resolve-polling, but a stalled distro

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Live SSH validation — DEFECT FOUND

Exercised on the Linux SSH target openclaw from an isolated Electron client of this branch (linux-val-15672 @ 7381e90c31). Relay 0.1.0+e8029d299a12 content-hash matched this worktree’s linux-x64 relay.js. Paired environment was not started.

What ran

  • New remote demo-project worktree orca-ssh-val-15672.
  • Real Claude over SSH. Hook snapshot: connectionId = this client’s SSH target id, sessionId = 827e26d7-1658-4221-8c39-48d2375807a4, transcriptPath = /home/brennan/.claude/projects/-home-brennan-orca-ssh-val-15672-demo-demo-project-orca-ssh-val-15672/827e26d7-1658-4221-8c39-48d2375807a4.jsonl.
  • Planted SSH_VAL_REMOTE_ONLY_MARKER_15672 only on that remote file.
  • Planted SSH_VAL_LOCAL_ONLY_MARKER_15672 only on the Mac at ~/.claude/projects/orca-ssh-val-15672-local-only/<sessionId>.jsonl.

Connected (host reachable)

window.api.nativeChat.readSession('claude', sessionId, 80, transcriptPath) returned:

{ "error": "Transcript unverifiable on the remote host", "unverifiable": true }

Relay logs showed fs.readFileStream (explorer) and no fs.readFileRange. Agent Session History did show the remote-only marker (different reader, not this IPC).

Claude TUI over SSH
Session history shows remote-only marker
Session details latest turn is the remote-only plant

After disconnect

Hook snapshot row was gone. readSession then returned the local-only plant as a successful transcript (messages[0].text === SSH_VAL_LOCAL_ONLY_MARKER_15672). That is silent local substitution: loss of contact was not unverifiable. The remote Claude PTY is still live on the host (not observed exited).

Verdict

DEFECT FOUND. Native-chat IPC does not deliver the remote transcript while the host is connected (unverifiable despite a live ranged-read-capable relay and a file that Session History can read), and on disconnect it attributes a Mac-only file to the SSH session. Folder-workspace subcase not run.

brennanb2025 and others added 14 commits August 23, 2026 14:35
…stead of spinning

An agent running in an SSH worktree writes its transcript on the remote
machine, so the desktop resolves nothing and subscribeNativeChatTranscript
re-polls forever with no frame. The client's loading state only clears on a
stream frame, so the chat view spins indefinitely with no error (#13663).

Emit one advisory snapshot once an unresolved transcript passes a deadline.
It is deliberately non-terminal: the resolve poll keeps running and a later
real snapshot replaces it, so a session that is merely slow to flush its
first JSONL line still loads (#8401). The deadline is generous for the same
reason -- a late message costs less than a false one on a healthy session.

This lands in the shared subscribe path, so desktop, mobile, web and headless
all get it without a wire change; clients already render an error carried on
the snapshot frame.
…non-destructive

Review follow-ups on the #13663 notice:

- Split the advisory latch from the WSL gate latch. They shared one boolean, so
  a distro that stalled after the deadline had its actionable retry message
  silenced by the generic notice.
- Never trade already-read history for an error card: an error frame carries no
  transcript, so the desktop keeps a non-empty ready list (mobile already
  retains its transcript for the same reason).
- Let the stream's error outrank the seed's notFound miss. Both deadlines expire
  at ~60s on the same transcript, so one failure was showing two messages
  depending on which resolved last.
- Schedule the next poll before notifying, and contain a throwing subscriber, so
  an emit on a dying connection can't kill the loop as an unhandled rejection.
- Say only what the deadline establishes: a remote host, a cold WSL distro and a
  slow first flush all land on it. Drops a comment that claimed the deadline
  exceeded the documented worst-case first flush when #8401 says minutes.
- Tests: assert the recovered transcript's content (the old assertion could pass
  on an empty frame), pin the once-only latch across ~10 further ticks, and
  publish test transcripts by rename so a zero-byte file can't race the poll.
…bscriber can't kill the poll

The unresolved-transcript notice was already contained, but its sibling emit in
runAttempt's catch was not: a throw there escaped `void runAttempt()` as an
unhandled rejection and skipped the reschedule below it, stranding the poll for
good. Route both through one emitAdvisory helper.
@brennanb2025
brennanb2025 force-pushed the brennanb2025/sta-3846-ssh-chat-transcript branch from 7381e90 to 5453890 Compare August 23, 2026 22:14
@coderabbitai

coderabbitai Bot commented Aug 23, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Revised this implementation around durable, server-authoritative transcript ownership.

What changed:

  • Agent-hook status now persists transcript-owner evidence across row expiry, disconnect, and restart, with conservative unresolved markers for pre-ledger SSH commitments.
  • Native-chat reads/subscriptions wait for owner hydration, follow pane transfer/alias changes, and fail closed when remote provenance cannot be verified.
  • Mobile, renderer remote-runtime, and web paths gate native-chat IO on the optional native-chat.transcript-owner.v1 host capability. Mobile capability proof is tied to transport generation, and stable logical subscriptions are not replayed onto a replacement transport before reprobe.
  • Regression coverage includes durable evidence, migration, disconnect/restart, owner transfer/retirement, legacy locator-free reads, hydration races, transport replacement, and old-host zero-call behavior.

What stayed:

  • The existing SSH filesystem provider, bounded ranged reads, transcript decoders, snapshot/append contract, and local/WSL readers remain the underlying mechanisms.
  • No new stream opcode or transcript-specific relay method was added.

Verification:

  • pnpm typecheck
  • node config/scripts/check-changed-code-quality.mjs
  • node config/scripts/check-react-doctor-changed.mjs
  • Focused root run: 12 files / 143 tests
  • Follow-up split regression run: 3 files / 24 tests
  • Mobile run: 458 files / 3,677 passed / 3 skipped
  • git diff --check; mobile/pnpm-lock.yaml unchanged

Non-vacuity: temporarily changing the SSH owner verdict to legacy-local made the receiver-sensitive test fail—expected [{ id: 'bound-remote' }], received { error: 'Transcript unavailable', notFound: true }. Restoring the owner verdict made the same test pass; the temporary mutation is not in the branch.

@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: 10

🧹 Nitpick comments (1)
src/renderer/src/web/web-preload-api.ts (1)

1302-1313: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Cache the capability probe instead of sending status.get on every native-chat request.

assertOwnerCapability issues a fresh status.get for each readSession and each subscribe. readSession also runs for every "load earlier" page, so each history page costs two round-trips over the web transport. The renderer runtime path avoids this: runtimeEnvironmentSupportsCapability caches the status result with a TTL and only reprobes when the cached value is stale or unsupported.

Cache the verdict per environment with a TTL, and invalidate it when the pairing changes or when the capability is absent.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 693a6d69-e2de-46fb-82b9-f798b131b0e3

📥 Commits

Reviewing files that changed from the base of the PR and between b89b58b and 5453890.

📒 Files selected for processing (81)
  • config/reliability-gates.jsonc
  • docs/reference/remote-wire-compatibility.md
  • mobile/app/h/[hostId]/session/[worktreeId].tsx
  • mobile/src/session/mobile-native-chat-eligibility.test.ts
  • mobile/src/session/mobile-native-chat-eligibility.ts
  • mobile/src/session/use-mobile-native-chat-controller.test.ts
  • mobile/src/session/use-mobile-native-chat-controller.ts
  • mobile/src/session/use-mobile-native-chat-session.test.ts
  • mobile/src/session/use-mobile-native-chat-session.ts
  • mobile/src/transport/host-status-gates.test.ts
  • mobile/src/transport/host-status-gates.ts
  • mobile/src/transport/stable-logical-rpc-client.test.ts
  • mobile/src/transport/stable-logical-rpc-client.ts
  • src/main/agent-hooks/server-last-status-write.test.ts
  • src/main/agent-hooks/server-transcript-owner-persistence.test.ts
  • src/main/agent-hooks/server.ts
  • src/main/agent-hooks/wsl-hook-relay-live.integration.test.ts
  • src/main/ipc/filesystem-path-containment.ts
  • src/main/ipc/native-chat.test.ts
  • src/main/ipc/native-chat.ts
  • src/main/native-chat/host-readable-transcript-path.test.ts
  • src/main/native-chat/host-readable-transcript-path.ts
  • src/main/native-chat/native-chat-transcript-owner.ts
  • src/main/native-chat/session-file-resolver.ts
  • src/main/native-chat/ssh-transcript-host-routing.test.ts
  • src/main/native-chat/ssh-transcript-owner-evidence-routing.test.ts
  • src/main/native-chat/ssh-transcript-range-fs.test.ts
  • src/main/native-chat/ssh-transcript-range-fs.ts
  • src/main/native-chat/ssh-transcript-range-pagination.test.ts
  • src/main/native-chat/ssh-transcript-read.ts
  • src/main/native-chat/ssh-transcript-relay-errno.test.ts
  • src/main/native-chat/ssh-transcript-subscription.ts
  • src/main/native-chat/transcript-file-version.ts
  • src/main/native-chat/transcript-host-verdict.ts
  • src/main/native-chat/transcript-incremental-reader.ts
  • src/main/native-chat/transcript-native-watcher.ts
  • src/main/native-chat/transcript-range-fs.ts
  • src/main/native-chat/transcript-tail-boundary.ts
  • src/main/native-chat/transcript-tail-reader.ts
  • src/main/native-chat/transcript-watch-contract.ts
  • src/main/native-chat/transcript-watch-engine.ts
  • src/main/native-chat/transcript-watch-error.test.ts
  • src/main/native-chat/transcript-watch-read.ts
  • src/main/native-chat/transcript-watch-resolve-poll.test.ts
  • src/main/native-chat/transcript-watch-wsl-stall.test.ts
  • src/main/native-chat/transcript-watch.ts
  • src/main/providers/filesystem-provider-contract.ts
  • src/main/providers/ssh-filesystem-dispatch.test.ts
  • src/main/providers/ssh-filesystem-dispatch.ts
  • src/main/providers/ssh-filesystem-provider-range.test.ts
  • src/main/providers/ssh-filesystem-provider.ts
  • src/main/runtime/rpc/methods/native-chat-rpc-schema.ts
  • src/main/runtime/rpc/methods/native-chat.test.ts
  • src/main/runtime/rpc/methods/native-chat.ts
  • src/preload/api/native-chat-api.ts
  • src/preload/index.ts
  • src/relay/dispatcher-structured-error.test.ts
  • src/relay/dispatcher.ts
  • src/relay/integration.test.ts
  • src/renderer/src/components/native-chat/NativeChatSessionGate.tsx
  • src/renderer/src/components/native-chat/NativeChatView.tsx
  • src/renderer/src/components/native-chat/native-chat-live-session-types.ts
  • src/renderer/src/components/native-chat/native-chat-live-source-key.ts
  • src/renderer/src/components/native-chat/native-chat-pane-resolution.test.ts
  • src/renderer/src/components/native-chat/native-chat-pane-resolution.ts
  • src/renderer/src/components/native-chat/native-chat-session-transport.test.ts
  • src/renderer/src/components/native-chat/native-chat-session-transport.ts
  • src/renderer/src/components/native-chat/native-chat-subscription-identity.ts
  • src/renderer/src/components/native-chat/native-chat-view-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
  • src/renderer/src/components/native-chat/use-native-chat-retained-session.ts
  • src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-host-session-launch.test.ts
  • src/renderer/src/runtime/runtime-rpc-client.ts
  • src/renderer/src/runtime/web-runtime-session-terminal-host-authority.test.ts
  • src/renderer/src/runtime/web-runtime-session.ts
  • src/renderer/src/web/web-preload-api-agent-providers.test.ts
  • src/renderer/src/web/web-preload-api.ts
  • src/shared/definitive-filesystem-absence.ts
  • src/shared/protocol-version.ts
  • tests/e2e/headless-native-chat-runtime-routing.spec.ts
💤 Files with no reviewable changes (2)
  • src/main/native-chat/transcript-watch-resolve-poll.test.ts
  • src/main/agent-hooks/wsl-hook-relay-live.integration.test.ts
🚧 Files skipped from review as they are similar to previous changes (7)
  • src/main/native-chat/transcript-file-version.ts
  • src/main/native-chat/transcript-native-watcher.ts
  • src/main/native-chat/transcript-incremental-reader.ts
  • src/main/native-chat/ssh-transcript-subscription.ts
  • src/main/native-chat/transcript-tail-boundary.ts
  • src/main/native-chat/transcript-watch-contract.ts
  • src/main/native-chat/transcript-tail-reader.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 0 remain after this review.

Comment on lines +99 to +104
client: transcriptTransportAuthorized ? client : null,
sourceIdentity: encodeNativeChatTranscriptIdentity([hostId, worktreeId]),
agent: activeChatResolution?.agent ?? null,
sessionId: activeChatSessionId,
transcriptPath: activeChatResolution?.transcriptPath ?? null
transcriptPath: activeChatResolution?.transcriptPath ?? null,
paneKey: activeChatResolution?.paneKey ?? null

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.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Gate native-chat writes with transcript authorization.

When SSH ownership is pending, unavailable, or unknown, this hook passes null to useMobileNativeChatSession. However, the answer, permission, stop, and message-send hooks still receive the original client, and inputSendable does not include transcriptTransportAuthorized. Users can therefore send native-chat actions while the transcript subscription is disabled, creating unseen turns and inconsistent chat state.

Gate the common write enablement with transcriptTransportAuthorized, or pass the gated client to every native-chat I/O hook.

Proposed fix
-  const inputSendable = nativeChatInputLeaseReady && connState === 'connected'
+  const inputSendable =
+    transcriptTransportAuthorized &&
+    nativeChatInputLeaseReady &&
+    connState === 'connected'

Comment on lines +54 to +56
paneKey: string | null
}): MobileNativeChatSession {
const { client, sourceIdentity, agent, sessionId, transcriptPath } = args
const { client, sourceIdentity, agent, sessionId, transcriptPath, paneKey } = args

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.

🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -eu

printf '%s\n' '--- hook signature and nearby code ---'
sed -n '35,75p' mobile/src/session/use-mobile-native-chat-session.ts

printf '%s\n' '--- cited test range ---'
sed -n '445,495p' mobile/src/session/use-mobile-native-chat-session.test.ts

printf '%s\n' '--- all hook call sites ---'
rg -n -C 4 'useMobileNativeChatSession' mobile

Repository: stablyai/orca

Length of output: 18308


🏁 Script executed:

#!/bin/bash
set -eu

printf '%s\n' '--- first test harness call ---'
sed -n '28,52p' mobile/src/session/use-mobile-native-chat-session.test.ts

printf '%s\n' '--- production controller call ---'
sed -n '88,115p' mobile/src/session/use-mobile-native-chat-controller.ts

printf '%s\n' '--- complete second harness declaration and call ---'
sed -n '458,485p' mobile/src/session/use-mobile-native-chat-session.test.ts

printf '%s\n' '--- direct-call property check (read-only) ---'
python3 - <<'PY'
from pathlib import Path
import re

files = [
    Path("mobile/src/session/use-mobile-native-chat-session.test.ts"),
    Path("mobile/src/session/use-mobile-native-chat-controller.ts"),
]
pattern = re.compile(r"useMobileNativeChatSession\s*\(\s*\{(?P<body>.*?)\}\s*\)", re.S)

for path in files:
    text = path.read_text()
    for match in pattern.finditer(text):
        line = text.count("\n", 0, match.start()) + 1
        body = match.group("body")
        properties = re.findall(r"(?m)^\s*([A-Za-z_$][\w$]*)\s*:", body)
        print(f"{path}:{line}: properties={properties}; paneKey={'present' if 'paneKey' in properties else 'MISSING'}")
PY

Repository: stablyai/orca

Length of output: 3370


Add paneKey to the second test harness.

The hook requires paneKey, but the call at mobile/src/session/use-mobile-native-chat-session.test.ts:472 omits it. Add paneKey: null or the fixture pane key to restore type-checking.

Comment on lines +121 to +135
it('does not replay native-chat subscriptions across an unproven generation', async () => {
const oldSession = new FakeSession('connected')
const replacement = new FakeSession('connected')
const client = createStableLogicalRpcClient(oldSession, 'lan')
client.subscribe('nativeChat.subscribe', { sessionId: 'session-1' }, vi.fn())

await client.migrateTo(replacement, 'relay')

expect(replacement.subscribe).not.toHaveBeenCalledWith(
'nativeChat.subscribe',
expect.anything(),
expect.any(Function),
expect.anything()
)
})

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🌐 Web query:

Does Vitest expect.anything() match undefined arguments in toHaveBeenCalledWith?

💡 Result:

No, Vitest's expect.anything does not match undefined arguments [1][2]. By official definition, expect.anything matches any value except null or undefined [1][2]. Therefore, if you pass undefined as an argument to a function and attempt to match it using expect.anything within toHaveBeenCalledWith, the assertion will fail [3].

Citations:


🏁 Script executed:

#!/bin/bash
set -eu

file="mobile/src/transport/stable-logical-rpc-client.test.ts"
printf '%s\n' '--- test file ---'
sed -n '1,190p' "$file"

printf '%s\n' '--- related symbols ---'
rg -n --glob '*.{ts,tsx,js,jsx}' \
  'createStableLogicalRpcClient|attachSubscription|migrateTo|nativeChat\.subscribe|class FakeSession' \
  mobile/src

Repository: stablyai/orca

Length of output: 16404


🏁 Script executed:

#!/bin/bash
set -eu

printf '%s\n' '--- migration and subscription implementation ---'
sed -n '200,335p' mobile/src/transport/stable-logical-rpc-client.ts

printf '%s\n' '--- RPC subscription type and relevant tests ---'
rg -n -A18 -B8 --glob '*.{ts,tsx}' \
  'subscribe\s*[:=]|interface RpcClient|type RpcClient|nativeChat\.subscribe' \
  mobile/src/transport mobile/src/session | head -240

Repository: stablyai/orca

Length of output: 25998


🏁 Script executed:

#!/bin/bash
set -eu

printf '%s\n' '--- subscription registration and record shape ---'
sed -n '1,175p' mobile/src/transport/stable-logical-rpc-client.ts

printf '%s\n' '--- RpcClient declarations ---'
rg -n -A45 -B8 --glob '*.ts' \
  'export interface RpcClient|interface RpcClient|subscribe\s*\(' \
  mobile/src/transport | head -220

Repository: stablyai/orca

Length of output: 23800


Make the negative assertion non-vacuous.

expect.anything() does not match undefined, so the matcher cannot detect a replay. Assert directly that replacement.subscribe was not called.

Comment on lines +252 to 261
// Why: native-chat ownership is generation-bound; its hook reprobes status before resubscribing.
for (const record of subscriptions.values()) {
const disposePrevious = record.disposePhysical
attachSubscription(record, nextSession, nextGeneration)
if (record.method === 'nativeChat.subscribe') {
record.disposePhysical = null
} else {
attachSubscription(record, nextSession, nextGeneration)
}
disposePrevious?.()
}

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 | 🟠 Major | 🏗️ Heavy lift

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify whether any consumer input changes on migration for locally owned native chat.
set -euo pipefail

rg -n -C6 "nativeChat.subscribe" mobile/src | head -80
rg -n -C10 "getGeneration" mobile/src
rg -n -C6 "transcriptTransportAuthorized|proven-local" mobile/src

Repository: stablyai/orca

Length of output: 34384


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- native chat hook ---'
sed -n '1,190p' mobile/src/session/use-mobile-native-chat-session.ts

printf '%s\n' '--- native chat controller ---'
sed -n '1,180p' mobile/src/session/use-mobile-native-chat-controller.ts

printf '%s\n' '--- migration implementation ---'
sed -n '210,275p' mobile/src/transport/stable-logical-rpc-client.ts

printf '%s\n' '--- controller client and capability state references ---'
rg -n -C8 "setClient|client:|nativeChatTranscriptOwnerCapabilityPending|nativeChatTranscriptOwnerCapable|transcriptTransportAuthorized|useMobileNativeChatSession" mobile/src/session mobile/src/transport

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- hook effects and dependency arrays ---'
rg -n -C12 "useEffect|\\[client|\\[.*paneKey|transcriptPath" mobile/src/session/use-mobile-native-chat-session.ts

printf '%s\n' '--- controller implementation ---'
sed -n '1,125p' mobile/src/session/use-mobile-native-chat-controller.ts

printf '%s\n' '--- controller hook invocation ---'
sed -n '90,112p' mobile/src/session/use-mobile-native-chat-controller.ts

printf '%s\n' '--- migration implementation ---'
sed -n '235,267p' mobile/src/transport/stable-logical-rpc-client.ts

Repository: stablyai/orca

Length of output: 16792


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
from pathlib import Path
import re

hook = Path("mobile/src/session/use-mobile-native-chat-session.ts").read_text()
controller = Path("mobile/src/session/use-mobile-native-chat-controller.ts").read_text()
migration = Path("mobile/src/transport/stable-logical-rpc-client.ts").read_text()

deps = re.search(
    r"\},\s*\[client, agent, sessionId, transcriptPath, paneKey, identity, setList\]\)",
    hook,
)
identity_fields = re.search(
    r"const identity = encodeNativeChatTranscriptIdentity\(\[\s*"
    r"sourceIdentity,\s*agent,\s*sessionId,\s*transcriptPath,\s*paneKey\s*\]\)",
    hook,
)
local_auth = re.search(
    r"const transcriptTransportAuthorized =\s*"
    r"transcriptOwnership === 'proven-local'",
    controller,
)
native_cutover = re.search(
    r"if \(record\.method === 'nativeChat\.subscribe'\) \{\s*"
    r"record\.disposePhysical = null",
    migration,
    re.S,
)

assert deps, "native chat effect dependency list changed or was not found"
assert identity_fields, "native chat identity fields changed or were not found"
assert local_auth, "proven-local authorization rule changed or was not found"
assert native_cutover, "native-chat cutover behavior changed or was not found"

deps_text = deps.group(0)
assert "generation" not in deps_text, deps_text
assert "sourceIdentity" in identity_fields.group(0)
assert "generation" not in identity_fields.group(0)

# React's dependency comparison is identity/value equality for these primitive
# inputs. A migration keeps the stable logical client and chat inputs unchanged.
before = ("logical-client", "claude", "session-1", "/tmp/transcript.json", "pane-1")
after = before
assert before == after

# The proven-local branch does not depend on capability-pending state.
transcript_ownership = "proven-local"
authorized_before = transcript_ownership == "proven-local"
authorized_after = transcript_ownership == "proven-local"
assert authorized_before and authorized_after

print("effect dependencies:", deps_text.split("[", 1)[1].split("]", 1)[0])
print("identity excludes generation: yes")
print("proven-local authorization before/after migration: true/true")
print("native-chat cutover clears physical attachment: yes")
print("effect rerun from migration-only changes: no")
PY

Repository: stablyai/orca

Length of output: 433


Reattach locally owned native-chat subscriptions after migration.

migrateTo clears the physical attachment but keeps the logical record. The hook effect does not depend on getGeneration(), so a proven-local session remains unsubscribed until another dependency changes. Reattach the subscription during migration, or resubscribe when the generation changes.

Comment on lines +885 to +898
awaitTranscriptOwnerHydration(): Promise<void> {
if (this.transcriptOwnerHydrated) {
return Promise.resolve()
}
return new Promise((resolve) => this.transcriptOwnerHydrationWaiters.add(resolve))
}

private markTranscriptOwnerHydrated(): void {
this.transcriptOwnerHydrated = true
for (const resolve of this.transcriptOwnerHydrationWaiters) {
resolve()
}
this.transcriptOwnerHydrationWaiters.clear()
}

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 | 🟠 Major | ⚡ Quick win

Resolve or reject hydration waiters when the server stops.

stop() sets transcriptOwnerHydrated = false and clears the owner maps, but it leaves transcriptOwnerHydrationWaiters populated and never calls markTranscriptOwnerHydrated(). Two consequences follow:

  • Waiters registered before stop() never settle. Their resolvers stay referenced in the set.
  • Any awaitTranscriptOwnerHydration() call after stop() and before a new start() returns a promise that never settles. resolveHydratedNativeChatTranscriptOwner awaits that promise before it checks the abort signal, so a native-chat read or subscription started in that window hangs with no timeout.

Settle the waiters in stop() and keep the set empty.

🔧 Proposed fix
     this.transcriptOwnersByPaneKey.clear()
     this.unresolvedRemoteTranscriptOwnersByPaneKey.clear()
+    // Why: a stopped server hydrates nothing more; settle waiters so readers fail fast instead of hanging.
+    this.markTranscriptOwnerHydrated()
     this.transcriptOwnerHydrated = false

Also applies to: 2582-2582, 2742-2744

Comment on lines +3159 to +3177
if (
entry?.providerSession &&
entry.payload.agentType &&
entry.payload.agentType !== 'unknown'
) {
this.transcriptOwnersByPaneKey.set(
resolvedPaneKey,
Object.freeze({
paneKey: resolvedPaneKey,
agentType: entry.payload.agentType,
sessionId: entry.providerSession.id,
...(entry.providerSession.transcriptPath
? { transcriptPath: entry.providerSession.transcriptPath }
: {}),
connectionId: entry.connectionId,
observedAt: entry.receivedAt
})
)
}

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.

🚀 Performance & Scalability | 🟠 Major | ⚡ Quick win

Bound the persisted transcript-owner maps.

Status entries are pruned by ttlCutoff, but owner evidence is not. Line 3159 derives owner evidence from every sanitized entry, including entries that are then dropped for age, and lines 3233-3252 rehydrate every persisted owner and marker without an age or size limit. serializeStatusFile writes the whole map back. A pane that ever reported a provider session therefore keeps a record in last-status.json forever, and the file and the in-memory maps grow without a ceiling across restarts.

observedAt is already available on both record types. Apply the same cutoff used for entries, or cap the maps like PANE_KEY_ALIASES_MAX, so growth stays bounded while recent ownership still survives row expiry.

Also applies to: 3233-3252

Comment on lines +293 to +294
await agentHookServer.awaitTranscriptOwnerHydration()
setupSignal?.throwIfAborted()

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 | 🟠 Major | ⚡ Quick win

Make owner hydration abortable.

At Line 293, an aborted setupSignal cannot stop awaitTranscriptOwnerHydration(). The server registers an unremovable hydration waiter, so IPC and RPC teardown leave each canceled setup pending until hydration completes. If hydration stalls, canceled subscriptions retain handlers and waiters. Update the hydration API to remove its waiter on abort, and pass setupSignal to it.

Comment on lines +32 to +37
// A reconnect gap has no provider session by construction; retain the last complete identity.
return {
...currentResolution,
sessionId: previousResolution.sessionId,
transcriptPath: previousResolution.transcriptPath
transcriptPath: previousResolution.transcriptPath,
connectionId: previousResolution.connectionId

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 | 🟠 Major | ⚡ Quick win

Preserve transcript ownership during the reconnect fallback.

When the replacement status has no connectionId, currentResolution has transcriptOwnership: 'unknown'. Lines 33-37 restore the prior session identity but retain that unknown verdict. NativeChatView then disables useNativeChatRetainedSession, so a previously proven transcript stops reading during the reconnect gap.

Retain the previous verdict only when the current verdict is unknown.

Proposed fix
       return {
         ...currentResolution,
         sessionId: previousResolution.sessionId,
         transcriptPath: previousResolution.transcriptPath,
-        connectionId: previousResolution.connectionId
+        connectionId: previousResolution.connectionId,
+        transcriptOwnership:
+          currentResolution.transcriptOwnership === 'unknown'
+            ? previousResolution.transcriptOwnership
+            : currentResolution.transcriptOwnership
       }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// A reconnect gap has no provider session by construction; retain the last complete identity.
return {
...currentResolution,
sessionId: previousResolution.sessionId,
transcriptPath: previousResolution.transcriptPath
transcriptPath: previousResolution.transcriptPath,
connectionId: previousResolution.connectionId
// A reconnect gap has no provider session by construction; retain the last complete identity.
return {
...currentResolution,
sessionId: previousResolution.sessionId,
transcriptPath: previousResolution.transcriptPath,
connectionId: previousResolution.connectionId,
transcriptOwnership:
currentResolution.transcriptOwnership === 'unknown'
? previousResolution.transcriptOwnership
: currentResolution.transcriptOwnership

Comment on lines +22 to +23
args.transcriptPath ?? null,
args.transcriptConnectionId ?? null

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.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Hide retained transcript messages when ownership is unknown.

When transcriptOwnership becomes unknown, NativeChatResolvedView passes enabled: false but can keep this identity unchanged. useNativeChatLiveSession preserves same-source state while disabled. This hook can then return cached transcript messages after provenance is no longer verified.

Return an empty loading session when args.enabled === false, or include an ownership gate in retention. Add a regression test for a ready session that becomes disabled without changing its session or connection ID.

Comment on lines +1342 to +1346
const session = captureSession()
void assertOwnerCapability(session.call)
.then(() => {
session.assertCurrent()
return session.client.subscribe(

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 | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Confirm getClientForEnvironment throws for manually disconnected environments and that
# no caller of nativeChat.subscribe guards against a synchronous throw.
set -euo pipefail

rg -n -C6 "manuallyDisconnectedEnvironmentIds" src/renderer/src/web/web-preload-api.ts
rg -n -C6 "nativeChat\.subscribe\(|\.subscribe\(\s*\{" src/renderer/src/components/native-chat

Repository: stablyai/orca

Length of output: 19579


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- web-preload-api.ts: subscribe implementation ---'
sed -n '1260,1385p' src/renderer/src/web/web-preload-api.ts

printf '%s\n' '--- session helpers and captureSession references ---'
rg -n -C8 "captureSession|assertOwnerCapability|session\.client\.subscribe|error snapshot|unsubscribe" src/renderer/src/web/web-preload-api.ts

printf '%s\n' '--- native chat transport implementation and callers ---'
sed -n '1,150p' src/renderer/src/components/native-chat/native-chat-session-transport.ts
rg -n -C8 "getNativeChatSessionTransport|nativeChatSessionTransport|\.subscribe\(" src/renderer/src/components/native-chat -g '*.{ts,tsx}'

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
from pathlib import Path

path = Path("src/renderer/src/web/web-preload-api.ts")
text = path.read_text()

subscribe = text[text.index("subscribe: (args, onFrame) => {"):text.index(
    "\n    }\n  }\n}", text.index("subscribe: (args, onFrame) => {")
) + 6]

checks = {
    "capture_session_precedes_chain": subscribe.index("const session = captureSession()")
    < subscribe.index("void assertOwnerCapability(session.call)"),
    "capture_session_is_outside_try": "try" not in subscribe[:subscribe.index("const session = captureSession()")],
    "catch_emits_initial_error_snapshot": (
        ".catch((err: unknown) => {" in subscribe
        and "if (!cancelled && !receivedInitial)" in subscribe
        and "type: 'snapshot'" in subscribe[subscribe.index(".catch((err: unknown) => {"):]
    ),
    "manual_disconnect_guard_throws": (
        "if (manuallyDisconnectedEnvironmentIds.has(environment.id))" in text
        and "throw new Error('runtime_manually_disconnected')" in text
    ),
}

for name, result in checks.items():
    print(f"{name}={result}")
if not all(checks.values()):
    raise SystemExit("control-flow invariant failed")
PY

Repository: stablyai/orca

Length of output: 299


Move captureSession() inside the promise chain.

When the environment is manually disconnected, captureSession() throws before .catch() runs. The caller receives no error snapshot or teardown function.

Kyino-Pan added a commit to Kyino-Pan/orca that referenced this pull request Sep 23, 2026
…annot read

On a Model-A SSH worktree (desktop owns the runtime, the agent runs on the
SSH target) Claude and Codex tabs were admitted into file-backed native
chat, but the host resolves the transcript against its own filesystem,
never finds it, and settles into an empty pending snapshot. Gate every
transcript agent on host readability, as Grok/omp already were; local,
WSL (connectionId null) and Model B (`runtime-ssh-`) are unchanged. The
source-control launch dialog now derives readability from the worktree's
connection instead of `!isRemote`, so Model B keeps its chat default there.

Stopgap for stablyai#13663 until stablyai#15672 reads the transcript on the execution host.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@Anarh2404

Copy link
Copy Markdown

Hi! Is there an ETA for when this could land in a release? We hit #13663 every day and it's quite disruptive: Orca desktop on macOS with two SSH targets (one macOS, one Linux), phone paired to the desktop. Every Claude session in an SSH worktree spins forever in Chat UI, while the raw terminal view of the same tab works fine.

Still reproduces on 1.4.215: nativeChat.readSession for such a session returns {"error":"Transcript unavailable","notFound":true}, since the hook's transcriptPath points to a file on the remote host. Happy to test a build if that helps.

warmwind added a commit to warmwind/orca that referenced this pull request Oct 7, 2026
… them

Mobile native chat for a Claude/Codex session in an SSH worktree showed an
empty "start a conversation" view: nativeChat.readSession/subscribe resolved
the transcript on the desktop's disk, while the agent writes it on the SSH host.

The RPC now imports its transcript functions from ssh-aware-transcript-watch,
which picks the owner from the agent-hook rows (session id / transcript path,
best match across hosts). SSH-owned sessions are read with ranged reads through
the connection's filesystem provider and followed by polling; local and WSL
sessions keep the existing reader. A dropped connection surfaces as an error
frame and recovers on reconnect instead of rendering an empty conversation.

Kept to a one-line change in an upstream file so the fork rebases cleanly;
upstream stablyai#15672 is the full fix.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@OrcaWin

OrcaWin commented Oct 11, 2026

Copy link
Copy Markdown
Collaborator

Thank you @brennanb2025. Native chat for SSH sessions now reads the transcript on the execution host (#26334, nativeChatTranscriptPathOnExecutionHost), which covers the main symptom here. Closing as fixed; if the ownership-across-restart part is still a gap on current builds, please open an issue for it.

@OrcaWin OrcaWin closed this Oct 11, 2026
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]: Native chat never loads for an agent in an SSH worktree (transcript resolved on the desktop, written on the remote host)

4 participants