Skip to content

fix(native-chat): read SSH worktree transcripts on the host that owns them - #13687

Closed
luisfelipesena wants to merge 6 commits into
stablyai:mainfrom
luisfelipesena:fix/ssh-worktree-native-chat-transcript
Closed

luisfelipesena wants to merge 6 commits into
stablyai:mainfrom
luisfelipesena:fix/ssh-worktree-native-chat-transcript

Conversation

@luisfelipesena

@luisfelipesena luisfelipesena commented Aug 10, 2026 •

Copy link
Copy Markdown

Fixes #13663.

ELI5

When you run a coding agent in a worktree on a remote machine (over SSH) and open its native chat view, the chat just spins forever — no messages ever appear, on desktop or on mobile. That's because the app looked for the agent's conversation log on your own computer, when it actually lives on the remote one. Now the app fetches the conversation from the remote machine instead, keeps it up to date live as the agent works, and if the remote can't be reached it shows an error after 30 seconds rather than spinning forever. Local sessions are untouched.

Summary

Native chat now loads for an agent running in an SSH worktree. Before this, the chat view spun forever and never rendered a single message, on the mobile companion and in the desktop renderer alike.

The transcript was resolved against the machine the main process runs on:

// src/main/native-chat/session-file-resolver.ts:22
function claudeProjectsDir(): string {
  return join(homedir(), '.claude', 'projects')
}

For an SSH worktree the agent runs on the remote host and writes its JSONL there, so that lookup can never succeed. An unresolvable transcript falls into the resolve-poll loop added for #8401, which reports watching: true, so the "Transcript unavailable" branch never fires and no frame is ever emitted. The client has nothing to settle on and stays in its loading state.

nativeChatRequiresLocalTranscript already names this hazard ("Under Model-A SSH that disk is the wrong host, so the chat view must stay closed instead of loading forever"), but it only covers grok and omp, whose hooks disclose no transcript path. Claude and Codex do disclose one, so they were let through with a path that belongs to another machine, which is exactly the "loading forever" the comment rules out.

