Skip to content

An agentic browser harness: an AI side panel & orb in your own logged-in Chrome, Edge, Arc, Brave or even Firefox run by the agent/subscription you already use (Claude Code, Codex, Antigravity). Free, open source, no API key. Also an MCP server.

feat(hands-free): lay out the mic orb — an arc menu that opens away from whichever edge it is dragged against and turns its order with it, captions and prompts on the side with room, and replies read as plain words

Shahriarf4f488f5c2b4
diff --git a/src/lib/handsfree/caption.test.ts b/src/lib/handsfree/caption.test.ts
new file mode 100644
index 0000000..3c84c4c
--- /dev/null
+++ b/src/lib/handsfree/caption.test.ts
@@ -0,0 +1,58 @@
+import { describe, expect, it } from 'vitest';
+import { captionOf, readingMs, replyOf, sharedWords, wordsOf } from './caption';
+
+describe('sharedWords', () => {
+ it('keeps the words a revised reading did not change', () => {
+ expect(sharedWords(wordsOf('open the first'), wordsOf('open the first result'))).toBe(3);
+ expect(sharedWords(wordsOf('open the fist'), wordsOf('open the first result'))).toBe(2);
+ expect(sharedWords([], wordsOf('hello'))).toBe(0);
+ });
+});
+
+describe('captionOf', () => {
+ it('reads markdown as plain text', () => {
+ expect(captionOf('## Done\n\n- **Saved** the [draft](https://x.test) as `v2`')).toBe('Done Saved the draft as v2');
+ });
+
+ it('drops code blocks entirely', () => {
+ expect(captionOf('Ran it:\n```js\nconsole.log(1)\n```\nAll good.')).toBe('Ran it: All good.');
+ });
+
+ it('cuts a long reply at a word, with an ellipsis', () => {
+ const caption = captionOf('word '.repeat(100), 40);
+ expect(caption.endsWith('word…')).toBe(true);
+ expect(caption.length).toBeLessThanOrEqual(41);
+ });
+});
+
+describe('replyOf', () => {
+ const user = (text: string) => ({ kind: 'user' as const, id: text, text });
+ const said = (text: string) => ({ kind: 'assistant' as const, id: text, text });
+ const failed = (text: string) => ({ kind: 'notice' as const, id: text, tone: 'error' as const, text });
+ const tool = { kind: 'tool' as const, id: 't', action: 'page.clickElement', input: {}, ok: true };
+
+ it('reads the latest reply of the turn', () => {
+ expect(replyOf([user('go'), said('Opening it'), tool, said('**Done** — signed in.')])).toEqual({
+ text: 'Done — signed in.',
+ tone: 'reply',
+ });
+ });
+
+ it('reads an error without its code', () => {
+ expect(replyOf([user('go'), said('Trying'), failed('CANCELLED: The tab was closed, so that run is over.')])).toEqual({
+ text: 'The tab was closed, so that run is over.',
+ tone: 'error',
+ });
+ });
+
+ it('never reaches back into an earlier turn', () => {
+ expect(replyOf([user('one'), said('First answer'), user('two'), tool])).toBeNull();
+ });
+});
+
+describe('readingMs', () => {
+ it('stays between a glance and a paragraph', () => {
+ expect(readingMs('ok')).toBe(4_000);
+ expect(readingMs('word '.repeat(200))).toBe(16_000);
+ });
+});
diff --git a/src/lib/handsfree/caption.ts b/src/lib/handsfree/caption.ts
new file mode 100644
index 0000000..d1aeb1e
--- /dev/null
+++ b/src/lib/handsfree/caption.ts
@@ -0,0 +1,45 @@
+import type { RunItem } from '@/lib/bridge/run-items';
+import type { CaptionTone } from './events';
+
+const MAX_SPOKEN_CHARS = 280;
+
+/** The last word of a finished turn — its latest reply or error — or nothing, if the turn said neither. */
+export function replyOf(items: readonly RunItem[]): { text: string; tone: CaptionTone } | null {
+ for (let index = items.length - 1; index >= 0; index--) {
+ const item = items[index];
+ if (item.kind === 'user') return null;
+ if (item.kind === 'assistant' && item.text.trim()) return { text: captionOf(item.text), tone: 'reply' };
+ if (item.kind === 'notice' && item.tone === 'error') {
+ return { text: captionOf(item.text.replace(/^[A-Z][A-Z_]+:\s*/, '')), tone: 'error' };
+ }
+ }
+ return null;
+}
+
+export const wordsOf = (text: string): string[] => text.split(/\s+/).filter(Boolean);
+
+/** How many leading words two readings share — those keep their place, and only the rest stream in. */
+export function sharedWords(before: readonly string[], after: readonly string[]): number {
+ let shared = 0;
+ while (shared < before.length && shared < after.length && before[shared] === after[shared]) shared += 1;
+ return shared;
+}
+
+/** A reply as a caption can carry it: markdown stripped, one paragraph, cut at a word. */
+export function captionOf(markdown: string, max = MAX_SPOKEN_CHARS): string {
+ const plain = markdown
+ .replace(/```[\s\S]*?```/g, ' ')
+ .replace(/`([^`]*)`/g, '$1')
+ .replace(/!?\[([^\]]*)\]\([^)]*\)/g, '$1')
+ .replace(/^\s{0,3}(#{1,6}|>|[-*+]|\d+[.)])\s+/gm, '')
+ .replace(/(\*\*|__|\*|_|~~)(\S(?:.*?\S)?)\1/g, '$2')
+ .replace(/\s+/g, ' ')
+ .trim();
+ if (plain.length <= max) return plain;
+ const cut = plain.slice(0, max);
+ const lastSpace = cut.lastIndexOf(' ');
+ return `${(lastSpace > max * 0.6 ? cut.slice(0, lastSpace) : cut).replace(/[\s,;:.–—-]+$/, '')}…`;
+}
+
+/** Long enough to read at an unhurried pace, never so long it lingers after the page moved on. */
+export const readingMs = (text: string): number => Math.min(16_000, Math.max(4_000, 2_500 + wordsOf(text).length * 300));
diff --git a/src/lib/handsfree/events.ts b/src/lib/handsfree/events.ts
new file mode 100644
index 0000000..ccc1f74
--- /dev/null
+++ b/src/lib/handsfree/events.ts
@@ -0,0 +1,176 @@
+import type { FocusedElement } from '@/lib/actions/protocol';
+import type { ThemeId } from '@/lib/bridge/theme';
+
+export const HANDS_FREE_CHANNEL = 'browsentic/handsFree';
+export const DICTATION_CHANNEL = 'browsentic/dictation';
+
+export const AUTO_SEND_MS = 1600;
+
+/** What the offscreen recognizer reports about itself. `held`: in hold-to-talk, ready and waiting for the key. */
+export type DictationPhase =
+ | 'starting'
+ | 'listening'
+ | 'held'
+ | 'needs-mic'
+ | 'blocked'
+ | 'no-mic'
+ | 'no-service'
+ | 'yielded';
+
+/**
+ * Hold-to-talk's key: left Control, matched by where it sits rather than what it types, so every
+ * layout agrees on it. Alone it does nothing on any platform or browser, and it sits at the far
+ * left on both Mac and PC keyboards.
+ */
+export const HOLD_KEY_CODE = 'ControlLeft';
+
+/**
+ * What the orb in one tab should say about the microphone. `paused` is every reason the
+ * background is not listening for this tab that the user did not choose — another tab in
+ * front, the agent working, the browser in the background.
+ */
+export type OrbVoice = DictationPhase | 'muted' | 'paused';
+
+export type OrbLink = 'live' | 'pending' | 'off';
+
+export type OrbRun = 'idle' | 'working' | 'approval';
+
+/** The orb's centre, as fractions of the viewport, so one position fits every tab. */
+export interface OrbPosition {
+ x: number;
+ y: number;
+}
+
+export interface OrbApproval {
+ toolId: string;
+ action: string;
+ site?: string;
+ /** For code the agent wrote: what it says the code is for, and the code itself. */
+ purpose?: string;
+ code?: string;
+ /** For any other action: its input, flattened to one short line. */
+ detail?: string;
+}
+
+export interface OrbView {
+ theme: ThemeId;
+ since: number;
+ position: OrbPosition | null;
+ link: OrbLink;
+ run: OrbRun;
+ voice: OrbVoice;
+ /** The mic stays off until the hold key is held, and letting go sends. */
+ pushToTalk: boolean;
+ approval?: OrbApproval;
+}
+
+export type CaptionTone = 'reply' | 'error' | 'ask';
+
+export type OrbCommand =
+ | { channel: typeof HANDS_FREE_CHANNEL; op: 'show'; view: OrbView }
+ | { channel: typeof HANDS_FREE_CHANNEL; op: 'hide' }
+ | { channel: typeof HANDS_FREE_CHANNEL; op: 'heard'; text: string; final: boolean }
+ | { channel: typeof HANDS_FREE_CHANNEL; op: 'say'; text: string; tone: CaptionTone };
+
+export interface OrbFile {
+ name: string;
+ mime: string;
+ size: number;
+ /** Base64, absent when the file is over the stored-file cap and travels by name and size only. */
+ content?: string;
+}
+
+export type OrbRequest =
+ | { channel: typeof HANDS_FREE_CHANNEL; op: 'sync' }
+ | { channel: typeof HANDS_FREE_CHANNEL; op: 'submit'; text: string; focus?: FocusedElement; liveTools: boolean }
+ | { channel: typeof HANDS_FREE_CHANNEL; op: 'cancel' }
+ | { channel: typeof HANDS_FREE_CHANNEL; op: 'decide'; toolId: string; allow: boolean; remember?: boolean }
+ | { channel: typeof HANDS_FREE_CHANNEL; op: 'openPanel' }
+ | { channel: typeof HANDS_FREE_CHANNEL; op: 'listen'; on: boolean }
+ | { channel: typeof HANDS_FREE_CHANNEL; op: 'grantMic' }
+ | { channel: typeof HANDS_FREE_CHANNEL; op: 'pick' }
+ | { channel: typeof HANDS_FREE_CHANNEL; op: 'attach'; file: OrbFile }
+ | { channel: typeof HANDS_FREE_CHANNEL; op: 'detach'; fileId: string }
+ | { channel: typeof HANDS_FREE_CHANNEL; op: 'move'; position: OrbPosition }
+ | { channel: typeof HANDS_FREE_CHANNEL; op: 'pushToTalk'; on: boolean }
+ | { channel: typeof HANDS_FREE_CHANNEL; op: 'talk'; on: boolean };
+
+export type DictationReport =
+ | { channel: typeof DICTATION_CHANNEL; op: 'phase'; phase: DictationPhase }
+ | { channel: typeof DICTATION_CHANNEL; op: 'heard'; text: string; final: boolean };
+
+/** Sent to a hold-to-talk dictation page: start hearing, or finish what was said and stop. */
+export type DictationCommand = { channel: typeof DICTATION_CHANNEL; op: 'talk'; on: boolean };
+
+const ORB_COMMANDS = new Set(['show', 'hide', 'heard', 'say']);
+const ORB_REQUESTS = new Set([
+ 'sync', 'submit', 'cancel', 'decide', 'openPanel', 'listen', 'grantMic', 'pick', 'attach', 'detach', 'move',
+ 'pushToTalk', 'talk',
+]);
+
+function onChannel(message: unknown, channel: string, ops: Set<string>): boolean {
+ if (typeof message !== 'object' || message === null) return false;
+ const frame = message as { channel?: unknown; op?: unknown };
+ return frame.channel === channel && typeof frame.op === 'string' && ops.has(frame.op);
+}
+
+export const isOrbCommand = (message: unknown): message is OrbCommand =>
+ onChannel(message, HANDS_FREE_CHANNEL, ORB_COMMANDS);
+
+export const isOrbRequest = (message: unknown): message is OrbRequest =>
+ onChannel(message, HANDS_FREE_CHANNEL, ORB_REQUESTS);
+
+export const isDictationReport = (message: unknown): message is DictationReport =>
+ onChannel(message, DICTATION_CHANNEL, new Set(['phase', 'heard']));
+
+export const isDictationCommand = (message: unknown): message is DictationCommand =>
+ onChannel(message, DICTATION_CHANNEL, new Set(['talk']));
+
+/** Lucide paths, copied for the same reason as the rail's: the content script carries no icon package. */
+export const ORB_ICONS = {
+ mic: ['M12 19v3', 'M19 10v2a7 7 0 0 1-14 0v-2', 'M9 5a3 3 0 0 1 6 0v7a3 3 0 0 1-6 0z'],
+ micOff: [
+ 'M12 19v3',
+ 'M15 9.34V5a3 3 0 0 0-5.68-1.33',
+ 'M16.95 16.95A7 7 0 0 1 5 12v-2',
+ 'M18.89 13.23A7 7 0 0 0 19 12v-2',
+ 'm2 2 20 20',
+ 'M9 9v3a3 3 0 0 0 5.12 2.12',
+ ],
+ stop: ['M5 3h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z'],
+ shield: [
+ 'M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z',
+ 'M12 8v4',
+ 'M12 16h.01',
+ ],
+ file: [
+ 'M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z',
+ 'M14 2v5a1 1 0 0 0 1 1h5',
+ 'M12 12v6',
+ 'm15 15-3-3-3 3',
+ ],
+ code: ['m18 16 4-4-4-4', 'm6 8-4 4 4 4', 'm14.5 4-5 16'],
+ focus: [
+ 'M3 7V5a2 2 0 0 1 2-2h2',
+ 'M17 3h2a2 2 0 0 1 2 2v2',
+ 'M21 17v2a2 2 0 0 1-2 2h-2',
+ 'M7 21H5a2 2 0 0 1-2-2v-2',
+ 'M11 12a1 1 0 1 0 2 0a1 1 0 1 0-2 0',
+ 'M18.944 12.33a1 1 0 0 0 0-.66 7.5 7.5 0 0 0-13.888 0 1 1 0 0 0 0 .66 7.5 7.5 0 0 0 13.888 0',
+ ],
+ panel: ['M5 3h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z', 'M15 3v18', 'm10 15-3-3 3-3'],
+ close: ['M18 6 6 18', 'm6 6 12 12'],
+ keyboard: [
+ 'M4 4h16a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2z',
+ 'M10 8h.01',
+ 'M12 12h.01',
+ 'M14 8h.01',
+ 'M16 12h.01',
+ 'M18 8h.01',
+ 'M6 8h.01',
+ 'M7 16h10',
+ 'M8 12h.01',
+ ],
+} as const;
+
+export type OrbIcon = keyof typeof ORB_ICONS;
diff --git a/src/lib/handsfree/geometry.test.ts b/src/lib/handsfree/geometry.test.ts
new file mode 100644
index 0000000..037d091
--- /dev/null
+++ b/src/lib/handsfree/geometry.test.ts
@@ -0,0 +1,113 @@
+import { describe, expect, it } from 'vitest';
+import {
+ MENU_ITEM,
+ ORB_INSET,
+ ORB_SIZE,
+ arcSlots,
+ outwardFrom,
+ placeBeside,
+ placeOrb,
+ sidesFacing,
+ toPosition,
+} from './geometry';
+
+const viewport = { width: 1440, height: 900 };
+const ITEMS = 5;
+const half = ORB_SIZE / 2 + ORB_INSET;
+
+describe('placeOrb', () => {
+ it('starts at the bottom middle', () => {
+ expect(placeOrb(null, viewport)).toEqual({ x: 720, y: 900 - half });
+ });
+
+ it('keeps a stored position whole on a smaller window', () => {
+ expect(placeOrb({ x: 0.99, y: 0.01 }, { width: 400, height: 300 })).toEqual({ x: 400 - half, y: half });
+ });
+
+ it('round-trips through a stored position to within a pixel', () => {
+ const back = placeOrb(toPosition({ x: 300, y: 450 }, viewport), viewport);
+ expect(back.x).toBeCloseTo(300, 0);
+ expect(back.y).toBeCloseTo(450, 0);
+ });
+});
+
+describe('arcSlots', () => {
+ it('fans upward from the bottom edge, dealt left to right', () => {
+ const slots = arcSlots(ITEMS, outwardFrom(placeOrb(null, viewport), viewport));
+ expect(slots.every((slot) => slot.y < 0)).toBe(true);
+ expect(slots.map((slot) => slot.x)).toEqual([...slots.map((slot) => slot.x)].sort((a, b) => a - b));
+ });
+
+ it('turns the arc and its order with the edge the orb is dragged to', () => {
+ const top = arcSlots(ITEMS, outwardFrom({ x: 720, y: half }, viewport));
+ expect(top.every((slot) => slot.y > 0)).toBe(true);
+ expect(top[0].x).toBeGreaterThan(top[ITEMS - 1].x);
+
+ const left = arcSlots(ITEMS, outwardFrom({ x: half, y: 450 }, viewport));
+ expect(left.every((slot) => slot.x > 0)).toBe(true);
+ expect(left[0].y).toBeLessThan(left[ITEMS - 1].y);
+
+ const right = arcSlots(ITEMS, outwardFrom({ x: 1440 - half, y: 450 }, viewport));
+ expect(right.every((slot) => slot.x < 0)).toBe(true);
+ expect(right[0].y).toBeGreaterThan(right[ITEMS - 1].y);
+ });
+
+ it('closes to a tighter arc in every corner and keeps every item on screen', () => {
+ for (const corner of [
+ { x: 1440 - half, y: 900 - half },
+ { x: half, y: half },
+ { x: half, y: 900 - half },
+ { x: 1440 - half, y: half },
+ ]) {
+ const outward = outwardFrom(corner, viewport);
+ expect(outward.cornered).toBe(true);
+ for (const slot of arcSlots(ITEMS, outward)) {
+ expect(corner.x + slot.x - MENU_ITEM / 2).toBeGreaterThanOrEqual(0);
+ expect(corner.y + slot.y - MENU_ITEM / 2).toBeGreaterThanOrEqual(0);
+ expect(corner.x + slot.x + MENU_ITEM / 2).toBeLessThanOrEqual(1440);
+ expect(corner.y + slot.y + MENU_ITEM / 2).toBeLessThanOrEqual(900);
+ }
+ }
+ expect(outwardFrom({ x: 1440 - half, y: 900 - half }, viewport).angle).toBe(-135);
+ });
+
+ it('keeps neighbouring items from overlapping', () => {
+ for (const center of [placeOrb(null, viewport), { x: half, y: half }]) {
+ const slots = arcSlots(ITEMS, outwardFrom(center, viewport));
+ for (let i = 1; i < slots.length; i++) {
+ expect(Math.hypot(slots[i].x - slots[i - 1].x, slots[i].y - slots[i - 1].y)).toBeGreaterThan(MENU_ITEM);
+ }
+ }
+ });
+
+ it('opens toward the middle of the page when clear of every edge', () => {
+ expect(outwardFrom({ x: 720, y: 600 }, viewport).angle).toBe(-90);
+ expect(outwardFrom({ x: 720, y: 300 }, viewport).angle).toBe(90);
+ });
+});
+
+describe('placeBeside', () => {
+ const box = { width: 300, height: 160 };
+
+ it('puts a caption above an orb on the bottom edge, centred over it', () => {
+ const orb = placeOrb(null, viewport);
+ const placed = placeBeside(box, orb, 14, viewport, sidesFacing(outwardFrom(orb, viewport)));
+ expect(placed.side).toBe('top');
+ expect(placed.left + box.width / 2).toBe(orb.x);
+ expect(placed.arrow).toBe(box.width / 2);
+ });
+
+ it('slides along the side instead of leaving the screen, and moves the arrow with it', () => {
+ const orb = { x: 1440 - half, y: 900 - half };
+ const placed = placeBeside(box, orb, 14, viewport, sidesFacing(outwardFrom(orb, viewport)));
+ expect(placed.side).toBe('top');
+ expect(placed.left + box.width).toBeLessThanOrEqual(1440 - 12);
+ expect(placed.arrow).toBeGreaterThan(box.width / 2);
+ });
+
+ it('falls to the next side when the preferred one has no room', () => {
+ const orb = { x: half, y: 120 };
+ const placed = placeBeside(box, orb, 14, viewport, ['top', 'right', 'bottom']);
+ expect(placed.side).toBe('right');
+ });
+});
diff --git a/src/lib/handsfree/geometry.ts b/src/lib/handsfree/geometry.ts
new file mode 100644
index 0000000..feb3b95
--- /dev/null
+++ b/src/lib/handsfree/geometry.ts
@@ -0,0 +1,125 @@
+import type { OrbPosition } from './events';
+
+export interface Point {
+ x: number;
+ y: number;
+}
+
+export interface Size {
+ width: number;
+ height: number;
+}
+
+export type Side = 'top' | 'bottom' | 'left' | 'right';
+
+export const ORB_SIZE = 56;
+export const ORB_INSET = 24;
+export const MENU_ITEM = 38;
+export const MENU_RADIUS = 80;
+/* A corner leaves a quarter turn, plus the slack of the orb's inset on either side: 110° at
+ 96 px keeps five items apart and every one of them on screen. */
+const CORNER_RADIUS = 96;
+const EDGE_SPAN = 150;
+const CORNER_SPAN = 110;
+const VIEW_MARGIN = 12;
+
+const clamp = (value: number, low: number, high: number) =>
+ high < low ? (low + high) / 2 : Math.min(high, Math.max(low, value));
+
+const round = (value: number) => Math.round(value * 10_000) / 10_000;
+
+/** The orb's centre for a stored position, pulled back on screen; no position means bottom-middle. */
+export function placeOrb(position: OrbPosition | null, viewport: Size): Point {
+ const half = ORB_SIZE / 2 + ORB_INSET;
+ const x = position ? position.x * viewport.width : viewport.width / 2;
+ const y = position ? position.y * viewport.height : viewport.height - half;
+ return { x: clamp(x, half, viewport.width - half), y: clamp(y, half, viewport.height - half) };
+}
+
+export function toPosition(center: Point, viewport: Size): OrbPosition {
+ return { x: round(center.x / viewport.width), y: round(center.y / viewport.height) };
+}
+
+export interface Outward {
+ /** Degrees on screen: 0 points right, 90 down, -90 up. */
+ angle: number;
+ cornered: boolean;
+}
+
+/**
+ * The way out from whichever edges the orb is up against. An orb clear of every edge opens
+ * toward the middle of the page — up from the lower half, down from the upper.
+ */
+export function outwardFrom(center: Point, viewport: Size): Outward {
+ const room = CORNER_RADIUS + MENU_ITEM / 2 + VIEW_MARGIN;
+ const dx = center.x < room ? 1 : viewport.width - center.x < room ? -1 : 0;
+ const near = center.y < room ? 1 : viewport.height - center.y < room ? -1 : 0;
+ const dy = dx === 0 && near === 0 ? (center.y > viewport.height / 2 ? -1 : 1) : near;
+ return { angle: (Math.atan2(dy, dx) * 180) / Math.PI, cornered: dx !== 0 && dy !== 0 };
+}
+
+export interface Slot extends Point {
+ angle: number;
+}
+
+/**
+ * Where each menu item sits around the orb, in order. The arc is centred on the way out and
+ * always swept clockwise, so against the bottom edge it runs left to right, and dragging the
+ * orb to another edge turns the whole arc — and the order it deals its items out — with it.
+ */
+export function arcSlots(count: number, outward: Outward): Slot[] {
+ const span = outward.cornered ? CORNER_SPAN : EDGE_SPAN;
+ const radius = menuRadius(outward);
+ return Array.from({ length: count }, (_, index) => {
+ const angle = outward.angle - span / 2 + (count === 1 ? span / 2 : (span * index) / (count - 1));
+ const radians = (angle * Math.PI) / 180;
+ return { angle: round(angle), x: round(Math.cos(radians) * radius), y: round(Math.sin(radians) * radius) };
+ });
+}
+
+export const menuRadius = (outward: Outward): number => (outward.cornered ? CORNER_RADIUS : MENU_RADIUS);
+
+/** How far from the orb's edge something must sit to clear the open menu. */
+export const clearOfMenu = (outward: Outward) => menuRadius(outward) + MENU_ITEM / 2 + 6 - ORB_SIZE / 2;
+
+const SIDE_ANGLES: Record<Side, number> = { top: -90, bottom: 90, left: 180, right: 0 };
+
+/** Sides of the orb, best first: the one facing the way out, then its neighbours, never back into the edge. */
+export function sidesFacing(outward: Outward): Side[] {
+ const score = (side: Side) => Math.round(Math.cos(((outward.angle - SIDE_ANGLES[side]) * Math.PI) / 180) * 1e6);
+ return (['top', 'bottom', 'left', 'right'] as const)
+ .map((side, order) => ({ side, order, score: score(side) }))
+ .sort((a, b) => b.score - a.score || a.order - b.order)
+ .map(({ side }) => side);
+}
+
+export interface Placement {
+ side: Side;
+ left: number;
+ top: number;
+ /** Along the box's edge nearest the orb, how far in the orb's centre falls — where an arrow points from. */
+ arrow: number;
+}
+
+/** Puts a box beside the orb on the first side it fits, sliding it along that side to stay on screen. */
+export function placeBeside(box: Size, orb: Point, gap: number, viewport: Size, sides: Side[]): Placement {
+ const reach = ORB_SIZE / 2 + gap;
+ const across = (side: Side): Placement => {
+ if (side === 'top' || side === 'bottom') {
+ const left = clamp(orb.x - box.width / 2, VIEW_MARGIN, viewport.width - VIEW_MARGIN - box.width);
+ const top = side === 'top' ? orb.y - reach - box.height : orb.y + reach;
+ return { side, left, top, arrow: orb.x - left };
+ }
+ const top = clamp(orb.y - box.height / 2, VIEW_MARGIN, viewport.height - VIEW_MARGIN - box.height);
+ const left = side === 'left' ? orb.x - reach - box.width : orb.x + reach;
+ return { side, left, top, arrow: orb.y - top };
+ };
+ const fits = ({ left, top }: Placement) =>
+ left >= VIEW_MARGIN &&
+ top >= VIEW_MARGIN &&
+ left + box.width <= viewport.width - VIEW_MARGIN &&
+ top + box.height <= viewport.height - VIEW_MARGIN;
+
+ const options = sides.map(across);
+ return options.find(fits) ?? options[0];
+}