Skip to content

Commit 626ca3d

Browse files
committed
refactor(browser): simplify relay lifecycle helpers
Remove duplicate profile admission and terminal handling, reuse RPC result schemas and deferred completion, and make announcement recipients and request-local action guards explicit. Preserve authentication, asynchronous ownership checks, cleanup acknowledgements, and action error precedence. Make the Gateway upgrade-head fixture deterministic at its existing input boundary instead of depending on TCP coalescing. Keep its assertions. Maintainer-requested follow-up to the standalone relay in #128379. Production LOC -75; test LOC -11. Validated with 203 focused tests, changed checks, full build, and fresh scoped-clean Codex autoreview at P0.
1 parent 6b64674 commit 626ca3d

7 files changed

Lines changed: 195 additions & 281 deletions

File tree

‎extensions/browser/src/browser/extension-relay/gateway-relay-route.integration.test.ts‎

Lines changed: 34 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import {
99
} from "openclaw/plugin-sdk/runtime-config-snapshot";
1010
import { withEnvAsync, withTempDir } from "openclaw/plugin-sdk/test-env";
1111
import { afterEach, describe, expect, it } from "vitest";
12-
import { WebSocket, type ClientOptions, type RawData } from "ws";
12+
import { WebSocket, type RawData } from "ws";
1313
import { parsePairingString } from "../../../chrome-extension/modules/relay-core.js";
1414
import { relayTestKey } from "../../../chrome-extension/relay-key.test-support.js";
1515
import {
@@ -83,33 +83,21 @@ async function relayInventory(port: number): Promise<unknown> {
8383
}
8484
}
8585

