Skip to content

Commit 5c77724

Browse files
authored
fix(canvas): validate A2UI JSONL centrally (#103713)
1 parent 1a9d09a commit 5c77724

6 files changed

Lines changed: 250 additions & 22 deletions

File tree

‎extensions/canvas/index.test.ts‎

Lines changed: 105 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,29 @@
11
// Canvas tests cover index plugin behavior.
2-
import type { AnyAgentTool, OpenClawPluginApi } from "openclaw/plugin-sdk/plugin-entry";
2+
import type {
3+
AnyAgentTool,
4+
OpenClawPluginApi,
5+
OpenClawPluginNodeInvokePolicyContext,
6+
} from "openclaw/plugin-sdk/plugin-entry";
37
import { createTestPluginApi } from "openclaw/plugin-sdk/plugin-test-api";
48
import { beforeEach, describe, expect, it, vi } from "vitest";
59
import canvasPlugin from "./index.js";
610
import { SHOW_WIDGET_REQUIRED_CLIENT_CAPS } from "./src/tool-schema.js";
711

12+
const VALID_A2UI_V08_JSONL = [
13+
JSON.stringify({
14+
surfaceUpdate: {
15+
surfaceId: "main",
16+
components: [
17+
{
18+
id: "root",
19+
component: { Text: { text: { literalString: "Canvas proof" }, usageHint: "body" } },
20+
},
21+
],
22+
},
23+
}),
24+
JSON.stringify({ beginRendering: { surfaceId: "main", root: "root" } }),
25+
].join("\n");
26+
827
const mocks = vi.hoisted(() => {
928
const httpHandler = {
1029
handleHttpRequest: vi.fn(async () => true),
@@ -71,6 +90,8 @@ function registerCanvas() {
7190
registrar: Parameters<OpenClawPluginApi["registerNodeCliFeature"]>[0];
7291
opts: Parameters<OpenClawPluginApi["registerNodeCliFeature"]>[1];
7392
}> = [];
93+
const nodeInvokePolicies: Array<Parameters<OpenClawPluginApi["registerNodeInvokePolicy"]>[0]> =
94+
[];
7495
canvasPlugin.register?.(
7596
createTestPluginApi({
7697
id: "canvas",
@@ -81,10 +102,23 @@ function registerCanvas() {
81102
registerHostedMediaResolver: (resolver) => resolvers.push(resolver),
82103
registerTool: (tool, opts) => tools.push({ tool, opts }),
83104
registerNodeCliFeature: (registrar, opts) => cliFeatures.push({ registrar, opts }),
84-
registerNodeInvokePolicy: vi.fn(),
105+
registerNodeInvokePolicy: (policy) => nodeInvokePolicies.push(policy),
85106
}),
86107
);
87-
return { routes, services, resolvers, tools, cliFeatures };
108+
return { routes, services, resolvers, tools, cliFeatures, nodeInvokePolicies };
109+
}
110+
111+
function createNodeInvokeContext(
112+
params: Partial<OpenClawPluginNodeInvokePolicyContext>,
113+
): OpenClawPluginNodeInvokePolicyContext {
114+
return {
115+
nodeId: "node-1",
116+
command: "canvas.a2ui.pushJSONL",
117+
params: {},
118+
config: {},
119+
invokeNode: vi.fn(async () => ({ ok: true as const })),
120+
...params,
121+
};
88122
}
89123

90124
describe("Canvas plugin entry", () => {
@@ -175,4 +209,72 @@ describe("Canvas plugin entry", () => {
175209
widget_code: "<p>ready</p>",
176210
});
177211
});
212+
213+
it.each([
214+
["malformed pushJSONL", "canvas.a2ui.pushJSONL", { jsonl: "{not-json}" }],
215+
[
216+
"versioned A2UI v0.9 pushJSONL",
217+
"canvas.a2ui.pushJSONL",
218+
{
219+
jsonl: JSON.stringify({ version: "v0.9", deleteSurface: { surfaceId: "main" } }),
220+
},
221+
],
222+
["malformed legacy push JSONL fallback", "canvas.a2ui.push", { jsonl: "{not-json}" }],
223+
])("rejects %s at the final Canvas node policy", async (_label, command, params) => {
224+
const { nodeInvokePolicies } = registerCanvas();
225+
const policy = nodeInvokePolicies[0];
226+
if (!policy) {
227+
throw new Error("Canvas node invoke policy was not registered");
228+
}
229+
const invokeNode = vi.fn(async () => ({ ok: true as const }));
230+
231+
const result = await policy.handle(createNodeInvokeContext({ command, params, invokeNode }));
232+
233+
expect(result).toMatchObject({ ok: false, code: "INVALID_A2UI_JSONL" });
234+
expect(invokeNode).not.toHaveBeenCalled();
235+
});
236+
237+
it("dispatches A2UI v0.8 JSONL unchanged through the final Canvas node policy", async () => {
238+
const { nodeInvokePolicies } = registerCanvas();
239+
const policy = nodeInvokePolicies[0];
240+
if (!policy) {
241+
throw new Error("Canvas node invoke policy was not registered");
242+
}
243+
const invokeNode = vi.fn(async () => ({ ok: true as const }));
244+
245+
const result = await policy.handle(
246+
createNodeInvokeContext({
247+
params: { jsonl: VALID_A2UI_V08_JSONL },
248+
invokeNode,
249+
}),
250+
);
251+
252+
expect(result).toEqual({ ok: true });
253+
expect(invokeNode).toHaveBeenCalledTimes(1);
254+
expect(invokeNode).toHaveBeenCalledWith();
255+
});
256+
257+
it("leaves canonical A2UI message arrays to the native node", async () => {
258+
const { nodeInvokePolicies } = registerCanvas();
259+
const policy = nodeInvokePolicies[0];
260+
if (!policy) {
261+
throw new Error("Canvas node invoke policy was not registered");
262+
}
263+
const invokeNode = vi.fn(async () => ({ ok: true as const }));
264+
265+
const result = await policy.handle(
266+
createNodeInvokeContext({
267+
command: "canvas.a2ui.push",
268+
params: {
269+
messages: [{ deleteSurface: { surfaceId: "main" } }],
270+
jsonl: "{not-used-by-native-node}",
271+
},
272+
invokeNode,
273+
}),
274+
);
275+
276+
expect(result).toEqual({ ok: true });
277+
expect(invokeNode).toHaveBeenCalledTimes(1);
278+
expect(invokeNode).toHaveBeenCalledWith();
279+
});
178280
});

‎extensions/canvas/index.ts‎

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,10 @@
55
import type { IncomingMessage, ServerResponse } from "node:http";
66
import type { Duplex } from "node:stream";
77
import type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
8+
import { formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
89
import { createLazyRuntimeModule } from "openclaw/plugin-sdk/lazy-runtime";
910
import { definePluginEntry, type AnyAgentTool } from "openclaw/plugin-sdk/plugin-entry";
11+
import { validateSupportedA2UIJsonl } from "./src/a2ui-jsonl.js";
1012
import { canvasConfigSchema, isCanvasHostEnabled } from "./src/config.js";
1113
import { A2UI_PATH, CANVAS_HOST_PATH, CANVAS_WS_PATH } from "./src/host/a2ui-shared.js";
1214
import {
@@ -143,7 +145,32 @@ export default definePluginEntry({
143145
commands: CANVAS_NODE_COMMANDS,
144146
defaultPlatforms: ["ios", "android", "macos", "windows", "unknown"],
145147
foregroundRestrictedOnIos: true,
146-
handle: (ctx) => ctx.invokeNode(),
148+
handle: async (ctx) => {
149+
const params =
150+
ctx.params && typeof ctx.params === "object" && !Array.isArray(ctx.params)
151+
? (ctx.params as Record<string, unknown>)
152+
: {};
153+
// Native nodes also accept JSONL under `push` when messages[] is absent.
154+
// Validate that fallback here so callers cannot bypass the JSONL policy.
155+
const usesJsonl =
156+
ctx.command === "canvas.a2ui.pushJSONL" ||
157+
(ctx.command === "canvas.a2ui.push" &&
158+
!Array.isArray(params.messages) &&
159+
Object.hasOwn(params, "jsonl"));
160+
if (usesJsonl) {
161+
const jsonl = typeof params.jsonl === "string" ? params.jsonl : "";
162+
try {
163+
validateSupportedA2UIJsonl(jsonl);
164+
} catch (error) {
165+
return {
166+
ok: false,
167+
code: "INVALID_A2UI_JSONL",
168+
message: formatErrorMessage(error),
169+
};
170+
}
171+
}
172+
return await ctx.invokeNode();
173+
},
147174
});
148175
api.registerTool((ctx) =>
149176
createLazyCanvasTool({

‎extensions/canvas/src/a2ui-jsonl.ts‎

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ const A2UI_ACTION_KEYS = [
99
"createSurface",
1010
] as const;
1111

12-
/** Supported A2UI message dialects accepted by the Canvas host. */
12+
/** A2UI message dialects recognized by the Canvas validator. */
1313
type A2UIVersion = "v0.8" | "v0.9";
1414

1515
/** Builds a minimal A2UI JSONL payload that renders text in a single surface. */
@@ -41,7 +41,7 @@ export function buildA2UITextJsonl(text: string) {
4141
}
4242

4343
/** Validates A2UI JSONL and returns the detected dialect/version metadata. */
44-
export function validateA2UIJsonl(jsonl: string) {
44+
function validateA2UIJsonl(jsonl: string) {
4545
const lines = jsonl.split(/\r?\n/);
4646
const errors: string[] = [];
4747
let sawV08 = false;
@@ -66,14 +66,26 @@ export function validateA2UIJsonl(jsonl: string) {
6666
return;
6767
}
6868
const record = obj as Record<string, unknown>;
69+
const explicitVersion = record.version;
70+
// Bundled v0.8 is strict and unversioned; v0.9 identifies every message.
71+
if (explicitVersion === "v0.8") {
72+
errors.push(`line ${idx + 1}: A2UI v0.8 messages must not include a version field`);
73+
return;
74+
}
75+
if (explicitVersion !== undefined && explicitVersion !== "v0.9") {
76+
errors.push(`line ${idx + 1}: unsupported A2UI version: ${JSON.stringify(explicitVersion)}`);
77+
return;
78+
}
6979
const actionKeys = A2UI_ACTION_KEYS.filter((key) => key in record);
7080
if (actionKeys.length !== 1) {
7181
errors.push(
7282
`line ${idx + 1}: expected exactly one action key (${A2UI_ACTION_KEYS.join(", ")})`,
7383
);
7484
return;
7585
}
76-
if (actionKeys[0] === "createSurface") {
86+
// v0.9 requires an explicit version, but keep recognizing legacy
87+
// createSurface payloads so older generators still fail closed.
88+
if (explicitVersion === "v0.9" || actionKeys[0] === "createSurface") {
7789
sawV09 = true;
7890
} else {
7991
sawV08 = true;
@@ -93,3 +105,12 @@ export function validateA2UIJsonl(jsonl: string) {
93105
const version: A2UIVersion = sawV09 ? "v0.9" : "v0.8";
94106
return { version, messageCount };
95107
}
108+
109+
/** Validates A2UI JSONL against the Canvas runtime's currently supported dialect. */
110+
export function validateSupportedA2UIJsonl(jsonl: string) {
111+
const result = validateA2UIJsonl(jsonl);
112+
if (result.version !== "v0.8") {
113+
throw new Error("Detected unsupported A2UI v0.9 JSONL. OpenClaw currently supports v0.8 only.");
114+
}
115+
return result;
116+
}

‎extensions/canvas/src/cli.ts‎

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ import {
2121
normalizeOptionalString,
2222
} from "openclaw/plugin-sdk/string-coerce-runtime";
2323
import { shortenHomePath } from "openclaw/plugin-sdk/text-utility-runtime";
24-
import { buildA2UITextJsonl, validateA2UIJsonl } from "./a2ui-jsonl.js";
24+
import { buildA2UITextJsonl, validateSupportedA2UIJsonl } from "./a2ui-jsonl.js";
2525
import { canvasSnapshotTempPath, parseCanvasSnapshotPayload } from "./cli-helpers.js";
2626

2727
/** Runtime output surface used by Canvas CLI commands. */
@@ -444,12 +444,7 @@ export function registerNodesCanvasCommands(nodes: Command, deps: CanvasCliDepen
444444
const jsonl = hasText
445445
? buildA2UITextJsonl(opts.text ?? "")
446446
: await fs.readFile(String(opts.jsonl), "utf8");
447-
const { version, messageCount } = validateA2UIJsonl(jsonl);
448-
if (version === "v0.9") {
449-
throw new Error(
450-
"Detected A2UI v0.9 JSONL (createSurface). OpenClaw currently supports v0.8 only.",
451-
);
452-
}
447+
const { messageCount } = validateSupportedA2UIJsonl(jsonl);
453448
await invokeCanvas(deps, opts, "canvas.a2ui.pushJSONL", { jsonl });
454449
if (!opts.json) {
455450
const { ok } = deps.getNodesTheme();

‎extensions/canvas/src/tool.test.ts‎

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,21 @@ import path from "node:path";
55
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
66
import { createCanvasTool } from "./tool.js";
77

8+
const VALID_A2UI_V08_JSONL = [
9+
JSON.stringify({
10+
surfaceUpdate: {
11+
surfaceId: "main",
12+
components: [
13+
{
14+
id: "root",
15+
component: { Text: { text: { literalString: "Canvas proof" }, usageHint: "body" } },
16+
},
17+
],
18+
},
19+
}),
20+
JSON.stringify({ beginRendering: { surfaceId: "main", root: "root" } }),
21+
].join("\n");
22+
823
const mocks = vi.hoisted(() => ({
924
callGatewayTool: vi.fn(),
1025
imageResultFromFile: vi.fn(async (params) => ({ content: [], details: params })),
@@ -60,6 +75,7 @@ describe("Canvas tool", () => {
6075
jsonlPath: "events.jsonl",
6176
}),
6277
).rejects.toThrow("jsonlPath outside workspace");
78+
expect(mocks.listNodes).not.toHaveBeenCalled();
6379
expect(mocks.callGatewayTool).not.toHaveBeenCalled();
6480
},
6581
);
@@ -152,6 +168,73 @@ describe("Canvas tool", () => {
152168
);
153169
});
154170

171+
it("dispatches valid A2UI v0.8 JSONL unchanged", async () => {
172+
const tool = createCanvasTool();
173+
174+
await tool.execute("tool-call-1", {
175+
action: "a2ui_push",
176+
jsonl: VALID_A2UI_V08_JSONL,
177+
});
178+
179+
expect(mocks.callGatewayTool).toHaveBeenCalledTimes(1);
180+
expect(mocks.callGatewayTool).toHaveBeenCalledWith(
181+
"node.invoke",
182+
{},
183+
{
184+
nodeId: "node-1",
185+
command: "canvas.a2ui.pushJSONL",
186+
params: { jsonl: VALID_A2UI_V08_JSONL },
187+
idempotencyKey: expect.any(String),
188+
},
189+
);
190+
});
191+
192+
it.each([
193+
["malformed JSONL", "{not-json}", /Invalid A2UI JSONL/],
194+
[
195+
"A2UI v0.9 createSurface JSONL",
196+
JSON.stringify({
197+
version: "v0.9",
198+
createSurface: {
199+
surfaceId: "main",
200+
catalogId: "https://a2ui.org/specification/v0_9/catalogs/basic/catalog.json",
201+
},
202+
}),
203+
/OpenClaw currently supports v0\.8 only/,
204+
],
205+
[
206+
"legacy createSurface JSONL",
207+
JSON.stringify({ createSurface: { surfaceId: "main", root: "root" } }),
208+
/OpenClaw currently supports v0\.8 only/,
209+
],
210+
[
211+
"A2UI v0.9 deleteSurface JSONL",
212+
JSON.stringify({ version: "v0.9", deleteSurface: { surfaceId: "main" } }),
213+
/OpenClaw currently supports v0\.8 only/,
214+
],
215+
[
216+
"an unsupported explicit A2UI version",
217+
JSON.stringify({ version: "v1.0", deleteSurface: { surfaceId: "main" } }),
218+
/unsupported A2UI version: "v1\.0"/,
219+
],
220+
[
221+
"an explicit version on an A2UI v0.8 message",
222+
JSON.stringify({ version: "v0.8", deleteSurface: { surfaceId: "main" } }),
223+
/A2UI v0\.8 messages must not include a version field/,
224+
],
225+
])("rejects %s before resolving or invoking a node", async (_label, jsonl, message) => {
226+
const tool = createCanvasTool();
227+
228+
await expect(
229+
tool.execute("tool-call-1", {
230+
action: "a2ui_push",
231+
jsonl,
232+
}),
233+
).rejects.toThrow(message);
234+
expect(mocks.listNodes).not.toHaveBeenCalled();
235+
expect(mocks.callGatewayTool).not.toHaveBeenCalled();
236+
});
237+
155238
it("rejects malformed numeric canvas params before invoking node commands", async () => {
156239
const tool = createCanvasTool();
157240

@@ -161,6 +244,7 @@ describe("Canvas tool", () => {
161244
maxWidth: "800px",
162245
}),
163246
).rejects.toThrow("maxWidth must be a positive integer");
247+
expect(mocks.listNodes).not.toHaveBeenCalled();
164248
expect(mocks.callGatewayTool).not.toHaveBeenCalled();
165249
});
166250

0 commit comments

Comments
 (0)