import { fileURLToPath } from "node:url"; import { afterEach, describe, expect, it } from "vitest"; import { createPiSession, type PiSession, } from "../../../test/fixture/create-pi-session.ts"; import { type CanvasState, restoreState } from "../src/store.ts"; let fixture: PiSession | undefined; afterEach(async () => { await fixture?.dispose(); fixture = undefined; }); async function openCanvas(): Promise<{ pi: PiSession; url: string }> { fixture = await createPiSession({ extensionPaths: [ fileURLToPath(new URL("../../../dist/canvas/index.ts", import.meta.url)), ], env: { PATH: "/canvas-test-no-executables", TERMUX_VERSION: undefined }, }); const pi = fixture; let url = ""; const ctx = pi.session.extensionRunner.createCommandContext(); ctx.ui.notify = (text) => { const match = text.match(/http:\/\/127\.0\.0\.1:\d+\/#\S+/u); if (match) url = match[0]; }; await pi.extensions[0]!.commands.get("canvas")!.handler("open", ctx); expect(url).not.toBe(""); expect(pi.errors).toEqual([]); return { pi, url }; } function tool( pi: PiSession, args: Record, signal?: AbortSignal, ) { return pi.extensions[0]!.tools.get("canvas")!.definition.execute( "native-proof", args, signal, undefined, pi.session.extensionRunner.createToolContext("native-proof", undefined), ); } async function request( url: string, path: string, body?: unknown, ): Promise { return fetch(new URL(path, url), { headers: { Authorization: `Bearer ${new URL(url).hash.slice(1)}`, ...(body ? { Origin: new URL(url).origin, "Content-Type": "application/json" } : {}), }, ...(body ? { method: "POST", body: JSON.stringify(body) } : {}), }); } async function state(url: string): Promise { return (await request(url, "/api/state")).json() as Promise; } const diagram = `flowchart TD\n${Array.from({ length: 30 }, (_, i) => `N${i}[Node ${i}] --> N${i + 1}`).join("\n")}`; describe.runIf(process.env["PI_CANVAS_NATIVE_TESTS"] === "1")( "Pi-owned drawing without viewer connections", () => { it("commits native text and Mermaid, persists them, and rejects obsolete browser commits", async () => { const { pi, url } = await openCanvas(); expect((await tool(pi, { action: "inspect" })).details).toMatchObject({ diagnostics: { viewerCount: 0 }, }); await tool(pi, { action: "draw", baseRevision: 0, title: "No viewer needed", additions: [ { id: "title", type: "text", x: 20, y: 20, text: "Browser-independent", }, ], }); await tool(pi, { action: "draw", baseRevision: 1, title: "Server diagram", mermaid: "flowchart LR\nA[Pi] --> B[Saved scene]", x: 20, y: 100, }); const committed = await state(url); expect(committed.revision).toBe(2); expect(committed.change?.origin).toBe("agent"); expect( committed.elements.some( (element) => element.id === "title" && element.text === "Browser-independent", ), ).toBe(true); expect( committed.elements.some((element) => element.type === "arrow"), ).toBe(true); expect(committed).not.toHaveProperty("pendingDraw"); expect((await tool(pi, { action: "inspect" })).details).toMatchObject({ diagnostics: { viewerCount: 0, pendingDraw: false, renderer: { launches: 1, running: true }, }, }); expect(restoreState(pi.session.sessionManager.getBranch())).toMatchObject( { revision: 2, elements: committed.elements, }, ); expect( ( await request(url, "/api/action", { kind: "commit", requestId: "obsolete", clientId: "browser", revision: 2, elements: [], }) ).status, ).toBe(400); expect((await state(url)).revision).toBe(2); expect(pi.providerState.callCount).toBe(0); }, 60000); it("rejects a stale candidate when a human revision arrives during worker startup", async () => { const { pi, url } = await openCanvas(); const pending = tool(pi, { action: "draw", baseRevision: 0, title: "Racing with human", mermaid: diagram, x: 20, y: 20, }); const rejected = expect(pending).rejects.toThrow(/changed|cancelled/iu); await expect .poll(async () => (await tool(pi, { action: "inspect" })).details, { timeout: 10000, interval: 10, }) .toMatchObject({ diagnostics: { pendingDraw: true, renderer: { running: true } }, }); const human = [ { id: "human", type: "rectangle", x: 10, y: 10, width: 100, height: 80, }, ]; expect( ( await request(url, "/api/action", { kind: "scene", revision: 0, clientId: "human", sequence: 1, activity: "active", elements: human, }) ).status, ).toBe(200); await rejected; expect(await state(url)).toMatchObject({ revision: 1, elements: human, change: { origin: "human" }, }); }, 60000); it("cancels an active renderer on branch shutdown without publishing a drawing", async () => { const { pi, url } = await openCanvas(); const pending = tool(pi, { action: "draw", baseRevision: 0, title: "Cancelled by branch change", mermaid: diagram, x: 20, y: 20, }); const rejected = expect(pending).rejects.toThrow(/closed|cancelled/iu); await expect .poll(async () => (await tool(pi, { action: "inspect" })).details, { timeout: 10000, interval: 10, }) .toMatchObject({ diagnostics: { pendingDraw: true, renderer: { running: true } }, }); await pi.session.extensionRunner.emit({ type: "session_tree", oldLeafId: "old", newLeafId: pi.session.sessionManager.getLeafId(), }); await rejected; expect(restoreState(pi.session.sessionManager.getBranch()).revision).toBe( 0, ); await expect(fetch(new URL("/api/state", url))).rejects.toThrow(); expect(pi.errors).toEqual([]); }, 60000); }, );