86-
function upgradeWithFrames(messages: object[]): {
87-
bytes: number;
88-
finishRequest: NonNullable<ClientOptions["finishRequest"]>;
89-
} {
90-
const frames = messages.map((message) => {
91-
const payload = Buffer.from(JSON.stringify(message));
92-
const extended = payload.length >= 126;
93-
const header = Buffer.alloc(extended ? 8 : 6);
94-
header[0] = 0x81;
95-
header[1] = 0x80 | (extended ? 126 : payload.length);
96-
if (extended) {
97-
header.writeUInt16BE(payload.length, 2);
98-
}
99-
// The fixed zero mask leaves these synthetic payload bytes unchanged.
100-
return Buffer.concat([header, payload]);
101-
});
102-
const finishRequest: NonNullable<ClientOptions["finishRequest"]> = (request) => {
103-
request.once("socket", (socket) => {
104-
socket.once("connect", () => {
105-
socket.cork();
106-
request.end();
107-
socket.write(Buffer.concat(frames));
108-
socket.uncork();
109-
});
110-
});
111-
};
112-
return { bytes: frames.reduce((sum, frame) => sum + frame.byteLength, 0), finishRequest };
86+
function encodeUpgradeHead(messages: object[]): Buffer {
87+
return Buffer.concat(
88+
messages.map((message) => {
89+
const payload = Buffer.from(JSON.stringify(message));
90+
const extended = payload.length >= 126;
91+
const header = Buffer.alloc(extended ? 8 : 6);
92+
header[0] = 0x81;
93+
header[1] = 0x80 | (extended ? 126 : payload.length);
94+
if (extended) {
95+
header.writeUInt16BE(payload.length, 2);
96+
}
97+
// The fixed zero mask leaves these synthetic payload bytes unchanged.
98+
return Buffer.concat([header, payload]);
99+
}),
100+
);
113101
}
114102

115103
function rawDataText(data: RawData): string {
@@ -219,14 +207,29 @@ describe.sequential("local Gateway extension relay wakeup", () => {
219207
OPENCLAW_GATEWAY_PORT: String(gatewayPort),
220208
},
221209
async () => {
210+
const inventory = {
211+
type: "tabs",
212+
tabs: [
213+
{
214+
tabId: 7,
215+
url: "https://example.test/initial",
216+
title: "Coalesced inventory",
217+
active: true,
218+
},
219+
],
220+
};
221+
const coalesced =
222+
legacy === "head" ? encodeUpgradeHead([EXTENSION_HELLO, inventory]) : undefined;
222223
const gatewayServer = http.createServer((_req, res) => {
223224
res.writeHead(426);
224225
res.end();
225226
});
226227
let upgradeHeadBytes = 0;
227228
gatewayServer.on("upgrade", (req, socket, head) => {
228-
upgradeHeadBytes = head.byteLength;
229-
void handleGatewayExtensionUpgrade(req, socket, head);
229+
// TCP writes cannot guarantee Node's upgrade-head size; supply that exact boundary.
230+
const initialHead = coalesced ?? head;
231+
upgradeHeadBytes = initialHead.byteLength;
232+
void handleGatewayExtensionUpgrade(req, socket, initialHead);
230233
});
231234
let extension: WebSocket | undefined;
232235
let daemon: Awaited<ReturnType<typeof runExtensionRelayDaemon>> | undefined;
@@ -261,22 +264,8 @@ describe.sequential("local Gateway extension relay wakeup", () => {
261264
const protocols = legacy
262265
? ["openclaw-extension-relay", `openclaw-extension-token.${RELAY_KEY}`]
263266
: BROWSER_RELAY_EXTENSION_SUBPROTOCOL;
264-
const inventory = {
265-
type: "tabs",
266-
tabs: [
267-
{
268-
tabId: 7,
269-
url: "https://example.test/initial",
270-
title: "Coalesced inventory",
271-
active: true,
272-
},
273-
],
274-
};
275-
const coalesced =
276-
legacy === "head" ? upgradeWithFrames([EXTENSION_HELLO, inventory]) : undefined;
277267
extension = new WebSocket(parsed.relayUrl, protocols, {
278268
origin: "chrome-extension://gateway-wakeup-integration",
279-
finishRequest: coalesced?.finishRequest,
280269
});
281270
await once(extension, "open");
282271
if (!legacy) {
@@ -307,7 +296,7 @@ describe.sequential("local Gateway extension relay wakeup", () => {
307296
expect(JSON.parse(rawDataText(okData))).toMatchObject({ type: "auth.ok", v: 2 });
308297
}
309298
if (legacy === "head") {
310-
expect(upgradeHeadBytes).toBe(coalesced?.bytes);
299+
expect(upgradeHeadBytes).toBe(coalesced?.byteLength);
311300
} else {
312301
extension.send(JSON.stringify(EXTENSION_HELLO));
313302
}

‎extensions/browser/src/browser/extension-relay/owner-client.ts‎

Lines changed: 23 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,9 @@ import {
1414
type RelayOwnerStatus,
1515
} from "./owner-protocol.js";
1616

17+
const nullableIdResult = z.string().nullable();
18+
const streamIdResult = z.number().int().positive();
19+
1720
type OwnerStream = {
1821
send: (raw: string) => void;
1922
close: () => Promise<void>;
@@ -43,23 +46,12 @@ export class RelayOwnerClient {
4346
private retirementAcknowledged = false;
4447
private closing: Promise<void> | undefined;
4548

46-
private constructor(
47-
private readonly ws: WebSocket,
48-
readonly owner: string,
49-
) {
49+
private constructor(private readonly ws: WebSocket) {
5050
ws.on("message", (raw) => {
5151
const parsed = parseStrictJsonObject(rawDataToString(raw));
5252
if (relayOwnerRetired.safeParse(parsed).success) {
5353
this.retirementAcknowledged = true;
54-
this.closed = true;
55-
for (const pending of this.pending.values()) {
56-
pending.reject(new Error("Relay owner retired"));
57-
}
58-
this.pending.clear();
59-
for (const stream of this.streams.values()) {
60-
stream.onClose?.();
61-
}
62-
this.streams.clear();
54+
this.invalidate("Relay owner retired");
6355
return;
6456
}
6557
const reply = relayOwnerReply.safeParse(parsed);
@@ -86,17 +78,19 @@ export class RelayOwnerClient {
8678
}
8779
ws.close(4003, "invalid relay owner response");
8880
});
89-
ws.once("close", () => {
90-
this.closed = true;
91-
for (const pending of this.pending.values()) {
92-
pending.reject(new Error("Relay owner connection lost"));
93-
}
94-
this.pending.clear();
95-
for (const stream of this.streams.values()) {
96-
stream.onClose?.();
97-
}
98-
this.streams.clear();
99-
});
81+
ws.once("close", () => this.invalidate("Relay owner connection lost"));
82+
}
83+
84+
private invalidate(message: string): void {
85+
this.closed = true;
86+
for (const pending of this.pending.values()) {
87+
pending.reject(new Error(message));
88+
}
89+
this.pending.clear();
90+
for (const stream of this.streams.values()) {
91+
stream.onClose?.();
92+
}
93+
this.streams.clear();
10094
}
10195

10296
static async connect(params: {
@@ -105,8 +99,8 @@ export class RelayOwnerClient {
10599
token: string;
106100
signal: AbortSignal;
107101
}) {
108-
const { ws, owner } = await authenticateRelayOwner(params);
109-
return new RelayOwnerClient(ws, owner);
102+
const { ws } = await authenticateRelayOwner(params);
103+
return new RelayOwnerClient(ws);
110104
}
111105

112106
adoptProfileLease(assertCurrent: () => void): void {
@@ -162,10 +156,7 @@ export class RelayOwnerClient {
162156
): Promise<RelayOperationReference> {
163157
this.assertCurrent();
164158
assertOperationCurrent();
165-
const ref = z
166-
.string()
167-
.nullable()
168-
.parse(await this.request("capture", { targetId }));
159+
const ref = nullableIdResult.parse(await this.request("capture", { targetId }));
169160
try {
170161
this.assertCurrent();
171162
assertOperationCurrent();
@@ -186,10 +177,7 @@ export class RelayOwnerClient {
186177
return {
187178
resolve: async () => {
188179
assertReference();
189-
const target = z
190-
.string()
191-
.nullable()
192-
.parse(await this.request("resolve", { ref }));
180+
const target = nullableIdResult.parse(await this.request("resolve", { ref }));
193181
assertReference();
194182
return target ?? undefined;
195183
},
@@ -223,11 +211,7 @@ export class RelayOwnerClient {
223211

224212
private async openStream(op: "cdp.open" | "ingress.open", ref?: string): Promise<OwnerStream> {
225213
this.assertCurrent();
226-
const id = z
227-
.number()
228-
.int()
229-
.positive()
230-
.parse(await this.request(op, ref ? { ref } : {}));
214+
const id = streamIdResult.parse(await this.request(op, ref ? { ref } : {}));
231215
this.assertCurrent();
232216
let closed = false;
233217
let closing: Promise<void> | undefined;

‎extensions/browser/src/browser/extension-relay/relay-access.ts‎

Lines changed: 7 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -13,32 +13,24 @@ export type BorrowedRelayAccess = {
1313
export type ExtensionRelayResource = ExtensionRelayHandle | BorrowedRelayAccess;
1414

1515
// Prepared by the profile lifecycle only. This registry never discovers keys or listeners.
16-
const borrowedCdpAccess = new Map<
17-
string,
18-
{ relay: BorrowedRelayAccess; assertCurrent: () => void }
19-
>();
16+
const borrowedCdpAccess = new Map<string, { relay: BorrowedRelayAccess }>();
2017

2118
export function registerBorrowedRelayCdpAccess(
2219
cdpUrl: string,
2320
relay: BorrowedRelayAccess,
24-
assertCurrent: () => void,
2521
): () => void {
26-
const entry = { relay, assertCurrent };
27-
borrowedCdpAccess.set(cdpUrl.replace(/\/$/u, ""), entry);
22+
const key = cdpUrl.replace(/\/$/u, "");
23+
const entry = { relay };
24+
borrowedCdpAccess.set(key, entry);
2825
return () => {
29-
const key = cdpUrl.replace(/\/$/u, "");
3026
if (borrowedCdpAccess.get(key) === entry) {
3127
borrowedCdpAccess.delete(key);
3228
}
3329
};
3430
}
3531

3632
export function getBorrowedRelayCdpAccess(cdpUrl: string): BorrowedRelayAccess | undefined {
37-
const entry = borrowedCdpAccess.get(cdpUrl.replace(/\/$/u, ""));
38-
if (!entry) {
39-
return undefined;
40-
}
41-
entry.assertCurrent();
42-
entry.relay.client.assertCurrent();
43-
return entry.relay;
33+
const relay = borrowedCdpAccess.get(cdpUrl.replace(/\/$/u, ""))?.relay;
34+
relay?.client.assertCurrent();
35+
return relay;
4436
}

‎extensions/browser/src/browser/extension-relay/relay-bridge.ts‎

Lines changed: 15 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -441,12 +441,9 @@ export class ExtensionRelayBridge {
441441
if (!client.autoAttach) {
442442
continue;
443443
}
444-
void this.withAttachedTab(client, info.tabId, ({ targetId, sessionId }) => {
444+
void this.withAttachedTab(client, info.tabId, (attached) => {
445445
if (client.autoAttach) {
446-
this.announceAttachedTab(info.tabId, targetId, sessionId, {
447-
onlyAutoAttach: false,
448-
onlyClient: client,
449-
});
446+
this.announceAttachedTab(info.tabId, attached, [client]);
450447
}
451448
}).catch((err: unknown) =>
452449
log.warn(`auto-attach of accessible tab ${info.tabId} failed: ${String(err)}`),
@@ -612,27 +609,21 @@ export class ExtensionRelayBridge {
612609

613610
private announceAttachedTab(
614611
tabId: number,
615-
targetId: string,
616-
sessionId: string,
617-
opts: { onlyAutoAttach: boolean; onlyClient?: CdpClientState },
612+
attached: { targetId: string; sessionId: string },
613+
recipients: readonly CdpClientState[],
618614
): void {
619615
const tab = this.tabs.get(tabId);
616+
const { targetId, sessionId } = attached;
620617
if (tab?.target?.sessionId !== sessionId) {
621618
return;
622619
}
623-
const event = {
624-
method: "Target.attachedToTarget",
625-
params: {
626-
sessionId,
627-
targetInfo: this.targetInfoForTab(tab, targetId),
628-
waitingForDebugger: false,
629-
},
620+
const params = {
621+
sessionId,
622+
targetInfo: this.targetInfoForTab(tab, targetId),
623+
waitingForDebugger: false,
630624
};
631-
const recipients = opts.onlyClient
632-
? [opts.onlyClient]
633-
: [...this.clients].filter((client) => !opts.onlyAutoAttach || client.autoAttach);
634625
for (const client of recipients) {
635-
this.sessions.announce(client, sessionId, sessionId, event.params);
626+
this.sessions.announce(client, sessionId, sessionId, params);
636627
}
637628
}
638629

@@ -843,13 +834,9 @@ export class ExtensionRelayBridge {
843834
client,
844835
tabId,
845836
(attached) => {
846-
this.announceAttachedTab(tabId, attached.targetId, attached.sessionId, {
847-
onlyAutoAttach: true,
848-
});
849-
this.announceAttachedTab(tabId, attached.targetId, attached.sessionId, {
850-
onlyAutoAttach: false,
851-
onlyClient: client,
852-
});
837+
const recipients = [...this.clients].filter((recipient) => recipient.autoAttach);
838+
this.announceAttachedTab(tabId, attached, recipients);
839+
this.announceAttachedTab(tabId, attached, [client]);
853840
this.respond(client, request, { targetId: attached.targetId });
854841
},
855842
typeof created.targetId === "string" ? created.targetId : undefined,
@@ -1063,12 +1050,9 @@ export class ExtensionRelayBridge {
10631050
if (autoAttach) {
10641051
const attachResults = await Promise.allSettled(
10651052
[...this.tabs.keys()].map((tabId) =>
1066-
this.withAttachedTab(client, tabId, ({ targetId, sessionId }) => {
1053+
this.withAttachedTab(client, tabId, (attached) => {
10671054
if (client.autoAttach) {
1068-
this.announceAttachedTab(tabId, targetId, sessionId, {
1069-
onlyAutoAttach: false,
1070-
onlyClient: client,
1071-
});
1055+
this.announceAttachedTab(tabId, attached, [client]);
10721056
}
10731057
}),
10741058
),

‎extensions/browser/src/browser/extension-relay/relay-lifecycle.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -261,7 +261,6 @@ async function ensureDesiredRelay(params: {
261261
unregister = registerBorrowedRelayCdpAccess(
262262
`http://127.0.0.1:${profile.cdpPort}`,
263263
borrowed,
264-
assertCurrent,
265264
);
266265
}
267266
actor.cleanupRelays.add(handle);

0 commit comments

Comments
 (0)