Repository navigation
feat(remote-control): support chunked streaming transfers up to 100 MiB - #4214
Conversation
🦋 Changeset detectedLatest commit: e5fa907 The changes in this PR will be included in the next version bump. This PR includes changesets to release 1 package
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
commit: |
c84de70 to
e9be438
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e9be4382a7
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| left.on('message', (data, isBinary) => void rightWrites.send(data, isBinary)); | ||
| right.on('message', (data, isBinary) => void leftWrites.send(data, isBinary)); |
There was a problem hiding this comment.
Drain queued WebSocket frames before propagating close
When either bridged peer sends several frames and then closes before the destination's send callbacks finish, these handlers only submit the first frame to ws; closeBoth immediately changes the destination to CLOSING, and SocketWriteQueue.write silently skips every remaining queued frame. The previous handlers called send synchronously for every message, so this introduces silent loss of trailing Remote Control WebSocket messages during normal close sequences; drain the relevant write queue before closing the opposite peer.
AGENTS.md reference: AGENTS.md:L117-L119
Useful? React with 👍 / 👎.
| } catch { | ||
| this.frames.delete(requestId); | ||
| if (this.socket.readyState !== WebSocket.OPEN) { | ||
| this.frames.clear(); | ||
| return; | ||
| } | ||
| this.onSendFailed(requestId); | ||
| continue; |
There was a problem hiding this comment.
Stop retrying an abort after its own send fails
When a response-frame send fails while the WebSocket still reports OPEN, onSendFailed enqueues an abort for the same request, but that abort is processed by this identical failure path. If its send also fails before the socket state changes, another abort is enqueued indefinitely, so the pump spins on one request and silently prevents every other queued HTTP response from being sent; mark the failure notification separately or reconnect if sending the abort fails.
AGENTS.md reference: AGENTS.md:L117-L119
Useful? React with 👍 / 👎.
| const bodyBase64 = parsed['body_base64']; | ||
| const minDecodedBytes = Math.floor(bodyBase64.length / 4) * 3 - 2; | ||
| if (this.pendingHttpBytes + minDecodedBytes > MAX_HTTP_REQUEST_BYTES) { | ||
| throw new SyntaxError('HTTP tunnel request exceeds 10 MiB'); | ||
| throw new SyntaxError( | ||
| `HTTP tunnel request exceeds ${MAX_HTTP_REQUEST_BYTES / 1024 / 1024} MiB`, | ||
| ); |
There was a problem hiding this comment.
Enforce the upload limit per request
For concurrent chunked uploads, pendingHttpBytes is shared across every request ID, so two individually valid 60 MiB uploads exceed the 104 MiB check when their chunks are interleaved and one is rejected with 400. This makes the advertised per-transfer 100 MiB support depend on unrelated in-flight uploads; retain a separate aggregate safety budget if needed, but validate the transfer-size limit against pending.size so each request can reach the documented limit.
Useful? React with 👍 / 👎.
| for (let offset = 0; offset < response.length; offset += RESPONSE_CHUNK_BYTES) { | ||
| const end = Math.min(offset + RESPONSE_CHUNK_BYTES, response.length); | ||
| queue.enqueue( | ||
| requestId, | ||
| JSON.stringify({ | ||
| request_id: requestId, | ||
| type: 'response_chunk', | ||
| is_last: end === response.length && response.length % RESPONSE_CHUNK_BYTES !== 0, | ||
| body_base64: response.subarray(offset, end).toString('base64'), | ||
| }), | ||
| ); |
There was a problem hiding this comment.
Serialize response chunks lazily
For a download near the new 100 MiB limit, this synchronous loop base64-encodes and JSON-serializes every chunk before the first send callback can run, leaving roughly 133 MiB of encoded frame strings queued in addition to the complete raw response and the buffers retained by requestLocalHttp. Memory-constrained CLI/server processes can therefore be terminated while handling a transfer the feature explicitly claims to support, and the event loop is blocked during all of that encoding; create each frame only when the queue is ready to send it, ideally while consuming the local response stream.
Useful? React with 👍 / 👎.
e9be438 to
f759eb9
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f759eb9d74
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| if (this.pendingHttpBytes + minDecodedBytes > MAX_PENDING_HTTP_BYTES) { | ||
| throw new SyntaxError( | ||
| `HTTP tunnel pending bytes exceed ${MAX_PENDING_HTTP_BYTES / 1024 / 1024} MiB`, | ||
| ); |
There was a problem hiding this comment.
Keep in-flight uploads within the memory budget
When several near-100 MiB uploads finish reassembly while the local server is slow to consume or answer them, this limit no longer protects the process: each request is removed from pendingHttpBytes before forwardHttpRequest completes, while its full rawRequest remains retained by the local HTTP call. An arbitrary number of completed uploads can therefore consume hundreds of MiB each and terminate the Remote Control process despite the aggregate safety budget; keep their bytes charged until forwarding finishes or impose a separate in-flight limit.
Useful? React with 👍 / 👎.
| return new Promise((resolve) => { | ||
| this.socket.send(data, { binary }, () => { | ||
| resolve(); | ||
| }); |
There was a problem hiding this comment.
Close the bridge when a queued WebSocket send fails
When a bridged WebSocket send invokes its callback with an error while the destination still reports OPEN, this callback always resolves, so the queue discards that application frame and proceeds without invoking closeBoth or otherwise notifying either peer. This turns an asynchronous compression or write failure into silent session-data loss; propagate the callback error and terminate the bridge instead.
AGENTS.md reference: AGENTS.md:L117-L119
Useful? React with 👍 / 👎.
f759eb9 to
b5b6ad7
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b5b6ad7b6c
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| queue.enqueue(requestId, () => | ||
| JSON.stringify({ | ||
| request_id: requestId, | ||
| type: 'response_chunk', | ||
| is_last: end === response.length && response.length % RESPONSE_CHUNK_BYTES !== 0, | ||
| body_base64: response.subarray(offset, end).toString('base64'), | ||
| }), |
There was a problem hiding this comment.
Bound queued large-response buffers
When several concurrent requests each return a near-100 MiB response faster than the tunnel can transmit them, every set of lazy frame closures captures its complete response buffer until that transfer's final chunk is sent; the round-robin queue therefore retains all large responses simultaneously with no aggregate response budget. The lazy serializer fixes the previously reported eager-base64 allocation, but concurrent downloads can still grow memory without bound and terminate the Remote Control process, so response buffers should be charged against a bounded budget or streamed from the local response.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in c78b91f. Response buffers are now charged against the same aggregate budget that already bounds uploads (MAX_PENDING_HTTP_BYTES = 2×104 MiB). The charge is acquired when the local response headers arrive (estimated from Content-Length, 0 when absent) and settled to the final transformed buffer length once the body is read; it is released exactly when the transfer leaves the HttpWriteQueue (final chunk sent / send failure / drop / connection teardown, via a new onTransferDone callback), or in the forwardHttpRequest finally path when nothing was enqueued. A response that would exceed the budget now fails fast with a synthesized 503 instead of queueing unboundedly — mirroring the upload-side 400 semantics. Waiting for budget instead of failing fast was rejected deliberately: at default relay speed a ~104 MiB grant can take minutes, which would trip the relay 30s first-chunk idle timeout anyway.
b5b6ad7 to
c78b91f
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c78b91f313
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| const settle = chargeResponse?.( | ||
| Number.isFinite(declaredLength) && declaredLength > 0 ? declaredLength : 0, |
There was a problem hiding this comment.
Budget actual response bytes while reading them
Fresh evidence after the earlier queued-response budget finding is that this new guard reserves only the declared Content-Length: a chunked response with no length reserves zero until settle(raw.length) runs after the entire body has been buffered, and that settlement never rechecks MAX_PENDING_HTTP_BYTES, so concurrent streaming responses can still bypass the advertised aggregate cap and exhaust memory. Conversely, HEAD and no-body responses reserve the representation length and can spuriously return 503 under concurrency; account for bytes incrementally as they are read, with no-body method/status handling.
AGENTS.md reference: AGENTS.md:L97-L99
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in e276586. Response bytes are now charged incrementally on every data event of the local response (received bytes + the retained request buffer), so chunked responses without Content-Length hit the same aggregate cap mid-read and fail fast with 503; HEAD and other no-body responses reserve nothing. Once the transform chain finishes, the charge is set to the final response length (only the small rewrite/gzip delta is applied without re-checking). This came with a lifecycle refactor: per-connection HttpTunnel, one transfer object per request_id whose single idempotent end() releases its charge, so there is no separate estimate/settle path anymore.
| pending.chunks.push(chunk); | ||
| pending.size += chunk.length; | ||
| this.pendingHttpBytes += chunk.length; | ||
| this.httpByteCharges.set(requestId, pending.size); | ||
| this.pendingHttpRequests.set(requestId, pending); |
There was a problem hiding this comment.
Bound metadata for incomplete request chunks
When a peer starts an upload with is_last: false, every fragment is retained in pending.chunks, but the global limit counts only chunk.length. Empty fragments therefore add a new Buffer and array entry without increasing pendingHttpBytes, and there is no chunk-count, pending-request-count, or assembly-time limit to clear them; a remote client can keep sending empty or tiny fragments and grow the process heap without ever approaching the 208 MiB budget. Bound the number of retained fragments/requests or discard and time out empty incomplete fragments.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in e276586. Each retained request fragment is now charged as chunk.length + 1 KiB against the same aggregate budget (MAX_RETAINED_HTTP_BYTES), so empty or tiny fragments consume budget and both the fragment count and the number of in-progress transfers are bounded without a separate counter; once the budget is exhausted the transfer gets a 400 and its buffers are released. No client-side assembly timeout was added: stalled transfers are reaped by the relay idle timeout, which sends abort and releases the transfer here.
c78b91f to
e276586
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e27658619c
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| chunks.push(chunk); | ||
| transfer.size += chunk.length; | ||
| if (!parsed['is_last']) return; | ||
| const raw = Buffer.concat(chunks, transfer.size); |
There was a problem hiding this comment.
Account for buffers duplicated during upload reassembly
When two supported near-100 MiB uploads are interleaved, both fragment sets fit under the 208 MiB retained-byte limit, but finalizing either request allocates another approximately 100 MiB with Buffer.concat before its fragment buffers can be released. The other upload and any completed request buffer remain retained, so actual usage can exceed 300 MiB despite the advertised aggregate bound and terminate a memory-constrained Remote Control process; reserve space for the reassembly copy or assemble/forward without duplicating the complete body.
AGENTS.md reference: AGENTS.md:L28-L28
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 1f83bfd by removing the copy instead of reserving for it: the request is no longer reassembled with Buffer.concat. parseRawHttpRequest now takes the fragment list, concatenates only the bounded header prefix (≤ 64 KiB + 4) to parse the request line and headers, and returns the body as zero-copy subarray views over the received fragments, which requestLocalHttp writes to the local request one by one (adding Content-Length from the total when the forwarded headers lack it). The retained-byte charge (fragment bytes + per-fragment overhead) therefore matches what is actually held from first fragment until the transfer ends, and two interleaved ~100 MiB uploads stay within the 208 MiB bound. Reserving room for a full copy was rejected because it would make the second of two concurrent supported 100 MiB uploads fail at finalization. Known remaining: response-side transform copies (buffer-then-slice download path) are tracked as the streaming-response follow-up.
e276586 to
1f83bfd
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 1f83bfd341
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| localResponse.on('data', (chunk: Buffer | string) => { | ||
| const buffer = Buffer.from(chunk); | ||
| receivedBytes += buffer.length; | ||
| if (!retain(receivedBytes)) { |
There was a problem hiding this comment.
Budget copies made while assembling large responses
Fresh evidence beyond the earlier response-budget thread is the end-of-stream assembly: this check charges only the bytes stored in chunks, but Buffer.concat(chunks) at line 1099 allocates a second full body before those chunks can be reclaimed, and the later Buffer.concat for the raw HTTP response makes another full-size allocation. Consequently, two valid concurrent 100 MiB downloads can be admitted under the 208 MiB aggregate limit while temporarily requiring roughly 400 MiB or more, defeating the stated memory bound and potentially terminating a memory-constrained Remote Control process; reserve the assembly copies or stream the response into the outgoing frames.
Useful? React with 👍 / 👎.
1f83bfd to
e5fa907
Compare
Requirement or Bug
Remote Control 隧道接入 relay 分块流式传输协议,上传/下载单笔上限从 10 MiB 放宽到 100 MiB。
Bug Reproduction Steps
N/A
Root Cause
N/A
Code Changes
改动集中在
packages/remote-control(隧道客户端)及其测试;relay 侧分块流式协议已部署测试环境,本 PR 为客户端接入:Remote Control WS 桥接与 management 通道的发送路径保持与 main 一致(直接
ws.send),本 PR 不改动。重连语义不变:closeCycle关闭当前 HttpTunnel、丢弃全部在途传输,新连接不补发旧request_id的块;在途状态归属单条连接,旧连接的迟到回调不会影响新连接的记账。Behavior Changes and Affected Users
response_chunk分块response整发device_idcapabilities=...,每连接随握手刷新受影响人群:使用 Remote Control(web / desktop 经隧道访问本机)传输文件的用户。≤10 MiB 流量行为与线上一致;>10 MiB 传输需要已部署分块协议的 relay(测试环境已就绪,relay 生产全量为发布 gate)。
测试覆盖(
packages/remote-control/test/remote-control.test.ts,40/40 通过,本地 macOS 与 m0-dev Linux 各验证一次):两次握手均声明 capabilities 且 register 不携带;11 MiB 三帧上传重组;>10 MiB 下载三帧分块(本地 chunked 响应)与字节级重组、15 MiB 精确对齐空尾帧;大小请求并发均正确完成;两笔 100 MiB 交错上传均获准并转发,此时 9 MiB 上传拒 400、无 Content-Length 的 11 MiB 下载拒 503、HEAD 15 MiB 资源正常 200,abort 释放后重试成功;HttpTunnel 单测——轮转顺序[a, b, a]、发送中 abort 后不再发块且额度释放、本地响应增量记账超预算被拒、空碎片按固定开销耗尽预算后拒 400、abort 释放转发中额度、发送失败关闭隧道并取消其余本地转发;重组中 / 本地转发中入向 abort(/hang取消可观测)、重复与未知 abort 忽略;WS 桥接连发 3 帧后 clean close 对端收齐;重连后旧在途传输不补发、新请求正常。遗留:relay 测试环境联调验收清单(接入指南 §5)待与 relay 侧约定窗口后执行。
Checklist
/approve).gen-changesetsskill, or this PR needs no changeset.gen-docsskill, or this PR needs no doc update.