Skip to content

fix(relay): signal capacity loss instead of dropping, hanging, or truncating - #17870

Merged
nwparker merged 1 commit into
mainfrom
fix/relay-payload-limits
Sep 2, 2026
Merged

nwparker merged 1 commit into
mainfrom
fix/relay-payload-limits

Conversation

@nwparker

@nwparker nwparker commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Rebased onto current main and squashed with #17934 into one commit. #17934 is folded in and can be closed. They must not land apart: on its own this PR arms a 60 s write timeout on an unstaged chunked Windows upload, which turns a hang into a mid-file failure that leaves a truncated artifact under the real remote name. Evidence below.

Three failures with one shape: a payload past a fixed capacity was met with silence, with a wait that never ends, or with a prefix presented as a whole.

#15238 — the workspace snapshot was silently dropped

workspace-session-handler.ts:154 called dispatcher.notify(...), which on rejection does nothing but logDroppedProducerNotification — one stderr line, no client-visible effect. Producer notifications are capped per frame at ¾ of the sink high-water mark (12288 B on a Node ≤21 remote), but DispatcherWriterAdmission.admit applies no per-frame cap to the control (1 MB) or legacy-response (2 MB) lanes. A 13.8 KB snapshot was never too big for the link, only for the one lane that broadcasts it unsolicited. So the relay publishes per client and, for a client whose sink refused the frame, sends a compact workspace.stale marker on the control lane; the client re-reads through workspace.get.

Wire compatibility. relay-handshake.ts:129 enforces exact version equality, so a paired client and relay are always the same build — but the failure shape of handleRemoteWorkspaceNotification (remote-workspace.ts:141) is identical to decodeTerminalStreamFrame returning null: an unknown method vanishes silently. Hence:

  • A new workspace.stale method, not a new field on workspace.changed. The tempting Rule-1 move — workspace.changed with snapshot omitted plus truncated: true — is destructive under Rule 3: normalizeSnapshot(undefined, ns) yields revision 0 and an empty session, which rememberRemoteWorkspaceSnapshot caches. An old client would replace its tab list with nothing, worse than the drop. A separate method degrades to exactly today's behaviour.
  • The marker carries { namespace } only — no revision, no sourceClientId. Markers coalesce per (client, namespace); one naming an author or generation would replay a projection the producer had moved past, re-creating the staleness being fixed.

The retention/retry machinery is extracted from the fs.changed overflow path into relay-client-resync-marker.ts rather than duplicated — the watcher emitter sheds ~130 lines and its 28 tests pass unchanged.

BEFORE  expected [] to have a length of 1 but got +0
        expected "vi.fn()" to be called 1 times, but got 0 times  (×3)
AFTER   6 passed

Fixture is 3 worktrees × 8 tabs ⇒ 13024 B, against the reported 13798 B.

#16432 — the Windows upload hung, and the naive fix could truncate

The issue was attributed to [Console]::In.ReadToEnd() materializing the base64 bundle. That is not what the reporter measured: he also measured new IO.StreamReader([Console]::OpenStandardInput()) — an incremental reader — hanging at 1 MB. The limit is in the stdin the host hands PowerShell over a non-pty ssh exec, not in the string the script builds. (A later measurement on real Windows PowerShell 5.1 confirmed CopyTo moves 2 MB through a plain pipe in under a second, so the constraint is the sshd exec channel specifically.)

  • uploadFileViaSystemSsh — the user file-import path (ssh-connection.ts:567-587) — was piping a whole file into one Windows stdin, unchunked and untimed. That is the path large files take, and it was untouched by the first half of this work. It now chunks into 32 KB writes, each with a bounded wait.
  • The Windows directory upload reuses that single-file path rather than repeating a weaker copy of chunk-read + write-buffer. readLocalUploadFile's isFile && size && ino && dev TOCTOU verification comes back with it.
  • A Windows write needing more than one exec lands on ${remotePath}.orca-partial and is published by [System.IO.File]::Move, so a failed chunk cannot leave a truncated artifact under the real name. exclusive is enforced once at the rename, not on the first chunk, where a retry met its own leftovers.
  • The mkdir batch reads stdin through the stream reader the reporter measured surviving 50 KB, not [Console]::In, which he measured wedging at that size. Paths only, batched, so a pathological tree cannot walk back into the same size.
  • waitForChannelClose takes an optional bound. A wedged PowerShell stays alive at idle CPU and never closes, so without one the promise is never settled and the caller waits forever with no error. It settles before closing — closing first made the resulting SIGTERM mask the timeout, the only diagnosis a wedged remote gives.

Why the two halves cannot land apart — truncation injected on both

A 262144 B source, upload driven through uploadDirectoryViaSystemSsh against a simulated Windows host, failing the 4th chunk write:

#17870 alone
  upload rejected:   write C:/…/relay/relay.js at offset 0 failed (exit 1)
  remote filesystem: C:/…/relay/relay.js  size=98304 B
  real-named artifact present: YES (98304 B of 262144)

