Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
feat(pages): cite text selected inside a bot's page
AdityaUmalea56d4bc5a421
diff --git a/shared/app-frame/helper.test.ts b/shared/app-frame/helper.test.tsindex 462554621c..5e961c7da0 100644--- a/shared/app-frame/helper.test.ts+++ b/shared/app-frame/helper.test.ts@@ -5,7 +5,7 @@ import { ROOM_VIEW_ONLY, type AppDocument } from "../app.ts";import { createAppBridge, type AppBridge } from "./bridge.ts";import { BOT_HTML_CSP, BOT_HTML_NETWORK } from "./csp.ts";import { ROOM_CAN } from "./document.ts";-import { APP_HELPER_SOURCE, APP_ROOM_HELPER_SOURCE } from "./helper.ts";+import { APP_HELPER_SOURCE, APP_ROOM_HELPER_SOURCE, APP_SELECTION_METHOD } from "./helper.ts";const DOC: AppDocument = {v: 1, messageId: "m1", rev: 0, srcdoc: "", csp: BOT_HTML_CSP,@@ -42,6 +42,7 @@ function boot(engaged = true, options: { scene?: Scene; start?: number; loaded?:const parent = {postMessage(data: unknown) {const copy = structuredClone(data);+ if ((copy as { method?: string }).method === APP_SELECTION_METHOD) seen.selections.push((copy as { params: unknown }).params);task(() => bridge.handleMessage({ source: frame, data: copy }));},};@@ -82,7 +83,7 @@ function boot(engaged = true, options: { scene?: Scene; start?: number; loaded?:});(document as unknown as { elementsFromPoint(): Element[] }).elementsFromPoint = () => [...under, document.body, root];}- const seen = { messages: [] as string[], links: [] as string[], contexts: [] as unknown[], heights: [] as number[] };+ const seen = { messages: [] as string[], links: [] as string[], contexts: [] as unknown[], heights: [] as number[], selections: [] as unknown[] };bridge = createAppBridge({doc: room ? { ...DOC, can: { ...ROOM_CAN }, room: true } : DOC,hostContext: { theme: "dark", styles: { variables: { "--color-text-primary": "#fafafa", "not-a-variable": "x" } } },@@ -209,6 +210,41 @@ describe("the bot-page helper", () => {});});+describe("the text the person selects in a bot page", () => {+ const selectText = (page: ReturnType<typeof boot>, text: string) => {+ const document = page.root.ownerDocument;+ const paragraph = document.createElement("p");+ paragraph.textContent = text;+ document.body.appendChild(paragraph);+ document.getSelection()!.selectAllChildren(paragraph);+ document.dispatchEvent(new document.defaultView!.Event("selectionchange"));+ };++ it("is reported once it settles, and reported gone once, so the host can offer to cite it", async () => {+ const page = boot();+ await expect.poll(() => page.bridge.initialized).toBe(true);+ selectText(page, "Total: 42");+ await expect.poll(() => page.seen.selections.length).toBe(1);+ expect(page.seen.selections[0]).toMatchObject({ text: "Total: 42", left: expect.any(Number), bottom: expect.any(Number) });+ const document = page.root.ownerDocument;+ document.getSelection()!.removeAllRanges();+ document.dispatchEvent(new document.defaultView!.Event("selectionchange"));+ await expect.poll(() => page.seen.selections.length).toBe(2);+ expect(page.seen.selections[1]).toEqual({ text: "" });+ document.dispatchEvent(new document.defaultView!.Event("selectionchange"));+ await new Promise((resolve) => setTimeout(resolve, 150));+ expect(page.seen.selections).toHaveLength(2);+ });++ it("is never reported from a room's page", async () => {+ const page = boot(true, { room: true });+ await expect.poll(() => page.bridge.initialized).toBe(true);+ selectText(page, "Total: 42");+ await new Promise((resolve) => setTimeout(resolve, 150));+ expect(page.seen.selections).toEqual([]);+ });+});+describe("the height a bot page reports", () => {const flow = (height: number) => () => height;diff --git a/shared/app-frame/helper.ts b/shared/app-frame/helper.tsindex 89cbf98ec4..e23dec16cb 100644--- a/shared/app-frame/helper.ts+++ b/shared/app-frame/helper.ts@@ -9,6 +9,9 @@// room: boolean, // shown in a room: send and setContext resolve and do nothing// }//+// 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.+//// 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// races the SDK's answer.@@ -25,6 +28,11 @@ export const APP_THEME_STYLE = ["--font-mono:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}",].join("");+/** The page's text selection, read by the desktop host beside the bridge: { text, left, bottom }, or { text: "" } once gone. */+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;+/** Plain ES2017 with no imports: it runs as written in every browser engine the apps ship in. */const helperSource = (room: boolean) => `(function () {"use strict";@@ -148,6 +156,30 @@ const helperSource = (room: boolean) => `(function () {window.addEventListener("load", report);report();};+ // 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;+ var shown = false;+ var timer = null;+ var report = function () {+ timer = null;+ var selection = document.getSelection();+ var text = selection && selection.rangeCount && !selection.isCollapsed ? String(selection) : "";+ if (!text.trim()) {+ if (shown) notify("${APP_SELECTION_METHOD}", { text: "" });+ shown = false;+ return;+ }+ var range = selection.getRangeAt(selection.rangeCount - 1);+ var rects = range.getClientRects();+ var end = rects.length ? rects[rects.length - 1] : range.getBoundingClientRect();+ shown = true;+ notify("${APP_SELECTION_METHOD}", { text: text.slice(0, ${APP_SELECTION_CHARS}), left: end.left, bottom: end.bottom });+ };+ document.addEventListener("selectionchange", function () {+ if (timer === null) timer = setTimeout(report, 100);+ });+ };var ready = request("ui/initialize", {appInfo: { name: "mausbot-page", version: "1.0.0" },appCapabilities: {},@@ -156,6 +188,7 @@ const helperSource = (room: boolean) => `(function () {apply(result && result.hostContext);notify("ui/notifications/initialized");watchSize();+ watchSelection();});var checked = function (result) {if (result && result.isError) throw new Error("The host could not do that.");diff --git a/src/components/CitationUI.tsx b/src/components/CitationUI.tsxindex d4da5ce368..5acace151d 100644--- a/src/components/CitationUI.tsx+++ b/src/components/CitationUI.tsx@@ -5,8 +5,10 @@ import {CITATION_MAX_COMMENT_LENGTH,CITATION_MAX_QUOTE_LENGTH,citationAttachment,+ createCitationTextSelector,withCitationComment,type CitationAttachment,+ type CitationSource,} from "@/lib/citations";import { captureCitationSelection, citationShortcutHint, citationTabShortcut, isCitationShortcut } from "@/lib/citations-dom";import { isMacPlatform } from "@/lib/keyboard-shortcuts";@@ -194,31 +196,78 @@ export function CitationSelectionToolbar({}}/>;}- const tooLong = captured.citation.quote.length > CITATION_MAX_QUOTE_LENGTH;- const shortcut = citationShortcutHint(isMac);+ return <CiteButton+ buttonRef={buttonRef}+ point={captured.point}+ tooLong={captured.citation.quote.length > CITATION_MAX_QUOTE_LENGTH}+ shortcut={{ hint: citationShortcutHint(isMac), keys: isMac ? "Meta+L" : "Control+L" }}+ onCite={() => setEditing(true)}+ onDismiss={() => setCaptured(null)}+ />;+}++function CiteButton({ buttonRef, point, tooLong, shortcut, onCite, onDismiss }: {+ buttonRef: RefObject<HTMLButtonElement | null>;+ point: Point;+ tooLong: boolean;+ shortcut?: { hint: string; keys: string };+ onCite: () => void;+ onDismiss: () => void;+}) {+ const hint = !tooLong && shortcut;return createPortal(<buttonref={buttonRef}type="button"disabled={tooLong}aria-label={t(tooLong ? "chat.citation.tooLongLabel" : "chat.citation.citeLabel")}- aria-keyshortcuts={tooLong ? undefined : isMac ? "Meta+L" : "Control+L"}- title={tooLong ? undefined : `${t("chat.citation.citeLabel")} (${shortcut})`}+ aria-keyshortcuts={hint ? hint.keys : undefined}+ title={tooLong ? undefined : hint ? `${t("chat.citation.citeLabel")} (${hint.hint})` : t("chat.citation.citeLabel")}onPointerDown={(event) => event.preventDefault()}- onClick={() => setEditing(true)}+ onClick={onCite}onKeyDown={(event) => {- if (event.key === "Escape") { event.preventDefault(); setCaptured(null); }+ if (event.key === "Escape") { event.preventDefault(); onDismiss(); }}}className="fixed z-50 flex items-center gap-1.5 rounded-full border border-hairline/50 bg-panel px-3 py-1.5 text-[12px] font-medium text-ink shadow-lg disabled:text-danger"- style={captured.point}+ style={point}><Quote size={13} aria-hidden="true" /> {t(tooLong ? "chat.citation.shorten" : "chat.citation.cite")}- {!tooLong && <kbd aria-hidden="true" className="font-sans text-[11px] font-normal text-ink-secondary">{shortcut}</kbd>}+ {hint && <kbd aria-hidden="true" className="font-sans text-[11px] font-normal text-ink-secondary">{hint.hint}</kbd>}</button>,document.body,);}+/** Cite for text the person selected inside a page in chat. The page reports the selection, so its keys stay+ * the page's own: no shortcut here. Once the card is open it stays, as chat's does, whatever the page selects. */+export function PageCitationButton({ selection, source, onAdd, onDismiss }: {+ selection: { text: string; point: Point } | null;+ source: Omit<CitationSource, "start" | "end" | "prefix" | "suffix">;+ onAdd: (citation: CitationAttachment) => void;+ onDismiss: () => void;+}) {+ const buttonRef = useRef<HTMLButtonElement>(null);+ const [editing, setEditing] = useState<{ citation: CitationAttachment; point: Point } | null>(null);+ const point = editing ? null : selection?.point;+ useLayoutEffect(() => {+ if (!point) return;+ const update = () => { if (buttonRef.current) place(buttonRef.current, point); };+ update();+ window.addEventListener("resize", update);+ return () => window.removeEventListener("resize", update);+ }, [point]);+ if (editing) {+ const done = () => { setEditing(null); onDismiss(); focusComposer(); };+ return <CitationEditor citation={editing.citation} point={editing.point} onCancel={done} onSave={(saved) => { onAdd(saved); done(); }} />;+ }+ if (!selection) return null;+ const cite = () => {+ const selector = createCitationTextSelector(selection.text, 0, selection.text.length);+ if (selector) setEditing({ citation: citationAttachment(source, selector), point: selection.point });+ };+ return <CiteButton buttonRef={buttonRef} point={selection.point} tooLong={selection.text.length > CITATION_MAX_QUOTE_LENGTH} onCite={cite} onDismiss={onDismiss} />;+}+export function CitationBadge({citation,onChange,diff --git a/src/components/app/AppFrame.tsx b/src/components/app/AppFrame.tsxindex ee214a4d73..4d125a1761 100644--- a/src/components/app/AppFrame.tsx+++ b/src/components/app/AppFrame.tsx@@ -4,7 +4,7 @@ import { useStore } from "@/state/store";import type { AppBlockedReason, AppDocument } from "../../../shared/app";import { RPC_HOST_REFUSED, type JsonRpcError } from "../../../shared/app-frame/bridge";import { callAppRpc, newAppSendId, postAppContext, sendAppMessage } from "./app-api";-import { mountAppFrame } from "./app-frame-host";+import { mountAppFrame, type AppSelection } from "./app-frame-host";import { appHostContext, appMaxHeight, appThemeContext } from "./app-host-context";export interface AppFrameHandle {@@ -33,6 +33,8 @@ export interface AppFrameProps {fill?: boolean;/** The tallest the frame grows to its content, under the window's own limit. */maxHeight?: number;+ /** Text the person selected in the page, in window coordinates, or null once it is gone. */+ onSelection?(selection: AppSelection | null): void;}const refusal = (message: string): JsonRpcError => ({ code: RPC_HOST_REFUSED, message });@@ -60,6 +62,7 @@ export function AppFrame(props: AppFrameProps) {hostVersion: appVersion(),...(import.meta.env?.DEV ? { log: (params: unknown) => console.info("[app]", params) } : {}),...(fill ? { fill: true } : {}),+ onSelection: (selection) => latest.current.onSelection?.(selection),adapter: {async callRpc(method, params) {const outcome = await callAppRpc({ botId, threadId, messageId, method, params });@@ -109,6 +112,7 @@ export function AppFrame(props: AppFrameProps) {window.removeEventListener("resize", later);if (timer !== undefined) clearTimeout(timer);if (latest.current.handle.current) latest.current.handle.current = null;+ latest.current.onSelection?.(null);// The row is going: the frame waits out the View's teardown somewhere hidden.host.retire();};diff --git a/src/components/app/AppMessage.tsx b/src/components/app/AppMessage.tsxindex 6c096b5b1b..270b4a32a5 100644--- a/src/components/app/AppMessage.tsx+++ b/src/components/app/AppMessage.tsx@@ -9,6 +9,10 @@ import { AppDocumentError, fetchAppDocument, type AppFetchFailure } from "./app-import { APP_POOL_LIMITS, useAppPoolSlot, type AppPool } from "./app-pool";import { AppDone, AppHeader, AppInfo, AppOpenButton, AppPlaceholder, AppStrip, APP_SURFACE } from "./AppChrome";import { AppFrame, type AppFrameHandle, type AppFrameProblem } from "./AppFrame";+import type { AppSelection } from "./app-frame-host";+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 { PAGE_HEIGHT, PAGE_PREVIEW_HEIGHT, PageFullScreen, PageNotes, PagePaneContext, PageToolbar, usePagePin, usePagePoint, usePageSave, usePageShare, usePageVersion } from "./PageTools";@@ -78,7 +82,7 @@ function AppRow({ botId, botName, threadId, message, payload, pool, room }: {pool?: AppPool;room?: boolean;}) {- const { dispatch } = useStore();+ const { dispatch, state: store } = useStore();const uid = useId();const page = payload.source === "html";const version = usePageVersion(payload);@@ -93,6 +97,10 @@ function AppRow({ botId, botName, threadId, message, payload, pool, room }: {const [loaded, setLoaded] = useState<Loaded | null>(null);const [fetching, setFetching] = useState(false);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 yourAccess = store?.bots?.find((candidate) => candidate.id === botId)?.yourAccess;+ const canWrite = useCanWriteIn(threadId, yourAccess) !== false;const frame = useRef<AppFrameHandle | null>(null);const wide = useRef<AppFrameHandle | null>(null);const [fullScreen, setFullScreen] = useState(false);@@ -238,6 +246,7 @@ function AppRow({ botId, botName, threadId, message, payload, pool, room }: {onProblem={setProblem}onTeardownRequested={onTeardownRequested}{...(page ? { maxHeight: PAGE_HEIGHT.cap } : {})}+ {...(!room ? { onSelection: setSelection } : {})}/>) : (<AppPlaceholder height={boxHeight} loading={slot.live} open={slot.live ? undefined : reloadNow} />@@ -286,8 +295,17 @@ function AppRow({ botId, botName, threadId, message, payload, pool, room }: {{payload.done && <AppDone done={payload.done} bordered={bordered} />}{strip && <AppStrip text={strip.text} action={strip.action} bordered={bordered} />}</div>+ {!room && canWrite && (+ <PageCitationButton+ selection={selection && { text: selection.text, point: { left: selection.left, top: selection.bottom + 8 } }}+ source={{ ownerType: "bot", ownerId: botId, threadId, messageId: message.id }}+ onAdd={(citation) => appendDraftAttachments(`bot:${botId}:${threadId}`, [citation])}+ onDismiss={() => setSelection(null)}+ />+ )}{page && fullScreen && current && (- <PageFullScreen {...tools} title={payload.title} doc={current} botId={botId} threadId={threadId} handle={wide} close={() => setFullScreen(false)} pane={pane} />+ <PageFullScreen {...tools} title={payload.title} doc={current} botId={botId} threadId={threadId} handle={wide} close={() => setFullScreen(false)} pane={pane}+ {...(!room ? { onSelection: setSelection } : {})} />)}</div>);diff --git a/src/components/app/PageTools.tsx b/src/components/app/PageTools.tsxindex 1c997edc8a..38ffcea744 100644--- a/src/components/app/PageTools.tsx+++ b/src/components/app/PageTools.tsx@@ -18,6 +18,7 @@ import type { PublishedPageCard } from "../../../shared/published-page";import { canonicalDownloadFilename } from "../AttachmentPreview";import { appDownloadPath, publishAppPage, unpublishPage } from "./app-api";import { AppFrame, type AppFrameHandle } from "./AppFrame";+import type { AppSelection } from "./app-frame-host";import { ASK_CHIP, ASK_CHIP_IDLE, ASK_CHIP_PICKED, ASK_PRIMARY_BUTTON } from "../AskCard";/** A page starts at this height in the chat and grows to its content up to the cap, then scrolls inside. */@@ -330,6 +331,8 @@ export function PageFullScreen(props: PageToolsProps & {close(): void;/** Open in this pane, leaving the message box usable, rather than over the whole window. */pane?: HTMLElement | null;+ /** Text the person selected in the page, to cite it: never in a room. */+ onSelection?(selection: AppSelection | null): void;}) {const { point, close, pane } = props;const closer = useRef<HTMLDivElement | null>(null);@@ -358,7 +361,8 @@ export function PageFullScreen(props: PageToolsProps & {</div><div className={cn("relative min-h-0 flex-1 bg-app", point.pointing && "ring-2 ring-inset ring-accent/60")}><AppFrame doc={props.doc} botId={props.botId} threadId={props.threadId} title={props.title} height={600} handle={props.handle}- onHeight={() => {}} onProblem={() => {}} onTeardownRequested={close} fill />+ onHeight={() => {}} onProblem={() => {}} onTeardownRequested={close} fill+ {...(props.onSelection ? { onSelection: props.onSelection } : {})} /></div></div>,pane ?? document.body,diff --git a/src/components/app/app-frame-host.test.ts b/src/components/app/app-frame-host.test.tsindex f5f5d3e014..9300e16696 100644--- a/src/components/app/app-frame-host.test.ts+++ b/src/components/app/app-frame-host.test.ts@@ -4,6 +4,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { APP_SAMPLES } from "../../../shared/app-samples";import { botHtmlDocument } from "../../../shared/app-frame/document";+import { APP_SELECTION_CHARS } from "../../../shared/app-frame/helper";import { APP_FRAME_SANDBOX, createAppIframe, mountAppFrame, trackAppEngagement, type AppFrameAdapter } from "./app-frame-host";const doc = botHtmlDocument({ messageId: "m1", rev: 0, html: APP_SAMPLES.counter!.html });@@ -115,6 +116,66 @@ describe("the bridge on the desktop", () => {});});+describe("text the person selects in a page", () => {+ const SELECTION = "mausbot/notifications/selection";++ function page(over: { doc?: typeof doc } = {}) {+ const onSelection = vi.fn();+ const host = mountAppFrame({ container, doc: over.doc ?? doc, title: "Coffee counter", height: 200, hostContext: {}, hostVersion: "1", adapter: adapter(), onSelection });+ const view = host.iframe.contentWindow!;+ const send = (data: unknown, source: unknown = view) => window.dispatchEvent(new MessageEvent("message", { data, source: source as MessageEventSource }));+ const select = (params: Record<string, unknown>, source?: unknown) => send({ jsonrpc: "2.0", method: SELECTION, params }, source);+ const initialize = () => {+ send({ jsonrpc: "2.0", id: 1, method: "ui/initialize", params: {} });+ send({ jsonrpc: "2.0", method: "ui/notifications/initialized", params: {} });+ };+ const engage = async () => {+ document.dispatchEvent(new KeyboardEvent("keydown", { key: "Tab" }));+ host.iframe.focus();+ host.iframe.dispatchEvent(new Event("focus"));+ await tick();+ };+ vi.spyOn(host.iframe, "getBoundingClientRect").mockReturnValue({ left: 100, top: 50, right: 700, bottom: 250, width: 600, height: 200, x: 100, y: 50, toJSON() {} } as DOMRect);+ return { host, onSelection, select, initialize, engage };+ }++ it("is passed on in the window's coordinates, and as null once it is gone", async () => {+ const { host, onSelection, select, initialize, engage } = page();+ select({ text: "before it started", left: 1, bottom: 2 });+ initialize();+ await engage();+ select({ text: "Total: 42", left: 12, bottom: 30 });+ select({ text: "" });+ expect(onSelection.mock.calls).toEqual([[{ text: "Total: 42", left: 112, bottom: 80 }], [null]]);+ host.destroy();+ });++ it("is dropped when the person did not make it, it is malformed or too long, or it comes from another window", async () => {+ const { host, onSelection, select, initialize, engage } = page();+ initialize();+ select({ text: "unprompted", left: 0, bottom: 0 });+ await engage();+ select({ text: "x".repeat(APP_SELECTION_CHARS + 1), left: 0, bottom: 0 });+ select({ text: 42, left: 0, bottom: 0 });+ select({ text: "ok", left: Number.NaN, bottom: 0 });+ select({ text: "ok", left: 0 });+ select({ text: "ok", left: 0, bottom: 0 }, window);+ expect(onSelection).not.toHaveBeenCalled();+ host.destroy();+ });++ it("is never offered in a room, where a page may not message", async () => {+ const roomDoc = botHtmlDocument({ messageId: "m1", rev: 0, html: APP_SAMPLES.counter!.html, room: true });+ const { host, onSelection, select, initialize, engage } = page({ doc: roomDoc });+ initialize();+ await engage();+ select({ text: "Total: 42", left: 0, bottom: 0 });+ select({ text: "" });+ expect(onSelection).not.toHaveBeenCalled();+ 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 49982a1de8..ee2f1c3cfe 100644--- a/src/components/app/app-frame-host.ts+++ b/src/components/app/app-frame-host.ts@@ -1,5 +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";/** Exactly these two tokens: never allow-same-origin, allow-popups or allow-top-navigation, and no `allow`* attribute. */@@ -89,6 +90,26 @@ export function trackAppEngagement(iframe: HTMLIFrameElement): AppEngagement {export type AppFrameAdapter = Omit<AppBridgeAdapter, "post" | "engaged" | "now">;+/** Text the person selected in a bot's page, and where its last line ends in the host window. */+export interface AppSelection {+ text: string;+ left: number;+ bottom: number;+}++const finite = (value: unknown): value is number => typeof value === "number" && Number.isFinite(value);++/** The page helper's selection report: undefined for any other message or a malformed one, null once it is gone. */+export function readPageSelection(data: unknown): AppSelection | null | undefined {+ if (!data || typeof data !== "object") return undefined;+ const message = data as { jsonrpc?: unknown; method?: unknown; id?: unknown; params?: { text?: unknown; left?: unknown; bottom?: unknown } };+ if (message.jsonrpc !== "2.0" || message.method !== APP_SELECTION_METHOD || message.id !== undefined) return undefined;+ const { text, left, bottom } = message.params ?? {};+ if (typeof text !== "string" || text.length > APP_SELECTION_CHARS) return undefined;+ if (!text.trim()) return null;+ return finite(left) && finite(bottom) ? { text, left, bottom } : undefined;+}+export interface AppFrameHostOptions {container: HTMLElement;doc: AppDocument;@@ -100,6 +121,8 @@ export interface AppFrameHostOptions {log?(params: unknown): void;/** The frame fills its container and the page scrolls inside it: the size the View reports is ignored. */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;}export interface AppFrameHost {@@ -178,7 +201,16 @@ export function mountAppFrame(options: AppFrameHostOptions): AppFrameHost {now: () => Date.now(),},});- const onMessage = (event: MessageEvent) => bridge.handleMessage({ source: event.source, data: event.data });+ const onMessage = (event: MessageEvent) => {+ 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.+ if (!options.onSelection || !doc.can.message || doc.room || !bridge.initialized || leaving) return;+ if (!selection) return options.onSelection(null);+ if (!engagement.engaged()) return;+ const box = iframe.getBoundingClientRect();+ options.onSelection({ text: selection.text, left: box.left + selection.left, bottom: box.top + selection.bottom });+ };win?.addEventListener("message", onMessage);// The router listens before the frame can speak: it loads on insertion.iframe.srcdoc = doc.srcdoc;