Skip to content

Commit 2e0f6d5

Browse files
committed
fix: recover browser routing and Discord voice context
1 parent 334e7f3 commit 2e0f6d5

16 files changed

Lines changed: 863 additions & 165 deletions

‎CHANGELOG.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,8 @@ Docs: https://docs.openclaw.ai
3333

3434
### Fixes
3535

36+
- **Browser auto-routing:** fall back to the Gateway host when an implicitly selected browser node reports that its control host is unreachable, while preserving explicit node pins and ambiguous action failures.
37+
- **Discord voice participant context:** maintain the live Gateway voice-state roster and include current channel participants in authorized voice agent turns so agents can answer who is present.
3638
- **OC Path JSONC insertion:** patch object and array insertions through `jsonc-parser` so comments, trailing commas, and CRLF formatting survive. (#106847)
3739
- **Control UI realtime Talk feedback:** request browser echo cancellation, noise suppression, and automatic gain control for every microphone transport, and keep PCM capture processors connected through zero-gain sinks so microphone input cannot play locally.
3840
- **Agent source-reply recovery:** preserve current-chat delivery evidence for message sends executed through Code Mode, preventing successful replies from triggering a redundant retry and misleading delivery-failure diagnostic.
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* Browser-node fallback classification.
3+
*
4+
* Only the node host's explicit pre-dispatch reachability failure is safe to
5+
* retry on the Gateway host. Other failures may follow a mutating action.
6+
*/
7+
const BROWSER_CONTROL_HOST_UNREACHABLE = /\bbrowser control host is not reachable\b/i;
8+
9+
export function isBrowserControlHostUnavailableError(value: unknown): boolean {
10+
const seen = new Set<object>();
11+
12+
const visit = (candidate: unknown, depth: number): boolean => {
13+
if (typeof candidate === "string") {
14+
return BROWSER_CONTROL_HOST_UNREACHABLE.test(candidate);
15+
}
16+
if (!candidate || typeof candidate !== "object" || depth > 3 || seen.has(candidate)) {
17+
return false;
18+
}
19+
seen.add(candidate);
20+
const record = candidate as Record<string, unknown>;
21+
if (
22+
typeof record.message === "string" &&
23+
BROWSER_CONTROL_HOST_UNREACHABLE.test(record.message)
24+
) {
25+
return true;
26+
}
27+
return [record.error, record.cause, record.details, record.nodeError].some((entry) =>
28+
visit(entry, depth + 1),
29+
);
30+
};
31+
32+
return visit(value, 0);
33+
}
Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,167 @@
1+
import crypto from "node:crypto";
2+
import { createSubsystemLogger } from "openclaw/plugin-sdk/runtime-env";
3+
import { isBrowserControlHostUnavailableError } from "./browser-node-fallback.js";
4+
import {
5+
BROWSER_PROXY_ERROR_ENVELOPE,
6+
parseBrowserProxyFailure,
7+
type BrowserProxyEnvelope,
8+
type BrowserProxySuccess,
9+
} from "./browser-proxy-envelope.js";
10+
import {
11+
applyBrowserProxyPaths,
12+
callGatewayTool,
13+
fetchBrowserJson,
14+
persistBrowserProxyFiles,
15+
} from "./browser-tool.runtime.js";
16+
import { BrowserServiceError } from "./browser/client-fetch.js";
17+
18+
const logger = createSubsystemLogger("browser");
19+
const DEFAULT_BROWSER_PROXY_TIMEOUT_MS = 20_000;
20+
const BROWSER_PROXY_GATEWAY_TIMEOUT_SLACK_MS = 5_000;
21+
22+
class BrowserNodeControlHostUnavailableError extends Error {
23+
constructor(cause: unknown) {
24+
super("auto-selected browser node control host unavailable", { cause });
25+
this.name = "BrowserNodeControlHostUnavailableError";
26+
}
27+
}
28+
29+
export type BrowserProxyRequest = ((params: {
30+
method: string;
31+
path: string;
32+
query?: Record<string, string | number | boolean | undefined>;
33+
body?: unknown;
34+
timeoutMs?: number;
35+
profile?: string;
36+
}) => Promise<unknown>) & {
37+
isHostFallbackActive: () => boolean;
38+
};
39+
40+
function unwrapBrowserProxyPayload(
41+
payload: { payload?: unknown; payloadJSON?: unknown } | null,
42+
): BrowserProxyEnvelope | null {
43+
if (payload?.payload !== undefined) {
44+
return payload.payload as BrowserProxyEnvelope;
45+
}
46+
if (typeof payload?.payloadJSON !== "string" || !payload.payloadJSON.trim()) {
47+
return null;
48+
}
49+
try {
50+
return JSON.parse(payload.payloadJSON) as BrowserProxyEnvelope;
51+
} catch {
52+
return null;
53+
}
54+
}
55+
56+
async function callBrowserProxy(params: {
57+
nodeId: string;
58+
markControlHostUnavailable: boolean;
59+
method: string;
60+
path: string;
61+
query?: Record<string, string | number | boolean | undefined>;
62+
body?: unknown;
63+
timeoutMs?: number;
64+
profile?: string;
65+
}): Promise<BrowserProxySuccess> {
66+
const proxyTimeoutMs =
67+
typeof params.timeoutMs === "number" && Number.isFinite(params.timeoutMs)
68+
? Math.max(1, Math.floor(params.timeoutMs))
69+
: DEFAULT_BROWSER_PROXY_TIMEOUT_MS;
70+
const gatewayTimeoutMs = proxyTimeoutMs + BROWSER_PROXY_GATEWAY_TIMEOUT_SLACK_MS;
71+
let payload: { payload?: unknown; payloadJSON?: unknown } | null;
72+
try {
73+
payload = await callGatewayTool<{ payload?: unknown; payloadJSON?: unknown }>(
74+
"node.invoke",
75+
{ timeoutMs: gatewayTimeoutMs },
76+
{
77+
nodeId: params.nodeId,
78+
command: "browser.proxy",
79+
// node.invoke owns a separate watchdog from browser.proxy. Keep both
80+
// bounded, with enough outer slack for the proxy result to cross back.
81+
timeoutMs: gatewayTimeoutMs,
82+
params: {
83+
method: params.method,
84+
path: params.path,
85+
query: params.query,
86+
body: params.body,
87+
timeoutMs: proxyTimeoutMs,
88+
profile: params.profile,
89+
errorEnvelope: BROWSER_PROXY_ERROR_ENVELOPE,
90+
},
91+
idempotencyKey: crypto.randomUUID(),
92+
},
93+
{ scopes: ["operator.admin"] },
94+
);
95+
} catch (error) {
96+
if (params.markControlHostUnavailable && isBrowserControlHostUnavailableError(error)) {
97+
throw new BrowserNodeControlHostUnavailableError(error);
98+
}
99+
throw error;
100+
}
101+
const parsed = unwrapBrowserProxyPayload(payload);
102+
const failure = parseBrowserProxyFailure(parsed);
103+
if (failure) {
104+
const { status, body } = failure.error;
105+
throw new BrowserServiceError(body.error, "reason" in body ? body : undefined, status);
106+
}
107+
if (!parsed || typeof parsed !== "object" || !("result" in parsed)) {
108+
throw new Error("browser proxy failed");
109+
}
110+
return parsed;
111+
}
112+
113+
async function callLocalBrowserControl(params: Parameters<BrowserProxyRequest>[0]) {
114+
const url = new URL(params.path, "http://localhost");
115+
for (const [key, value] of Object.entries(params.query ?? {})) {
116+
if (value !== undefined) {
117+
url.searchParams.set(key, String(value));
118+
}
119+
}
120+
if (params.profile) {
121+
url.searchParams.set("profile", params.profile);
122+
}
123+
return await fetchBrowserJson(`${url.pathname}${url.search}`, {
124+
method: params.method,
125+
body: params.body === undefined ? undefined : JSON.stringify(params.body),
126+
timeoutMs: params.timeoutMs,
127+
});
128+
}
129+
130+
export function createBrowserNodeProxyRequest(params: {
131+
nodeTarget: { nodeId: string; label?: string };
132+
allowAutomaticHostFallback: boolean;
133+
}): BrowserProxyRequest {
134+
let hostFallbackActive = false;
135+
const dispatch = async (request: Parameters<BrowserProxyRequest>[0]) => {
136+
if (hostFallbackActive) {
137+
return await callLocalBrowserControl(request);
138+
}
139+
try {
140+
const proxy = await callBrowserProxy({
141+
nodeId: params.nodeTarget.nodeId,
142+
markControlHostUnavailable: params.allowAutomaticHostFallback,
143+
...request,
144+
});
145+
const mapping = await persistBrowserProxyFiles(proxy.files);
146+
applyBrowserProxyPaths(proxy.result, mapping);
147+
return proxy.result;
148+
} catch (error) {
149+
if (
150+
!params.allowAutomaticHostFallback ||
151+
!(error instanceof BrowserNodeControlHostUnavailableError)
152+
) {
153+
throw error;
154+
}
155+
// This exact node-host failure occurs before any browser action. Retrying
156+
// other failures could duplicate a mutating operation.
157+
hostFallbackActive = true;
158+
logger.warn(
159+
`browser node ${params.nodeTarget.label ?? params.nodeTarget.nodeId} control host unavailable; falling back to Gateway host`,
160+
);
161+
return await callLocalBrowserControl(request);
162+
}
163+
};
164+
return Object.assign(dispatch, {
165+
isHostFallbackActive: () => hostFallbackActive,
166+
});
167+
}

‎extensions/browser/src/browser-tool.runtime.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ export {
5959
browserStop,
6060
browserTabs,
6161
} from "./browser/client.js";
62+
export { fetchBrowserJson } from "./browser/client-fetch.js";
6263
export { resolveBrowserConfig, resolveProfile } from "./browser/config.js";
6364
export { DEFAULT_AI_SNAPSHOT_MAX_CHARS } from "./browser/constants.js";
6465
export { resolveExistingUploadPaths } from "./browser/paths.js";

‎extensions/browser/src/browser-tool.test.ts‎

Lines changed: 143 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,13 @@ const sessionTabRegistryMocks = vi.hoisted(() => ({
186186
vi.mock("./browser/session-tab-registry.js", () => sessionTabRegistryMocks);
187187

188188
const toolCommonMocks = vi.hoisted(() => ({
189+
fetchBrowserJson: vi.fn(
190+
async (..._args: unknown[]): Promise<Record<string, unknown>> => ({
191+
ok: true,
192+
running: true,
193+
source: "gateway-host",
194+
}),
195+
),
189196
imageResultFromFile: vi.fn(),
190197
describeImageFile: vi.fn(async () => ({ text: undefined, decision: { outcome: "skipped" } })),
191198
normalizeBrowserScreenshot: vi.fn(async (buffer: Buffer) => ({ buffer })),
@@ -233,6 +240,7 @@ vi.mock("./browser-tool.runtime.js", () => {
233240
...configMocks,
234241
...gatewayMocks,
235242
...sessionTabRegistryMocks,
243+
fetchBrowserJson: toolCommonMocks.fetchBrowserJson,
236244
getRuntimeConfig: configMocks.loadConfig,
237245
resolveRuntimeImageSanitization: () => {
238246
const configured = configMocks.loadConfig().agents?.defaults?.imageMaxDimensionPx;
@@ -330,6 +338,11 @@ function resetBrowserToolMocks() {
330338
toolCommonMocks.stageBrowserScreenshotForSharing.mockResolvedValue(
331339
"/tmp/openclaw-media/outbound/share.png",
332340
);
341+
toolCommonMocks.fetchBrowserJson.mockResolvedValue({
342+
ok: true,
343+
running: true,
344+
source: "gateway-host",
345+
});
333346
}
334347

335348
function setResolvedBrowserProfiles(
@@ -999,6 +1012,136 @@ describe("browser tool snapshot maxChars", () => {
9991012
expect(browserClientMocks.browserStatus).not.toHaveBeenCalled();
10001013
});
10011014

1015+
it("falls back to the Gateway host when an auto-selected node has no browser host", async () => {
1016+
mockSingleBrowserProxyNode();
1017+
gatewayMocks.callGatewayTool.mockRejectedValueOnce(
1018+
new Error(
1019+
"Browser control host is not reachable on 127.0.0.1:18791. Start the local OpenClaw browser control host.",
1020+
),
1021+
);
1022+
const tool = createBrowserTool();
1023+
1024+
const result = await tool.execute?.("call-1", { action: "status" });
1025+
1026+
expect(result?.details).toMatchObject({ source: "gateway-host" });
1027+
expect(toolCommonMocks.fetchBrowserJson).toHaveBeenCalledWith("/", {
1028+
method: "GET",
1029+
body: undefined,
1030+
timeoutMs: undefined,
1031+
});
1032+
});
1033+
1034+
it("tracks tabs opened after automatic host fallback", async () => {
1035+
mockSingleBrowserProxyNode();
1036+
gatewayMocks.callGatewayTool.mockRejectedValueOnce(
1037+
new Error("Browser control host is not reachable on 127.0.0.1:18791."),
1038+
);
1039+
toolCommonMocks.fetchBrowserJson.mockResolvedValueOnce({
1040+
targetId: "host-tab-opened",
1041+
url: "https://example.com",
1042+
});
1043+
const tool = createBrowserTool({ agentSessionKey: "agent:main:main" });
1044+
1045+
await tool.execute?.("call-1", { action: "open", url: "https://example.com" });
1046+
1047+
expect(sessionTabRegistryMocks.trackSessionBrowserTab).toHaveBeenCalledWith({
1048+
sessionKey: "agent:main:main",
1049+
targetId: "host-tab-opened",
1050+
baseUrl: undefined,
1051+
profile: undefined,
1052+
});
1053+
});
1054+
1055+
it("touches tabs used after automatic host fallback", async () => {
1056+
mockSingleBrowserProxyNode();
1057+
gatewayMocks.callGatewayTool.mockRejectedValueOnce(
1058+
new Error("Browser control host is not reachable on 127.0.0.1:18791."),
1059+
);
1060+
toolCommonMocks.fetchBrowserJson.mockResolvedValueOnce({
1061+
targetId: "host-tab-used",
1062+
url: "https://example.com/next",
1063+
});
1064+
const tool = createBrowserTool({ agentSessionKey: "agent:main:main" });
1065+
1066+
await tool.execute?.("call-1", {
1067+
action: "navigate",
1068+
url: "https://example.com/next",
1069+
targetId: "host-tab-used",
1070+
});
1071+
1072+
expect(sessionTabRegistryMocks.touchSessionBrowserTab).toHaveBeenCalledWith({
1073+
sessionKey: "agent:main:main",
1074+
targetId: "host-tab-used",
1075+
baseUrl: undefined,
1076+
profile: undefined,
1077+
});
1078+
});
1079+
1080+
it("untracks tabs closed after automatic host fallback", async () => {
1081+
mockSingleBrowserProxyNode();
1082+
gatewayMocks.callGatewayTool.mockRejectedValueOnce(
1083+
new Error("Browser control host is not reachable on 127.0.0.1:18791."),
1084+
);
1085+
toolCommonMocks.fetchBrowserJson.mockResolvedValueOnce({ ok: true });
1086+
const tool = createBrowserTool({ agentSessionKey: "agent:main:main" });
1087+
1088+
await tool.execute?.("call-1", { action: "close", targetId: "host-tab-closed" });
1089+
1090+
expect(sessionTabRegistryMocks.untrackSessionBrowserTab).toHaveBeenCalledWith({
1091+
sessionKey: "agent:main:main",
1092+
targetId: "host-tab-closed",
1093+
baseUrl: undefined,
1094+
profile: undefined,
1095+
});
1096+
});
1097+
1098+
it.each([
1099+
["an explicit node target", { target: "node" }],
1100+
["an explicit node pin", { node: "node-1" }],
1101+
])("does not host-fallback for %s", async (_label, route) => {
1102+
mockSingleBrowserProxyNode();
1103+
gatewayMocks.callGatewayTool.mockRejectedValueOnce(
1104+
new Error("Browser control host is not reachable on 127.0.0.1:18791."),
1105+
);
1106+
const tool = createBrowserTool();
1107+
1108+
await expect(tool.execute?.("call-1", { action: "status", ...route })).rejects.toThrow(
1109+
/Browser control host is not reachable/,
1110+
);
1111+
expect(toolCommonMocks.fetchBrowserJson).not.toHaveBeenCalled();
1112+
});
1113+
1114+
it("does not host-fallback after an ambiguous node failure", async () => {
1115+
mockSingleBrowserProxyNode();
1116+
gatewayMocks.callGatewayTool.mockRejectedValueOnce(new Error("node invoke timed out"));
1117+
const tool = createBrowserTool();
1118+
1119+
await expect(tool.execute?.("call-1", { action: "status" })).rejects.toThrow(
1120+
/node invoke timed out/,
1121+
);
1122+
expect(toolCommonMocks.fetchBrowserJson).not.toHaveBeenCalled();
1123+
});
1124+
1125+
it("does not host-fallback for a browser-service error with similar wording", async () => {
1126+
mockSingleBrowserProxyNode();
1127+
gatewayMocks.callGatewayTool.mockResolvedValueOnce({
1128+
ok: true,
1129+
payload: {
1130+
error: {
1131+
status: 503,
1132+
body: { error: "Browser control host is not reachable during this action" },
1133+
},
1134+
},
1135+
});
1136+
const tool = createBrowserTool();
1137+
1138+
await expect(tool.execute?.("call-1", { action: "status" })).rejects.toMatchObject({
1139+
name: "BrowserServiceError",
1140+
status: 503,
1141+
});
1142+
expect(toolCommonMocks.fetchBrowserJson).not.toHaveBeenCalled();
1143+
});
1144+
10021145
it.each([
10031146
["target=node", { target: "node" }],
10041147
["an explicit node pin", { node: "node-1" }],

0 commit comments

Comments
 (0)