This reads the transcript where it lives, reusing the split the AI Vault relay already uses:

  • nativeChat.readTranscript on the relay (src/relay/native-chat-handler.ts) resolves, reads and decodes with the existing resolveSessionFilePath, readNativeChatTranscriptTail and readIncrementalTranscriptMessages, against the remote host's own home. Only decoded messages cross the mux, never the JSONL.
  • The host picks the owning connection from the agent hook row, which already carries connectionId for remote panes plus the providerSession identity. No new field on the client wire contract, so an older mobile build is fixed by updating the desktop alone. A WSL guest's wsl:<distro> id is transport provenance, not a remote host, so those sessions stay on the existing UNC translation.
  • Live tailing polls with a byte cursor. An unchanged file is answered from a stat; a grown one returns only the records past the cursor, so appends arrive as onAppend (the local watcher's behavior) instead of a full-window replacement that would reset the reader's paged-in history every second. The cursor stops at the start of a half-written record, so a line the agent is mid-flush on is re-read whole rather than skipped.
  • A silent relay reports itself. After 30s with no answer the subscription emits one error-carrying frame, so the failure mode this PR fixes cannot come back in a new shape. A notFound (transcript not flushed yet) is never counted as silence: it waits, exactly like the local loop.

Local sessions are untouched: same local reader, and an explicit filePath is never routed to a relay. An agent with no transcript decoder, or a blank session id, fails fast instead of polling a relay forever.

transcript-tail-reader.ts loses two .toReversed() calls (Node 20+): it now also runs inside the relay, whose Node-18 baseline src/relay/subprocess.test.ts enforces. The oxlint suppression carries that reason inline.

Screenshots

No visual change: this renders the existing chat UI, which previously had nothing to render. The bug it fixes, mobile companion on a Claude Code session in an SSH worktree:

Chat view stuck on the spinner for an SSH worktree session

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

42 new tests across four files, colocated with the code they cover:

  • src/relay/native-chat-handler.test.ts: reads a real JSONL fixture, answers unchanged from the cursor, ships only new records after an append, leaves a half-written record for the next tick, re-windows a file that shrank, never answers a pagination read from the cursor, reports an unresolvable transcript as a retry-worthy miss, clamps junk params.
  • src/main/native-chat/ssh-transcript-host.test.ts: owner lookup by session id and by hook transcript path, path match beating an earlier id-only row, WSL guests treated as local, local rows staying local, unknown sessions not claimed, a client-supplied path never forwarded, an unparseable relay payload becoming a miss instead of rendered junk.
  • src/main/native-chat/ssh-transcript-subscription.test.ts: first window as a snapshot (the frame that clears the loading state), appends delivered as appends and not replacements, a rotated file replacing the window, cursor and resolved path carried forward, notFound waited out, an unreachable relay reported once and still recovering, no cursor advance when a subscriber throws, unsubscribe stopping the loop.
  • src/main/native-chat/transcript-source-routing.test.ts: SSH sessions routed, local sessions not, hook path forwarded instead of the client's, misses reported rather than reading a local look-alike, AbortError propagated, fast-fail for an undecodable agent or blank session id.

Beyond the suite, the relay reader was run against the real 4 MB transcript of the session in the screenshot, on the SSH host that owns it: it resolved the file and decoded the tail (assistant/tool/assistant, with tool-call, tool-result and text blocks). That is the file the desktop could not open.

Full run: 49256 passed, 7 failed. All 7 fail identically on a clean main worktree on this machine and sit in areas this change does not touch: relay/pty-shell-launch bash-wrapper markers (3), main/providers/local-pty-shell-ready (2), relay/git-handler upstream status (1), main/ssh/ssh-remote-commands GC listing order (1). I checked out main beside the branch and ran them there to be sure.

AI Review Report

Three review passes ran over the diff (correctness and regression risk, cross-platform plus remote compatibility, security and performance), each reading the code independently, plus the branch's own tests. Everything below is code reading and unit tests: nothing was exercised on a Windows host, in a WSL distro, or against a live paired phone.

  • Cross-platform (macOS, Linux, Windows). No path concatenation is added: the relay resolves with its own host's path utilities, and a transcript path is only ever compared against a value from the same hook row, so there is no POSIX/Win32 separator mismatch. The relay bundle builds for all six platform targets and carries the new method. Two real findings, both fixed here: WSL hook rows carry a wsl:<distro> connection id that every other consumer treats as local, and my first cut would have routed them to a relay that does not exist; and the relay bundle picked up two .toReversed() calls, which the repo's Node-18 gate rejects.
  • SSH, remote, and local. Local sessions keep the untouched local reader: an explicit filePath short-circuits, and routing only happens for a hook row with a non-null, non-WSL connectionId. Both entry points (Electron IPC and runtime RPC) go through the same two routing functions, so a paired mobile client, a web client and a headless orca serve host behave identically. A desktop paired to a relay predating the method gets a reported miss rather than a hang; the method-not-found probe is cached per connect and reset on deploy and reconnect, matching requestAiVaultSessionList.
  • Agents and integrations. Claude, OpenClaude and Codex are reached. The relay can resolve grok and omp too, but their toggle stays hidden on remote panes via nativeChatRequiresLocalTranscript; opening that up is deliberately out of scope here. pi is not a native chat agent.
  • Performance. The first cut shipped the whole window on every append (300 messages on desktop, with uncapped tool output) and, worse, the renderer treats a replacement as a new generation, so paged-in history was discarded and an in-flight "load earlier" could never land. Fixed: the relay now answers a live poll with only the records past the cursor, and an idle session costs one stat round trip. The relay also echoes the path it resolved, so a poll does not re-walk the remote agent home each tick.
  • Correctness and regression risk. Three findings fixed here: notFound was being counted as silence and settled a fresh session into an error after ~3s; the poll cursor advanced before the frame was delivered, so a throwing subscriber could lose records; and .catch(() => null) swallowed AbortError. One finding, fixed by the delta path itself, was the pagination reset described above. My own test for the half-written record caught a data-loss bug in the delta cursor before it shipped.
  • UI. No UI changes. The diff touches main process, relay and shared code only; no renderer or mobile files.
  • Known limits, not fixed here. A single window is capped at 2000 messages with no byte budget, so very deep "load earlier" on a heavy transcript can stop silently on SSH; and the remote resolve still runs per tick when the hook reported no transcript path. Both are bounded and strictly better than the current behavior of showing nothing, and both are noted rather than papered over.

Security Audit

The change adds one relay method and no new client-facing wire fields. Reads run over the existing authenticated SSH relay session, and the session-to-host mapping comes from the agent hook row rather than from the client.

  • Input handling. The relay normalizes its params on the remote side: agent and session id trimmed, limit clamped, transcript path length-capped at 4096. The host validates the relay's response envelope with zod before anything reaches a client.
  • Path handling. The first cut forwarded the client-supplied transcriptPath to the remote host, which would let any paired client name a file there. Fixed: only the transcriptPath from the hook row that supplied the connection id is ever forwarded, and after the first read the relay's own resolved path is used. A path match now also beats an id-only match, closing the "render another machine's conversation" ordering case.
  • Command execution. None added. The relay bundle's transitive graph has no electron import and no new spawn.
  • IPC and RPC surface. No new IPC channel, no new stream opcode, no change to the client-facing RPC params, so docs/reference/remote-wire-compatibility.md Rules 1 to 3 are untouched.
  • Auth, secrets, dependencies. Unchanged, none handled, none added.
  • Follow-up. Message block bodies are validated structurally (z.array(z.unknown())), so a hostile remote host could return a malformed block and break the chat view's sanitizer. That requires an already-compromised host the desktop trusts with PTY execution, so it is an availability issue, not an escalation. Worth tightening separately.

Notes

  • Not validated here. This machine is headless (no Electron GUI) and has no paired phone, so the desktop-to-relay leg is covered by unit tests with the relay call mocked, and the relay leg was proven against a real transcript. pnpm build does pass here, including the relay bundle for all six platform targets; its install-dev-cli step only warns that it cannot symlink into /usr/local/bin without root.

  • Left alone deliberately. The mobile client still has no loading deadline of its own, AgentHookProviderSessionIdentity still drops connectionId, and grok/omp remain gated on remote panes. All are separate concerns; this PR keeps to the transcript path.

  • X handle. @luisfelipe_sena

@luisfelipesena
luisfelipesena force-pushed the fix/ssh-worktree-native-chat-transcript branch from 8ed4d06 to 02e869d Compare August 10, 2026 23:03
@coderabbitai

coderabbitai Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Added SSH relay contracts and transcript handling for full, appended, unchanged, paginated, and unavailable results. Added SSH ownership resolution, connection-scoped reader registration, capability caching, and teardown. Added routed local or SSH transcript reads and polling subscriptions with cursor tracking, retries, backoff, cancellation, and unavailable reporting. Added complete-record cursor propagation and comprehensive Vitest coverage.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.00% 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
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 and concisely describes the main change: reading native-chat transcripts from the owning SSH worktree host.
Description check ✅ Passed The description covers the problem, scope, rationale, linked issue, testing, limitations, security, and compatibility considerations, with only minor template deviations.

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

🧹 Nitpick comments (4)
src/main/native-chat/ssh-transcript-host.ts (1)

49-77: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value

Ownership resolution scans every hook row on each call and prefers the first id match.

Two notes on resolveNativeChatSshOwner:

  1. The id-match branch keeps the first matching row and does not compare freshness. Hook rows carry receivedAt. If two connections ever report the same provider session id, the winner depends on snapshot order. Selecting the newest receivedAt row is deterministic.
  2. resolveNativeChatSshOwner is called on every routed read and on every subscription setup, and each call walks the whole snapshot. That cost is fine at the current row counts, but the poll loop in ssh-transcript-subscription.ts resolves once and caches, while readRoutedNativeChatTranscriptTail re-resolves per page request.

Item 1 is worth fixing; item 2 is informational.

src/main/native-chat/ssh-transcript-subscription.test.ts (1)

46-67: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a test for a subscriber callback that throws.

No test covers onInitialSnapshot throwing. That gap allowed the snapshotDelivered ordering defect flagged on ssh-transcript-subscription.ts lines 136-152. A regression test would assert that the next poll still routes the full window to onInitialSnapshot and not to onReplace.

💚 Proposed test
+  it('retries the initial snapshot when the subscriber throws on the first frame', async () => {
+    readSshNativeChatTranscript.mockResolvedValue(window([message('a')], 10))
+    const callbacks = harness()
+    callbacks.onInitialSnapshot.mockImplementationOnce(() => {
+      throw new Error('renderer not mounted')
+    })
+
+    const subscription = subscribeSshNativeChatTranscript(
+      'dev-box',
+      { agent: 'claude', sessionId: 'abc', ...callbacks },
+      { pollIntervalMs: 5 }
+    )
+    await vi.advanceTimersByTimeAsync(12)
+
+    expect(callbacks.onInitialSnapshot).toHaveBeenCalledTimes(2)
+    expect(callbacks.onReplace).not.toHaveBeenCalled()
+    subscription.unsubscribe()
+  })
src/main/native-chat/transcript-source-routing.ts (2)

59-72: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Lines 69-71 are a dead branch: both paths return TRANSCRIPT_MISS.

The guard if (remote && !isSshNativeChatUnchangedResult(remote)) returns the same constant as the unconditional return on line 72. The isSshNativeChatUnchangedResult import is used only here. Keep the explanatory comment and drop the branch.

♻️ Proposed simplification
   // This session is known to live on another machine, so a local read could only
   // hit a look-alike: the same session id, or the same absolute path under a
   // matching home layout. Report the miss instead of rendering another machine's
   // conversation. `unchanged` and `appended` cannot answer a windowed read.
-  if (remote && !isSshNativeChatUnchangedResult(remote)) {
-    return TRANSCRIPT_MISS
-  }
   return TRANSCRIPT_MISS

Remove the now-unused isSshNativeChatUnchangedResult import on line 2.


83-93: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low value

setupSignal is checked once and then discarded on the SSH path.

The local branch on line 81 forwards setupSignal to subscribeNativeChatTranscript. The SSH branch checks it on line 83 and never passes it on. An abort that lands after that check still starts a polling subscription. The caller holds unsubscribe, so the impact is bounded.

Forward the signal into subscribeSshNativeChatTranscript and abort its internal controller, so both branches honor setup cancellation the same way.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: f8a833db-21c1-472a-80ed-48fc4d926a59

📥 Commits

Reviewing files that changed from the base of the PR and between 8da3629 and 8ed4d06fed740902186b769b48df405d238f0c6b.

📒 Files selected for processing (15)
  • src/main/ipc/native-chat.ts
  • src/main/native-chat/ssh-transcript-dispatch.ts
  • src/main/native-chat/ssh-transcript-host.test.ts
  • src/main/native-chat/ssh-transcript-host.ts
  • src/main/native-chat/ssh-transcript-subscription.test.ts
  • src/main/native-chat/ssh-transcript-subscription.ts
  • src/main/native-chat/transcript-source-routing.test.ts
  • src/main/native-chat/transcript-source-routing.ts
  • src/main/native-chat/transcript-tail-reader.ts
  • src/main/runtime/rpc/methods/native-chat.ts
  • src/main/ssh/ssh-relay-session.ts
  • src/relay/native-chat-handler.test.ts
  • src/relay/native-chat-handler.ts
  • src/relay/relay.ts
  • src/shared/ssh-native-chat-relay.ts

Comment thread src/main/ssh/ssh-relay-session.ts Resolved
Comment thread src/relay/native-chat-handler.ts Resolved
Comment thread src/shared/ssh-native-chat-relay.ts Resolved
@luisfelipesena

Copy link
Copy Markdown
Author

Pushed 5b59111 addressing every review comment, plus the four nitpicks. All eight threads are answered and resolved.

Taken as filed

  • snapshotDelivered now flips after onInitialSnapshot returns.
  • Schema-validation failures return a bare { error }; only an unwritten transcript keeps notFound.
  • The subscribe path destructures transcriptPath out of args, so a client-supplied path cannot reach the relay.
  • The window cursor comes from completedRecordEnd, not the raw file end.
  • Results carry a dev:ino:mtimeMs generation, so a same-length replacement is detected.
  • deliver runs outside the transport try; ownership prefers the freshest hook row; the dead TRANSCRIPT_MISS branch is gone; setupSignal is forwarded into the poll loop.

Found while verifying those, also fixed

  • noteSilence() was called from inside the transport catch, and its own callback could throw before schedule(), killing the poll loop permanently with watching: true. Every callback now runs inside one log-only guard.
  • unavailableReported had the same flag-before-callback shape as snapshotDelivered.
  • With the flag moved, a permanently throwing subscriber would have re-read the whole remote window at 1 Hz forever: the backoff reset now runs only after a frame is delivered.
  • Cursor and generation are stamped after the read, not before, so a record landing mid-read no longer re-ships or forces a spurious re-window.
  • A rotation between the read and the cursor probe returns a retry-worthy miss instead of rejecting, which the poll loop was counting as relay silence.
  • findLastCompleteLineEnd checks bytesRead before comparing an allocUnsafe byte the new caller could reach past EOF.
  • Pagination reads skip the cursor probe they never use.

The one I declined

Migrating the relay-method flags onto GitCapabilityCache. It models git binary capabilities behind a closed union and a 30-minute retry; relay method support resets on deploy and reconnect instead, and the two AI Vault flags beside it already use the boolean pattern. Moving all three belongs in its own PR. I took the testable half: ssh-relay-session-native-chat.test.ts covers the initial fallback, the cached fallback, the reset after a reconnect on the same session, and a non-capability error surfacing.

Verification

pnpm lint, pnpm typecheck and pnpm build clean. 258 tests across the six files here. Two of the subtler fixes were mutation-tested: reverting the backoff move or the unavailableReported order turns the new tests red. One test that would have passed for the wrong reason was replaced with a direct completedRecordEnd suite (empty, complete, half-written, shrunk, missing). Full run: 49426 passing, 7 failures that also fail on a clean main worktree on this machine, in pty-shell-launch, local-pty-shell-ready, git-handler and ssh-remote-commands.

Not covered by a test, stated plainly: the stat/read skew behind the post-read stamping is argued from the code, not reproduced, because there is no hook to append mid-read.

@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 (3)
src/relay/native-chat-handler.ts (1)

194-202: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Narrow the swallowed error to the rotation case.

windowCursor maps every failure to null, and the caller turns that into notFound: true. The shared contract in src/shared/ssh-native-chat-relay.ts reserves notFound for a retry-worthy miss, and the subscription waits silently on it. A persistent EACCES or EIO on the probe therefore keeps the loading view spinning with no report.

Return null only for a missing file, and let other errors surface as a real error result.

♻️ Proposed narrowing
 async function windowCursor(filePath: string, size: number): Promise<number | null> {
   try {
     return await completedRecordEnd(filePath, size)
-  } catch {
-    return null
+  } catch (error) {
+    const code = (error as NodeJS.ErrnoException | undefined)?.code
+    if (code === 'ENOENT' || code === 'ENOTDIR') {
+      return null
+    }
+    throw error
   }
 }
src/main/ssh/ssh-relay-session-native-chat.test.ts (1)

129-150: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add concurrent-probe and host-isolation coverage for the capability fallback.

This test covers the initial fallback and the cached call. It does not cover two overlapping requestNativeChatTranscript calls that race the first probe, and it does not cover two sessions for different targets keeping separate capability state. A poll loop plus a manual chat open can issue overlapping requests, so a missing in-flight guard would send one relay request per caller.

Add one test that starts two requests before the first resolves and asserts a single relay method call, and one test that establishes two sessions and asserts a fallback on one target does not disable the other.

As per coding guidelines: "Use GitCapabilityCache with a narrow unsupported-error predicate, scope capability state to the executing host, and test initial fallbacks, cached calls, concurrent probes, and host isolation."

Source: Coding guidelines

src/main/native-chat/ssh-transcript-subscription.test.ts (1)

421-425: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Add a lower bound so a dead loop cannot pass this test.

The assertion only caps the call count. A regression that stops the loop after the first throw produces one call and still satisfies toBeLessThan(12). Assert a lower bound too, so the test pins both backoff and continued polling.

♻️ Proposed assertion
     // 1s, 2s, 4s, 5s, 5s… rather than 30 ticks at 1s.
     expect(readSshNativeChatTranscript.mock.calls.length).toBeLessThan(12)
+    expect(readSshNativeChatTranscript.mock.calls.length).toBeGreaterThan(4)

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 35c1243d-9b8a-43cb-81dc-85582afb6cee

📥 Commits

Reviewing files that changed from the base of the PR and between 02e869dc34dcc0bb3e99e1b8bb33d513a9300c58 and 5b591110e6fde8250d0ebd64626e4f4dc0aa67cd.

📒 Files selected for processing (12)
  • src/main/native-chat/ssh-transcript-host.test.ts
  • src/main/native-chat/ssh-transcript-host.ts
  • src/main/native-chat/ssh-transcript-subscription.test.ts
  • src/main/native-chat/ssh-transcript-subscription.ts
  • src/main/native-chat/transcript-completed-record-end.test.ts
  • src/main/native-chat/transcript-source-routing.test.ts
  • src/main/native-chat/transcript-source-routing.ts
  • src/main/native-chat/transcript-tail-reader.ts
  • src/main/ssh/ssh-relay-session-native-chat.test.ts
  • src/relay/native-chat-handler.test.ts
  • src/relay/native-chat-handler.ts
  • src/shared/ssh-native-chat-relay.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • src/shared/ssh-native-chat-relay.ts
  • src/main/native-chat/transcript-source-routing.ts
  • src/main/native-chat/ssh-transcript-host.ts
  • src/main/native-chat/ssh-transcript-subscription.ts

Comment thread src/relay/native-chat-handler.ts Resolved
@luisfelipesena

Copy link
Copy Markdown
Author

256bcc5 is up with the cursor fix, and the three nitpicks from this round are in as well: the backoff test now asserts a lower bound (a loop that dies after the first throw used to satisfy the cap on its own), and the relay-method capability tests cover host isolation and two callers racing the first probe.

On the windowCursor nitpick: it is moot rather than narrowed. Taking the cursor from the read removed that probe entirely, so there is no longer a swallowed EACCES/EIO to classify.

On the in-flight guard: there is none, deliberately. Two overlapping callers each pay one method not found reply, once per connect, and the AI Vault methods beside this one behave the same. The test asserts what actually happens (both resolve null, the fallback latches, later callers stop asking) instead of implying a dedupe that is not there.

Full run on this branch: 49428 passing, 7 failures that also fail on a clean main worktree on this machine (pty-shell-launch x3, local-pty-shell-ready x2, git-handler, ssh-remote-commands). Lint, typecheck and build clean.

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


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: a8cb7378-cb31-4f1a-b24f-e8a31e7119ed

📥 Commits

Reviewing files that changed from the base of the PR and between 5b591110e6fde8250d0ebd64626e4f4dc0aa67cd and 256bcc52509644c0eceab556a5951563685eca45.

📒 Files selected for processing (6)
  • src/main/native-chat/ssh-transcript-subscription.test.ts
  • src/main/native-chat/transcript-source-routing.ts
  • src/main/native-chat/transcript-tail-reader-completed-to.test.ts
  • src/main/native-chat/transcript-tail-reader.ts
  • src/main/ssh/ssh-relay-session-native-chat.test.ts
  • src/relay/native-chat-handler.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/main/native-chat/ssh-transcript-subscription.test.ts
  • src/main/native-chat/transcript-source-routing.ts

Comment thread src/relay/native-chat-handler.ts Resolved
luisfelipesena and others added 4 commits August 11, 2026 15:50
… them

An agent running in an SSH worktree writes its JSONL transcript on the
remote host, but native chat resolved it against the desktop's own home
(session-file-resolver.ts). Resolution could never succeed, and because an
unresolvable transcript falls into the resolve-poll loop that reports
watching: true, no frame was ever emitted: the chat view spun forever with
no error, on mobile and on the desktop alike.

Read the transcript where it lives. A new relay method resolves, reads and
decodes next to the file, mirroring the AI Vault relay split. The host maps a
session to its SSH connection through the agent hook row that already carries
connectionId, so the client wire contract is unchanged and a WSL guest, whose
id is transport-only, stays on the local UNC path.

Live tailing polls that method with a byte cursor: an unchanged file is
answered from a stat, and a grown one returns only the records past the
cursor, so appends stream as appends instead of re-shipping the window and
resetting the reader's paged-in history. The cursor stops at the start of a
half-written record, so a line the agent is still flushing is re-read whole
rather than skipped. A relay that stays silent for 30s reports itself once
instead of reproducing the spinner this fixes, while a not-yet-flushed
transcript keeps waiting the way the local loop does.

transcript-tail-reader.ts drops two `.toReversed()` calls: it now also runs
inside the relay, whose Node-18 baseline subprocess.test.ts enforces.

Fixes stablyai#13663
Review found the poll loop could still strand the very view it exists to
unstick, and that the byte cursor was not tight enough to trust.

- A subscriber that threw on the first frame locked the view in loading
  forever: snapshotDelivered flipped before onInitialSnapshot ran, so the
  retry took the replacement branch, the client never got a snapshot and the
  silence report was suppressed. The flag, the cursor and the backoff reset
  now all happen after the callback returns.
- Every callback the loop makes runs inside one log-only guard, and
  schedule() always runs. A throw from the unavailable frame used to escape
  before it and kill the loop with no timer armed.
- A window read returned the raw file end as the cursor while the reader
  excludes a half-written trailing record, so the next incremental read
  started mid-record and lost it. completedRecordEnd is now the cursor, and
  it clamps to the live size; findLastCompleteLineEnd checks bytesRead before
  reading an allocUnsafe byte it may never have filled.
- The cursor was size-only, so a transcript replaced by one of the same
  length answered unchanged forever. Results now carry an opaque
  dev:ino:mtimeMs generation that the caller echoes back; a peer that omits
  it keeps the old behavior.
- Cursor and generation are stamped after the read, not before, so a record
  landing mid-read no longer re-ships or forces a spurious re-window.
- A rotation between the read and the cursor probe reports the same
  retry-worthy miss as every other rotation instead of rejecting, which the
  poll loop was counting as relay silence.
- A schema-validation failure no longer borrows notFound, which the loop
  waits out silently; only a genuinely unwritten transcript does.
- A client-supplied transcriptPath could still reach the relay through the
  subscribe path's spread. It is destructured out, and ownership now prefers
  the freshest hook row on both the path and the id key.

Adds ssh-relay-session-native-chat.test.ts for the relay-method capability
fallback (initial, cached, reset on reconnect) and a completedRecordEnd suite.
Review round two: the window cursor still came from a stat, just a later
one. A record appended while the read was in flight moved the cursor past a
record the read never returned, so the next incremental read skipped it.

The tail reader already knew the answer and dropped it. It now reports
completedTo, the offset just past the last complete record inside the range
it actually covered, and the relay uses that as the cursor. A cursor can no
longer sit mid-record, and it can no longer pass a record that is not in the
window it accompanies. The standalone completedRecordEnd probe goes away with
it: one less open per read, and the rotation race it introduced disappears
with the second stat.

The boundary is computed lazily. A range ending on a newline is already a
record boundary, so the common case adds no I/O; only a half-written trailing
record pays for the back-scan.

Also from review: the backoff test asserts a lower bound, so a loop that dies
after the first throw cannot pass it, and the relay-method capability tests
cover host isolation and two callers racing the first probe.
A path-level stat can outlive the inode it measured: clamp to the open
handle's live size and treat a short final-byte read as a miss instead of
minting a cursor from allocUnsafe garbage. When the post-read generation
no longer matches the pre-read stamp, retry once (or miss) so a same-length
replacement cannot publish old messages under the new generation and lock
the next poll on unchanged.

Co-authored-by: Cursor <[email protected]>
@luisfelipesena
luisfelipesena force-pushed the fix/ssh-worktree-native-chat-transcript branch from 256bcc5 to aedb5d1 Compare August 11, 2026 16:01
@coderabbitai

coderabbitai Bot commented Aug 11, 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.

@luisfelipesena

Copy link
Copy Markdown
Author

Rebased onto current main (a0a654c3a9), resolved the transcript-tail-reader.ts conflicts (kept abort-signal checks from main + the completed-record cursor from this branch), and pushed aedb5d1 for the latest review round:

  • Rotation / short-read (transcript-tail-reader.ts): clamp to the open handle's live size; short final-byte read → empty retryable cursor. New transcript-tail-reader-rotation.test.ts.
  • Generation race (native-chat-handler.ts): generation flip mid-read → one retry, then notFound. Append path refuses a same-size generation flip. New native-chat-handler-generation-race.test.ts.
  • GitCapabilityCache: declined again (closed Git union + 30m retry; relay methods reset on establish/reconnect, matching the AI Vault flags beside this one). Host isolation covered by the existing per-target + reconnect tests.

All review threads on this PR are resolved. mergeable: MERGEABLE.

@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.

🧹 Nitpick comments (1)
src/relay/native-chat-handler.ts (1)

230-234: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value

Consider rejecting an invalid limit instead of defaulting to 1.

If a caller sends a missing, non-numeric, or non-positive limit, the relay answers with a one-record window. The caller cannot distinguish that window from a transcript that truly holds one record, so the chat view renders a silently truncated history. An explicit error, or a default equal to the normal page size, makes the failure visible.

♻️ Proposed alternative default
+const SSH_NATIVE_CHAT_READ_LIMIT_DEFAULT = 40
 const limit =
   typeof rawLimit === 'number' && Number.isFinite(rawLimit) && rawLimit > 0
     ? Math.min(Math.floor(rawLimit), SSH_NATIVE_CHAT_READ_LIMIT_MAX)
-    : 1
+    : SSH_NATIVE_CHAT_READ_LIMIT_DEFAULT

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: e8f4cf54-fc75-4fe5-b4cf-3a15bdb11f92

📥 Commits

Reviewing files that changed from the base of the PR and between a0a654c and aedb5d1.

📒 Files selected for processing (20)
  • src/main/ipc/native-chat.ts
  • src/main/native-chat/ssh-transcript-dispatch.ts
  • src/main/native-chat/ssh-transcript-host.test.ts
  • src/main/native-chat/ssh-transcript-host.ts
  • src/main/native-chat/ssh-transcript-subscription.test.ts
  • src/main/native-chat/ssh-transcript-subscription.ts
  • src/main/native-chat/transcript-source-routing.test.ts
  • src/main/native-chat/transcript-source-routing.ts
  • src/main/native-chat/transcript-tail-reader-cancellation.test.ts
  • src/main/native-chat/transcript-tail-reader-completed-to.test.ts
  • src/main/native-chat/transcript-tail-reader-rotation.test.ts
  • src/main/native-chat/transcript-tail-reader.ts
  • src/main/runtime/rpc/methods/native-chat.ts
  • src/main/ssh/ssh-relay-session-native-chat.test.ts
  • src/main/ssh/ssh-relay-session.ts
  • src/relay/native-chat-handler-generation-race.test.ts
  • src/relay/native-chat-handler.test.ts
  • src/relay/native-chat-handler.ts
  • src/relay/relay.ts
  • src/shared/ssh-native-chat-relay.ts
🚧 Files skipped from review as they are similar to previous changes (16)
  • src/main/runtime/rpc/methods/native-chat.ts
  • src/main/native-chat/transcript-source-routing.test.ts
  • src/shared/ssh-native-chat-relay.ts
  • src/main/native-chat/ssh-transcript-subscription.test.ts
  • src/main/ssh/ssh-relay-session-native-chat.test.ts
  • src/main/native-chat/transcript-source-routing.ts
  • src/main/native-chat/ssh-transcript-subscription.ts
  • src/main/native-chat/ssh-transcript-dispatch.ts
  • src/main/native-chat/transcript-tail-reader-completed-to.test.ts
  • src/main/native-chat/ssh-transcript-host.ts
  • src/main/ipc/native-chat.ts
  • src/relay/relay.ts
  • src/main/ssh/ssh-relay-session.ts
  • src/relay/native-chat-handler.test.ts
  • src/main/native-chat/ssh-transcript-host.test.ts
  • src/main/native-chat/transcript-tail-reader.ts

A client-supplied transcriptPath could path-match a hook row without
co-binding providerSession.id, so session A plus another pane's path
could select that pane's remote connection and read its JSONL.

Require the same session id for path-based owner selection; path only
disambiguates among same-session rows. Add regression coverage for the
cross-session case.
TS2709 came from indexing an import-type namespace as a type in the
generation-race test; index via typeof instead. Drop redundant
unknown|null reader return types (null is a normal unknown value) so
type-aware oxlint --deny-warnings stops failing static analysis.
@nwparker

Copy link
Copy Markdown
Contributor

Superseded by #15672, which explicitly names this PR and #15515 as superseded. The newer implementation expands the same SSH transcript ownership fix to persist host-owner evidence across disconnects/restarts, gate mixed-version clients, and cover mobile/web paths. Keeping #15672 as the active implementation avoids parallel fixes for #13663.

@nwparker

Copy link
Copy Markdown
Contributor

Superseded by #15672.

@nwparker nwparker closed this Sep 27, 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)

5 participants