Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

0.9.0 G3: Point at it (frontend) (#487)

Oleksandr Ivanchenkof2280485d795
diff --git a/frontend/src/attachments.ts b/frontend/src/attachments.ts
index f1b652ef..9baf7f6a 100644
--- a/frontend/src/attachments.ts
+++ b/frontend/src/attachments.ts
@@ -1,5 +1,6 @@
// File attachments in chats: uploads from the composer and files agents share (batch 2 / D).
import { parseMetaObject } from './questions';
+import { PointMeta, PointPick, parsePointMeta, pointMetaOf } from './point';
export const MAX_ATTACHMENT_BYTES = 20 * 1024 * 1024;
/** Videos (mp4, mov, webm) may be bigger; the server enforces the same caps by the file's bytes. */
@@ -18,6 +19,8 @@ export interface AttachmentRef {
name: string;
mime: string;
size: number;
+ /** G3: a part of the page the person pointed at (the crop and where it came from). */
+ point?: PointMeta;
}
export interface Attachment extends AttachmentRef {
@@ -72,7 +75,9 @@ export function parseAttachments(meta: unknown): AttachmentRef[] {
return m.attachments.flatMap((a: unknown) => {
const x = a as Partial<AttachmentRef> | null;
if (!x || typeof x.id !== 'string' || !UUID_RE.test(x.id) || typeof x.name !== 'string') return [];
- return [{ id: x.id, name: x.name, mime: typeof x.mime === 'string' ? x.mime : 'application/octet-stream', size: typeof x.size === 'number' ? x.size : 0 }];
+ const ref: AttachmentRef = { id: x.id, name: x.name, mime: typeof x.mime === 'string' ? x.mime : 'application/octet-stream', size: typeof x.size === 'number' ? x.size : 0 };
+ const point = 'point' in x ? parsePointMeta((x as { point?: unknown }).point) : null;
+ return [point ? { ...ref, point } : ref];
});
}
@@ -261,8 +266,13 @@ export interface PendingUpload {
/** False when Retry can't help, e.g. an unsupported file type. */
retryable?: boolean;
attachment?: Attachment;
+ /** G3: a part of the page picked with Point; `pick` arrives when the capture is done. */
+ point?: { label: string; pick?: PointPick };
}
+/** Picks in the composer, capturing ones included (at most 5 per message). */
+export const pointPicks = (items: PendingUpload[]) => items.filter((i) => i.point).length;
+
/** Room for more files: at most 10 per message. */
export const uploadSlotsLeft = (items: PendingUpload[]) => Math.max(0, MAX_ATTACHMENTS - items.length);
@@ -272,8 +282,17 @@ export function composerReady(text: string, items: PendingUpload[]): boolean {
return text.trim().length > 0 || items.length > 0;
}
-export const readyAttachments = (items: PendingUpload[]): AttachmentRef[] =>
- items.flatMap((i) => (i.state === 'done' && i.attachment ? [{ id: i.attachment.id, name: i.attachment.name, mime: i.attachment.mime, size: i.attachment.size }] : []));
+/** What goes in `attachment_ids` (and the sent bubble), in order. Picks get `n of N` by their order, as the server counts them. */
+export function readyAttachments(items: PendingUpload[]): AttachmentRef[] {
+ const ready = items.filter((i) => i.state === 'done' && i.attachment);
+ const of = ready.filter((i) => i.point?.pick).length;
+ let n = 0;
+ return ready.map((i) => {
+ const a = i.attachment!;
+ const ref: AttachmentRef = { id: a.id, name: a.name, mime: a.mime, size: a.size };
+ return i.point?.pick ? { ...ref, point: pointMetaOf(i.point.pick, ++n, of) } : ref;
+ });
+}
/**
* Uploads one file as the raw request body (`?name=`), reporting progress. XHR because fetch has
diff --git a/frontend/src/components/Attachments.tsx b/frontend/src/components/Attachments.tsx
index 24f90e04..84f9a00d 100644
--- a/frontend/src/components/Attachments.tsx
+++ b/frontend/src/components/Attachments.tsx
@@ -1,6 +1,7 @@
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
-import { AlertCircle, Download, ExternalLink, FileText, Film, Loader2, RotateCw, X } from 'lucide-react';
+import { AlertCircle, Download, ExternalLink, FileText, Film, Image as ImageIcon, Loader2, RotateCw, X } from 'lucide-react';
+import { POINT_COPY, chipLine, pickName, pickTitle, removeText, rowLine } from '../point';
import { AttachmentRef, PendingUpload, attachKind, attachmentUrl, fileKind, formatBytes, isInlineImage, isVideo, uploadProgressText } from '../attachments';
/**
@@ -301,12 +302,24 @@ export const FileTiles: React.FC<{ files: AttachmentRef[]; align?: 'start' | 'en
sharedBy,
at = null,
}) => (
- <ul className={`mt-2 flex flex-wrap gap-2 w-full ${align === 'end' ? 'justify-end' : ''}`} aria-label={files.length === 1 ? 'Attached file' : `${files.length} attached files`}>
- {files.map((f) => (
- <li key={f.id} className={`max-w-full${sharedBy ? ' w-full sm:w-auto' : ''}`}>
- <FileTile file={f} sharedBy={sharedBy} at={at} />
- </li>
- ))}
+ // S5: picks stack one row each (flex-col), other attachments keep wrapping as before.
+ <ul
+ className={`mt-2 flex gap-2 w-full ${
+ files.some((f) => f.point) ? `flex-col ${align === 'end' ? 'items-end' : 'items-start'} gap-1.5` : `flex-wrap ${align === 'end' ? 'justify-end' : ''}`
+ }`}
+ aria-label={files.length === 1 ? 'Attached file' : `${files.length} attached files`}
+ >
+ {files.map((f) =>
+ f.point ? (
+ <li key={f.id} className="w-full sm:w-auto max-w-full sm:max-w-[420px]">
+ <PointRow file={f} sharedBy={sharedBy} at={at} />
+ </li>
+ ) : (
+ <li key={f.id} className={`max-w-full${sharedBy ? ' w-full sm:w-auto' : ''}`}>
+ <FileTile file={f} sharedBy={sharedBy} at={at} />
+ </li>
+ ),
+ )}
</ul>
);
@@ -377,3 +390,87 @@ export const UploadChip: React.FC<{ item: PendingUpload; onRemove: () => void; o
</li>
);
};
+
+/**
+ * G3: a part of the page in a sent message. The crop (64 × 42) opens the image viewer; the selector
+ * and where it came from sit beside it. No picture (or an embedded page): an image icon instead.
+ */
+export const PointRow: React.FC<{ file: AttachmentRef; sharedBy?: string; at?: string | null }> = ({ file, sharedBy, at = null }) => {
+ const [open, setOpen] = useState(false);
+ const [broken, setBroken] = useState(false);
+ const p = file.point!;
+ const name = pickName(p);
+ const fullName = pickTitle(p);
+ const picture = p.picture && isInlineImage(file.mime) && !broken;
+ return (
+ <div data-point-row="" className="flex items-center gap-2.5 max-w-full sm:max-w-[420px] p-1.5 pr-3 rounded-[10px] border border-violet-400/30 bg-violet-500/[0.08]">
+ {picture ? (
+ <button
+ type="button"
+ onClick={() => setOpen(true)}
+ aria-label={`Open the picture of ${name}`}
+ className="shrink-0 w-16 h-[42px] rounded-md overflow-hidden border border-white/10 bg-[#0a0719] focus:outline-none focus-visible:ring-2 focus-visible:ring-violet-300"
+ >
+ <img src={attachmentUrl(file.id)} alt="" loading="lazy" onError={() => setBroken(true)} className="w-full h-full object-contain" />
+ </button>
+ ) : (
+ <span className="shrink-0 w-16 h-[42px] rounded-md border border-white/10 bg-[#0a0719] inline-flex items-center justify-center text-zinc-500" aria-hidden="true">
+ <ImageIcon size={16} />
+ </span>
+ )}
+ <span className="min-w-0 flex-1">
+ <span className="block truncate font-mono text-[12px] text-zinc-100" title={fullName}>
+ {name}
+ </span>
+ <span className="block truncate text-[11px] text-zinc-400" title={p.url || undefined}>
+ {rowLine(p)}
+ </span>
+ </span>
+ {open && <ImageViewer file={file} sharedBy={sharedBy} at={at} onClose={() => setOpen(false)} />}
+ </div>
+ );
+};
+
+/** G3: a pick in the composer: capturing, done (crop, selector, host and path), no picture, or an embedded page. */
+export const PointChip: React.FC<{ item: PendingUpload; onRemove: () => void }> = ({ item, onRemove }) => {
+ const pick = item.point?.pick;
+ const capturing = item.state === 'uploading' || !pick;
+ const name = pick ? pickName(pick) : item.point?.label || item.name;
+ const fullName = pick ? pickTitle(pick) : name;
+ const thumb = pick?.picture && pick.thumb_url && !pick.frame?.cross_site ? pick.thumb_url : null;
+ const warn = !!pick && !pick.picture && !pick.frame?.cross_site;
+ return (
+ <li
+ data-point-chip={capturing ? 'capturing' : warn ? 'no-picture' : pick?.frame?.cross_site ? 'frame' : 'ready'}
+ className={`relative inline-flex items-center h-10 gap-2 w-full sm:w-auto sm:max-w-[320px] rounded-[10px] border pl-1 pr-1.5 ${
+ warn ? 'border-amber-400/45 bg-amber-500/10' : 'border-violet-400/35 bg-violet-500/10'
+ }`}
+ >
+ {capturing ? (
+ <span className="shrink-0 w-11 h-[30px] rounded-md bg-violet-400/20 motion-safe:animate-pulse" aria-hidden="true" />
+ ) : thumb ? (
+ <img src={thumb} alt="" className="shrink-0 w-11 h-[30px] rounded-md object-contain bg-[#0a0719] border border-white/10" />
+ ) : (
+ <span className={`shrink-0 w-11 h-[30px] rounded-md border inline-flex items-center justify-center ${warn ? 'border-amber-400/40 text-amber-300' : 'border-white/10 text-zinc-400'}`} aria-hidden="true">
+ <ImageIcon size={14} />
+ </span>
+ )}
+ <span className="min-w-0 flex-1">
+ <span className="block truncate font-mono text-[11.5px] leading-4 text-zinc-100" title={fullName}>
+ {name}
+ </span>
+ <span className={`block truncate text-[11px] leading-4 ${warn ? 'text-amber-200' : 'text-zinc-400'}`} role={capturing ? 'status' : undefined}>
+ {capturing ? POINT_COPY.capturing : chipLine(pick!)}
+ </span>
+ </span>
+ <button
+ type="button"
+ onClick={onRemove}
+ aria-label={removeText(name)}
+ className="relative shrink-0 w-6 h-6 inline-flex items-center justify-center rounded text-zinc-400 hover:text-white hover:bg-white/10 focus:outline-none focus-visible:ring-2 focus-visible:ring-violet-300 before:absolute before:-inset-[10px] before:content-['']"
+ >
+ <X size={12} aria-hidden="true" />
+ </button>
+ </li>
+ );
+};
diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsx
index 4eaf09e3..cb92af30 100644
--- a/frontend/src/components/ChatView.tsx
+++ b/frontend/src/components/ChatView.tsx
@@ -52,11 +52,14 @@ import {
uploadWithRetry,
uploadRetryable,
uploadSlotsLeft,
+ pointPicks,
ATTACH_TITLE,
} from '../attachments';
+import type { Attachment } from '../attachments';
+import type { PointSink } from './PointLayer';
import { DropRecipient, FOLDER_NOTE, dragHasFiles, dropAnnouncement, dropCard, leaveMs, modalOpen, previewDrag, splitDrop, windowDragWatch } from '../dragPreview';
import { DropBot, DropLayer, DropPhase } from './DropLayer';
-import { EarlierCopies, FileTiles, UploadChip } from './Attachments';
+import { EarlierCopies, FileTiles, PointChip, UploadChip } from './Attachments';
import { arrangeSharedFiles, botDisplayName, botOf, shareInfo } from '../sharedFiles';
import { ranOnLabel } from '../engines';
import { replyTokens } from '../modelUsage';
@@ -985,6 +988,35 @@ export const ChatView: React.FC<ChatViewProps> = ({
setUploads((list) => list.filter((u) => u.key !== key));
};
+ // G3 Point at it: a pick from the browser pane is a composer upload with a `point`
+ const pointSink: PointSink = {
+ picks: pointPicks(uploads),
+ filesLeft: uploadSlotsLeft(uploads),
+ start: (label, n, { fromMouse }) => {
+ const key = `point-${Date.now()}-${Math.random().toString(36).slice(2)}`;
+ setUploads((list) => [...list, { key, name: `pointed-${n}.png`, size: 0, mime: 'image/png', progress: 0, state: 'uploading', point: { label } }]);
+ // A mouse pick hands over to the composer only when nothing was typed yet
+ if (fromMouse && !inputVal.trim()) textareaRef.current?.focus({ preventScroll: true });
+ return key;
+ },
+ done: (key, pick) =>
+ setUploads((list) =>
+ list.map((u) =>
+ u.key === key
+ ? {
+ ...u,
+ state: 'done',
+ progress: 1,
+ mime: pick.picture ? 'image/png' : 'text/plain',
+ point: { label: u.point?.label ?? pick.label, pick },
+ attachment: { id: pick.attachment_id, name: u.name, mime: pick.picture ? 'image/png' : 'text/plain', size: 0 } as Attachment,
+ }
+ : u,
+ ),
+ ),
+ fail: (key) => setUploads((list) => list.filter((u) => u.key !== key)),
+ };
+
const retryUpload = (key: string) => {
const f = uploadFiles.current.get(key)?.file;
if (!f) return;
@@ -1068,6 +1100,15 @@ export const ChatView: React.FC<ChatViewProps> = ({
};
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
+ // Backspace in an empty composer takes back the last part of the page that was picked
+ if (e.key === 'Backspace' && !inputVal && !e.repeat) {
+ const lastPick = [...uploads].reverse().find((u) => u.point);
+ if (lastPick) {
+ e.preventDefault();
+ removeUpload(lastPick.key);
+ return;
+ }
+ }
if (slashOpen && (e.key === 'Tab' || (e.key === 'Enter' && !e.shiftKey))) {
e.preventDefault();
completeIdea();
@@ -2245,9 +2286,13 @@ export const ChatView: React.FC<ChatViewProps> = ({
<div className="basis-full min-w-0 px-1 pt-0.5 space-y-1.5">
{uploads.length > 0 && (
<ul className="flex flex-wrap gap-1.5 min-w-0" aria-label="Files to send">
- {uploads.map((u) => (
- <UploadChip key={u.key} item={u} onRemove={() => removeUpload(u.key)} onRetry={() => retryUpload(u.key)} fresh={freshChips[u.key]} />
- ))}
+ {uploads.map((u) =>
+ u.point ? (
+ <PointChip key={u.key} item={u} onRemove={() => removeUpload(u.key)} />
+ ) : (
+ <UploadChip key={u.key} item={u} onRemove={() => removeUpload(u.key)} onRetry={() => retryUpload(u.key)} fresh={freshChips[u.key]} />
+ ),
+ )}
</ul>
)}
{uploadNote && (
@@ -2525,6 +2570,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
onStepDone={onVmStepDone}
solveRequest={vmSolveRequest}
showOnceBot={vmShowOnceBot}
+ point={pointSink}
/>
</div>
{layerPhase && (
diff --git a/frontend/src/components/PointLayer.tsx b/frontend/src/components/PointLayer.tsx
new file mode 100644
index 00000000..cdf5d6b9
--- /dev/null
+++ b/frontend/src/components/PointLayer.tsx
@@ -0,0 +1,472 @@
+// G3 (0.9.0) Point at it: the layer over the watch view while Point is on. Hover (or a tap on a
+// phone) outlines the element under the pointer, arrows walk the tree, a click / Enter / Add to
+// message picks it. A pick becomes an unsent upload in the composer (through `sink`).
+// Design: release-090/designs/g3-point.md. Wire: release-090/g3-contract.md rev 2.
+import React, { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
+import {
+ ARROW_DIRS,
+ FAIL_BAR_MS,
+ HOVER_THROTTLE_MS,
+ LIMIT_BAR_MS,
+ PICKED_FLASH_MS,
+ POINT_COPY,
+ PointEl,
+ PointError,
+ PointPick,
+ SELF_REFRESH_MS,
+ addedText, sheetLine,
+ containFit,
+ parsePointEl,
+ parsePointPick,
+ pickRefusal,
+ pickedCountText,
+ spokenText,
+ tagPlacement,
+ tagText,
+ toPage,
+ toView,
+} from '../point';
+
+/** Where picks go: the composer's upload list. */
+export interface PointSink {
+ /** Picks already in the composer (capturing ones included). */
+ picks: number;
+ /** Files the composer can still take (10 in all). */
+ filesLeft: number;
+ /** A capturing chip appears; returns its key. */
+ start(label: string, n: number, opts: { fromMouse: boolean }): string;
+ /** The capture finished: the chip becomes the pick. */
+ done(key: string, pick: PointPick): void;
+ /** The capture failed: the chip goes away. */
+ fail(key: string): void;
+}
+
+export interface PointLayerProps {
+ request: (payload: Record<string, unknown>) => Promise<Record<string, any>>;
+ /** The page's viewport in CSS px (the frame's width and height), or null before the first frame. */
+ page: { width: number; height: number } | null;
+ /** The newest frame's id: a new one re-reads the selected element (`dir:"self"`). */
+ frameId: number | null;
+ pageUrl?: string;
+ phone: boolean;
+ sink: PointSink;
+ /** Esc (or the phone's Back to chat, through onBackToChat) */
+ onExit: () => void;
+ onBackToChat?: () => void;
+}
+
+type Bar = { kind: 'fail' | 'limit' | 'waiting'; text: string } | null;
+type Sheet = 'none' | 'select' | 'added';
+
+function useReducedMotion(): boolean {
+ const [reduced, setReduced] = useState(() => typeof window !== 'undefined' && !!window.matchMedia?.('(prefers-reduced-motion: reduce)').matches);
+ useEffect(() => {
+ const mq = window.matchMedia?.('(prefers-reduced-motion: reduce)');
+ if (!mq) return;
+ const on = () => setReduced(mq.matches);
+ mq.addEventListener?.('change', on);
+ return () => mq.removeEventListener?.('change', on);
+ }, []);
+ return reduced;
+}
+
+const codeOf = (e: unknown) => (e instanceof PointError ? e.code : 'failed');
+
+export const PointLayer: React.FC<PointLayerProps> = ({ request, page, frameId, pageUrl, phone, sink, onExit, onBackToChat }) => {
+ const viewRef = useRef<HTMLDivElement>(null);
+ const [size, setSize] = useState<{ width: number; height: number }>({ width: 0, height: 0 });
+ const [sel, setSel] = useState<PointEl | null>(null);
+ const [picked, setPicked] = useState<string | null>(null);
+ const [bar, setBar] = useState<Bar>(null);
+ const [said, setSaid] = useState('');
+ const [sheet, setSheet] = useState<Sheet>('none');
+ const reduced = useReducedMotion();
+
+ // Only the newest hit test / neighbour answer is drawn
+ const tok = useRef(0);
+ const lastPos = useRef<{ x: number; y: number } | null>(null);
+ const lastHover = useRef(0);
+ const hoverTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const sinkRef = useRef(sink);
+ sinkRef.current = sink;
+ const selRef = useRef(sel);
+ selRef.current = sel;
+ const alive = useRef(true);
+ useEffect(() => () => {
+ alive.current = false;
+ if (hoverTimer.current) clearTimeout(hoverTimer.current);
+ }, []);
+
+ // Measure the view the page image is drawn in
+ useEffect(() => {
+ const el = viewRef.current;
+ if (!el) return;
+ const measure = () => setSize({ width: el.clientWidth, height: el.clientHeight });
+ measure();
+ if (typeof ResizeObserver === 'undefined') return;
+ const ro = new ResizeObserver(measure);
+ ro.observe(el);
+ return () => ro.disconnect();
+ }, []);
+
+ // Keyboard users land in the view when Point turns on
+ useEffect(() => {
+ viewRef.current?.focus({ preventScroll: true });
+ }, []);
+
+ const fit = useMemo(() => (page ? containFit(size, page) : null), [size, page]);
+
+ // Bars clear themselves (the waiting bar stays until an answer comes)
+ useEffect(() => {
+ if (!bar || bar.kind === 'waiting') return;
+ const t = setTimeout(() => setBar(null), bar.kind === 'fail' ? FAIL_BAR_MS : LIMIT_BAR_MS);
+ return () => clearTimeout(t);
+ }, [bar]);
+
+ // Teal after a pick: 600 ms, or until the selection changes under reduced motion
+ useEffect(() => {
+ if (!picked || reduced) return;
+ const t = setTimeout(() => setPicked(null), PICKED_FLASH_MS);
+ return () => clearTimeout(t);
+ }, [picked, reduced]);
+
+ const select = useCallback((el: PointEl | null, announce = true) => {
+ setSel((prev) => {
+ if (prev?.handle !== el?.handle) setPicked(null);
+ return el;
+ });
+ if (el && announce) setSaid(spokenText(el));
+ }, []);
+
+ const onError = useCallback((e: unknown, loud: boolean) => {
+ const code = codeOf(e);
+ if (code === 'loading') setBar({ kind: 'waiting', text: POINT_COPY.waiting });
+ else if (code === 'bad_request') console.error('point: bad request', e);
+ else if (loud && code !== 'unsupported') setBar({ kind: 'fail', text: POINT_COPY.failed });
+ if (code === 'nothing' || code === 'stale') select(null, false);
+ }, [select]);
+
+ /** Hit test at a view point; `then` runs with the element when it's still the newest answer. */
+ const hit = useCallback((vx: number, vy: number, loud: boolean, then?: (el: PointEl) => void) => {
+ if (!fit || !page) return;
+ const p = toPage(fit, page, vx, vy);
+ if (!p) {
+ if (loud) setBar({ kind: 'fail', text: POINT_COPY.failed });
+ select(null, false);
+ return;
+ }
+ lastPos.current = { x: vx, y: vy };
+ const t = ++tok.current;
+ request({ action: 'point_at', x: p.x, y: p.y }).then(
+ (m) => {
+ if (!alive.current || t !== tok.current) return;
+ const el = parsePointEl(m.el);
+ if (!el) return onError(new PointError('failed'), loud);
+ setBar((b) => (b?.kind === 'waiting' ? null : b));
+ select(el);
+ then?.(el);
+ },
+ (e) => {
+ if (!alive.current || t !== tok.current) return;
+ onError(e, loud);
+ },
+ );
+ }, [fit, page, request, select, onError]);
+
+ const neighbour = useCallback((dir: string) => {
+ const cur = selRef.current;
+ const t = ++tok.current;
+ request(cur ? { action: 'point_neighbour', handle: cur.handle, dir } : { action: 'point_neighbour', dir: 'centre' }).then(
+ (m) => {
+ if (!alive.current || t !== tok.current) return;
+ const el = parsePointEl(m.el, m.edge ?? m.el?.edge);
+ if (!el) return onError(new PointError('failed'), true);
+ setBar((b) => (b?.kind === 'waiting' ? null : b));
+ // Nothing that way: keep the selection and say nothing new
+ if (el.edge && cur && el.handle === cur.handle) return;
+ select(el);
+ },
+ (e) => {
+ if (!alive.current || t !== tok.current) return;
+ if (codeOf(e) === 'stale' && lastPos.current) return hit(lastPos.current.x, lastPos.current.y, false);
+ onError(e, true);
+ },
+ );
+ }, [request, select, onError, hit]);
+
+ const pick = useCallback((el: PointEl, fromMouse: boolean) => {
+ const s = sinkRef.current;
+ const refusal = pickRefusal(s.picks, s.filesLeft);
+ if (refusal) {
+ setBar({ kind: 'limit', text: refusal });
+ setSaid(refusal);
+ return;
+ }
+ const n = s.picks + 1;
+ const key = s.start(el.label, n, { fromMouse });
+ setPicked(el.handle);
+ setSaid(addedText(el.label));
+ if (phone) setSheet('added');
+ request({ action: 'point_pick', handle: el.handle, n }).then(
+ (m) => {
+ const p = parsePointPick(m.pick);
+ if (!p) {
+ sinkRef.current.fail(key);
+ if (alive.current) setBar({ kind: 'fail', text: POINT_COPY.failed });
+ return;
+ }
+ sinkRef.current.done(key, p);
+ },
+ (e) => {
+ sinkRef.current.fail(key);
+ if (!alive.current) return;
+ setPicked(null);
+ if (phone) setSheet('none');
+ const code = codeOf(e);
+ if (code === 'bad_request') console.error('point: bad request', e);
+ setBar({ kind: 'fail', text: POINT_COPY.failed });
+ if (code === 'stale' && lastPos.current) hit(lastPos.current.x, lastPos.current.y, false);
+ },
+ );
+ }, [request, phone, hit]);
+
+ // A new frame while something is selected: re-read its box, at most every 250 ms
+ const lastSelf = useRef(0);
+ const selfTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
+ useEffect(() => {
+ if (!sel || frameId === null) return;
+ const run = () => {
+ selfTimer.current = null;
+ const cur = selRef.current;
+ if (!cur) return;
+ lastSelf.current = Date.now();
+ const t = tok.current;
+ request({ action: 'point_neighbour', handle: cur.handle, dir: 'self' }).then(
+ (m) => {
+ if (!alive.current || t !== tok.current || selRef.current?.handle !== cur.handle) return;
+ const el = parsePointEl(m.el);
+ if (el) setSel(el);
+ },
+ (e) => {
+ if (!alive.current || t !== tok.current) return;
+ if (codeOf(e) === 'stale') {
+ if (lastPos.current && !phone) hit(lastPos.current.x, lastPos.current.y, false);
+ else select(null, false);
+ }
+ },
+ );
+ };
+ if (selfTimer.current) return;
+ const wait = Math.max(0, SELF_REFRESH_MS - (Date.now() - lastSelf.current));
+ selfTimer.current = setTimeout(run, wait);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [frameId]);
+ useEffect(() => () => {
+ if (selfTimer.current) clearTimeout(selfTimer.current);
+ }, []);
+
+ // The page moved on: whatever was selected belongs to the old one
+ const firstUrl = useRef(true);
+ useEffect(() => {
+ if (firstUrl.current) {
+ firstUrl.current = false;
+ return;
+ }
+ tok.current++;
+ select(null, false);
+ setSheet('none');
+ }, [pageUrl, select]);
+
+ const local = (e: { clientX: number; clientY: number }) => {
+ const r = viewRef.current!.getBoundingClientRect();
+ return { x: e.clientX - r.left, y: e.clientY - r.top };
+ };
+
+ const onPointerMove = (e: React.PointerEvent) => {
+ if (phone || e.pointerType !== 'mouse') return;
+ const { x, y } = local(e);
+ lastPos.current = { x, y };
+ const fire = () => {
+ hoverTimer.current = null;
+ lastHover.current = Date.now();
+ const p = lastPos.current;
+ if (p) hit(p.x, p.y, false);
+ };
+ if (hoverTimer.current) return;
+ const since = Date.now() - lastHover.current;
+ if (since >= HOVER_THROTTLE_MS) fire();
+ else hoverTimer.current = setTimeout(fire, HOVER_THROTTLE_MS - since);
+ };
+
+ const outline = sel && fit && page ? toView(fit, page, sel.box) : null;
+
+ const onClick = (e: React.MouseEvent) => {
+ const { x, y } = local(e);
+ if (phone) {
+ hit(x, y, true, () => setSheet('select'));
+ return;
+ }
+ const cur = selRef.current;
+ if (cur && outline && x >= outline.x && x <= outline.x + outline.width && y >= outline.y && y <= outline.y + outline.height) {
+ pick(cur, true);
+ return;
+ }
+ hit(x, y, true, (el) => pick(el, true));
+ };
+
+ const onKeyDown = (e: React.KeyboardEvent) => {
+ if (e.target !== e.currentTarget) return;
+ const dir = ARROW_DIRS[e.key];
+ if (dir) {
+ e.preventDefault();
+ neighbour(selRef.current ? dir : 'centre');
+ return;
+ }
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ if (selRef.current) pick(selRef.current, false);
+ return;
+ }
+ if (e.key === 'Escape') {
+ e.preventDefault();
+ e.stopPropagation();
+ if (sheet !== 'none') setSheet('none');
+ else onExit();
+ }
+ };
+
+ const teal = !!sel && picked === sel.handle;
+ const tag = sel ? tagText(sel) : '';
+ const tagLabel = teal ? addedText(sel!.label) : tag;
+ // S1: clamp the tag by its real width, so a wide tag never runs past the right edge.
+ const tagRef = useRef<HTMLSpanElement | null>(null);
+ const [tagW, setTagW] = useState(160);
+ useLayoutEffect(() => {
+ const w = tagRef.current?.offsetWidth;
+ if (w && w !== tagW) setTagW(w);
+ });
+ const place = outline ? tagPlacement(outline, size.height) : 'above';
+ const topText = !page ? POINT_COPY.waiting : phone ? POINT_COPY.barPhone : POINT_COPY.barDesktop;
+
+ return (
+ <div
+ ref={viewRef}
+ role="application"
+ tabIndex={0}
+ aria-label={POINT_COPY.viewName}
+ data-point-layer=""
+ data-point-state={teal ? 'picked' : sel ? 'selected' : 'idle'}
+ onPointerMove={onPointerMove}
+ onPointerLeave={() => {
+ if (hoverTimer.current) clearTimeout(hoverTimer.current);
+ hoverTimer.current = null;
+ }}
+ onClick={onClick}
+ onKeyDown={onKeyDown}
+ className="absolute inset-0 z-10 cursor-crosshair rounded-xl ring-2 ring-inset ring-violet-500/70 focus:outline-none focus-visible:ring-[3px] focus-visible:ring-sky-300"
+ >
+ <div className="absolute top-0 inset-x-0 h-7 px-2.5 flex items-center justify-between gap-2 bg-[rgb(14_10_33/0.88)] text-[11.5px] text-zinc-100 pointer-events-none rounded-t-xl">
+ <span className="truncate font-semibold">{bar?.kind === 'waiting' ? bar.text : topText}</span>
+ {!phone && <span className="shrink-0 text-zinc-400">{POINT_COPY.keys}</span>}
+ </div>
+
+ {outline && outline.width > 0 && outline.height > 0 && (
+ <>
+ <div
+ data-point-outline=""
+ className={`absolute pointer-events-none rounded-[3px] border-2 ${
+ teal ? 'border-teal-300 bg-teal-300/15' : 'border-violet-400 bg-violet-400/10'
+ } motion-safe:transition-[left,top,width,height] motion-safe:duration-75`}
+ style={{ left: outline.x, top: outline.y, width: outline.width, height: outline.height }}
+ />
+ <span
+ ref={tagRef}
+ data-point-tag=""
+ className={`absolute pointer-events-none max-w-[calc(100%-8px)] truncate h-[18px] px-1.5 leading-[18px] rounded font-mono text-[11px] ${
+ teal ? 'bg-teal-300 text-teal-950' : 'bg-violet-600 text-white'
+ }`}
+ style={{
+ left: Math.max(4, Math.min(outline.x, size.width - 4 - tagW)),
+ top: place === 'above' ? outline.y - 20 : place === 'below' ? outline.y + outline.height + 2 : outline.y + 2,
+ }}
+ >
+ {tagLabel}
+ </span>
+ </>
+ )}
+
+ {bar && bar.kind !== 'waiting' && (
+ <div
+ role="alert"
+ data-point-bar={bar.kind}
+ className={`absolute bottom-2 inset-x-2 px-2.5 py-1.5 rounded-lg text-xs pointer-events-none ${
+ bar.kind === 'fail' ? 'border border-rose-500/40 bg-rose-950/90 text-rose-200' : 'border border-white/15 bg-[rgb(14_10_33/0.92)] text-zinc-200'
+ }`}
+ >
+ {bar.text}
+ </div>
+ )}
+
+ <span className="sr-only" aria-live="polite" data-point-live="">
+ {said}
+ </span>
+
+ {phone && sheet !== 'none' && (
+ <div
+ role="dialog"
+ aria-label={sheet === 'added' ? POINT_COPY.added : tag}
+ data-point-sheet={sheet}
+ onClick={(e) => e.stopPropagation()}
+ className="fixed inset-x-0 bottom-0 z-[70] px-4 pt-3 pb-[calc(12px+env(safe-area-inset-bottom))] bg-[#14102b] border-t border-[#3f3868] rounded-t-2xl shadow-2xl cursor-default"
+ >
+ {sheet === 'select' && sel ? (
+ <>
+ <p className="font-mono text-[12px] text-zinc-100 truncate">{tag}</p>
+ <p className="mt-0.5 text-[12px] text-zinc-400 truncate">{sheetLine(sel.text)}</p>
+ <div className="mt-3 flex gap-2">
+ <button
+ type="button"
+ onClick={() => neighbour('parent')}
+ className="flex-1 h-11 rounded-[10px] border border-[#3f3868] text-zinc-100 text-sm font-semibold focus:outline-none focus-visible:ring-2 focus-visible:ring-violet-300"
+ >
+ {POINT_COPY.wider}
+ </button>
+ <button
+ type="button"
+ onClick={() => pick(sel, false)}
+ className="flex-1 h-11 rounded-[10px] bg-violet-600 text-white text-sm font-semibold focus:outline-none focus-visible:ring-2 focus-visible:ring-violet-300"
+ >
+ {POINT_COPY.add}
+ </button>
+ </div>
+ </>
+ ) : (
+ <>
+ <p className="text-sm font-semibold text-teal-200">{POINT_COPY.added}</p>
+ <p className="mt-0.5 text-[12px] text-zinc-300">{pickedCountText(sink.picks)}</p>
+ <div className="mt-3 flex gap-2">
+ <button
+ type="button"
+ onClick={() => {
+ setSheet('none');
+ select(null, false);
+ }}
+ className="flex-1 h-11 rounded-[10px] border border-[#3f3868] text-zinc-100 text-sm font-semibold focus:outline-none focus-visible:ring-2 focus-visible:ring-violet-300"
+ >
+ {POINT_COPY.keep}
+ </button>
+ <button
+ type="button"
+ onClick={() => (onBackToChat ?? onExit)()}
+ className="flex-1 h-11 rounded-[10px] bg-violet-600 text-white text-sm font-semibold focus:outline-none focus-visible:ring-2 focus-visible:ring-violet-300"
+ >
+ {POINT_COPY.back}
+ </button>
+ </div>
+ </>
+ )}
+ </div>
+ )}
+ </div>
+ );
+};
diff --git a/frontend/src/components/VirtualMachinePane.tsx b/frontend/src/components/VirtualMachinePane.tsx
index 9f5ca837..f0a80547 100644
--- a/frontend/src/components/VirtualMachinePane.tsx
+++ b/frontend/src/components/VirtualMachinePane.tsx
@@ -14,6 +14,7 @@ import {
CheckCircle2,
Eye,
Hand,
+ Crosshair,
} from 'lucide-react';
import { playSfx } from '../audio/chiptune';
import { BOT_BUSY_TEXT, HELD_BY_PERSON_TEXT, useBrowserStream } from '../useBrowserStream';
@@ -29,6 +30,8 @@ import type { SwitchEntry } from '../watchLive';
import { BrowserSwitcherMenu, BrowserSwitcherRow } from './WatchLive';
import { showOnce, showOnceStore, useShowOnce } from '../showOnce';
import { RecordStepsButton, RecordingStrip } from './ShowOnce';
+import { PointLayer, PointSink } from './PointLayer';
+import { POINT_COPY, footerText } from '../point';
const PHONE_QUERY = '(max-width: 639px)';
@@ -98,6 +101,8 @@ export interface VirtualMachinePaneProps {
onStepDone?: (id: string) => Promise<string | void> | void;
/** Show it once: the single bot this browser belongs to (not set for teams and channels). */
showOnceBot?: { id: string; name: string };
+ /** G3 Point at it: where picks go (the composer). Without it there's no Point button. */
+ point?: PointSink;
}
type PaneTab = 'browser' | 'terminal' | 'vault';
@@ -137,6 +142,7 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
solveRequest = 0,
humanStep = null,
onStepDone,
+ point,
switcher,
showOnceBot,
}) => {
@@ -344,6 +350,19 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
const loginsOnThisPage = useMemo(() => passwords.logins.filter((l) => loginMatchesPage(l, pageUrl)).length, [passwords.logins, pageUrl]);
+ // G3 Point at it: shown while a page is on screen and the server knows the point actions
+ const [pointing, setPointing] = useState(false);
+ const pointButton = useRef<HTMLButtonElement>(null);
+ const pointShown = !!point && !isWindow && activeTab === 'browser' && !!frameSrc && stream.connected && !stream.unsupported.has('point');
+ const pointOn = pointing && pointShown && !takeover;
+ useEffect(() => {
+ if (pointing && (!pointShown || takeover)) setPointing(false);
+ }, [pointing, pointShown, takeover]);
+ const stopPointing = useCallback(() => {
+ setPointing(false);
+ pointButton.current?.focus();
+ }, []);
+
if (!isOpen) return null;
const switching = !!switcher && switcher.entries.length >= 2;
@@ -380,8 +399,31 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
<ComputerModeChip api={computer} />
<OpenWindowButton api={computer} />
- {/* Take over: always there while a browser exists, so keyboard users have a way in */}
- {!isWindow && (
+ {pointShown || (point && takeover && !isWindow) ? (
+ <button
+ ref={pointButton}
+ type="button"
+ data-point-button=""
+ aria-pressed={pointOn}
+ aria-label={POINT_COPY.buttonName}
+ title={takeover ? POINT_COPY.handBack : POINT_COPY.buttonName}
+ disabled={takeover}
+ onClick={() => {
+ playSfx('click');
+ setPointing((p) => !p);
+ }}
+ className={`${narrow ? 'h-11' : 'h-[30px]'} px-2.5 rounded-[10px] inline-flex items-center gap-1.5 text-[13px] font-semibold whitespace-nowrap cursor-pointer disabled:cursor-not-allowed disabled:opacity-50 focus:outline-none focus-visible:ring-2 focus-visible:ring-sky-300 border ${
+ pointOn ? 'bg-violet-600 border-violet-400 text-white ring-[3px] ring-violet-500/25' : 'border-[#3f3868] text-zinc-200 hover:bg-[#2c2552]'
+ }`}
+ >
+ <Crosshair size={14} aria-hidden="true" />
+ {POINT_COPY.button}
+ </button>
+ ) : null}
+
+ {/* Take over: always there while a browser exists, so keyboard users have a way in.
+ On a phone with Point showing, the view's own Take over is the way in (no room for both). */}
+ {!isWindow && !(narrow && pointShown && !isControlMode) && (
<button
type="button"
onClick={() => (isControlMode ? handBack() : takeOver())}
@@ -689,12 +731,27 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
draggable={false}
className="w-full h-full object-contain"
/>
- {!needsYou && !waitingForBot && !waitBot?.gaveUp && (
+ {pointOn && point && (
+ <PointLayer
+ request={stream.request}
+ page={stream.frame ? { width: stream.frame.width, height: stream.frame.height } : null}
+ frameId={stream.frame?.id ?? null}
+ pageUrl={pageUrl}
+ phone={narrow}
+ sink={point}
+ onExit={stopPointing}
+ onBackToChat={() => {
+ setPointing(false);
+ onClose();
+ }}
+ />
+ )}
+ {!pointOn && !needsYou && !waitingForBot && !waitBot?.gaveUp && (
<span className="absolute top-2 left-2 h-[22px] px-2 inline-flex items-center gap-1 rounded-full bg-[rgb(14_10_33/0.88)] text-[11px] text-zinc-200 pointer-events-none group-hover:opacity-0 group-focus-within:opacity-0 kw-veil-in">
<Eye size={12} aria-hidden="true" /> Watching
</span>
)}
- {!isWindow && stream.connected && (
+ {!pointOn && !isWindow && stream.connected && (
/* B / C: one click anywhere on the page takes it over (that click isn't passed on) */
<button
type="button"
@@ -847,7 +904,7 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
{/* Footer Status */}
<div className="p-2.5 border-t border-zinc-800 bg-zinc-900/60 flex items-center justify-between text-[11px] text-zinc-400">
- <div className="flex items-center gap-1.5" data-browser-footer>
+ <div className="flex items-center gap-1.5 shrink-0" data-browser-footer>
{isLocal ? (
<Laptop size={12} className={browserReady || isWindow ? 'text-amber-300/80' : 'text-zinc-500'} />
) : (
@@ -855,6 +912,22 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
)}
<span>{browserFooterLabel(computer.state.settings, browserReady)}</span>
</div>
+ {pointOn && point ? (
+ <span data-point-footer="" className="min-w-0 flex-1 px-2 text-center leading-snug text-zinc-300 [overflow-wrap:anywhere]">
+ {/* Wraps only between "Pointing · n picked" and "· Esc to stop" in a narrow pane */}
+ {(() => {
+ const [state, count, keys] = footerText(point.picks).split(' · ');
+ return (
+ <>
+ <span className="whitespace-nowrap">{`${state} · ${count}`}</span>{' '}
+ <span className="whitespace-nowrap">{`· ${keys}`}</span>
+ </>
+ );
+ })()}
+ </span>
+ ) : point && takeover && !isWindow ? (
+ <span data-point-footer="" className="min-w-0 flex-1 px-2 text-center leading-snug text-zinc-400">{POINT_COPY.handBack}</span>
+ ) : null}
{onRestartVm && !isWindow && (
<button
type="button"
diff --git a/frontend/src/point.ts b/frontend/src/point.ts
new file mode 100644
index 00000000..12859bf7
--- /dev/null
+++ b/frontend/src/point.ts
@@ -0,0 +1,326 @@
+// G3 (0.9.0) Point at it: the person points at part of the page the bot is browsing, and the bot
+// gets that exact element. Design: release-090/designs/g3-point.md (Mira). Wire: release-090/g3-contract.md
+// rev 2 (Vega). Everything here is pure, so the tests can run it without a browser.
+
+/** Every point error carries one of these; route on it, never on the error text. */
+export type PointCode = 'nothing' | 'stale' | 'loading' | 'failed' | 'bad_request';
+const CODES: ReadonlySet<string> = new Set(['nothing', 'stale', 'loading', 'failed', 'bad_request']);
+
+export interface PointBox {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+}
+
+export interface PointFrame {
+ host: string;
+ cross_site: boolean;
+}
+
+/** One element under the pointer, from a `point_at` or `point_neighbour` ack. */
+export interface PointEl {
+ handle: string;
+ label: string;
+ selector: string | null;
+ box: PointBox;
+ viewport: { width: number; height: number };
+ text: string;
+ frame: PointFrame | null;
+ /** `point_neighbour` only: nothing in that direction, so this is the same element. */
+ edge: boolean;
+}
+
+/** A `point_pick` ack: the crop is already an unsent upload. */
+export interface PointPick {
+ attachment_id: string;
+ picture: boolean;
+ url: string;
+ host: string;
+ path: string;
+ label: string;
+ selector: string | null;
+ box: PointBox;
+ viewport: { width: number; height: number };
+ frame: PointFrame | null;
+ captured_at: string;
+ thumb_url: string | null;
+}
+
+/** The bubble's `meta.attachments[i].point`. */
+export interface PointMeta {
+ n: number;
+ of: number;
+ url: string;
+ host: string;
+ path: string;
+ label: string;
+ selector: string | null;
+ width: number;
+ height: number;
+ captured_at: string;
+ picture: boolean;
+ frame_host: string | null;
+}
+
+/** At most 5 picks per message (the server answers a 6th with `too_many_picks`). */
+export const MAX_PICKS = 5;
+/** Hover hit tests: one per 80 ms, only the newest is drawn (Mira's ENG note). */
+export const HOVER_THROTTLE_MS = 80;
+/** A selected element is re-read at most this often while frames arrive (`dir:"self"`). */
+export const SELF_REFRESH_MS = 250;
+/** A point request with no answer by then counts as failed. */
+export const POINT_TIMEOUT_MS = 5000;
+/** How long the teal "Added …" outline stays (none under reduced motion: it just stays teal). */
+export const PICKED_FLASH_MS = 600;
+export const FAIL_BAR_MS = 4000;
+export const LIMIT_BAR_MS = 3000;
+
+// Copy (Mira's list, all of it)
+export const POINT_COPY = {
+ button: 'Point',
+ buttonName: 'Point at part of the page',
+ barDesktop: 'Click the part you mean',
+ barPhone: 'Tap the part you mean',
+ keys: '↑ wider · Esc stop',
+ waiting: 'Waiting for the page…',
+ handBack: 'Hand back to point at something',
+ failed: "Couldn't read that part of the page. Try again.",
+ limit: 'Up to 5 parts per message',
+ capturing: 'Taking a picture…',
+ noPicture: 'No picture · the code was added',
+ wider: 'Wider',
+ add: 'Add to message',
+ added: 'Added to your message',
+ keep: 'Keep pointing',
+ back: 'Back to chat',
+ viewName: 'Page view. Arrows choose a part, Enter adds it, Escape stops',
+} as const;
+
+export const footerText = (n: number) => `Pointing · ${n} picked · Esc to stop`;
+export const addedText = (label: string) => `Added ${label}`;
+/** S3: the phone sheet's second line. */
+export const sheetLine = (text: string | null | undefined) => (text ? `"${text}" · tap another part to change it` : 'Tap another part to change it');
+export const embeddedText = (host: string) => `Embedded page from ${host}`;
+export const removeText = (name: string) => `Remove ${name}`;
+export const pickedCountText = (n: number) =>
+ n === 1 ? '1 part picked. Tap another to add it, or go back and write what to change.' : `${n} parts picked. Tap another to add it, or go back and write what to change.`;
+
+/** An error the point actions answered, or `failed` for a timeout, a close or no socket. */
+export class PointError extends Error {
+ constructor(readonly code: PointCode | 'unsupported', message?: string) {
+ super(message || code);
+ this.name = 'PointError';
+ }
+}
+
+/** The code on a point error; anything unknown (an older server) reads as failed. */
+export function pointErrorCode(message: { code?: unknown; error?: unknown }): PointCode | 'unsupported' {
+ if (typeof message.code === 'string' && CODES.has(message.code)) return message.code as PointCode;
+ // A server from before G3 refuses the new actions as bad input: hide Point, don't log a bug
+ if (message.code === undefined && /invalid browser input/i.test(String(message.error ?? ''))) return 'unsupported';
+ return 'failed';
+}
+
+const num = (v: unknown): number | null => (typeof v === 'number' && Number.isFinite(v) ? v : null);
+const str = (v: unknown, max = 2000): string | null => (typeof v === 'string' ? v.slice(0, max) : null);
+
+function parseBox(v: unknown): PointBox | null {
+ const b = v as Record<string, unknown> | null;
+ if (!b || typeof b !== 'object') return null;
+ const x = num(b.x), y = num(b.y), width = num(b.width), height = num(b.height);
+ if (x === null || y === null || width === null || height === null || width < 0 || height < 0) return null;
+ return { x, y, width, height };
+}
+
+function parseViewport(v: unknown): { width: number; height: number } | null {
+ const b = v as Record<string, unknown> | null;
+ const width = num(b?.width), height = num(b?.height);
+ return width && height && width > 0 && height > 0 ? { width, height } : null;
+}
+
+function parseFrame(v: unknown): PointFrame | null {
+ const f = v as Record<string, unknown> | null;
+ if (!f || typeof f !== 'object' || typeof f.host !== 'string') return null;
+ return { host: f.host.slice(0, 253), cross_site: f.cross_site === true };
+}
+
+/** An `el` from an ack, or null when it isn't one (then the reply is ignored, never drawn). */
+export function parsePointEl(v: unknown, edge?: unknown): PointEl | null {
+ const e = v as Record<string, unknown> | null;
+ if (!e || typeof e !== 'object') return null;
+ const handle = str(e.handle, 40);
+ const label = str(e.label, 80);
+ const box = parseBox(e.box);
+ if (!handle || label === null || !box) return null;
+ return {
+ handle,
+ label,
+ selector: str(e.selector, 300) || null,
+ box,
+ viewport: parseViewport(e.viewport) ?? { width: 0, height: 0 },
+ text: str(e.text, 80) ?? '',
+ frame: parseFrame(e.frame),
+ edge: edge === true,
+ };
+}
+
+/** A `pick` from a `point_pick` ack, or null. */
+export function parsePointPick(v: unknown): PointPick | null {
+ const p = v as Record<string, unknown> | null;
+ if (!p || typeof p !== 'object') return null;
+ const attachment_id = str(p.attachment_id, 64);
+ const box = parseBox(p.box);
+ if (!attachment_id || !box) return null;
+ const thumb = str(p.thumb_url, 300);
+ return {
+ attachment_id,
+ picture: p.picture !== false,
+ url: str(p.url) ?? '',
+ host: str(p.host, 253) ?? '',
+ path: str(p.path) ?? '',
+ label: str(p.label, 80) ?? '',
+ selector: str(p.selector, 300) || null,
+ box,
+ viewport: parseViewport(p.viewport) ?? { width: 0, height: 0 },
+ frame: parseFrame(p.frame),
+ captured_at: str(p.captured_at, 40) ?? '',
+ // Only our own attachment route: a URL from the wire is never loaded from anywhere else
+ thumb_url: thumb && thumb.startsWith('/api/attachments/') ? thumb : null,
+ };
+}
+
+/** The bubble's `point` object, or null when malformed (then it's an ordinary file tile). */
+export function parsePointMeta(v: unknown): PointMeta | null {
+ const p = v as Record<string, unknown> | null;
+ if (!p || typeof p !== 'object') return null;
+ const n = num(p.n), of = num(p.of), width = num(p.width), height = num(p.height);
+ if (n === null || of === null || width === null || height === null) return null;
+ return {
+ n,
+ of,
+ url: str(p.url) ?? '',
+ host: str(p.host, 253) ?? '',
+ path: str(p.path) ?? '',
+ label: str(p.label, 80) ?? '',
+ selector: str(p.selector, 300) || null,
+ width,
+ height,
+ captured_at: str(p.captured_at, 40) ?? '',
+ picture: p.picture !== false,
+ frame_host: str(p.frame_host, 253) || null,
+ };
+}
+
+/** The bubble's `point` for a pick, as the server will write it (n/of from the picks' order). */
+export function pointMetaOf(pick: PointPick, n: number, of: number): PointMeta {
+ return {
+ n,
+ of,
+ url: pick.url,
+ host: pick.host,
+ path: pick.path,
+ label: pick.label,
+ selector: pick.selector,
+ width: pick.box.width,
+ height: pick.box.height,
+ captured_at: pick.captured_at,
+ picture: pick.picture,
+ frame_host: pick.frame?.cross_site ? pick.frame.host : null,
+ };
+}
+
+/** What the outline's tag says: `button.pay 328 × 36`, or `iframe pay.example.net` for a cross-site frame. */
+export function tagText(el: Pick<PointEl, 'label' | 'box' | 'frame'>): string {
+ if (el.frame?.cross_site) return `iframe ${el.frame.host}`;
+ return `${el.label} ${Math.round(el.box.width)} × ${Math.round(el.box.height)}`;
+}
+
+/** The live region's line: "button.pay, 328 by 36, Pay €42.00". */
+export function spokenText(el: Pick<PointEl, 'label' | 'box' | 'text' | 'frame'>): string {
+ const name = el.frame?.cross_site ? `iframe ${el.frame.host}` : el.label;
+ const parts = [name, `${Math.round(el.box.width)} by ${Math.round(el.box.height)}`];
+ if (el.text) parts.push(el.text);
+ return parts.join(', ');
+}
+
+/** The chip's and the row's first line: the selector, or the label when nothing unique was built. */
+/** S2: the short label (as the tag says it) for display and names; the full selector goes in the title. */
+export const pickName = (p: { selector: string | null; label: string }) => p.label || p.selector || '';
+export const pickTitle = (p: { selector: string | null; label: string }) => p.selector || p.label || '';
+
+/** The chip's second line. */
+export function chipLine(p: { picture: boolean; host: string; path: string; frame_host?: string | null; frame?: PointFrame | null }): string {
+ const frameHost = p.frame_host ?? (p.frame?.cross_site ? p.frame.host : null);
+ if (frameHost) return embeddedText(frameHost);
+ if (!p.picture) return POINT_COPY.noPicture;
+ return `${p.host}${p.path}`;
+}
+
+/** HH:MM in the viewer's local time, or '' for a bad time. */
+export function clockText(at: string, locale?: string): string {
+ const t = at ? new Date(at) : null;
+ if (!t || Number.isNaN(t.getTime())) return '';
+ return t.toLocaleTimeString(locale ?? [], { hour: '2-digit', minute: '2-digit', hour12: false });
+}
+
+/** The bubble row's second line: `{host}{path} · W × H · HH:MM`. */
+export function rowLine(p: PointMeta, locale?: string): string {
+ const where = p.frame_host ? embeddedText(p.frame_host) : `${p.host}${p.path}`;
+ return [where, `${Math.round(p.width)} × ${Math.round(p.height)}`, clockText(p.captured_at, locale)].filter(Boolean).join(' · ');
+}
+
+/** Where the page image sits inside the view (object-contain): the scale and the letterbox offsets. */
+export interface Fit {
+ scale: number;
+ left: number;
+ top: number;
+}
+
+export function containFit(view: { width: number; height: number }, page: { width: number; height: number }): Fit | null {
+ if (!(view.width > 0) || !(view.height > 0) || !(page.width > 0) || !(page.height > 0)) return null;
+ const scale = Math.min(view.width / page.width, view.height / page.height);
+ return { scale, left: (view.width - page.width * scale) / 2, top: (view.height - page.height * scale) / 2 };
+}
+
+/** A point in the view (relative to its top left) in page CSS px, or null in the letterbox. */
+export function toPage(fit: Fit, page: { width: number; height: number }, x: number, y: number): { x: number; y: number } | null {
+ const px = (x - fit.left) / fit.scale;
+ const py = (y - fit.top) / fit.scale;
+ if (px < 0 || py < 0 || px > page.width || py > page.height) return null;
+ return { x: Math.round(px * 10) / 10, y: Math.round(py * 10) / 10 };
+}
+
+/** A page box drawn in the view, clipped to the page picture. */
+export function toView(fit: Fit, page: { width: number; height: number }, box: PointBox): PointBox {
+ const x0 = Math.max(0, box.x), y0 = Math.max(0, box.y);
+ const x1 = Math.min(page.width, box.x + box.width), y1 = Math.min(page.height, box.y + box.height);
+ return {
+ x: fit.left + x0 * fit.scale,
+ y: fit.top + y0 * fit.scale,
+ width: Math.max(0, x1 - x0) * fit.scale,
+ height: Math.max(0, y1 - y0) * fit.scale,
+ };
+}
+
+/** The tag goes above the outline, or below it when there's no room above (inside it as a last resort). */
+export function tagPlacement(outline: PointBox, viewHeight: number, tagHeight = 18): 'above' | 'below' | 'inside' {
+ if (outline.y >= tagHeight + 2) return 'above';
+ if (outline.y + outline.height + tagHeight + 2 <= viewHeight) return 'below';
+ return 'inside';
+}
+
+/** The arrow keys' directions. */
+export const ARROW_DIRS: Record<string, 'parent' | 'child' | 'prev' | 'next'> = {
+ ArrowUp: 'parent',
+ ArrowDown: 'child',
+ ArrowLeft: 'prev',
+ ArrowRight: 'next',
+};
+
+/** Why another pick can't be added now, or null. */
+export function pickRefusal(picks: number, filesLeft: number): string | null {
+ if (picks >= MAX_PICKS) return POINT_COPY.limit;
+ if (filesLeft <= 0) return 'Up to 10 files per message';
+ return null;
+}
diff --git a/frontend/src/useBrowserStream.ts b/frontend/src/useBrowserStream.ts
index 05472048..ba5a644b 100644
--- a/frontend/src/useBrowserStream.ts
+++ b/frontend/src/useBrowserStream.ts
@@ -3,6 +3,7 @@ import { useCallback, useEffect, useRef, useState } from 'react';
import { browserStreamUrl } from './browserViewport';
import { PageDialog, SelectRequest, Size, parseDialog, parseSelect, streamErrorText } from './browserInput';
import { onRecordingFrame } from './showOnce';
+import { POINT_TIMEOUT_MS, PointError, pointErrorCode } from './point';
export interface BrowserFrame {
id: number;
@@ -52,6 +53,15 @@ export function useBrowserStream(id: string | undefined, visible: boolean) {
// Actions the server answered "Invalid browser input" for (an older server): hide their buttons
const [unsupported, setUnsupported] = useState<ReadonlySet<string>>(new Set());
const actionsById = useRef(new Map<number, string>());
+ // G3 point requests waiting for their answer, by id: they never touch the panel's banner or busy state
+ const waiters = useRef(new Map<number, { resolve: (m: Record<string, any>) => void; reject: (e: PointError) => void; timer: ReturnType<typeof setTimeout> }>());
+ const failWaiters = () => {
+ for (const w of waiters.current.values()) {
+ clearTimeout(w.timer);
+ w.reject(new PointError('failed'));
+ }
+ waiters.current.clear();
+ };
useEffect(() => {
if (!id || id === 'default' || !visible) return;
@@ -70,6 +80,18 @@ export function useBrowserStream(id: string | undefined, visible: boolean) {
if (disposed || socket.current !== ws) return;
let message: Record<string, any>;
try { message = JSON.parse(event.data); } catch { return; }
+ const waiter = (message.type === 'ack' || message.type === 'error') && typeof message.id === 'number' ? waiters.current.get(message.id) : undefined;
+ if (waiter) {
+ waiters.current.delete(message.id);
+ clearTimeout(waiter.timer);
+ if (message.type === 'ack') waiter.resolve(message);
+ else {
+ const code = pointErrorCode(message);
+ if (code === 'unsupported') setUnsupported((s) => new Set(s).add('point'));
+ waiter.reject(new PointError(code, typeof message.error === 'string' ? message.error : undefined));
+ }
+ return;
+ }
switch (message.type) {
case 'ping': ws.send(JSON.stringify({ action: 'pong' })); break;
case 'frame': {
@@ -129,6 +151,7 @@ export function useBrowserStream(id: string | undefined, visible: boolean) {
socket.current = null;
pending.current.clear();
actionsById.current.clear();
+ failWaiters();
takingControl.current = false;
setConnected(false);
setControlling(false);
@@ -150,6 +173,7 @@ export function useBrowserStream(id: string | undefined, visible: boolean) {
socket.current = null;
pending.current.clear();
actionsById.current.clear();
+ failWaiters();
setConnected(false);
setControlling(false);
setBusy(false);
@@ -200,13 +224,31 @@ export function useBrowserStream(id: string | undefined, visible: boolean) {
if (ws?.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ action: 'restore_viewport', id: ++sequence.current }));
}, []);
+ /**
+ * A G3 point action that waits for its own answer: resolves with the ack, rejects with a PointError
+ * (its `code`, or `failed` after 5 s, on a close or with no socket). Never shows the panel's banner.
+ */
+ const request = useCallback((payload: Record<string, unknown>, timeoutMs = POINT_TIMEOUT_MS): Promise<Record<string, any>> => {
+ const ws = socket.current;
+ if (!ws || ws.readyState !== WebSocket.OPEN) return Promise.reject(new PointError('failed'));
+ const id = ++sequence.current;
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(() => {
+ waiters.current.delete(id);
+ reject(new PointError('failed'));
+ }, timeoutMs);
+ waiters.current.set(id, { resolve, reject, timer });
+ ws.send(JSON.stringify({ ...payload, id }));
+ });
+ }, []);
+
const clearSelect = useCallback(() => setSelect(null), []);
const clearDialog = useCallback(() => setDialog(null), []);
const clearError = useCallback(() => setError(null), []);
return {
connected, controlling, busy, error, frame, location, tapFocus, viewport, select, dialog, cursor, unsupported, resizeIgnored,
- send, acknowledgeFrame, restoreViewport, clearSelect, clearDialog, clearError,
+ send, request, acknowledgeFrame, restoreViewport, clearSelect, clearDialog, clearError,
};
}
diff --git a/frontend/tests/point.test.mjs b/frontend/tests/point.test.mjs
new file mode 100644
index 00000000..cd9b28a4
--- /dev/null
+++ b/frontend/tests/point.test.mjs
@@ -0,0 +1,306 @@
+// 0.9.0 G3 Point at it (release-090/designs/g3-point.md, release-090/g3-contract.md rev 2):
+// the pure helpers, the stream's request/answer path, the composer's n/of, and the layer, chip and row.
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { JSDOM } from 'jsdom';
+import { loadBundled } from './bundle.mjs';
+
+const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/s/spc_default', pretendToBeVisual: true });
+const g = globalThis;
+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'Event', 'KeyboardEvent', 'MouseEvent', 'requestAnimationFrame', 'cancelAnimationFrame', 'getComputedStyle', 'localStorage']) {
+ if (!(k in dom.window)) continue;
+ Object.defineProperty(g, k, { value: dom.window[k], configurable: true, writable: true });
+}
+// The view measures itself: give every element a 640 × 400 box
+Object.defineProperty(dom.window.HTMLElement.prototype, 'clientWidth', { get: () => 640, configurable: true });
+Object.defineProperty(dom.window.HTMLElement.prototype, 'clientHeight', { get: () => 400, configurable: true });
+
+const sockets = [];
+class FakeWebSocket {
+ static OPEN = 1;
+ constructor(url) { this.url = url; this.readyState = 1; this.sent = []; sockets.push(this); }
+ send(text) { this.sent.push(JSON.parse(text)); }
+ close() { this.readyState = 3; }
+ receive(message) { this.onmessage?.({ data: JSON.stringify(message) }); }
+}
+g.WebSocket = g.window.WebSocket = FakeWebSocket;
+
+const m = await loadBundled(`
+ export { default as React } from 'react';
+ export { createRoot } from 'react-dom/client';
+ export { flushSync } from 'react-dom';
+ export * from './src/point';
+ export { useBrowserStream } from './src/useBrowserStream';
+ export { readyAttachments, parseAttachments, pointPicks } from './src/attachments';
+ export { PointLayer } from './src/components/PointLayer';
+ export { PointChip, PointRow } from './src/components/Attachments';
+`);
+const h = (...a) => m.React.createElement(...a);
+const settle = async () => { for (let i = 0; i < 10; i++) await new Promise((r) => setTimeout(r, 0)); };
+const UUID = '6b0c1d2e-3f40-4a5b-8c6d-7e8f90a1b2c3';
+const UUID2 = '7b0c1d2e-3f40-4a5b-8c6d-7e8f90a1b2c3';
+
+const el = (over = {}) => ({ handle: 'k3f9.12', label: 'button.pay', selector: 'main > form#checkout > button.pay', box: { x: 15, y: 303, width: 328, height: 36 }, viewport: { width: 1280, height: 800 }, text: 'Pay €42.00', frame: null, ...over });
+const pickWire = (over = {}) => ({ attachment_id: UUID, picture: true, url: 'https://shop.example.com/checkout', host: 'shop.example.com', path: '/checkout', label: 'button.pay', selector: 'main > form#checkout > button.pay', box: { x: 15, y: 303, width: 328, height: 36 }, viewport: { width: 1280, height: 800 }, frame: null, captured_at: '2026-11-10T14:04:09Z', thumb_url: `/api/attachments/${UUID}/content`, ...over });
+
+test('error codes: route on code; an older server without one hides Point; anything else is failed', () => {
+ assert.equal(m.pointErrorCode({ code: 'stale', error: 'x' }), 'stale');
+ assert.equal(m.pointErrorCode({ error: 'Invalid browser input' }), 'unsupported');
+ assert.equal(m.pointErrorCode({ code: 'weird', error: 'Invalid browser input' }), 'failed');
+ assert.equal(m.pointErrorCode({ error: 'boom' }), 'failed');
+});
+
+test('parsing: a thumb only from our attachment route; frame_host only for a cross-site frame', () => {
+ assert.equal(m.parsePointPick(pickWire({ thumb_url: 'https://evil.example/x.png' })).thumb_url, null);
+ assert.equal(m.parsePointPick(pickWire()).thumb_url, `/api/attachments/${UUID}/content`);
+ assert.equal(m.parsePointPick({ picture: true }), null, 'no attachment id, no pick');
+ assert.equal(m.parsePointEl({ handle: 'a', label: 'div' }), null, 'no box, no element');
+ const same = m.pointMetaOf(m.parsePointPick(pickWire({ frame: { host: 'shop.example.com', cross_site: false } })), 1, 1);
+ assert.equal(same.frame_host, null);
+ const cross = m.pointMetaOf(m.parsePointPick(pickWire({ frame: { host: 'pay.example.net', cross_site: true } })), 2, 2);
+ assert.equal(cross.frame_host, 'pay.example.net');
+});
+
+test('copy: tag, spoken line, chip line, bubble row, footer and limits', () => {
+ assert.equal(m.tagText(el()), 'button.pay 328 × 36');
+ assert.equal(m.tagText(el({ frame: { host: 'pay.example.net', cross_site: true } })), 'iframe pay.example.net');
+ assert.equal(m.spokenText(el()), 'button.pay, 328 by 36, Pay €42.00');
+ assert.equal(m.chipLine(m.parsePointPick(pickWire())), 'shop.example.com/checkout');
+ assert.equal(m.chipLine(m.parsePointPick(pickWire({ picture: false }))), 'No picture · the code was added');
+ assert.equal(m.chipLine(m.parsePointPick(pickWire({ frame: { host: 'pay.example.net', cross_site: true } }))), 'Embedded page from pay.example.net');
+ assert.equal(m.chipLine(m.parsePointPick(pickWire({ host: '', path: 'about:blank' }))), 'about:blank');
+ const row = m.rowLine(m.pointMetaOf(m.parsePointPick(pickWire()), 1, 1), 'en-GB');
+ assert.match(row, /^shop\.example\.com\/checkout · 328 × 36 · \d\d:\d\d$/);
+ assert.equal(m.footerText(2), 'Pointing · 2 picked · Esc to stop');
+ assert.equal(m.pickRefusal(5, 5), 'Up to 5 parts per message');
+ assert.equal(m.pickRefusal(2, 0), 'Up to 10 files per message');
+ assert.equal(m.pickRefusal(4, 1), null);
+ assert.doesNotMatch(Object.values(m.POINT_COPY).join(' '), /\p{Extended_Pictographic}/u, 'no emoji in copy');
+});
+
+test('geometry: object-contain letterbox, view to page and back, clipped outline', () => {
+ const fit = m.containFit({ width: 640, height: 500 }, { width: 1280, height: 800 });
+ assert.deepEqual(fit, { scale: 0.5, left: 0, top: 50 });
+ assert.equal(m.toPage(fit, { width: 1280, height: 800 }, 100, 20), null, 'the letterbox is not the page');
+ assert.deepEqual(m.toPage(fit, { width: 1280, height: 800 }, 100, 150), { x: 200, y: 200 });
+ assert.deepEqual(m.toView(fit, { width: 1280, height: 800 }, { x: -20, y: 790, width: 100, height: 40 }), { x: 0, y: 445, width: 40, height: 5 });
+ assert.equal(m.tagPlacement({ x: 0, y: 4, width: 10, height: 10 }, 400), 'below');
+ assert.equal(m.tagPlacement({ x: 0, y: 4, width: 10, height: 395 }, 400), 'inside');
+});
+
+test('composer: n/of by the picks\' order, other files not counted; the bubble parses it back', () => {
+ const pick = (id, n) => ({ key: id, name: `pointed-${n}.png`, size: 0, progress: 1, state: 'done', point: { label: 'button.pay', pick: m.parsePointPick(pickWire({ attachment_id: id })) }, attachment: { id, name: `pointed-${n}.png`, mime: 'image/png', size: 0 } });
+ const file = { key: 'f', name: 'a.txt', size: 3, progress: 1, state: 'done', attachment: { id: '8b0c1d2e-3f40-4a5b-8c6d-7e8f90a1b2c3', name: 'a.txt', mime: 'text/plain', size: 3 } };
+ const capturing = { key: 'c', name: 'pointed-4.png', size: 0, progress: 0, state: 'uploading', point: { label: 'div' } };
+ const items = [pick(UUID2, 2), file, pick(UUID, 3), capturing];
+ assert.equal(m.pointPicks(items), 3, 'a capturing pick counts toward the 5');
+ const refs = m.readyAttachments(items);
+ assert.deepEqual(refs.map((r) => r.name), ['pointed-2.png', 'a.txt', 'pointed-3.png'], 'files keep their names');
+ assert.deepEqual(refs.map((r) => r.point && [r.point.n, r.point.of]), [[1, 2], undefined, [2, 2]]);
+ const back = m.parseAttachments(JSON.stringify({ attachments: refs }));
+ assert.equal(back[0].point.selector, 'main > form#checkout > button.pay');
+ assert.equal(back[1].point, undefined);
+ assert.equal(m.parseAttachments({ attachments: [{ id: UUID, name: 'p.png', mime: 'image/png', size: 1, point: { n: 'x' } }] })[0].point, undefined, 'a malformed point is a plain file');
+});
+
+test('stream: point answers resolve or reject by id and never touch the panel banner', async () => {
+ let stream;
+ function Hold() {
+ stream = m.useBrowserStream('p1', true);
+ return null;
+ }
+ const root = m.createRoot(document.createElement('div'));
+ m.flushSync(() => root.render(h(Hold)));
+ await settle();
+ const ws = sockets.at(-1);
+ ws.onopen?.();
+ await settle();
+
+ const a = stream.request({ action: 'point_at', x: 1, y: 2 });
+ const sentA = ws.sent.at(-1);
+ assert.equal(sentA.action, 'point_at');
+ ws.receive({ type: 'ack', id: sentA.id, el: el() });
+ assert.equal((await a).el.handle, 'k3f9.12');
+
+ const b = stream.request({ action: 'point_neighbour', dir: 'centre' });
+ ws.receive({ type: 'error', id: ws.sent.at(-1).id, error: 'No element there', code: 'nothing' });
+ await assert.rejects(b, (e) => e.code === 'nothing');
+ await settle();
+ assert.equal(stream.error, null, 'the panel banner stays clear');
+
+ const c = stream.request({ action: 'point_at', x: 1, y: 2 }, 30);
+ await assert.rejects(c, (e) => e.code === 'failed', 'no answer in time is failed');
+
+ const d = stream.request({ action: 'point_neighbour', dir: 'centre' });
+ ws.receive({ type: 'error', id: ws.sent.at(-1).id, error: 'Invalid browser input' });
+ await assert.rejects(d, (e) => e.code === 'unsupported');
+ await settle();
+ assert.ok(stream.unsupported.has('point'), 'an older server hides Point');
+
+ const e = stream.request({ action: 'point_pick', handle: 'k', n: 1 });
+ ws.onclose?.();
+ await assert.rejects(e, (x) => x.code === 'failed', 'a close fails what was in flight');
+ m.flushSync(() => root.unmount());
+});
+
+function fakeRequest() {
+ const calls = [];
+ const fn = (payload) => new Promise((resolve, reject) => calls.push({ payload, resolve, reject }));
+ return { fn, calls };
+}
+function fakeSink(picks = 0, filesLeft = 10) {
+ const log = [];
+ return {
+ log,
+ sink: {
+ picks,
+ filesLeft,
+ start: (label, n, o) => { log.push(['start', label, n, o.fromMouse]); return `k${n}`; },
+ done: (key, p) => log.push(['done', key, p.attachment_id]),
+ fail: (key) => log.push(['fail', key]),
+ },
+ };
+}
+const key = (node, k) => node.dispatchEvent(new dom.window.KeyboardEvent('keydown', { key: k, bubbles: true }));
+
+test('layer: keyboard walks from the centre, Enter picks, Esc stops; announced in the live region', async () => {
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const root = m.createRoot(host);
+ const req = fakeRequest();
+ const { sink, log } = fakeSink();
+ let exits = 0;
+ m.flushSync(() => root.render(h(m.PointLayer, { request: req.fn, page: { width: 1280, height: 800 }, frameId: 1, pageUrl: 'https://shop.example.com/checkout', phone: false, sink, onExit: () => exits++ })));
+ await settle();
+ const view = host.querySelector('[role="application"]');
+ assert.equal(view.getAttribute('aria-label'), 'Page view. Arrows choose a part, Enter adds it, Escape stops');
+ assert.equal(document.activeElement, view, 'the view takes focus');
+
+ key(view, 'ArrowUp');
+ assert.deepEqual(req.calls[0].payload, { action: 'point_neighbour', dir: 'centre' }, 'the first arrow starts from the centre');
+ req.calls[0].resolve({ type: 'ack', el: el() });
+ await settle();
+ assert.equal(host.querySelector('[data-point-tag]').textContent, 'button.pay 328 × 36');
+ assert.match(host.querySelector('[data-point-tag]').className, /\bbg-violet-600\b/, 'tag is violet-600 for AA (M1)');
+ assert.match(view.className, /focus-visible:ring-\[3px\] focus-visible:ring-sky-300/, 'view focus ring (S4)');
+ assert.equal(host.querySelector('[data-point-live]').textContent, 'button.pay, 328 by 36, Pay €42.00');
+
+ key(view, 'ArrowUp');
+ assert.deepEqual(req.calls[1].payload, { action: 'point_neighbour', handle: 'k3f9.12', dir: 'parent' });
+ req.calls[1].resolve({ type: 'ack', el: el(), edge: true });
+ await settle();
+ assert.equal(host.querySelector('[data-point-tag]').textContent, 'button.pay 328 × 36', 'an edge keeps the selection');
+
+ key(view, 'Enter');
+ const pickCall = req.calls.at(-1);
+ assert.deepEqual(pickCall.payload, { action: 'point_pick', handle: 'k3f9.12', n: 1 });
+ assert.deepEqual(log[0], ['start', 'button.pay', 1, false]);
+ pickCall.resolve({ type: 'ack', pick: pickWire() });
+ await settle();
+ assert.deepEqual(log[1], ['done', 'k1', UUID]);
+ assert.equal(host.querySelector('[data-point-live]').textContent, 'Added button.pay');
+
+ key(view, 'Escape');
+ assert.equal(exits, 1);
+ m.flushSync(() => root.unmount());
+ host.remove();
+});
+
+test('layer: a 6th pick is refused before asking the server; a failed pick takes its chip back', async () => {
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const root = m.createRoot(host);
+ const req = fakeRequest();
+ const full = fakeSink(5);
+ m.flushSync(() => root.render(h(m.PointLayer, { request: req.fn, page: { width: 1280, height: 800 }, frameId: 1, phone: false, sink: full.sink, onExit() {} })));
+ await settle();
+ const view = host.querySelector('[role="application"]');
+ key(view, 'ArrowDown');
+ req.calls[0].resolve({ type: 'ack', el: el() });
+ await settle();
+ key(view, 'Enter');
+ await settle();
+ assert.equal(req.calls.length, 1, 'no point_pick sent');
+ assert.equal(host.querySelector('[data-point-bar="limit"]').textContent, 'Up to 5 parts per message');
+ assert.doesNotMatch(host.querySelector('[data-point-bar="limit"]').className, /amber/, 'the limit bar is neutral (C2)');
+
+ const one = fakeSink(1);
+ m.flushSync(() => root.render(h(m.PointLayer, { request: req.fn, page: { width: 1280, height: 800 }, frameId: 1, phone: false, sink: one.sink, onExit() {} })));
+ key(view, 'Enter');
+ const pickCall = req.calls.at(-1);
+ assert.equal(pickCall.payload.n, 2);
+ pickCall.reject(Object.assign(new m.PointError('failed')));
+ await settle();
+ assert.deepEqual(one.log.at(-1), ['fail', 'k2']);
+ assert.equal(host.querySelector('[data-point-bar="fail"]').getAttribute('role'), 'alert');
+ assert.equal(host.querySelector('[data-point-bar="fail"]').textContent, "Couldn't read that part of the page. Try again.");
+ m.flushSync(() => root.unmount());
+ host.remove();
+});
+
+test('layer: a hover answer that is no longer the newest is not drawn', async () => {
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const root = m.createRoot(host);
+ const req = fakeRequest();
+ m.flushSync(() => root.render(h(m.PointLayer, { request: req.fn, page: { width: 1280, height: 800 }, frameId: 1, phone: false, sink: fakeSink().sink, onExit() {} })));
+ await settle();
+ const view = host.querySelector('[role="application"]');
+ key(view, 'ArrowUp');
+ key(view, 'ArrowUp');
+ req.calls[1].resolve({ type: 'ack', el: el({ handle: 'new', label: 'form#checkout' }) });
+ await settle();
+ req.calls[0].resolve({ type: 'ack', el: el({ handle: 'old', label: 'div.old' }) });
+ await settle();
+ assert.match(host.querySelector('[data-point-tag]').textContent, /^form#checkout/);
+ m.flushSync(() => root.unmount());
+ host.remove();
+});
+
+test('sheet line 2 and the short pick name (S2, S3)', () => {
+ assert.equal(m.sheetLine('Pay €42.00'), '"Pay €42.00" · tap another part to change it');
+ assert.equal(m.sheetLine(''), 'Tap another part to change it');
+ assert.equal(m.sheetLine(null), 'Tap another part to change it');
+ assert.equal(m.pickName({ label: 'button.pay', selector: 'main > button.pay' }), 'button.pay');
+ assert.equal(m.pickTitle({ label: 'button.pay', selector: 'main > button.pay' }), 'main > button.pay');
+ assert.equal(m.pickName({ label: '', selector: 'main > button.pay' }), 'main > button.pay');
+});
+
+test('chip and row: capturing, ready, no picture, embedded page; remove names the part; crop opens the viewer', async () => {
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const root = m.createRoot(host);
+ const chip = (item) => {
+ m.flushSync(() => root.render(h('ul', null, h(m.PointChip, { item, onRemove() {} }))));
+ return host.querySelector('[data-point-chip]');
+ };
+ const base = { key: 'a', name: 'pointed-1.png', size: 0, progress: 0, state: 'uploading', point: { label: 'button.pay' } };
+ let c = chip(base);
+ assert.equal(c.dataset.pointChip, 'capturing');
+ assert.match(c.textContent, /Taking a picture…/);
+ c = chip({ ...base, state: 'done', point: { label: 'button.pay', pick: m.parsePointPick(pickWire()) } });
+ assert.equal(c.dataset.pointChip, 'ready');
+ assert.match(c.textContent, /shop\.example\.com\/checkout/);
+ assert.equal(c.querySelector('button').getAttribute('aria-label'), 'Remove button.pay');
+ assert.equal(c.querySelector('.font-mono').textContent, 'button.pay', 'line 1 shows the short label (S2)');
+ assert.equal(c.querySelector('.font-mono').getAttribute('title'), 'main > form#checkout > button.pay', 'the full selector is the title');
+ assert.equal(c.querySelector('img').getAttribute('src'), `/api/attachments/${UUID}/content`, "the chip uses its own pick's thumbnail (C5)");
+ c = chip({ ...base, state: 'done', point: { label: 'x', pick: m.parsePointPick(pickWire({ picture: false, thumb_url: null })) } });
+ assert.equal(c.dataset.pointChip, 'no-picture');
+ c = chip({ ...base, state: 'done', point: { label: 'x', pick: m.parsePointPick(pickWire({ frame: { host: 'pay.example.net', cross_site: true } })) } });
+ assert.equal(c.dataset.pointChip, 'frame');
+ assert.match(c.textContent, /Embedded page from pay\.example\.net/);
+
+ const ref = { id: UUID, name: 'pointed-1.png', mime: 'image/png', size: 10, point: m.pointMetaOf(m.parsePointPick(pickWire()), 1, 1) };
+ m.flushSync(() => root.render(h(m.PointRow, { file: ref })));
+ const open = host.querySelector('[data-point-row] button');
+ assert.equal(open.getAttribute('aria-label'), 'Open the picture of button.pay');
+ const rowName = host.querySelector('[data-point-row] .font-mono');
+ assert.equal(rowName.textContent, 'button.pay');
+ assert.equal(rowName.getAttribute('title'), 'main > form#checkout > button.pay');
+ m.flushSync(() => open.click());
+ await settle();
+ assert.ok(document.querySelector('[role="dialog"]'), 'the image viewer opened');
+ m.flushSync(() => root.unmount());
+ host.remove();
+});