Repository navigation
fix: desktop stream hangs when the gateway never acknowledges close - #165806
Conversation
After the local target ends, a gateway that never completes the WebSocket close handshake held the stream command for the library's 30s close timer. The command now finishes and the socket is terminated after 5s. Signed-off-by: Sebastien Tardif <[email protected]>
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. Reviewed October 6, 2026, 6:20 PM ET / 22:20 UTC (Revision 23). ClawSweeper reviewWhat this changesThe PR bounds empty desktop and portal stream shutdown, waits for outgoing data to drain before closing, and adds transport regressions for unresponsive peers. Merge readiness✅ Ready for maintainer review Keep open: the shutdown improvement remains absent from current main and the latest release. The latest regression test addresses the documented coverage gap; no blocking correctness finding remains. Priority: P2 Review scores
Verification
How this fits togetherThe node stream transport connects a local desktop or portal service to the Gateway through an authenticated WebSocket. Its completion controls when the Gateway retires the receiving stream. flowchart LR
A[Local desktop or portal] --> B[Node stream transport]
B --> C[Outgoing buffer]
C --> D{Empty or forwarded data}
D --> E[Bounded empty shutdown]
D --> F[Drain before handshake]
E --> G[Gateway receiving stream]
F --> G
Before mergeNone. Agent review detailsSecurityNone. PR surfaceSource +76, Tests +499. Total +575 across 2 files. View PR surface stats
Review metricsNone. Technical reviewBest possible solution: Keep bounded empty-stream retirement and drain-aware forwarding while leaving the close handshake with the installed WebSocket library. Do we have a high-confidence way to reproduce the issue? Yes: a real TCP peer that completes attachment but withholds close acknowledgement exposes the shutdown delay, with recorded comparative transport traces. This read-only review inspected the source and supplied observations without executing a reproduction. Is this the best way to solve the issue? Yes: distinguishing empty shutdown from forwarded data preserves delivery while reusing the library's handshake owner; the latest fake-timer regression protects finite socket retirement. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 51f772aeefbc. LabelsLabel changes: No label changes. Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (22 earlier review cycles; latest 8 shown)
|
The socket data callback was string or Buffer, so Buffer.concat failed check-test-types-core-1. The other listener in this file already types the chunk as Buffer. Signed-off-by: Sebastien Tardif <[email protected]>
ws.close() returns while the last payload and the close frame can still be queued. The 5 second budget now starts after that buffer drains. A flush that stays queued keeps the 30 second allowance. A local gateway that stopped reading left the command pending past a 40 ms budget. It settled 59 ms after the gateway resumed. Signed-off-by: Sebastien Tardif <[email protected]>
The paused gateway kept the command pending on this machine and settled immediately in CI. The acknowledgement budget test stays on a real socket with a 40 ms deadline. Signed-off-by: Sebastien Tardif <[email protected]>
The regression waited on a two-second wall clock against a 40 ms timer. It now waits until the close path schedules that callback, then runs the callback. Signed-off-by: Sebastien Tardif <[email protected]>
|
@SebTardif the built Gateway + enrolled node runtime comparison found a slow-stream regression on
Please make the acknowledgement timer start only once the socket's buffered bytes have drained, so the final payload and close frame survive this slow path. The current The ordinary acknowledged-close and active-stream controls passed, the withheld-ack timeout behaved as intended for the small payload, and the regression test is red on base / green on the candidate. Those passes do not override this truncation. The PR's Evidence section now records the full comparison; this PR should not land as-is. |
bufferedAmount 0 only means the kernel accepted the bytes. After more than 64 KiB, the close acknowledgement uses the 30s flush budget instead of 5s, so a slow attach can finish reading before the node command retires the gateway stream. Signed-off-by: Sebastien Tardif <[email protected]>
Core lint stripe 5 rejects createDeferred<void>() because void is already the default type parameter. Signed-off-by: Sebastien Tardif <[email protected]>
A received close still retires on the 30 second flush. The library closeTimeout override stays, so a forwarded stream is not destroyed while a proxy holds the tail. Signed-off-by: Sebastien Tardif <[email protected]>
The multi-day closeTimeout and the extra post-close timer retired the same handshake. Empty closes still use five seconds, and a stalled send buffer still waits before close. Signed-off-by: Sebastien Tardif <[email protected]>
The ordinary suite waits for the close record instead of polling logs. The default-timer withheld-FIN measurement stays in the pull request body, outside this file. Signed-off-by: Sebastien Tardif <[email protected]>
|
@SebTardif, thanks for consolidating handshake ownership in I pinned your
Both slow cases delivered all 12,582,912 bytes with zero corrupt bytes, on both revisions. Those runs use the built Gateway, an enrolled node, synthetic RFB target, and a proxy forwarding at at most 16 KiB per 64 ms. Your active control delivered its 15-byte marker at 7.117 s and remained open until deliberate cleanup. The other shutdown cases invoke the actual source transport against real TCP peers with production default timers; they are not represented as built-Gateway runs. No shutdown-boundary case hung past the 40-second cap. Removing the duplicate post-drain/command-failure timers remained bounded in these cases via Concrete coverage gap: your Your unmodified file passes 27/27 in 33.402 s wall time; the valid-close case consumes 30.035 s. The affected Below is an optional test-only suggestion against your pinned head for the remaining polling/real-timer findings. It waits for actual close events, advances fake time only after the peer receives FIN, and leaves production untouched. In isolation this patch passed 27/27 in 3.836 s wall time, passed the affected type graph, and its valid-close test failed under the same multi-day-timeout mutation ( Suggested event-driven test patch (not pushed)--- a/src/node-host/node-stream-transport.test.ts
+++ b/src/node-host/node-stream-transport.test.ts
@@ -1,12 +1,14 @@
import { createHash, X509Certificate } from "node:crypto";
+import { once } from "node:events";
import { createServer as createHttpServer } from "node:http";
import { createServer as createHttpsServer } from "node:https";
import net, { type AddressInfo } from "node:net";
import { Duplex } from "node:stream";
import { rawDataToString } from "@openclaw/gateway-client/websocket-data";
import { installGlobalProxy } from "@openclaw/proxyline";
-import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { WebSocketServer } from "ws";
+import { WebSocket } from "../../packages/gateway-client/src/websocket.js";
import { createDeferred } from "../../test/helpers/promise.js";
import { TEST_TLS_CERT_PEM, TEST_TLS_KEY_PEM } from "../../test/helpers/tls-fixture.js";
import { createSuiteLogPathTracker } from "../logging/log-test-helpers.js";
@@ -308,7 +310,6 @@
gateway.listen(0, "127.0.0.1", resolve);
});
const controller = new AbortController();
- let settled = false;
const running = runNodeStreamTransport({
gatewayUrl: `ws://127.0.0.1:${(gateway.address() as AddressInfo).port}`,
attachPath: `/node-${streamName}/attach`,
@@ -317,14 +318,11 @@
metadata: { ok: true },
streamName,
signal: controller.signal,
- }).then(() => {
- settled = true;
});
try {
await wrote.promise;
target.push(Buffer.from("terminal-response"));
target.push(null);
- await expect.poll(() => settled).toBe(true);
await running;
expect(frames).toEqual([JSON.stringify({ ok: true }), "terminal-response"]);
expect(writes).toBe(1);
@@ -350,6 +348,7 @@
const logCapture = createDiagnosticLogRecordCapture();
logCaptures.push(logCapture);
const gotFrame = createDeferred();
+ const terminate = vi.spyOn(WebSocket.prototype, "terminate");
const gateway = net.createServer((socket) => {
let buffer = Buffer.alloc(0);
let upgraded = false;
@@ -435,12 +434,12 @@
ack?.();
await running;
expect(failure).toBeUndefined();
- await expect
- .poll(async () => {
- await logCapture.flush();
- return logCapture.records.find((record) => record.message === "node stream closed");
- })
- .toBeTruthy();
+ const client = terminate.mock.contexts[0];
+ if (!(client instanceof WebSocket)) {
+ throw new Error("Expected cleanup to terminate the client WebSocket");
+ }
+ await once(client, "close");
+ await logCapture.flush();
expect(
logCapture.records.find((record) => record.message === "node stream closed")?.attributes,
).toMatchObject({
@@ -452,6 +451,7 @@
controller.abort();
await running;
targetPeer?.destroy();
+ terminate.mockRestore();
await new Promise<void>((resolve) => {
targetServer.close(() => resolve());
});
@@ -747,9 +747,12 @@
it("bounds a gateway close that withholds TCP FIN", async () => {
let peer: net.Socket | undefined;
+ const close = vi.spyOn(WebSocket.prototype, "close");
+ const receivedFin = createDeferred();
const gateway = net.createServer({ allowHalfOpen: true }, (socket) => {
peer = socket;
socket.on("error", () => undefined);
+ socket.once("end", () => receivedFin.resolve());
let buffer = Buffer.alloc(0);
let upgraded = false;
let sentClose = false;
@@ -794,29 +797,43 @@
callback();
},
});
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
const controller = new AbortController();
- const started = Date.now();
+ let failure: unknown;
+ const running = runNodeStreamTransport({
+ gatewayUrl: `ws://127.0.0.1:${(gateway.address() as AddressInfo).port}`,
+ attachPath: "/node-desktop/attach",
+ expectedAttachPath: "/node-desktop/attach",
+ target: { stream: target },
+ metadata: { ok: true },
+ streamName: "desktop",
+ signal: controller.signal,
+ }).catch((error: unknown) => {
+ failure = error;
+ });
try {
- await runNodeStreamTransport({
- gatewayUrl: `ws://127.0.0.1:${(gateway.address() as AddressInfo).port}`,
- attachPath: "/node-desktop/attach",
- expectedAttachPath: "/node-desktop/attach",
- target: { stream: target },
- metadata: { ok: true },
- streamName: "desktop",
- signal: controller.signal,
- });
- const elapsed = Date.now() - started;
+ await receivedFin.promise;
expect(target.readableEnded).toBe(false);
- expect(elapsed).toBeGreaterThan(20_000);
- expect(elapsed).toBeLessThan(40_000);
+ const client = close.mock.contexts[0];
+ if (!(client instanceof WebSocket)) {
+ throw new Error("Expected a client WebSocket close handshake");
+ }
+ const closed = once(client, "close");
+ await vi.advanceTimersByTimeAsync(30_000);
+ expect(client.readyState).toBe(WebSocket.CLOSED);
+ await closed;
+ await running;
+ expect(failure).toBeUndefined();
} finally {
controller.abort();
target.destroy();
peer?.destroy();
+ await running;
+ close.mockRestore();
+ vi.useRealTimers();
await new Promise<void>((resolve) => {
gateway.close(() => resolve());
});
}
- }, 50_000);
+ });
});The harness is retained; happy to repeat the affected checks on your next revision. |
|
@SebTardif, thanks for removing the 30-second wait. Production at 1f7ec3a is unchanged from 4a1fb57, and our runtime numbers above still hold: every case is bounded at about 30 s, empty streams take 5 s, and slow 12 MiB transfers deliver every byte. One gap remains: the tests no longer guard the bug this PR fixes. With Could you add one fake-timer test that would fail on that mutation? For example, a valid Gateway close frame with a peer that keeps the TCP connection half-open ( |
A valid gateway close that keeps TCP half-open must reach CLOSED after the library close deadline. Fake timers cover that bound, so the suite fails if closeTimeout is raised to a multi-day value. Signed-off-by: Sebastien Tardif <[email protected]>
|
@obviyus Added one fake-timer test for a valid gateway close that withholds TCP FIN. Head The peer keeps the connection half-open. After it sees the client FIN, the test advances 30 seconds and expects the client socket to be CLOSED and the command to settle. The file is 27 tests and finishes in about 2 seconds. With |
|
Landed in a6051a2. Thanks @SebTardif for sticking with this one! On this head the withheld-FIN regression fails if the close timeout is removed, an empty close settles in ~5 s instead of ~30 s, and a slow 12 MiB payload still arrives intact. |
|
🦞👀 Command router queued. I will update this comment with the next step. |
|
🦞👀 Command router queued. I will update this comment with the next step. |
What Problem This Solves
A desktop or portal stream used to stay open when the local target ended and the gateway never finished the WebSocket close. The short acknowledgement that fixed that hang also settled the node command while a proxy could still be holding the tail. Settling the command destroys the gateway receive stream, so those bytes never arrive.
A size cutoff does not fix that. Forwards of 64 KiB or less still took the 5 second path. Any fixed wait after the local buffer drains has the same hole:
bufferedAmount === 0means the kernel accepted the bytes, not that the gateway has read them.Evidence
Gateway close that withholds TCP FIN: 1f7ec3a
wsowns the close handshake. The multi-daycloseTimeoutoverride is gone, and so is the extra node timer that fired 30 seconds after drain. An empty close still uses the 5 second acknowledgement. A send buffer that is still shrinking still waits beforeclose().Local production call on macOS 26.6.2 arm64 (Darwin 25.6.0), Node v26.10.0. A TCP peer with
allowHalfOpencompleted the WebSocket upgrade, wrote close code 1000 after the metadata frame, and did not send FIN. Default timers. No enrolled gateway. The 12 MiB enrolled-node run was not repeated.peer_end 18is the client's close-handshake write FIN. The command settled at 30121 ms, and the library logged the socket close. A second local peer sent invalid opcode 3. The command rejected at 17 ms, the peer sawpeer_endat 17 ms, and the same close log followed the 30008 ms tick. That default-timer run stays outside the ordinary test file.node scripts/run-vitest.mjs src/node-host/node-stream-transport.test.tspassed 26 tests in 1.44 s, with no real 30 second wait. The empty-close case waits for the diagnostic close record, then flushes once.Test-only follow-up: 4b10b22
The protocol-error regression on that head uses a TCP peer with
allowHalfOpen: trueand withholds FIN. It sends invalid opcode 3, fires the injected cleanup callback, observes the real clientterminate()call, then awaits that client'scloseevent and verifiesCLOSEDbefore peer teardown. No sleeps or polling were added. Production code on that head was unchanged from the runtime-proven e5cb252.expected "terminate" to be called once, but got 0 times(53 ms). The mutation was restored and never committed.pnpm test src/node-host/node-stream-transport.test.ts --maxWorkers=1passed 26/26, 5.349 s wall time (Vitest 3.92 s; repaired case 5 ms), in secretlessnode:24.16.0-bookworm.git diff --checkpassed. No overlap with Pash/Sarah changes.The previous test-only head failed TypeScript because a spy context is
unknown. This head replaces the non-narrowing expectation with aninstanceof WebSocketguard. The affected type graph passes:node scripts/run-tsgo.mjs -p test/tsconfig/tsconfig.core.test.gateway-other.json --noEmit(exit 0).Exact-head verification: e5cb252
Fresh isolated Docker proof on this head:
closeevent occurred at 30,009 ms. This observes socket retirement, not just timer scheduling. The same peer on base closed at 30,139 ms; the previous candidate remained unclosed at the 40-second cap.gpt-5-minicall, reasoninglow, output budget 4096:P165806_LIVE_OK, statusok, exit 0.Boundary replays above invoke the actual source-level transport against real TCP peers with default timers; they are not built-Gateway proofs. The delivery/control cases use the built Gateway and enrolled node. No physical desktop was used. This is bounded evidence for the stated rates and payloads, not a claim that every arbitrarily delayed tail is preserved.
Historical observations (not current-head claims)
On head
f85d55f8c56, a built Gateway, an enrolled node, and a throttled proxy delivered all 12,582,912 bytes of a 12 MiB stream paced at 16 KiB per 64 ms, and the proxy forwarded the close frame. That measurement is the maintainer's. The exact-head repeat is recorded above.Historical trace from
2dc5166a082, before the current finite post-drain deadline: productionrunNodeStreamTransportconnected to a local gateway through a TCP proxy on127.0.0.1. The proxy forwarded the HTTP upgrade, read the rest from the node, and held those bytes for 35 seconds before writing them to the gateway. The local target wrote 1024 bytes and ended. The production close budget was left in place.At 32 seconds the command was still pending and the gateway had not received the payload. After the proxy released the bytes, the gateway counted 1024 payload bytes and the command settled at 35080 ms. That is past both the 5 second acknowledgement and the library's 30 second close timer.
An empty close still uses the 5 second acknowledgement. In an earlier revision the production default was left in place, the target ended without writing a payload, and the silent gateway never completed the close. The command settled at 5013 ms.
{"event":"empty_close","settled":true,"elapsedMs":5013}On historical head
7532b772cd8, a local gateway read 64 payload bytes and then stayed silent. The production budgets were left in place. The command settled at 30014 ms.{"event":"silent_close_after_forward","payloadBytes":64,"settled":true,"elapsedMs":30014}A send buffer that stops shrinking for 30 seconds still retires, because those bytes have not left this process. The historical 35-second hold does not establish delivery under the current finite post-drain deadline; current-head delivery evidence is reported above.
On an earlier head, a local peer sent a frame with RSV1 set. The command rejected while that peer held the TCP connection open, and a scheduled cleanup terminated the socket. The current head leaves that handshake to
ws.Real behavior proof
Behavior addressed: A gateway close frame that withholds TCP FIN retires through the library close timer. The node does not add a second post-close timer or a multi-day closeTimeout override.
Real environment tested: macOS 26.6.2 arm64, Darwin 25.6.0, Node v26.10.0. Local process calling production runNodeStreamTransport. No enrolled gateway and no physical desktop.
Exact steps or command run after this patch: pnpm exec tsx ran a local script that is not in the commit. The script listened on 127.0.0.1 with allowHalfOpen, answered the WebSocket upgrade, and on the next payload wrote bytes 88 02 03 e8. It imported runNodeStreamTransport from src/node-host/node-stream-transport.ts and used default timers with an open Duplex target.
Evidence after fix: terminal output copied below.
Observed result after fix: The command settled at 30121 ms and the library logged the socket close. The peer logged peer_end at 18 ms. Earlier Docker and 12 MiB results above are for e5cb252 and were not repeated.
What was not tested: a live enrolled gateway, a physical desktop or portal, and the 12 MiB paced transfer. That transfer already passed on e5cb252 and was not repeated.
Summary
Forwarded streams send the close only after the outbound buffer drains.
wsthen owns the handshake, including a gateway close that withholds TCP FIN. An empty close still uses the 5 second bound. A send buffer that stops shrinking still waits before close. A failed command rejects without a second node handshake timer.