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.

feat(extension): render the companion verdict in a panel on the checkout page

nirholasdb5ba75e1e1e
diff --git a/extensions/checkout-companion/panel.css b/extensions/checkout-companion/panel.css
new file mode 100644
index 000000000..a8997b63b
--- /dev/null
+++ b/extensions/checkout-companion/panel.css
@@ -0,0 +1,22 @@
+/* Positioning only. Everything the panel looks like lives in its shadow root,
+ so a merchant's stylesheet cannot reach it and ours cannot leak onto their
+ page. This file styles the host element and nothing else.
+
+ The host is pointer-transparent and the card inside takes events back (see
+ panel.js): the panel must never sit between a person and the button they came
+ to press. */
+.threews-checkout-companion {
+ position: fixed;
+ right: 16px;
+ bottom: 16px;
+ z-index: 2147483000;
+ pointer-events: none;
+}
+
+@media (max-width: 480px) {
+ .threews-checkout-companion {
+ right: 12px;
+ left: 12px;
+ bottom: 12px;
+ }
+}
diff --git a/extensions/checkout-companion/panel.js b/extensions/checkout-companion/panel.js
new file mode 100644
index 000000000..8a87ae135
--- /dev/null
+++ b/extensions/checkout-companion/panel.js
@@ -0,0 +1,241 @@
+// The panel: what the companion looks like on someone else's checkout page.
+//
+// Every design decision here is about not being the thing that ruins a
+// purchase. It is anchored, not floating over the pay button. It never takes
+// focus, never traps the keyboard, and never blocks a click. It opens collapsed
+// to a single line when there is nothing alarming and expands itself only when
+// there is a red flag, which is the one case where an interruption is earned.
+//
+// It is built in a shadow root so a merchant's stylesheet cannot restyle it and
+// ours cannot leak onto their page. panel.css styles only the host element.
+
+const SEVERITY_LABEL = { flag: 'Worth checking', notice: 'Good to know', info: 'For reference' };
+
+export function mount({ speak = true } = {}) {
+ const host = document.createElement('div');
+ host.className = 'threews-checkout-companion';
+ host.setAttribute('role', 'complementary');
+ host.setAttribute('aria-label', 'three.ws checkout companion');
+ const root = host.attachShadow({ mode: 'open' });
+ root.innerHTML = template();
+ document.body.appendChild(host);
+
+ const $ = (sel) => root.querySelector(sel);
+ const card = $('.card');
+ const body = $('.body');
+ const status = $('.status');
+ const toggle = $('.toggle');
+
+ let expanded = false;
+ const setExpanded = (next) => {
+ expanded = next;
+ card.classList.toggle('expanded', expanded);
+ toggle.setAttribute('aria-expanded', String(expanded));
+ toggle.title = expanded ? 'Collapse' : 'Expand';
+ };
+
+ toggle.addEventListener('click', () => setExpanded(!expanded));
+ $('.close').addEventListener('click', () => host.remove());
+ // Escape closes it, and only when the panel itself has focus: a checkout
+ // form uses Escape for its own dialogs and we do not get to steal that.
+ root.addEventListener('keydown', (e) => {
+ if (e.key === 'Escape') host.remove();
+ });
+
+ const api = {
+ setState(state, data) {
+ card.dataset.state = state;
+ if (state === 'reading') {
+ status.textContent = 'Reading this page…';
+ body.innerHTML = '<p class="muted">Checking the total, the terms, and anything that repeats.</p>';
+ return;
+ }
+ if (state === 'error') {
+ status.textContent = 'Could not read this page';
+ body.innerHTML = `<p class="muted">${escapeHtml(data?.message || 'The read did not complete.')}</p>${
+ data?.code === 'unauthorized'
+ ? '<p class="muted">Open the extension and connect your three.ws account.</p>'
+ : ''
+ }`;
+ setExpanded(true);
+ return;
+ }
+ render(data);
+ },
+ destroy() {
+ host.remove();
+ },
+ };
+
+ function render(result) {
+ const findings = result?.findings || [];
+ const flags = findings.filter((f) => f.severity === 'flag');
+
+ if (!findings.length) {
+ status.textContent = 'Nothing unusual on this page';
+ body.innerHTML = [
+ '<p class="muted">The total matches what you were shown and the page does not describe a repeating charge.</p>',
+ redactionNote(result),
+ ].join('');
+ setExpanded(false);
+ return;
+ }
+
+ status.textContent = flags.length
+ ? `${flags.length} thing${flags.length === 1 ? '' : 's'} worth checking`
+ : `${findings.length} note${findings.length === 1 ? '' : 's'} on this page`;
+
+ body.innerHTML = [
+ `<ul class="findings">${findings.map(findingHtml).join('')}</ul>`,
+ result.reading_status === 'unavailable'
+ ? '<p class="muted">The terms were not read this time, so only the amounts were checked.</p>'
+ : '',
+ redactionNote(result),
+ ].join('');
+
+ // Expand on a red flag, stay out of the way otherwise. This is the whole
+ // interruption policy and it is one line on purpose.
+ setExpanded(flags.length > 0);
+
+ if (speak && result.spoken) say(result.spoken);
+ }
+
+ function say(line) {
+ try {
+ if (!('speechSynthesis' in window)) return;
+ const utterance = new SpeechSynthesisUtterance(line);
+ utterance.rate = 1.02;
+ utterance.volume = 0.9;
+ window.speechSynthesis.speak(utterance);
+ } catch {
+ // A tab that refuses speech still shows the panel. The text is the
+ // product; the voice is the flourish.
+ }
+ }
+
+ return api;
+}
+
+function findingHtml(f) {
+ return [
+ `<li class="finding ${escapeHtml(f.severity)}">`,
+ `<span class="badge">${escapeHtml(SEVERITY_LABEL[f.severity] || 'Note')}</span>`,
+ `<strong>${escapeHtml(f.title)}</strong>`,
+ `<p>${escapeHtml(f.detail || '')}</p>`,
+ f.evidence ? `<blockquote>${escapeHtml(f.evidence)}</blockquote>` : '',
+ '</li>',
+ ].join('');
+}
+
+function redactionNote(result) {
+ const n = result?.redactions || 0;
+ return `<p class="privacy">${
+ n
+ ? `${n} piece${n === 1 ? '' : 's'} of personal data removed before this page was read.`
+ : 'No card, contact, or account details were found in the text read.'
+ } Nothing about this page is stored.</p>`;
+}
+
+function escapeHtml(value) {
+ return String(value ?? '').replace(/[&<>"']/g, (c) => ({
+ '&': '&amp;',
+ '<': '&lt;',
+ '>': '&gt;',
+ '"': '&quot;',
+ "'": '&#39;',
+ })[c]);
+}
+
+function template() {
+ return `
+<style>
+ :host { all: initial; }
+ *, *::before, *::after { box-sizing: border-box; }
+ .card {
+ /* The host is pointer-transparent so the panel can never sit between a
+ person and the button they came to press; the card takes events back
+ for itself only. */
+ pointer-events: auto;
+ font: 14px/1.45 -apple-system, BlinkMacSystemFont, "Segoe UI", Inter, system-ui, sans-serif;
+ width: 340px;
+ max-width: calc(100vw - 32px);
+ background: #ffffff;
+ color: #14161a;
+ border: 1px solid rgba(16, 18, 22, 0.12);
+ border-radius: 14px;
+ box-shadow: 0 18px 48px rgba(12, 14, 18, 0.18);
+ overflow: hidden;
+ transform: translateY(8px);
+ opacity: 0;
+ animation: rise 260ms cubic-bezier(0.22, 1, 0.36, 1) forwards;
+ }
+ @keyframes rise { to { transform: translateY(0); opacity: 1; } }
+ @media (prefers-reduced-motion: reduce) {
+ .card { animation: none; opacity: 1; transform: none; }
+ }
+ header {
+ display: flex; align-items: center; gap: 10px;
+ padding: 12px 12px 12px 14px;
+ border-bottom: 1px solid rgba(16, 18, 22, 0.08);
+ }
+ .dot {
+ width: 26px; height: 26px; border-radius: 50%; flex: none;
+ background: linear-gradient(140deg, #6d5cff, #21d4c2);
+ }
+ .status { font-weight: 600; flex: 1; min-width: 0; }
+ button {
+ font: inherit; border: 0; background: transparent; cursor: pointer;
+ color: #5b616e; border-radius: 8px; width: 28px; height: 28px; flex: none;
+ transition: background 120ms ease, color 120ms ease;
+ }
+ button:hover { background: rgba(16, 18, 22, 0.06); color: #14161a; }
+ button:focus-visible { outline: 2px solid #6d5cff; outline-offset: 2px; }
+ .body { display: none; padding: 4px 14px 14px; }
+ .card.expanded .body { display: block; }
+ .toggle svg { transition: transform 160ms ease; }
+ .card.expanded .toggle svg { transform: rotate(180deg); }
+ ul.findings { list-style: none; margin: 10px 0 0; padding: 0; display: grid; gap: 12px; }
+ .finding { border-left: 3px solid #c9ccd4; padding-left: 10px; }
+ .finding.flag { border-left-color: #e0483c; }
+ .finding.notice { border-left-color: #e0a03c; }
+ .finding strong { display: block; margin-top: 2px; }
+ .finding p { margin: 4px 0 0; color: #3d434f; }
+ .badge {
+ font-size: 11px; font-weight: 600; letter-spacing: 0.02em;
+ text-transform: uppercase; color: #6b7280;
+ }
+ .finding.flag .badge { color: #c23a2f; }
+ blockquote {
+ margin: 6px 0 0; padding: 6px 8px; font-size: 12.5px; color: #4b5160;
+ background: rgba(16, 18, 22, 0.04); border-radius: 6px;
+ }
+ .muted { color: #5b616e; margin: 8px 0 0; }
+ .privacy { font-size: 12px; color: #6b7280; margin: 12px 0 0; }
+ @media (prefers-color-scheme: dark) {
+ .card { background: #16181d; color: #edeff3; border-color: rgba(255,255,255,0.12); }
+ header { border-bottom-color: rgba(255,255,255,0.08); }
+ button { color: #9aa1ae; }
+ button:hover { background: rgba(255,255,255,0.08); color: #edeff3; }
+ .finding p { color: #b9bfca; }
+ .muted, .privacy, .badge { color: #9aa1ae; }
+ blockquote { background: rgba(255,255,255,0.06); color: #c3c9d4; }
+ }
+</style>
+<div class="card" data-state="reading">
+ <header>
+ <div class="dot" aria-hidden="true"></div>
+ <span class="status">Reading this page…</span>
+ <button class="toggle" aria-expanded="false" title="Expand" aria-label="Expand findings">
+ <svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-hidden="true">
+ <path d="M3 5.5 7 9.5 11 5.5" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>
+ </svg>
+ </button>
+ <button class="close" title="Dismiss" aria-label="Dismiss">
+ <svg width="12" height="12" viewBox="0 0 12 12" fill="none" aria-hidden="true">
+ <path d="M2.5 2.5l7 7m0-7l-7 7" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/>
+ </svg>
+ </button>
+ </header>
+ <div class="body"></div>
+</div>`;
+}
diff --git a/scripts/companion-e2e.mjs b/scripts/companion-e2e.mjs
new file mode 100644
index 000000000..72e0c01fb
--- /dev/null
+++ b/scripts/companion-e2e.mjs
@@ -0,0 +1,184 @@
+// End-to-end exercise of the companion against the REAL database and the REAL
+// handlers, with no HTTP server in between: it calls the exported handlers with
+// mock req/res objects exactly as the Cloud Run router does, on a throwaway
+// user it deletes afterwards.
+//
+// npm run companion:e2e
+//
+// It needs DATABASE_URL (.env.local), writes only rows it owns, and exits
+// non-zero on the first failed check, so it is safe to run against production
+// and useful as a post-deploy proof that the whole path still works: settings
+// provisioning, the bridge endpoint, triage, contact attribution, quiet hours,
+// idempotency, the feed, and the live SSE stream.
+
+const { sql } = await import('../api/_lib/db.js');
+
+// A throwaway user, cleaned up at the end.
+const email = `companion-e2e-${Date.now()}@example.test`;
+const [user] = await sql`
+ insert into users (email, username, password_hash)
+ values (${email}, ${`ce2e${Date.now()}`}, 'x')
+ returning id, email
+`;
+console.log('user', user.id);
+
+function mockRes() {
+ const res = {
+ statusCode: 0,
+ headers: {},
+ body: '',
+ writableEnded: false,
+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },
+ getHeader(k) { return this.headers[k.toLowerCase()]; },
+ removeHeader(k) { delete this.headers[k.toLowerCase()]; },
+ writeHead(code, hdrs) { this.statusCode = code; Object.assign(this.headers, hdrs || {}); return this; },
+ write(chunk) { this.body += chunk; return true; },
+ end(chunk) { if (chunk) this.body += chunk; this.writableEnded = true; return this; },
+ on() {},
+ json() { try { return JSON.parse(this.body); } catch { return this.body; } },
+ };
+ return res;
+}
+
+function mockReq({ method = 'GET', url = '/', body = null, headers = {}, query = {} } = {}) {
+ const payload = body ? JSON.stringify(body) : '';
+ const req = {
+ method,
+ url,
+ query,
+ headers: { host: 'three.ws', 'content-type': 'application/json', ...headers },
+ socket: { remoteAddress: '127.0.0.1' },
+ on(event, handler) {
+ if (event === 'data' && payload) handler(Buffer.from(payload));
+ if (event === 'end') handler();
+ return req;
+ },
+ [Symbol.asyncIterator]: async function* () { if (payload) yield Buffer.from(payload); },
+ };
+ return req;
+}
+
+async function call(modulePath, options) {
+ const mod = await import(modulePath);
+ const res = mockRes();
+ await mod.default(mockReq(options), res);
+ return { status: res.statusCode, data: res.json() };
+}
+
+const results = [];
+function check(name, ok, detail = '') {
+ results.push({ name, ok, detail });
+ console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${detail ? ` ${detail}` : ''}`);
+}
+
+try {
+ // 1. Settings provisioning (this is what a first page load does).
+ const { getSettings, upsertContact, listEvents } = await import('../api/_lib/companion/store.js');
+ const settings = await getSettings(user.id);
+ check('settings provision a bridge token', /^cmp_/.test(settings.ingest_token), settings.ingest_token.slice(0, 12) + '…');
+ check('default threshold is 60', settings.threshold === 60);
+
+ // 2. The bridge endpoint, with the real token, through the real handler.
+ const low = await call('../api/companion/ingest.js', {
+ method: 'POST',
+ url: '/api/companion/ingest',
+ headers: { authorization: `Bearer ${settings.ingest_token}` },
+ body: { title: 'Weekly newsletter: 10 things to read', sender: 'Digest', sender_id: '[email protected]', app: 'Email' },
+ });
+ check('a newsletter is stored, not spoken', low.status === 201 && low.data.event.delivered === false, `score ${low.data?.event?.importance}`);
+
+ const high = await call('../api/companion/ingest.js', {
+ method: 'POST',
+ url: '/api/companion/ingest',
+ headers: { authorization: `Bearer ${settings.ingest_token}` },
+ body: { title: 'Your verification code is 449201', sender: 'Bank', sender_id: '[email protected]', app: 'Messages', priority: 'high' },
+ });
+ check('a one-time code is delivered', high.status === 201 && high.data.event.delivered === true, `score ${high.data?.event?.importance}`);
+
+ // 3. Idempotency: the same id twice is one delivery.
+ const once = await call('../api/companion/ingest.js', {
+ method: 'POST', url: '/api/companion/ingest',
+ headers: { authorization: `Bearer ${settings.ingest_token}` },
+ body: { id: 'stable-1', title: 'Sarah is at the door', sender: 'Sarah' },
+ });
+ const twice = await call('../api/companion/ingest.js', {
+ method: 'POST', url: '/api/companion/ingest',
+ headers: { authorization: `Bearer ${settings.ingest_token}` },
+ body: { id: 'stable-1', title: 'Sarah is at the door', sender: 'Sarah' },
+ });
+ check('a retry is a duplicate, not a second delivery', once.status === 201 && twice.data.duplicate === true);
+
+ // 4. A bad token is refused.
+ const refused = await call('../api/companion/ingest.js', {
+ method: 'POST', url: '/api/companion/ingest',
+ headers: { authorization: 'Bearer cmp_not_a_real_token' },
+ body: { title: 'should not land' },
+ });
+ check('an unknown token is refused', refused.status === 401);
+
+ // 5. Contacts change who delivers, and how loudly.
+ const contact = await upsertContact(user.id, {
+ identifier: '@sarah',
+ display_name: 'Sarah',
+ avatar_glb_url: 'https://three.ws/avatars/michelle.glb',
+ voice: 'nova',
+ priority_boost: 30,
+ });
+ const fromContact = await call('../api/companion/ingest.js', {
+ method: 'POST', url: '/api/companion/ingest',
+ headers: { authorization: `Bearer ${settings.ingest_token}` },
+ body: { title: 'downstairs, cannot find your door', sender: 'Sarah', sender_id: '@sarah', app: 'Telegram' },
+ });
+ check('a saved contact clears the bar', fromContact.data?.event?.delivered === true, `score ${fromContact.data?.event?.importance}`);
+ const [stored] = await sql`select contact_id from companion_events where user_id = ${user.id} and title like '%cannot find%'`;
+ check('the delivery is attributed to the contact', stored?.contact_id === contact.id);
+
+ // 6. Quiet hours silence even a loud message.
+ const { updateSettings } = await import('../api/_lib/companion/store.js');
+ const hour = new Date().getUTCHours();
+ await updateSettings(user.id, { quiet_start: hour, quiet_end: (hour + 2) % 24, timezone: 'UTC' });
+ const quiet = await call('../api/companion/ingest.js', {
+ method: 'POST', url: '/api/companion/ingest',
+ headers: { authorization: `Bearer ${settings.ingest_token}` },
+ body: { title: 'URGENT: emergency, call me now', sender: 'Sarah', sender_id: '@sarah', priority: 'high' },
+ });
+ check('quiet hours hold a loud message', quiet.data?.event?.delivered === false, `score ${quiet.data?.event?.importance}`);
+ await updateSettings(user.id, { quiet_start: null, quiet_end: null });
+
+ // 7. The feed reads back with scores and reasons.
+ const feed = await listEvents(user.id, { limit: 20 });
+ check('the feed holds every message, loud and quiet', feed.length === 5, `${feed.length} events`);
+ check('every event carries a reason', feed.every((e) => e.reason && e.spoken_line));
+
+ // 8. Source validation refuses a bad credential before storing it.
+ const badSource = await call('../api/companion/sources/index.js', {
+ method: 'POST', url: '/api/companion/sources',
+ body: { kind: 'calendar', ics_url: 'https://example.com/not-a-calendar' },
+ });
+ check('an unauthenticated source connect is refused', badSource.status === 401);
+
+ // 9. The SSE stream authenticates with the bridge token and replays.
+ const streamMod = await import('../api/companion/stream.js');
+ const res = mockRes();
+ const req = mockReq({
+ method: 'GET',
+ url: `/api/companion/stream?since=${encodeURIComponent(new Date(Date.now() - 3600_000).toISOString())}`,
+ headers: { authorization: `Bearer ${settings.ingest_token}` },
+ });
+ const handled = streamMod.default(req, res);
+ await new Promise((r) => setTimeout(r, 1200));
+ res.writableEnded = true;
+ check('the stream says hello and replays deliveries', res.body.includes('event: hello') && res.body.includes('event: delivery'),
+ `${(res.body.match(/event: delivery/g) || []).length} deliveries`);
+ await handled?.catch?.(() => {});
+} finally {
+ await sql`delete from companion_events where user_id = ${user.id}`;
+ await sql`delete from companion_contacts where user_id = ${user.id}`;
+ await sql`delete from companion_sources where user_id = ${user.id}`;
+ await sql`delete from companion_settings where user_id = ${user.id}`;
+ await sql`delete from users where id = ${user.id}`;
+ console.log('\ncleaned up');
+ const failed = results.filter((r) => !r.ok);
+ console.log(`${results.length - failed.length}/${results.length} checks passed`);
+ process.exit(failed.length ? 1 : 0);
+}