repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by admin
extensions/canvas/__e2e__/agent-server.ts
Raw// Isolated real-Pi fixture for browser-driven checks (including WebDriver BiDi).
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import {
type FauxResponseFactory,
fauxAssistantMessage,
} from "@earendil-works/pi-ai";
import { createPiSession } from "../../../test/fixture/create-pi-session.ts";
const canvasPackage = JSON.parse(
readFileSync(
new URL("../../../dist/canvas/package.json", import.meta.url),
"utf8",
),
) as { pi: { extensions: string[] } };
const canvasEntry = canvasPackage.pi.extensions[0];
if (!canvasEntry) throw new Error("Canvas Pi extension entry missing");
// Native mode exercises real tool dispatch when the browser runner is unavailable.
// Draw one standalone text shape; each next drawing observation advances a phase.
const nativeEdits = process.env["CANVAS_FIXTURE_NATIVE_EDITS"] === "1";
const nativeResponse: FauxResponseFactory = (context, _options, state) => {
const operation = Math.floor((state.callCount - 1) / 3);
const phase = (state.callCount - 1) % 3;
if (operation >= 3) return fauxAssistantMessage("");
if (phase === 0)
return fauxAssistantMessage([
{
type: "toolCall",
id: `inspect-${operation}`,
name: "canvas",
arguments: { action: "inspect" },
},
]);
const last = context.messages.findLast(
(message) => message.role === "toolResult",
);
if (last?.role !== "toolResult" || last.isError)
throw new Error("Native fixture canvas tool failed.");
if (phase === 2)
return fauxAssistantMessage(
`Native ${["move", "relabel", "delete"][operation]} committed.`,
);
const body = last.content.find((part) => part.type === "text");
if (body?.type !== "text")
throw new Error("Native fixture inspection is missing.");
const data = JSON.parse(body.text) as {
revision: number;
scene: {
elements: Array<{ id: string; type: string; containerId: string | null }>;
};
};
const text = data.scene.elements.find(
(element) => element.type === "text" && !element.containerId,
);
if (!text)
throw new Error("Draw standalone text before native fixture verification.");
const edit =
operation === 0
? { moves: [{ ids: [text.id], dx: 120, dy: 40 }] }
: operation === 1
? { relabels: [{ id: text.id, text: "Clear shared idea" }] }
: { deleteIds: [text.id] };
return fauxAssistantMessage([
{
type: "toolCall",
id: `edit-${operation}`,
name: "canvas",
arguments: {
action: "draw",
baseRevision: data.revision,
title: "Native editing verification",
...edit,
},
},
]);
};
const catchupMode = process.env["CANVAS_FIXTURE_CATCHUP"] === "1";
const catchupResponse: FauxResponseFactory = (context, _options, state) => {
if (state.callCount > 4) return fauxAssistantMessage("");
if (state.callCount === 1)
return fauxAssistantMessage([
{
type: "toolCall",
id: "catchup-inspect",
name: "canvas",
arguments: { action: "inspect" },
},
]);
const last = context.messages.findLast(
(message) => message.role === "toolResult",
);
if (last?.role !== "toolResult" || last.isError)
throw new Error("Catch-up fixture tool failed.");
if (state.callCount === 4)
return fauxAssistantMessage("Catch-up commits ready.");
const part = last.content.find((item) => item.type === "text");
if (part?.type !== "text")
throw new Error("Catch-up fixture result missing.");
const data = JSON.parse(part.text) as {
revision: number;
scene: { elements: Array<{ id: string; type: string }> };
};
const text = data.scene.elements.find((element) => element.type === "text");
if (!text) throw new Error("Draw one text shape for catch-up verification.");
return fauxAssistantMessage([
{
type: "toolCall",
id: `catchup-${state.callCount}`,
name: "canvas",
arguments: {
action: "draw",
baseRevision: data.revision,
title: "Background transaction",
moves: [
{ ids: [text.id], dx: state.callCount === 2 ? 120 : 60, dy: 40 },
],
},
},
]);
};
const fixture = await createPiSession({
extensionPaths: [
fileURLToPath(
new URL(`../../../dist/canvas/${canvasEntry}`, import.meta.url),
),
],
env: {
PATH: "/canvas-test-no-executables",
TERMUX_VERSION: undefined,
PI_CANVAS_DEBUG: "0",
},
responses: Array.from(
{ length: 20 },
(): FauxResponseFactory =>
catchupMode
? catchupResponse
: nativeEdits
? nativeResponse
: async (_context, _options, state) => {
await new Promise((resolve) => setTimeout(resolve, 1500));
return fauxAssistantMessage(
`Firefox drawing observed: ${state.callCount}`,
);
},
),
});
let closing = false;
const expiry = setTimeout(() => {
void close();
}, 600_000);
async function close(): Promise<void> {
if (closing) return;
closing = true;
clearTimeout(expiry);
await fixture.dispose();
console.log(
JSON.stringify({
kind: "closed",
calls: fixture.providerState.callCount,
errors: fixture.errors,
}),
);
process.exitCode = fixture.errors.length ? 1 : 0;
}
process.once("SIGINT", () => {
void close();
});
process.once("SIGTERM", () => {
void close();
});
try {
if (fixture.errors.length) throw new Error(fixture.errors.join("\n"));
let url = "";
const context = fixture.session.extensionRunner.createCommandContext();
context.ui.notify = (text) => {
const match = text.match(/http:\/\/127\.0\.0\.1:\d+\/#\S+/u);
if (match) url = match[0];
};
await fixture.extensions[0]!.commands.get("canvas")!.handler("open", context);
if (!url) throw new Error("Canvas fixture did not open.");
console.log(JSON.stringify({ kind: "ready", pid: process.pid, url }));
} catch (error) {
await close();
throw error;
}