Skip to content

Commit 25a16dd

Browse files
authored
fix(portals): keep worker previews reachable and owned by the active environment (#130434)
* fix(portals): preserve worker routes and portal lifetime ownership * fix(worker): keep diagnostics off the JSON result stream * test(portals): model worker stream closure across Node versions * test(agents): refresh compaction runtime mocks
1 parent c464bf1 commit 25a16dd

17 files changed

Lines changed: 770 additions & 490 deletions

‎docs/gateway/portals.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,8 @@ The Gateway never executes these commands automatically. The agent reads the fil
5555

5656
The application must honor `PORT`. Use `PUBLIC_URL` when it needs to generate absolute URLs.
5757

58+
The server can listen on IPv4 or IPv6 loopback (`127.0.0.1` or `::1`), both on the Gateway host and on a worker. Worker streams also preserve the node's configured Gateway context path when connecting through a reverse proxy.
59+
5860
The proxy rewrites `Host` to the local target, so typical development servers such as Vite and Next.js need no additional configuration. WebSockets and hot module replacement are proxied through the same portal.
5961

6062
## Availability and configuration

‎src/agents/embedded-agent-runner/compact.hooks.harness.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -880,15 +880,15 @@ export async function loadCompactHooksHarness(): Promise<{
880880
resolveBootstrapContextForRun: vi.fn(async () => ({ contextFiles: [] })),
881881
}));
882882

