1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
// node --test test/page.test.mjs (after scripts/stage.sh: dist/ as served; skips without Chrome)
// index.html as served, in headless Chrome, signed in: every lib's action forms render, the MCP servers list
// their tools (read-only ones public), and the agent runs in the page's wasm worker against a stubbed Messages
// API: a read tool runs as the user, a write tool waits for the confirm dialog (denied here). Stubbed: the OAuth
// client (esm.sh: a session whose fetchHandler is the stub PDS), the PLC directory, the PDS, inference, and the
// stylesheet, unless ATLIBS_DOCS_NETWORK=1.
import assert from "node:assert/strict";
import { test } from "node:test";
// atlibs' headless Chrome harness (its docs/, not in the npm package), vendored
import { browse, CHROME } from "./browser.mjs";
const ROOT = new URL("../dist/", import.meta.url).pathname;
const NETWORK = process.env.ATLIBS_DOCS_NETWORK === "1";
const did = "did:plc:lpfuqerea3deuoyrn7ojser4";
const CORS = [{ name: "access-control-allow-origin", value: "*" }, { name: "access-control-allow-headers", value: "*" }, { name: "access-control-allow-methods", value: "*" }];
const OAUTH = `export const BrowserOAuthClient = { load: async () => ({
init: async () => ({ session: { did: ${JSON.stringify(did)}, fetchHandler: (path, init) => fetch("https://pds.test" + path, init) } }),
signIn: async () => {}, revoke: async () => {},
}) }`;
// atlibs-webrtc, stubbed: its webrtc: fetcher is a stub guest agent MCP shell (no peer connection)
const WEBRTC = `const reply = (m) => m.method === "initialize" ? { protocolVersion: m.params.protocolVersion, capabilities: { tools: {} }, serverInfo: { name: "socialweb-guest-agent", version: "0" } }
: m.method === "tools/list" ? { tools: ["exec", "start", "read", "write", "kill", "list"].map((name) => ({ name, description: name, inputSchema: { type: "object" } })) }
: { content: [{ type: "text", text: JSON.stringify({ exitCode: 0, stdout: "ran " + m.params.arguments.command + "\\n", stderr: "", truncated: false }) }] };
export class WebrtcHost {
constructor(options) { globalThis.webrtcOptions = options }
get calls() { return {} }
fetchers() { return { "webrtc:": async ({ url, body }) => { (globalThis.webrtcUrls ??= []).push(url); const m = JSON.parse(body); return m.id === undefined ? { status: 202, headers: {}, body: "" } : { status: 200, headers: { "Content-Type": "application/json" }, body: JSON.stringify({ jsonrpc: "2.0", id: m.id, result: reply(m) }) } } } }
}`;
// a kept VM's shell, and the URL as a model miscopied it live (one CID character off): the host sends the kept one
const RECEIPT = "at://did:plc:bidder/com.publicdomainrelay.temp.market.receipt/receipt-1";
const ref = (cid) => Buffer.from(JSON.stringify({ bidder: "did:plc:bidder", receipt: { cid, uri: RECEIPT } })).toString("base64url");
const VM = `webrtc:///${ref("bafygood")}/shell/mcp`;
const MISCOPIED = `webrtc:///${ref("bafygod")}/shell/mcp`;
// the VM kept: vm-mcp's computer.socialweb.vm.kept record in the user's repo
const KEPT = { uri: `at://${did}/computer.socialweb.vm.kept/self`, cid: "bafykept", value: { vms: [{ vm: "vm-1", bidder: "did:plc:bidder", cpus: 2, mem: 4, created: "2026-11-10T00:00:00Z", expires: "2099-01-01T00:00:00Z", shell: VM, receipt: { uri: RECEIPT, cid: "bafygood" }, records: [] }] } };
const DOMAINS = { records: [{ uri: `at://${did}/at.marque.domain/example.com`, cid: "bafy", value: { domain: "example.com", status: "active" } }] };
const TURNS = [
{ content: [{ type: "tool_use", id: "a", name: "marque__list_domains", input: {} }, { type: "tool_use", id: "b", name: "vm__vm_create", input: {} }], stop_reason: "tool_use" },
{ content: [{ type: "tool_use", id: "c", name: "mcp_connect", input: { name: "shell", server: { url: MISCOPIED } } }], stop_reason: "tool_use" },
{ content: [{ type: "tool_use", id: "d", name: "shell__exec", input: { command: "uname -a; id -u" } }], stop_reason: "tool_use" },
{ content: [{ type: "text", text: "you have example.com; the VM was declined" }], stop_reason: "end_turn" },
];
test("the page boots signed in, lists tools, and runs the agent with a confirm", { skip: !CHROME && "no Chrome", timeout: 60_000 }, () =>
browse(async ({ send, on, open, evaluate }) => {
const errors = [];
const keys = [];
const writes = [];
on("Runtime.exceptionThrown", ({ exceptionDetails: e }) => errors.push(e.exception?.description ?? e.text));
on("Log.entryAdded", ({ entry }) => entry.level === "error" && !entry.url?.endsWith("/favicon.ico") && errors.push(`${entry.text} ${entry.url ?? ""}`));
on("Fetch.requestPaused", ({ requestId, request }) => {
const url = new URL(request.url);
let type = "application/json";
let body;
if (request.method === "OPTIONS") body = "";
else if (url.origin === "https://esm.sh") [type, body] = ["text/javascript", url.pathname.includes("oauth-client-browser") ? OAUTH : "export const secp256k1 = {};"];
else if (/\/atlibs-webrtc@[^/]+\/js\/index\.js$/.test(url.pathname)) [type, body] = ["text/javascript", WEBRTC];
else if (url.origin === "https://cdn.jsdelivr.net") [type, body] = ["text/css", ""];
else if (url.origin === "https://plc.directory") body = JSON.stringify({ service: [{ id: "#atproto_pds", serviceEndpoint: "https://pds.test" }] });
else if (url.origin === "https://inference.test") (keys.push(request.headers["x-api-key"] ?? request.headers["X-Api-Key"]), (body = JSON.stringify({ ...TURNS.shift(), usage: { input_tokens: 1, output_tokens: 1 } })));
else if (url.pathname.endsWith("com.atproto.repo.listRecords") && url.searchParams.get("collection") === "at.marque.domain") body = JSON.stringify(DOMAINS);
else if (url.pathname.endsWith("com.atproto.repo.getRecord") && url.searchParams.get("collection") === "computer.socialweb.vm.kept") body = JSON.stringify(KEPT);
else (request.method === "POST" && writes.push(url.pathname), (body = JSON.stringify({ error: "RecordNotFound" })));
send("Fetch.fulfillRequest", { requestId, responseCode: body.includes("RecordNotFound") ? 400 : 200, responseHeaders: [{ name: "content-type", value: type }, ...CORS], body: Buffer.from(body).toString("base64") });
});
await send("Runtime.enable");
await send("Log.enable");
const stubbed = ["https://plc.directory/*", "https://pds.test/*", "https://inference.test/*", "*/atlibs-webrtc@*/js/index.js", ...(NETWORK ? [] : ["https://esm.sh/*", "https://cdn.jsdelivr.net/npm/@picocss/*"])];
await send("Fetch.enable", { patterns: stubbed.map((urlPattern) => ({ urlPattern })) });
await open("/index.html");
const until = async (expression, ms = 20_000) => {
for (const end = Date.now() + ms; Date.now() < end; await new Promise((ok) => setTimeout(ok, 100))) if (await evaluate(expression)) return;
assert.fail(`timed out: ${expression}\n${errors.join("\n")}\n${await evaluate(`document.getElementById("status").textContent + " " + document.getElementById("error").textContent`)}`);
};
await until(`document.body.dataset.ready === "true"`);
// the VM kept, as vm_list reads it from the user's repo
await until(`document.getElementById("vms").textContent.includes("vm-1")`);
assert.match(await evaluate(`document.getElementById("vms").textContent`), /^vm-1 2 vCPUs, 4 GiB from did:plc:bidder since 2026-11-10T00:00:00Z until 2099/);
assert.equal(await evaluate(`document.getElementById("vms-none").hidden`), true);
// co/core is the default provider: no key field
assert.deepEqual(await evaluate(`[document.getElementById("agent").provider.value, document.getElementById("use-custom").checked, document.getElementById("key").hidden, document.getElementById("custom").hidden]`), ["cocore", false, true, true]);
// the switch: a custom endpoint shows its base URL, format and key
await evaluate(`(() => { const s = document.getElementById("use-custom"); s.checked = true; s.dispatchEvent(new Event("change")) })()`);
assert.deepEqual(await evaluate(`[document.getElementById("agent").provider.value, document.getElementById("key").hidden, document.getElementById("custom").hidden]`), ["custom", false, false]);
assert.equal(await evaluate(`document.querySelector("#who code").textContent`), did);
// the source link; on 127.0.0.1 co/core is usable (no CORS note, the switch enabled)
assert.equal(await evaluate(`document.getElementById("source").href`), "https://knotless.dev/johnandersen777.bsky.social/atlibs-agent-reference-spa");
assert.deepEqual(await evaluate(`[document.getElementById("cocore-cors").hidden, document.getElementById("use-custom").disabled]`), [true, false]);
assert.equal(await evaluate(`document.querySelector("#login").hidden`), true);
// a form per action: knotless 2, marque 5, fedproxy 2, cocore 2 + 4, vm 5; cocore is no MCP server
assert.equal(await evaluate(`document.querySelectorAll("#actions form").length`), 20);
assert.deepEqual(await evaluate(`[...document.querySelectorAll("#servers summary")].map((s) => s.textContent)`), ["code (1 tools)", "knotless (2 tools)", "marque (5 tools)", "fedproxy (2 tools)", "vm (5 tools)"]);
// public at first: the read-only tools
assert.equal(await evaluate(`[...document.querySelectorAll("#servers input:checked")].length`), 1 + 0 + 2 + 1 + 1);
// signed in: the webrtc transport signals through requester runs
assert.deepEqual(await evaluate(`[typeof webrtcOptions.events, typeof webrtcOptions.signal, typeof webrtcOptions.makePeer]`), ["function", "function", "function"]);
await evaluate(`(() => { const f = document.getElementById("agent"); f.prompt.value = "what do I have?"; f.endpoint.value = "https://inference.test"; f.model.value = "m"; f.apiKey.value = "PAGE-KEY"; f.requestSubmit() })()`);
await until(`document.getElementById("confirm").open`);
assert.equal(await evaluate(`document.querySelector("#confirm .tool").textContent`), "vm-mcp vm_create");
await evaluate(`document.querySelector('#confirm button[value=deny]').click()`);
await until(`document.getElementById("status").textContent.includes("stop: end_turn")`);
const transcript = await evaluate(`document.getElementById("transcript").textContent`);
assert.match(transcript, /example\.com/);
assert.match(transcript, /declined/);
assert.match(transcript, /ran uname -a; id -u/);
assert.match(transcript, /the VM was declined/);
assert.deepEqual(keys, ["PAGE-KEY", "PAGE-KEY", "PAGE-KEY", "PAGE-KEY"]);
// the agent's connected server, over the host's webrtc: fetcher
assert.equal(await evaluate(`document.getElementById("connected").textContent`), `shell ${MISCOPIED} · ready · 6 tools · connected by the agent`);
assert.ok((await evaluate(`webrtcUrls`)).every((u) => u === VM), "the kept VM's own ref went out");
assert.deepEqual(writes, []);
// the key is kept sealed, not shown again
assert.equal(await evaluate(`document.getElementById("agent").apiKey.value`), "");
assert.match(await evaluate(`document.getElementById("key-state").textContent`), /saved/);
await evaluate(`document.getElementById("forget-key").click()`);
await until(`document.getElementById("key-state").textContent === "" && document.getElementById("forget-key").hidden`);
assert.deepEqual(errors, []);
}, { root: ROOT }));