AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).
test(ui): run the frame's confirm flow with a faked fetch and FrameConfirm (#641)
ladislav-urban2da785b2b078
diff --git a/packages/ui/scripts/cardActions.test.mjs b/packages/ui/scripts/cardActions.test.mjsindex b4970fe3..65a5ead6 100644--- a/packages/ui/scripts/cardActions.test.mjs+++ b/packages/ui/scripts/cardActions.test.mjs@@ -6,9 +6,11 @@ import assert from "node:assert/strict";import { readFileSync } from "node:fs";import test from "node:test";import {+ AFTER_INPUT_MS,CardActionNotConfirmed,cardActionFor,frameActionFor,+ frameGate,messageOf,ownPageFor,} from "../src/lib/cardActions.ts";@@ -118,13 +120,134 @@ test("a browser that can't tell the frame is seen answers on this app's own pagetest("the frame checks every request, in any frame, and asks about what may have been lured", () => {const provider = read("../src/components/embed/EmbedProvider.tsx");assert.match(provider, /if \(window\.top === window\.self\) return;/);- assert.match(provider, /const action = frameActionFor\(method, url, init\?\.body, HOST_CALLS\);/);- assert.match(provider, /action\.card \|\| Date\.now\(\) - lastInput\.current < AFTER_INPUT_MS/);+ assert.match(provider, /const current = frameGate\(original, HOST_CALLS, setPending\);/);+ assert.match(provider, /window\.fetch = current\.fetch;/);+ assert.match(provider, /if \(event\.isTrusted\) current\.input\(\);/);// A drop or a paste is input too: a page over the frame can put its own// file in a drag.assert.match(provider, /const INPUT_EVENTS = \["pointerdown", "keydown", "drop", "paste"\] as const;/);- assert.match(provider, /if \(asks && !\(await confirm\(action\)\)\) throw new CardActionNotConfirmed\(\);/);// It asks inside the frame, and never opens a window.assert.match(provider, /<FrameConfirm action=\{pending\.action\} onAnswer=\{answer\} \/>/);assert.doesNotMatch(provider, /window\.open\(/);});++// frameGate run for real: a faked fetch records what reached the API, and a+// faked FrameConfirm records what was asked and answers it.+function gateHarness() {+ const sent = [];+ const shown = [];+ let clock = 1_000_000;+ const send = async (input, init) => {+ sent.push(`${init?.method ?? "GET"} ${input}`);+ return new Response("{}");+ };+ const gate = frameGate(send, CALLS, (ask) => shown.push(ask), () => clock);+ const asked = () => shown.filter(Boolean);+ const tick = (ms) => {+ clock += ms;+ };+ // Lets a pending fetch reach its question.+ const settle = () => new Promise((resolve) => setImmediate(resolve));+ return { gate, sent, shown, asked, tick, settle };+}++const APPROVE = ["/api/backend/decisions/7/approve", { method: "POST" }];+const REJECT = ["/api/backend/decisions/8/reject", { method: "POST" }];+const PAUSE = ["/api/backend/executive/pause", { method: "POST" }];++test("a card action asks, and a Yes sends it", async () => {+ const { gate, sent, shown, asked, settle } = gateHarness();+ const call = gate.fetch(...APPROVE);+ await settle();+ assert.equal(asked().length, 1);+ assert.equal(asked()[0].action.verb, "approve");+ assert.deepEqual(sent, []);+ gate.answer(true);+ assert.equal((await call).status, 200);+ assert.deepEqual(sent, ["POST /api/backend/decisions/7/approve"]);+ // The question is taken down.+ assert.equal(shown.at(-1), null);+});++test("a No throws and sends nothing", async () => {+ const { gate, sent, settle } = gateHarness();+ const call = gate.fetch(...APPROVE);+ await settle();+ gate.answer(false);+ await assert.rejects(call, CardActionNotConfirmed);+ assert.deepEqual(sent, []);+});++test("one question at a time: a second change while one is asked is refused", async () => {+ const { gate, sent, asked, settle } = gateHarness();+ const first = gate.fetch(...APPROVE);+ await settle();+ // Refused at once, never shown, never sent, and the first question stays.+ await assert.rejects(gate.fetch(...REJECT), CardActionNotConfirmed);+ assert.equal(asked().length, 1);+ assert.equal(asked()[0].action.decisionId, 7);+ gate.answer(true);+ await first;+ assert.deepEqual(sent, ["POST /api/backend/decisions/7/approve"]);+ // Once answered, the next one asks again rather than riding on that Yes.+ const next = gate.fetch(...REJECT);+ await settle();+ assert.equal(asked().length, 2);+ gate.answer(false);+ await assert.rejects(next, CardActionNotConfirmed);+ assert.deepEqual(sent, ["POST /api/backend/decisions/7/approve"]);+});++test("an answer with no question pending does nothing", () => {+ const { gate, shown, sent } = gateHarness();+ gate.answer(true);+ assert.deepEqual(sent, []);+ assert.deepEqual(shown, [null]);+});++test("a change off the host list asks only soon after input, or soon after an answer", async () => {+ const { gate, sent, asked, tick, settle } = gateHarness();+ // On its own, long after any input: sent without asking.+ await gate.fetch(...PAUSE);+ assert.equal(asked().length, 0);+ // Right after a click: asks.+ gate.input();+ tick(AFTER_INPUT_MS - 1);+ const lured = gate.fetch(...PAUSE);+ await settle();+ assert.equal(asked().length, 1);+ gate.answer(true);+ await lured;+ // A Yes counts as input: what it sets off next asks again.+ tick(AFTER_INPUT_MS - 1);+ const after = gate.fetch(...PAUSE);+ await settle();+ assert.equal(asked().length, 2);+ gate.answer(true);+ await after;+ // Once that has passed, the page is on its own again.+ tick(AFTER_INPUT_MS);+ await gate.fetch(...PAUSE);+ assert.equal(asked().length, 2);+ assert.equal(sent.length, 4);+});++test("reads and host-list calls never ask, even right after input", async () => {+ const { gate, sent, asked } = gateHarness();+ gate.input();+ await gate.fetch("/api/backend/today");+ await gate.fetch("/api/backend/alerts/3/ack", { method: "POST" });+ await gate.fetch(new Request("http://this.app/api/backend/today"));+ assert.equal(asked().length, 0);+ assert.equal(sent.length, 3);+});++test("a Request's own method counts, not just init's", async () => {+ const { gate, sent, asked, settle } = gateHarness();+ const call = gate.fetch(new Request("http://this.app/api/backend/decisions/7/approve", { method: "POST" }));+ await settle();+ assert.equal(asked().length, 1);+ gate.answer(false);+ await assert.rejects(call, CardActionNotConfirmed);+ assert.deepEqual(sent, []);+});diff --git a/packages/ui/src/components/embed/EmbedProvider.tsx b/packages/ui/src/components/embed/EmbedProvider.tsxindex c13f03e2..5e3c16f3 100644--- a/packages/ui/src/components/embed/EmbedProvider.tsx+++ b/packages/ui/src/components/embed/EmbedProvider.tsx@@ -3,7 +3,7 @@import { createContext, useContext, useEffect, useRef, useState } from "react";import FrameConfirm from "@/components/embed/FrameConfirm";-import { CardActionNotConfirmed, frameActionFor, type CardAction } from "@/lib/cardActions";+import { frameGate, type FrameAsk, type FrameGate } from "@/lib/cardActions";import HOST_LIST from "@/lib/host-list.json";import {acceptsEvent,@@ -28,9 +28,6 @@ import {// over the frame could have lured it.const HOST_CALLS = HOST_LIST.calls.map(([method, pattern]) => [method, pattern] as const);-// A change made this soon after a click or a key in the frame may have been-// lured, so it asks; later than that, the page made it on its own.-const AFTER_INPUT_MS = 10_000;// What counts as input: a click, a key, a drop or a paste (a page over the// frame can lure any of them, and put its own file in a drag).const INPUT_EVENTS = ["pointerdown", "keydown", "drop", "paste"] as const;@@ -49,8 +46,6 @@ export function useEmbed(): EmbedState {return useContext(EmbedContext);}-type Pending = { action: CardAction; resolve: (ok: boolean) => void };-function applyTheme(theme: EmbedTheme, font: string | null): void {const root = document.documentElement;root.dataset.theme = theme.mode;@@ -72,9 +67,8 @@ export default function EmbedProvider({children: React.ReactNode;}) {const [state, setState] = useState<EmbedState>(NOT_EMBEDDED);- const [pending, setPending] = useState<Pending | null>(null);- const pendingRef = useRef<Pending | null>(null);- const lastInput = useRef(0);+ const [pending, setPending] = useState<FrameAsk | null>(null);+ const gate = useRef<FrameGate | null>(null);// The handshake: `ready` to the parent, addressed to each listed host// origin (the browser delivers it only to the one the parent is), then@@ -105,44 +99,26 @@ export default function EmbedProvider({}, [hostOrigins, version]);// In any frame: every card action and chat message, and any change off- // the host list that follows a click, waits for a Yes in FrameConfirm.+ // the host list that follows a click, waits for a Yes in FrameConfirm+ // (lib/cardActions.ts, frameGate).useEffect(() => {if (window.top === window.self) return;+ const original = window.fetch;+ const current = frameGate(original, HOST_CALLS, setPending);+ gate.current = current;const onInput = (event: Event) => {- if (event.isTrusted) lastInput.current = Date.now();+ if (event.isTrusted) current.input();};for (const type of INPUT_EVENTS) window.addEventListener(type, onInput, true);- const original = window.fetch;- const confirm = (action: CardAction) =>- new Promise<boolean>((resolve) => {- // One at a time: a second action while one is asked about is refused.- if (pendingRef.current) return resolve(false);- const next = { action, resolve };- pendingRef.current = next;- setPending(next);- });- window.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {- const method = init?.method ?? (input instanceof Request ? input.method : "GET");- const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;- const action = frameActionFor(method, url, init?.body, HOST_CALLS);- const asks = action !== null && (action.card || Date.now() - lastInput.current < AFTER_INPUT_MS);- if (asks && !(await confirm(action))) throw new CardActionNotConfirmed();- return original(input, init);- };+ window.fetch = current.fetch;return () => {window.fetch = original;for (const type of INPUT_EVENTS) window.removeEventListener(type, onInput, true);+ gate.current = null;};}, []);- const answer = (ok: boolean) => {- const current = pendingRef.current;- pendingRef.current = null;- // A Yes is input too: what the confirmed change sets off next asks again.- lastInput.current = Date.now();- setPending(null);- current?.resolve(ok);- };+ const answer = (ok: boolean) => gate.current?.answer(ok);return (<EmbedContext.Provider value={state}>diff --git a/packages/ui/src/lib/cardActions.ts b/packages/ui/src/lib/cardActions.tsindex 3cce0cfb..313c38e2 100644--- a/packages/ui/src/lib/cardActions.ts+++ b/packages/ui/src/lib/cardActions.ts@@ -223,3 +223,63 @@ export class CardActionNotConfirmed extends Error {this.name = "CardActionNotConfirmed";}}++// A change made this soon after a click or a key in the frame may have been+// lured, so it asks; later than that, the page made it on its own.+export const AFTER_INPUT_MS = 10_000;++export type FrameAsk = { action: CardAction; resolve: (ok: boolean) => void };++export type FrameGate = {+ // window.fetch in the frame: asks first where `frameActionFor` says so.+ fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;+ // A trusted click, key, drop or paste in the frame.+ input: () => void;+ // The person's answer in FrameConfirm.+ answer: (ok: boolean) => void;+};++/**+ * The frame's check on every request (EmbedProvider): a card action always+ * asks, and any other change off `hostCalls` asks when it follows input+ * within AFTER_INPUT_MS. `show` puts the question up (FrameConfirm), or takes+ * it down with null. One question at a time: a second change while one is+ * asked is refused. A No, or a refusal, throws CardActionNotConfirmed and+ * never reaches `send`.+ */+export function frameGate(+ send: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>,+ hostCalls: readonly HostCall[],+ show: (ask: FrameAsk | null) => void,+ now: () => number = Date.now,+): FrameGate {+ let pending: FrameAsk | null = null;+ let lastInput = 0;+ const confirm = (action: CardAction) =>+ new Promise<boolean>((resolve) => {+ if (pending) return resolve(false);+ pending = { action, resolve };+ show(pending);+ });+ return {+ fetch: async (input, init) => {+ const method = init?.method ?? (input instanceof Request ? input.method : "GET");+ const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;+ const action = frameActionFor(method, url, init?.body, hostCalls);+ const asks = action !== null && (action.card || now() - lastInput < AFTER_INPUT_MS);+ if (asks && !(await confirm(action))) throw new CardActionNotConfirmed();+ return send(input, init);+ },+ input: () => {+ lastInput = now();+ },+ answer: (ok) => {+ const current = pending;+ pending = null;+ // A Yes is input too: what the confirmed change sets off next asks again.+ lastInput = now();+ show(null);+ current?.resolve(ok);+ },+ };+}