Skip to content

Commit 5657318

Browse files
committed
perf: split canvas a2ui shared imports
1 parent 40e4a00 commit 5657318

4 files changed

Lines changed: 90 additions & 74 deletions

File tree

‎src/canvas-host/a2ui-shared.ts‎

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
import { lowercasePreservingWhitespace } from "../shared/string-coerce.js";
2+
3+
export const A2UI_PATH = "/__openclaw__/a2ui";
4+
5+
export const CANVAS_HOST_PATH = "/__openclaw__/canvas";
6+
7+
export const CANVAS_WS_PATH = "/__openclaw__/ws";
8+
9+
export function isA2uiPath(pathname: string): boolean {
10+
return pathname === A2UI_PATH || pathname.startsWith(`${A2UI_PATH}/`);
11+
}
12+
13+
export function injectCanvasLiveReload(html: string): string {
14+
const snippet = `
15+
<script>
16+
(() => {
17+
// Cross-platform action bridge helper.
18+
// Works on:
19+
// - iOS: window.webkit.messageHandlers.openclawCanvasA2UIAction.postMessage(...)
20+
// - Android: window.openclawCanvasA2UIAction.postMessage(...)
21+
const handlerNames = ["openclawCanvasA2UIAction"];
22+
function postToNode(payload) {
23+
try {
24+
const raw = typeof payload === "string" ? payload : JSON.stringify(payload);
25+
for (const name of handlerNames) {
26+
const iosHandler = globalThis.webkit?.messageHandlers?.[name];
27+
if (iosHandler && typeof iosHandler.postMessage === "function") {
28+
iosHandler.postMessage(raw);
29+
return true;
30+
}
31+
const androidHandler = globalThis[name];
32+
if (androidHandler && typeof androidHandler.postMessage === "function") {
33+
// Important: call as a method on the interface object (binding matters on Android WebView).
34+
androidHandler.postMessage(raw);
35+
return true;
36+
}
37+
}
38+
} catch {}
39+
return false;
40+
}
41+
function sendUserAction(userAction) {
42+
const id =
43+
(userAction && typeof userAction.id === "string" && userAction.id.trim()) ||
44+
(globalThis.crypto?.randomUUID?.() ?? String(Date.now()));
45+
const action = { ...userAction, id };
46+
return postToNode({ userAction: action });
47+
}
48+
globalThis.OpenClaw = globalThis.OpenClaw ?? {};
49+
globalThis.OpenClaw.postMessage = postToNode;
50+
globalThis.OpenClaw.sendUserAction = sendUserAction;
51+
globalThis.openclawPostMessage = postToNode;
52+
globalThis.openclawSendUserAction = sendUserAction;
53+
54+
try {
55+
const cap = new URLSearchParams(location.search).get("oc_cap");
56+
const proto = location.protocol === "https:" ? "wss" : "ws";
57+
const capQuery = cap ? "?oc_cap=" + encodeURIComponent(cap) : "";
58+
const ws = new WebSocket(proto + "://" + location.host + ${JSON.stringify(CANVAS_WS_PATH)} + capQuery);
59+
ws.onmessage = (ev) => {
60+
if (String(ev.data || "") === "reload") location.reload();
61+
};
62+
} catch {}
63+
})();
64+
</script>
65+
`.trim();
66+
67+
const idx = lowercasePreservingWhitespace(html).lastIndexOf("</body>");
68+
if (idx >= 0) {
69+
return `${html.slice(0, idx)}\n${snippet}\n${html.slice(idx)}`;
70+
}
71+
return `${html}\n${snippet}\n`;
72+
}

‎src/canvas-host/a2ui.ts‎

Lines changed: 9 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,16 @@ import path from "node:path";
44
import { fileURLToPath } from "node:url";
55
import { detectMime } from "../media/mime.js";
66
import { lowercasePreservingWhitespace } from "../shared/string-coerce.js";
7+
import { A2UI_PATH, injectCanvasLiveReload, isA2uiPath } from "./a2ui-shared.js";
78
import { resolveFileWithinRoot } from "./file-resolver.js";
89

9-
export const A2UI_PATH = "/__openclaw__/a2ui";
10-
11-
export const CANVAS_HOST_PATH = "/__openclaw__/canvas";
12-
13-
export const CANVAS_WS_PATH = "/__openclaw__/ws";
10+
export {
11+
A2UI_PATH,
12+
CANVAS_HOST_PATH,
13+
CANVAS_WS_PATH,
14+
injectCanvasLiveReload,
15+
isA2uiPath,
16+
} from "./a2ui-shared.js";
1417

1518
let cachedA2uiRootReal: string | null | undefined;
1619
let resolvingA2uiRoot: Promise<string | null> | null = null;
@@ -79,67 +82,6 @@ async function resolveA2uiRootReal(): Promise<string | null> {
7982
return resolvingA2uiRoot;
8083
}
8184

