~ knotless Search/
↑↓ move↵ open⇧↵ all results

johnandersen777.bsky.social/atlibs-asyncai

0
0
main
56 lines · 4.5 KB Raw History
// node --test web/asyncai/page.test.mjs  (after `cargo wasm`; skips without Chrome)
// index.html as served, in headless Chrome: the form runs the real module in the page's wasm worker,
// against a stubbed Messages API (the custom backend, Anthropic's format), and the transcript shows the
// answer. @atproto/oauth-client-browser (esm.sh) is stubbed: signed out.
import assert from "node:assert/strict";
import { test } from "node:test";

import { browse, CHROME } from "../../../atlibs/docs/browser.mjs";

const ROOT = new URL("./", import.meta.url).pathname;
const CORS = [{ name: "access-control-allow-origin", value: "*" }, { name: "access-control-allow-headers", value: "*" }, { name: "access-control-allow-methods", value: "*" }];

test("the page runs the agent and shows the transcript; the key goes only to the inference origin", { skip: !CHROME && "no Chrome" }, () =>
	browse(async ({ send, on, open, evaluate }) => {
		const errors = [];
		const keys = [];
		on("Runtime.exceptionThrown", ({ exceptionDetails: e }) => errors.push(e.exception?.description ?? e.text));
		on("Fetch.requestPaused", ({ requestId, request }) => {
			if (request.url.startsWith("https://esm.sh/")) {
				const stub = "export const BrowserOAuthClient = { load: async () => ({ init: async () => undefined }) }";
				return send("Fetch.fulfillRequest", { requestId, responseCode: 200, responseHeaders: [{ name: "content-type", value: "text/javascript" }, ...CORS], body: Buffer.from(stub).toString("base64") });
			}
			if (request.method !== "OPTIONS") keys.push(request.headers["x-api-key"] ?? request.headers["X-Api-Key"]);
			const body = request.method === "OPTIONS" ? "" : JSON.stringify({ content: [{ type: "text", text: "hello from the stub" }], stop_reason: "end_turn", usage: { input_tokens: 1, output_tokens: 1 } });
			send("Fetch.fulfillRequest", { requestId, responseCode: 200, responseHeaders: [{ name: "content-type", value: "application/json" }, ...CORS], body: Buffer.from(body).toString("base64") });
		});
		await send("Runtime.enable");
		await send("Fetch.enable", { patterns: [{ urlPattern: "https://inference.test/*" }, { urlPattern: "https://esm.sh/*" }] });
		await open("/index.html");
		await evaluate(`(() => { const f = document.getElementById("form"); f.prompt.value = "hi"; f.backend.value = "custom"; f.format.value = "anthropic"; f.endpoint.value = "https://inference.test"; f.apiKey.value = "PAGE-KEY"; f.mcp.value = "[]"; f.requestSubmit() })()`);
		const until = async (expression) => {
			for (const end = Date.now() + 15_000; 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`)}`);
		};
		await until(`document.getElementById("transcript").textContent.includes("hello from the stub")`);
		assert.match(await evaluate(`document.getElementById("status").textContent`), /stop: end_turn, steps: 1/);
		assert.deepEqual(keys, ["PAGE-KEY"]);
		assert.deepEqual(errors, []);
	}, { root: ROOT }));

test("co/core is the default backend and asks to sign in", { skip: !CHROME && "no Chrome" }, () =>
	browse(async ({ send, on, open, evaluate }) => {
		on("Fetch.requestPaused", ({ requestId }) => {
			const stub = "export const BrowserOAuthClient = { load: async () => ({ init: async () => undefined }) }";
			send("Fetch.fulfillRequest", { requestId, responseCode: 200, responseHeaders: [{ name: "content-type", value: "text/javascript" }, ...CORS], body: Buffer.from(stub).toString("base64") });
		});
		await send("Fetch.enable", { patterns: [{ urlPattern: "https://esm.sh/*" }] });
		await open("/index.html");
		for (const end = Date.now() + 15_000; Date.now() < end && (await evaluate(`document.getElementById("login").hidden`)); ) await new Promise((ok) => setTimeout(ok, 100));
		assert.equal(await evaluate(`document.querySelector("#form").backend.value`), "cocore");
		assert.equal(await evaluate(`document.getElementById("login").hidden`), false);
		assert.equal(await evaluate(`document.getElementById("custom").hidden`), true);
		await evaluate(`(() => { const f = document.getElementById("form"); f.prompt.value = "hi"; f.mcp.value = "[]"; f.requestSubmit() })()`);
		for (const end = Date.now() + 15_000; Date.now() < end && !(await evaluate(`document.getElementById("status").textContent`)); ) await new Promise((ok) => setTimeout(ok, 100));
		assert.match(await evaluate(`document.getElementById("status").textContent`), /co\/core runs as you: sign in first/);
	}, { root: ROOT }));