Skip to content

fix(relay): stream an oversized fs.listFiles reply instead of refusing it - #17954

Merged
nwparker merged 1 commit into
mainfrom
fix/quick-open-byte-budget
Sep 2, 2026
Merged

nwparker merged 1 commit into
mainfrom
fix/quick-open-byte-budget

Conversation

@nwparker

@nwparker nwparker commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​348 $\color{#cf222e}{\Huge{\mathbf{−}}}$​23 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​325
Prod 7 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​93 $\color{#cf222e}{\Huge{\mathbf{−}}}$​26 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​67

Closes #12547. Standalone on main — previously stacked on #17934 / #17870; it is not any more, and neither is needed. See "Unstacked" below.

ELI5

Opening Orca's own checkout over SSH cannot list its files in one response frame. The relay demotes any reply over 1 MiB to a lane whose admission depends on unrelated producer load, so a listing that big is delivered or refused depending on what else the host is doing.

Picking a ceiling to refuse at — a row count or a byte budget — does not fix that. It moves where the failure shows up, and it refuses listings that would have been delivered. This routes fs.listFiles through __streamResponse, the opt-in response streaming that already carries large git diffs onto the bulk lane, so the size of a listing stops being a correctness question.

The measurement

Against the real limitQuickOpenFilesBySerializedBytes and this repository's own tracked file list — 22,617 paths, 58.2 characters average:

serialized fits a 1,044,480-byte budget?
20,001-row page (current client) 1,223,415 B no — 17,168 / 20,001
uncapped (client that sends no maxResults) 1,346,611 B no — 17,168 / 22,617

Break-even is roughly 49 characters of average path. Any packages/<name>/src/... monorepo is over the line. After this change no budget is consulted: the 1.22 MB page becomes 10 chunks of 128 KB on the bulk lane, and the sentinel that replaces it in the response frame is ~150 bytes.

Wire compatibility

tests/e2e/cross-version-wire/ does not cover file RPCs, so there is no CI record for this. The reasoning, by hand:

  • Old client + new host. Sends neither __streamResponse nor maxResults. maybeStreamRpcResponse returns the plain array and it goes out on the legacy-response lane exactly as today. No change.
  • New client + old host. Sends __streamResponse: true; an old relay reads only rootPath / maxResults / searchQuery / excludePaths and ignores the extra key, answering plainly. isGitResponseStreamMarker is false, so the reader returns the plain value. Rule 1.
  • No Rule 2 exposure. __streamResponse is self-negotiating in both directions — there is no new method, no new opcode, and nothing to advertise in a handshake. That property is the reason this is the right mechanism rather than a new one.
  • files.listAll + maxResults. New optional zod field. An old host .strip()s it and keeps its existing 20,001 default; a new host sees undefined from an old client and falls back to the same default. Additive both ways. Rule 1.

One registry per relay

FsHandler and GitHandler now share a single GitResponseStreamRegistry, constructed in relay-runtime-services.ts. This is a constraint, not a preference, and the header of git-response-stream.ts says so for the next handler that wants streaming:

  • a client keys reassembly on streamId alone, so two registries would hand out the same id and cross-feed each other's chunks;
  • only the handler that registers git.responseAck can credit the ack window a pump parks on, so the other's streams would stall at STREAM_ACK_WINDOW_CHUNKS forever.

FsHandler takes it as an optional argument and, without one, answers plainly rather than emitting a stream nothing can credit.

Testing

  • tests/e2e/ssh-docker-quick-open-large-listing.spec.ts (new) seeds a Docker SSH container from this repository's own git ls-files -z and lists it over the real relay. Both directions pass: the 20,001-row page comes back whole, and a request naming no maxResults returns all 22,618 listable paths. The expectation is derived from the real shouldIncludeQuickOpenPath rather than a hand-written list — Quick Open prunes .husky/ on purpose, and a copied list would go stale and read as a transport bug.
  • src/relay/fs-list-files-large-response.integration.test.ts (new) runs the real RelayDispatcher + FsHandler + GitHandler + SshChannelMultiplexer over an in-memory pipe. Its precondition is measured from the payload, not asserted between two constants, and the streamed and plain cases assert opposite frame-size outcomes on the same payload. Verified to fail when the streaming call is reverted.
  • pnpm tc clean. src/relay 1584 passed. src/shared 6549 passed. check:code-quality:changed 0 findings.
  • src/main/runtime/automation-change-publication.test.ts times out at 30s on this machine — reproduced 3/3 on unmodified main, pre-existing and unrelated.

Unstacked

This was stacked on #17934, which is stacked on #17870; both are held on their own findings. The dependency was not real. Against main, the change is "share the registry, and return maybeStreamRpcResponse(...) instead of returning the scan directly". The row-cap raise and the uncapped-listing throw those PRs introduce are deliberately left behind — they belong to those PRs and are part of what is being held. Nothing here asserts on them.

Note that the byte budget an earlier revision of this PR proposed is gone entirely, along with src/relay/fs-list-files-response-budget.ts and its tautological expect(BUDGET).toBeLessThan(DISPATCHER_CONTROL_QUEUE_MAX_BYTES) self-comparison. Deliverability is the transport's problem, and since #17968 an over-budget response already fails its own request rather than closing the client.

@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 critical issues — one test is weaker than it looks.

Reviewed changes

  • fs.listFiles uncapped scans now run to QUICK_OPEN_LISTING_UNCAPPED_SCAN_LIMIT (the 100k retention limit) instead of the 20,001-row page cap, letting a short-path workspace exceed the old row ceiling.
  • New src/relay/fs-list-files-response-budget.ts derives a byte budget (DISPATCHER_CONTROL_QUEUE_MAX_BYTES - 4096) and a single listFilesUndeliverableReason covering both the byte-fit check and the uncapped row-cap check.
  • Tests rewritten around the byte budget, plus a new describe block for byte-bounded ceilings.

The core accounting is sound: limitQuickOpenFilesBySerializedBytes measures the exact serialized array bytes, and the 4096-byte envelope reserve comfortably covers the JSON-RPC wrapper plus the 13-byte frame header, so a boundary response stays on the control lane.

ℹ️ Control-lane saturation remains, and this PR widens it slightly

A response at the new byte budget (~1 MiB) consumes essentially the whole control lane, and admitControl treats overflow as fatal, closing the client. The PR body already documents this and defers it to a maintainer call, so this is a confirm-and-track rather than a blocker. Note the exposure is marginally amplified here: the previous worst case was ~900 KB (20,001 short paths), and this PR allows up to ~1 MiB, so there is less headroom for a concurrent control frame than before. Worth resolving before this path is considered settled.

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

@nwparker

nwparker commented Sep 1, 2026

Copy link
Copy Markdown
Contributor Author

Undisclosed behavior change, found in wire-compat audit — compliant, but it belongs in the description

The PR body describes the relaxing direction only. There is a tightening direction too, and it changes what an old client sees on an existing path.

Relaxed (described): an uncapped request previously threw at 20,001 rows; it now scans to QUICK_OPEN_LISTING_UNCAPPED_SCAN_LIMIT (100,000) and refuses on bytes. An old client on a 50k-file workspace goes from an error to a full listing.

Tightened (not described): a capped request can now throw where it previously returned rows. In fs-list-files-response-budget.ts, listFilesUndeliverableReason runs the byte check unconditionally, before the requestedMaxResults === undefined branch:

const deliverable = limitQuickOpenFilesBySerializedBytes(files, QUICK_OPEN_LISTING_MAX_RESPONSE_BYTES)
if (deliverable.length < files.length) {
  return `This workspace's ${files.length} file paths do not fit in one ...`
}
if (requestedMaxResults === undefined && files.length >= scanLimit) { ... }

The PR's own test pins it — "refuses a capped request whose own page does not fit, instead of blowing the lane", calling listFiles({ rootPath, maxResults: 4_000 }) and expecting a throw. So an old client asking for maxResults: 4000 over long paths previously got a reply and now gets an error.

This is still the right behaviour. That old reply would have exceeded DISPATCHER_CONTROL_QUEUE_MAX_BYTES, been demoted to the legacy-response lane, and been refused there as an opaque ResponseOverCapacity firing on unrelated concurrent load rather than on the request. Trading a load-dependent opaque failure for a deterministic explanatory one is correct, and both outcomes are errors an old client already handles.

But it is an un-capability-gated change to what the host publishes on an existing path, and per docs/reference/remote-wire-compatibility.md Rule 3 that reaches old clients with no wire change. It deserves a line in the PR body so the next reader does not have to derive it from a test name.

No Rule 1 or Rule 2 exposure: fs.listFiles still returns a bare string[], no new field, no new opcode. src/shared/terminal-stream-protocol.ts is untouched.

@nwparker

nwparker commented Sep 1, 2026

Copy link
Copy Markdown
Contributor Author

Adversarial review says this is a symptom patch, and I think it is right

Two findings that outrank the disclosure note above.

1. The byte budget contradicts a neighbouring invariant that has a test behind it

src/shared/file-range-read.ts:1-24 states the rule in the repo's own words: the control lane is shared, so a full-cap response must leave room for a second one. It is pinned — fs-handler-file-range.test.ts:112-124 asserts frameBytes * 2 <= DISPATCHER_CONTROL_QUEUE_MAX_BYTES. That is why MAX_FILE_RANGE_READ_BYTES is 256 KiB, not 1 MiB.

This PR sets QUICK_OPEN_LISTING_MAX_RESPONSE_BYTES = 1 MiB − 4096 — a single frame at 99.6% of the shared lane. Its doc comment calls that "the boundary past which the reply stops being deliverable"; by the neighbouring file's rule it is the boundary past which it is never reliably deliverable. The two constants disagree and only the smaller one has a test.

Concrete failure: a 250k-file monorepo over SSH, user hits Quick Open (~700 KB) while a file preview pages fs.readFileRange (~350 KB on the same lane) and a pane reattaches. canAdmitControl(700 KB) fails → the user sees "Relay response exceeded the bounded transport capacity." Retry a second later on an idle lane: works. Nothing about the request changed.

Three outcomes are indistinguishable to the user: reply genuinely too big; reply fine but lane busy; lane so full the ~150-byte substitute is also rejected, onSettled never fires, and the request hangs to the 30s timeout. And RelayErrorCode.ResponseOverCapacity (-33008) has no client-side handler — a grep across src/main/ssh finds only the relay-protocol.ts re-export — so it rejects with a generic message, no retry and no narrowing hint.

2. The escape hatch already exists and fs.listFiles ignores it

src/relay/git-handler.ts:129-143, maybeStreamResponse: the client opts in with params.__streamResponse === true; over GIT_RESPONSE_STREAM_THRESHOLD (256 KiB) the result becomes a GitResponseStreamMarker sentinel and the payload ships as chunks on the bulk lane, ack-paced with a 4-chunk credit window. Per-request flow control, zero control-lane bytes.

fs.listFiles is the identical shape — an in-memory serialized string — and is the only large response still framed whole onto the control lane. pty gets a credit ledger and git gets an ack window because both are unbounded-size producers; control responses got a shared bucket on the assumption they are small. fs.listFiles broke that assumption, and this PR widens the bucket's tolerance instead of moving the payload.

Where that leaves this PR

The byte budget is still strictly better than the row cap it replaces — a row count bounds nothing about a frame — and #17968 (stacked above) fixes the genuinely severe half, where overflow closed the whole session. Neither should be discarded.

But the honest root-cause fix is to route fs.listFiles through the existing stream path rather than to pick a larger control-lane number. Two options for the maintainer:

  • Minimal and consistent now: drop QUICK_OPEN_LISTING_MAX_RESPONSE_BYTES to respect the two-deep rule the sibling constant already encodes and tests. This is the ~11k-file cap decision, and it makes the two constants agree.
  • Correct: adopt maybeStreamResponse for fs.listFiles, capability-gated the same way git's is, after which the cap question largely disappears.

I would not hold #17968 for either. This PR is the one that should carry the decision.

@nwparker

nwparker commented Sep 1, 2026

Copy link
Copy Markdown
Contributor Author

Merge blocker: this breaks current clients, not just old ones

I checked the arithmetic and it holds. A new client sends maxResults: 20_001 against a ceiling of 1 MiB − 4096 = 1,044,480 bytes:

1,044,480 / 20,001 ≈ 52.2 bytes per path
   minus JSON quotes + comma  →  ~49 characters of path

So any workspace whose average relative path exceeds ~49 characters throws, regardless of client version:

avg path length serialized total result
40 chars 860,043 B ok
47 chars 1,000,050 B ok
55 chars 1,160,058 B throws
70 chars 1,460,073 B throws

49 characters is not a generous budget. packages/frontend/src/components/settings/SettingsPanel.tsx is 58. Any monorepo with a packages/<name>/src/... convention is over the line, and deep test-fixture trees are far over it. This is not an edge case — it is a large fraction of real repositories, and Quick Open would hard-fail on them with "This workspace's N file paths do not fit in one response."

Old clients are worse still: they send no maxResults, so they take the throw at fs-list-files-response-budget.ts:52-56 telling the user to upgrade — an ungated Rule 3 change per docs/reference/remote-wire-compatibility.md.

The host cannot byte-clamp instead, and that is the crux: the reply is a bare string[] with no truncation field, so returning a shorter array would be a silent prefix — the exact defect #12547 is about. The missing signal is what forces the throw.

The fix does not need a new opcode

src/relay/git-handler.ts:129-143 already solves this shape. The client opts in with params.__streamResponse === true; above GIT_RESPONSE_STREAM_THRESHOLD (256 KiB) the result becomes a sentinel marker and the payload ships ack-paced on the bulk lane with a 4-chunk credit window (git-response-stream.ts:113-138). Its own header describes the payload as "an in-memory serialized string rather than a file handle" — which is exactly fs.listFiles. __streamResponse is currently read only in git-handler.ts; there is no technical reason fs.listFiles cannot use it.

The opt-in param is itself the negotiation, in both directions. An old client never sends it and gets today's behaviour; a new client sends it and gets a stream. No opcode, no capability table, no Rule 2 exposure.

(For completeness: fs-stream-registry.ts is not the right hatch — it is fd-backed and takes a FileHandle. And fs-list-files-scan-coordinator.ts bounds scan concurrency, not delivery.)

Recommendation

Hold this PR. #17968 (stacked above) is independently valuable and fixes the severe half — an oversized response no longer closes the whole session — and should not be held for this.

Two viable paths here, in order of preference:

  1. Route fs.listFiles through maybeStreamResponse. Removes the cap question rather than tuning it, uses machinery that already exists and is already proven on the git path, and is the root-cause fix.
  2. If that is too large for now: drop the budget to respect the two-deep rule its sibling constant already encodes and tests (fs-handler-file-range.test.ts:112-124 asserts frameBytes * 2 <= DISPATCHER_CONTROL_QUEUE_MAX_BYTES, which is why MAX_FILE_RANGE_READ_BYTES is 256 KiB). That makes the two constants agree — but it tightens the cap further, so it must be paired with lowering the default maxResults the client sends, or the throw gets more common rather than less.

Option 2 alone makes this PR worse for the monorepo case. Option 1 is the one worth doing.

@greptile-apps

greptile-apps Bot commented Sep 2, 2026

Copy link
Copy Markdown

Too many files changed for review (1051 files, 100 file limit).

@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

  • Replaced the byte-budget refusal with opt-in response streaming: fs.listFiles now reuses the existing __streamResponse git mechanism, chunking any reply over GIT_RESPONSE_STREAM_THRESHOLD onto the bulk lane instead of refusing it.
  • Extracted maybeStreamRpcResponse into git-response-stream.ts and shared a single GitResponseStreamRegistry between FsHandler and GitHandler, so stream ids stay unique and git.responseAck credits fs.listFiles streams through the one route.
  • Wired the client SshFilesystemProvider.listFiles through requestGitStreamable, so a current client always opts into streaming while an old relay/old client falls back to the plain array in both directions.
  • Declared an optional maxResults on the files.listAll runtime RPC and forwarded it from the renderer (additive wire rule 1).
  • Added a real-dispatcher integration test and a Docker-SSH e2e spec asserting an over-budget listing arrives intact in both wire directions.

The prior inline finding (the tautological lane-budget test) is resolved: the byte-budget module is gone, and fs-list-files-large-response.integration.test.ts now serializes a real over-budget payload and asserts Math.max(...writtenFrames) < DISPATCHER_CONTROL_QUEUE_MAX_BYTES. The earlier control-lane-saturation note is also substantially resolved for current clients, which stream above 256 KiB rather than emitting a ~1 MiB control-lane frame.

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

@nwparker
nwparker force-pushed the fix/quick-open-byte-budget branch from 402f206 to 5afeba1 Compare September 2, 2026 09:45
@nwparker
nwparker changed the base branch from fix/windows-upload-correction to main September 2, 2026 09:45
@nwparker nwparker changed the title fix(relay): bound fs.listFiles by response bytes, not by a row count fix(relay): stream an oversized fs.listFiles reply instead of refusing it Sep 2, 2026
@coderabbitai

coderabbitai Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 3b6f9a7a-6c68-42c5-b234-44f8e8abf40b

📥 Commits

Reviewing files that changed from the base of the PR and between 5afeba1 and 7a9950f.

📒 Files selected for processing (1)
  • config/scripts/run-ssh-docker-e2e.mjs

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


📝 Walkthrough

Walkthrough

The change adds shared relay response streaming for large RPC payloads. fs.listFiles opts into streamable responses and preserves plain-array fallback behavior for older relays and small results. A shared stream registry is injected into filesystem and Git handlers. The files.listAll RPC method accepts and forwards optional maxResults values. Integration and Docker SSH tests cover oversized listings, legacy clients, small responses, and paginated results.

Merge Risk: 🔵 Low · up to 7a995

This change streams oversized file listings while preserving existing plain responses for clients and relays that do not opt in. The PR is mergeable with owner awareness that the acceptance test should directly verify the legacy plain-response path.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 37.50% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 8 functions across 12 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the primary change: streaming oversized fs.listFiles replies instead of refusing them.
Description check ✅ Passed The description provides a detailed problem statement, implementation summary, compatibility analysis, linked issue, and testing evidence. It omits several template headings and checklist confirmation…
Linked Issues check ✅ Passed The changes satisfy issue #12547 by streaming oversized remote file listings over the bulk lane, preserving plain-response fallback and adding integration and end-to-end coverage.
Out of Scope Changes check ✅ Passed The production changes, compatibility handling, registry sharing, and tests directly support the oversized fs.listFiles response objective in issue #12547. No unrelated code changes are evident.
Full details: Description check

Explanation

The description provides a detailed problem statement, implementation summary, compatibility analysis, linked issue, and testing evidence. It omits several template headings and checklist confirmations, but the core required information is complete.

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

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

Run ID: f9b3037b-f2a8-465e-84a2-077e0a950744

📥 Commits

Reviewing files that changed from the base of the PR and between 8197268 and 5afeba1.

📒 Files selected for processing (11)
  • src/main/providers/ssh-filesystem-provider.test.ts
  • src/main/providers/ssh-filesystem-provider.ts
  • src/main/runtime/rpc/methods/files-list-all-page-size.test.ts
  • src/main/runtime/rpc/methods/files.ts
  • src/relay/fs-handler.ts
  • src/relay/fs-list-files-large-response.integration.test.ts
  • src/relay/git-handler.ts
  • src/relay/git-response-stream.ts
  • src/relay/relay-runtime-services.ts
  • tests/e2e/helpers/docker-ssh-relay-target.ts
  • tests/e2e/ssh-docker-quick-open-large-listing.spec.ts

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

const FileListAll = WorktreeSelector.extend({
excludePaths: z.array(z.string()).optional()
excludePaths: z.array(z.string()).optional(),
maxResults: z.number().int().positive().optional()

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

🧩 Analysis chain

🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

rg -n -C 12 '\blistRuntimeFiles\b|\bmaxResults\b' src/main --glob '*.ts'

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

printf '%s\n' '--- repository guidance ---'
find /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4 -maxdepth 2 -type f -name '*.md' -print \
  | sort \
  | while IFS= read -r f; do
      printf '\n### %s\n' "$f"
      head -20 "$f"
    done

printf '%s\n' '--- listRuntimeFiles definitions and callers ---'
rg -n -l '\blistRuntimeFiles\b' src/main --glob '*.ts' \
  | while IFS= read -r f; do
      printf '\n### %s\n' "$f"
      rg -n -C 18 '\blistRuntimeFiles\b' "$f"
    done

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

rg -n -C 25 'listRuntimeFiles' src/main/runtime --glob '*.ts' --glob '!*.test.ts'

Repository: stablyai/orca

Length of output: 20295


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

sed -n '1,125p' src/main/runtime/runtime-file-commands-search-runtime-files.ts

printf '\n--- listing-limit definitions and provider listFiles implementations ---\n'
rg -n -C 8 'QUICK_OPEN_LISTING_MAX_RESULTS|listFiles\s*\(' src/main src/relay --glob '*.ts' \
  | head -240

Repository: stablyai/orca

Length of output: 26871


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

sed -n '215,255p' src/relay/fs-handler.ts
sed -n '295,325p' src/main/providers/ssh-filesystem-provider.ts
rg -n -C 12 'QUICK_OPEN_LISTING_MAX_RESULTS' src/shared src/main/ipc src/relay --glob '*.ts'
rg -n -C 18 'export async function listQuickOpenFiles|function listQuickOpenFiles' src/main/ipc --glob '*.ts'

Repository: stablyai/orca

Length of output: 20944


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

sed -n '32,175p' src/main/ipc/filesystem-list-files.ts
rg -n -C 10 'runListFilesScan|resolveQuickOpenResultLimit|maxResults' src/main/ipc/filesystem-list-files-git-fallback.ts src/shared/quick-open-readdir-walk.ts src/main/ipc/filesystem-list-files.ts --glob '*.ts'

Repository: stablyai/orca

Length of output: 32470


Denial of Service (CWE-400): Uncontrolled Resource Consumption

Reachability: External · Exploitability: Moderate

Clamp maxResults to the shared listing limit.

The SSH relay clamps maxResults to 20,001, but the local listQuickOpenFiles path uses the client value directly. A client can therefore request more than QUICK_OPEN_LISTING_MAX_RESULTS and increase local scan and memory costs. Apply resolveQuickOpenResultLimit before both paths.


// Why: a client that predates `maxResults` on this call sends none at all, and it cannot
// reassemble a streamed reply either — it has to be answered on the plain response path.
const oldClient = await listFiles()

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

Do not label this call as an older-client path.

Line 128 uses the same current-client listFiles closure as Line 123. SshFilesystemProvider.listFiles always uses requestGitStreamable, so this call still sends __streamResponse and reassembles an oversized response. Omitting maxResults does not test a legacy plain-response client.

Use a legacy request path without __streamResponse, or rename this assertion as an uncapped current-client case.

@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

  • Unstacked onto main — dropped the row-cap raise (QUICK_OPEN_LISTING_UNCAPPED_SCAN_LIMIT) and the uncapped-listing throw that belonged to the held #17934/#17870; fs.listFiles now keeps main's 20,001 maxResults behavior and only opts into response streaming.
  • Removed the renderer hop — runtime-file-search-client.ts no longer forwards maxResults; files.listAll still declares and forwards the additive optional field, but no current client sends it (forward-looking wiring, per the commit message).
  • Streaming mechanism unchanged — shared GitResponseStreamRegistry, maybeStreamRpcResponse, and both new tests (fs-list-files-large-response.integration.test.ts, files-list-all-page-size.test.ts) carried through and pass.

The unstacking is a clean net removal: the response-streaming path and wire-compatibility reasoning reviewed at 402f206 are unchanged, and nothing new is introduced by the rebase onto main.

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

…g it

Opening Orca's own checkout over SSH cannot list its files in one response frame.
22,617 tracked paths average 58 characters, so the 20,001-row page the client asks
for serializes to 1,223,415 bytes — past `DISPATCHER_CONTROL_QUEUE_MAX_BYTES`, so
`sendResponse` demotes it to the `legacy-response` lane, where an unrelated
producer backlog can refuse it as an opaque `ResponseOverCapacity`. Break-even is
around 49 characters of average path; any `packages/<name>/src/...` monorepo is
over the line.

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. `__streamResponse` already
exists for exactly this on the git methods, and it is its own negotiation in both
directions: an old client never sends it and gets the plain array on the
legacy-response lane as before, and an old relay ignores it and answers plainly,
which the client detects by the sentinel marker being absent. So fs.listFiles opts
into it — no new method, no new opcode, nothing to advertise — and the size of a
listing stops being a correctness question.

The response-stream registry becomes one per relay, shared by FsHandler and
GitHandler. A second registry is not an option and the header of
git-response-stream.ts says why: a client keys reassembly on `streamId` alone, so
two would hand out the same id and cross-feed chunks, and only the handler that
registers `git.responseAck` can credit the window a pump parks on.

Also declares `maxResults` on the runtime-RPC `files.listAll` and forwards it.
The mechanism "the client names its cap, so a full page reads as truncation" was
wired only on the Electron IPC hop; web and mobile were saved incidentally by
`remoteFileContentBudget` defaulting the cap inside `listRuntimeFiles`. A new
optional field is additive in both directions (wire rule 1).

The new Docker-gated spec is claimed by run-ssh-docker-e2e.mjs. The sharded e2e
lanes set no ORCA_E2E_SSH_DOCKER, so a Docker-gated spec that no runner names
self-skips everywhere and still reports green — pr-e2e-gate-contract enforces that.

Closes #12547
@nwparker
nwparker force-pushed the fix/quick-open-byte-budget branch from 5afeba1 to 7a9950f Compare September 2, 2026 12:13

@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

  • Claimed the Docker-gated e2e spec in its lane runner. run-ssh-docker-e2e.mjs now names ssh-docker-quick-open-large-listing.spec.ts, which at the prior commit existed but was unclaimed — a Docker-gated spec no runner names self-skips everywhere and still reports green. pr-e2e-gate-contract.test.mjs ("gives every Docker-gated SSH spec a lane that runs it") was red at the prior SHA and passes now (verified locally: 42/42).

The production streaming path, shared registry, and both tests are byte-for-byte unchanged from the prior review at 5afeba1; this commit only wires the new spec into the runner the gate contract already enumerates.

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

@nwparker
nwparker merged commit f737f34 into main Sep 2, 2026
32 checks passed
nwparker added a commit that referenced this pull request Sep 2, 2026
…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 added a commit that referenced this pull request Sep 2, 2026
…ncating (#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.** `#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`).
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…g it (stablyai#17954)

Opening Orca's own checkout over SSH cannot list its files in one response frame.
22,617 tracked paths average 58 characters, so the 20,001-row page the client asks
for serializes to 1,223,415 bytes — past `DISPATCHER_CONTROL_QUEUE_MAX_BYTES`, so
`sendResponse` demotes it to the `legacy-response` lane, where an unrelated
producer backlog can refuse it as an opaque `ResponseOverCapacity`. Break-even is
around 49 characters of average path; any `packages/<name>/src/...` monorepo is
over the line.

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. `__streamResponse` already
exists for exactly this on the git methods, and it is its own negotiation in both
directions: an old client never sends it and gets the plain array on the
legacy-response lane as before, and an old relay ignores it and answers plainly,
which the client detects by the sentinel marker being absent. So fs.listFiles opts
into it — no new method, no new opcode, nothing to advertise — and the size of a
listing stops being a correctness question.

The response-stream registry becomes one per relay, shared by FsHandler and
GitHandler. A second registry is not an option and the header of
git-response-stream.ts says why: a client keys reassembly on `streamId` alone, so
two would hand out the same id and cross-feed chunks, and only the handler that
registers `git.responseAck` can credit the window a pump parks on.

Also declares `maxResults` on the runtime-RPC `files.listAll` and forwards it.
The mechanism "the client names its cap, so a full page reads as truncation" was
wired only on the Electron IPC hop; web and mobile were saved incidentally by
`remoteFileContentBudget` defaulting the cap inside `listRuntimeFiles`. A new
optional field is additive in both directions (wire rule 1).

The new Docker-gated spec is claimed by run-ssh-docker-e2e.mjs. The sharded e2e
lanes set no ORCA_E2E_SSH_DOCKER, so a Docker-gated spec that no runner names
self-skips everywhere and still reports green — pr-e2e-gate-contract enforces that.

Closes stablyai#12547
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] Remote Quick Open / Files sidebar fails when the file-list response exceeds relay capacity

1 participant