82-
export function injectCanvasLiveReload(html: string): string {
83-
const snippet = `
84-
<script>
85-
(() => {
86-
// Cross-platform action bridge helper.
87-
// Works on:
88-
// - iOS: window.webkit.messageHandlers.openclawCanvasA2UIAction.postMessage(...)
89-
// - Android: window.openclawCanvasA2UIAction.postMessage(...)
90-
const handlerNames = ["openclawCanvasA2UIAction"];
91-
function postToNode(payload) {
92-
try {
93-
const raw = typeof payload === "string" ? payload : JSON.stringify(payload);
94-
for (const name of handlerNames) {
95-
const iosHandler = globalThis.webkit?.messageHandlers?.[name];
96-
if (iosHandler && typeof iosHandler.postMessage === "function") {
97-
iosHandler.postMessage(raw);
98-
return true;
99-
}
100-
const androidHandler = globalThis[name];
101-
if (androidHandler && typeof androidHandler.postMessage === "function") {
102-
// Important: call as a method on the interface object (binding matters on Android WebView).
103-
androidHandler.postMessage(raw);
104-
return true;
105-
}
106-
}
107-
} catch {}
108-
return false;
109-
}
110-
function sendUserAction(userAction) {
111-
const id =
112-
(userAction && typeof userAction.id === "string" && userAction.id.trim()) ||
113-
(globalThis.crypto?.randomUUID?.() ?? String(Date.now()));
114-
const action = { ...userAction, id };
115-
return postToNode({ userAction: action });
116-
}
117-
globalThis.OpenClaw = globalThis.OpenClaw ?? {};
118-
globalThis.OpenClaw.postMessage = postToNode;
119-
globalThis.OpenClaw.sendUserAction = sendUserAction;
120-
globalThis.openclawPostMessage = postToNode;
121-
globalThis.openclawSendUserAction = sendUserAction;
122-
123-
try {
124-
const cap = new URLSearchParams(location.search).get("oc_cap");
125-
const proto = location.protocol === "https:" ? "wss" : "ws";
126-
const capQuery = cap ? "?oc_cap=" + encodeURIComponent(cap) : "";
127-
const ws = new WebSocket(proto + "://" + location.host + ${JSON.stringify(CANVAS_WS_PATH)} + capQuery);
128-
ws.onmessage = (ev) => {
129-
if (String(ev.data || "") === "reload") location.reload();
130-
};
131-
} catch {}
132-
})();
133-
</script>
134-
`.trim();
135-
136-
const idx = lowercasePreservingWhitespace(html).lastIndexOf("</body>");
137-
if (idx >= 0) {
138-
return `${html.slice(0, idx)}\n${snippet}\n${html.slice(idx)}`;
139-
}
140-
return `${html}\n${snippet}\n`;
141-
}
142-
14385
export async function handleA2uiHttpRequest(
14486
req: IncomingMessage,
14587
res: ServerResponse,
@@ -150,8 +92,7 @@ export async function handleA2uiHttpRequest(
15092
}
15193

15294
const url = new URL(urlRaw, "http://localhost");
153-
const basePath =
154-
url.pathname === A2UI_PATH || url.pathname.startsWith(`${A2UI_PATH}/`) ? A2UI_PATH : undefined;
95+
const basePath = isA2uiPath(url.pathname) ? A2UI_PATH : undefined;
15596
if (!basePath) {
15697
return false;
15798
}

‎src/canvas-host/server.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,8 @@ import {
99
A2UI_PATH,
1010
CANVAS_HOST_PATH,
1111
CANVAS_WS_PATH,
12-
handleA2uiHttpRequest,
1312
injectCanvasLiveReload,
14-
} from "./a2ui.js";
13+
} from "./a2ui-shared.js";
1514

1615
type MockWatcher = {
1716
on: (event: string, cb: (...args: unknown[]) => void) => MockWatcher;
@@ -106,6 +105,7 @@ async function captureHandlerResponse(
106105
}
107106

108107
async function captureA2uiResponse(url: string, method = "GET"): Promise<CapturedResponse> {
108+
const { handleA2uiHttpRequest } = await import("./a2ui.js");
109109
return await captureHttpResponse(handleA2uiHttpRequest, url, method);
110110
}
111111

‎src/canvas-host/server.ts‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,9 @@ import { ensureDir, resolveUserPath } from "../utils.js";
2020
import {
2121
CANVAS_HOST_PATH,
2222
CANVAS_WS_PATH,
23-
handleA2uiHttpRequest,
2423
injectCanvasLiveReload,
25-
} from "./a2ui.js";
24+
isA2uiPath,
25+
} from "./a2ui-shared.js";
2626
import { normalizeUrlPath, resolveFileWithinRoot } from "./file-resolver.js";
2727

2828
type ChokidarWatch = typeof import("chokidar").watch;
@@ -469,8 +469,11 @@ export async function startCanvasHost(opts: CanvasHostServerOpts): Promise<Canva
469469
return;
470470
}
471471
void (async () => {
472-
if (await handleA2uiHttpRequest(req, res)) {
473-
return;
472+
if (req.url && isA2uiPath(new URL(req.url, "http://localhost").pathname)) {
473+
const { handleA2uiHttpRequest } = await import("./a2ui.js");
474+
if (await handleA2uiHttpRequest(req, res)) {
475+
return;
476+
}
474477
}
475478
if (await handler.handleHttpRequest(req, res)) {
476479
return;

0 commit comments

Comments
 (0)