Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

test(glance): cover the widget service worker, the SDK and the knock policy

nirholas503a42dd4690
diff --git a/tests/agent-glance-sdk.test.js b/tests/agent-glance-sdk.test.js
new file mode 100644
index 000000000..111ae7cc4
--- /dev/null
+++ b/tests/agent-glance-sdk.test.js
@@ -0,0 +1,114 @@
+// @three-ws/agent-glance: the npm client that talks to /api/glance.
+//
+// Every URL builder validates the agent id up front, because the failure this
+// prevents is a card silently rendering someone else's agent (or a 404 image)
+// in a README that nobody re-reads.
+
+import { describe, it, expect, vi } from 'vitest';
+import {
+ fetchGlanceCard,
+ glanceCardUrl,
+ glanceImageUrl,
+ glanceMarkdown,
+ glanceEmbedHtml,
+ renderGlanceAnsi,
+ GlanceError,
+} from '../packages/agent-glance/src/index.js';
+
+const ID = '0f3a1c22-9b7e-4d51-8a10-2c6f5d90ab34';
+
+const CARD = {
+ version: 1,
+ id: ID,
+ name: 'Atlas Scout',
+ description: 'Watches the launch feed.',
+ headline: 'Working.',
+ url: `https://three.ws/agents/${ID}`,
+ status: 'active',
+ metric: { label: 'Moves today', value: 17 },
+ stats: [
+ { label: 'This week', value: 96 },
+ { label: 'All time', value: 412 },
+ { label: 'Skills', value: 4 },
+ ],
+};
+
+describe('url builders', () => {
+ it('builds the json and image urls off one agent id', () => {
+ expect(glanceCardUrl(ID)).toBe(`https://three.ws/api/glance/card?agent=${ID}`);
+ expect(glanceImageUrl(ID)).toBe(
+ `https://three.ws/api/glance/card?agent=${ID}&format=svg&size=medium&theme=auto`,
+ );
+ });
+
+ it('honours size and theme, and refuses values it does not serve', () => {
+ expect(glanceImageUrl(ID, { size: 'large', theme: 'dark' })).toContain('size=large&theme=dark');
+ expect(glanceImageUrl(ID, { size: 'gigantic', theme: 'neon' })).toContain(
+ 'size=medium&theme=auto',
+ );
+ });
+
+ it('points at a self-hosted origin when told to', () => {
+ expect(glanceCardUrl(ID, { origin: 'http://localhost:3000' })).toBe(
+ `http://localhost:3000/api/glance/card?agent=${ID}`,
+ );
+ });
+
+ it('rejects anything that is not an agent id, before any network call', () => {
+ expect(() => glanceCardUrl('atlas-scout')).toThrow(GlanceError);
+ expect(() => glanceImageUrl('')).toThrow(/not a three\.ws agent id/);
+ });
+
+ it('emits a README snippet that links the image back to the agent', () => {
+ const md = glanceMarkdown(ID, { size: 'small' });
+ expect(md).toBe(
+ `[![three.ws agent](https://three.ws/api/glance/card?agent=${ID}&format=svg&size=small&theme=auto)](https://three.ws/agents/${ID})`,
+ );
+ });
+
+ it('emits an embed snippet that loads the element and the tag together', () => {
+ const html = glanceEmbedHtml(ID, { theme: 'dark' });
+ expect(html).toContain('https://three.ws/glance/element.js');
+ expect(html).toContain(`<agent-glance agent="${ID}" size="medium" theme="dark">`);
+ });
+});
+
+describe('fetchGlanceCard', () => {
+ it('returns the card on a 200', async () => {
+ const fetchImpl = vi.fn(async () => ({ ok: true, status: 200, json: async () => CARD }));
+ await expect(fetchGlanceCard(ID, { fetchImpl })).resolves.toEqual(CARD);
+ expect(fetchImpl.mock.calls[0][1].signal).toBeDefined();
+ });
+
+ it('says plainly that the agent does not exist on a 404', async () => {
+ const fetchImpl = vi.fn(async () => ({ ok: false, status: 404, json: async () => ({}) }));
+ await expect(fetchGlanceCard(ID, { fetchImpl })).rejects.toThrow(/no such agent/);
+ });
+
+ it('wraps a transport failure instead of leaking a raw network error', async () => {
+ const fetchImpl = vi.fn(async () => {
+ throw new Error('ECONNREFUSED');
+ });
+ await expect(fetchGlanceCard(ID, { fetchImpl })).rejects.toThrow(/could not reach three\.ws/);
+ });
+});
+
+describe('renderGlanceAnsi', () => {
+ it('draws a bordered card that fits a terminal', () => {
+ const plain = renderGlanceAnsi(CARD, { color: false, width: 68 });
+ const lines = plain.split('\n');
+ expect(lines[0]).toMatch(/^╭─+╮$/);
+ expect(lines.at(-1)).toMatch(/^╰─+╯$/);
+ expect(plain).toContain('Atlas Scout');
+ expect(plain).toContain('17 moves today');
+ expect(plain).toContain(`https://three.ws/agents/${ID}`);
+ });
+
+ it('keeps every row the same width once the escapes are stripped', () => {
+ const colored = renderGlanceAnsi(CARD, { color: true, width: 68 });
+ // eslint-disable-next-line no-control-regex
+ const widths = new Set(colored.split('\n').map((l) => l.replace(/\[[0-9;]*m/g, '').length));
+ expect(widths.size).toBe(1);
+ expect([...widths][0]).toBe(68);
+ });
+});
diff --git a/tests/glance-sw.test.js b/tests/glance-sw.test.js
new file mode 100644
index 000000000..79d666f3c
--- /dev/null
+++ b/tests/glance-sw.test.js
@@ -0,0 +1,188 @@
+// The Windows 11 widget half of Glance: public/glance-sw.js evaluated as the
+// real file text against a fake `self`, the same way tests/share-target.test.js
+// exercises the share-target worker.
+//
+// What matters here is that a widget slot ALWAYS has something in it: signed
+// out, no agent yet, and offline are three designed cards, not three errors.
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+const SW_SOURCE = readFileSync(resolve(process.cwd(), 'public/glance-sw.js'), 'utf8');
+
+function makeFakeCaches() {
+ const stores = new Map();
+ class FakeCache {
+ constructor() {
+ this.entries = new Map();
+ }
+ async put(key, res) {
+ this.entries.set(String(key), res);
+ }
+ async match(key) {
+ return this.entries.get(String(key));
+ }
+ async delete(key) {
+ return this.entries.delete(String(key));
+ }
+ }
+ return {
+ stores,
+ async open(name) {
+ if (!stores.has(name)) stores.set(name, new FakeCache());
+ return stores.get(name);
+ },
+ };
+}
+
+/** Evaluate the worker source against a fake global and hand back its exports. */
+function loadWorker({ fetchImpl } = {}) {
+ const listeners = new Map();
+ const updates = [];
+ const self = {
+ addEventListener: (type, fn) => listeners.set(type, fn),
+ widgets: {
+ updateByTag: async (tag, payload) => updates.push({ tag, payload }),
+ matchAll: async () => [{ definition: { tag: 'agent-glance', msAcTemplate: '{}' } }],
+ },
+ };
+ const caches = makeFakeCaches();
+ const fn = new Function('self', 'caches', 'fetch', 'Response', 'AbortSignal', SW_SOURCE);
+ fn(self, caches, fetchImpl || globalThis.fetch, Response, AbortSignal);
+ return { self, listeners, updates, caches };
+}
+
+describe('glance widget worker', () => {
+ let worker;
+ beforeEach(() => {
+ worker = loadWorker();
+ });
+
+ it('registers every widget lifecycle event the board fires', () => {
+ expect([...worker.listeners.keys()].sort()).toEqual([
+ 'periodicsync',
+ 'widgetclick',
+ 'widgetinstall',
+ 'widgetresume',
+ 'widgetuninstall',
+ ]);
+ });
+
+ it('renders a sign-in card rather than an error when nobody is signed in', () => {
+ const payload = worker.self.__threewsGlancePayload({ signedIn: false, signInUrl: 'https://three.ws/login' });
+ expect(payload.state).toBe('signed-out');
+ expect(payload.name).toMatch(/sign in/i);
+ expect(payload.url).toBe('https://three.ws/login');
+ expect(payload.metric.value).toBe('0');
+ });
+
+ it('invites the owner to create one when the account has no agent yet', () => {
+ const payload = worker.self.__threewsGlancePayload({ signedIn: true, card: null, createUrl: 'https://three.ws/create' });
+ expect(payload.state).toBe('empty');
+ expect(payload.headline).toMatch(/create your first agent/i);
+ expect(payload.url).toBe('https://three.ws/create');
+ });
+
+ it('carries the live card through with every value stringified for the host', () => {
+ const payload = worker.self.__threewsGlancePayload({
+ signedIn: true,
+ card: {
+ name: 'Atlas Scout',
+ headline: 'Working.',
+ image: 'https://cdn.example/thumb.png',
+ url: 'https://three.ws/agents/abc',
+ status: 'active',
+ metric: { label: 'Moves today', value: 17 },
+ stats: [{ label: 'This week', value: 96 }],
+ updatedAt: '2026-08-28T12:00:00.000Z',
+ },
+ });
+ expect(payload.state).toBe('active');
+ expect(payload.metric).toEqual({ label: 'Moves today', value: '17' });
+ expect(payload.stats).toEqual([{ label: 'This week', value: '96' }]);
+ expect(payload.image).toBe('https://cdn.example/thumb.png');
+ });
+
+ it('marks a card offline instead of blanking the slot', () => {
+ const payload = worker.self.__threewsGlancePayload(
+ {
+ signedIn: true,
+ card: {
+ name: 'Atlas Scout',
+ headline: 'Working.',
+ image: null,
+ url: 'https://three.ws/agents/abc',
+ status: 'active',
+ metric: { label: 'Moves today', value: 3 },
+ stats: [],
+ },
+ },
+ { offline: true },
+ );
+ expect(payload.state).toBe('offline');
+ expect(payload.headline).toBe('Working. (offline)');
+ expect(payload.image).toBe('/pwa-192x192.png');
+ });
+
+ it('pushes the fetched card into the host on install', async () => {
+ const fetchImpl = vi.fn(async () => ({
+ ok: true,
+ status: 200,
+ json: async () => ({
+ signedIn: true,
+ card: {
+ name: 'Atlas Scout',
+ headline: 'Working.',
+ image: null,
+ url: 'https://three.ws/agents/abc',
+ status: 'active',
+ metric: { label: 'Moves today', value: 5 },
+ stats: [],
+ },
+ }),
+ }));
+ const w = loadWorker({ fetchImpl });
+ await w.self.__threewsGlanceRender({ definition: { tag: 'agent-glance', msAcTemplate: '{}' } });
+ expect(fetchImpl).toHaveBeenCalledWith('/api/glance/mine', expect.objectContaining({ credentials: 'include' }));
+ expect(w.updates).toHaveLength(1);
+ expect(JSON.parse(w.updates[0].payload.data).name).toBe('Atlas Scout');
+ });
+
+ it('falls back to the last card this device saw when the network is gone', async () => {
+ let online = true;
+ const fetchImpl = vi.fn(async () => {
+ if (!online) throw new Error('offline');
+ return {
+ ok: true,
+ status: 200,
+ json: async () => ({
+ signedIn: true,
+ card: {
+ name: 'Atlas Scout',
+ headline: 'Working.',
+ image: null,
+ url: 'https://three.ws/agents/abc',
+ status: 'active',
+ metric: { label: 'Moves today', value: 9 },
+ stats: [],
+ },
+ }),
+ };
+ });
+ const w = loadWorker({ fetchImpl });
+ const widget = { definition: { tag: 'agent-glance', msAcTemplate: '{}' } };
+ await w.self.__threewsGlanceRender(widget);
+
+ online = false;
+ await w.self.__threewsGlanceRender(widget);
+ const last = JSON.parse(w.updates.at(-1).payload.data);
+ expect(last.name).toBe('Atlas Scout');
+ expect(last.state).toBe('offline');
+ expect(last.headline).toBe('Working. (offline)');
+ });
+
+ it('bounds the data fetch so a stalled network cannot hold the board', () => {
+ expect(SW_SOURCE).toMatch(/AbortSignal\.timeout\(GLANCE_TIMEOUT_MS\)/);
+ });
+});
diff --git a/tests/knock-policy.test.js b/tests/knock-policy.test.js
new file mode 100644
index 000000000..304689f54
--- /dev/null
+++ b/tests/knock-policy.test.js
@@ -0,0 +1,201 @@
+// Unit tests for the Knock policy rules (api/_lib/knock/policy.js): what a
+// door costs, what a stranger is allowed to send through it, how loudly a paid
+// knock lands, and exactly what the recipient's avatar says out loud.
+//
+// These are the parts of Knock a person will argue with, so they are pinned
+// here rather than only exercised through HTTP. The module is pure: no
+// database, no network, no clock.
+
+import { describe, it, expect } from 'vitest';
+import {
+ DEFAULT_PRICE_ATOMICS,
+ MAX_PRICE_ATOMICS,
+ MIN_PRICE_ATOMICS,
+ blockKeysFor,
+ doorRefusal,
+ formatUsdc,
+ importanceFor,
+ knockError,
+ normalizeHandle,
+ parsePrice,
+ spokenLineFor,
+ titleFor,
+ validateKnock,
+} from '../api/_lib/knock/policy.js';
+
+const DOOR = { open: true, max_chars: 600, daily_cap: 25 };
+
+describe('formatUsdc', () => {
+ it('renders whole dollars and cents', () => {
+ expect(formatUsdc(0n)).toBe('$0.00');
+ expect(formatUsdc('50000')).toBe('$0.05');
+ expect(formatUsdc('1000000')).toBe('$1.00');
+ expect(formatUsdc('1234500000')).toBe('$1234.50');
+ });
+
+ it('keeps sub-cent precision instead of rounding a price to zero', () => {
+ expect(formatUsdc(MIN_PRICE_ATOMICS)).toBe('$0.001');
+ expect(formatUsdc('1')).toBe('$0.000001');
+ });
+});
+
+describe('parsePrice', () => {
+ it('accepts what a person actually types', () => {
+ expect(parsePrice('0.05')).toBe(50000n);
+ expect(parsePrice('$0.05')).toBe(50000n);
+ expect(parsePrice('1,000')).toBe(1000000000n);
+ expect(parsePrice(String(DEFAULT_PRICE_ATOMICS), { unit: 'atomics' })).toBe(DEFAULT_PRICE_ATOMICS);
+ });
+
+ it('treats zero as a free door, not an out-of-range price', () => {
+ expect(parsePrice('0')).toBe(0n);
+ });
+
+ it('refuses a price the settle rail cannot carry', () => {
+ expect(() => parsePrice('0.0005')).toThrow(/between/);
+ expect(() => parsePrice('1001')).toThrow(/between/);
+ expect(() => parsePrice('abc')).toThrow(/USDC amount/);
+ expect(() => parsePrice('0.1234567')).toThrow(/USDC amount/);
+ });
+
+ it('round-trips the documented bounds', () => {
+ expect(parsePrice(formatUsdc(MIN_PRICE_ATOMICS))).toBe(MIN_PRICE_ATOMICS);
+ expect(parsePrice(formatUsdc(MAX_PRICE_ATOMICS))).toBe(MAX_PRICE_ATOMICS);
+ });
+});
+
+describe('normalizeHandle', () => {
+ it('strips the @ and lowercases', () => {
+ expect(normalizeHandle('@Nirholas')).toBe('nirholas');
+ });
+
+ it('drops anything a username could never contain', () => {
+ expect(normalizeHandle('ni r/ho..las!')).toBe('nirho..las');
+ expect(normalizeHandle('')).toBe('');
+ expect(normalizeHandle(null)).toBe('');
+ });
+});
+
+describe('importanceFor', () => {
+ it('puts every paid knock above the default interrupt bar of 60', () => {
+ for (const price of ['1000', '50000', '1000000', '1000000000']) {
+ expect(importanceFor(price)).toBeGreaterThan(60);
+ }
+ });
+
+ it('keeps a free knock below it, so a free door cannot interrupt anyone', () => {
+ expect(importanceFor(0)).toBeLessThan(60);
+ });
+
+ it('ranks a bigger payment higher without letting one buy the whole feed', () => {
+ expect(importanceFor('1000000')).toBeGreaterThan(importanceFor('50000'));
+ expect(importanceFor('1000000000')).toBeLessThanOrEqual(99);
+ });
+});
+
+describe('spokenLineFor', () => {
+ it('leads with who and what they paid, because that is the decision', () => {
+ expect(spokenLineFor({ senderName: 'Ada', amountAtomics: '50000', subject: 'Your settle path' }))
+ .toBe('Ada paid $0.05 to reach you: Your settle path.');
+ });
+
+ it('says a free knock plainly rather than claiming a payment', () => {
+ expect(spokenLineFor({ senderName: 'Ada', amountAtomics: 0 })).toBe('Ada is at your door.');
+ });
+
+ it('never speaks the message body', () => {
+ const line = spokenLineFor({ senderName: 'Ada', amountAtomics: '50000', subject: 'Hi' });
+ expect(line).not.toContain('body');
+ expect(line.length).toBeLessThan(120);
+ });
+
+ it('survives a sender with no name', () => {
+ expect(spokenLineFor({ amountAtomics: '50000' })).toBe('Someone paid $0.05 to reach you.');
+ });
+});
+
+describe('titleFor', () => {
+ it('names the sender and the subject', () => {
+ expect(titleFor({ senderName: 'Ada', amountAtomics: '50000', subject: 'Settle path' })).toBe('Ada: Settle path');
+ });
+
+ it('falls back to the amount when there is no subject', () => {
+ expect(titleFor({ senderName: 'Ada', amountAtomics: '50000' })).toBe('Ada knocked ($0.05)');
+ expect(titleFor({ senderName: 'Ada', amountAtomics: 0 })).toBe('Ada knocked');
+ });
+});
+
+describe('validateKnock', () => {
+ const ok = { from: 'Ada', message: 'a message long enough to be real' };
+
+ it('returns the cleaned payload', () => {
+ const clean = validateKnock({ ...ok, subject: ' Settle path ', url: 'https://example.com' }, DOOR);
+ expect(clean.senderName).toBe('Ada');
+ expect(clean.subject).toBe('Settle path');
+ expect(clean.senderUrl).toBe('https://example.com');
+ expect(clean.senderKind).toBe('unknown');
+ });
+
+ it('enforces the door\'s own length limit, not a global one', () => {
+ expect(() => validateKnock({ ...ok, message: 'x'.repeat(120) }, { ...DOOR, max_chars: 100 }))
+ .toThrow(/up to 100 characters/);
+ expect(validateKnock({ ...ok, message: 'x'.repeat(120) }, { ...DOOR, max_chars: 600 }).message.length).toBe(120);
+ });
+
+ it('refuses a message with nothing in it', () => {
+ expect(() => validateKnock({ ...ok, message: 'hi' }, DOOR)).toThrow(/at least 8/);
+ expect(() => validateKnock({ ...ok, from: ' ' }, DOOR)).toThrow(/who you are/);
+ });
+
+ it('refuses a link that is not a plain http(s) URL', () => {
+ for (const url of ['javascript:alert(1)', 'data:text/html,x', 'not a url']) {
+ expect(() => validateKnock({ ...ok, url }, DOOR)).toThrow(/http\(s\) link/);
+ }
+ });
+
+ it('only trusts sender_kind from the allowlist', () => {
+ expect(validateKnock({ ...ok, sender_kind: 'agent' }, DOOR).senderKind).toBe('agent');
+ expect(validateKnock({ ...ok, sender_kind: 'admin' }, DOOR).senderKind).toBe('unknown');
+ });
+});
+
+describe('doorRefusal', () => {
+ it('refuses a door nobody opened', () => {
+ expect(doorRefusal(null)?.code).toBe('no_door');
+ expect(doorRefusal(null)?.status).toBe(404);
+ });
+
+ it('refuses a shut door', () => {
+ expect(doorRefusal({ ...DOOR, open: false })?.code).toBe('door_closed');
+ });
+
+ it('refuses once the day\'s cap is spent, with a retryable status', () => {
+ const refusal = doorRefusal(DOOR, { knocksToday: 25 });
+ expect(refusal?.code).toBe('door_full');
+ expect(refusal?.status).toBe(429);
+ });
+
+ it('lets a knock through below the cap', () => {
+ expect(doorRefusal(DOOR, { knocksToday: 24 })).toBeNull();
+ });
+});
+
+describe('blockKeysFor', () => {
+ it('matches on the paying wallet and on the name', () => {
+ expect(blockKeysFor({ payerWallet: 'AbC', senderName: 'Ada' })).toEqual(['abc', 'ada']);
+ });
+
+ it('deduplicates and drops empties', () => {
+ expect(blockKeysFor({ payerWallet: 'ada', senderName: 'Ada' })).toEqual(['ada']);
+ expect(blockKeysFor({})).toEqual([]);
+ });
+});
+
+describe('knockError', () => {
+ it('carries a machine code and the right HTTP status', () => {
+ expect(knockError('door_full', 'x').status).toBe(429);
+ expect(knockError('blocked', 'x').status).toBe(403);
+ expect(knockError('duplicate', 'x').status).toBe(409);
+ expect(knockError('something_new', 'x').status).toBe(400);
+ });
+});