883-
vi.doMock("../bundle-mcp-tools.js", () => ({
883+
vi.doMock("../agent-bundle-mcp-tools.js", () => ({
884884
retireSessionMcpRuntime: vi.fn(async () => true),
885885
createBundleMcpToolRuntime: vi.fn(async () => ({
886886
tools: [],
887887
dispose: vi.fn(async () => {}),
888888
})),
889889
}));
890890

891-
vi.doMock("../bundle-lsp-runtime.js", () => ({
891+
vi.doMock("../agent-bundle-lsp-runtime.js", () => ({
892892
createBundleLspToolRuntime: vi.fn(async () => ({
893893
tools: [],
894894
sessions: [],

‎src/gateway/portals/portal-http-proxy.test.ts‎

Lines changed: 93 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import {
77
} from "node:http";
88
import net, { type AddressInfo } from "node:net";
99
import { duplexPair, type Duplex } from "node:stream";
10-
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
10+
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
1111
import { type RawData, WebSocket, WebSocketServer } from "ws";
1212
import type { PortalTarget } from "./portal-http-proxy.js";
1313
import { createGatewayPortalService, type GatewayPortalService } from "./portal-service.js";
@@ -97,11 +97,21 @@ async function listenTargetServer(server: Server): Promise<number> {
9797
return (server.address() as AddressInfo).port;
9898
}
9999

100-
function createWorkerStream(port: number): Duplex {
100+
function createWorkerStreamPair() {
101101
const [gatewayStream, workerStream] = duplexPair({ allowHalfOpen: false });
102+
// WebSocket closure delivers EOF to its peer; Node 22's duplexPair does not forward destroy.
103+
gatewayStream.once("close", () => workerStream.push(null));
104+
workerStream.once("close", () => gatewayStream.push(null));
105+
return [gatewayStream, workerStream] as const;
106+
}
107+
108+
function createWorkerStream(port: number): Duplex {
109+
const [gatewayStream, workerStream] = createWorkerStreamPair();
102110
const appSocket = net.connect({ host: "127.0.0.1", port });
103111
workerStream.on("error", () => appSocket.destroy());
104112
appSocket.on("error", () => workerStream.destroy());
113+
workerStream.once("close", () => appSocket.destroy());
114+
appSocket.once("close", () => workerStream.destroy());
105115
workerStream.pipe(appSocket).pipe(workerStream);
106116
return gatewayStream;
107117
}
@@ -228,7 +238,7 @@ describe("portal HTTP proxy", () => {
228238
res.statusCode = 200;
229239
res.end("proxied");
230240
};
231-
const portal = (await portalService().open({ targetPort, title: "App" })).portal;
241+
const portal = await portalService().open({ targetPort, title: "App" });
232242

233243
const unauthorized = await httpCall({ port: portal.listenPort });
234244
expect(unauthorized.status).toBe(401);
@@ -266,8 +276,8 @@ describe("portal HTTP proxy", () => {
266276
res.end("target-b");
267277
});
268278
const service = portalService();
269-
const portalA = (await service.open({ targetPort })).portal;
270-
const portalB = (await service.open({ targetPort: targetPortB })).portal;
279+
const portalA = await service.open({ targetPort });
280+
const portalB = await service.open({ targetPort: targetPortB });
271281
const jar = new Map<string, string>();
272282

273283
expect(
@@ -321,7 +331,7 @@ describe("portal HTTP proxy", () => {
321331
res.write("hello ");
322332
res.end("portal");
323333
};
324-
const portal = (await portalService().open({ targetPort })).portal;
334+
const portal = await portalService().open({ targetPort });
325335
const result = await httpCall({
326336
port: portal.listenPort,
327337
path: "/asset?q=1",
@@ -367,8 +377,8 @@ describe("portal HTTP proxy", () => {
367377
res.end("target-b");
368378
});
369379
const service = portalService();
370-
const portalA = (await service.open({ targetPort })).portal;
371-
const portalB = (await service.open({ targetPort: targetPortB })).portal;
380+
const portalA = await service.open({ targetPort });
381+
const portalB = await service.open({ targetPort: targetPortB });
372382
const jar = new Map<string, string>();
373383

374384
const initialA = await browserCall(jar, {
@@ -418,7 +428,7 @@ describe("portal HTTP proxy", () => {
418428
res.end("target-a");
419429
};
420430
const service = portalService();
421-
const portalA = (await service.open({ targetPort })).portal;
431+
const portalA = await service.open({ targetPort });
422432
const jar = new Map<string, string>();
423433
await browserCall(jar, {
424434
port: portalA.listenPort,
@@ -434,7 +444,7 @@ describe("portal HTTP proxy", () => {
434444
}
435445
res.end("target-b");
436446
};
437-
const portalB = (await service.open({ targetPort })).portal;
447+
const portalB = await service.open({ targetPort });
438448
expect(portalB.tokenQuery).not.toBe(portalA.tokenQuery);
439449

440450
await browserCall(jar, {
@@ -456,7 +466,7 @@ describe("portal HTTP proxy", () => {
456466
res.statusCode = 200;
457467
res.end("proxied");
458468
};
459-
const portal = (await portalService().open({ targetPort })).portal;
469+
const portal = await portalService().open({ targetPort });
460470
const token = portal.tokenQuery.slice("openclaw_portal=".length);
461471

462472
const result = await httpCall({
@@ -485,7 +495,7 @@ describe("portal HTTP proxy", () => {
485495
res.end();
486496
});
487497
};
488-
const portal = (await portalService().open({ targetPort })).portal;
498+
const portal = await portalService().open({ targetPort });
489499
const result = await httpCall({
490500
port: portal.listenPort,
491501
method: "POST",
@@ -509,7 +519,7 @@ describe("portal HTTP proxy", () => {
509519
await new Promise<void>((resolve) => {
510520
unavailableTarget.close(() => resolve());
511521
});
512-
const portal = (await portalService().open({ targetPort: port })).portal;
522+
const portal = await portalService().open({ targetPort: port });
513523

514524
const result = await httpCall({
515525
port: portal.listenPort,
@@ -536,15 +546,13 @@ describe("portal HTTP proxy", () => {
536546
socket.on("message", (data) => socket.send(data));
537547
});
538548
const appPort = await listenTargetServer(appServer);
539-
const portal = (
540-
await portalService().open({
541-
targetPort: remotePort,
542-
target: workerTarget(async () => {
543-
connectionCount += 1;
544-
return createWorkerStream(appPort);
545-
}, remotePort),
546-
})
547-
).portal;
549+
const portal = await portalService().open({
550+
targetPort: remotePort,
551+
target: workerTarget(async () => {
552+
connectionCount += 1;
553+
return createWorkerStream(appPort);
554+
}, remotePort),
555+
});
548556

549557
expect(
550558
await httpCall({ port: portal.listenPort, path: `/preview?${portal.tokenQuery}` }),
@@ -577,16 +585,14 @@ describe("portal HTTP proxy", () => {
577585
releaseDial = resolve;
578586
});
579587
const remotePort = 4173;
580-
const portal = (
581-
await portalService().open({
582-
targetPort: remotePort,
583-
target: workerTarget(async () => {
584-
notifyDialStarted();
585-
await dialReleased;
586-
return createWorkerStream(targetPort);
587-
}, remotePort),
588-
})
589-
).portal;
588+
const portal = await portalService().open({
589+
targetPort: remotePort,
590+
target: workerTarget(async () => {
591+
notifyDialStarted();
592+
await dialReleased;
593+
return createWorkerStream(targetPort);
594+
}, remotePort),
595+
});
590596

591597
const response = httpCall({
592598
port: portal.listenPort,
@@ -598,6 +604,50 @@ describe("portal HTTP proxy", () => {
598604
expect(await response).toMatchObject({ status: 200, body: "worker /slow" });
599605
});
600606

607+
it.each([
608+
["local", "browser"],
609+
["worker", "browser"],
610+
["local", "app"],
611+
["worker", "app"],
612+
] as const)("closes both sides when the %s portal's %s disconnects", async (kind, disconnect) => {
613+
let appResponse: ServerResponse | undefined;
614+
let appClosed = false;
615+
targetHandler = (_req, res) => {
616+
appResponse = res;
617+
res.once("close", () => {
618+
appClosed = true;
619+
});
620+
res.setHeader("Content-Type", "text/event-stream");
621+
res.write("data: ready\n\n");
622+
};
623+
const portal = await portalService().open({
624+
targetPort,
625+
...(kind === "worker"
626+
? {
627+
target: workerTarget(async () => createWorkerStream(targetPort), targetPort),
628+
}
629+
: {}),
630+
});
631+
const browserResponse = await new Promise<IncomingMessage>((resolve, reject) => {
632+
const browserRequest = request(portal.url, (res) => {
633+
res.on("error", () => undefined);
634+
res.once("data", () => resolve(res));
635+
});
636+
browserRequest.once("error", reject);
637+
browserRequest.end();
638+
});
639+
try {
640+
(disconnect === "browser" ? browserResponse : appResponse)?.destroy();
641+
await vi.waitFor(() => {
642+
expect(browserResponse.destroyed).toBe(true);
643+
expect(appClosed).toBe(true);
644+
});
645+
} finally {
646+
browserResponse.destroy();
647+
appResponse?.destroy();
648+
}
649+
});
650+
601651
it.each(["rejected", "closed", "reset"] as const)(
602652
"shows the worker retry page for HTTP and upgrades when its node stream is %s",
603653
async (streamState) => {
@@ -606,20 +656,18 @@ describe("portal HTTP proxy", () => {
606656
if (streamState === "rejected") {
607657
throw new Error("Worker node stream unavailable");
608658
}
609-
const [gatewayStream, workerStream] = duplexPair({ allowHalfOpen: false });
659+
const [gatewayStream, workerStream] = createWorkerStreamPair();
610660
if (streamState === "closed") {
611661
workerStream.end();
612662
} else {
613663
workerStream.destroy();
614664
}
615665
return gatewayStream;
616666
};
617-
const portal = (
618-
await portalService().open({
619-
targetPort: remotePort,
620-
target: workerTarget(connect, remotePort),
621-
})
622-
).portal;
667+
const portal = await portalService().open({
668+
targetPort: remotePort,
669+
target: workerTarget(connect, remotePort),
670+
});
623671
const cookie = portalAuthCookie(portal);
624672
const requestHeaders: Record<string, string>[] = [
625673
{ Cookie: cookie },
@@ -647,7 +695,7 @@ describe("portal HTTP proxy", () => {
647695
});
648696
try {
649697
const v6Port = (v6Target.address() as AddressInfo).port;
650-
const portal = (await portalService().open({ targetPort: v6Port })).portal;
698+
const portal = await portalService().open({ targetPort: v6Port });
651699
const result = await httpCall({
652700
port: portal.listenPort,
653701
path: `/?${portal.tokenQuery}`,
@@ -662,7 +710,7 @@ describe("portal HTTP proxy", () => {
662710

663711
it("splices WebSockets and destroys upgraded sockets and listeners on close", async () => {
664712
const service = portalService();
665-
const portal = (await service.open({ targetPort })).portal;
713+
const portal = await service.open({ targetPort });
666714
targetWebSocketSetCookie = "socket=ready; Domain=target.example; Path=/; HttpOnly";
667715
let upgradeCookies: string[] | undefined;
668716
const ws = new WebSocket(
@@ -706,8 +754,8 @@ describe("portal HTTP proxy", () => {
706754
res.end("target-b");
707755
});
708756
const service = portalService();
709-
const portalA = (await service.open({ targetPort })).portal;
710-
const portalB = (await service.open({ targetPort: targetPortB })).portal;
757+
const portalA = await service.open({ targetPort });
758+
const portalB = await service.open({ targetPort: targetPortB });
711759
const jar = new Map<string, string>();
712760
await browserCall(jar, {
713761
port: portalA.listenPort,
@@ -739,7 +787,7 @@ describe("portal HTTP proxy", () => {
739787

740788
it("does not forward WebSocket cookies from a closed portal when its target port is reused", async () => {
741789
const service = portalService();
742-
const portalA = (await service.open({ targetPort })).portal;
790+
const portalA = await service.open({ targetPort });
743791
targetWebSocketSetCookie = "socket=portal-a-secret; Path=/; HttpOnly";
744792
const connectionA = await openWebSocket(
745793
`ws://127.0.0.1:${portalA.listenPort}/hmr?${portalA.tokenQuery}`,
@@ -749,7 +797,7 @@ describe("portal HTTP proxy", () => {
749797
await closeWebSocket(connectionA.socket);
750798
await service.close(portalA.id);
751799

752-
const portalB = (await service.open({ targetPort })).portal;
800+
const portalB = await service.open({ targetPort });
753801
targetWebSocketSetCookie = "socket=portal-b; Path=/; HttpOnly";
754802
const connectionB = await openWebSocket(
755803
`ws://127.0.0.1:${portalB.listenPort}/hmr?${portalB.tokenQuery}`,

‎src/gateway/portals/portal-http-proxy.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -318,6 +318,7 @@ export function handlePortalProxyRequest(params: {
318318
// send the token-bearing portal URL to every third-party origin it references.
319319
res.setHeader("Referrer-Policy", PORTAL_REFERRER_POLICY);
320320
res.statusCode = proxyRes.statusCode ?? 502;
321+
proxyRes.once("error", () => res.destroy());
321322
proxyRes.pipe(res);
322323
});
323324
proxyReq.once("error", () => {
@@ -332,7 +333,8 @@ export function handlePortalProxyRequest(params: {
332333
respondPortalWaiting(req, res, targetPort);
333334
}
334335
});
335-
req.once("aborted", () => proxyReq.destroy());
336+
// A browser can leave after its request body ended (for example during SSE).
337+
res.once("close", () => proxyReq.destroy());
336338
req.pipe(proxyReq);
337339
},
338340
() => {

0 commit comments

Comments
 (0)