Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Page card: ask the rendered page whether it opens with a heading
luishron12315c43352cf70
diff --git a/shared/app-frame/heading.test.ts b/shared/app-frame/heading.test.tsnew file mode 100644index 0000000000..8394ef83cb--- /dev/null+++ b/shared/app-frame/heading.test.ts@@ -0,0 +1,110 @@+import { Window } from "happy-dom";+import { afterEach, describe, expect, it } from "vitest";++import { APP_HEADING_METHOD, APP_HELPER_SOURCE, APP_OPENS_WITH_HEADING_SOURCE } from "./helper.ts";++const pages: Window[] = [];+afterEach(async () => { for (const page of pages.splice(0)) await page.happyDOM.close(); });++function open(body: string, head = ""): Window {+ const page = new Window();+ pages.push(page);+ page.document.head.innerHTML = head;+ page.document.body.innerHTML = body;+ return page;+}++const opensWithHeading = (page: Window) =>+ (new Function(`return ${APP_OPENS_WITH_HEADING_SOURCE}`)() as (window: unknown, document: unknown) => boolean | null)(page, page.document);++describe("whether a page opens with a heading of its own", () => {+ it("is so when the first text it shows is a heading, whatever the heading says", () => {+ expect(opensWithHeading(open("<h1>Pricing</h1><p>body</p>"))).toBe(true);+ expect(opensWithHeading(open("<main><section><h2>Not the page's title at all</h2></section></main>"))).toBe(true);+ expect(opensWithHeading(open("<div role=\"heading\" aria-level=\"1\">Pricing</div><p>body</p>"))).toBe(true);+ });++ it("is not so when the first text it shows is anything else", () => {+ expect(opensWithHeading(open("<p>body</p><h1>Pricing</h1>"))).toBe(false);+ expect(opensWithHeading(open("<div class=\"tile\"><b>4.2.0</b> on the server</div><h2>Later</h2>"))).toBe(false);+ });++ it("does not count a heading the page hides with CSS", () => {+ expect(opensWithHeading(open("<h1 style=\"display:none\">Hidden</h1><p>body</p>"))).toBe(false);+ expect(opensWithHeading(open("<h1 class=\"gone\">Hidden</h1><p>body</p>", "<style>.gone{display:none}</style>"))).toBe(false);+ expect(opensWithHeading(open("<h1 style=\"visibility:hidden\">Hidden</h1><p>body</p>"))).toBe(false);+ expect(opensWithHeading(open("<header hidden><h1>Hidden</h1></header><p>body</p>"))).toBe(false);+ });++ it("looks past hidden text that comes before a heading", () => {+ expect(opensWithHeading(open("<p style=\"display:none\">Hidden</p><h1>Title</h1>"))).toBe(true);+ expect(opensWithHeading(open("<p class=\"gone\">Hidden</p><h1>Title</h1>", "<style>.gone{display:none}</style>"))).toBe(true);+ expect(opensWithHeading(open("<script>var a = 1;</script><template><p>x</p></template><noscript>off</noscript><h1>Title</h1>"))).toBe(true);+ });++ it("has no answer for a page that shows no text yet", () => {+ expect(opensWithHeading(open("<div id=\"root\"></div><script>render()</script>"))).toBeNull();+ });+});++describe("the page helper's heading report", () => {+ /** The helper in a fake frame over a real document: the host answers ui/initialize and keeps what the page reports. */+ function boot(body: string) {+ const page = open(body);+ const reports: (boolean | null)[] = [];+ const listeners = new Set<(event: { source: unknown; data: unknown }) => void>();+ const parent = {+ postMessage(data: { id?: string; method?: string; params?: { heading?: boolean | null } }) {+ if (data.method === APP_HEADING_METHOD) reports.push(data.params!.heading!);+ if (data.method === "ui/initialize") setTimeout(() => { for (const listener of listeners) listener({ source: parent, data: { jsonrpc: "2.0", id: data.id, result: {} } }); }, 0);+ },+ };+ const frame = {+ parent, innerWidth: 560, innerHeight: 400, scrollY: 0,+ addEventListener(type: string, listener: (event: { source: unknown; data: unknown }) => void) { if (type === "message") listeners.add(listener); },+ getComputedStyle: (element: unknown) => page.getComputedStyle(element as never),+ };+ Object.defineProperty(page.document, "readyState", { configurable: true, get: () => "complete" });+ new Function("window", "document", "MutationObserver", "ResizeObserver", "requestAnimationFrame", APP_HELPER_SOURCE)(+ frame, page.document, page.MutationObserver, undefined, (callback: () => void) => setTimeout(callback, 0));+ return { page, reports };+ }++ it("says once whether the page opens with a heading", async () => {+ const titled = boot("<h1>Pricing</h1><p>body</p>");+ await expect.poll(() => titled.reports).toEqual([true]);+ const plain = boot("<p>body</p>");+ await expect.poll(() => plain.reports).toEqual([false]);+ });++ it("waits for a page that draws itself from a script, and reports the heading the script inserts", async () => {+ const { page, reports } = boot("<div id=\"root\"></div>");+ await new Promise((resolve) => setTimeout(resolve, 50));+ expect(reports).toEqual([]);+ page.document.getElementById("root")!.innerHTML = "<h1>Drawn by a script</h1><p>body</p>";+ await expect.poll(() => reports).toEqual([true]);+ });++ it("says a jsx page is still drawing, then what it drew, however long its libraries take", async () => {+ const { page, reports } = boot("<div id=\"mausbot-root\"></div>");+ await new Promise((resolve) => setTimeout(resolve, 900));+ expect(reports).toEqual([null]);+ page.document.getElementById("mausbot-root")!.innerHTML = "<main><h1>Drawn by React</h1><p>body</p></main>";+ await expect.poll(() => reports).toEqual([null, true]);+ });++ it("says again when the page changes what it opens with", async () => {+ const { page, reports } = boot("<p>Loading the report</p>");+ await expect.poll(() => reports).toEqual([false]);+ page.document.body.innerHTML = "<h1>Report</h1>";+ await expect.poll(() => reports).toEqual([false, true]);+ page.document.querySelector("h1")!.setAttribute("style", "display:none");+ page.document.body.append(Object.assign(page.document.createElement("p"), { textContent: "body" }) as never);+ await expect.poll(() => reports).toEqual([false, true, false]);+ });++ it("settles on no heading for a page that never shows any text", async () => {+ const { reports } = boot("<canvas></canvas>");+ await expect.poll(() => reports, { timeout: 3_000 }).toEqual([false]);+ });+});diff --git a/shared/app-frame/helper.ts b/shared/app-frame/helper.tsindex 1281ac8a81..4d758d09fe 100644--- a/shared/app-frame/helper.ts+++ b/shared/app-frame/helper.ts@@ -10,7 +10,8 @@// }//// Outside a room it also reports the person's text selection (mausbot/notifications/selection), so the host can-// offer to cite it in the chat's composer.+// offer to cite it in the chat's composer. Everywhere it reports whether the page, as rendered, opens with a heading+// (mausbot/notifications/heading), so the host's card knows whether to put the page's title above it.//// A page pasted from an SDK build runs its own App beside this one: the helper's request ids are strings// ("mausbot:1"), never the SDK's numeric ones, and it answers no host request but teardown, so it never@@ -33,6 +34,51 @@ export const APP_SELECTION_METHOD = "mausbot/notifications/selection";/** One past the longest quote a chat citation holds, so the host can say a longer selection is too long. */export const APP_SELECTION_CHARS = 12_001;+/** Whether the page opens with a heading of its own, as rendered: { heading }. Sent again when that changes; null+ * once, from a page still drawing itself from a script, so the host waits for the answer instead of guessing. */+export const APP_HEADING_METHOD = "mausbot/notifications/heading";+/** A heading that starts lower than this is not what the page opens with (px). */+const HEADING_TOP = 96;+/** How long a page with nothing to read yet may still be drawing itself before it counts as having no heading. */+const HEADING_WAIT_MS = 600;+/** The same for a jsx page, whose libraries come over the network before it draws anything. */+const HEADING_DRAWING_MS = 8_000;++/** `(window, document) => true | false | null`: whether the first text the page shows sits in a heading near its top;+ * null while it shows no text at all. Text counts when no ancestor is `display: none` or `hidden`, it is not+ * `visibility: hidden`, and, where there is a layout to ask, its element is more than a pixel in size. */+export const APP_OPENS_WITH_HEADING_SOURCE = `function (window, document) {+ var body = document.body;+ if (!body) return null;+ var skipped = { SCRIPT: 1, STYLE: 1, TEMPLATE: 1, NOSCRIPT: 1, TITLE: 1 };+ var laidOut = document.documentElement.getBoundingClientRect().width > 0;+ var budget = 2000;+ var first = function (element) {+ if (skipped[element.tagName] || element.hasAttribute("hidden")) return null;+ var style = window.getComputedStyle(element);+ if (style.display === "none") return null;+ var shown = style.visibility !== "hidden" && style.visibility !== "collapse";+ for (var child = element.firstChild; child; child = child.nextSibling) {+ if ((budget -= 1) < 0) return null;+ if (child.nodeType === 3) {+ if (!shown || !/\\S/.test(child.nodeValue || "")) continue;+ if (!laidOut) return element;+ var box = element.getBoundingClientRect();+ if (box.width > 1 && box.height > 1) return element;+ } else if (child.nodeType === 1) {+ var found = first(child);+ if (found) return found;+ }+ }+ return null;+ };+ var holder = first(body);+ if (!holder) return null;+ var heading = holder.closest("h1, h2, h3, [role=heading]");+ if (!heading) return false;+ return !laidOut || heading.getBoundingClientRect().top + (window.scrollY || 0) <= ${HEADING_TOP};+}`;+/** Plain ES2017 with no imports: it runs as written in every browser engine the apps ship in. */const helperSource = (room: boolean) => `(function () {"use strict";@@ -156,6 +202,39 @@ const helperSource = (room: boolean) => `(function () {window.addEventListener("load", report);report();};+ // Whether the page opens with a heading, looked at again whenever the page changes: a page that draws itself from a+ // script has nothing to read at first, so "no text yet" waits a moment before it counts as "no heading".+ var opensWithHeading = ${APP_OPENS_WITH_HEADING_SOURCE};+ var watchHeading = function () {+ var last;+ var queued = false;+ var waiting = null;+ var later = typeof requestAnimationFrame === "function" ? requestAnimationFrame : function (fn) { return setTimeout(fn, 16); };+ var send = function (heading) {+ if (waiting !== null) { clearTimeout(waiting); waiting = null; }+ if (heading !== last) { last = heading; notify("${APP_HEADING_METHOD}", { heading: heading }); }+ };+ var look = function () {+ if (queued || document.readyState !== "complete") return;+ queued = true;+ later(function () {+ queued = false;+ var found = opensWithHeading(window, document);+ if (found !== null || last !== undefined) return send(found === true);+ if (waiting !== null) return;+ var mount = document.getElementById("mausbot-root");+ var drawing = Boolean(mount) && !mount.firstChild;+ if (drawing) notify("${APP_HEADING_METHOD}", { heading: null });+ waiting = setTimeout(function () { waiting = null; send(false); }, drawing ? ${HEADING_DRAWING_MS} : ${HEADING_WAIT_MS});+ });+ };+ if (typeof MutationObserver === "function") {+ new MutationObserver(look).observe(root, { childList: true, subtree: true, characterData: true, attributes: true, attributeFilter: ["class", "style", "hidden"] });+ }+ window.addEventListener("load", look);+ window.addEventListener("resize", look);+ look();+ };// What the person selects, and where it ends, so the host can offer to cite it as chat does. Not in a room.var watchSelection = function () {if (room || typeof document.getSelection !== "function") return;@@ -188,6 +267,8 @@ const helperSource = (room: boolean) => `(function () {}).then(function (result) {apply(result && result.hostContext);notify("ui/notifications/initialized");+ // Before the size, so the host hears both in one go and lays the card out once.+ watchHeading();watchSize();watchSelection();});diff --git a/src/components/app/AppChrome.tsx b/src/components/app/AppChrome.tsxindex 30021d3190..0d799a1e27 100644--- a/src/components/app/AppChrome.tsx+++ b/src/components/app/AppChrome.tsx@@ -6,6 +6,7 @@ import { openExternalLink } from "@/lib/app-links";import type { AppDoneState, AppNetwork } from "../../../shared/app";import { ASK_CHIP, ASK_CHIP_IDLE, ASK_QUIET_BUTTON } from "../AskCard";+const PAGE_ICON = "flex shrink-0 text-ink-secondary";export const APP_SURFACE = "w-full overflow-hidden rounded-2xl bg-composer ring-1 ring-composer-ring";const ICON_BUTTON ="flex size-7 shrink-0 items-center justify-center rounded-full text-ink-tertiary transition-colors hover:bg-ink/[0.07] hover:text-ink focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-focus disabled:opacity-40";@@ -82,7 +83,7 @@ export function PageCardFooter({ title, detail, updated, infoId, infoOpen, onInf}) {return (<div data-page-footer className="flex min-h-18 items-center gap-3 border-t border-ink/[0.08] px-5 py-4">- <span data-page-icon className="flex size-8 shrink-0 items-center justify-center rounded-xl bg-inset text-ink-secondary">+ <span data-page-icon className={PAGE_ICON}><AppWindow aria-hidden="true" size={16} /></span><div className="min-w-0 flex-1">diff --git a/src/components/app/AppFrame.tsx b/src/components/app/AppFrame.tsxindex 4d125a1761..91499506ff 100644--- a/src/components/app/AppFrame.tsx+++ b/src/components/app/AppFrame.tsx@@ -35,6 +35,8 @@ export interface AppFrameProps {maxHeight?: number;/** Text the person selected in the page, in window coordinates, or null once it is gone. */onSelection?(selection: AppSelection | null): void;+ /** Whether the page, as rendered, opens with a heading of its own; null while it is still drawing itself. */+ onHeading?(heading: boolean | null): void;}const refusal = (message: string): JsonRpcError => ({ code: RPC_HOST_REFUSED, message });@@ -63,6 +65,7 @@ export function AppFrame(props: AppFrameProps) {...(import.meta.env?.DEV ? { log: (params: unknown) => console.info("[app]", params) } : {}),...(fill ? { fill: true } : {}),onSelection: (selection) => latest.current.onSelection?.(selection),+ onHeading: (heading) => latest.current.onHeading?.(heading),adapter: {async callRpc(method, params) {const outcome = await callAppRpc({ botId, threadId, messageId, method, params });diff --git a/src/components/app/AppMessage.compact.test.ts b/src/components/app/AppMessage.compact.test.tsindex eec95ac1ce..ec0aa0abb7 100644--- a/src/components/app/AppMessage.compact.test.ts+++ b/src/components/app/AppMessage.compact.test.ts@@ -36,11 +36,14 @@ const card = () => host.querySelector<HTMLElement>("[data-app=a1]")!;const opener = () => card().querySelector<HTMLButtonElement>("[data-page-open]")!;const press = (element: HTMLElement) => act(async () => { element.click(); await new Promise((resolve) => setTimeout(resolve, 0)); });-let html: string;+/** happy-dom runs no script in the frame, so the page's word on its heading is played by a message from its window. */+const pageSays = (heading: boolean | null) => act(async () => {+ const view = card().querySelector("iframe")!.contentWindow;+ window.dispatchEvent(new MessageEvent("message", { data: { jsonrpc: "2.0", method: "mausbot/notifications/heading", params: { heading } }, source: view as MessageEventSource }));+});beforeEach(() => {- html = "<p>page</p>";- vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify(botHtmlDocument({ messageId: "a1", rev: 0, html })),+ vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify(botHtmlDocument({ messageId: "a1", rev: 0, html: "<p>page</p>" })),{ status: 200, headers: { "content-type": "application/json" } })));vi.stubGlobal("IntersectionObserver", undefined);forgetAppRows();@@ -84,24 +87,67 @@ describe("a bot's page as a compact card", () => {expect(card().className).not.toContain("max-w-[760px]");});- it("puts the title above a page that has no heading of its own", async () => {+ it("keeps the preview covered, with no title, until the page has said whether it opens with a heading", async () => {+ await render(row(payload()));+ const box = card().querySelector<HTMLElement>("[data-app-box]")!;+ expect(box.querySelector("[data-page-settling]")).not.toBeNull();+ expect(box.querySelector("[data-page-title]")).toBeNull();+ expect(box.querySelector("[data-page-fade]")).toBeNull();+ expect(box.querySelector("iframe")).not.toBeNull();+ });++ it("puts the title above a page that says it has no heading of its own", async () => {await render(row(payload()));+ await pageSays(false);const box = card().querySelector<HTMLElement>("[data-app-box]")!;expect(box.firstElementChild!.matches("[data-page-title]")).toBe(true);expect(box.firstElementChild!.textContent).toBe("Pricing");expect(box.querySelector("[data-page-title] ~ [data-app-frame-box]")).not.toBeNull();+ expect(box.querySelector("[data-page-settling]")).toBeNull();});- it("leaves the top of the preview to a page that opens with its own heading", async () => {- html = "<h1>Pricing</h1><p>page</p>";+ it("leaves the top of the preview to a page that says it opens with its own heading", async () => {await render(row(payload()));+ await pageSays(true);expect(card().querySelector("[data-page-title]")).toBeNull();+ expect(card().querySelector("[data-page-settling]")).toBeNull();expect(card().querySelector("[data-app-box]")!.firstElementChild!.matches("[data-app-frame-box]")).toBe(true);expect(card().querySelector("[data-page-footer]")!.textContent).toBe("PricingPage");});+ it("follows the page when it changes what it opens with, and remembers the answer for the next time the card is drawn", async () => {+ await render(row(payload()));+ await pageSays(false);+ await pageSays(true);+ expect(card().querySelector("[data-page-title]")).toBeNull();+ act(() => root.unmount());+ root = createRoot(host);+ await render(row(payload()));+ expect(card().querySelector("[data-page-settling]")).toBeNull();+ expect(card().querySelector("[data-page-title]")).toBeNull();+ });++ it("shows the preview with the title after a while when the page never says", async () => {+ await render(row(payload()));+ await act(async () => { await new Promise((resolve) => setTimeout(resolve, 1_600)); });+ expect(card().querySelector("[data-page-settling]")).toBeNull();+ expect(card().querySelector("[data-page-title]")!.textContent).toBe("Pricing");+ });++ it("keeps waiting for a page that says it is still drawing itself", async () => {+ await render(row(payload()));+ await pageSays(null);+ await act(async () => { await new Promise((resolve) => setTimeout(resolve, 1_600)); });+ expect(card().querySelector("[data-page-settling]")).not.toBeNull();+ expect(card().querySelector("[data-page-title]")).toBeNull();+ await pageSays(true);+ expect(card().querySelector("[data-page-settling]")).toBeNull();+ expect(card().querySelector("[data-page-title]")).toBeNull();+ });+it("fades the foot of a clipped preview with a plain gradient and parts it from the footer with a rule", async () => {await render(row(payload()));+ await pageSays(false);const fade = card().querySelector<HTMLElement>("[data-app-box] > [data-page-fade]")!;expect(fade.className).toContain("bg-gradient-to-t from-composer to-transparent");expect(fade.className).toContain("h-8");@@ -111,6 +157,7 @@ describe("a bot's page as a compact card", () => {it("shows a short page whole, with nothing over its foot", async () => {await render(row(payload({ height: 120 })));+ await pageSays(false);expect(card().querySelector<HTMLElement>("[data-app-box]")!.style.height).toBe("164px");expect(card().querySelector("[data-page-fade]")).toBeNull();});diff --git a/src/components/app/AppMessage.tsx b/src/components/app/AppMessage.tsxindex 78be64cd35..2168fc7da6 100644--- a/src/components/app/AppMessage.tsx+++ b/src/components/app/AppMessage.tsx@@ -14,7 +14,6 @@ import { PageCitationButton } from "../CitationUI";import { appendDraftAttachments } from "@/lib/drafts";import { useCanWriteIn } from "@/lib/cloud-guest";import { closePage, onPageOpened, openPage, openPageFor } from "@/lib/open-page";-import { pageOpensWithHeading } from "./page-heading";import { PAGE_HEIGHT, PAGE_PREVIEW_HEIGHT, PageFullScreen, PageNotes, PagePaneContext, PageToolbar, usePagePin, usePagePoint, usePageSave, usePageShare, usePageVersion } from "./PageTools";const WIDTH = "max-w-[760px]";@@ -24,10 +23,17 @@ const CARD_TITLE_HEIGHT = 44;const DOC_REUSE_MS = 60_000;const heights = new Map<string, number>();+/** Whether a page opens with a heading of its own, as it last said: by message id and version. */+const headings = new Map<string, boolean>();+/** How long a card waits for its page to say, before it shows the preview with the title above it. */+const HEADING_WAIT_MS = 1_500;+/** The same once the page has said it is still drawing itself. */+const HEADING_DRAWING_MS = 10_000;const docs = new Map<string, { doc: AppDocument; at: number }>();export function forgetAppRows(): void {heights.clear();+ headings.clear();docs.clear();}@@ -103,6 +109,7 @@ function AppRow({ botId, botName, threadId, message, payload, pool, room }: {const [problem, setProblem] = useState<AppFrameProblem | null>(null);// Text the person selected in the page, to cite in the composer as chat text is; never in a room.const [selection, setSelection] = useState<AppSelection | null>(null);+ const [heading, setHeading] = useState<{ key: string; opens: boolean | null } | null>(null);const yourAccess = store?.bots?.find((candidate) => candidate.id === botId)?.yourAccess;const canWrite = useCanWriteIn(threadId, yourAccess) !== false;const frame = useRef<AppFrameHandle | null>(null);@@ -165,6 +172,10 @@ function AppRow({ botId, botName, threadId, message, payload, pool, room }: {heights.set(`${message.id}:${rev}`, next);if (mounted.current) setHeight(next);}, [message.id, rev]);+ const onHeading = useCallback((next: boolean | null) => {+ if (next !== null) headings.set(`${message.id}:${rev}`, next);+ if (mounted.current) setHeading({ key: `${message.id}:${rev}`, opens: next });+ }, [message.id, rev]);const current = slot.live ? loaded?.doc : undefined;const point = usePagePoint({@@ -227,8 +238,20 @@ function AppRow({ botId, botName, threadId, message, payload, pool, room }: {const state = collapsed ? "collapsed" : current ? "live" : noPage ? "unavailable" : slot.live ? "loading" : "idle";const infoId = `${uid}-info`;- const srcdoc = compact ? current?.srcdoc : undefined;- const titled = useMemo(() => srcdoc !== undefined && !pageOpensWithHeading(srcdoc), [srcdoc]);+ // The page says, once it has rendered, whether it opens with a heading of its own; a card whose page does not gets+ // the title above the preview. Until the page has spoken the preview stays covered, so nothing moves under the eye.+ const said = heading?.key === `${message.id}:${rev}` ? heading.opens : undefined;+ const opens = said ?? headings.get(`${message.id}:${rev}`);+ const undecided = compact && Boolean(current) && opens === undefined;+ const drawing = said === null;+ const frameKey = loaded?.key;+ useEffect(() => {+ if (!undecided) return;+ const key = `${message.id}:${rev}`;+ const timer = setTimeout(() => setHeading({ key, opens: false }), drawing ? HEADING_DRAWING_MS : HEADING_WAIT_MS);+ return () => clearTimeout(timer);+ }, [undecided, drawing, frameKey, message.id, rev]);+ const titled = compact && Boolean(current) && opens === false;// The compact card clips the page at its natural size, so it reads as a preview of the real thing.const previewHeight = height + (titled ? CARD_TITLE_HEIGHT : 0);const boxHeight = compact ? Math.min(previewHeight, PAGE_PREVIEW_HEIGHT) : height;@@ -256,6 +279,7 @@ function AppRow({ botId, botName, threadId, message, payload, pool, room }: {height={height}handle={frame}onHeight={onHeight}+ {...(compact ? { onHeading } : {})}onProblem={setProblem}onTeardownRequested={onTeardownRequested}{...(page ? { maxHeight: PAGE_HEIGHT.cap } : {})}@@ -264,7 +288,12 @@ function AppRow({ botId, botName, threadId, message, payload, pool, room }: {) : (<AppPlaceholder height={boxHeight} loading={slot.live} open={slot.live ? undefined : reloadNow} />)}- {compact && current && previewHeight > PAGE_PREVIEW_HEIGHT && (+ {undecided && (+ <div data-page-settling className="absolute inset-0 bg-composer">+ <AppPlaceholder height={boxHeight} loading />+ </div>+ )}+ {compact && current && !undecided && previewHeight > PAGE_PREVIEW_HEIGHT && (<div data-page-fade aria-hidden="true" className="pointer-events-none absolute inset-x-0 bottom-0 h-8 bg-gradient-to-t from-composer to-transparent" />)}</div>diff --git a/src/components/app/app-frame-host.test.ts b/src/components/app/app-frame-host.test.tsindex 9300e16696..7a1e737af7 100644--- a/src/components/app/app-frame-host.test.ts+++ b/src/components/app/app-frame-host.test.ts@@ -176,6 +176,25 @@ describe("text the person selects in a page", () => {});});+describe("a page's word on whether it opens with a heading", () => {+ const HEADING = "mausbot/notifications/heading";++ it("is passed on each time the page says it, and only from the page's own window", () => {+ const onHeading = vi.fn();+ const host = mountAppFrame({ container, doc, title: "Coffee counter", height: 200, hostContext: {}, hostVersion: "1", adapter: adapter(), onHeading });+ const send = (data: unknown, source: unknown = host.iframe.contentWindow) => window.dispatchEvent(new MessageEvent("message", { data, source: source as MessageEventSource }));+ send({ jsonrpc: "2.0", method: HEADING, params: { heading: true } });+ send({ jsonrpc: "2.0", method: HEADING, params: { heading: false } });+ send({ jsonrpc: "2.0", method: HEADING, params: { heading: null } });+ send({ jsonrpc: "2.0", method: HEADING, params: { heading: "yes" } });+ send({ jsonrpc: "2.0", method: HEADING, params: {} });+ send({ jsonrpc: "2.0", id: 4, method: HEADING, params: { heading: true } });+ send({ jsonrpc: "2.0", method: HEADING, params: { heading: true } }, window);+ expect(onHeading.mock.calls).toEqual([[true], [false], [null]]);+ host.destroy();+ });+});+describe("a row leaving the page", () => {type Movable = { moveBefore?: (node: Node, child: Node | null) => void };const proto = HTMLElement.prototype as unknown as Movable;diff --git a/src/components/app/app-frame-host.ts b/src/components/app/app-frame-host.tsindex ee2f1c3cfe..f045a6e229 100644--- a/src/components/app/app-frame-host.ts+++ b/src/components/app/app-frame-host.ts@@ -1,6 +1,6 @@import type { AppDocument } from "../../../shared/app";import { APP_FRAME_LIMITS, createAppBridge, type AppBridgeAdapter, type AppHostContext } from "../../../shared/app-frame/bridge";-import { APP_SELECTION_CHARS, APP_SELECTION_METHOD } from "../../../shared/app-frame/helper";+import { APP_HEADING_METHOD, APP_SELECTION_CHARS, APP_SELECTION_METHOD } from "../../../shared/app-frame/helper";/** Exactly these two tokens: never allow-same-origin, allow-popups or allow-top-navigation, and no `allow`* attribute. */@@ -110,6 +110,16 @@ export function readPageSelection(data: unknown): AppSelection | null | undefinereturn finite(left) && finite(bottom) ? { text, left, bottom } : undefined;}+/** The page helper's word on whether the page opens with a heading, null while it is still drawing itself; undefined+ * for any other message. */+export function readPageHeading(data: unknown): boolean | null | undefined {+ if (!data || typeof data !== "object") return undefined;+ const message = data as { jsonrpc?: unknown; method?: unknown; id?: unknown; params?: { heading?: unknown } };+ if (message.jsonrpc !== "2.0" || message.method !== APP_HEADING_METHOD || message.id !== undefined) return undefined;+ const heading = message.params?.heading;+ return typeof heading === "boolean" || heading === null ? heading : undefined;+}+export interface AppFrameHostOptions {container: HTMLElement;doc: AppDocument;@@ -123,6 +133,8 @@ export interface AppFrameHostOptions {fill?: boolean;/** Text the person selected in a page that may message (never a room's), or null once it is gone: to cite it. */onSelection?(selection: AppSelection | null): void;+ /** Whether the page, as rendered, opens with a heading of its own; again whenever that changes. Null: still drawing. */+ onHeading?(heading: boolean | null): void;}export interface AppFrameHost {@@ -202,6 +214,11 @@ export function mountAppFrame(options: AppFrameHostOptions): AppFrameHost {},});const onMessage = (event: MessageEvent) => {+ const heading = event.source === iframe.contentWindow ? readPageHeading(event.data) : undefined;+ if (heading !== undefined) {+ if (!leaving) options.onHeading?.(heading);+ return;+ }const selection = event.source === iframe.contentWindow ? readPageSelection(event.data) : undefined;if (selection === undefined) return bridge.handleMessage({ source: event.source, data: event.data });// Only to cite in the person's own chat: never in a room, and only what they selected themselves.diff --git a/src/components/app/page-heading.test.ts b/src/components/app/page-heading.test.tsdeleted file mode 100644index 4318ae2d3d..0000000000--- a/src/components/app/page-heading.test.ts+++ /dev/null@@ -1,29 +0,0 @@-// @vitest-environment happy-dom-import { describe, expect, it } from "vitest";--import { botHtmlDocument } from "../../../shared/app-frame/document";-import { pageOpensWithHeading } from "./page-heading";--const opens = (html: string) => pageOpensWithHeading(botHtmlDocument({ messageId: "a1", rev: 0, html }).srcdoc);--describe("whether a page opens with a heading of its own", () => {- it("says yes when the first words are a heading, however deep it sits", () => {- expect(opens("<!DOCTYPE html><html><head><title>Sales</title><style>h1{margin:0}</style></head><body><h1>Weekly sales</h1><p>Numbers</p></body></html>")).toBe(true);- expect(opens("<main><header><h2>Weekly <em>sales</em></h2></header><p>Numbers</p></main>")).toBe(true);- expect(opens("<div role=\"heading\" aria-level=\"1\">Weekly sales</div>")).toBe(true);- });-- it("says no when something else comes first", () => {- expect(opens("<div class=\"tiles\"><div>0.1.161</div></div><h1>Weekly sales</h1>")).toBe(false);- expect(opens("<p>Numbers</p>")).toBe(false);- });-- it("looks past what a page does not show", () => {- expect(opens("<script>var title = 'x';</script><template>Draft</template><p hidden>Old</p><h1>Weekly sales</h1>")).toBe(true);- });-- it("says no for a page a script draws", () => {- expect(opens("<div id=\"root\"></div><script>document.getElementById('root').textContent = 'Weekly sales';</script>")).toBe(false);- expect(pageOpensWithHeading(botHtmlDocument({ messageId: "a1", rev: 0, format: "jsx", title: "Sales", html: "export default () => <h1>Weekly sales</h1>;" }).srcdoc)).toBe(false);- });-});diff --git a/src/components/app/page-heading.ts b/src/components/app/page-heading.tsdeleted file mode 100644index a6741e99f2..0000000000--- a/src/components/app/page-heading.ts+++ /dev/null@@ -1,20 +0,0 @@-const UNSEEN = new Set(["SCRIPT", "STYLE", "TEMPLATE", "NOSCRIPT", "TITLE"]);--function firstText(node: Node): Text | null {- for (const child of Array.from(node.childNodes)) {- if (child.nodeType === 3) {- if (child.textContent?.trim()) return child as Text;- } else if (child.nodeType === 1 && !UNSEEN.has((child as Element).tagName) && !(child as Element).hasAttribute("hidden")) {- const found = firstText(child);- if (found) return found;- }- }- return null;-}--/** Whether the first words of a page's markup are a heading of its own. A page that draws itself with a script has none. */-export function pageOpensWithHeading(srcdoc: string): boolean {- if (typeof DOMParser === "undefined") return false;- const body = new DOMParser().parseFromString(srcdoc, "text/html").body;- return Boolean(body && firstText(body)?.parentElement?.closest("h1, h2, h3, [role=heading]"));-}