#17870 + #17934 (this commit)
  upload rejected:   write C:/…/relay/relay.js.orca-partial at offset 98304 failed (exit 1)
  remote filesystem: C:/…/relay/relay.js.orca-partial  size=98304 B
  real-named artifact present: no

A truncated relay.js is a broken relay that looks installed.

#12547 — Quick Open showed a prefix as the whole workspace

quick-open-file-list.ts:265 hardcoded truncated: false. The mechanism "a full page means there is more" only works if the caller named the cap, and this caller named none. Quick Open now sends QUICK_OPEN_LISTING_MAX_RESULTS on the Electron IPC hop and the runtime-RPC hop (the optional maxResults field #17954 added to files.listAll but nothing was sending), and reads a full page as truncation — lighting the quickOpen.moreMatchesAvailable string that already existed, so no catalog change. The local listQuickOpenFiles path honours the cap too, which it previously ignored.

What the rebase dropped, and why

Earlier revisions of this work also clamped the host unconditionally (#17870) and escalated an uncapped request to an explicit error (#17934). #17954 landed today and removed the premise. An oversized fs.listFiles reply is now streamed on the bulk lane; its commit message states the case directly — "picking a ceiling to refuse at does not fix that, it just moves where it shows up and refuses listings that would have been delivered."

Keeping either would have been a regression:

  • the unconditional clamp re-introduces exactly the silent prefix this PR set out to kill, for every caller that names no limit;
  • the throw hard-fails three current in-tree callers that pass no options at all — runtime-file-commands-search-runtime-files.ts:81, filesystem-read-handlers.ts:125, runtime-file-commands-constructor.ts:41 — so the markdown panel and the mobile file browser break on any large remote workspace. That is this build calling itself.

So the host now returns the whole listing when no limit is named and only clamps a limit it was given. fs-handler-list-files-bounded-response.test.ts is renamed fs-handler-list-files-result-limit.test.ts and inverted: it asserts an uncapped request is answered in full, so nothing can quietly re-add a host-side default.

Verification

$ pnpm tc                                     # clean
$ pnpm run check:code-quality:changed         # 0 new findings across 20 files
$ pnpm test src/relay src/main/ssh src/main/runtime
  866 files | 9790 passed | 27 skipped
$ pnpm test src/main/ipc src/renderer/src/components/quick-open-file-list.react.test.tsx
  1087 files | 11093 passed

Rebase check: of the 20 files touched, main had moved three since the merge base — filesystem-search-handlers.ts (inlined QUICK_OPEN_SSH_LEGACY_RESULT_LIMIT), ssh-system-fallback.test.ts (+3 unclaimed-alias cases from #17946), fs-handler.ts (#17954's streaming). All three verified present in the final file content, not just in the patch. No other file differs from main; en.json is untouched.

Residual risk

The 32 KB chunk size is derived from the reporter's measurements, not verified against a real Windows sshd, which is the layer the constraint actually lives in. The 60 s bound makes the failure mode a timeout rather than a hang either way, and staging makes a mid-file failure non-destructive. It adds ~47 round-trips for a 1.5 MB bundle — cheap under ControlMaster, worth watching if deploy latency regresses. The reporter's own preferred fix (bsdtar, in Windows since 10 1803, reusing the POSIX transport and cutting the payload ~4.8×) remains the better long-term answer.

Fixes #15238, #16432
Refs #12547, #17954
Supersedes #17934


ELI5

Three ways a remote connection dropped or hung on a large payload: workspace updates over ~12 KB were silently thrown away, leaving your tab list stale; a big Windows upload hung forever instead of erroring, and the obvious fix for that could leave half a file under the real name; and Quick Open showed you the first 20,001 files as if that were all of them.

User-facing regression risk

  • Windows uploads now go per file in 32 KB chunks: roughly 47 extra round-trips for a 1.5 MB bundle, and a failed upload now leaves a .orca-partial file behind instead of a truncated real one.
  • Quick Open now reports "more matches available" on large workspaces where it previously showed a prefix silently. The listing itself is unchanged in size.
  • Reasoned, not host-verified: the 32 KB chunk size comes from the reporter's measurements, not a real Windows sshd. A 60 s timeout bounds it regardless.

Visual Proof

N/A — no visual or interaction change. The only user-visible surface is the existing quickOpen.moreMatchesAvailable hint, which now appears when it should.

Testing

  • Unit / integration tests (pnpm test src/relay src/main/ssh src/main/runtime src/main/ipc)
  • Typecheck (pnpm tc)
  • Changed-code quality gate
  • Truncation injection reproduced on both the intermediate and combined states (above)
  • Platforms: macOS (host). Windows upload path is covered by system-ssh-windows-upload.test.ts against a simulated host; no real Windows sshd was available.

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

Important

One cross-cutting behavior change to settle before merge: the relay-side fs.listFiles cap is now unconditional, and it silently truncates two fs.listFiles callers that never asked for a bound and have no truncation UI — markdown-document listing. Details below.

Reviewed changes

  • Relay workspace snapshot publication — workspace.changed is now published per client on the producer lane, and a frame that exceeds the per-client producer capacity degrades to a new workspace.stale control-lane marker instead of a silent drop (workspace-snapshot-publication.ts, workspace-session-handler.ts).
  • Client stale resync — the client coalesces workspace.stale markers per target and re-reads the snapshot through workspace.get, suppressing the authoring client's own echo via session comparison (remote-workspace-stale-resync.ts, remote-workspace.ts).
  • Marker machinery extraction — the retention/retry state machine is lifted out of the watcher emitter into relay-client-resync-marker.ts and shared by both fs.changed and workspace.stale.
  • fs.listFiles bounding — the relay applies resolveQuickOpenResultLimit() unconditionally rather than only when the caller remembered to send maxResults (fs-handler.ts).
  • Quick Open truncation flag — the renderer requests the cap explicitly and derives truncated from a full page instead of hardcoding false (quick-open-file-list.ts, runtime-file-search-client.ts).
  • Windows upload framing — directory uploads split into a batched mkdir pass plus per-file 32 KB stdin writes, and waitForChannelClose gains an optional timeout applied to every Windows stdin write (system-ssh-file-transfer.ts, system-ssh-file-binary-transfer.ts, system-ssh-operation-lifecycle.ts).

⚠️ The unconditional fs.listFiles cap also truncates markdown-document listing

The relay change is right for Quick Open — but fs.listFiles is a shared listing endpoint, and two callers pass no maxResults and surface no truncation signal. They now silently return only the first 20,001 paths on large repos, where they were previously unbounded.

Technical details
# fs.listFiles cap reaches callers without a truncation signal

## Affected sites
- src/main/ipc/filesystem.ts:826 — `fs:listMarkdownDocuments` calls `provider.listFiles(args.rootPath)` with no `maxResults`.
- src/main/runtime/runtime-file-commands-search-runtime-files.ts:81 — `listRuntimeMarkdownDocuments` calls `provider.listFiles(target.worktree.path)` with no `maxResults`.
- src/relay/fs-handler.ts — now bounds every `fs.listFiles` request at `QUICK_OPEN_LISTING_MAX_RESULTS` regardless of caller.

## Required outcome
- Markdown-document listing must not silently omit documents beyond 20,001 paths, OR the truncation must be visible to the user.
- Quick Open keeps its refine hint; the markdown paths currently have no equivalent signal.

## Suggested approach (optional)
- Have the two markdown callers pass an explicit, larger bound (or a dedicated scan) and/or return a `truncated` flag, or scope the relay default so non-Quick-Open callers can opt into unbounded listing.
## Open questions for the human (optional)
- Is a silently partial markdown-document list acceptable for >20k-file repos, or should these callers be updated in this PR?

ℹ️ Nitpicks

  • quick-open-file-list.ts:271 reports truncated: files.length >= QUICK_OPEN_LISTING_MAX_RESULTS, so a workspace with exactly 20,001 files shows a spurious "more matches available" hint. The PR body describes the limit + 1 / length > limit pattern, but the relay clamps the request at the cap, so limit + 1 is not actually used here; the >= check is the only workable heuristic given that clamp — just noting the description/off-by-one mismatch.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@nwparker
nwparker force-pushed the fix/relay-payload-limits branch from 494fa7b to 48a097f Compare September 1, 2026 09:59
@coderabbitai

coderabbitai Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The PR adds stale remote workspace resynchronization across the relay and main process. It adds bounded, staged Windows SSH uploads with channel timeouts. It replaces hard-coded quick-open listing limits with shared limit propagation and truncation reporting. New tests cover resynchronization coalescing, relay fallback markers, Windows upload framing and failure modes, and file listing limits.

Merge Risk: 🟠 High · up to 6c93e

The PR improves large workspace, file-list, and Windows upload handling, but a failed Windows replacement upload can delete the existing destination before the replacement is published, leaving the file missing. This high-impact data-loss risk, along with staging-file interference, should be fixed or explicitly accepted before merging.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning The PR includes Quick Open listing changes associated with #12547 and Windows upload changes associated with #16432, but the linked_issues context contains only [#15238]. These changes are not require… Link #12547 and #16432 explicitly as linked issues, or move the Quick Open and Windows upload changes into separate pull requests. Keep this pull request limited to the workspace resynchronization changes if only #15238 is intended.
Docstring Coverage ⚠️ Warning Docstring coverage is 24.49% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 49 functions across 20 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The PR satisfies [#15238] by replacing silently dropped workspace.changed events with workspace.stale markers and client-side workspace.get resynchronization. The implementation also deduplicates read…
Title check ✅ Passed The title clearly summarizes the main change: preventing capacity-related payload loss, hangs, and truncation. It is concise and relevant to the changeset.
Description check ✅ Passed The description is detailed and covers the ELI5 summary, changes, rationale, linked issues, visual proof, testing, platforms, and residual risks. Some template headings and checklist items are not inc…
Full details: Linked Issues check

Explanation

The PR satisfies [#15238] by replacing silently dropped workspace.changed events with workspace.stale markers and client-side workspace.get resynchronization. The implementation also deduplicates reads, suppresses duplicate snapshots, handles errors, and includes tests. This meets the issue's minimum follow-up synchronization requirement without requiring chunking or streaming.

Full details: Out of Scope Changes check

Explanation

The PR includes Quick Open listing changes associated with #12547 and Windows upload changes associated with #16432, but the linked_issues context contains only [#15238]. These changes are not required by #15238 and are outside the provided linked-issue scope.

Full details: Description check

Explanation

The description is detailed and covers the ELI5 summary, changes, rationale, linked issues, visual proof, testing, platforms, and residual risks. Some template headings and checklist items are not included explicitly, but the required information is mostly present.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 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.

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

ℹ️ No code issues in this delta — one commit-message nitpick below.

Reviewed changes

  • Rebased the fs.listFiles handler change onto main's split of src/main/ipc/filesystem.ts into src/main/ipc/filesystem/filesystem-search-handlers.ts: the maxResults pass-through to listQuickOpenFiles moved with the function and is byte-identical, so no behavior changed.

ℹ️ Nitpicks

  • The amended commit message body lost its #15238 / #12547 / #16432 lead-in lines, leaving sentence fragments in the merged history (e.g. "…silence or with a wait that never ends. stderr line, so the client kept a stale tab/session list…", "and the failing UI is a call site that does not."). Restore those three lines before merge so the permanent git log entry stays coherent.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@nwparker

nwparker commented Sep 1, 2026

Copy link
Copy Markdown
Contributor Author

Merge blocker: this must not land without #17934 — data-corruption risk

Independent audit found a new unsafe pair. This PR makes a corruption path more reachable than main does.

(a) Windows large-file upload writes a truncated prefix under the final name

uploadWindowsFileInChunks reads the source in 32KB chunks and writes each straight to the destination path:

await writeBufferViaSystemSsh(target, file.remotePath, buffer.subarray(0, bytesRead), {
  ...options,
  append: offset > 0
})

No staging, no rename. And this PR newly arms a 60s WINDOWS_STDIN_WRITE_TIMEOUT_MS on every one of those writes — so a wedged or slow host now fails mid-file where it previously hung. That converts a hang into a partially-written artifact sitting at the real path (.orca-remote/relay/relay.js and friends) with nothing marking it incomplete. Under exclusive, the retry's CreateNew then fails on its own leftovers.

A truncated relay.js is a broken relay that looks installed.

#17934 is exactly the fix: stage to ${remotePath}.orca-partial and publish via [System.IO.File]::Move (WINDOWS_STAGED_WRITE_SUFFIX, publishWindowsStagedWrite).

(b) This PR does not fix the single-file Windows upload it is titled for

uploadFileViaSystemSsh is untouched here. On Windows it still pipes the whole file into one PowerShell stdin via makeWindowsWriteFileCommand with waitForChannelClose(channel, ...) and no timeout (system-ssh-file-binary-transfer.ts:97-152). That function is the user file-import path (SshConnection.openFileUploadSession, ssh-connection.ts:582).

So this ships as "stop the Windows upload hanging" while leaving the user-facing upload hanging. #17934 routes it through writeWindowsBytesViaSystemSsh.

(c) A TOCTOU check is silently weakened

uploadWindowsFileInChunks replaced readLocalUploadFile's isFile && size && ino && dev verification with isFile && size only. #17934 restores the full check by delegating back to uploadFileViaSystemSsh. Minor on its own, but it is a security check removed and re-added across the stack — worth noting so a partial landing does not leave it removed.

(d) fs.listFiles Rule 3 break for old clients

Tracked separately in the #17954 thread.

Recommendation

Add to the merge-ordering constraints: #17870 must land with #17934, not before it.

That now makes four load-bearing pairs in this sweep:

Of these, this one is the only data-corruption risk rather than a process-lifecycle one.

…ncating

Three failures with one shape: a payload past a fixed capacity was met with
silence, with a wait that never ends, or with a prefix presented as a whole.

**The workspace snapshot was silently dropped.** `workspace.changed` carries the
tab/session list, and a snapshot past the producer frame capacity (12288 B on a
Node <=21 remote) was dropped with only a relay stderr line, so the client kept a
stale list forever. The relay now publishes per client and, for a client whose
sink refused the frame, sends a compact `workspace.stale` marker on the control
lane; the client re-reads through `workspace.get`, whose lane is budgeted in
megabytes rather than in one producer frame. A new JSON-RPC notification rather
than a new field on `workspace.changed`: `normalizeSnapshot(undefined, ns)` yields
revision 0 and an empty session, so a Rule-1 field would make an old client
replace its tab list with nothing — worse than the drop. An old client ignores the
unknown method and is exactly where it is today. The marker retention/retry
machinery is extracted from the `fs.changed` overflow path and shared by both.

**The Windows upload hung, and the fix for it could truncate.** `#16432` was
attributed to `[Console]::In.ReadToEnd()` materializing the base64 bundle. That is
not what the reporter measured: he also measured
`new IO.StreamReader([Console]::OpenStandardInput())` — an incremental reader —
hanging at 1 MB. The limit is in the stdin the host hands PowerShell over a
non-pty ssh exec, not in the string the script builds.

- `uploadFileViaSystemSsh` — the user file-import path — was piping a whole file
  into one Windows stdin, unchunked and untimed. That is the path large files
  take; it now chunks into 32 KB writes and bounds each wait.
- The Windows directory upload reuses that single-file path rather than repeating
  a weaker copy of chunk-read + write-buffer; the `ino`/`dev` TOCTOU verification
  comes with it.
- A Windows write needing more than one exec lands on a `.orca-partial` staging
  path and is published by rename, so a failed chunk cannot leave a truncated
  artifact under the real name. `exclusive` is enforced once at the rename, not on
  the first chunk, where a retry met its own leftovers.
- The mkdir batch reads stdin through the stream reader the reporter measured
  surviving 50 KB, not `[Console]::In`, which he measured wedging at that size.
- `waitForChannelClose` takes an optional bound. A wedged PowerShell stays alive
  at idle CPU and never closes, so without one the promise is simply never
  settled and the caller waits forever with no error to show.

**Quick Open showed a prefix as the whole workspace.** The mechanism "a full page
means there is more" only works if the caller named the cap, and the failing UI
named none — it hardcoded `truncated: false`. Quick Open now names
`QUICK_OPEN_LISTING_MAX_RESULTS` on both the Electron IPC hop and the runtime-RPC
hop (the field #17954 added to `files.listAll`), and reads a full page as
truncation. The local hop honours the cap too, which it previously ignored.

Rebase note on `fs.listFiles`: an earlier revision of this work also clamped the
host unconditionally, and #17934 escalated an uncapped request to an explicit
error. #17954 has since landed and made an oversized reply streamable, which
removes the premise — the host no longer has to choose between a prefix and a
refusal, so it returns the whole listing when no limit is named and only clamps a
limit it was given. Keeping either would have regressed #17954 and hard-failed
three in-tree callers that deliberately pass no options
(`runtime-file-commands-search-runtime-files.ts:81`,
`filesystem-read-handlers.ts:125`, `runtime-file-commands-constructor.ts:41`).
@nwparker
nwparker force-pushed the fix/relay-payload-limits branch from 48a097f to 6c93e03 Compare September 2, 2026 22:28

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

✅ No new issues found.

Reviewed changes

  • Removed the relay-side fs.listFiles default cap — the host no longer bounds a caller that omitted maxResults; it only clamps a named limit via resolveQuickOpenResultLimit, leaning on the merged #17954 reply streaming. This resolves the prior markdown-document truncation concern.
  • Staged multi-chunk Windows writes — writeWindowsBytesViaSystemSsh now lands any write exceeding one stdin chunk on a .orca-partial path and publishes it with File::Move, so a mid-file failure no longer leaves a truncated artifact under the real name; exclusive is enforced once at the rename instead of smeared across the first chunk.
  • Chunked, bounded single-file Windows uploads — uploadFileViaSystemSsh reuses the chunked writer with the 60s waitForChannelClose timeout on every write, and directory uploads delegate per file instead of base64-ing the whole bundle.
  • Mkdir batch reader swap — the directory batch reads stdin via StreamReader on [Console]::OpenStandardInput() (the construct the reporter measured surviving 50KB) instead of [Console]::In.ReadToEnd().
  • Optional maxResults forwarding — listRuntimeFiles forwards maxResults only when a caller names one, so unnamed callers keep the whole listing rather than an unannounced prefix.

The prior [!IMPORTANT] (unconditional cap truncating markdown listing) is correctly addressed: with #17954 merged, an unbounded listing is streamable, and callers that want a bound state it explicitly.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@nwparker nwparker changed the title fix(relay): stop dropping oversized payloads silently, and stop the Windows upload hanging fix(relay): signal capacity loss instead of dropping, hanging, or truncating Sep 2, 2026

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

🧹 Nitpick comments (1)
src/main/ssh/system-ssh-file-binary-transfer.ts (1)

257-261: 🚀 Performance & Scalability | 🔵 Trivial | 🏗️ Heavy lift

Confirm that per-chunk execs stay multiplexed, or uploads will regress badly.

Each 32 KB chunk now spawns its own ssh exec. A 600 KB artifact becomes about 19 sequential connections, and a 1.9 MB bundle about 60. With ControlMaster multiplexing active, each exec is cheap. getSystemSshBuildArgsFromOperationOptions still forwards disableControlMaster and suppressOrcaControlMaster, and expectOrcaControlMasterArgs in src/main/ssh/ssh-system-fallback.test.ts shows that a Windows local client suppresses the Orca ControlMaster args entirely. On those paths every chunk pays a full handshake and authentication round trip.

Measure the upload duration on a target without multiplexing. If it regresses, consider one exec per file that reads length-prefixed frames in a PowerShell loop, so the stdin bound is preserved without one connection per chunk.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: ef0b0292-91f0-4f11-a4e9-d54a44cb7fed

📥 Commits

Reviewing files that changed from the base of the PR and between 074a236 and 6c93e03.

📒 Files selected for processing (20)
  • src/main/ipc/filesystem/filesystem-search-handlers.ts
  • src/main/ipc/remote-workspace-stale-resync.test.ts
  • src/main/ipc/remote-workspace-stale-resync.ts
  • src/main/ipc/remote-workspace.ts
  • src/main/ssh/ssh-system-fallback.test.ts
  • src/main/ssh/system-ssh-file-binary-transfer.ts
  • src/main/ssh/system-ssh-file-transfer.ts
  • src/main/ssh/system-ssh-operation-lifecycle.ts
  • src/main/ssh/system-ssh-windows-upload.test.ts
  • src/relay/fs-handler-list-files-result-limit.test.ts
  • src/relay/fs-handler.ts
  • src/relay/relay-client-resync-marker.ts
  • src/relay/relay-watcher-event-emitter.ts
  • src/relay/workspace-session-handler.ts
  • src/relay/workspace-snapshot-publication.test.ts
  • src/relay/workspace-snapshot-publication.ts
  • src/renderer/src/components/quick-open-file-list.react.test.tsx
  • src/renderer/src/components/quick-open-file-list.ts
  • src/renderer/src/runtime/runtime-file-search-client.ts
  • src/shared/remote-workspace-types.ts

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

Comment on lines +158 to +160
void resyncStaleRemoteWorkspace(target, (snapshot) =>
sendRemoteWorkspaceChanged(targetId, snapshot, undefined)
)

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

Pass an onError handler to resyncStaleRemoteWorkspace.

resyncStaleRemoteWorkspace declares onError: (error: unknown) => void = () => {} and catches every error from the workspace.get read. This call site omits the argument, so the default no-op applies. If the re-read fails, the main process emits no renderer event and writes no log. The workspace stays stale with no diagnostic, which is the silent-desync outcome this change replaces.

Log the failure so an operator can distinguish a failed resync from a suppressed echo.

🪵 Proposed fix to report resync failures
     void resyncStaleRemoteWorkspace(target, (snapshot) =>
       sendRemoteWorkspaceChanged(targetId, snapshot, undefined)
-    )
+    , (error) => {
+      console.error(`[remote-workspace] stale resync failed for ${targetId}:`, error)
+    })

Use the project logger if this module already has one.

📝 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
void resyncStaleRemoteWorkspace(target, (snapshot) =>
sendRemoteWorkspaceChanged(targetId, snapshot, undefined)
)
void resyncStaleRemoteWorkspace(target, (snapshot) =>
sendRemoteWorkspaceChanged(targetId, snapshot, undefined)
, (error) => {
console.error(`[remote-workspace] stale resync failed for ${targetId}:`, error)
})

Comment on lines +322 to +323
...(exclusive ? [] : ['[System.IO.File]::Delete($path)']),
'[System.IO.File]::Move($staging, $path)'

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

🔎 Supported by static analysis

🌐 Web query:

Windows PowerShell 5.1 .NET Framework System.IO.File Move overwrite overload availability and File.Replace atomic replacement

💡 Result:

In Windows PowerShell 5.1 (which runs on.NET Framework), the System.IO.File.Move method does not support an overwrite overload [1]. The overload accepting a boolean overwrite parameter was introduced later in.NET Core 3.0 and is not available in.NET Framework 4.8 or earlier versions [1][2][3]. Consequently, attempting to move a file to an existing destination path in PowerShell 5.1 will result in an IOException stating that the file already exists [2]. To achieve a file move with overwrite capability in PowerShell 5.1, you can use the Move-Item cmdlet with the -Force parameter [4]. Alternatively, if working directly with.NET objects, a common workaround is to delete the destination file before moving, though this is not atomic [1][5]. Regarding File.Replace, it is a separate method that replaces the contents of a specified file with another, optionally creating a backup [6]. While it is often used as a way to perform a more robust replacement on Windows because it internally calls the native Win32 ReplaceFile API, its atomicity is not formally guaranteed or documented as a strict contractual behavior [7][8]. Although it may behave atomically in many NTFS scenarios—essentially swapping file IDs—developers should not rely on it as a guaranteed transactional operation for critical data integrity, especially across different file systems or in the presence of complex metadata/ACL configurations [7][8]. For strict transactional requirements, Microsoft has historically suggested using TxF (Transactional NTFS), though that technology is deprecated and generally discouraged [7][8].

Citations:


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- repository convention scopes ---'
find /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4 -maxdepth 2 -type f -name '*.md' -print | sort
printf '%s\n' '--- target file outline and changed region ---'
ast-grep outline src/main/ssh/system-ssh-file-binary-transfer.ts
sed -n '270,345p' src/main/ssh/system-ssh-file-binary-transfer.ts
printf '%s\n' '--- direct references to the transfer implementation and PowerShell target ---'
rg -n -F 'system-ssh-file-binary-transfer' src test tests 2>/dev/null || true
rg -n -F 'System.IO.File' src/main/ssh/system-ssh-file-binary-transfer.ts

Repository: stablyai/orca

Length of output: 7357


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- applicable repository conventions and learnings ---'
cat /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/conventions/repo-wide.md
cat /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/learnings/src-main-ssh.md
printf '%s\n' '--- transfer flow and callers ---'
sed -n '1,285p' src/main/ssh/system-ssh-file-binary-transfer.ts
sed -n '1,180p' src/main/ssh/system-ssh-windows-upload.test.ts
sed -n '1,100p' src/main/ssh/system-ssh-file-transfer.ts

Repository: stablyai/orca

Length of output: 22628


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- publish-related tests and command assertions ---'
sed -n '180,420p' src/main/ssh/system-ssh-windows-upload.test.ts
printf '%s\n' '--- exact working-tree change summary ---'
git diff --stat -- src/main/ssh/system-ssh-file-binary-transfer.ts
git diff -- src/main/ssh/system-ssh-file-binary-transfer.ts | sed -n '1,180p'

Repository: stablyai/orca

Length of output: 4638


Use a single-operation replacement for non-exclusive publishes.

When exclusive is false, the code deletes $path before moving $staging. A connection drop or remote process failure between these commands can leave the destination missing while $path.orca-partial remains. Select a replacement primitive supported by the target PowerShell/.NET runtime, including a safe path for an absent destination.

Comment on lines +197 to +198
const entryBytes = Buffer.byteLength(directory) + 4
if (batch.length > 0 && batchBytes + entryBytes > WINDOWS_STDIN_WRITE_CHUNK_BYTES) {

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

The batch size estimate undercounts escaped JSON, so the 32 KB bound can be exceeded.

entryBytes charges Buffer.byteLength(directory) + 4. The serialized form is longer than that. JSON.stringify escapes every backslash as \\, and Windows remote paths carry backslash separators when hostPlatform.pathSeparator is '\\'. A path of N backslash-heavy bytes serializes to close to 2N bytes but is budgeted at N+4.

The comment above createWindowsUploadDirectories states that a pathological tree cannot reach the stdin size that wedges PowerShell. With the current accounting it can: the payload can reach roughly twice the budget while batchBytes still reads as under 32768.

Measure the serialized payload instead of estimating it.

🐛 Proposed fix: budget against the actual JSON length
   for (const directory of directories) {
-    const entryBytes = Buffer.byteLength(directory) + 4
+    // Budget the serialized form: JSON escapes backslashes, which Windows paths are full of.
+    const entryBytes = Buffer.byteLength(JSON.stringify(directory)) + 1
     if (batch.length > 0 && batchBytes + entryBytes > WINDOWS_STDIN_WRITE_CHUNK_BYTES) {
       await flush()
     }
📝 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
const entryBytes = Buffer.byteLength(directory) + 4
if (batch.length > 0 && batchBytes + entryBytes > WINDOWS_STDIN_WRITE_CHUNK_BYTES) {
// Budget the serialized form: JSON escapes backslashes, which Windows paths are full of.
const entryBytes = Buffer.byteLength(JSON.stringify(directory)) + 1
if (batch.length > 0 && batchBytes + entryBytes > WINDOWS_STDIN_WRITE_CHUNK_BYTES) {
🧰 Tools
🪛 ast-grep (0.45.2)

[warning] Importing child_process exposes a command-execution surface; ensure any command/argument built from input is validated, and prefer execFile/spawn with an argument array over exec.
Context: import { spawn } from 'node:child_process'
Note: [CWE-78] Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection').

(detect-child-process-typescript)

Comment on lines +155 to +157
expect(
waitForChannelCloseSpy.mock.calls.every((call) => call[2] === WINDOWS_STDIN_WRITE_TIMEOUT_MS)
).toBe(true)

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

This assertion passes when no wait was recorded at all.

Array.prototype.every returns true for an empty array. If the production code stops calling waitForChannelClose, or the partial mock at lines 28-32 stops intercepting it, waitForChannelCloseSpy.mock.calls is empty and this assertion still passes. The test then reports success for the exact regression it exists to catch.

Assert the call count as well.

💚 Proposed fix: require the spy to have observed the waits
     // A wedged PowerShell never closes on its own, so no wait on this path may be unbounded.
+    expect(waitForChannelCloseSpy.mock.calls.length).toBe(writes.length)
     expect(
       waitForChannelCloseSpy.mock.calls.every((call) => call[2] === WINDOWS_STDIN_WRITE_TIMEOUT_MS)
     ).toBe(true)

// false unconditionally is what made the truncation silent — the host bounds the scan to
// the cap it is given, so a full page means there are more paths behind it.
files,
truncated: files.length >= QUICK_OPEN_LISTING_MAX_RESULTS

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

Carry an explicit truncation signal instead of inferring it from page length.

An exact-cap result is ambiguous. The production code currently reports complete listings as truncated, and the test preserves that behavior.

  • src/renderer/src/components/quick-open-file-list.ts#L272-L272: consume an explicit hasMore or truncation value from the listing layer, or use a distinct over-fetch sentinel.
  • src/renderer/src/components/quick-open-file-list.react.test.tsx#L220-L221: test both an exact-cap complete listing and a response explicitly marked as truncated.
📍 Affects 2 files
  • src/renderer/src/components/quick-open-file-list.ts#L272-L272 (this comment)
  • src/renderer/src/components/quick-open-file-list.react.test.tsx#L220-L221

@nwparker
nwparker merged commit 510305e into main Sep 2, 2026
32 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…ncating (stablyai#17870)

Three failures with one shape: a payload past a fixed capacity was met with
silence, with a wait that never ends, or with a prefix presented as a whole.

**The workspace snapshot was silently dropped.** `workspace.changed` carries the
tab/session list, and a snapshot past the producer frame capacity (12288 B on a
Node <=21 remote) was dropped with only a relay stderr line, so the client kept a
stale list forever. The relay now publishes per client and, for a client whose
sink refused the frame, sends a compact `workspace.stale` marker on the control
lane; the client re-reads through `workspace.get`, whose lane is budgeted in
megabytes rather than in one producer frame. A new JSON-RPC notification rather
than a new field on `workspace.changed`: `normalizeSnapshot(undefined, ns)` yields
revision 0 and an empty session, so a Rule-1 field would make an old client
replace its tab list with nothing — worse than the drop. An old client ignores the
unknown method and is exactly where it is today. The marker retention/retry
machinery is extracted from the `fs.changed` overflow path and shared by both.

**The Windows upload hung, and the fix for it could truncate.** `stablyai#16432` was
attributed to `[Console]::In.ReadToEnd()` materializing the base64 bundle. That is
not what the reporter measured: he also measured
`new IO.StreamReader([Console]::OpenStandardInput())` — an incremental reader —
hanging at 1 MB. The limit is in the stdin the host hands PowerShell over a
non-pty ssh exec, not in the string the script builds.

- `uploadFileViaSystemSsh` — the user file-import path — was piping a whole file
  into one Windows stdin, unchunked and untimed. That is the path large files
  take; it now chunks into 32 KB writes and bounds each wait.
- The Windows directory upload reuses that single-file path rather than repeating
  a weaker copy of chunk-read + write-buffer; the `ino`/`dev` TOCTOU verification
  comes with it.
- A Windows write needing more than one exec lands on a `.orca-partial` staging
  path and is published by rename, so a failed chunk cannot leave a truncated
  artifact under the real name. `exclusive` is enforced once at the rename, not on
  the first chunk, where a retry met its own leftovers.
- The mkdir batch reads stdin through the stream reader the reporter measured
  surviving 50 KB, not `[Console]::In`, which he measured wedging at that size.
- `waitForChannelClose` takes an optional bound. A wedged PowerShell stays alive
  at idle CPU and never closes, so without one the promise is simply never
  settled and the caller waits forever with no error to show.

**Quick Open showed a prefix as the whole workspace.** The mechanism "a full page
means there is more" only works if the caller named the cap, and the failing UI
named none — it hardcoded `truncated: false`. Quick Open now names
`QUICK_OPEN_LISTING_MAX_RESULTS` on both the Electron IPC hop and the runtime-RPC
hop (the field stablyai#17954 added to `files.listAll`), and reads a full page as
truncation. The local hop honours the cap too, which it previously ignored.

Rebase note on `fs.listFiles`: an earlier revision of this work also clamped the
host unconditionally, and stablyai#17934 escalated an uncapped request to an explicit
error. stablyai#17954 has since landed and made an oversized reply streamable, which
removes the premise — the host no longer has to choose between a prefix and a
refusal, so it returns the whole listing when no limit is named and only clamps a
limit it was given. Keeping either would have regressed stablyai#17954 and hard-failed
three in-tree callers that deliberately pass no options
(`runtime-file-commands-search-runtime-files.ts:81`,
`filesystem-read-handlers.ts:125`, `runtime-file-commands-constructor.ts:41`).
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]: SSH relay silently drops oversized workspace.changed events, leaving the client's session list stale

1 participant