reifyui 0.13.8 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +39 -0
- package/dist/agent-chat.cjs +2046 -0
- package/dist/agent-chat.cjs.map +1 -0
- package/dist/agent-chat.d.ts +190 -0
- package/dist/agent-chat.js +1952 -0
- package/dist/agent-chat.js.map +1 -0
- package/dist/chunk-AGSX5YKH.js +177 -0
- package/dist/chunk-AGSX5YKH.js.map +1 -0
- package/dist/chunk-WAND7AYD.js +124 -0
- package/dist/chunk-WAND7AYD.js.map +1 -0
- package/dist/graph.js +2 -1
- package/dist/graph.js.map +1 -1
- package/dist/index.cjs +29 -8
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +34 -11
- package/dist/index.js.map +1 -1
- package/package.json +11 -2
- package/src/agent-chat/components.jsx +777 -0
- package/src/agent-chat/index.d.ts +190 -0
- package/src/agent-chat/index.js +24 -0
- package/src/agent-chat/marks.js +51 -0
- package/src/agent-chat/time.js +55 -0
- package/src/agent-chat/tools.js +357 -0
- package/src/agent-chat/turn.js +476 -0
- package/src/auth/GoogleButton.jsx +24 -4
- package/styles/agent-chat.css +306 -0
- package/dist/chunk-J7SECRIG.js +0 -295
- package/dist/chunk-J7SECRIG.js.map +0 -1
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.js","../src/stream/responses.js","../src/state/blocks.js","../src/state/conversationStore.js","../src/state/turns.js","../src/components/icons.jsx","../src/components/toolMeta.js","../src/components/ToolSteps.jsx","../src/components/ChatMessages.jsx","../src/components/Composer.jsx","../src/components/ChatPanel.jsx","../src/components/Chip.jsx","../src/format.js","../src/input/dictate.js","../src/components/CodeBlock.jsx","../src/components/resizable.jsx","../src/components/TaskList.jsx","../src/components/Dialog.jsx","../src/components/overlay.js","../src/auth/client.js","../src/auth/AuthForm.jsx","../src/auth/GoogleButton.jsx","../src/auth/MicrosoftButton.jsx","../src/sheet/SheetGrid.jsx","../src/mention/MentionInput.jsx","../src/components/Popover.jsx","../src/mention/mentionModel.js","../src/collab/colors.js","../src/components/FileTypeIcon.jsx","../src/components/FileCard.jsx","../src/components/FilePreview.jsx","../src/components/form.jsx","../src/components/Carousel.jsx","../src/components/Card.jsx","../src/components/SearchField.jsx","../src/components/CascadeMenu.jsx","../src/components/Modal.jsx","../src/hooks/useTypewriter.js","../src/components/Panel.jsx","../src/grid/PanelGrid.jsx","../src/grid/layout.js","../src/timeline/Timeline.jsx"],"sourcesContent":["// UI Core — shared Conversational Agent surface (extracted from HarnessRouter).\n// Plain ESM React source: consumers alias this package (Vite resolve.alias / Next webpack alias\n// + tsconfig paths) and import straight from source. No build step. Only peer dep: react.\nexport { createResponsesDispatcher, readSSEStream, pumpResponsesStream } from './stream/responses.js';\nexport { withText, withReasoning, withStep, withResult, asstText } from './state/blocks.js';\nexport { createConversationStore } from './state/conversationStore.js';\n// Gateway turns -> the message shape ChatMessages/ChatPanel render. Also on reifyui/harness; it is\n// here too because ChatPanel's loadHistory takes messages, and converting history must not require\n// importing a transport. Pure function, no fetch.\nexport { turnsToMessages } from './state/turns.js';\nexport { Svg, Chevron, IcDownload, IcEye, IcTool, IcPlug, IcSkill, IcTerminal, IcDoc, IcList, IcGlobe, IcSearch, IcScroll, IcSpawn, IcCheck, IcThink, IcSend, IcX, IcMic, IcPaperclip, IcPanelRight } from './components/icons.jsx';\nexport { humanize, parseArgs, baseName, prettyJson, toolMeta, summarizeSteps } from './components/toolMeta.js';\nexport { ToolGroup, ToolRow } from './components/ToolSteps.jsx';\nexport { ChatMessages, ChatMessagesSkeleton, UserTurn, AssistantTurn, DEFAULT_STATUS_LABELS } from './components/ChatMessages.jsx';\nexport { Composer } from './components/Composer.jsx';\n// The whole conversation column beside a document — history, live turn, retry, attachments,\n// dictation, composer. Four products had a divergent copy of this; the transport and the product's\n// prose stay at the call site, everything else is here. Needs styles/chat.css.\nexport { ChatPanel } from './components/ChatPanel.jsx';\n// Voice input through the browser's own recogniser. Returns null where the API is absent, which\n// is what makes \"render no microphone\" the easy path and a disabled one impossible to reach for.\nexport { createDictation } from './input/dictate.js';\nexport { bytesLabel } from './format.js';\n// CodeBlock lazy-imports highlight.js — the consuming app must depend on highlight.js (^11),\n// same rule as mermaid for the Mermaid blocks. See components/CodeBlock.jsx.\nexport { CodeBlock } from './components/CodeBlock.jsx';\nexport { useResizablePane, PaneResizer } from './components/resizable.jsx';\n// Master list beside a conversation (runs/sessions): filter, status, cursor pagination.\n// Transport-agnostic — the consumer supplies fetchPage(cursor) -> {items, cursor}.\nexport { TaskList, taskStatusGroup } from './components/TaskList.jsx';\n// In-app alert/confirm/prompt. Native browser popups block the event loop and can't be styled,\n// which reads as a browser warning rather than as part of the product — these replace them with\n// the same awaited call-site shape. Needs styles/dialog.css and a <DialogHost> at the root.\nexport { DialogHost, useDialog } from './components/Dialog.jsx';\n// Shared product auth (extracted from ContextualGraph): the engine /v1/auth\n// client (configureAuth({product, engine}) once at boot) + the sign-in form\n// and Google SSO button. Consumers may also deep-import './auth/*'.\nexport {\n configureAuth, authConfig, SESSION_EVENT,\n getSession, clearSession, getToken, isAuthed,\n login, register, googleSignIn, microsoftSignIn, requestPasswordReset, switchOrg,\n refreshToken, handleAuthExpired, logout, authFetch, fetchBalance,\n} from './auth/client.js';\nexport { AuthForm } from './auth/AuthForm.jsx';\nexport { GoogleButton, GOOGLE_ENABLED } from './auth/GoogleButton.jsx';\nexport { MicrosoftButton, MICROSOFT_ENABLED, microsoftIdToken } from './auth/MicrosoftButton.jsx';\n// Shared AI-spreadsheet grid (reusable in the Sheets product AND studio Spaces).\nexport { SheetGrid, sheetToDelimited, sheetToAoA } from './sheet/SheetGrid.jsx';\n// Files, drawn the same wherever they appear. FileTypeIcon uses react-file-icon when it is\n// installed (an optional peer) and falls back to an extension badge when it is not.\nexport { FileTypeIcon, extOf } from './components/FileTypeIcon.jsx';\nexport { FileCard } from './components/FileCard.jsx';\nexport { FilePreview } from './components/FilePreview.jsx';\n// Form primitives. Every surface here had been hand-rolling label+select+textarea, which is why\n// the same form looked different in each of them.\nexport { Field, Input, Textarea, Select, FormActions, Button } from './components/form.jsx';\n// ── the library page: the surface a document product opens on ────────────────\n// Small, product-agnostic pieces that existed 3-6 times each across the products built on this\n// package, every copy slightly different. Needs styles/library.css (+ chip.css, preview.css).\nexport { Carousel } from './components/Carousel.jsx';\nexport { Card } from './components/Card.jsx';\nexport { Chip } from './components/Chip.jsx';\nexport { SearchField } from './components/SearchField.jsx';\n// Anchored panel with placement built in — flips, clamps to the viewport, closes on Escape and\n// outside press. Ten hand-rolled versions of this existed; one survived a phone.\nexport { Popover } from './components/Popover.jsx';\n// Two-level pick in one panel (items, then the highlighted item's options), on Popover.\nexport { CascadeMenu } from './components/CascadeMenu.jsx';\n// A dialog whose body is yours (useDialog answers a question; this holds content). Shares the\n// dialog host's Escape ordering and overlay layer. Needs styles/preview.css.\nexport { Modal } from './components/Modal.jsx';\nexport { useTypewriter } from './hooks/useTypewriter.js';\n// ── boards: a grid of panels ─────────────────────────────────────────────────\n// The frame around one thing on a board (and, crucially, the two states that thing spends most\n// of its life in: loading, and failed-with-a-message), plus the grid that arranges them.\n// Read-only is the default; nothing here depends on a charting library — the chart that usually\n// goes INSIDE a panel is at reifyui/chart, so a board of tables costs nothing extra.\n// Needs styles/panels.css (+ form.css when a panel offers a retry).\nexport { Panel } from './components/Panel.jsx';\nexport { PanelGrid, packLayout } from './grid/PanelGrid.jsx';\n\n// A timeline: lanes of clips against a ruler, with a playhead and pointer-anchored zoom. Product\n// neutral — it takes {start, duration} and draws them, and never invents a width for a duration\n// nobody measured. Needs styles/timeline.css.\nexport {\n Timeline, majorTickStep, tickLabel, durationLabel as timelineDurationLabel,\n TL_MIN_PPS, TL_MAX_PPS, TL_DEFAULT_PPS, TL_HEAD_W,\n} from './timeline/Timeline.jsx';\n// Mentions: a field that holds people, columns, files as pills; the menu at the caret; the\n// read-only renderer; and the token model ({{Name}} / @Name) hosts serialize through.\nexport { MentionInput, MentionText } from './mention/MentionInput.jsx';\nexport * as mention from './mention/mentionModel.js';\n","// OpenAI Responses SSE event parsing — extracted from HarnessRouter's chat client\n// (harnessrouter/src/lib/chat.ts streamResponse). Transport-agnostic: the caller does the\n// fetch/POST however it likes (BFF, broker, direct) and hands the response body (a\n// ReadableStream) plus a handlers object here.\n//\n// Two layers:\n// readSSEStream(body, onData) — raw SSE framing (blank-line separated, data: lines)\n// createResponsesDispatcher(handlers) — native Responses event -> handler dispatch\n// pumpResponsesStream(body, handlers) — both together; resolves to the response id\n//\n// Handlers (all optional):\n// onCreated(responseId) response.created\n// onSession(sessionId) response.created metadata.session_id (continuation)\n// onReasoningDelta(text) response.reasoning_summary_text.delta\n// onToolCall(name, args, callId) response.function_call_arguments.done (name + call_id\n// captured from the matching output_item.added, keyed by\n// output_index — the same pairing HR ships)\n// onToolResult(callId, output) function_call_output items\n// onTextDelta(text) response.output_text.delta\n// onFile({container_id,file_id,filename}) container_file_citation annotations\n// onDone(status, response) response.completed / .incomplete / .failed (a failed\n// response's own status distinguishes user cancels)\n// onError(message) error events\n\nexport function createResponsesDispatcher(h) {\n // function_call name + call_id live on output_item.added; arguments finalize on .done — key by\n // output_index. function_call_output (the tool result) carries the same call_id → pair them.\n const fnByIdx = {};\n const self = {\n responseId: null,\n dispatch(ev) {\n const t = ev.type;\n switch (t) {\n case 'response.created': {\n const resp = ev.response || {};\n self.responseId = resp.id || self.responseId;\n if (self.responseId) h.onCreated?.(self.responseId);\n const sid = (resp.metadata && resp.metadata.session_id) || '';\n if (sid) h.onSession?.(sid);\n break;\n }\n case 'response.reasoning_summary_text.delta':\n h.onReasoningDelta?.(ev.delta || '');\n break;\n case 'response.output_item.added': {\n const item = ev.item || {};\n if (item.type === 'function_call') {\n fnByIdx[ev.output_index] = { name: item.name || 'tool', callId: item.call_id || '' };\n } else if (item.type === 'function_call_output') {\n h.onToolResult?.(item.call_id || '', String(item.output ?? ''));\n }\n break;\n }\n case 'response.function_call_arguments.done': {\n const fn = fnByIdx[ev.output_index] || { name: 'tool', callId: '' };\n h.onToolCall?.(fn.name, ev.arguments || '', fn.callId);\n break;\n }\n case 'response.output_text.delta':\n h.onTextDelta?.(ev.delta || '');\n break;\n case 'response.output_text.annotation.added': {\n const a = ev.annotation || {};\n if (a.type === 'container_file_citation') {\n h.onFile?.({ container_id: a.container_id, file_id: a.file_id, filename: a.filename });\n }\n break;\n }\n case 'response.completed':\n h.onDone?.('completed', ev.response);\n break;\n case 'response.incomplete':\n h.onDone?.('incomplete', ev.response);\n break;\n case 'response.failed':\n // the response object's own status distinguishes a user cancel ('cancelled')\n // from a real failure — surface it so the UI can badge them differently\n h.onDone?.((ev.response && ev.response.status) || 'failed', ev.response);\n break;\n case 'error':\n h.onError?.(ev.message || 'stream error');\n break;\n default:\n break;\n }\n },\n };\n return self;\n}\n\n/** Read an SSE body stream, calling onData(dataString) per frame (data: lines joined). */\nexport async function readSSEStream(body, onData) {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buf = '';\n for (;;) {\n const { value, done } = await reader.read();\n if (done) break;\n buf += decoder.decode(value, { stream: true });\n let nl;\n // SSE frames are separated by a blank line; each frame has one or more `data:` lines.\n while ((nl = buf.indexOf('\\n\\n')) !== -1) {\n const frame = buf.slice(0, nl);\n buf = buf.slice(nl + 2);\n const data = frame.split('\\n').filter((l) => l.startsWith('data:')).map((l) => l.slice(5).trim()).join('');\n if (!data) continue;\n onData(data);\n }\n }\n}\n\n/**\n * Convenience: parse a Responses SSE body end-to-end, dispatching to handlers.\n * Resolves to the response id (for previous_response_id chaining), or null.\n */\nexport async function pumpResponsesStream(body, handlers) {\n const d = createResponsesDispatcher(handlers);\n await readSSEStream(body, (data) => {\n try { d.dispatch(JSON.parse(data)); } catch { /* ignore malformed frame */ }\n });\n return d.responseId;\n}\n","// Assistant-turn block state machine — extracted from HarnessRouter's workbench.\n// An assistant turn is an ORDERED list of blocks appended as stream events arrive, so tool\n// activity interleaves with prose in real time (never all tools hoisted to the top):\n// { kind: 'text', text } — streamed prose\n// { kind: 'tools', reasoning, steps: ToolStep[] } — a contiguous run of tool activity\n// ToolStep: { name, args, result?, callId? }\n\nexport function withText(blocks, d) {\n const out = blocks.slice(); const last = out[out.length - 1];\n if (last && last.kind === 'text') out[out.length - 1] = { kind: 'text', text: last.text + d };\n else out.push({ kind: 'text', text: d });\n return out;\n}\n\nexport function withReasoning(blocks, d) {\n const out = blocks.slice(); const last = out[out.length - 1];\n if (last && last.kind === 'tools') out[out.length - 1] = { ...last, reasoning: last.reasoning + d };\n else out.push({ kind: 'tools', reasoning: d, steps: [] });\n return out;\n}\n\nexport function withStep(blocks, step) {\n const out = blocks.slice(); const last = out[out.length - 1];\n if (last && last.kind === 'tools') out[out.length - 1] = { ...last, steps: [...last.steps, step] };\n else out.push({ kind: 'tools', reasoning: '', steps: [step] });\n return out;\n}\n\nexport function withResult(blocks, callId, output) {\n return blocks.map((b) => (b.kind !== 'tools' ? b\n : { ...b, steps: b.steps.map((t) => ((t.callId && t.callId === callId && t.result === undefined) ? { ...t, result: output } : t)) }));\n}\n\n/** All prose of an assistant message joined (for copy-to-clipboard etc.). */\nexport function asstText(a) {\n return a.blocks.filter((b) => b.kind === 'text').map((b) => b.text).join('\\n\\n');\n}\n","// Session-continuation store — extracted from HarnessRouter's workbench conv store.\n// A module-level (per createConversationStore() instance) map of conversation state keyed by\n// session id (or any stable key for a not-yet-allocated conversation), so:\n// - switching conversations never destroys an optimistic user message or an in-flight stream\n// - N concurrent turns all keep streaming into their own entries in the background\n// - a broadcast/bus event source can write to the same entry the POST stream writes to\n//\n// State shape (extend via patches — unknown keys pass through):\n// { msgs, busy, prevId, firstTurn, loaded }\n// prevId is the last response id (previous_response_id chaining = session continuation).\nimport { useSyncExternalStore } from 'react';\n\nexport function createConversationStore(makeInitial) {\n const initial = makeInitial || (() => ({ msgs: [], busy: false, prevId: null, firstTurn: true, loaded: false }));\n const store = new Map();\n const subs = new Map();\n\n function get(key) {\n let s = store.get(key);\n if (!s) { s = initial(); store.set(key, s); }\n return s;\n }\n function set(key, patch) {\n const cur = get(key);\n const p = typeof patch === 'function' ? patch(cur) : patch;\n store.set(key, { ...cur, ...p });\n subs.get(key)?.forEach((f) => f());\n }\n /** Rebind/seed a key directly (e.g. copy a new-conversation entry onto its real session id). */\n function seed(key, state) { store.set(key, state); subs.get(key)?.forEach((f) => f()); }\n /** Mutate the LAST assistant message of a conversation (streaming writes). */\n function updateLastAssistant(key, fn) {\n set(key, (s) => {\n const out = s.msgs.slice();\n for (let i = out.length - 1; i >= 0; i--) {\n if (out[i].role === 'assistant') { const a = { ...out[i] }; fn(a); out[i] = a; break; }\n }\n return { msgs: out };\n });\n }\n /** React hook: subscribe a component to one conversation's state. */\n function use(key) {\n return useSyncExternalStore(\n (cb) => {\n let set_ = subs.get(key);\n if (!set_) { set_ = new Set(); subs.set(key, set_); }\n set_.add(cb);\n return () => { set_.delete(cb); };\n },\n () => get(key),\n () => get(key),\n );\n }\n return { get, set, seed, updateLastAssistant, use };\n}\n","// Gateway turns -> the message shape ChatMessages renders.\n//\n// This lives in state/ rather than in the transport because it is a pure shape translation with\n// no network in it, and because ChatPanel (a root export) takes ChatMessage[] from its\n// loadHistory: a root consumer must be able to convert history without pulling the whole\n// HarnessRouter fetch layer into its bundle. reifyui/harness re-exports it, so the transport's\n// own callers keep importing it from where the rest of their transport lives.\n//\n// Four apps had each open-coded this function. Three of the four copies were byte-identical and\n// the fourth was the same logic with the status map inlined as a nested ternary.\n\nconst TURN_STATUS = {\n failed: 'failed', error: 'failed', cancelled: 'cancelled',\n incomplete: 'incomplete', max_turns: 'incomplete', timeout: 'incomplete',\n};\n\n/** Gateway turns -> ChatMessages' message shape. */\nexport function turnsToMessages(turns) {\n const out = [];\n for (const t of turns || []) {\n if (t.user) out.push({ role: 'user', text: t.user });\n const steps = (t.tools || []).map((x) => ({ name: x.name, args: x.arguments, result: x.result }));\n const blocks = [];\n if (steps.length) blocks.push({ kind: 'tools', reasoning: '', steps });\n if (t.assistant) blocks.push({ kind: 'text', text: t.assistant });\n const status = TURN_STATUS[t.status] || 'done';\n if (blocks.length || status !== 'done') out.push({ role: 'assistant', blocks, status });\n }\n return out;\n}\n","// Line-glyph icon set for the conversational surface (16-17px, currentColor stroke) —\n// extracted verbatim from HarnessRouter's workbench. Dependency-free (inline SVG only).\nimport React from 'react';\n\nexport function Svg({ children, s = 16 }) {\n return (\n <svg width={s} height={s} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\"\n strokeWidth=\"1.8\" strokeLinecap=\"round\" strokeLinejoin=\"round\">{children}</svg>\n );\n}\n\nexport function Chevron({ dir, size = 16 }) {\n const d = dir === 'left' ? 'M15 18l-6-6 6-6' : dir === 'right' ? 'M9 18l6-6-6-6' : 'M6 9l6 6 6-6';\n return (\n <svg width={size} height={size} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\"\n strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\"><path d={d} /></svg>\n );\n}\n\n// ── tool-step icons (activity timeline) ──\nexport const IcTool = () => <Svg s={17}><path d=\"M14.7 6.3a4 4 0 0 1-5.4 5.4L4 17v3h3l5.3-5.3a4 4 0 0 1 5.4-5.4l-2.3 2.3-1.7-1.7 2.3-2.3a4 4 0 0 0-1.6 0Z\" /></Svg>;\nexport const IcPlug = () => <Svg s={17}><path d=\"M9 2v6M15 2v6M6 8h12v3a6 6 0 0 1-12 0z\" /><path d=\"M12 17v5\" /></Svg>;\nexport const IcSkill = () => <Svg s={17}><path d=\"M9 18h6M10 22h4\" /><path d=\"M12 2a7 7 0 0 0-4 12.7c.6.5 1 1.3 1 2.1V18h6v-1.2c0-.8.4-1.6 1-2.1A7 7 0 0 0 12 2z\" /></Svg>;\nexport const IcTerminal = () => <Svg s={17}><rect x=\"3\" y=\"4\" width=\"18\" height=\"16\" rx=\"2\" /><path d=\"M7 9l3 3-3 3M13 15h4\" /></Svg>;\nexport const IcDoc = () => <Svg s={17}><path d=\"M14 3H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z\" /><path d=\"M14 3v6h6M8 13h8M8 17h6\" /></Svg>;\nexport const IcList = () => <Svg s={17}><path d=\"M8 6h12M8 12h12M8 18h12M3.5 6h.01M3.5 12h.01M3.5 18h.01\" /></Svg>;\nexport const IcGlobe = () => <Svg s={17}><circle cx=\"12\" cy=\"12\" r=\"9\" /><path d=\"M3 12h18M12 3a15 15 0 0 1 0 18a15 15 0 0 1 0-18z\" /></Svg>;\nexport const IcSearch = () => <Svg s={17}><circle cx=\"11\" cy=\"11\" r=\"7\" /><path d=\"m21 21-4.3-4.3\" /></Svg>;\nexport const IcScroll = () => <Svg s={17}><path d=\"M6 3h10a2 2 0 0 1 2 2v12a3 3 0 0 0 3 3H8a2 2 0 0 1-2-2V3z\" /><path d=\"M6 3a2 2 0 0 0-2 2v2h2M10 8h6M10 12h6\" /></Svg>;\nexport const IcSpawn = () => <Svg s={17}><circle cx=\"6\" cy=\"6\" r=\"3\" /><circle cx=\"18\" cy=\"18\" r=\"3\" /><path d=\"M6 9v3a3 3 0 0 0 3 3h6\" /></Svg>;\nexport const IcCheck = () => <Svg s={17}><circle cx=\"12\" cy=\"12\" r=\"9\" /><path d=\"m9 12 2 2 4-4\" /></Svg>;\nexport const IcThink = () => <Svg s={16}><path d=\"M9.5 2a5.5 5.5 0 0 0-3 10.1V15a2 2 0 0 0 2 2h3a2 2 0 0 0 2-2v-2.9A5.5 5.5 0 0 0 9.5 2zM9 20h4M10 22h2\" /></Svg>;\nexport const IcSend = () => <Svg s={16}><path d=\"M12 19V5\" /><path d=\"M5 12l7-7 7 7\" /></Svg>;\n\n// ── chrome glyphs (chat panel, chips, search) ──\n// The package draws its own so a consumer never inherits an icon-library dependency from a\n// component: four apps pull the same four glyphs out of lucide today purely to hand them to a\n// panel that could have drawn them itself.\nexport const IcX = ({ size = 14 }) => <Svg s={size}><path d=\"M18 6 6 18M6 6l12 12\" /></Svg>;\nexport const IcMic = ({ size = 15 }) => <Svg s={size}><rect x=\"9\" y=\"2\" width=\"6\" height=\"12\" rx=\"3\" /><path d=\"M5 11a7 7 0 0 0 14 0M12 18v4M8 22h8\" /></Svg>;\nexport const IcPaperclip = ({ size = 16 }) => <Svg s={size}><path d=\"M21.4 11.1 12.2 20.3a5.5 5.5 0 0 1-7.8-7.8l9.2-9.2a3.7 3.7 0 0 1 5.2 5.2l-9.2 9.2a1.8 1.8 0 0 1-2.6-2.6l8.5-8.5\" /></Svg>;\nexport const IcPanelRight = ({ size = 17 }) => <Svg s={size}><rect x=\"3\" y=\"4\" width=\"18\" height=\"16\" rx=\"2\" /><path d=\"M15 4v16\" /></Svg>;\nexport const IcDownload = ({ size = 16 }) => <Svg s={size}><path d=\"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4\" /><path d=\"M7 10l5 5 5-5\" /><path d=\"M12 15V3\" /></Svg>;\nexport const IcEye = ({ size = 15 }) => <Svg s={size}><path d=\"M2 12s3.6-7 10-7 10 7 10 7-3.6 7-10 7-10-7-10-7z\" /><circle cx=\"12\" cy=\"12\" r=\"3\" /></Svg>;\n","// Tool-step presentation metadata — extracted from HarnessRouter's workbench.\n// toolMeta(name, args) -> { Icon, label, chip? }: a rich end-user-facing row for one tool step.\n// summarizeSteps(steps) -> \"Ran 5 commands, read 2 files, wrote a file\" natural-language recap.\nimport {\n IcTool, IcPlug, IcSkill, IcTerminal, IcDoc, IcList, IcGlobe, IcSearch, IcScroll, IcSpawn,\n} from './icons.jsx';\n\nexport function humanize(s) {\n return (s || '').replace(/[_\\-]+/g, ' ').trim().replace(/\\b\\w/g, (c) => c.toUpperCase());\n}\nexport function parseArgs(args) {\n try { return (typeof args === 'string' ? JSON.parse(args) : args) || {}; } catch { return {}; }\n}\nexport function baseName(p) { return String(p || '').split('/').filter(Boolean).pop() || String(p || ''); }\nexport function prettyJson(s) { try { return JSON.stringify(JSON.parse(s), null, 2); } catch { return s || ''; } }\n\n// Rich end-user-facing metadata for one tool step: icon + label (+ optional filename/kind chip).\nexport function toolMeta(name, args) {\n const n = name || ''; const a = parseArgs(args);\n const mcp = n.match(/^mcp__(.+?)__(.+)$/);\n if (mcp) return { Icon: IcPlug, label: `${humanize(mcp[1])} · ${humanize(mcp[2])}` };\n switch (n) {\n case 'Skill': return { Icon: IcSkill, label: 'Skill', chip: String(a.command || a.name || a.skill || a.skill_name || '') || undefined };\n case 'ToolSearch': return { Icon: IcSearch, label: 'Finding tools' };\n case 'TaskCreate': return { Icon: IcList, label: 'Added task' + (a.subject ? `: ${a.subject}` : '') };\n case 'TaskUpdate': {\n const s = String(a.status || '');\n return { Icon: IcList, label: s === 'completed' ? 'Completed task' : s === 'in_progress' ? 'Started task' : 'Updated task' };\n }\n case 'Bash': {\n const cmd = String(a.command || '');\n const label = /^\\s*mkdir/.test(cmd) ? 'Create working directory' : /^\\s*(cd|ls|pwd|cat|find)\\b/.test(cmd) ? 'Inspected the workspace' : 'Ran a command';\n return { Icon: IcTerminal, label };\n }\n case 'Write': return { Icon: IcDoc, label: 'Wrote a file', chip: baseName(a.file_path || a.path) };\n case 'Edit': case 'MultiEdit': return { Icon: IcDoc, label: 'Edited a file', chip: baseName(a.file_path || a.path) };\n case 'Read': return { Icon: IcScroll, label: 'Read ' + (baseName(a.file_path || a.path) || 'a file') };\n case 'Glob': return { Icon: IcSearch, label: 'Found files' };\n case 'Grep': return { Icon: IcSearch, label: 'Searched code' };\n case 'LS': return { Icon: IcList, label: 'Listed files' };\n case 'WebSearch': return { Icon: IcGlobe, label: 'Searched the web' };\n case 'WebFetch': return { Icon: IcGlobe, label: 'Fetched a web page' };\n case 'Task': case 'Agent': return { Icon: IcSpawn, label: 'Ran a sub-agent' };\n default: return { Icon: IcTool, label: humanize(n) };\n }\n}\n\n// Natural-language summary for a group of steps, counted per operation type and concatenated,\n// e.g. \"Ran 5 commands\" or \"Ran 5 commands, read 2 files, wrote a file\".\nexport function summarizeSteps(steps) {\n // name -> a stable category key (Edit/MultiEdit collapse; mcp__*/unknown -> 'tool')\n const catOf = (n) => {\n if (/^mcp__/.test(n)) return 'tool';\n return ({ Bash: 'bash', Write: 'write', Edit: 'edit', MultiEdit: 'edit', Read: 'read', Glob: 'glob',\n Grep: 'grep', LS: 'ls', WebSearch: 'websearch', WebFetch: 'webfetch', Task: 'agent', Agent: 'agent',\n ToolSearch: 'toolsearch', Skill: 'skill', TaskCreate: 'taskcreate', TaskUpdate: 'taskupdate' })[n] || 'tool';\n };\n // category -> phrase(count). Lowercase; the first word of the whole summary is capitalized below.\n const phrase = (cat, c) => {\n const one = c === 1;\n switch (cat) {\n case 'bash': return one ? 'ran a command' : `ran ${c} commands`;\n case 'write': return one ? 'wrote a file' : `wrote ${c} files`;\n case 'edit': return one ? 'edited a file' : `edited ${c} files`;\n case 'read': return one ? 'read a file' : `read ${c} files`;\n case 'grep': return one ? 'searched code' : `searched code ${c} times`;\n case 'glob': return 'found files';\n case 'ls': return 'listed files';\n case 'websearch': return one ? 'searched the web' : `searched the web ${c} times`;\n case 'webfetch': return one ? 'fetched a page' : `fetched ${c} pages`;\n case 'agent': return one ? 'ran a sub-agent' : `ran ${c} sub-agents`;\n case 'toolsearch': return 'loaded tools';\n case 'skill': return one ? 'used a skill' : `used ${c} skills`;\n case 'taskcreate': return one ? 'added a task' : `added ${c} tasks`;\n case 'taskupdate': return one ? 'updated a task' : `updated ${c} tasks`;\n default: return one ? 'used a tool' : `used ${c} tools`;\n }\n };\n // count per category, preserving first-seen order\n const order = [];\n const counts = {};\n for (const s of steps) {\n const cat = catOf(s.name || '');\n if (!(cat in counts)) { counts[cat] = 0; order.push(cat); }\n counts[cat]++;\n }\n if (order.length === 0) return 'Working…';\n const parts = order.map((cat) => phrase(cat, counts[cat]));\n const j = parts.join(', ');\n return j.charAt(0).toUpperCase() + j.slice(1);\n}\n","// Activity timeline — extracted from HarnessRouter's workbench.\n// ToolGroup: a collapsible group whose summary is a natural-language recap (\"Ran 5 commands,\n// wrote a file\"); open while the turn runs, auto-collapses when it concludes. Each ToolRow\n// carries a typed icon + friendly label (+ filename chip) and expands to its Request / Result.\n//\n// Override slot: renderStep(step, idx) replaces the default ToolRow for a step (return\n// undefined to fall through to the default).\nimport React, { useEffect, useState } from 'react';\nimport { Chevron, IcThink, IcCheck } from './icons.jsx';\nimport { toolMeta, summarizeSteps, prettyJson } from './toolMeta.js';\n\n// Takes a single `props` object (destructured inside) so TSX consumers don't infer every slot\n// as required.\nexport function ToolGroup(props) {\n const {\n reasoning, steps, running,\n workingLabel = 'Working…', thinkingLabel = 'Thinking', doneLabel = 'Done', thoughtLabel = 'Thought process',\n renderStep,\n } = props;\n // Open while the turn runs; auto-collapse to a one-line recap once it concludes.\n const [open, setOpen] = useState(running);\n useEffect(() => { setOpen(running); }, [running]);\n if (!reasoning && steps.length === 0) return null;\n const summary = running ? workingLabel : (steps.length ? summarizeSteps(steps) : thoughtLabel);\n return (\n <div className={'wbx-acts' + (open ? ' open' : '')}>\n <button className=\"wbx-acts-sum\" onClick={() => setOpen((v) => !v)}>\n <Chevron dir={open ? 'down' : 'right'} size={13} /><span>{summary}</span>\n </button>\n {open && (\n <div className=\"wbx-acts-body\">\n {reasoning && (\n <div className=\"wbx-act\"><span className=\"wbx-act-ic-t thinking\"><IcThink /></span>\n <div className=\"wbx-act-main\"><div className=\"wbx-act-k\">{thinkingLabel}</div>\n <div className=\"wbx-act-v\">{reasoning}</div></div></div>\n )}\n {steps.map((s, j) => {\n if (renderStep) {\n const el = renderStep(s, j);\n if (el !== undefined) return <React.Fragment key={j}>{el}</React.Fragment>;\n }\n return <ToolRow key={j} step={s} />;\n })}\n {!running && (\n <div className=\"wbx-act\"><span className=\"wbx-act-ic-t done\"><IcCheck /></span>\n <div className=\"wbx-act-main\"><div className=\"wbx-act-k\">{doneLabel}</div></div></div>\n )}\n </div>\n )}\n </div>\n );\n}\n\nexport function ToolRow(props) {\n const { step, requestLabel = 'Request', resultLabel = 'Result' } = props;\n const [open, setOpen] = useState(false);\n const meta = toolMeta(step.name, step.args);\n const Icon = meta.Icon;\n const hasDetail = !!(step.args && step.args !== '{}') || step.result !== undefined;\n return (\n <div className=\"wbx-act\">\n <span className=\"wbx-act-ic-t\"><Icon /></span>\n <div className=\"wbx-act-main\">\n <button className={'wbx-act-row' + (open ? ' open' : '')} disabled={!hasDetail} onClick={() => setOpen((v) => !v)}>\n <span className=\"wbx-act-k\">{meta.label}</span>\n {meta.chip && <span className=\"wbx-act-chip\">{meta.chip}</span>}\n {hasDetail && <span className=\"wbx-act-exp\"><Chevron dir={open ? 'down' : 'right'} size={12} /></span>}\n </button>\n {open && (\n <div className=\"wbx-act-detail\">\n {step.args && step.args !== '{}' && (\n <div className=\"wbx-act-block\"><div className=\"wbx-act-block-h\">{requestLabel}</div>\n <pre className=\"wbx-act-pre\">{prettyJson(step.args)}</pre></div>\n )}\n {step.result !== undefined && (\n <div className=\"wbx-act-block\"><div className=\"wbx-act-block-h\">{resultLabel}</div>\n <pre className=\"wbx-act-pre\">{String(step.result).slice(0, 4000)}</pre></div>\n )}\n </div>\n )}\n </div>\n </div>\n );\n}\n","// Message list — extracted from HarnessRouter's workbench conversation render.\n// Messages:\n// { role: 'user', text, ... }\n// { role: 'assistant', blocks, status: 'running'|'done'|'failed'|'cancelled'|'incomplete', ... }\n// Assistant blocks render in stream order so tool activity interleaves with prose.\n//\n// Override slots (all optional):\n// renderMarkdown(text) markdown renderer for prose blocks (inject your ReactMarkdown;\n// default is a plain pre-wrap div — the package has no deps)\n// renderMessage(m, i) full custom render for a message (return undefined to fall through)\n// userExtras(m, i) extra content INSIDE the user bubble, before the text\n// (HR renders its attachment cards here)\n// workingExtra(m, i) extra content on the live Working row (HR's Stop button)\n// assistantFooter(m, i) content below a finished assistant turn (file cards, action row)\n// roleLabel(m, i) small caption above a turn (\"You\", the agent's name); none by default\n// renderStep(step, j) per-step override inside the activity timeline\n// statusLabels terminal badge copy per status\n// workingLabel / toolLabels live-indicator + timeline copy\nimport React from 'react';\nimport { ToolGroup } from './ToolSteps.jsx';\n\nexport const DEFAULT_STATUS_LABELS = {\n failed: '✕ Failed. See the output above for the reason',\n cancelled: '◼ Stopped by you',\n // Claims only what is true of every cause: an incomplete turn may have hit its step or time\n // budget, or been cut mid-flight (a replica restart under a live turn settles as incomplete).\n // Asserting \"step or time limit\" for all of them sent an operator debugging a limit that was\n // never reached. A host that knows the actual cause says so in its own chrome (statusLabels /\n // assistantFooter).\n incomplete: '◔ Stopped before finishing. Continue to resume',\n};\n\nconst defaultMarkdown = (text) => <div style={{ whiteSpace: 'pre-wrap' }}>{text}</div>;\n\n// Reduced motion: the typewriter is motion — render streamed text directly.\nconst REDUCED_MOTION = typeof window !== 'undefined'\n && typeof window.matchMedia === 'function'\n && window.matchMedia('(prefers-reduced-motion: reduce)').matches;\n\n// Typewriter reveal for the actively-streaming text block. Deltas arrive in ~1.2s bursts, so raw\n// rendering makes short answers pop in whole. This fills characters at a deliberate pace: reveal\n// the currently-pending text over ~REVEAL_SEC seconds, but never slower than MIN_CPS (so the last\n// characters don't drag) — and because the rate is (gap / REVEAL_SEC), a newly-arrived batch grows\n// the gap and automatically speeds the reveal to catch up. Snaps to full when streaming stops.\n//\n// The typewriter is a DELTA smoother, not an entrance animation: text already present at mount is\n// history (e.g. opening a running session loads the turn's progress-so-far as one snapshot) and\n// paints instantly — only text appended after mount animates. A turn started live in this tab\n// mounts with empty text, so its stream animates exactly as before.\nconst REVEAL_SEC = 3; // a pending burst fills over ~3s...\nconst MIN_CPS = 10; // ...unless the tail is small, then at least this many chars/sec\nfunction TypewriterText(props) {\n const { text, render } = props;\n const active = props.active && !REDUCED_MOTION;\n const [n, setN] = React.useState(() => (text ? text.length : 0));\n const textRef = React.useRef(text);\n textRef.current = text;\n const accRef = React.useRef(text ? text.length : 0); // float char position (setN renders the floor)\n React.useEffect(() => {\n if (!active) { setN(textRef.current ? textRef.current.length : 0); return undefined; }\n let raf; let prev = null;\n const tick = (t) => {\n if (prev == null) prev = t;\n const dt = Math.min(0.1, (t - prev) / 1000); // clamp dt so a backgrounded tab doesn't jump\n prev = t;\n const len = textRef.current ? textRef.current.length : 0;\n const gap = len - accRef.current;\n if (gap > 0) {\n const cps = Math.max(MIN_CPS, gap / REVEAL_SEC); // bigger backlog -> faster reveal\n accRef.current = Math.min(len, accRef.current + cps * dt);\n setN(Math.floor(accRef.current));\n }\n raf = requestAnimationFrame(tick);\n };\n raf = requestAnimationFrame(tick);\n return () => cancelAnimationFrame(raf);\n }, [active]);\n const shown = active ? (text || '').slice(0, n) : (text || '');\n return render(shown);\n}\n\n// NOTE: components take a single `props` object and destructure inside — TypeScript consumers\n// (HR is TSX) infer inline-destructured JS props as REQUIRED, which would force every slot.\nexport function UserTurn(props) {\n const { msg, children, label } = props;\n const bubble = (\n <div className=\"wbx-bubble-user\">\n {children}\n {msg.text && <div className=\"wbx-bubble-text\">{msg.text}</div>}\n </div>\n );\n // With a caption, caption and bubble share one column so the caption's left edge is the\n // bubble's left edge (the design), while the column itself still sits at the trailing side.\n return (\n <div className=\"wbx-turn user\">\n {label ? <div className=\"wbx-turn-body\"><div className=\"wbx-role\">{label}</div>{bubble}</div> : bubble}\n </div>\n );\n}\n\nexport function AssistantTurn(props) {\n const {\n msg,\n renderMarkdown = defaultMarkdown,\n workingLabel = 'Working…',\n workingExtra,\n statusLabels = DEFAULT_STATUS_LABELS,\n renderStep,\n toolLabels,\n footer,\n label,\n } = props;\n return (\n <div className=\"wbx-turn asst\">\n {label ? <div className=\"wbx-role\">{label}</div> : null}\n {msg.blocks.map((b, bi) => (b.kind === 'tools'\n ? <ToolGroup key={bi} reasoning={b.reasoning} steps={b.steps}\n running={msg.status === 'running' && bi === msg.blocks.length - 1}\n renderStep={renderStep} {...(toolLabels || {})} />\n : <div key={bi} className=\"wbx-md\"><TypewriterText text={b.text} render={renderMarkdown}\n active={msg.status === 'running' && bi === msg.blocks.length - 1} /></div>\n ))}\n {/* Live \"working\" indicator BELOW the last row for the whole running turn (not just before\n the first token) — long tool/think phases otherwise look frozen. */}\n {msg.status === 'running' && (\n <div className=\"wbx-working\" aria-label=\"Working\">\n <span className=\"wbx-working-dots\"><span /><span /><span /></span>\n <span className=\"wbx-working-txt\">{workingLabel}</span>\n {workingExtra}\n </div>\n )}\n {(msg.status === 'failed' || msg.status === 'cancelled' || msg.status === 'incomplete') && (\n <div className={'wbx-turnbadge ' + msg.status} role=\"status\">{statusLabels[msg.status]}</div>\n )}\n {footer}\n </div>\n );\n}\n\n// Loading placeholder for the conversation. Mirrors UserTurn/AssistantTurn geometry\n// exactly (same .wbx-turn / .wbx-bubble-user / .wbx-md classes), so when real history\n// streams in it lands with ZERO layout shift — assistant turns are full-width prose\n// lines, user turns are right-aligned brand-tinted bubbles a fraction of the column.\n// Themeable through the same --uic-* tokens as the live surface (light + dark), and\n// the wrapper is display:contents so the turns inherit the consumer's own inter-turn\n// spacing. Use on any conversational surface while history / the first tokens load:\n// {loading ? <ChatMessagesSkeleton /> : <ChatMessages ... />}\n// Pass `turns` to customize the mix (each {role:'user'|'assistant', lines:[widths],\n// width?} — user `width` is the bubble's fraction of the column).\nconst DEFAULT_SKELETON_TURNS = [\n { role: 'assistant', lines: ['94%', '82%', '58%'] },\n { role: 'user', width: '46%', lines: ['88%', '62%'] },\n { role: 'assistant', lines: ['90%', '97%', '71%'] },\n { role: 'user', width: '38%', lines: ['80%'] },\n];\n\nexport function ChatMessagesSkeleton(props) {\n const turns = (props && props.turns) || DEFAULT_SKELETON_TURNS;\n return (\n <div className=\"wbx-skel\" aria-busy=\"true\" aria-label=\"Loading conversation\">\n {turns.map((t, i) => (t.role === 'user' ? (\n <div key={i} className=\"wbx-turn user wbx-skel-turn\" aria-hidden=\"true\">\n <div className=\"wbx-bubble-user wbx-skel-lines\" style={{ width: t.width }}>\n {t.lines.map((w, j) => <span key={j} className=\"wbx-skel-bar\" style={{ width: w }} />)}\n </div>\n </div>\n ) : (\n <div key={i} className=\"wbx-turn asst wbx-skel-turn\" aria-hidden=\"true\">\n <div className=\"wbx-md wbx-skel-lines\">\n {t.lines.map((w, j) => <span key={j} className=\"wbx-skel-bar\" style={{ width: w }} />)}\n </div>\n </div>\n )))}\n </div>\n );\n}\n\nexport function ChatMessages(props) {\n const {\n messages,\n renderMarkdown,\n renderMessage,\n userExtras,\n workingExtra,\n assistantFooter,\n statusLabels,\n renderStep,\n workingLabel,\n toolLabels,\n roleLabel,\n } = props;\n return (\n <>\n {messages.map((m, i) => {\n if (renderMessage) {\n const el = renderMessage(m, i);\n if (el !== undefined) return <React.Fragment key={i}>{el}</React.Fragment>;\n }\n return m.role === 'user' ? (\n <UserTurn key={i} msg={m} label={roleLabel?.(m, i)}>{userExtras?.(m, i)}</UserTurn>\n ) : (\n <AssistantTurn key={i} msg={m}\n renderMarkdown={renderMarkdown}\n workingLabel={workingLabel}\n workingExtra={workingExtra?.(m, i)}\n statusLabels={statusLabels}\n renderStep={renderStep}\n toolLabels={toolLabels}\n label={roleLabel?.(m, i)}\n footer={assistantFooter?.(m, i)} />\n );\n })}\n </>\n );\n}\n","// Composer — extracted from HarnessRouter's workbench composer (textarea + bottom action row).\n// Enter sends (Shift+Enter for a newline). Auto-grows to fit content, capped at maxRows, then\n// scrolls (HR behavior; pass autoGrow={false} for a fixed-height textarea).\n//\n// Slots:\n// attachments node rendered ABOVE the textarea (attachment card row)\n// accessoriesLeft nodes before the flexible spacer (attach button, model select, mic, …)\n// accessoriesRight nodes after the spacer, before the send button\n// renderSend() replaces the default send button entirely\n// inline single-line layout: accessories, textarea and send share ONE row,\n// vertically aligned (the classic chat input). Buttons stick to the\n// bottom edge as the textarea grows, so multiline still reads right.\n// tray node rendered INSIDE the card, under the action row — one seamless\n// surface, no divider band. This is where a product puts the row that\n// belongs to the message being composed (Arena's harness+model chips,\n// a template picker, a recipient list) rather than to the app chrome.\n// onFiles(FileList) files dropped on the composer (or on dropTargetRef's element, when a\n// product wants the whole conversation to take a drop). The composer is\n// the one that lights up (.is-dropping) either way. Absent: no drop.\n// dropTargetRef a ref to a wider drop target than the composer itself\n// classNames { root, input, row } — each REPLACES the default class when provided,\n// so a product can restyle wholesale without fighting the package CSS\n//\n// NOTE: autoGrow and a CSS-driven min-height on the textarea are mutually exclusive — autoGrow\n// writes an explicit height on every keystroke, which the min-height then cannot raise. A fixed\n// multi-line box wants autoGrow={false} + rows.\nimport React, { useEffect, useRef, useState } from 'react';\nimport { IcSend } from './icons.jsx';\n\n// Takes a single `props` object (destructured inside) so TSX consumers don't infer every slot\n// as required.\nexport function Composer(props) {\n const {\n value,\n onChange,\n onSend,\n disabled = false,\n sendDisabled,\n placeholder,\n rows = 1,\n autoGrow = true,\n inline = false,\n maxRows = 15,\n autoFocus,\n // The composer on a landing page often has an ANIMATING placeholder (a typewriter cycling\n // through example prompts), and a placeholder is the textarea's only accessible name unless\n // one is given — so the field announces a different name every few seconds.\n inputAriaLabel,\n attachments,\n tray,\n onFiles,\n dropTargetRef,\n accessoriesLeft,\n accessoriesRight,\n renderSend,\n classNames = {},\n inputRef,\n } = props;\n const ownRef = useRef(null);\n const taRef = inputRef || ownRef;\n const rootRef = useRef(null);\n\n // Drag-and-drop attach. Native listeners on the target (the composer, or the wider element a\n // product names), so any element can take the drop; a depth counter, because children fire\n // their own enter/leave pairs and the highlight would flicker off while crossing them.\n const [dropping, setDropping] = useState(false);\n useEffect(() => {\n if (!onFiles || disabled) return undefined;\n const el = (dropTargetRef && dropTargetRef.current) || rootRef.current;\n if (!el) return undefined;\n let depth = 0;\n const hasFiles = (e) => Array.from((e.dataTransfer && e.dataTransfer.types) || []).includes('Files');\n const enter = (e) => { if (!hasFiles(e)) return; e.preventDefault(); depth += 1; setDropping(true); };\n const over = (e) => { if (!hasFiles(e)) return; e.preventDefault(); e.dataTransfer.dropEffect = 'copy'; };\n const leave = (e) => { if (!hasFiles(e)) return; e.preventDefault(); depth = Math.max(0, depth - 1); if (depth === 0) setDropping(false); };\n const drop = (e) => {\n if (!hasFiles(e)) return;\n e.preventDefault(); depth = 0; setDropping(false);\n if (e.dataTransfer.files && e.dataTransfer.files.length) onFiles(e.dataTransfer.files);\n };\n el.addEventListener('dragenter', enter); el.addEventListener('dragover', over);\n el.addEventListener('dragleave', leave); el.addEventListener('drop', drop);\n return () => {\n el.removeEventListener('dragenter', enter); el.removeEventListener('dragover', over);\n el.removeEventListener('dragleave', leave); el.removeEventListener('drop', drop);\n };\n }, [onFiles, disabled, dropTargetRef]);\n const rootClass = (classNames.root ?? 'wbx-composer') + (dropping ? ' is-dropping' : '');\n\n // Auto-grow the composer to fit its content, capped at ~maxRows rows (then it scrolls).\n useEffect(() => {\n if (!autoGrow) return;\n const el = taRef.current; if (!el) return;\n el.style.height = 'auto';\n const cs = getComputedStyle(el);\n const lh = parseFloat(cs.lineHeight) || 21;\n const max = lh * maxRows + parseFloat(cs.paddingTop || '0') + parseFloat(cs.paddingBottom || '0');\n el.style.height = Math.min(el.scrollHeight, max) + 'px';\n el.style.overflowY = el.scrollHeight > max ? 'auto' : 'hidden';\n }, [value, autoGrow, maxRows, taRef]);\n\n const sendEl = renderSend ? renderSend() : (\n <button type=\"button\" className=\"uic-send\" disabled={sendDisabled} onClick={() => onSend()} aria-label=\"Send message\">\n <IcSend />\n </button>\n );\n\n if (inline) {\n return (\n <div ref={rootRef} className={rootClass}>\n {attachments}\n <div className=\"uic-composer-line\">\n {accessoriesLeft}\n <textarea\n ref={taRef}\n className={classNames.input ?? 'wbx-composer-input'}\n rows={rows}\n value={value}\n placeholder={placeholder}\n aria-label={inputAriaLabel || placeholder}\n disabled={disabled}\n autoFocus={autoFocus}\n onChange={(e) => onChange(e.target.value)}\n onKeyDown={(e) => {\n if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); onSend(); }\n }}\n />\n {accessoriesRight}\n {sendEl}\n </div>\n {tray ? <div className=\"uic-composer-tray\">{tray}</div> : null}\n </div>\n );\n }\n\n return (\n <div ref={rootRef} className={rootClass}>\n {attachments}\n <textarea\n ref={taRef}\n className={classNames.input ?? 'wbx-composer-input'}\n placeholder={placeholder}\n value={value}\n disabled={disabled}\n rows={rows}\n autoFocus={autoFocus}\n aria-label={inputAriaLabel}\n onChange={(e) => onChange(e.target.value)}\n // Enter obeys sendDisabled, exactly as the send button does: two ways to trigger one\n // action must not disagree about whether it is available. (It still swallows the key —\n // a newline is not what Enter means in this box.) sendDisabled defaults to undefined,\n // so for a caller that never set it nothing changes.\n onKeyDown={(e) => {\n if (e.key !== 'Enter' || e.shiftKey) return;\n e.preventDefault();\n if (!sendDisabled) onSend();\n }}\n />\n <div className={classNames.row ?? 'wbx-composer-row'}>\n {accessoriesLeft}\n <span style={{ flex: 1 }} />\n {accessoriesRight}\n {renderSend ? renderSend() : (\n <button type=\"button\" className=\"uic-send\" disabled={sendDisabled} onClick={() => onSend()} aria-label=\"Send message\">\n <IcSend />\n </button>\n )}\n </div>\n {tray ? <div className=\"uic-composer-tray\">{tray}</div> : null}\n </div>\n );\n}\n","// ChatPanel — the whole conversational column beside a document: header, history, live turn,\n// connecting/retry state, attachments, dictation, composer.\n//\n// This existed four times (273 / 336 / 350 / 333 lines) in four products, and every copy had\n// drifted: one shipped a disabled paperclip labelled \"coming soon\", three shipped a disabled\n// microphone, one never showed that a turn was running when the turn had been started somewhere\n// else, one dropped its staged files before checking whether the send would even happen, and one\n// decided whether a session id was \"real\" by looking for the prefix \"new:\" in it.\n//\n// What is HERE is what is the same in all four: the state machine of a conversation.\n// What stays with the CALLER is everything that differs — the transport, the product's prose,\n// and where the panel sits in the page:\n//\n// runTurn run one turn and report it through `handlers`. The panel does not know whether\n// that is one stream, a stream with a fallback, or three requests.\n// loadHistory the conversation so far, already as ChatMessage[]. Callers write\n// `.then(turnsToMessages)`; a caller whose brand-new document has no session\n// short-circuits to [] here and never makes the request. The panel treats the\n// session id as opaque and never parses it, which is what makes that possible.\n//\n// The panel owns `busy` (its own turn is in flight) and takes `externalBusy` (a turn is running\n// that this tab did not start — another window, or the very first turn before the session is\n// queryable). While externalBusy is true and there is nothing local, it polls history so the\n// conversation appears, and when it goes false it reloads once so the final answer lands. A\n// panel that ignores externalBusy shows a blank \"describe what you want\" prompt while the agent\n// is visibly working, which is what one of the four copies did.\n//\n// Session ids: a document created from a landing page has no session until the first turn opens\n// one, so `sessionId` can change mid-stream from the caller's placeholder to the real id. That is\n// the same conversation renaming itself, not a reason to refetch over blocks arriving live — see\n// the adopt guard below.\nimport React, { useCallback, useEffect, useRef, useState } from 'react';\nimport { ChatMessages, ChatMessagesSkeleton } from './ChatMessages.jsx';\nimport { Composer } from './Composer.jsx';\nimport { Chip } from './Chip.jsx';\nimport { IcMic, IcPanelRight, IcPaperclip, IcSend } from './icons.jsx';\nimport { withReasoning, withResult, withStep, withText } from '../state/blocks.js';\nimport { bytesLabel } from '../format.js';\n\n// Not props. Every one of the four copies used these exact numbers, so there is nothing to\n// configure — a knob nobody turns is a knob that only makes the call sites longer.\nconst POLL_MS = 3000; // catch-up poll while a turn runs elsewhere\nconst RETRY_MS = 20000; // resend a message the gateway was not up to receive\nconst PIN_PX = 80; // \"close enough to the bottom\" to keep following the stream\n\n// ChatPanel's own defaults, NOT the package's DEFAULT_STATUS_LABELS. All four panels overrode\n// that export with these sentences; promoting them into the export would silently rewrite the\n// badges of every other consumer, which none of them asked for.\nconst PANEL_STATUS_LABELS = {\n failed: 'This turn failed. Please try again.',\n cancelled: 'Stopped',\n incomplete: 'The turn hit its limit. Send a follow up to continue.',\n};\n\nexport function ChatPanel(props) {\n const {\n sessionId,\n runTurn,\n loadHistory,\n onSessionStarted,\n onChanged,\n\n seed = '',\n onSeedConsumed,\n\n externalBusy = false,\n\n attachments = null,\n dictation = null,\n\n title = '',\n headerRight = null,\n collapsed = false,\n onToggleCollapse,\n width,\n\n placeholder = 'Message',\n emptyState = null,\n busyState,\n connectingLabel = 'connecting',\n connectingNote = 'Still connecting. Your message will be sent as soon as it is online.',\n workingLabel = 'Working…',\n statusLabels = PANEL_STATUS_LABELS,\n renderMarkdown,\n userExtras,\n toolLabels,\n classNames = {},\n } = props;\n\n const [messages, setMessages] = useState([]);\n const [draft, setDraft] = useState('');\n const [busy, setBusy] = useState(false);\n const [connecting, setConnecting] = useState(false);\n // A turn this tab started but can no longer hear: its stream broke after the gateway accepted\n // it. Its messages come from history until it settles.\n const [dropped, setDropped] = useState(false);\n const [histLoading, setHistLoading] = useState(true);\n const [staged, setStaged] = useState([]); // files picked, not yet sent\n const [attachErr, setAttachErr] = useState('');\n const [listening, setListening] = useState(false);\n\n const pendingRef = useRef(null); // { text, files } awaiting a live gateway\n const seededRef = useRef(false);\n const adoptedRef = useRef(null);\n const bodyRef = useRef(null);\n const fileRef = useRef(null);\n const pinnedRef = useRef(true);\n const prevExternalBusyRef = useRef(false);\n const prevIdRef = useRef(sessionId);\n\n // The callbacks arrive as fresh arrow functions on every render of the page, so they cannot be\n // effect dependencies without re-running the history load on every keystroke. Reading them\n // through a ref keeps the effects keyed on the things that actually changed (the session, the\n // busy flags) while still calling the CURRENT function.\n const api = useRef(null);\n api.current = { runTurn, loadHistory, onSessionStarted, onChanged, onSeedConsumed };\n\n // Stop listening when the panel goes away — the recogniser keeps the microphone otherwise.\n // Build `dictation` ONCE at the call site (useState(() => createDictation())): a fresh object\n // per render would stop the recogniser on every keystroke.\n useEffect(() => () => dictation?.stop(), [dictation]);\n\n // ── the message list ──────────────────────────────────────────────────────\n function updateLastAsst(fn) {\n setMessages((m) => {\n const out = m.slice();\n for (let i = out.length - 1; i >= 0; i -= 1) {\n if (out[i].role === 'assistant') { out[i] = fn({ ...out[i] }); break; }\n }\n return out;\n });\n }\n\n function dropRunningAsst() {\n setMessages((m) => (m.length && m[m.length - 1].role === 'assistant' && m[m.length - 1].status === 'running'\n ? m.slice(0, -1) : m));\n }\n\n // Follow the stream only when the reader is already at the bottom. Measured on scroll rather\n // than after the update, because by then the new content has already grown the distance.\n const onBodyScroll = () => {\n const el = bodyRef.current;\n if (el) pinnedRef.current = el.scrollHeight - el.scrollTop - el.clientHeight <= PIN_PX;\n };\n useEffect(() => {\n const el = bodyRef.current;\n if (el && pinnedRef.current) el.scrollTo({ top: el.scrollHeight });\n }, [messages, connecting, histLoading]);\n\n // ── running a turn ────────────────────────────────────────────────────────\n const deliver = useCallback(async (text, files = []) => {\n setBusy(true);\n setMessages((m) => [...m, { role: 'assistant', blocks: [], status: 'running' }]);\n try {\n const out = await api.current.runTurn({\n sessionId,\n text,\n attachments: files,\n handlers: {\n onSession: (sid) => {\n // Arm the adopt guard only when the id is genuinely CHANGING: a session reporting\n // the id it already has is not a rename and must not suppress a later reload.\n if (sid && sid !== sessionId) adoptedRef.current = sid;\n api.current.onSessionStarted?.(sid);\n },\n onReasoningDelta: (d) => updateLastAsst((a) => ({ ...a, blocks: withReasoning(a.blocks, d) })),\n onToolCall: (name, args, callId) => updateLastAsst((a) => ({ ...a, blocks: withStep(a.blocks, { name, args, callId }) })),\n onToolResult: (callId, output) => updateLastAsst((a) => ({ ...a, blocks: withResult(a.blocks, callId, output) })),\n onTextDelta: (d) => updateLastAsst((a) => ({ ...a, blocks: withText(a.blocks, d) })),\n onDone: (status) => updateLastAsst((a) => ({ ...a, status: status === 'completed' ? 'done' : status })),\n onError: () => updateLastAsst((a) => ({\n ...a,\n blocks: a.blocks.length ? a.blocks : withText([], 'Something went wrong. Please try again.'),\n status: 'failed',\n })),\n },\n }) || {};\n if (out.connecting) {\n // Not a failure: the gateway is still coming up. Take the turn back off the list and\n // hold the message — including its files — for the retry.\n dropRunningAsst();\n pendingRef.current = { text, files };\n setConnecting(true);\n return;\n }\n pendingRef.current = null;\n setConnecting(false);\n if (out.dropped) {\n // The turn is running and this tab lost its stream. Never resend: that starts a second\n // turn behind the first (a game played twice at once, a deck written twice). The message\n // stays as sent, the answer stays \"running\", and history fills it in below.\n setDropped(true);\n return;\n }\n updateLastAsst((a) => (a.status === 'running' ? { ...a, status: 'done' } : a));\n api.current.onChanged?.();\n } catch (e) {\n // A refused turn is an answer, not a gateway still coming up: a wall, a bad request, a\n // session busy with another turn. Say so on the message and leave it there; resending\n // every twenty seconds is what filled a pane with \"connecting\" over a game that was\n // playing fine (2026-09-22).\n updateLastAsst((a) => ({\n ...a,\n blocks: a.blocks.length ? a.blocks : withText([], (e && e.message) || 'The turn could not be started.'),\n status: 'failed',\n }));\n } finally {\n setBusy(false);\n }\n }, [sessionId]);\n\n const preparing = staged.some((f) => f.pending);\n const sendBlocked = busy || histLoading || preparing;\n\n function send() {\n const t = draft.trim();\n // The guard comes FIRST. One copy cleared its staged files above this line, so a send that\n // was refused (mid-turn, or with an empty box) silently threw the attachments away.\n if (!t || sendBlocked) return;\n // Sending ends the utterance: dictation is hands-free, and a recogniser still listening after\n // the message has gone types the next sentence into an empty box the person is not looking at.\n if (listening) { dictation?.stop(); setListening(false); }\n const files = staged;\n // The names ride on the message so the bubble shows what was sent with it. They are not\n // replayed from history — the transcript stores the person's text, not the files — so this is\n // what was attached in this session, not a claim about every past turn.\n setMessages((m) => [...m, { role: 'user', text: t, files: files.map((f) => f.name) }]);\n setDraft('');\n setStaged([]);\n setAttachErr('');\n deliver(t, files);\n }\n\n // ── history ───────────────────────────────────────────────────────────────\n // Keyed on sessionId. A placeholder id resolving to the real one is the SAME conversation, and\n // refetching there would setMessages() over blocks arriving live — the panel would show the\n // user's bubble and nothing else while the agent was visibly working. We know it is the same\n // conversation because our own stream just told us so.\n //\n // The guard is consumed on every run, not just the matching one: coming BACK to this id later\n // is a real reason to reload, and a guard that is never cleared would skip that too.\n useEffect(() => {\n const adopted = adoptedRef.current;\n adoptedRef.current = null;\n if (adopted && adopted === sessionId) { prevIdRef.current = sessionId; return undefined; }\n\n // A different document: drop the previous conversation instead of leaving it on screen\n // under a new title until (and only if) the new one turns out to be non-empty.\n if (prevIdRef.current !== sessionId) {\n prevIdRef.current = sessionId;\n setMessages([]);\n setHistLoading(true);\n setStaged([]);\n setAttachErr('');\n // A different document gets its own first message. The once-only latch is about not\n // resending THIS document's seed, not about one seed per panel for all time.\n seededRef.current = false;\n }\n\n // Fired before the await so the caller can strip ?seed= from the URL immediately — a refresh\n // or a back-button must never resend it. It fires whenever a seed was supplied, including\n // when history turns out to be non-empty and the seed is therefore skipped: making the URL\n // non-replayable is the point, and it is not conditional on the send.\n if (seed) api.current.onSeedConsumed?.();\n\n let dead = false;\n Promise.resolve(api.current.loadHistory(sessionId)).then((hist) => {\n if (dead) return;\n if (hist?.length) setMessages(hist);\n setHistLoading(false);\n if (seed && !seededRef.current && !hist?.length) {\n seededRef.current = true;\n setMessages([{ role: 'user', text: seed }]);\n deliver(seed);\n }\n }).catch(() => { if (!dead) setHistLoading(false); });\n return () => { dead = true; };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [sessionId]);\n\n // Retry a message the gateway was not up to receive.\n useEffect(() => {\n if (!connecting) return undefined;\n const iv = window.setInterval(() => {\n const p = pendingRef.current;\n if (p && !busy) deliver(p.text, p.files);\n }, RETRY_MS);\n return () => window.clearInterval(iv);\n }, [connecting, busy, deliver]);\n\n // A turn this tab started and lost the stream of: poll its history until the turn settles,\n // then one last reload for the final answer and whatever it changed.\n useEffect(() => {\n if (!dropped) return undefined;\n let dead = false;\n const tick = () => Promise.resolve(api.current.loadHistory(sessionId)).then((hist) => {\n if (dead || !hist?.length) return;\n const last = hist[hist.length - 1];\n const settled = !(last.role === 'assistant' && last.status === 'running')\n && !externalBusy;\n setMessages(hist);\n if (settled) { setDropped(false); api.current.onChanged?.(); }\n }).catch(() => {});\n const iv = window.setInterval(tick, POLL_MS);\n return () => { dead = true; window.clearInterval(iv); };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [dropped, externalBusy, sessionId]);\n\n // A turn may be running that this tab did not start. While that is true and nothing local is\n // streaming, poll history so its messages appear; when it ends, reload once so the final answer\n // and whatever it changed land here without a refresh.\n useEffect(() => {\n let dead = false;\n let poll;\n const reload = () => Promise.resolve(api.current.loadHistory(sessionId)).then((hist) => {\n // Never clobber a turn streaming in THIS tab, or a message still waiting to be sent.\n if (!dead && hist?.length && !busy && !pendingRef.current) setMessages(hist);\n }).catch(() => {});\n if (externalBusy && messages.length === 0 && !busy) poll = window.setInterval(reload, POLL_MS);\n if (prevExternalBusyRef.current && !externalBusy) {\n reload();\n api.current.onChanged?.();\n }\n prevExternalBusyRef.current = externalBusy;\n return () => { dead = true; if (poll) window.clearInterval(poll); };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [externalBusy, messages.length, busy, sessionId]);\n\n // ── attachments ───────────────────────────────────────────────────────────\n // Each file appears immediately as a pending chip and resolves in place. prepare() is a real\n // wait — a network upload for one product, base64 of up to 25 MB for another — and a picker\n // that looks inert for three seconds is how people pick the same file twice.\n function pick(list) {\n if (!attachments?.prepare) return;\n setAttachErr('');\n for (const file of list) {\n const entry = { name: file.name, size: file.size, pending: true };\n setStaged((cur) => [...cur, entry]);\n Promise.resolve(attachments.prepare(file)).then((ready) => {\n setStaged((cur) => cur.map((s) => (s === entry ? { name: entry.name, size: entry.size, ...ready } : s)));\n }).catch((e) => {\n // Drop the chip and say why on its own line. The alternative one copy shipped — leaving a\n // chip named \"(failed) report.pdf\" in the row — looks like a file that is going to be sent.\n setStaged((cur) => cur.filter((s) => s !== entry));\n setAttachErr(e?.message || `${file.name} could not be attached.`);\n });\n }\n }\n\n function toggleDictation() {\n if (!dictation) return;\n if (listening) { dictation.stop(); setListening(false); return; }\n setListening(true);\n dictation.start({\n onText: (text) => setDraft((cur) => (cur ? `${cur.replace(/\\s+$/, '')} ${text}` : text)),\n onEnd: () => setListening(false),\n onError: () => setListening(false),\n });\n }\n\n // ── render ────────────────────────────────────────────────────────────────\n const rootCls = ['uic-chat', collapsed ? 'is-collapsed' : '', classNames.root || '']\n .filter(Boolean).join(' ');\n const toggle = onToggleCollapse ? (\n <button type=\"button\" className=\"uic-panel-toggle\" onClick={onToggleCollapse}\n title={collapsed ? 'Show the conversation' : 'Hide the conversation'}\n aria-label={collapsed ? 'Show the conversation' : 'Hide the conversation'}\n aria-expanded={!collapsed}>\n <IcPanelRight />\n </button>\n ) : null;\n\n if (collapsed) {\n return (\n <aside className={rootCls}>\n <div className=\"uic-chat-h\">{toggle}</div>\n </aside>\n );\n }\n\n const empty = messages.length === 0;\n const attachControl = attachments ? (\n <>\n <input ref={fileRef} type=\"file\" hidden\n accept={attachments.accept}\n multiple={attachments.multiple !== false}\n onChange={(e) => { pick([...e.target.files]); e.target.value = ''; }} />\n <button type=\"button\" className=\"uic-chat-icon\" aria-label=\"Attach a file\"\n disabled={busy} onClick={() => fileRef.current?.click()}>\n <IcPaperclip />\n </button>\n </>\n ) : null;\n // No control for a capability we do not have: `dictation` is null wherever the browser has no\n // recogniser, and then there is no microphone at all — never a disabled one.\n const micControl = dictation ? (\n <button type=\"button\" className={'uic-chat-icon' + (listening ? ' is-on' : '')}\n aria-label={listening ? 'Stop dictating' : 'Dictate'} aria-pressed={listening}\n disabled={busy} onClick={toggleDictation}>\n <IcMic />\n </button>\n ) : null;\n const defaultBusyState = (\n <div className=\"uic-chat-empty\">\n <span className=\"uic-chat-pulse\" aria-hidden=\"true\" />\n <div className=\"uic-chat-empty-t\">{workingLabel}</div>\n </div>\n );\n\n return (\n <aside className={rootCls} style={width ? { flex: `0 0 ${width}px` } : undefined}>\n <div className=\"uic-chat-h\">\n {toggle}\n {title ? <span className=\"uic-chat-title\" title={title}>{title}</span> : null}\n {headerRight}\n {connecting ? <span className=\"uic-chat-conn\">{connectingLabel}</span> : null}\n {dropped ? <span className=\"uic-chat-conn\">{workingLabel}</span> : null}\n </div>\n\n <div className=\"uic-chat-body\" ref={bodyRef} onScroll={onBodyScroll} role=\"log\" aria-live=\"polite\">\n {histLoading ? <ChatMessagesSkeleton />\n : empty && externalBusy ? (busyState === undefined ? defaultBusyState : busyState)\n : empty ? emptyState\n : (\n <ChatMessages\n messages={messages}\n renderMarkdown={renderMarkdown}\n // The caller's slot falls through to the built-in file chips when it returns\n // undefined, the same contract ChatMessages already uses for renderMessage.\n userExtras={(m, i) => {\n const own = userExtras?.(m, i);\n if (own !== undefined) return own;\n if (!m.files?.length) return undefined;\n return (\n <span className=\"uic-chat-msg-files\">\n {m.files.map((n) => (\n <Chip key={n} icon={<IcPaperclip size={11} />} label={n} title={n} />\n ))}\n </span>\n );\n }}\n workingLabel={workingLabel}\n // All four panels wrote the same string twice, because ToolGroup carries its own\n // default. One label, one place.\n toolLabels={{ workingLabel, ...(toolLabels || {}) }}\n statusLabels={statusLabels}\n />\n )}\n {connecting ? (\n <div className=\"uic-chat-note\" role=\"status\">\n <span className=\"uic-chat-dot\" aria-hidden=\"true\" />\n {connectingNote}\n </div>\n ) : null}\n </div>\n\n <Composer\n value={draft}\n onChange={setDraft}\n onSend={send}\n disabled={histLoading}\n sendDisabled={sendBlocked || !draft.trim()}\n placeholder={placeholder}\n rows={2}\n autoGrow={false}\n classNames={{ root: 'uic-chat-cmp', input: 'uic-chat-cmp-input', row: 'uic-chat-cmp-row' }}\n attachments={(staged.length > 0 || attachErr) ? (\n <div className=\"uic-chat-files\">\n {staged.map((f, i) => (\n <Chip\n key={`${f.name}-${i}`}\n icon={<IcPaperclip size={11} />}\n title={f.name}\n label={<>\n <span className=\"uic-chip-t\">{f.name}</span>\n <span className=\"uic-chip-meta\">{f.pending ? '…' : bytesLabel(f.size)}</span>\n </>}\n onRemove={() => setStaged((c) => c.filter((_, j) => j !== i))}\n removeLabel={`Remove ${f.name}`}\n />\n ))}\n {attachErr ? <span className=\"uic-chat-file-err\">{attachErr}</span> : null}\n </div>\n ) : null}\n accessoriesLeft={attachControl}\n accessoriesRight={micControl}\n renderSend={() => (\n <button type=\"button\" className=\"uic-chat-send\" onClick={send}\n disabled={sendBlocked || !draft.trim()} aria-label=\"Send message\">\n <IcSend />\n </button>\n )}\n />\n </aside>\n );\n}\n","// Chip — a small labelled token: a staged file, a chosen template, a filter that is set.\n//\n// Three spellings of this existed across four apps, and the interactive ones were built as\n// <span role=\"button\" tabIndex={0}> with a keydown handler that only answered Enter (never\n// Space), inside another button. Here the pressable parts are real <button>s, so the keyboard,\n// the accessibility tree and the browser's own focus ring all work without being re-implemented.\n//\n// Width is CSS, not a prop: two of the copies set maxWidth 180 and 220 inline on the same\n// component in the same app. The label ellipsizes against the row it is in.\nimport React, { forwardRef } from 'react';\nimport { IcX } from './icons.jsx';\n\n/**\n * label the text (a node — e.g. name + a size span)\n * icon leading glyph\n * title native tooltip, usually the untruncated label\n * selected this chip stands for something chosen (brand fill)\n * onClick makes the chip itself a button\n * slot the dashed \"open slot\" look for a chip that stands for a choice not yet made\n * (+ add a file). Defaults to clickable-and-unselected, which is how every earlier\n * caller got it; pass slot={false} for a chip that is clickable AND already set,\n * e.g. a chosen route that opens its own editor.\n * onRemove adds a trailing ✕ button; removeLabel is REQUIRED with it, because \"✕\" alone tells\n * a screen reader nothing about which of five chips it removes\n * trailing a node rendered between the label and the ✕ — a compact control the chip carries,\n * e.g. a per-route model <select> in a comparison bar. It is the CALLER's control:\n * the chip never wraps it in its own press target, so a select inside a clickable\n * chip still opens instead of triggering the chip.\n * ref lands on the OUTERMOST element, the box a Popover or CascadeMenu anchors against.\n * ...rest goes onto the press target (aria-expanded, aria-haspopup, data-*), so a chip that\n * opens a menu can say so to assistive tech without the library naming every attribute.\n */\nexport const Chip = forwardRef(function Chip(props, ref) {\n const { label, icon, title, selected = false, onClick, onRemove, removeLabel, trailing, className,\n slot, ...rest } = props;\n const isSlot = slot ?? (Boolean(onClick) && !selected);\n const cls = ['uic-chip',\n selected ? 'is-selected' : '',\n isSlot ? 'is-open' : '',\n className || ''].filter(Boolean).join(' ');\n\n const body = (\n <>\n {icon ? <span className=\"uic-chip-ic\" aria-hidden=\"true\">{icon}</span> : null}\n <span className=\"uic-chip-l\">{label}</span>\n </>\n );\n\n // A chip that is both pressable and removable is two controls, so the outer element stays a\n // plain span and the press target becomes its own button — never a button inside a button.\n const trail = trailing ? <span className=\"uic-chip-tr\">{trailing}</span> : null;\n\n if (onClick && onRemove) {\n return (\n <span ref={ref} className={cls} title={title}>\n <button type=\"button\" className=\"uic-chip-press\" onClick={onClick} {...rest}>{body}</button>\n {trail}\n <button type=\"button\" className=\"uic-chip-x\" aria-label={removeLabel} onClick={onRemove}>\n <IcX size={12} />\n </button>\n </span>\n );\n }\n if (onClick) {\n // trailing needs its own interactivity, and a control inside a <button> is invalid HTML the\n // browser un-nests unpredictably — so a clickable chip that carries one keeps the split form.\n if (trailing) {\n return (\n <span ref={ref} className={cls} title={title}>\n <button type=\"button\" className=\"uic-chip-press\" onClick={onClick} {...rest}>{body}</button>\n {trail}\n </span>\n );\n }\n return <button ref={ref} type=\"button\" className={cls} title={title} onClick={onClick} {...rest}>{body}</button>;\n }\n return (\n <span ref={ref} className={cls} title={title} {...rest}>\n {body}\n {trail}\n {onRemove ? (\n <button type=\"button\" className=\"uic-chip-x\" aria-label={removeLabel} onClick={onRemove}>\n <IcX size={12} />\n </button>\n ) : null}\n </span>\n );\n});\n","// Formatting helpers shared by components that display file metadata.\n\n/** A byte count as a person reads it. Null/undefined renders as nothing, not as \"0 B\" — an\n * unknown size is not a size of zero. */\nexport function bytesLabel(n) {\n if (n == null) return '';\n if (n < 1024) return `${n} B`;\n if (n < 1048576) return `${Math.round(n / 1024)} KB`;\n return `${(n / 1048576).toFixed(1)} MB`;\n}\n","// Voice input, using the recogniser the browser already has.\n//\n// Chrome, Edge and Safari ship SpeechRecognition, and it is exactly the feature — speak, get text\n// in the box. Where the API is absent, createDictation() returns null and the caller renders no\n// button at all. A disabled microphone labelled \"coming soon\" is a control that does nothing,\n// which is worse than its absence: it says the product has a capability it does not have. Three\n// of the four panels this package now serves shipped exactly that button; returning null is what\n// makes the honest version the easy one to write.\n//\n// Nothing here is agent- or product-specific, which is why it is a root export rather than part\n// of a transport: it turns speech into a string and stops.\n\nconst Impl = typeof window !== 'undefined'\n ? (window.SpeechRecognition || window.webkitSpeechRecognition)\n : null;\n\nexport function createDictation({ lang } = {}) {\n if (!Impl) return null;\n let rec = null;\n\n return {\n /** onText fires once per finished phrase, so the draft grows as you speak rather than being\n * rewritten from scratch on every interim guess. */\n start({ onText, onEnd, onError }) {\n this.stop();\n rec = new Impl();\n rec.lang = lang || navigator.language || 'en-US';\n rec.continuous = true;\n rec.interimResults = false;\n rec.onresult = (e) => {\n for (let i = e.resultIndex; i < e.results.length; i += 1) {\n if (!e.results[i].isFinal) continue;\n const text = String(e.results[i][0]?.transcript || '').trim();\n if (text) onText?.(text);\n }\n };\n // 'no-speech' and 'aborted' are the two ways a quiet or cancelled session ends. Neither is\n // a failure worth telling anyone about; both just stop.\n rec.onerror = (e) => {\n rec = null;\n if (e.error === 'no-speech' || e.error === 'aborted') onEnd?.();\n else onError?.(e.error || 'Dictation stopped.');\n };\n rec.onend = () => { rec = null; onEnd?.(); };\n try {\n rec.start();\n } catch (e) {\n rec = null;\n onError?.(e?.message || 'Dictation could not start.');\n }\n },\n\n stop() {\n if (!rec) return;\n const r = rec;\n rec = null;\n try { r.stop(); } catch { /* already stopped */ }\n },\n };\n}\n","// Fenced code block with language-aware syntax highlighting (highlight.js core).\n//\n// Consumers wire this into their markdown renderer's `pre` override (see the ChatPanel /\n// workbench MD_COMPONENTS): a ```mermaid fence keeps rendering as a diagram; every other fence\n// renders here. Design notes (same lazy pattern as the Mermaid block):\n// - highlight.js is LAZY-loaded (dynamic import) — the core plus exactly one small grammar\n// chunk per language actually used, never the full-language bundle. Until it loads the block\n// renders as plain <pre><code>, byte-identical geometry, so there is no layout shift.\n// - Highlighting is DEBOUNCED: while a fence is still streaming in token by token we render\n// plain text and re-arm the timer; the block highlights once it settles. hljs itself never\n// throws on partial input, the debounce just avoids re-lexing on every token.\n// - Unknown / missing language: NO auto-detect, render plain. Wrong-language colors are worse\n// than none.\n// - `gremlin` maps to the groovy grammar (Gremlin is a Groovy DSL — closest match).\n// - Colors are token-driven: .wbx-code maps hljs classes onto five --uic-code-* custom\n// properties (keyword/string/comment/number/function) with defaults tuned for the dark\n// code-block background. See styles/chat.css + README \"Theming\".\n// highlight.js must be a dependency of the CONSUMING app (the dynamic import resolves in its\n// bundler) — same rule as mermaid.\nimport React from 'react';\n\nlet _hljsPromise = null;\nfunction loadHljs() {\n if (!_hljsPromise) {\n _hljsPromise = import('highlight.js/lib/core').then((m) => m.default || m);\n }\n return _hljsPromise;\n}\n\n// One static dynamic-import per grammar so each becomes its own code-split chunk and only the\n// languages that actually appear in a conversation ever download.\nconst GRAMMARS = {\n javascript: () => import('highlight.js/lib/languages/javascript'),\n typescript: () => import('highlight.js/lib/languages/typescript'),\n python: () => import('highlight.js/lib/languages/python'),\n json: () => import('highlight.js/lib/languages/json'),\n bash: () => import('highlight.js/lib/languages/bash'),\n sql: () => import('highlight.js/lib/languages/sql'),\n java: () => import('highlight.js/lib/languages/java'),\n go: () => import('highlight.js/lib/languages/go'),\n rust: () => import('highlight.js/lib/languages/rust'),\n xml: () => import('highlight.js/lib/languages/xml'),\n css: () => import('highlight.js/lib/languages/css'),\n yaml: () => import('highlight.js/lib/languages/yaml'),\n groovy: () => import('highlight.js/lib/languages/groovy'),\n};\n\n// Fence-tag aliases → canonical grammar name.\nconst ALIASES = {\n js: 'javascript', jsx: 'javascript', mjs: 'javascript', cjs: 'javascript', node: 'javascript',\n ts: 'typescript', tsx: 'typescript',\n py: 'python', python3: 'python',\n sh: 'bash', shell: 'bash', zsh: 'bash', console: 'bash',\n html: 'xml', xhtml: 'xml', svg: 'xml',\n yml: 'yaml',\n golang: 'go',\n rs: 'rust',\n jsonc: 'json',\n postgres: 'sql', postgresql: 'sql', mysql: 'sql', plsql: 'sql',\n gremlin: 'groovy',\n};\n\nfunction canonicalLang(tag) {\n const t = String(tag || '').toLowerCase();\n if (!t) return null;\n const name = ALIASES[t] || t;\n return GRAMMARS[name] ? name : null;\n}\n\n// canonical name -> Promise<hljs | null> (null = load failed; stay plain forever, never retry-loop)\nconst _ready = new Map();\nfunction ensureLanguage(name) {\n if (!_ready.has(name)) {\n const p = Promise.all([loadHljs(), GRAMMARS[name]()])\n .then(([hljs, mod]) => {\n if (!hljs.getLanguage(name)) hljs.registerLanguage(name, mod.default || mod);\n return hljs;\n })\n .catch(() => null);\n _ready.set(name, p);\n }\n return _ready.get(name);\n}\n\nexport function CodeBlock(props) {\n const { code, language, className } = props;\n const src = String(code || '');\n const lang = canonicalLang(language);\n const [hl, setHl] = React.useState(null); // { src, html } — html valid only for exactly that src\n\n React.useEffect(() => {\n if (!lang || !src) return undefined;\n let cancelled = false;\n // Debounce: during streaming the fence grows every few ms — wait for a quiet gap, then\n // highlight the settled source. hljs output is fully HTML-escaped (safe to inject).\n const timer = setTimeout(() => {\n ensureLanguage(lang).then((hljs) => {\n if (!hljs || cancelled) return;\n try {\n const out = hljs.highlight(src, { language: lang, ignoreIllegals: true });\n if (!cancelled) setHl({ src, html: out.value });\n } catch {\n /* stay plain */\n }\n });\n }, 200);\n return () => { cancelled = true; clearTimeout(timer); };\n }, [src, lang]);\n\n const html = hl && hl.src === src ? hl.html : null;\n const label = String(language || '').toLowerCase();\n return (\n <pre className={'wbx-code' + (className ? ' ' + className : '')}>\n {label ? <span className=\"wbx-code-lang\" aria-hidden=\"true\">{label}</span> : null}\n {html != null\n ? <code className={'hljs language-' + label} dangerouslySetInnerHTML={{ __html: html }} />\n : <code className={label ? 'language-' + label : undefined}>{src}</code>}\n </pre>\n );\n}\n","// Drag-to-resize pane primitive — drag mechanics lifted from HarnessRouter's workbench\n// useHResize (iframe/text-selection neutralization included), extended with:\n// - min/max clamps (absolute px and/or a viewport fraction, e.g. 60vw)\n// - per-user width persistence (localStorage, storageKey)\n// - double-click the divider to reset to the default width\n// - axis: 'x' (default, side-by-side panes) or 'y' (stacked panes, e.g. an artifact preview\n// under a narrow chat column, where splitting sideways would leave neither half readable)\n//\n// Usage:\n// const pane = useResizablePane({ initial: 340, min: 320, maxFraction: 0.6,\n// fromRight: true, storageKey: 'cg.chat.w' });\n// <PaneResizer pane={pane} />\n// <aside style={{ flex: `0 0 ${pane.width}px` }}>…</aside>\nimport React, { useCallback, useRef, useState } from 'react';\n\nexport function useResizablePane(opts = {}) {\n const {\n initial = 380,\n min = 240,\n max = null, // absolute px cap (null = none)\n maxFraction = null, // viewport-width fraction cap, e.g. 0.6 for 60vw (null = none)\n fromRight = false, // divider sits on the pane's LEFT/TOP edge (dragging toward it shrinks)\n storageKey = null, // persist the chosen size per user (localStorage)\n axis = 'x', // 'x' = width (col-resize), 'y' = height (row-resize)\n } = opts;\n const vertical = axis === 'y';\n // One clamp, one drag, one persistence path for both orientations: the axis only decides which\n // pointer coordinate and which viewport dimension are read.\n const coord = (e) => (vertical ? e.clientY : e.clientX);\n const viewportExtent = () => (typeof window === 'undefined' ? 0 : (vertical ? window.innerHeight : window.innerWidth));\n const cursor = vertical ? 'row-resize' : 'col-resize';\n\n const clamp = useCallback((x) => {\n let hi = max ?? Infinity;\n if (maxFraction && typeof window !== 'undefined') hi = Math.min(hi, Math.round(viewportExtent() * maxFraction));\n return Math.min(hi, Math.max(min, x));\n }, [min, max, maxFraction, vertical]); // eslint-disable-line react-hooks/exhaustive-deps\n\n const [width, setWidth] = useState(() => {\n if (storageKey && typeof window !== 'undefined') {\n try {\n const n = parseInt(window.localStorage.getItem(storageKey) || '', 10);\n if (Number.isFinite(n)) return clamp(n);\n } catch { /* private mode */ }\n }\n return initial;\n });\n const widthRef = useRef(width);\n widthRef.current = width;\n\n const persist = useCallback((w) => {\n if (!storageKey) return;\n try { window.localStorage.setItem(storageKey, String(w)); } catch { /* private mode */ }\n }, [storageKey]);\n\n const onMouseDown = useCallback((e) => {\n e.preventDefault();\n const sx = coord(e), base = widthRef.current, dir = fromRight ? -1 : 1;\n // While dragging, neutralize iframes/text-selection so an embedded preview can't swallow\n // mousemove/mouseup (which would strand the drag).\n document.body.classList.add('uic-resizing');\n const move = (ev) => setWidth(clamp(base + dir * (coord(ev) - sx)));\n const up = () => {\n window.removeEventListener('mousemove', move); window.removeEventListener('mouseup', up);\n document.body.style.cursor = ''; document.body.classList.remove('uic-resizing');\n persist(widthRef.current);\n };\n window.addEventListener('mousemove', move); window.addEventListener('mouseup', up);\n document.body.style.cursor = cursor;\n }, [clamp, fromRight, persist, vertical]); // eslint-disable-line react-hooks/exhaustive-deps\n\n // Touch / pen drags (pointer events). Mouse keeps the mousedown path above\n // untouched — this handler ignores mouse pointers so the two never double up.\n const onPointerDown = useCallback((e) => {\n if (e.pointerType === 'mouse') return;\n e.preventDefault();\n const sx = coord(e), base = widthRef.current, dir = fromRight ? -1 : 1;\n const el = e.currentTarget;\n document.body.classList.add('uic-resizing');\n try { el.setPointerCapture(e.pointerId); } catch { /* unsupported */ }\n const move = (ev) => setWidth(clamp(base + dir * (coord(ev) - sx)));\n const up = () => {\n el.removeEventListener('pointermove', move);\n el.removeEventListener('pointerup', up);\n el.removeEventListener('pointercancel', up);\n document.body.classList.remove('uic-resizing');\n persist(widthRef.current);\n };\n el.addEventListener('pointermove', move);\n el.addEventListener('pointerup', up);\n el.addEventListener('pointercancel', up);\n }, [clamp, fromRight, persist, vertical]); // eslint-disable-line react-hooks/exhaustive-deps\n\n // Keyboard resizing: move the pane edge by a signed px delta (clamped,\n // persisted). Positive delta = wider pane.\n const nudge = useCallback((delta) => {\n const w = clamp(widthRef.current + delta);\n setWidth(w);\n persist(w);\n }, [clamp, persist]);\n\n const reset = useCallback(() => {\n setWidth(initial);\n if (storageKey) { try { window.localStorage.removeItem(storageKey); } catch { /* private mode */ } }\n }, [initial, storageKey]);\n\n // Resolved clamp bounds for aria-valuemin/max on the divider.\n let maxResolved = max ?? null;\n if (maxFraction && typeof window !== 'undefined') {\n const frac = Math.round(viewportExtent() * maxFraction);\n maxResolved = maxResolved == null ? frac : Math.min(maxResolved, frac);\n }\n\n return { width, onMouseDown, onPointerDown, nudge, reset, min, max: maxResolved, fromRight, axis };\n}\n\n/** The grabbable divider (comfortable 7px hit area, col-resize cursor, dblclick = reset).\n * Keyboard: focus it (Tab) and use ArrowLeft/ArrowRight to move the divider\n * in 24px steps (Shift for 96px); touch drags work through pointer events.\n * Mouse drag and double-click reset behave exactly as before. */\nexport function PaneResizer(props) {\n const { pane, className, title = 'Drag to resize (double-click to reset)' } = props;\n const vertical = pane.axis === 'y';\n const onKeyDown = (e) => {\n const keys = vertical ? ['ArrowUp', 'ArrowDown'] : ['ArrowLeft', 'ArrowRight'];\n if (!keys.includes(e.key)) return;\n if (!pane.nudge) return;\n e.preventDefault();\n const step = e.shiftKey ? 96 : 24;\n // Arrows move the SEPARATOR: for a trailing pane (divider on its leading\n // edge) the forward key shrinks the pane; for a leading pane it grows it.\n const forward = e.key === 'ArrowRight' || e.key === 'ArrowDown';\n const dir = (forward ? 1 : -1) * (pane.fromRight ? -1 : 1);\n pane.nudge(dir * step);\n };\n return (\n <div\n className={className ?? (vertical ? 'uic-hresize' : 'uic-vresize')}\n role=\"separator\"\n // The separator's own orientation: a stacked (axis 'y') split is divided by a HORIZONTAL bar.\n aria-orientation={vertical ? 'horizontal' : 'vertical'}\n aria-label={title}\n aria-valuenow={Math.round(pane.width)}\n aria-valuemin={pane.min != null ? Math.round(pane.min) : undefined}\n aria-valuemax={pane.max != null ? Math.round(pane.max) : undefined}\n tabIndex={0}\n title={title}\n onMouseDown={pane.onMouseDown}\n onPointerDown={pane.onPointerDown}\n onKeyDown={onKeyDown}\n onDoubleClick={pane.reset}\n />\n );\n}\n","// TaskList — the master list beside an agent conversation: one row per run/session, with\n// live status, text filter, status filter, cursor pagination on scroll, and optional delete.\n//\n// Transport-agnostic, like everything else here. The consumer supplies `fetchPage`, which\n// returns `{ items, cursor }` for a given cursor ('' = first page). ReifyUI never decides how\n// you authenticate or where your API lives; it only decides how the result looks and behaves.\n//\n// Pagination model: the FIRST page is refetched on `refreshNonce` so live runs stay current,\n// while older pages accumulate in a tail. Merging de-duplicates by id, so a run that moves\n// between pages while you scroll cannot appear twice.\n//\n// Slots:\n// header node rendered above the filter row (e.g. a harness selector)\n// onNew when provided, renders the \"New task\" action\n// onDelete when provided, each row gets a delete affordance (confirm is the consumer's job\n// if it wants one — this only calls back)\n// renderMeta (item) => node, replaces the default right-hand status/time cell\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\n\nconst STATUS_GROUPS = {\n all: () => true,\n working: (s) => ['running', 'starting', 'queued', 'in_progress'].includes(s),\n done: (s) => ['done', 'completed'].includes(s),\n failed: (s) => ['failed', 'cancelled', 'incomplete', 'error'].includes(s),\n};\n\n/** Coarse bucket for the status dot — keeps colour logic in one place. */\nexport function taskStatusGroup(status) {\n const s = String(status || '').toLowerCase();\n for (const k of ['working', 'done', 'failed']) if (STATUS_GROUPS[k](s)) return k;\n return 'idle';\n}\n\nfunction relTime(ts) {\n const n = Number(ts) || 0;\n if (!n) return '';\n // Accept seconds or milliseconds — callers differ and a 1000x error is a silent wrong label.\n const ms = n > 1e12 ? n : n * 1000;\n const d = Math.max(0, Date.now() - ms) / 1000;\n if (d < 60) return 'just now';\n if (d < 3600) return `${Math.floor(d / 60)}m ago`;\n if (d < 86400) return `${Math.floor(d / 3600)}h ago`;\n return `${Math.floor(d / 86400)}d ago`;\n}\n\nexport function TaskList({\n fetchPage,\n selected,\n onSelect,\n onNew,\n onDelete,\n header,\n renderMeta,\n refreshNonce = 0,\n emptyLabel = 'No tasks yet',\n newLabel = 'New task',\n idKey = 'id',\n titleKey = 'title',\n statusKey = 'status',\n timeKey = 'updated_at',\n}) {\n const [head, setHead] = useState(null); // null = loading, [] = loaded-empty\n const [tail, setTail] = useState([]);\n const [cursor, setCursor] = useState('');\n const [loadingMore, setLoadingMore] = useState(false);\n const [q, setQ] = useState('');\n const [statusFilter, setStatusFilter] = useState('all');\n const alive = useRef(true);\n\n useEffect(() => () => { alive.current = false; }, []);\n\n // First page — refetched whenever the consumer bumps refreshNonce (poll, SSE, post-send).\n useEffect(() => {\n let ok = true;\n Promise.resolve(fetchPage(''))\n .then((r) => {\n if (!ok) return;\n setHead(Array.isArray(r?.items) ? r.items : []);\n setCursor(r?.cursor || '');\n })\n .catch(() => { if (ok) setHead((p) => p ?? []); }); // keep what we had; don't blank the list\n return () => { ok = false; };\n }, [fetchPage, refreshNonce]);\n\n const loadMore = useCallback(() => {\n if (!cursor || loadingMore) return;\n setLoadingMore(true);\n Promise.resolve(fetchPage(cursor))\n .then((r) => {\n if (!alive.current) return;\n if (Array.isArray(r?.items)) setTail((t) => [...t, ...r.items]);\n setCursor(r?.cursor || '');\n })\n .catch(() => { /* keep the cursor so the next scroll retries */ })\n .finally(() => { if (alive.current) setLoadingMore(false); });\n }, [cursor, loadingMore, fetchPage]);\n\n const items = useMemo(() => {\n const h = head || [];\n const seen = new Set(h.map((x) => x?.[idKey]));\n return [...h, ...tail.filter((t) => !seen.has(t?.[idKey]))];\n }, [head, tail, idKey]);\n\n const shown = useMemo(() => {\n const needle = q.trim().toLowerCase();\n const pass = STATUS_GROUPS[statusFilter] || STATUS_GROUPS.all;\n return items.filter((it) => {\n if (!pass(String(it?.[statusKey] || '').toLowerCase())) return false;\n if (!needle) return true;\n return String(it?.[titleKey] || '').toLowerCase().includes(needle);\n });\n }, [items, q, statusFilter, statusKey, titleKey]);\n\n const onScroll = (e) => {\n const el = e.currentTarget;\n if (el.scrollTop + el.clientHeight > el.scrollHeight - 140) loadMore();\n };\n\n return (\n <div className=\"rui-tasks\">\n {header ? <div className=\"rui-tasks-header\">{header}</div> : null}\n {onNew ? (\n <button type=\"button\" className=\"rui-tasks-new\" onClick={onNew}>+ {newLabel}</button>\n ) : null}\n\n <div className=\"rui-tasks-filters\">\n <input\n className=\"rui-tasks-search\"\n value={q}\n placeholder=\"Filter tasks…\"\n onChange={(e) => setQ(e.target.value)}\n aria-label=\"Filter tasks\"\n />\n <select\n className=\"rui-tasks-status\"\n value={statusFilter}\n onChange={(e) => setStatusFilter(e.target.value)}\n aria-label=\"Filter by status\"\n >\n <option value=\"all\">All</option>\n <option value=\"working\">Working</option>\n <option value=\"done\">Done</option>\n <option value=\"failed\">Failed</option>\n </select>\n </div>\n\n <div className=\"rui-tasks-list\" onScroll={onScroll}>\n {head === null ? (\n <div className=\"rui-tasks-empty\">Loading…</div>\n ) : shown.length === 0 ? (\n <div className=\"rui-tasks-empty\">{items.length ? 'No matching tasks' : emptyLabel}</div>\n ) : (\n shown.map((it) => {\n const id = it?.[idKey];\n const group = taskStatusGroup(it?.[statusKey]);\n return (\n <div\n key={id}\n className={`rui-task${id === selected ? ' is-selected' : ''}`}\n onClick={() => onSelect?.(id)}\n role=\"button\"\n tabIndex={0}\n onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') onSelect?.(id); }}\n >\n <div className=\"rui-task-main\">\n <div className=\"rui-task-title\">{it?.[titleKey] || 'Untitled task'}</div>\n <div className=\"rui-task-meta\">\n {renderMeta ? renderMeta(it) : (\n <>\n <span className={`rui-task-dot is-${group}`} />\n <span className=\"rui-task-status\">{it?.[statusKey] || ''}</span>\n {it?.[timeKey] ? <span className=\"rui-task-time\">{relTime(it[timeKey])}</span> : null}\n </>\n )}\n </div>\n </div>\n {onDelete ? (\n <button\n type=\"button\"\n className=\"rui-task-del\"\n aria-label=\"Delete task\"\n onClick={(e) => { e.stopPropagation(); onDelete(it); }}\n >×</button>\n ) : null}\n </div>\n );\n })\n )}\n {loadingMore ? <div className=\"rui-tasks-empty\">Loading more…</div> : null}\n </div>\n </div>\n );\n}\n","// Dialog — in-app replacements for window.alert / window.confirm / window.prompt.\n//\n// Agentic surfaces ask the user things constantly: confirm a destructive tool call, name a\n// workspace, acknowledge a failure. Native browser popups block the event loop, cannot be\n// styled, and look like a security warning rather than part of your product. This gives the\n// same call-site ergonomics — an awaited call that returns a value — without any of that.\n//\n// Usage:\n// 1. Mount <DialogHost> once, wrapping your app.\n// 2. Anywhere underneath:\n//\n// const { confirm, prompt, alert } = useDialog();\n//\n// if (await confirm({ title: 'Delete task', message: 'This cannot be undone.',\n// destructive: true, confirmLabel: 'Delete' })) { … }\n//\n// const name = await prompt({ title: 'New workspace', label: 'Name',\n// validate: (v) => v.length < 40 ? null : 'Too long' });\n// // string, or null when cancelled\n//\n// await alert({ title: 'Run failed', message: err, variant: 'error' });\n//\n// Dialogs stack rather than replace: a second caller layers on top instead of trampling the\n// first, because two independent code paths asking at once is normal in a streaming UI.\n//\n// Styling is one stylesheet away — import 'reifyui/styles/dialog.css' — and every colour is a\n// themeable variable, so it inherits the host app's palette.\nimport {\n createContext, useCallback, useContext, useEffect,\n useId, useMemo, useRef, useState,\n} from 'react';\nimport { createPortal } from 'react-dom';\nimport { useOverlayEscape } from './overlay.js';\n\nconst DialogCtx = createContext(null);\n\nconst LABELS = {\n en: { confirm: 'Confirm', cancel: 'Cancel', ok: 'OK', create: 'Create', required: 'Please enter a value' },\n zh: { confirm: '确认', cancel: '取消', ok: '好的', create: '创建', required: '请输入内容' },\n};\n\nlet _idSeq = 0;\n\n/**\n * Mount once near the root. `locale` picks a built-in label set ('en' | 'zh'); `labels`\n * overrides individual strings for any other language.\n */\nexport function DialogHost({ children, locale = 'en', labels }) {\n const [stack, setStack] = useState([]);\n const t = useMemo(\n () => ({ ...(LABELS[locale] || LABELS.en), ...(labels || {}) }),\n [locale, labels],\n );\n\n const open = useCallback((spec) => new Promise((resolve) => {\n setStack((s) => [...s, { id: `dlg_${++_idSeq}`, spec, resolve }]);\n }), []);\n\n const close = useCallback((id, value) => {\n setStack((s) => {\n const target = s.find((d) => d.id === id);\n if (target) target.resolve(value);\n return s.filter((d) => d.id !== id);\n });\n }, []);\n\n const ctx = useMemo(() => ({\n confirm: (opts) => open({ kind: 'confirm', ...opts }),\n prompt: (opts) => open({ kind: 'prompt', ...opts }),\n alert: (opts) => open({ kind: 'alert', ...opts }),\n create: (opts) => open({ kind: 'create', ...opts }),\n labels: t,\n }), [open, t]);\n\n return (\n <DialogCtx.Provider value={ctx}>\n {children}\n {stack.length > 0 && typeof document !== 'undefined' && createPortal(\n <div className=\"rui-dlg-root\" role=\"presentation\">\n {stack.map((d, i) => (\n <DialogShell key={d.id} dialog={d} isTop={i === stack.length - 1} onClose={close} t={t} />\n ))}\n </div>,\n document.body,\n )}\n </DialogCtx.Provider>\n );\n}\n\nexport function useDialog() {\n const ctx = useContext(DialogCtx);\n // Fail loudly rather than silently no-op: a confirm() that always resolves false would skip\n // the user's decision entirely, which is worse than a crash in development.\n if (!ctx) throw new Error('useDialog() called outside <DialogHost>');\n return ctx;\n}\n\n// A cancelled prompt/create yields null (no value); a cancelled confirm/alert yields false.\nconst cancelValue = (kind) => ((kind === 'prompt' || kind === 'create') ? null : false);\n\nfunction DialogShell({ dialog, isTop, onClose, t }) {\n const { id, spec } = dialog;\n const ref = useRef(null);\n const titleId = useId();\n\n // Escape goes through the package's shared overlay stack rather than a listener of our own, so\n // a Modal or Popover opened ON TOP of this dialog answers the key and this one does not.\n const escape = useCallback(() => onClose(id, cancelValue(spec.kind)), [id, onClose, spec.kind]);\n useOverlayEscape(isTop, escape);\n\n // Focus the field if there is one, else the primary action — so Enter does the obvious thing.\n useEffect(() => {\n if (!isTop || !ref.current) return;\n const el = ref.current.querySelector('input, textarea')\n || ref.current.querySelector('.rui-dlg-primary')\n || ref.current.querySelector('button');\n el?.focus();\n }, [isTop]);\n\n const onBackdrop = (e) => {\n if (e.target === e.currentTarget && isTop) onClose(id, cancelValue(spec.kind));\n };\n\n const done = (v) => onClose(id, v);\n\n return (\n <div className=\"rui-dlg-backdrop\" onClick={onBackdrop}>\n <div\n ref={ref}\n role=\"dialog\"\n aria-modal=\"true\"\n aria-labelledby={spec.title ? titleId : undefined}\n className={`rui-dlg-card${spec.kind === 'create' ? ' is-wide' : ''}`}\n >\n {spec.kind === 'alert' && <AlertBody spec={spec} onClose={done} t={t} titleId={titleId} />}\n {spec.kind === 'confirm' && <ConfirmBody spec={spec} onClose={done} t={t} titleId={titleId} />}\n {spec.kind === 'prompt' && <PromptBody spec={spec} onClose={done} t={t} titleId={titleId} />}\n {spec.kind === 'create' && <CreateBody spec={spec} onClose={done} t={t} titleId={titleId} />}\n </div>\n </div>\n );\n}\n\nfunction Header({ title, variant, titleId }) {\n if (!title) return null;\n return (\n <div className={`rui-dlg-h${variant ? ` is-${variant}` : ''}`}>\n <div className=\"rui-dlg-title\" id={titleId}>{title}</div>\n </div>\n );\n}\n\nconst Footer = ({ children }) => <div className=\"rui-dlg-f\">{children}</div>;\n\nfunction AlertBody({ spec, onClose, t, titleId }) {\n return (\n <>\n <Header title={spec.title} variant={spec.variant} titleId={titleId} />\n <div className=\"rui-dlg-b\">\n {spec.message ? <div className=\"rui-dlg-msg\">{spec.message}</div> : null}\n </div>\n <Footer>\n <button type=\"button\" className=\"rui-dlg-btn rui-dlg-primary\" onClick={() => onClose(true)}>\n {spec.confirmLabel || t.ok}\n </button>\n </Footer>\n </>\n );\n}\n\nfunction ConfirmBody({ spec, onClose, t, titleId }) {\n const destructive = !!spec.destructive;\n return (\n <>\n <Header title={spec.title} variant={destructive ? 'destructive' : spec.variant} titleId={titleId} />\n <div className=\"rui-dlg-b\">\n {spec.message ? <div className=\"rui-dlg-msg\">{spec.message}</div> : null}\n </div>\n <Footer>\n <button type=\"button\" className=\"rui-dlg-btn rui-dlg-secondary\" onClick={() => onClose(false)}>\n {spec.cancelLabel || t.cancel}\n </button>\n <button\n type=\"button\"\n className={`rui-dlg-btn rui-dlg-primary${destructive ? ' is-destructive' : ''}`}\n onClick={() => onClose(true)}\n >\n {spec.confirmLabel || t.confirm}\n </button>\n </Footer>\n </>\n );\n}\n\nfunction PromptBody({ spec, onClose, t, titleId }) {\n const [value, setValue] = useState(spec.defaultValue ?? '');\n const [err, setErr] = useState(null);\n const inputId = useId();\n const Field = spec.multiline ? 'textarea' : 'input';\n\n const submit = () => {\n const invalid = spec.validate?.(value);\n if (invalid) { setErr(String(invalid)); return; }\n if (spec.required !== false && !String(value).trim()) { setErr(t.required); return; }\n onClose(String(value));\n };\n\n return (\n <>\n <Header title={spec.title} variant={spec.variant} titleId={titleId} />\n <div className=\"rui-dlg-b\">\n {spec.message ? <div className=\"rui-dlg-msg\">{spec.message}</div> : null}\n {spec.label ? <label className=\"rui-dlg-label\" htmlFor={inputId}>{spec.label}</label> : null}\n <Field\n id={inputId}\n className={`rui-dlg-input${err ? ' is-err' : ''}`}\n type={spec.multiline ? undefined : (spec.inputType || 'text')}\n rows={spec.multiline ? (spec.rows || 4) : undefined}\n value={value}\n placeholder={spec.placeholder || ''}\n onChange={(e) => { setValue(e.target.value); if (err) setErr(null); }}\n onKeyDown={(e) => {\n if (e.key === 'Enter' && !e.shiftKey && !spec.multiline) { e.preventDefault(); submit(); }\n }}\n autoComplete=\"off\"\n spellCheck=\"false\"\n />\n {err ? <div className=\"rui-dlg-err\">{err}</div> : null}\n {!err && spec.help ? <div className=\"rui-dlg-help\">{spec.help}</div> : null}\n </div>\n <Footer>\n <button type=\"button\" className=\"rui-dlg-btn rui-dlg-secondary\" onClick={() => onClose(null)}>\n {spec.cancelLabel || t.cancel}\n </button>\n <button type=\"button\" className=\"rui-dlg-btn rui-dlg-primary\" onClick={submit}>\n {spec.confirmLabel || t.confirm}\n </button>\n </Footer>\n </>\n );\n}\n\n// Pick-a-type-then-name, for \"New …\" flows where the thing being created has variants. The\n// caller supplies `types: [{ kind, label, color, icon, choices? }]`, so this stays icon-library\n// agnostic. A type may offer a starting point (`choices: { label, load, defaultId }`, where\n// load() resolves to [{ id, name, description? }], typically templates); the list is fetched\n// when the type is first selected and the chosen id rides along as `choice`.\n// Resolves to { kind, name, choice? } or null.\nfunction CreateBody({ spec, onClose, t, titleId }) {\n const types = spec.types || [];\n const [kind, setKind] = useState(spec.defaultKind || types[0]?.kind || '');\n const [value, setValue] = useState(spec.defaultValue ?? '');\n const [err, setErr] = useState(null);\n const [lists, setLists] = useState({});\n const inputId = useId();\n const sel = types.find((x) => x.kind === kind) || types[0] || {};\n\n useEffect(() => {\n const ch = sel.choices;\n if (!ch || lists[kind]) return undefined;\n let dead = false;\n setLists((m) => ({ ...m, [kind]: { status: 'loading', items: [], chosen: ch.defaultId ?? null } }));\n Promise.resolve().then(() => ch.load()).then((items) => {\n if (dead) return;\n const arr = Array.isArray(items) ? items : [];\n const chosen = arr.some((it) => it.id === ch.defaultId) ? ch.defaultId : (arr[0]?.id ?? ch.defaultId ?? null);\n setLists((m) => ({ ...m, [kind]: { status: 'ready', items: arr, chosen } }));\n }).catch(() => {\n if (dead) return;\n setLists((m) => ({ ...m, [kind]: { status: 'failed', items: [], chosen: ch.defaultId ?? null } }));\n });\n return () => { dead = true; };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [kind]);\n const pick = (id) => setLists((m) => ({ ...m, [kind]: { ...m[kind], chosen: id } }));\n\n const submit = () => {\n if (spec.required !== false && !String(value).trim()) { setErr(t.required); return; }\n const entry = sel.choices ? lists[kind] : null;\n onClose({ kind, name: String(value).trim(), ...(entry ? { choice: entry.chosen } : {}) });\n };\n\n return (\n <>\n <Header title={spec.title} titleId={titleId} />\n <div className=\"rui-dlg-b\">\n {types.length > 0 ? (\n <div className=\"rui-dlg-typegrid\">\n {types.map((ty) => (\n <button\n key={ty.kind}\n type=\"button\"\n className={`rui-dlg-type${ty.kind === kind ? ' is-on' : ''}`}\n onClick={() => setKind(ty.kind)}\n >\n {ty.icon ? (\n <span className=\"rui-dlg-type-ic\" style={ty.color ? { color: ty.color, background: `${ty.color}1f` } : undefined}>\n {ty.icon}\n </span>\n ) : null}\n <span className=\"rui-dlg-type-lbl\">{ty.label}</span>\n </button>\n ))}\n </div>\n ) : null}\n <label className=\"rui-dlg-label\" htmlFor={inputId}>\n {spec.label || `${sel.label || 'Item'} name`}\n </label>\n <input\n id={inputId}\n className={`rui-dlg-input${err ? ' is-err' : ''}`}\n value={value}\n placeholder={spec.placeholder || 'Untitled'}\n onChange={(e) => { setValue(e.target.value); if (err) setErr(null); }}\n onKeyDown={(e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); submit(); } }}\n autoComplete=\"off\"\n spellCheck=\"false\"\n />\n {err ? <div className=\"rui-dlg-err\">{err}</div> : null}\n {sel.choices ? <ChoiceList label={sel.choices.label} entry={lists[kind]} onPick={pick} /> : null}\n </div>\n <Footer>\n <button type=\"button\" className=\"rui-dlg-btn rui-dlg-secondary\" onClick={() => onClose(null)}>\n {spec.cancelLabel || t.cancel}\n </button>\n <button type=\"button\" className=\"rui-dlg-btn rui-dlg-primary\" onClick={submit}>\n {spec.confirmLabel || t.create}\n </button>\n </Footer>\n </>\n );\n}\n\n// The starting-point list under the name: one row per choice, the chosen one marked; scrolls\n// past a handful so the dialog keeps its height on a phone.\nfunction ChoiceList({ label, entry, onPick }) {\n const labelId = useId();\n const status = entry?.status || 'loading';\n return (\n <div className=\"rui-dlg-choices\" role=\"radiogroup\" aria-labelledby={labelId}>\n <div className=\"rui-dlg-label\" id={labelId}>{label}</div>\n {status === 'loading' ? <div className=\"rui-dlg-help\">Loading</div> : null}\n {status === 'failed' ? <div className=\"rui-dlg-help\">The list could not be loaded. The default will be used.</div> : null}\n {status === 'ready' && entry.items.length > 0 ? (\n <div className=\"rui-dlg-choice-list\">\n {entry.items.map((it) => {\n const on = it.id === entry.chosen;\n return (\n <button key={it.id} type=\"button\" role=\"radio\" aria-checked={on}\n className={`rui-dlg-choice${on ? ' is-on' : ''}`} onClick={() => onPick(it.id)}>\n <span className=\"rui-dlg-choice-dot\" aria-hidden=\"true\" />\n <span className=\"rui-dlg-choice-text\">\n <span className=\"rui-dlg-choice-name\">{it.name}</span>\n {it.description ? <span className=\"rui-dlg-choice-desc\">{it.description}</span> : null}\n </span>\n </button>\n );\n })}\n </div>\n ) : null}\n </div>\n );\n}\n","// One Escape key, one stack.\n//\n// The package now has three things that float above the page — the dialog host, Modal and\n// Popover — and each of them wanting its own document keydown listener is how Escape ends up\n// closing two of them at once. They register here instead: the LAST one opened owns Escape, and\n// nothing below it hears the key.\n//\n// Deliberately not a React context: a Popover inside a Modal inside a dialog is a legitimate\n// arrangement, and the ordering that matters is the order they OPENED in, which is exactly what\n// an array push/splice records. A context would order them by tree position instead.\n//\n// Internal to the package (not exported from the root): a consumer that wants this behaviour\n// gets it by using the overlay components, not by wiring the stack itself.\nimport { useEffect } from 'react';\n\nconst stack = [];\nlet listening = false;\n\nfunction onKey(e) {\n if (e.key !== 'Escape') return;\n const top = stack[stack.length - 1];\n if (!top) return;\n e.preventDefault();\n top.onEscape?.();\n}\n\nfunction listen() {\n if (listening || typeof document === 'undefined') return;\n document.addEventListener('keydown', onKey);\n listening = true;\n}\n\nfunction unlisten() {\n if (!listening || stack.length) return;\n document.removeEventListener('keydown', onKey);\n listening = false;\n}\n\n/** Push while mounted-and-open. Returns the dispose. `onEscape` is read live, so a handler that\n * closes over changing state does not have to re-register. */\nexport function pushOverlay(entry) {\n stack.push(entry);\n listen();\n return () => {\n const i = stack.indexOf(entry);\n if (i >= 0) stack.splice(i, 1);\n unlisten();\n };\n}\n\n/**\n * Escape closes THIS overlay only while it is the top-most one.\n * `active` is false for an overlay that is closed, or that is not the top of its own local stack\n * (the dialog host layers several at once and only the last should answer).\n */\nexport function useOverlayEscape(active, onEscape) {\n useEffect(() => {\n if (!active) return undefined;\n // The entry object is stable for the life of this registration; onEscape is captured with it,\n // and the effect re-runs whenever the caller's handler identity changes.\n return pushOverlay({ onEscape });\n }, [active, onEscape]);\n}\n","// Shared product auth client — a thin client over the AgentStudio engine's\n// /v1/auth endpoints, extracted from ContextualGraph. Product apps configure\n// it ONCE at boot:\n//\n// configureAuth({ product: 'flowness', engine: ENGINE_URL, loginHash: '#/login' })\n//\n// The JWT is the source of truth; the decoded principal (member / orgs /\n// active org) is stored alongside it in localStorage under\n// `<product>.session`. Stateless on the server side: every request just\n// carries the Bearer token. All functions below read the live config, so\n// call order (configure first) is the only contract.\n/* eslint-env browser */\n\nconst _cfg = {\n // Same-origin. A product that forgets to configure gets the working default rather than the\n // engine's Azure FQDN, which no browser may call — its ingress admits only the VM that fronts\n // these apps, so a direct call 403s and reads as \"Failed to fetch\".\n engine: '/engine',\n product: '',\n loginHash: '#/login',\n};\n\nexport function configureAuth(cfg) {\n Object.assign(_cfg, cfg);\n if (!_cfg.product) throw new Error('configureAuth: product is required');\n}\n\nexport function authConfig() { return { ..._cfg }; }\n\nfunction sessionKey() { return `${_cfg.product}.session`; }\n\n/** Fired on every session write so chrome holding a snapshot can re-read. */\nexport const SESSION_EVENT = 'ui-core:session';\n\nexport function getSession() {\n try {\n const raw = window.localStorage.getItem(sessionKey());\n return raw ? JSON.parse(raw) : null;\n } catch {\n return null;\n }\n}\n\nfunction setSession(s) {\n window.localStorage.setItem(sessionKey(), JSON.stringify(s));\n window.dispatchEvent(new CustomEvent(SESSION_EVENT));\n}\n\nexport function clearSession() {\n window.localStorage.removeItem(sessionKey());\n window.dispatchEvent(new CustomEvent(SESSION_EVENT));\n}\n\nexport function getToken() {\n return getSession()?.token ?? null;\n}\n\nexport function isAuthed() {\n const s = getSession();\n return !!(s?.token && s?.orgId);\n}\n\nasync function readError(res) {\n try {\n const body = await res.json();\n return typeof body?.detail === 'string' ? body.detail : `request failed (${res.status})`;\n } catch {\n return `request failed (${res.status})`;\n }\n}\n\nfunction toSession(body) {\n return {\n token: body.token,\n member: body.member,\n orgs: body.orgs ?? [],\n orgId: body.org_id ?? null,\n };\n}\n\nasync function authPost(path, body, token = null) {\n const headers = { 'content-type': 'application/json' };\n if (token) headers.authorization = `Bearer ${token}`;\n const res = await fetch(`${_cfg.engine}${path}`, {\n method: 'POST',\n headers,\n body: body ? JSON.stringify(body) : undefined,\n });\n if (!res.ok) throw new Error(await readError(res));\n return res.json();\n}\n\nexport async function login(email, password) {\n const s = toSession(await authPost('/v1/auth/login', { email, password, product: _cfg.product }));\n setSession(s);\n return s;\n}\n\nexport async function register(email, password, name = '') {\n const s = toSession(await authPost('/v1/auth/register', { email, password, name, product: _cfg.product }));\n setSession(s);\n return s;\n}\n\nexport async function googleSignIn(credential) {\n const s = toSession(await authPost('/v1/auth/google', { credential, product: _cfg.product }));\n setSession(s);\n return s;\n}\n\n// Exchange a Microsoft (Entra) id token for a session, as googleSignIn does\n// with Google's. The engine answers a refusal with a sentence to show as is:\n// a personal account, a disabled member, or sign-in not configured.\nexport async function microsoftSignIn(credential) {\n const s = toSession(await authPost('/v1/auth/microsoft', { credential, product: _cfg.product }));\n setSession(s);\n return s;\n}\n\nexport async function requestPasswordReset(email) {\n await fetch(`${_cfg.engine}/v1/auth/request-password-reset`, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ email, product: _cfg.product }),\n });\n}\n\n/** Re-mint an org-scoped token for the chosen org. */\nexport async function switchOrg(orgId) {\n const current = getSession();\n if (!current) throw new Error('not authenticated');\n const body = await authPost('/v1/auth/switch-org', { org_id: orgId }, current.token);\n const next = { ...current, token: body.token, orgId: body.org_id };\n setSession(next);\n return next;\n}\n\n/** Slide the session: swap the still valid token for a fresh full TTL one. */\nexport async function refreshToken() {\n const cur = getSession();\n if (!cur?.token) return false;\n try {\n const res = await fetch(`${_cfg.engine}/v1/auth/refresh`, {\n method: 'POST',\n headers: { authorization: `Bearer ${cur.token}` },\n });\n if (res.status === 401) { handleAuthExpired(); return false; }\n if (!res.ok) return false;\n const body = await res.json();\n const now = getSession();\n if (body?.token && now) setSession({ ...now, token: body.token });\n return true;\n } catch {\n return false; // offline, keep the session and retry later\n }\n}\n\nlet redirecting = false;\n/** The token is dead: clear the session and land on the login route. */\nexport function handleAuthExpired() {\n if (redirecting) return;\n redirecting = true;\n clearSession();\n window.location.hash = _cfg.loginHash;\n setTimeout(() => { redirecting = false; }, 500);\n}\n\nexport function logout() {\n clearSession();\n window.location.hash = _cfg.loginHash;\n}\n\n/** fetch() with the Bearer token; a 401 fails closed into the login route. */\nexport async function authFetch(url, init = {}) {\n const headers = new Headers(init.headers);\n const token = getToken();\n if (token) headers.set('authorization', `Bearer ${token}`);\n const res = await fetch(url, { ...init, headers });\n if (res.status === 401) handleAuthExpired();\n return res;\n}\n\n/** GET the org's credit balance from the engine billing plane. */\nexport async function fetchBalance() {\n const res = await authFetch(`${_cfg.engine}/v1/billing/balance`);\n if (!res.ok) throw new Error(await readError(res));\n return res.json();\n}\n","// The complete sign-in unit (modeled on the HarnessRouter login screen),\n// extracted from ContextualGraph: brand mark on top, email + password with\n// the sign in button, Google SSO below, then the register / forgot password\n// links. Product-agnostic: the caller passes its brand node (`brand`) and\n// product display name (`productName`); auth calls ride the shared client\n// (configureAuth must have run at boot).\nimport { useState } from 'react';\nimport {\n login, register, googleSignIn, microsoftSignIn, requestPasswordReset, switchOrg,\n} from './client.js';\nimport { GoogleButton, GOOGLE_ENABLED } from './GoogleButton.jsx';\nimport { MicrosoftButton, MICROSOFT_ENABLED } from './MicrosoftButton.jsx';\n\nexport function AuthForm({ onDone, subtitle, brand = null, productName = '' }) {\n const [mode, setMode] = useState('signin'); // signin | register | forgot\n const [email, setEmail] = useState('');\n const [password, setPassword] = useState('');\n const [name, setName] = useState('');\n const [err, setErr] = useState('');\n const [busy, setBusy] = useState(false);\n const [choices, setChoices] = useState(null); // orgs, when the account has more than one\n const [resetSent, setResetSent] = useState(false);\n\n async function enter(orgId) {\n const session = await switchOrg(orgId);\n onDone(session);\n }\n\n // Route a freshly authenticated session: straight in, or via the org picker.\n async function afterAuth(session) {\n if (session.orgId) onDone(session);\n else if (session.orgs.length === 1) await enter(session.orgs[0].id);\n else if (session.orgs.length > 1) setChoices(session.orgs);\n else setErr('This account is not a member of any organization yet.');\n }\n\n async function submit(e) {\n e.preventDefault();\n setErr('');\n setBusy(true);\n try {\n if (mode === 'forgot') {\n await requestPasswordReset(email.trim());\n setResetSent(true);\n } else {\n const s = mode === 'register'\n ? await register(email.trim(), password, name.trim())\n : await login(email.trim(), password);\n await afterAuth(s);\n }\n } catch (ex) {\n setErr(ex instanceof Error ? ex.message : `${mode === 'register' ? 'Sign up' : 'Sign in'} failed.`);\n } finally {\n setBusy(false);\n }\n }\n\n async function onMicrosoft(credential) {\n setErr('');\n setBusy(true);\n try {\n await afterAuth(await microsoftSignIn(credential));\n } catch (ex) {\n setErr(ex instanceof Error ? ex.message : 'Microsoft sign in failed.');\n } finally {\n setBusy(false);\n }\n }\n\n async function onGoogle(credential) {\n setErr('');\n setBusy(true);\n try {\n await afterAuth(await googleSignIn(credential));\n } catch (ex) {\n setErr(ex instanceof Error ? ex.message : 'Google sign in failed.');\n } finally {\n setBusy(false);\n }\n }\n\n if (choices) {\n return (\n <div>\n <div className=\"logo\">{brand}</div>\n <h1>Choose workspace</h1>\n <div className=\"org-list\">\n {choices.map((o) => (\n <button\n key={o.id}\n type=\"button\"\n className=\"btn\"\n style={{ width: '100%', justifyContent: 'flex-start', height: 38 }}\n disabled={busy}\n onClick={() => {\n setBusy(true);\n enter(o.id).catch((ex) => {\n setErr(ex instanceof Error ? ex.message : 'Could not select the workspace.');\n setBusy(false);\n });\n }}\n >\n {o.name || o.id}\n </button>\n ))}\n </div>\n {err && <div className=\"auth-err\">{err}</div>}\n </div>\n );\n }\n\n return (\n <form onSubmit={submit}>\n <div className=\"logo\">{brand}</div>\n <h1>{mode === 'register' ? 'Create your account' : mode === 'forgot' ? 'Reset password' : 'Sign in'}</h1>\n <p className=\"sub\">\n {mode === 'register' ? 'Get started in seconds.'\n : mode === 'forgot' ? 'We will email you a reset link.'\n : (subtitle || 'Welcome back.')}\n </p>\n\n {mode === 'forgot' ? (\n resetSent ? (\n <>\n <div className=\"auth-note\">\n If an account exists for <b>{email.trim()}</b>, a password reset link is on its way. It is valid for 1 hour.\n </div>\n <button\n type=\"button\"\n className=\"btn primary lg\"\n style={{ width: '100%', marginTop: 14 }}\n onClick={() => { setErr(''); setResetSent(false); setMode('signin'); }}\n >\n Back to sign in\n </button>\n </>\n ) : (\n <>\n <div className=\"field\">\n <label>Email</label>\n <input className=\"input\" type=\"email\" value={email} onChange={(e) => setEmail(e.target.value)} autoFocus required autoComplete=\"email\" />\n </div>\n {err && <div className=\"auth-err\">{err}</div>}\n <button type=\"submit\" className=\"btn primary lg\" style={{ width: '100%', marginTop: 8 }} disabled={busy}>\n {busy ? 'Please wait...' : 'Send reset link'}\n </button>\n <p className=\"auth-switch\">\n <button type=\"button\" onClick={() => { setErr(''); setMode('signin'); }}>Back to sign in</button>\n </p>\n </>\n )\n ) : (\n <>\n {mode === 'register' && (\n <div className=\"field\">\n <label>Name</label>\n <input className=\"input\" value={name} onChange={(e) => setName(e.target.value)} autoComplete=\"name\" placeholder=\"Jane Doe\" />\n </div>\n )}\n <div className=\"field\">\n <label>Email</label>\n <input className=\"input\" type=\"email\" value={email} onChange={(e) => setEmail(e.target.value)} autoFocus required autoComplete=\"email\" />\n </div>\n <div className=\"field\">\n <div className=\"field-row\">\n <label>Password</label>\n {mode === 'signin' && (\n <button type=\"button\" className=\"link-sm\" onClick={() => { setErr(''); setResetSent(false); setMode('forgot'); }}>\n Forgot password?\n </button>\n )}\n </div>\n <input\n className=\"input\"\n type=\"password\"\n value={password}\n onChange={(e) => setPassword(e.target.value)}\n required\n autoComplete={mode === 'register' ? 'new-password' : 'current-password'}\n placeholder={mode === 'register' ? 'At least 8 characters' : ''}\n />\n </div>\n {err && <div className=\"auth-err\">{err}</div>}\n <button type=\"submit\" className=\"btn primary lg\" style={{ width: '100%', marginTop: 8 }} disabled={busy}>\n {busy ? 'Please wait...' : mode === 'register' ? 'Create account' : 'Sign in'}\n </button>\n\n {(GOOGLE_ENABLED || MICROSOFT_ENABLED) && <div className=\"auth-or\"><span>or</span></div>}\n {GOOGLE_ENABLED && <GoogleButton onCredential={onGoogle} onError={setErr} divider={false} />}\n {MICROSOFT_ENABLED && <MicrosoftButton onCredential={onMicrosoft} onError={setErr} disabled={busy} />}\n\n <p className=\"auth-switch\">\n {mode === 'register' ? 'Already have an account?' : `New to ${productName || 'the product'}?`}{' '}\n <button type=\"button\" onClick={() => { setErr(''); setMode(mode === 'register' ? 'signin' : 'register'); }}>\n {mode === 'register' ? 'Sign in' : 'Create one'}\n </button>\n </p>\n </>\n )}\n </form>\n );\n}\n","// Google Identity Services button (shared Epsilla user pool) — extracted from\n// ContextualGraph. On success it hands the id_token (credential) to the\n// caller, which exchanges it for a session via the engine's /v1/auth/google.\n//\n// The client id is the shared platform OAuth Web client (PUBLIC — Google\n// inlines it into every page); each product's origin must be listed on that\n// client's Authorized JavaScript origins. The whole block (the \"or\" divider\n// included) collapses when GIS cannot render, e.g. while an origin is not yet\n// authorized, so the form never shows a dead gap.\nimport { useEffect, useRef, useState } from 'react';\n\nconst CLIENT_ID = '247853836408-ojk91u8901hdlbkevid4fohmrfdot17l.apps.googleusercontent.com';\n\nexport function GoogleButton({ onCredential, onError, divider = true }) {\n const ref = useRef(null);\n const [failed, setFailed] = useState(false);\n // Keep the latest callbacks in a ref so the GIS button mounts exactly once\n // and never flickers when the parent re-renders on each keystroke.\n const cb = useRef({ onCredential, onError });\n cb.current = { onCredential, onError };\n\n useEffect(() => {\n if (!CLIENT_ID || !ref.current) return undefined;\n const SRC = 'https://accounts.google.com/gsi/client';\n let done = false;\n const render = () => {\n if (done) return;\n const g = window.google;\n if (!g?.accounts?.id || !ref.current) return;\n done = true;\n try {\n g.accounts.id.initialize({\n client_id: CLIENT_ID,\n callback: (resp) => {\n if (resp?.credential) cb.current.onCredential(resp.credential);\n else cb.current.onError?.('Google sign in was cancelled.');\n },\n });\n ref.current.innerHTML = '';\n g.accounts.id.renderButton(ref.current, {\n theme: 'outline', size: 'large', shape: 'pill', text: 'continue_with', width: 320,\n });\n } catch {\n setFailed(true);\n }\n };\n let s = document.querySelector(`script[src=\"${SRC}\"]`);\n if (s && window.google) render();\n else {\n if (!s) {\n s = document.createElement('script');\n s.src = SRC;\n s.async = true;\n s.defer = true;\n document.head.appendChild(s);\n }\n s.addEventListener('load', render);\n }\n // If nothing rendered (script blocked, origin not authorized, offline),\n // collapse the block instead of leaving an empty gap.\n const check = window.setTimeout(() => {\n const iframe = ref.current?.querySelector('iframe');\n if (!iframe || iframe.getBoundingClientRect().height < 10) setFailed(true);\n }, 3500);\n return () => {\n s?.removeEventListener('load', render);\n window.clearTimeout(check);\n };\n }, []);\n\n if (!CLIENT_ID || failed) return null;\n return (\n <>\n {divider && <div className=\"auth-or\"><span>or</span></div>}\n <div ref={ref} className=\"auth-gwrap\" />\n </>\n );\n}\n\nexport const GOOGLE_ENABLED = !!CLIENT_ID;\n","// Sign in with Microsoft (work and school accounts), the platform's\n// multi-tenant Entra application. Like GoogleButton, it only obtains an\n// OpenID Connect id token and hands it to the caller, which exchanges it for\n// a session at the engine's /v1/auth/microsoft.\n//\n// The token comes back in a popup, to <this origin>/auth/microsoft. That\n// address must be one of the application's registered SPA return addresses\n// (one per product host) and should serve a blank page: this window reads the\n// popup the moment it is back on our origin, before anything could run in it.\n// The client id is PUBLIC (it is in every authorize URL).\nimport { useRef, useState } from 'react';\n\nconst CLIENT_ID = 'cb5c1b6e-aca8-48dd-9da9-31320de30b73';\nconst AUTHORIZE = 'https://login.microsoftonline.com/organizations/oauth2/v2.0/authorize';\nconst RETURN_PATH = '/auth/microsoft';\nconst GIVE_UP_MS = 5 * 60 * 1000;\n\nexport const MICROSOFT_ENABLED = !!CLIENT_ID;\n\nfunction randomHex(bytes = 16) {\n const a = new Uint8Array(bytes);\n crypto.getRandomValues(a);\n return Array.from(a, (b) => b.toString(16).padStart(2, '0')).join('');\n}\n\nfunction jwtClaims(token) {\n try {\n const part = token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/');\n const bin = atob(part + '='.repeat((4 - (part.length % 4)) % 4));\n return JSON.parse(new TextDecoder().decode(Uint8Array.from(bin, (c) => c.charCodeAt(0))));\n } catch {\n return {};\n }\n}\n\n/** Open Microsoft's sign-in in a popup and resolve with the id token, or\n * reject with a sentence a person can read. */\nexport function microsoftIdToken() {\n return new Promise((resolve, reject) => {\n const state = randomHex();\n const nonce = randomHex();\n const back = `${window.location.origin}${RETURN_PATH}`;\n const url = `${AUTHORIZE}?${new URLSearchParams({\n client_id: CLIENT_ID, response_type: 'id_token', redirect_uri: back,\n scope: 'openid profile email', response_mode: 'fragment',\n state, nonce, prompt: 'select_account',\n })}`;\n const w = 480;\n const h = 640;\n const left = Math.max(0, window.screenX + (window.outerWidth - w) / 2);\n const top = Math.max(0, window.screenY + (window.outerHeight - h) / 2);\n const popup = window.open(url, 'microsoft-sign-in', `width=${w},height=${h},left=${left},top=${top}`);\n if (!popup) {\n reject(new Error('Allow pop-ups for this site to sign in with Microsoft.'));\n return;\n }\n const started = Date.now();\n const timer = window.setInterval(() => {\n if (popup.closed) {\n window.clearInterval(timer);\n reject(new Error('Microsoft sign in was cancelled.'));\n return;\n }\n if (Date.now() - started > GIVE_UP_MS) {\n window.clearInterval(timer);\n popup.close();\n reject(new Error('Microsoft sign in took too long. Try again.'));\n return;\n }\n let href = '';\n try { href = popup.location.href; } catch { return; } // still on Microsoft's pages\n if (!href.startsWith(back)) return;\n window.clearInterval(timer);\n const params = new URLSearchParams(popup.location.hash.replace(/^#/, ''));\n popup.close();\n if (params.get('error')) {\n const why = (params.get('error_description') || '').split(/\\r?\\n/)[0].replace(/^AADSTS\\d+:\\s*/, '');\n reject(new Error(why || 'Microsoft sign in did not complete.'));\n return;\n }\n const token = params.get('id_token') || '';\n if (!token || params.get('state') !== state || jwtClaims(token).nonce !== nonce) {\n reject(new Error('Microsoft sign in could not be confirmed. Try again.'));\n return;\n }\n resolve(token);\n }, 300);\n });\n}\n\nfunction MicrosoftLogo() {\n return (\n <svg width=\"18\" height=\"18\" viewBox=\"0 0 21 21\" aria-hidden=\"true\">\n <rect x=\"1\" y=\"1\" width=\"9\" height=\"9\" fill=\"#F25022\" />\n <rect x=\"11\" y=\"1\" width=\"9\" height=\"9\" fill=\"#7FBA00\" />\n <rect x=\"1\" y=\"11\" width=\"9\" height=\"9\" fill=\"#00A4EF\" />\n <rect x=\"11\" y=\"11\" width=\"9\" height=\"9\" fill=\"#FFB900\" />\n </svg>\n );\n}\n\nexport function MicrosoftButton({ onCredential, onError, disabled }) {\n const [waiting, setWaiting] = useState(false);\n const cb = useRef({ onCredential, onError });\n cb.current = { onCredential, onError };\n if (!CLIENT_ID) return null;\n\n async function start() {\n setWaiting(true);\n try {\n const token = await microsoftIdToken();\n await cb.current.onCredential(token);\n } catch (ex) {\n cb.current.onError?.(ex instanceof Error ? ex.message : 'Microsoft sign in failed.');\n } finally {\n setWaiting(false);\n }\n }\n\n return (\n <div className=\"auth-mswrap\">\n <button type=\"button\" className=\"auth-msbtn\" onClick={start} disabled={disabled || waiting}>\n <MicrosoftLogo />\n <span>{waiting ? 'Waiting for Microsoft...' : 'Sign in with Microsoft'}</span>\n </button>\n </div>\n );\n}\n","// SheetGrid — the reusable AI-spreadsheet grid (UI Core).\n//\n// Product-agnostic: it renders a sheet JSON and calls back for edits/runs.\n// The Sheets product (frontend-sheets) AND agentstudio studio Spaces both\n// mount it via @ui-core, so a Space can nest a sheet-typed element with the\n// same component. All I/O is injected — this file has no product API.\n//\n// Sheet shape (see backend/sheets sheet_model):\n// { meta{title,rev}, columns[{id,name,type,options?,compute?}],\n// rows[{id}], cells{ \"<rowId>:<colId>\": {value,status,error} } }\n//\n// Props:\n// sheet — the sheet JSON (required)\n// onRunCell(rowId, colId) — run one computed cell (optional)\n// ops — the document ops (useSheetCollab's sheetOps); every\n// edit is one op on this tab, never a whole-sheet replace\n// onRunColumn(colId) — batch-run a computed column (optional)\n// peers — this tab's other people: [{id, name, color, sel, typing}] (from\n// useSheetCollab); their selection is outlined and tinted in\n// their color, their in-progress text shows in the cell as they type\n// onPresence — ({sel, typing}) what THIS person selects and types, for peers\n// readOnly — no editing/running (template previews / embedded read views)\n// fetchBlobUrl(path) — async product-authed fetch -> object URL, for\n// inline images whose url is a product path\n// onOpenResource(ref) — open a referenced artifact (sheet/slides/…)\n//\n// Editing goes straight to the document: local edits are ops on it; the\n// host persists + (via realtime) rebroadcasts truth back through `sheet`.\nimport { useEffect, useMemo, useRef, useState } from 'react';\nimport { MentionInput } from '../mention/MentionInput.jsx';\nimport { createPortal } from 'react-dom';\nimport { withAlpha } from '../collab/colors.js';\n\nconst cellKey = (rowId, colId) => `${rowId}:${colId}`;\nconst uid = (p) => `${p}_${Math.random().toString(36).slice(2, 10)}`;\n\nconst TYPE_LABEL = {\n text: 'Text', number: 'Number', select: 'Select', tags: 'Tags',\n checkbox: 'Checkbox', date: 'Date', url: 'Link', resource: 'Resource', compute: 'Computed',\n};\n// A one-glyph mark per column type, for pills and pickers.\nconst TYPE_GLYPH = { text: 'Aa', number: '#', select: '▾', tags: '#', checkbox: '✓', date: '▦', url: '↗', resource: '◫', compute: '✦' };\n\nconst MANUAL_TYPES = ['text', 'number', 'select', 'tags', 'checkbox', 'date', 'url', 'resource'];\nconst COMPUTE_KINDS = [\n { kind: 'prompt', label: 'AI prompt' },\n { kind: 'harness', label: 'Agent (harness)' },\n { kind: 'workflow', label: 'Workflow' },\n { kind: 'image', label: 'Generate image' },\n];\nconst RESOURCE_KINDS = ['image', 'sheet', 'slides', 'workflow', 'graph'];\nconst RESOURCE_ICON = { image: '🖼', sheet: '▦', slides: '▤', workflow: '⚙', graph: '◉' };\n\n// Popovers render through a body portal with FIXED positioning — inside the\n// grid they'd be clipped by the scroll container and out-stacked by the\n// sticky header/row-number cells. anchor is a DOMRect captured at open time;\n// the box clamps to the viewport and flips above the anchor when the bottom\n// would overflow. A scroll OUTSIDE the box closes it (the anchor moved);\n// scrolling inside it (a long prompt, a long option list) is the box's own.\nfunction PopPortal({ anchor, width = 250, estHeight = 300, className, children, onClose }) {\n const boxRef = useRef(null);\n useEffect(() => {\n if (!onClose) return undefined;\n const close = (e) => {\n if (e?.type === 'scroll' && boxRef.current && e.target instanceof Node && boxRef.current.contains(e.target)) return;\n onClose();\n };\n window.addEventListener('scroll', close, true);\n window.addEventListener('resize', close);\n return () => { window.removeEventListener('scroll', close, true); window.removeEventListener('resize', close); };\n }, [onClose]);\n if (!anchor) return null;\n const left = Math.max(8, Math.min(anchor.right - width, window.innerWidth - width - 8));\n let top = anchor.bottom + 6;\n if (top + estHeight > window.innerHeight - 8) top = Math.max(8, anchor.top - estHeight - 6);\n return createPortal(\n <div ref={boxRef} className={className} style={{ position: 'fixed', top, left, width, zIndex: 1000 }}>\n {children}\n </div>,\n document.body,\n );\n}\n\n// Value styling. A column's `options` are its value vocabulary: each option is\n// a value and a color. A select column offers them as choices; EVERY column\n// type paints a cell whose value matches one as a pill in that color, so an\n// enumerated result (CORRECT / WRONG, HEALTHY / AT RISK) reads at a glance.\n// The palette is named so a color can mean something; an option that declares\n// no color takes the muted rotation.\nexport const PILL_PALETTE = [\n { name: 'green', color: '#D1FAE5' }, { name: 'red', color: '#FEE2E2' },\n { name: 'amber', color: '#FEF3C7' }, { name: 'blue', color: '#DBEAFE' },\n { name: 'purple', color: '#EDE9FE' }, { name: 'pink', color: '#FCE7F3' },\n { name: 'teal', color: '#CCFBF1' }, { name: 'gray', color: '#E5E7EB' },\n];\nconst PILL_FALLBACKS = ['#E0E7FF', '#FCE7F3', '#D1FAE5', '#FEF3C7', '#E0F2FE', '#F3E8FF', '#FFE4E6'];\n\nexport function normOptions(options) {\n return (options || []).map((o, i) => {\n if (typeof o === 'string') return { label: o, color: PILL_FALLBACKS[i % PILL_FALLBACKS.length] };\n return { label: o.label ?? String(o.value ?? ''), color: o.color || PILL_FALLBACKS[i % PILL_FALLBACKS.length] };\n });\n}\n\nconst sameValue = (a, b) => String(a).trim().toLowerCase() === String(b).trim().toLowerCase();\n\n/** The option a value matches (trimmed, case-insensitive), or null. */\nfunction optionFor(value, options) {\n if (value === undefined || value === null || value === '') return null;\n return normOptions(options).find((o) => sameValue(o.label, value)) || null;\n}\n\nfunction pillColor(label, options) {\n const hit = optionFor(label, options);\n if (hit) return hit.color;\n // stable fallback by hash so ad-hoc tags keep their color\n let h = 0;\n for (const ch of String(label)) h = (h * 31 + ch.charCodeAt(0)) >>> 0;\n return PILL_FALLBACKS[h % PILL_FALLBACKS.length];\n}\n\n// An inline image whose url may be a product path (needs authed fetch).\nfunction RefImage({ refVal, fetchBlobUrl }) {\n const [src, setSrc] = useState(/^https?:\\/\\//i.test(refVal.url || '') ? refVal.url : null);\n useEffect(() => {\n let dead = false; let obj = null;\n if (!src && refVal.url && fetchBlobUrl) {\n fetchBlobUrl(refVal.url).then((u) => { if (!dead) { obj = u; setSrc(u); } });\n }\n return () => { dead = true; if (obj) URL.revokeObjectURL(obj); };\n }, [refVal.url]);\n if (!src) return <span className=\"shg-refchip\">{RESOURCE_ICON.image} {refVal.name || 'image'}</span>;\n return <img className=\"shg-refimg\" src={src} alt={refVal.name || ''} title={refVal.name || ''} />;\n}\n\nfunction ResourceChip({ refVal, onOpen }) {\n const icon = RESOURCE_ICON[refVal.kind] || '◇';\n return (\n <button className=\"shg-refchip shg-refchip-btn\" title={`Open ${refVal.kind}`}\n onClick={(e) => { e.stopPropagation(); onOpen && onOpen(refVal); }}>\n <span className=\"shg-refchip-ic\">{icon}</span>\n <span className=\"shg-refchip-name\">{refVal.name || refVal.id || refVal.kind}</span>\n </button>\n );\n}\n\n// A small status dot for computed cells while work is pending or went wrong;\n// a finished cell is its value.\nfunction StatusDot({ status }) {\n if (!status || status === 'empty' || status === 'done') return null;\n return <span className={`shg-dot shg-dot-${status}`} title={status} />;\n}\n\nfunction CellValue({ cell, col, fetchBlobUrl, onOpenResource }) {\n const v = cell?.value;\n if (v === undefined || v === null || v === '') return <span className=\"shg-val-txt\" />;\n // A typed artifact ref renders the same whether hand-set (resource column)\n // or produced by a compute kind (e.g. Generate image).\n if (v && typeof v === 'object' && !Array.isArray(v) && v.kind) {\n if (v.kind === 'image') return <RefImage refVal={v} fetchBlobUrl={fetchBlobUrl} />;\n return <ResourceChip refVal={v} onOpen={onOpenResource} />;\n }\n const styled = col.type !== 'tags' && optionFor(v, col.options);\n if (styled) return <span className=\"shg-pill\" style={{ background: styled.color }}>{styled.label}</span>;\n switch (col.type) {\n case 'select':\n return <span className=\"shg-pill\" style={{ background: pillColor(String(v), col.options) }}>{String(v)}</span>;\n case 'tags': {\n const tags = Array.isArray(v) ? v : String(v).split(',').map((s) => s.trim()).filter(Boolean);\n return (\n <span className=\"shg-pills\">\n {tags.map((t) => (\n <span key={t} className=\"shg-pill\" style={{ background: pillColor(t, col.options) }}>{t}</span>\n ))}\n </span>\n );\n }\n case 'checkbox':\n return <span className={'shg-check' + (v ? ' on' : '')}>{v ? '✓' : ''}</span>;\n case 'url': {\n const href = /^https?:\\/\\//i.test(String(v)) ? String(v) : `https://${v}`;\n return <a className=\"shg-link\" href={href} target=\"_blank\" rel=\"noreferrer\" onClick={(e) => e.stopPropagation()}>{String(v)}</a>;\n }\n case 'number':\n return <span className=\"shg-val-txt shg-num\">{String(v)}</span>;\n default:\n return <span className=\"shg-val-txt\">{typeof v === 'object' ? JSON.stringify(v) : String(v)}</span>;\n }\n}\n\nexport function SheetGrid({ sheet, ops, onRunCell, onRunColumn, readOnly = false, fetchBlobUrl, onOpenResource, peers, onPresence }) {\n const columns = sheet?.columns || [];\n const rows = sheet?.rows || [];\n const cells = sheet?.cells || {};\n const tabId = sheet?.id;\n const canEdit = !readOnly && !!ops && !!tabId;\n const [editing, setEditing] = useState(null); // {rowId, colId, type}\n const [draft, setDraft] = useState('');\n const [menuCol, setMenuCol] = useState(null); // {id, rect} of the open column menu\n const [sizeDraft, setSizeDraft] = useState({}); // live {col:{id:w}, row:{id:h}} during a drag\n const [dnd, setDnd] = useState(null); // {kind:'col'|'row', id} being dragged\n const [dropAt, setDropAt] = useState(null); // {kind, id, after} current drop slot\n const inputRef = useRef(null);\n const dragRef = useRef(null);\n // Selection, Google Sheets style: a click selects, a drag or Shift extends\n // the range, a double click / Enter / typing edits the focus cell. Indexes\n // into this tab's rows and columns; presence carries the ids.\n const [sel, setSel] = useState(null); // {a:{r,c}, f:{r,c}}\n const dragSel = useRef(false);\n const rootRef = useRef(null);\n const presenceRef = useRef(onPresence);\n presenceRef.current = onPresence;\n const range = sel ? { r0: Math.min(sel.a.r, sel.f.r), r1: Math.max(sel.a.r, sel.f.r),\n c0: Math.min(sel.a.c, sel.f.c), c1: Math.max(sel.a.c, sel.f.c) } : null;\n const inSel = (ri, ci) => !!range && ri >= range.r0 && ri <= range.r1 && ci >= range.c0 && ci <= range.c1;\n const isFocus = (ri, ci) => !!sel && sel.f.r === ri && sel.f.c === ci;\n const clampSel = (p) => ({ r: Math.max(0, Math.min(p.r, rows.length - 1)), c: Math.max(0, Math.min(p.c, columns.length - 1)) });\n const moveFocus = (dr, dc, extend) => setSel((cur) => {\n if (!cur || !rows.length || !columns.length) return cur;\n const f = clampSel({ r: cur.f.r + dr, c: cur.f.c + dc });\n return { a: extend ? cur.a : f, f };\n });\n useEffect(() => {\n const up = () => { dragSel.current = false; };\n window.addEventListener('mouseup', up);\n return () => window.removeEventListener('mouseup', up);\n }, []);\n // Tell peers what this person selects and types.\n useEffect(() => {\n const fn = presenceRef.current;\n if (!fn) return;\n const ids = (p) => [rows[p.r]?.id, columns[p.c]?.id];\n fn({\n sel: sel && rows[sel.f.r] && columns[sel.f.c] ? { a: ids(sel.a), f: ids(sel.f) } : null,\n typing: editing && typeof draft === 'string' ? { key: cellKey(editing.rowId, editing.colId), text: draft } : null,\n });\n }, [sel, editing, draft, rows, columns]);\n // Peers on this tab: who has which cell in focus, which cells sit in their\n // ranges, and what they are typing where.\n const peerLayer = useMemo(() => {\n const focus = {}, tint = {}, typing = {};\n const rIdx = new Map(rows.map((r, i) => [r.id, i]));\n const cIdx = new Map(columns.map((c, i) => [c.id, i]));\n for (const p of peers || []) {\n if (p.typing && p.typing.key) typing[p.typing.key] = { text: p.typing.text, color: p.color, name: p.name };\n if (!p.sel || !p.sel.a || !p.sel.f) continue;\n const a = { r: rIdx.get(p.sel.a[0]), c: cIdx.get(p.sel.a[1]) }, f = { r: rIdx.get(p.sel.f[0]), c: cIdx.get(p.sel.f[1]) };\n if ([a.r, a.c, f.r, f.c].some((v) => v === undefined)) continue;\n focus[cellKey(p.sel.f[0], p.sel.f[1])] = p;\n for (let r = Math.min(a.r, f.r); r <= Math.max(a.r, f.r); r++) {\n for (let c = Math.min(a.c, f.c); c <= Math.max(a.c, f.c); c++) {\n const k = cellKey(rows[r].id, columns[c].id);\n if (!tint[k]) tint[k] = p.color;\n }\n }\n }\n return { focus, tint, typing };\n }, [peers, rows, columns]);\n\n // Drag-to-resize: live via sizeDraft, persisted into the sheet on release.\n const startResize = (e, kind, id, start) => {\n if (readOnly) return;\n e.preventDefault(); e.stopPropagation();\n const origin = kind === 'col' ? e.clientX : e.clientY;\n dragRef.current = { kind, id, start, origin, last: start };\n const onMove = (ev) => {\n const d = dragRef.current; if (!d) return;\n const delta = (d.kind === 'col' ? ev.clientX : ev.clientY) - d.origin;\n const next = Math.max(d.kind === 'col' ? 90 : 26, d.start + delta);\n d.last = next;\n setSizeDraft((sd) => ({ ...sd, [d.kind]: { ...(sd[d.kind] || {}), [d.id]: next } }));\n };\n const onUp = () => {\n const d = dragRef.current; dragRef.current = null;\n window.removeEventListener('mousemove', onMove);\n window.removeEventListener('mouseup', onUp);\n document.body.style.cursor = '';\n if (!d) return;\n setSizeDraft({});\n if (!canEdit) return;\n if (d.kind === 'col') { const c = columns.find((x) => x.id === d.id); if (c) ops.setColumn(tabId, { ...c, width: Math.round(d.last) }); }\n else { const r = rows.find((x) => x.id === d.id); if (r) ops.setRow(tabId, { ...r, height: Math.round(d.last) }); }\n };\n window.addEventListener('mousemove', onMove);\n window.addEventListener('mouseup', onUp);\n document.body.style.cursor = kind === 'col' ? 'col-resize' : 'row-resize';\n };\n const colWidth = (col) => (sizeDraft.col && sizeDraft.col[col.id]) || col.width || undefined;\n\n // Drag-to-reorder (columns by their header, rows by their number cell).\n const reorder = (kind, fromId, toId, after) => {\n if (!canEdit || fromId === toId) return;\n const arr = (kind === 'col' ? columns : rows).map((x) => x.id);\n const i = arr.indexOf(fromId);\n if (i < 0) return;\n arr.splice(i, 1);\n let j = arr.indexOf(toId);\n if (j < 0) return;\n if (after) j += 1;\n if (kind === 'col') ops.moveColumn(tabId, fromId, j); else ops.moveRow(tabId, fromId, j);\n };\n const dndProps = (kind, id) => (readOnly ? {} : {\n draggable: true,\n onDragStart: (e) => {\n if (e.target.closest && e.target.closest('.shg-resize-col, .shg-resize-row, input, button')) { e.preventDefault(); return; }\n e.dataTransfer.effectAllowed = 'move';\n e.dataTransfer.setData('text/plain', `${kind}:${id}`);\n setDnd({ kind, id });\n },\n onDragOver: (e) => {\n if (!dnd || dnd.kind !== kind || dnd.id === id) return;\n e.preventDefault();\n const r = e.currentTarget.getBoundingClientRect();\n const after = kind === 'col' ? e.clientX > r.x + r.width / 2 : e.clientY > r.y + r.height / 2;\n setDropAt((d) => (d && d.id === id && d.after === after ? d : { kind, id, after }));\n },\n onDrop: (e) => {\n e.preventDefault();\n if (dnd && dnd.kind === kind && dnd.id !== id) {\n const r = e.currentTarget.getBoundingClientRect();\n const after = kind === 'col' ? e.clientX > r.x + r.width / 2 : e.clientY > r.y + r.height / 2;\n reorder(kind, dnd.id, id, after);\n }\n setDnd(null); setDropAt(null);\n },\n onDragEnd: () => { setDnd(null); setDropAt(null); },\n });\n const dndClass = (kind, id) => {\n let cls = '';\n if (dnd && dnd.kind === kind && dnd.id === id) cls += ' shg-dragging';\n if (dropAt && dropAt.kind === kind && dropAt.id === id) {\n cls += dropAt.after ? (kind === 'col' ? ' shg-drop-after' : ' shg-drop-below')\n : (kind === 'col' ? ' shg-drop-before' : ' shg-drop-above');\n }\n return cls;\n };\n // The number gutter is FIXED: sized by the digit count of the row total so\n // it never stretches (an empty grid otherwise splits the table width).\n const numW = Math.max(40, 24 + String(rows.length || 1).length * 9);\n const numStyle = { width: numW, minWidth: numW, maxWidth: numW };\n const rowHeight = (row) => (sizeDraft.row && sizeDraft.row[row.id]) || row.height || undefined;\n\n useEffect(() => { if (editing && inputRef.current) inputRef.current.focus(); }, [editing]);\n\n const setCell = (rowId, colId, value) => {\n if (!canEdit) return;\n ops.setCell(tabId, cellKey(rowId, colId), { value, status: 'done', updated_at: Math.floor(Date.now() / 1000) });\n };\n\n const openEdit = (rowId, col, anchorEl, initial) => {\n if (!canEdit) return;\n if (col.type === 'compute') return; // computed cells aren't hand-edited\n if (col.type === 'checkbox') { // toggles directly\n const cur = cells[cellKey(rowId, col.id)];\n setCell(rowId, col.id, !(cur && cur.value));\n return;\n }\n const c = cells[cellKey(rowId, col.id)];\n const v = c?.value;\n if (col.type === 'tags') setDraft(initial ?? (Array.isArray(v) ? v.join(', ') : (v || '')));\n else if (col.type === 'resource') setDraft(v && typeof v === 'object' ? v : { kind: 'sheet', name: '', id: '', url: '' });\n else setDraft(initial ?? (v == null ? '' : String(v)));\n setEditing({ rowId, colId: col.id, type: col.type, rect: anchorEl?.getBoundingClientRect?.() || null });\n };\n\n const commitEdit = () => {\n if (!editing) return;\n const { rowId, colId, type } = editing;\n let value = draft;\n if (type === 'number') value = draft === '' ? null : Number(draft);\n else if (type === 'tags') value = draft ? draft.split(',').map((s) => s.trim()).filter(Boolean) : [];\n setCell(rowId, colId, value);\n setEditing(null);\n };\n\n const addColumn = () => canEdit && ops.setColumn(tabId, { id: uid('col'), name: `Column ${columns.length + 1}`, type: 'text' });\n const addRow = () => canEdit && ops.setRow(tabId, { id: uid('row') });\n const deleteColumn = (colId) => canEdit && ops.deleteColumn(tabId, colId);\n const deleteRow = (rowId) => canEdit && ops.deleteRow(tabId, rowId);\n const renameColumn = (colId, name) => {\n const c = columns.find((x) => x.id === colId);\n if (canEdit && c) ops.setColumn(tabId, { ...c, name });\n };\n const configureColumn = (colId, patch) => {\n const c = columns.find((x) => x.id === colId);\n if (!canEdit || !c) return;\n const next = { ...c, ...patch };\n if (patch.type && patch.type !== 'compute') delete next.compute;\n ops.setColumn(tabId, next);\n };\n\n // The selection as text: one line per row, tab between cells.\n const cellText = (c) => {\n const v = c?.value;\n if (v === undefined || v === null) return '';\n if (Array.isArray(v)) return v.join(', ');\n if (typeof v === 'object') return v.name || v.url || v.id || '';\n return String(v);\n };\n const copySelection = (e) => {\n if (!range || editing) return;\n const lines = [];\n for (let r = range.r0; r <= range.r1; r++) {\n const parts = [];\n for (let c = range.c0; c <= range.c1; c++) parts.push(cellText(cells[cellKey(rows[r].id, columns[c].id)]));\n lines.push(parts.join('\\t'));\n }\n e.clipboardData.setData('text/plain', lines.join('\\n'));\n e.preventDefault();\n };\n const pasteAt = (e) => {\n if (!sel || editing || !canEdit) return;\n const text = e.clipboardData.getData('text/plain');\n if (!text) return;\n e.preventDefault();\n const now = Math.floor(Date.now() / 1000);\n const patch = {};\n const lines = text.replace(/\\r/g, '').split('\\n');\n if (lines.length > 1 && lines[lines.length - 1] === '') lines.pop();\n lines.forEach((line, dr) => line.split('\\t').forEach((raw, dc) => {\n const row = rows[sel.f.r + dr], col = columns[sel.f.c + dc];\n if (!row || !col || col.type === 'compute') return;\n let value = raw;\n if (col.type === 'number') value = raw === '' ? null : Number(raw);\n else if (col.type === 'checkbox') value = /^(true|yes|1|✓)$/i.test(raw.trim());\n else if (col.type === 'tags') value = raw ? raw.split(',').map((x) => x.trim()).filter(Boolean) : [];\n patch[cellKey(row.id, col.id)] = value === null || value === '' ? null : { value, status: 'done', updated_at: now };\n }));\n if (Object.keys(patch).length) ops.setCells(tabId, patch);\n setSel({ a: sel.f, f: clampSel({ r: sel.f.r + lines.length - 1, c: sel.f.c + Math.max(...lines.map((l) => l.split('\\t').length)) - 1 }) });\n };\n const clearSelection = () => {\n if (!range || !canEdit) return;\n const patch = {};\n for (let r = range.r0; r <= range.r1; r++) {\n for (let c = range.c0; c <= range.c1; c++) {\n if (columns[c].type === 'compute') continue;\n const k = cellKey(rows[r].id, columns[c].id);\n if (cells[k]) patch[k] = null;\n }\n }\n if (Object.keys(patch).length) ops.setCells(tabId, patch);\n };\n const onKeyDown = (e) => {\n if (editing || menuCol) return;\n if (!sel) return;\n const meta = e.metaKey || e.ctrlKey;\n if (meta && (e.key === 'c' || e.key === 'v' || e.key === 'x')) return; // copy/paste events handle these\n const focusCell = () => ({ row: rows[sel.f.r], col: columns[sel.f.c] });\n switch (e.key) {\n case 'ArrowUp': e.preventDefault(); moveFocus(-1, 0, e.shiftKey); return;\n case 'ArrowDown': e.preventDefault(); moveFocus(1, 0, e.shiftKey); return;\n case 'ArrowLeft': e.preventDefault(); moveFocus(0, -1, e.shiftKey); return;\n case 'ArrowRight': e.preventDefault(); moveFocus(0, 1, e.shiftKey); return;\n case 'Tab': e.preventDefault(); moveFocus(0, e.shiftKey ? -1 : 1, false); return;\n case 'Escape': setSel(null); return;\n case 'Enter': case 'F2': {\n e.preventDefault();\n const { row, col } = focusCell();\n if (row && col) openEdit(row.id, col, rootRef.current?.querySelector(`[data-cell=\"${cellKey(row.id, col.id)}\"]`));\n return;\n }\n case 'Delete': case 'Backspace': e.preventDefault(); clearSelection(); return;\n default:\n }\n if (!meta && !e.altKey && e.key.length === 1) {\n const { row, col } = focusCell();\n if (row && col && col.type !== 'compute' && col.type !== 'checkbox') {\n e.preventDefault();\n openEdit(row.id, col, rootRef.current?.querySelector(`[data-cell=\"${cellKey(row.id, col.id)}\"]`), e.key);\n }\n }\n };\n\n // The inline editor for the editing cell, by type.\n const renderEditor = (col) => {\n if (col.type === 'resource') {\n const d = typeof draft === 'object' && draft ? draft : { kind: 'sheet' };\n const set = (k, v) => setDraft({ ...d, [k]: v });\n return (\n <PopPortal anchor={editing.rect} width={240} estHeight={230}\n className=\"shg-select-pop shg-ref-pop\" onClose={() => setEditing(null)}>\n <div onClick={(e) => e.stopPropagation()}>\n <select className=\"shg-menu-input\" value={d.kind || 'sheet'} onChange={(e) => set('kind', e.target.value)}>\n {RESOURCE_KINDS.map((k) => <option key={k} value={k}>{k}</option>)}\n </select>\n <input className=\"shg-menu-input\" placeholder=\"Name\" value={d.name || ''} onChange={(e) => set('name', e.target.value)} />\n <input className=\"shg-menu-input\" placeholder=\"Resource id (e.g. sheet.…)\" value={d.id || ''} onChange={(e) => set('id', e.target.value)} />\n <input className=\"shg-menu-input\" placeholder=\"or URL\" value={d.url || ''} onChange={(e) => set('url', e.target.value)} />\n <div className=\"shg-menu-actions\">\n <button className=\"shg-pop-clear\" onClick={() => { setCell(editing.rowId, editing.colId, null); setEditing(null); }}>Clear</button>\n <button className=\"shg-menu-apply\" onClick={() => { setCell(editing.rowId, editing.colId, d); setEditing(null); }}>Set</button>\n </div>\n </div>\n </PopPortal>\n );\n }\n if (col.type === 'select') {\n const opts = normOptions(col.options);\n return (\n <PopPortal anchor={editing.rect} width={190} estHeight={40 + opts.length * 30}\n className=\"shg-select-pop\" onClose={() => setEditing(null)}>\n {opts.length === 0 && <div className=\"shg-pop-note\">No options yet — add them in the column menu.</div>}\n {opts.map((o) => (\n <button key={o.label} className=\"shg-pill shg-pill-btn\" style={{ background: o.color }}\n onClick={(e) => { e.stopPropagation(); setCell(editing.rowId, editing.colId, o.label); setEditing(null); }}>\n {o.label}\n </button>\n ))}\n <button className=\"shg-pop-clear\"\n onClick={(e) => { e.stopPropagation(); setCell(editing.rowId, editing.colId, null); setEditing(null); }}>\n Clear\n </button>\n </PopPortal>\n );\n }\n const inputType = col.type === 'date' ? 'date' : col.type === 'number' ? 'number' : 'text';\n return (\n <input ref={inputRef} className=\"shg-input\" type={inputType} value={draft}\n placeholder={col.type === 'tags' ? 'tag, tag, …' : ''}\n onChange={(e) => setDraft(e.target.value)}\n onBlur={commitEdit}\n onKeyDown={(e) => {\n if (e.key === 'Enter') { e.preventDefault(); commitEdit(); moveFocus(1, 0, false); rootRef.current?.focus(); }\n else if (e.key === 'Tab') { e.preventDefault(); commitEdit(); moveFocus(0, e.shiftKey ? -1 : 1, false); rootRef.current?.focus(); }\n else if (e.key === 'Escape') { setEditing(null); rootRef.current?.focus(); }\n }} />\n );\n };\n\n return (\n <div className=\"shg\" ref={rootRef} tabIndex={0} onKeyDown={onKeyDown} onCopy={copySelection} onPaste={pasteAt}>\n <div className=\"shg-scroll\">\n <table className=\"shg-table\">\n <thead>\n <tr>\n <th className=\"shg-corner\" style={numStyle} />\n {columns.map((col) => (\n <th key={col.id}\n className={'shg-col' + (col.type === 'compute' ? ' shg-col-compute' : '') + dndClass('col', col.id)}\n style={colWidth(col) ? { width: colWidth(col), minWidth: colWidth(col), maxWidth: colWidth(col) } : undefined}\n {...dndProps('col', col.id)}>\n {!readOnly && (\n <span className=\"shg-resize-col\" onMouseDown={(e) => startResize(e, 'col', col.id, colWidth(col) || e.currentTarget.closest('th').offsetWidth)} />\n )}\n <div className=\"shg-col-h\">\n <ColumnHeader\n col={col} columns={columns} readOnly={readOnly}\n menuOpen={menuCol?.id === col.id}\n menuAnchor={menuCol?.id === col.id ? menuCol.rect : null}\n onMenu={(e) => setMenuCol(menuCol?.id === col.id ? null\n : { id: col.id, rect: e.currentTarget.getBoundingClientRect() })}\n onCloseMenu={() => setMenuCol(null)}\n onRename={renameColumn}\n onConfigure={configureColumn}\n onDelete={() => { setMenuCol(null); deleteColumn(col.id); }}\n onRun={col.type === 'compute' && onRunColumn ? () => onRunColumn(col.id) : null}\n width={colWidth(col)} />\n </div>\n </th>\n ))}\n {!readOnly && (\n <th className=\"shg-add-col\"><button className=\"shg-add\" onClick={addColumn} title=\"Add column\">+</button></th>\n )}\n </tr>\n </thead>\n <tbody>\n {rows.map((row, ri) => (\n <tr key={row.id}\n style={{\n ...(rowHeight(row) ? { height: rowHeight(row) } : null),\n '--shg-clamp': Math.max(1, Math.floor(((rowHeight(row) || 34) - 10) / 18)),\n }}>\n <td className={'shg-rownum' + dndClass('row', row.id)} style={numStyle}\n title=\"Drag to reorder\" {...dndProps('row', row.id)}>\n <span>{ri + 1}</span>\n {!readOnly && <button className=\"shg-rowdel\" onClick={() => deleteRow(row.id)} title=\"Delete row\">×</button>}\n {!readOnly && (\n <span className=\"shg-resize-row\" onMouseDown={(e) => startResize(e, 'row', row.id, rowHeight(row) || e.currentTarget.closest('tr').offsetHeight)} />\n )}\n </td>\n {columns.map((col, ci) => {\n const key = cellKey(row.id, col.id);\n const c = cells[key] || {};\n const isEditing = editing && editing.rowId === row.id && editing.colId === col.id;\n const peer = peerLayer.focus[key];\n const ghost = !isEditing && peerLayer.typing[key];\n const selected = inSel(ri, ci), focused = isFocus(ri, ci);\n const shadows = [];\n if (focused) shadows.push('inset 0 0 0 2px var(--brand, #0E7490)');\n if (peer) shadows.push(`inset 0 0 0 2px ${peer.color}`);\n const tint = !selected && peerLayer.tint[key];\n return (\n <td key={col.id} data-cell={key}\n className={'shg-cell' + (col.type === 'compute' ? ' shg-cell-compute' : '')\n + (c.status && col.type === 'compute' ? ` shg-cell-${c.status}` : '')\n + (selected ? ' shg-sel' : '') + (focused ? ' shg-focus' : '')\n + (peer ? ' shg-cell-peer' : '')}\n style={{ ...(shadows.length ? { boxShadow: shadows.join(', ') } : null),\n ...(tint ? { background: withAlpha(tint, 0.10) } : null) }}\n onMouseDown={(e) => {\n if (e.button !== 0 || isEditing) return;\n if (editing) commitEdit();\n const p = { r: ri, c: ci };\n setSel((cur) => (e.shiftKey && cur ? { a: cur.a, f: p } : { a: p, f: p }));\n dragSel.current = true;\n e.preventDefault();\n rootRef.current?.focus();\n }}\n onMouseEnter={() => { if (dragSel.current) setSel((cur) => (cur ? { a: cur.a, f: { r: ri, c: ci } } : cur)); }}\n onClick={(e) => { if (col.type === 'checkbox' && !isEditing) openEdit(row.id, col, e.currentTarget); }}\n onDoubleClick={(e) => { if (!isEditing) openEdit(row.id, col, e.currentTarget); }}\n title={c.error || ''}>\n {peer && <span className=\"shg-peer-flag\" style={{ background: peer.color }}>{peer.name}</span>}\n {isEditing ? renderEditor(col) : (\n <div className=\"shg-val\"\n style={{ maxWidth: (colWidth(col) ? colWidth(col) - 20 : 400) }}>\n {col.type === 'compute' && <StatusDot status={c.status} />}\n {ghost ? (\n <span className=\"shg-ghost\" style={{ color: ghost.color }} title={`${ghost.name} is typing`}>{ghost.text}</span>\n ) : (\n <CellValue cell={c} col={col} fetchBlobUrl={fetchBlobUrl} onOpenResource={onOpenResource} />\n )}\n {col.type === 'compute' && !readOnly && onRunCell && (\n <button className=\"shg-runcell\" title=\"Run this cell\"\n onClick={(e) => { e.stopPropagation(); onRunCell(row.id, col.id); }}>▶</button>\n )}\n </div>\n )}\n </td>\n );\n })}\n {!readOnly && <td className=\"shg-pad\" />}\n </tr>\n ))}\n {!readOnly && (\n <tr className=\"shg-ghost-row\" onClick={addRow}>\n <td className=\"shg-rownum shg-ghost-num\" style={numStyle}>+</td>\n <td className=\"shg-ghost-cell\" colSpan={columns.length + 1}>New row</td>\n </tr>\n )}\n </tbody>\n </table>\n </div>\n </div>\n );\n}\n\nfunction ColumnHeader({ col, columns, readOnly, menuOpen, menuAnchor, onMenu, onCloseMenu, onRename, onConfigure, onDelete, onRun, width }) {\n const [editing, setEditing] = useState(false);\n const [name, setName] = useState(col.name);\n useEffect(() => setName(col.name), [col.name]);\n // A narrow column keeps its name: the caption goes first, then the Run label.\n const w = Number(width) || 0;\n const fit = w && w < 160 ? ' tight' : w && w < 200 ? ' narrow' : '';\n return (\n <div className={'shg-colhdr' + fit}>\n <div className=\"shg-colhdr-main\">\n {editing && !readOnly ? (\n <input className=\"shg-colname-input\" value={name} autoFocus\n onChange={(e) => setName(e.target.value)}\n onBlur={() => { setEditing(false); if (name.trim() && name !== col.name) onRename(col.id, name.trim()); }}\n onKeyDown={(e) => { if (e.key === 'Enter') e.target.blur(); }} />\n ) : (\n <span className=\"shg-colname\" onDoubleClick={() => !readOnly && setEditing(true)} title={col.name}>{col.name}</span>\n )}\n <span className={'shg-coltype' + (col.type === 'compute' ? ' compute' : '')}>\n {TYPE_LABEL[col.type] || col.type}\n {col.type === 'compute' && col.compute?.kind ? ` · ${col.compute.kind}` : ''}\n </span>\n </div>\n {!readOnly && (\n <div className=\"shg-colhdr-tools\">\n {onRun && <button className=\"shg-colrun\" onClick={onRun} title=\"Run this column\" aria-label=\"Run this column\">▶<span className=\"shg-colrun-label\"> Run</span></button>}\n <button className=\"shg-colmenu-btn\" onClick={(e) => onMenu(e)} title=\"Column settings\">⋯</button>\n </div>\n )}\n {menuOpen && !readOnly && (\n <ColumnMenu col={col} columns={columns} anchor={menuAnchor}\n onApply={(patch) => { onConfigure(col.id, patch); onCloseMenu(); }}\n onDelete={onDelete} onClose={onCloseMenu} />\n )}\n </div>\n );\n}\n\n// The column's values as pills in one field: type a value and press Enter or\n// comma to add it, Backspace on an empty field removes the last, and clicking\n// a pill opens the palette to pick its color. Select and tags columns offer\n// these as choices; every column paints a matching value in its color.\nfunction ValuePills({ values, onChange }) {\n const [text, setText] = useState('');\n const [picking, setPicking] = useState(null); // index of the pill whose palette is open\n const add = () => {\n const label = text.trim();\n if (!label) return;\n if (!values.some((v) => sameValue(v.label, label))) onChange([...values, { label }]);\n setText('');\n };\n const remove = (i) => { onChange(values.filter((_, j) => j !== i)); setPicking(null); };\n const paint = (i, color) => { onChange(values.map((v, j) => (j === i ? { ...v, color } : v))); setPicking(null); };\n return (\n <div className=\"shg-values\" onClick={(e) => { if (e.target === e.currentTarget) e.currentTarget.querySelector('input')?.focus(); }}>\n {values.map((v, i) => (\n <span key={v.label} className=\"shg-value\">\n <button type=\"button\" className=\"shg-pill shg-pill-btn\"\n style={{ background: v.color || PILL_FALLBACKS[i % PILL_FALLBACKS.length] }}\n title=\"Pick a color\" aria-expanded={picking === i}\n onClick={(e) => { e.stopPropagation(); setPicking(picking === i ? null : i); }}>\n {v.label}\n <span className=\"shg-value-x\" role=\"button\" aria-label={`Remove ${v.label}`}\n onClick={(e) => { e.stopPropagation(); remove(i); }}>×</span>\n </button>\n {picking === i && (\n <span className=\"shg-swatches\" role=\"listbox\" aria-label={`Color for ${v.label}`}>\n {PILL_PALETTE.map((p) => (\n <button key={p.name} type=\"button\" role=\"option\" aria-selected={v.color === p.color}\n className={'shg-swatch' + (v.color === p.color ? ' on' : '')}\n style={{ background: p.color }} title={p.name}\n onClick={(e) => { e.stopPropagation(); paint(i, p.color); }} />\n ))}\n </span>\n )}\n </span>\n ))}\n <input className=\"shg-values-input\" value={text} placeholder={values.length ? '' : 'Type a value, press Enter'}\n onChange={(e) => setText(e.target.value)}\n onKeyDown={(e) => {\n if (e.key === 'Enter' || e.key === ',') { e.preventDefault(); add(); }\n else if (e.key === 'Backspace' && !text && values.length) remove(values.length - 1);\n }}\n onBlur={add} />\n </div>\n );\n}\n\n// The column configuration popover: type, options (select/tags), and the\n// compute mount (prompt / harness / workflow + deps). Product-agnostic —\n// plain controlled inputs, applied as one patch.\nfunction ColumnMenu({ col, columns, anchor, onApply, onDelete, onClose }) {\n const [type, setType] = useState(col.type || 'text');\n // The column's values, in order, each with the color it was given (or none).\n const [values, setValues] = useState(() => (col.options || []).map((o) =>\n (typeof o === 'string' ? { label: o } : { label: o.label ?? String(o.value ?? ''), ...(o.color ? { color: o.color } : {}) })));\n const comp = col.compute || {};\n const [kind, setKind] = useState(comp.kind || 'prompt');\n const [prompt, setPrompt] = useState(comp.prompt || '');\n const [harnessId, setHarnessId] = useState(comp.harness_id || '');\n const [wfSlug, setWfSlug] = useState(comp.workflow_slug || '');\n const [outKey, setOutKey] = useState(comp.output_key || '');\n const [deps, setDeps] = useState(new Set(comp.deps || []));\n const ref = useRef(null);\n\n useEffect(() => {\n // a press inside the prompt's mention menu (a portal on the body) is not \"outside\"\n const onDown = (e) => {\n if (ref.current && !ref.current.contains(e.target) && !(e.target.closest && e.target.closest('.uic-pop'))) onClose();\n };\n window.addEventListener('mousedown', onDown);\n return () => window.removeEventListener('mousedown', onDown);\n }, [onClose]);\n\n // What the prompt may read: the columns to the LEFT of this one (a row fills left to right,\n // so those hold values when this cell computes). The rest are shown, but say why not.\n const promptItems = useMemo(() => {\n const at = columns.findIndex((c) => c.id === col.id);\n return columns.filter((c) => c.id !== col.id).map((c) => {\n const idx = columns.findIndex((x) => x.id === c.id);\n const right = at >= 0 && idx > at;\n return {\n id: c.id, name: c.name, kind: c.type, section: right ? 'Fills after this column' : 'Columns',\n icon: TYPE_GLYPH[c.type] || 'Aa', description: TYPE_LABEL[c.type] || c.type,\n color: c.type === 'compute' ? '#7C3AED' : undefined,\n disabled: right ? 'to the right' : false,\n };\n });\n }, [columns, col.id]);\n\n const apply = () => {\n const patch = { type };\n // A value with a chosen color travels as {label, color}; the rest as labels.\n patch.options = values.map((v) => (v.color ? { label: v.label, color: v.color } : v.label));\n if (type === 'compute') {\n const compute = { kind, deps: [...deps] };\n if (kind === 'prompt') compute.prompt = prompt;\n if (kind === 'harness') { compute.harness_id = harnessId; compute.prompt = prompt; }\n if (kind === 'workflow') { compute.workflow_slug = wfSlug; compute.output_key = outKey; }\n patch.compute = compute;\n }\n onApply(patch);\n };\n\n return (\n <PopPortal anchor={anchor} width={250} estHeight={340} className=\"shg-menu\" onClose={onClose}>\n <div ref={ref} onClick={(e) => e.stopPropagation()}>\n <label className=\"shg-menu-lbl\">Type\n <select className=\"shg-menu-input\" value={type} onChange={(e) => setType(e.target.value)}>\n {MANUAL_TYPES.map((t) => <option key={t} value={t}>{TYPE_LABEL[t]}</option>)}\n <option value=\"compute\">Computed</option>\n </select>\n </label>\n\n <div className=\"shg-menu-lbl\">{type === 'select' || type === 'tags' ? 'Options' : 'Values'}\n <ValuePills values={values} onChange={setValues} />\n </div>\n\n {type === 'compute' && (\n <>\n <label className=\"shg-menu-lbl\">Runs\n <select className=\"shg-menu-input\" value={kind} onChange={(e) => setKind(e.target.value)}>\n {COMPUTE_KINDS.map((k) => <option key={k.kind} value={k.kind}>{k.label}</option>)}\n </select>\n </label>\n {(kind === 'prompt' || kind === 'harness') && (\n <div className=\"shg-menu-lbl\">Prompt\n <div className=\"shg-menu-input shg-menu-prompt\">\n <MentionInput\n value={prompt}\n onChange={(v, ms) => { setPrompt(v); setDeps(new Set(ms.map((m) => m.id))); }}\n items={promptItems}\n placeholder=\"Summarize @Company in one line\"\n menuTitle=\"Columns this cell can read\"\n emptyText=\"No column by that name\"\n label=\"Prompt\"\n />\n </div>\n <div className=\"shg-menu-hint\">Type @ to add a column from this row. Columns to the left fill first.</div>\n </div>\n )}\n {kind === 'harness' && (\n <label className=\"shg-menu-lbl\">Agent id\n <input className=\"shg-menu-input\" value={harnessId} onChange={(e) => setHarnessId(e.target.value)} placeholder=\"chrn_…\" />\n </label>\n )}\n {kind === 'workflow' && (\n <>\n <label className=\"shg-menu-lbl\">Workflow id\n <input className=\"shg-menu-input\" value={wfSlug} onChange={(e) => setWfSlug(e.target.value)} placeholder=\"my-workflow\" />\n </label>\n <label className=\"shg-menu-lbl\">Output key (optional)\n <input className=\"shg-menu-input\" value={outKey} onChange={(e) => setOutKey(e.target.value)} placeholder=\"summary\" />\n </label>\n </>\n )}\n </>\n )}\n\n <div className=\"shg-menu-actions\">\n <button className=\"shg-menu-del\" onClick={onDelete}>Delete column</button>\n <button className=\"shg-menu-apply\" onClick={apply}>Apply</button>\n </div>\n </div>\n </PopPortal>\n );\n}\n\n// ── Export helpers (CSV / TSV / array-of-arrays) ─────────────────────────────\nexport function sheetToDelimited(sheet, sep = ',') {\n const cols = sheet?.columns || [];\n const rows = sheet?.rows || [];\n const cells = sheet?.cells || {};\n const esc = (v) => {\n const s = v == null ? '' : (Array.isArray(v) ? v.join(', ') : (typeof v === 'object' ? JSON.stringify(v) : String(v)));\n if (sep === ',' && /[\",\\n]/.test(s)) return `\"${s.replace(/\"/g, '\"\"')}\"`;\n return s;\n };\n const header = cols.map((c) => esc(c.name)).join(sep);\n const body = rows.map((r) => cols.map((c) => {\n const cell = cells[cellKey(r.id, c.id)];\n return esc(cell ? cell.value : '');\n }).join(sep));\n return [header, ...body].join('\\n');\n}\n\n/** Rows as an array-of-arrays (header first) — feed to an xlsx writer. */\nexport function sheetToAoA(sheet) {\n const cols = sheet?.columns || [];\n const rows = sheet?.rows || [];\n const cells = sheet?.cells || {};\n const val = (v) => (v == null ? '' : (Array.isArray(v) ? v.join(', ') : (typeof v === 'object' ? JSON.stringify(v) : v)));\n return [cols.map((c) => c.name),\n ...rows.map((r) => cols.map((c) => val(cells[cellKey(r.id, c.id)]?.value)))];\n}\n","// MentionInput — a text field that can hold people, columns, files: anything a host offers.\n//\n// Type the trigger (\"@\" by default) and a menu opens at the caret with the host's items, searched\n// as you type (name, description, keywords). Pick one and it becomes a pill in the text: one\n// unit to the caret and to Backspace, with its icon and name, tinted by kind. Underneath, the\n// value is a plain string in the host's token format ({{Name}} for a sheet prompt, @Name for a\n// chat message) and a `mentions` list rides beside it, so a host never parses text to learn who\n// was mentioned. Loading a value turns the tokens it can resolve back into pills.\n//\n// items [{ id, name, kind?, section?, description?, keywords?, icon?, avatar?, color?,\n// disabled? (true | 'reason'), tag? }] the menu, in the host's order\n// format { open, close } token spelling; CURLY ({{Name}}) by default, AT for @Name\n// trigger the character that opens the menu ('@')\n// onChange(value, mentions)\n// onSubmit() when given with submitOnEnter, Enter submits and Shift+Enter breaks the line\n// ref { focus(), insertMention(item), clear(), el }\n//\n// The editor is a contentEditable whose DOM is read back into the model on every input; the\n// menu is a Popover anchored to the caret. No dependency beyond react and react-dom.\nimport React, { forwardRef, useCallback, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState } from 'react';\nimport { Popover } from '../components/Popover.jsx';\nimport { CURLY, makeResolver, parseValue, serializeSegments, mentionsOf, groupItems, activeTrigger } from './mentionModel.js';\n\nconst MENTION_ATTR = 'data-mention-id';\n\nfunction monogram(name) {\n const parts = String(name || '').trim().split(/\\s+/).filter(Boolean);\n return ((parts[0] || '')[0] || '') + ((parts[1] || '')[0] || '') || '?';\n}\n\n// The pill, as a DOM node (the editor is not React-managed inside).\nexport function buildPillNode(item) {\n const el = document.createElement('span');\n el.className = 'uic-mention';\n el.setAttribute(MENTION_ATTR, item.id);\n el.setAttribute('data-name', item.name);\n if (item.kind) el.setAttribute('data-kind', item.kind);\n el.setAttribute('contenteditable', 'false');\n if (item.description) el.title = item.description;\n if (item.color) el.style.setProperty('--uic-mention-color', item.color);\n const ic = document.createElement('span');\n ic.className = 'uic-mention-ic';\n if (item.avatar) { const img = document.createElement('img'); img.src = item.avatar; img.alt = ''; ic.appendChild(img); }\n else { ic.textContent = typeof item.icon === 'string' && item.icon ? item.icon : monogram(item.name); if (!(typeof item.icon === 'string' && item.icon)) ic.classList.add('is-mono'); }\n const nm = document.createElement('span');\n nm.className = 'uic-mention-name';\n nm.textContent = item.name;\n el.appendChild(ic);\n el.appendChild(nm);\n return el;\n}\n\n// DOM -> segments. Text nodes are text, <br> and block boundaries are line breaks, a pill is a\n// mention; the browser's own trailing <br> (it keeps one so the last empty line can be reached)\n// is not a newline of the user's.\nfunction readSegments(root, resolver) {\n const out = [];\n let buf = '';\n const flush = () => { if (buf) { out.push({ type: 'text', text: buf }); buf = ''; } };\n const walk = (node, isLastAtRoot) => {\n const kids = Array.from(node.childNodes);\n kids.forEach((k, i) => {\n const last = isLastAtRoot && i === kids.length - 1;\n // a contentEditable writes a trailing space as a no-break space; the value keeps plain ones\n if (k.nodeType === 3) { buf += k.data.replace(/\\u00a0/g, ' '); return; }\n if (k.nodeType !== 1) return;\n const tag = k.tagName;\n if (tag === 'BR') { if (!last) buf += '\\n'; return; }\n if (k.hasAttribute(MENTION_ATTR)) {\n flush();\n const id = k.getAttribute(MENTION_ATTR);\n const name = k.getAttribute('data-name') || '';\n const item = resolver.get(name) || { id, name, kind: k.getAttribute('data-kind') || null };\n out.push({ type: 'mention', id: item.id, name: item.name, kind: item.kind || null, item });\n return;\n }\n if (tag === 'DIV' || tag === 'P') {\n // a block after other content starts a new line\n if (out.length || buf) buf += '\\n';\n walk(k, last);\n return;\n }\n walk(k, last);\n });\n };\n walk(root, true);\n flush();\n return out;\n}\n\n// segments -> DOM\nfunction writeSegments(root, segments) {\n root.textContent = '';\n for (const s of segments) {\n if (s.type === 'mention') { root.appendChild(buildPillNode(s.item || s)); continue; }\n const lines = String(s.text).split('\\n');\n lines.forEach((line, i) => {\n if (i > 0) root.appendChild(document.createElement('br'));\n if (line) root.appendChild(document.createTextNode(line));\n });\n }\n // the reachable last line\n root.appendChild(document.createElement('br'));\n}\n\nfunction placeCaretAfter(node) {\n const sel = window.getSelection();\n if (!sel) return;\n const r = document.createRange();\n r.setStartAfter(node);\n r.collapse(true);\n sel.removeAllRanges();\n sel.addRange(r);\n}\n\nfunction selectionIn(root) {\n const sel = typeof window !== 'undefined' ? window.getSelection() : null;\n if (!sel || !sel.rangeCount) return null;\n const r = sel.getRangeAt(0);\n if (!root.contains(r.startContainer)) return null;\n return { sel, range: r };\n}\n\nexport const MentionInput = forwardRef(function MentionInput(props, ref) {\n const {\n value = '', onChange, items = [], format = CURLY, trigger = '@', placeholder, disabled = false,\n onSubmit, submitOnEnter = false, autoFocus = false, className = '', label, menuWidth = 360,\n menuTitle, emptyText = 'No match', renderIcon, onOpenChange, onFocus, onBlur, onKeyDown, id,\n } = props;\n const editorRef = useRef(null);\n const resolver = useMemo(() => makeResolver(items), [items]);\n const [menu, setMenu] = useState(null); // { node, start, query, rect }\n const [active, setActive] = useState(0);\n const [empty, setEmpty] = useState(!value);\n const listId = useMemo(() => `uic-mention-${Math.random().toString(36).slice(2, 8)}`, []);\n\n // ── model <-> DOM ──\n const emit = useCallback(() => {\n const root = editorRef.current;\n if (!root) return;\n const segs = readSegments(root, resolver);\n const next = serializeSegments(segs, format);\n setEmpty(!next);\n if (onChange) onChange(next, mentionsOf(segs));\n }, [resolver, format, onChange]);\n\n // A value that arrives from outside (a reset after send, a loaded prompt) is drawn; the one\n // the editor just emitted is already on screen, so the caret is left alone.\n useLayoutEffect(() => {\n const root = editorRef.current;\n if (!root) return;\n const current = serializeSegments(readSegments(root, resolver), format);\n if (current === (value || '')) return;\n writeSegments(root, parseValue(value || '', format, resolver));\n setEmpty(!value);\n }, [value, resolver, format]);\n\n useEffect(() => { if (autoFocus && editorRef.current) editorRef.current.focus(); }, [autoFocus]);\n\n // ── the menu at the caret ──\n const closeMenu = useCallback(() => setMenu(null), []);\n useEffect(() => { if (onOpenChange) onOpenChange(!!menu); }, [menu, onOpenChange]);\n const groups = useMemo(() => (menu ? groupItems(items, menu.query) : []), [items, menu]);\n const flat = useMemo(() => groups.flatMap((g) => g.items), [groups]);\n useEffect(() => { setActive(0); }, [menu && menu.query, groups.length]);\n\n const syncMenu = useCallback(() => {\n const root = editorRef.current;\n const s = root && selectionIn(root);\n if (!s || !s.range.collapsed) { setMenu(null); return; }\n const node = s.range.startContainer;\n if (node.nodeType !== 3) { setMenu(null); return; }\n const hit = activeTrigger(node.data.slice(0, s.range.startOffset), trigger);\n if (!hit) { setMenu(null); return; }\n const r = document.createRange();\n r.setStart(node, hit.start);\n r.setEnd(node, Math.min(node.data.length, hit.start + 1));\n const rect = r.getBoundingClientRect();\n setMenu({ node, start: hit.start, query: hit.query, rect: rect.width || rect.height ? rect : root.getBoundingClientRect() });\n }, [trigger]);\n\n const anchorRef = useMemo(() => ({\n current: {\n getBoundingClientRect: () => (menu ? menu.rect : new DOMRect()),\n contains: () => false,\n },\n }), [menu]);\n\n const insertPill = useCallback((item, replace) => {\n const root = editorRef.current;\n if (!root || !item || item.disabled) return;\n const pill = buildPillNode(item);\n const space = document.createTextNode(' ');\n if (replace && replace.node && replace.node.parentNode === root) {\n const { node, start, query } = replace;\n node.deleteData(start, trigger.length + query.length);\n const after = node.splitText(start);\n root.insertBefore(pill, after);\n root.insertBefore(space, after);\n } else {\n const s = selectionIn(root);\n if (s) { s.range.deleteContents(); s.range.insertNode(space); s.range.insertNode(pill); }\n else { root.appendChild(pill); root.appendChild(space); }\n }\n placeCaretAfter(space);\n setMenu(null);\n emit();\n }, [emit, trigger]);\n\n const pick = useCallback((item) => insertPill(item, menu), [insertPill, menu]);\n\n const insertText = useCallback((text) => {\n const root = editorRef.current;\n if (!root) return;\n root.focus();\n let done = false;\n try { done = document.execCommand('insertText', false, text); } catch { done = false; }\n if (!done) {\n const s = selectionIn(root);\n const tn = document.createTextNode(text);\n if (s) { s.range.deleteContents(); s.range.insertNode(tn); placeCaretAfter(tn); }\n else root.appendChild(tn);\n }\n emit();\n syncMenu();\n }, [emit, syncMenu]);\n\n // Markdown helpers for a host's formatting row: wrap what is selected (or leave the caret\n // between the marks), or start the current line with a prefix.\n const wrapSelection = useCallback((before, after = '') => {\n const root = editorRef.current;\n if (!root) return;\n root.focus();\n const s = selectionIn(root);\n const selected = s ? s.range.toString() : '';\n insertText(before + selected + after);\n if (!selected && after) {\n const sel = window.getSelection();\n for (let i = 0; i < after.length; i++) sel && sel.modify && sel.modify('move', 'backward', 'character');\n }\n }, [insertText]);\n const prefixLine = useCallback((prefix) => {\n const root = editorRef.current;\n if (!root) return;\n root.focus();\n const s = selectionIn(root);\n const node = s && s.range.startContainer;\n const before = node && node.nodeType === 3 ? node.data.slice(0, s.range.startOffset) : '';\n const atLineStart = !before || /\\n$/.test(before) || (node && node.nodeType !== 3);\n insertText((atLineStart ? '' : '\\n') + prefix);\n }, [insertText]);\n\n useImperativeHandle(ref, () => ({\n focus: () => editorRef.current && editorRef.current.focus(),\n clear: () => { const root = editorRef.current; if (root) { writeSegments(root, []); emit(); } },\n insertMention: (item) => insertPill(item, null),\n insertText,\n wrapSelection,\n prefixLine,\n get el() { return editorRef.current; },\n }), [emit, insertPill, insertText, wrapSelection, prefixLine]);\n\n // ── events ──\n const handleInput = () => { emit(); syncMenu(); };\n const handleKeyDown = (e) => {\n if (onKeyDown) onKeyDown(e);\n if (e.defaultPrevented) return;\n if (menu) {\n if (e.key === 'ArrowDown') { e.preventDefault(); setActive((a) => (flat.length ? (a + 1) % flat.length : 0)); return; }\n if (e.key === 'ArrowUp') { e.preventDefault(); setActive((a) => (flat.length ? (a - 1 + flat.length) % flat.length : 0)); return; }\n if ((e.key === 'Enter' || e.key === 'Tab') && flat.length) { e.preventDefault(); pick(flat[active]); return; }\n if (e.key === 'Escape') { e.preventDefault(); setMenu(null); return; }\n }\n if (e.key === 'Enter') {\n if (submitOnEnter && !e.shiftKey) { e.preventDefault(); if (onSubmit) onSubmit(); return; }\n e.preventDefault();\n insertText('\\n');\n }\n };\n const handlePaste = (e) => {\n e.preventDefault();\n const text = (e.clipboardData && e.clipboardData.getData('text/plain')) || '';\n if (!text) return;\n // pasted tokens the host knows become pills, the rest stays text\n const segs = parseValue(text, format, resolver);\n if (segs.every((s) => s.type === 'text')) { insertText(text); return; }\n const root = editorRef.current;\n const s = selectionIn(root);\n if (!s) { insertText(text); return; }\n s.range.deleteContents();\n const frag = document.createDocumentFragment();\n let lastNode = null;\n for (const seg of segs) {\n if (seg.type === 'mention') { lastNode = buildPillNode(seg.item || seg); frag.appendChild(lastNode); continue; }\n seg.text.split('\\n').forEach((line, i) => {\n if (i > 0) { lastNode = document.createElement('br'); frag.appendChild(lastNode); }\n if (line) { lastNode = document.createTextNode(line); frag.appendChild(lastNode); }\n });\n }\n s.range.insertNode(frag);\n if (lastNode) placeCaretAfter(lastNode);\n emit();\n syncMenu();\n };\n const handleBlur = (e) => { if (onBlur) onBlur(e); };\n const handleFocus = (e) => { if (onFocus) onFocus(e); };\n\n // the caret moving away from the trigger (a click, an arrow) closes the menu\n useEffect(() => {\n if (!menu) return undefined;\n const onSel = () => syncMenu();\n document.addEventListener('selectionchange', onSel);\n return () => document.removeEventListener('selectionchange', onSel);\n }, [menu, syncMenu]);\n\n // the active option stays in view: the list scrolls, never the page (scrollIntoView can\n // move the document under a host that watches it)\n useEffect(() => {\n if (!menu) return;\n const el = document.getElementById(`${listId}-${active}`);\n const list = el && el.closest('.uic-mention-menu');\n if (!el || !list) return;\n const top = el.offsetTop - list.offsetTop;\n const bottom = top + el.offsetHeight;\n if (top < list.scrollTop) list.scrollTop = top;\n else if (bottom > list.scrollTop + list.clientHeight) list.scrollTop = bottom - list.clientHeight;\n }, [active, menu, listId]);\n\n const iconOf = (item) => {\n if (renderIcon) { const n = renderIcon(item); if (n) return n; }\n if (item.avatar) return <img src={item.avatar} alt=\"\" />;\n if (typeof item.icon === 'string' && item.icon) return item.icon;\n if (item.icon) return item.icon;\n return <span className=\"is-mono\">{monogram(item.name)}</span>;\n };\n\n let index = -1;\n return (\n <div className={['uic-mention-field', disabled ? 'is-disabled' : '', className].filter(Boolean).join(' ')}>\n <div\n ref={editorRef}\n id={id}\n className={'uic-mention-editor' + (empty ? ' is-empty' : '')}\n contentEditable={!disabled}\n suppressContentEditableWarning\n role=\"textbox\"\n aria-multiline=\"true\"\n aria-label={label}\n aria-autocomplete=\"list\"\n aria-expanded={!!menu}\n aria-controls={menu ? listId : undefined}\n aria-activedescendant={menu && flat.length ? `${listId}-${active}` : undefined}\n data-placeholder={placeholder || ''}\n spellCheck=\"true\"\n onInput={handleInput}\n onKeyDown={handleKeyDown}\n onPaste={handlePaste}\n onFocus={handleFocus}\n onBlur={handleBlur}\n />\n <Popover open={!!menu} anchorRef={anchorRef} onClose={closeMenu} width={menuWidth} minHeight={120} className=\"uic-mention-pop\" label={menuTitle || 'Mentions'}>\n <div className=\"uic-mention-menu\" role=\"listbox\" id={listId} onMouseDown={(e) => e.preventDefault()}>\n {menuTitle ? <div className=\"uic-mention-head\">{menuTitle}</div> : null}\n {groups.map((g) => (\n <div className=\"uic-mention-group\" key={g.section || '_'}>\n {g.section ? <div className=\"uic-mention-sec\">{g.section}</div> : null}\n {g.items.map((item) => {\n index += 1;\n const i = index;\n const dis = !!item.disabled;\n const reason = typeof item.disabled === 'string' ? item.disabled : null;\n return (\n <button\n key={item.id} type=\"button\" id={`${listId}-${i}`} role=\"option\" aria-selected={i === active} aria-disabled={dis || undefined}\n className={'uic-mention-item' + (i === active ? ' is-active' : '') + (dis ? ' is-disabled' : '')}\n style={item.color ? { '--uic-mention-color': item.color } : undefined}\n onMouseEnter={() => setActive(i)}\n onClick={() => { if (!dis) pick(item); }}\n >\n <span className=\"uic-mention-ic\">{iconOf(item)}</span>\n <span className=\"uic-mention-text\">\n <span className=\"uic-mention-name\">{item.name}</span>\n {item.description ? <span className=\"uic-mention-desc\">{item.description}</span> : null}\n </span>\n {reason || item.tag ? <span className=\"uic-mention-tag\">{reason || item.tag}</span> : null}\n </button>\n );\n })}\n </div>\n ))}\n {!flat.length ? <div className=\"uic-mention-empty\">{emptyText}</div> : null}\n </div>\n </Popover>\n </div>\n );\n});\n\n// Read-only: a stored value drawn with its pills, for a message or a preview.\nexport function MentionText({ value, items = [], format = CURLY, className = '', renderIcon }) {\n const resolver = useMemo(() => makeResolver(items), [items]);\n const segs = useMemo(() => parseValue(value || '', format, resolver), [value, format, resolver]);\n return (\n <span className={['uic-mention-text-view', className].filter(Boolean).join(' ')}>\n {segs.map((s, i) => {\n if (s.type === 'text') return <React.Fragment key={i}>{s.text}</React.Fragment>;\n const item = s.item || s;\n const icon = renderIcon ? renderIcon(item) : null;\n return (\n <span key={i} className=\"uic-mention\" data-kind={s.kind || undefined} title={item.description || undefined}\n style={item.color ? { '--uic-mention-color': item.color } : undefined}>\n <span className={'uic-mention-ic' + (icon || (typeof item.icon === 'string' && item.icon) || item.avatar ? '' : ' is-mono')}>\n {icon || (item.avatar ? <img src={item.avatar} alt=\"\" /> : (typeof item.icon === 'string' && item.icon ? item.icon : monogram(item.name)))}\n </span>\n <span className=\"uic-mention-name\">{s.name}</span>\n </span>\n );\n })}\n </span>\n );\n}\n","// Popover — a panel anchored to a control: a menu, a picker, a row's overflow actions.\n//\n// Ten of these were hand-rolled across four apps, each with its own mousedown-outside listener,\n// and exactly ONE of the ten survived a 390px viewport: the other nine positioned themselves with\n// `position: absolute; bottom: 36px` and either ran off the screen or grew taller than it. That\n// one implementation's placement logic is what this component is, so placement is built IN and\n// is not separately exportable — a hook you can skip is how you ship the other nine again.\n//\n// It portals to the body and positions itself `fixed`, so it is never clipped by an ancestor's\n// overflow (the reason the absolute ones lived inside their own scroll containers).\nimport React, { useCallback, useEffect, useRef, useState } from 'react';\nimport { createPortal } from 'react-dom';\nimport { useOverlayEscape } from './overlay.js';\n\nconst GAP = 6; // between the anchor and the panel\nconst MARGIN = 8; // minimum clearance from the viewport edge\n\n/**\n * open render it\n * anchorRef ref to the control it belongs to; the panel positions against its box\n * onClose Escape, an outside pointerdown, or the caller's own reason\n * width preferred width; clamped to the viewport\n * minHeight never squeeze below this — flip to the other side instead\n * placement 'auto' (default) picks the side with more room; 'above'/'below' force one\n */\nexport function Popover(props) {\n const { open, anchorRef, onClose, width = 280, minHeight = 140, placement = 'auto',\n children, className, label } = props;\n const popRef = useRef(null);\n const [pos, setPos] = useState(null);\n\n useEffect(() => {\n if (!open) { setPos(null); return undefined; }\n const place = () => {\n const el = anchorRef?.current;\n if (!el) return;\n const r = el.getBoundingClientRect();\n const vw = window.innerWidth;\n const vh = window.innerHeight;\n const w = Math.min(width, vw - MARGIN * 2);\n const below = vh - r.bottom - GAP - MARGIN;\n const above = r.top - GAP - MARGIN;\n const up = placement === 'above'\n || (placement === 'auto' && below < minHeight && above > below);\n const maxHeight = Math.max(minHeight, Math.floor(up ? above : below));\n const left = Math.max(MARGIN, Math.min(r.left, vw - w - MARGIN));\n setPos(up\n ? { left, bottom: Math.round(vh - r.top + GAP), width: w, maxHeight }\n : { left, top: Math.round(r.bottom + GAP), width: w, maxHeight });\n };\n place();\n window.addEventListener('resize', place);\n // Capture phase: the anchor is usually inside a scrolling pane, and a scroll event on that\n // pane does not bubble to the window.\n window.addEventListener('scroll', place, true);\n return () => {\n window.removeEventListener('resize', place);\n window.removeEventListener('scroll', place, true);\n };\n }, [open, anchorRef, width, minHeight, placement]);\n\n useEffect(() => {\n if (!open) return undefined;\n const onDown = (e) => {\n if (popRef.current?.contains(e.target)) return;\n // The anchor closes it through its own onClick; treating the press as \"outside\" here would\n // close and immediately reopen it.\n if (anchorRef?.current?.contains(e.target)) return;\n onClose?.();\n };\n document.addEventListener('pointerdown', onDown);\n return () => document.removeEventListener('pointerdown', onDown);\n }, [open, anchorRef, onClose]);\n\n const escape = useCallback(() => onClose?.(), [onClose]);\n useOverlayEscape(open, escape);\n\n if (!open || !pos || typeof document === 'undefined') return null;\n return createPortal(\n <div ref={popRef} className={['uic-pop', className || ''].filter(Boolean).join(' ')}\n style={pos} role=\"dialog\" aria-label={label}>\n {children}\n </div>,\n document.body,\n );\n}\n","// The mention model: what a mention input holds, how it is written down, and how a menu is\n// searched. Pure functions, no DOM, no React, so the same code serves the editor, the\n// read-only renderer of a stored message, and a test.\n//\n// A value is a plain string with tokens in it. The token format belongs to the host:\n// { open: '{{', close: '}}' } a sheet prompt: \"Grade {{Answer}} against {{Gold}}\"\n// { open: '@', close: '' } a chat message: \"@Project Manager can you take CT-281\"\n// A token names the item (its `name`), so the string stays readable wherever it travels, and\n// the editor keeps a `mentions` list beside it ({id, name, kind}) so a host never parses text\n// to learn who was mentioned.\n\nexport const CURLY = Object.freeze({ open: '{{', close: '}}' });\nexport const AT = Object.freeze({ open: '@', close: '' });\n// A chat message carries the id too, as a markdown link a sanitizer lets through:\n// [@Project Manager](#m-member.bot.project_manager)\nexport const CHAT_LINK = Object.freeze({\n write: (item) => `[@${item.name}](#m-${item.id})`,\n pattern: /\\[@(?<name>[^\\]\\n]+)\\]\\(#m-(?<id>[^)\\s]+)\\)/g,\n});\n\n/** A resolver answers `name -> item | null`. Built from the items a host offers, longest names\n * first, so \"@Project Manager\" is not read as \"@Project\" + \" Manager\". */\nexport function makeResolver(items) {\n const byName = new Map();\n const byId = new Map();\n for (const it of items || []) {\n if (!it) continue;\n if (it.name) byName.set(it.name, it);\n if (it.id != null) byId.set(String(it.id), it);\n }\n const names = [...byName.keys()].sort((a, b) => b.length - a.length);\n return { get: (name) => byName.get(name) || null, byId: (id) => byId.get(String(id)) || null, names };\n}\n\n// A token spelled with its id parses even when the item is not offered any more (a member who\n// left, a column since renamed): the name in the token is what is shown.\nfunction parsePattern(text, format, resolver) {\n const out = [];\n const re = new RegExp(format.pattern.source, format.pattern.flags.includes('g') ? format.pattern.flags : format.pattern.flags + 'g');\n let last = 0;\n let m;\n while ((m = re.exec(text))) {\n if (m.index > last) out.push({ type: 'text', text: text.slice(last, m.index) });\n const id = m.groups && m.groups.id != null ? m.groups.id : null;\n const name = (m.groups && m.groups.name) || '';\n const item = (id != null && resolver && resolver.byId(id)) || (resolver && resolver.get(name)) || { id: id ?? name, name, kind: null };\n out.push({ type: 'mention', id: item.id, name: item.name || name, kind: item.kind || null, item });\n last = m.index + m[0].length;\n }\n if (last < text.length) out.push({ type: 'text', text: text.slice(last) });\n return out;\n}\n\n/** value -> segments: [{ type: 'text', text }] and [{ type: 'mention', id, name, kind, item }].\n * Only names the resolver knows become mentions; anything else stays text, verbatim. */\nexport function parseValue(value, format, resolver) {\n const text = value == null ? '' : String(value);\n if (format && format.pattern) return parsePattern(text, format, resolver);\n const { open, close } = format || CURLY;\n const out = [];\n let buf = '';\n let i = 0;\n const flush = () => { if (buf) { out.push({ type: 'text', text: buf }); buf = ''; } };\n while (i < text.length) {\n if (resolver && text.startsWith(open, i)) {\n // At a word boundary for the bare \"@\" form: \"email@host\" is not a mention.\n const boundary = close ? true : (i === 0 || /[\\s([{\"'>]/.test(text[i - 1]));\n let hit = null;\n if (boundary) {\n for (const name of resolver.names) {\n const start = i + open.length;\n if (text.startsWith(name, start)) {\n const end = start + name.length;\n if (!close || text.startsWith(close, end)) {\n // the bare form must end at a word boundary too\n if (close || end === text.length || /[\\s.,;:!?)\\]}\"']/.test(text[end])) { hit = { name, end: end + close.length }; break; }\n }\n }\n }\n }\n if (hit) {\n flush();\n const item = resolver.get(hit.name);\n out.push({ type: 'mention', id: item.id, name: item.name, kind: item.kind || null, item });\n i = hit.end;\n continue;\n }\n }\n buf += text[i];\n i += 1;\n }\n flush();\n return out;\n}\n\n/** segments -> value string in the host's format. */\nexport function serializeSegments(segments, format) {\n const f = format || CURLY;\n if (f.write) return (segments || []).map((s) => (s.type === 'mention' ? f.write(s.item || s) : s.text)).join('');\n const { open, close } = f;\n return (segments || []).map((s) => (s.type === 'mention' ? `${open}${s.name}${close}` : s.text)).join('');\n}\n\n/** The distinct mentions in a segment list, in order of first appearance. */\nexport function mentionsOf(segments) {\n const seen = new Set();\n const out = [];\n for (const s of segments || []) {\n if (s.type !== 'mention' || seen.has(s.id)) continue;\n seen.add(s.id);\n out.push({ id: s.id, name: s.name, kind: s.kind || null });\n }\n return out;\n}\n\n// ── search ──────────────────────────────────────────────────────────────────\n// Free text over name, description and keywords. A name that starts with the query ranks\n// first, then a word of the name, then anything containing it, then a subsequence (typing\n// \"pm\" finds \"Project Manager\"); a description or keyword match trails the name matches.\nfunction norm(s) { return String(s || '').toLowerCase(); }\n\nfunction subsequence(hay, needle) {\n let j = 0;\n for (let i = 0; i < hay.length && j < needle.length; i++) if (hay[i] === needle[j]) j++;\n return j === needle.length;\n}\n\nexport function scoreItem(item, query) {\n const q = norm(query).trim();\n if (!q) return 1;\n const name = norm(item.name);\n if (name === q) return 120;\n if (name.startsWith(q)) return 100;\n if (name.split(/[\\s_-]+/).some((w) => w.startsWith(q))) return 80;\n if (name.includes(q)) return 60;\n const initials = name.split(/[\\s_-]+/).map((w) => w[0]).join('');\n if (initials.startsWith(q)) return 50;\n if (subsequence(name, q)) return 30;\n const desc = norm(item.description);\n if (desc && desc.includes(q)) return 20;\n const kws = (item.keywords || []).map(norm);\n if (kws.some((k) => k.includes(q))) return 15;\n return 0;\n}\n\n/** Items that match, best first, stable within a score (host order wins ties). */\nexport function searchItems(items, query) {\n const scored = (items || []).map((it, i) => ({ it, i, s: scoreItem(it, query) })).filter((x) => x.s > 0);\n scored.sort((a, b) => b.s - a.s || a.i - b.i);\n return scored.map((x) => x.it);\n}\n\n/** Matching items grouped by section, sections in the order the host listed them\n * (items without a section share the unnamed group, first). */\nexport function groupItems(items, query) {\n const groups = new Map();\n for (const it of searchItems(items, query)) {\n const key = it.section || '';\n if (!groups.has(key)) groups.set(key, []);\n groups.get(key).push(it);\n }\n const order = [''];\n for (const it of items || []) { const k = it.section || ''; if (!order.includes(k)) order.push(k); }\n return order.filter((k) => groups.has(k)).map((k) => ({ section: k, items: groups.get(k) }));\n}\n\n/** Where a trigger is live in a piece of text ending at the caret: the query typed after it,\n * or null. A trigger counts only at a word start and only while the query has no line break\n * and is not too long to be a name someone is still typing. */\nexport function activeTrigger(textBeforeCaret, trigger = '@', maxLen = 48) {\n const at = textBeforeCaret.lastIndexOf(trigger);\n if (at < 0) return null;\n if (at > 0 && !/[\\s([{\"'>]/.test(textBeforeCaret[at - 1])) return null;\n const query = textBeforeCaret.slice(at + trigger.length);\n if (query.length > maxLen || /\\n/.test(query)) return null;\n return { start: at, query };\n}\n","// One palette for everyone who shows up in a shared document: the cursor in a\n// doc, the selection in a sheet, the drag on a graph canvas. A person's color\n// comes from their member id, so they look the same in every surface and to\n// every viewer, with no per-document assignment to disagree.\nexport const PEER_PALETTE = ['#1e40af', '#c2410c', '#15803d', '#6d28d9', '#be123c', '#0e7490', '#a16207', '#4338ca'];\n\nexport function peerColor(key) {\n let h = 0;\n for (const ch of String(key || '')) h = (h * 31 + ch.charCodeAt(0)) >>> 0;\n return PEER_PALETTE[h % PEER_PALETTE.length];\n}\n\n/** rgba() of a #rrggbb color. */\nexport function withAlpha(hex, alpha) {\n const m = /^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(String(hex || ''));\n if (!m) return hex;\n return `rgba(${parseInt(m[1], 16)}, ${parseInt(m[2], 16)}, ${parseInt(m[3], 16)}, ${alpha})`;\n}\n","// The coloured file-type glyph — pdf red, docx blue, xlsx green, pptx orange, py yellow.\n//\n// react-file-icon is the standard library for this and it is already what the HarnessRouter\n// console draws, so a file looks the same wherever it appears: a card under an answer, a card in\n// a spreadsheet cell, the header of a preview pane. Redrawing these per surface is how two\n// products end up disagreeing about what a .pptx looks like.\n//\n// The dependency is OPTIONAL. Where it is absent the extension is drawn as a plain badge rather\n// than nothing, because a file with no glyph still needs to be identifiable.\nimport { useEffect, useState } from 'react';\n\nexport function extOf(name) {\n const m = String(name || '').toLowerCase().match(/\\.([a-z0-9]+)$/);\n return m ? m[1] : '';\n}\n\nlet mod = null; // { FileIcon, defaultStyles } once resolved\nlet tried = false;\n\nexport function FileTypeIcon({ name, size = 36 }) {\n const [, force] = useState(0);\n const ext = extOf(name);\n\n useEffect(() => {\n if (tried || mod) return;\n tried = true;\n import('react-file-icon')\n .then((m) => { mod = m; force((n) => n + 1); })\n .catch(() => { /* not installed; the badge below is the answer */ });\n }, []);\n\n const box = { width: size, height: Math.round(size * 1.16), display: 'inline-block', flex: '0 0 auto' };\n\n if (!mod) {\n return (\n <span className=\"uic-fileglyph\" style={box} aria-hidden=\"true\">\n <span className=\"uic-fileglyph-ext\">{(ext || 'file').slice(0, 4)}</span>\n </span>\n );\n }\n const { FileIcon, defaultStyles } = mod;\n const style = defaultStyles?.[ext] || {};\n return (\n <span style={box}>\n <FileIcon extension={ext || undefined} {...style} />\n </span>\n );\n}\n","// One produced file, as a card: type glyph, name, what it is, download, preview.\n//\n// The same card under a chat answer and inside a spreadsheet cell. Those two started as different\n// things — a full-width row with a Preview button, and a bare text chip — which is how one surface\n// ends up with a download affordance the other never got.\n//\n// There is ONE card. There was briefly a `compact` variant for grid cells, which shrank the\n// actions to two 20px glyphs on a tinted background; it was a worse version of the thing it was\n// a variant of, which is what a variant usually is. A cell narrow enough to need a different card\n// is a cell too narrow to show the file at all — the name ellipsises and the card still works.\nimport { FileTypeIcon, extOf } from './FileTypeIcon.jsx';\nimport { IcDownload } from './icons.jsx';\n\n/** \"PPTX · output\" — what it is, then where it came from. `origin` is the caller's word. */\nfunction subtitle(name, origin, bytes) {\n const parts = [(extOf(name) || 'file').toUpperCase()];\n if (origin) parts.push(origin);\n if (bytes != null) parts.push(bytesLabel(bytes));\n return parts.join(' · ');\n}\n\nexport function bytesLabel(n) {\n if (n == null) return '';\n if (n < 1024) return `${n} B`;\n if (n < 1048576) return `${Math.round(n / 1024)} KB`;\n return `${(n / 1048576).toFixed(1)} MB`;\n}\n\nexport function FileCard({ name, origin = 'output', bytes, onPreview, onDownload, className = '' }) {\n // The whole card opens the preview, and the eye repeats it as an explicit target — a card that\n // is clickable without saying so is a card people do not click.\n const open = onPreview ? (e) => { e.stopPropagation(); onPreview(); } : undefined;\n return (\n <div className={'uic-filecard' + (open ? ' is-clickable' : '') + (className ? ' ' + className : '')}\n onClick={open}\n role={open ? 'button' : undefined}\n tabIndex={open ? 0 : undefined}\n onKeyDown={open ? (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); open(e); } } : undefined}\n title={name}>\n <span className=\"uic-filecard-ic\"><FileTypeIcon name={name} size={32} /></span>\n <span className=\"uic-filecard-meta\">\n <span className=\"uic-filecard-name\">{name}</span>\n <span className=\"uic-filecard-sub\">{subtitle(name, origin, bytes)}</span>\n </span>\n {onDownload && (\n <button type=\"button\" className=\"uic-filecard-dl\" aria-label={`Download ${name}`} title=\"Download\"\n onClick={(e) => { e.stopPropagation(); onDownload(); }}>\n <IcDownload size={18} />\n </button>\n )}\n {onPreview && (\n <button type=\"button\" className=\"uic-filecard-open\" aria-label={`Preview ${name}`} onClick={open}>\n Preview\n </button>\n )}\n </div>\n );\n}\n","// One produced file, rendered. Images, pdf, video, audio, Markdown, spreadsheets, delimited text\n// and code all render inline; anything else says so and offers the download.\n//\n// Ported from the HarnessRouter console, where it was already the answer, so a file previews the\n// same wherever it is opened. Two things changed on the way in, both because a package cannot\n// assume a product:\n//\n// - transport is injected. The console fetches with an auth header; a kit is same-origin and\n// needs none. `fetchFile` defaults to a plain fetch, which is right for same-origin callers.\n// - markdown, code and SPREADSHEETS render through props. The package does not depend on a\n// markdown library, and it already ships one code renderer (CodeBlock) — adding a second\n// highlighter to render the same text twice is the duplication this component exists to\n// argue against.\n//\n// `parseWorkbook` is the same rule, learned the hard way: this file used to `await\n// import('xlsx')` directly, which put a spreadsheet library in the dependency graph of every\n// app that imports anything from this package's root. A kit that shows slides, or charts,\n// and has never heard of a spreadsheet then fails to BUILD — Rollup cannot resolve a dynamic\n// import of a package that is not installed. The rule the chart entry states (\"an app that\n// imports a Button must not resolve a charting library\") was already being broken here.\n// Without the prop, spreadsheets fall through to the download, honestly labelled.\n//\n// `officePdfUrl` is how a caller offers a server-rendered PDF for formats no browser draws\n// (pptx, docx, odp). Without it those fall through to the download, honestly labelled.\nimport { useEffect, useState } from 'react';\nimport { FileTypeIcon, extOf } from './FileTypeIcon.jsx';\nimport { CodeBlock } from './CodeBlock.jsx';\nimport { IcDownload, IcX } from './icons.jsx';\n\nconst LANG = {\n js: 'javascript', mjs: 'javascript', cjs: 'javascript', jsx: 'javascript', ts: 'typescript',\n tsx: 'typescript', py: 'python', rb: 'ruby', go: 'go', rs: 'rust', java: 'java', c: 'c', h: 'c',\n cpp: 'cpp', hpp: 'cpp', cs: 'csharp', php: 'php', swift: 'swift', kt: 'kotlin', scala: 'scala',\n sh: 'bash', bash: 'bash', zsh: 'bash', sql: 'sql', css: 'css', scss: 'scss', less: 'less',\n html: 'xml', htm: 'xml', xml: 'xml', svg: 'xml', json: 'json', yaml: 'yaml', yml: 'yaml',\n toml: 'ini', ini: 'ini', r: 'r', lua: 'lua', pl: 'perl', dockerfile: 'dockerfile', diff: 'diff',\n md: 'markdown', txt: 'plaintext', log: 'plaintext', csv: 'plaintext',\n};\n\n// Presentations and word documents render faithfully through the server's PDF rendition.\n// Spreadsheets render as a real grid instead — a PDF of a sheet is the wrong mental model.\nconst OFFICE = new Set(['pptx', 'ppt', 'pptm', 'odp', 'doc', 'docx', 'odt', 'rtf']);\nconst SHEET = new Set(['xls', 'xlsx', 'xlsm', 'xlsb', 'ods']);\n\nfunction kindOf(name, mime = '') {\n const e = extOf(name);\n if (mime.startsWith('image/') || /^(png|jpe?g|gif|webp|svg|bmp|ico|avif)$/.test(e)) return 'image';\n if (mime === 'application/pdf' || e === 'pdf') return 'pdf';\n if (mime.startsWith('video/') || ['mp4', 'webm', 'mov', 'm4v'].includes(e)) return 'video';\n if (mime.startsWith('audio/') || ['mp3', 'wav', 'ogg', 'm4a', 'flac'].includes(e)) return 'audio';\n if (e === 'csv' || e === 'tsv') return 'csv';\n if (e === 'md' || e === 'markdown') return 'markdown';\n if (e === 'html' || e === 'htm') return 'html'; // the page itself, or its source: the header switches\n if (SHEET.has(e)) return 'sheet';\n if (OFFICE.has(e)) return 'office';\n if (mime.startsWith('text/') || LANG[e] || /^(txt|log|env|conf|cfg|gitignore)$/.test(e)) return 'code';\n return 'binary';\n}\n\nfunction delimitedToRows(text, sep) {\n return text.split(/\\r?\\n/).filter((l) => l.length).slice(0, 1000).map((line) => {\n const out = []; let cur = ''; let q = false;\n for (const ch of line) {\n if (ch === '\"') q = !q;\n else if (ch === sep && !q) { out.push(cur); cur = ''; }\n else cur += ch;\n }\n out.push(cur);\n return out.map((c) => c.replace(/^\"|\"$/g, ''));\n });\n}\n\nfunction Grid({ rows }) {\n if (!rows?.length) return <div className=\"uic-fp-empty\">This file is empty.</div>;\n const [head, ...body] = rows;\n return (\n <div className=\"uic-fp-sheet\">\n <table>\n <thead><tr>{head.map((c, i) => <th key={i}>{c}</th>)}</tr></thead>\n <tbody>{body.map((r, i) => <tr key={i}>{r.map((c, j) => <td key={j}>{c}</td>)}</tr>)}</tbody>\n </table>\n </div>\n );\n}\n\nconst defaultDownload = (url, name) => {\n const a = document.createElement('a');\n a.href = url; a.download = name; a.rel = 'noreferrer';\n document.body.appendChild(a); a.click(); a.remove();\n};\n\n/**\n * `parseWorkbook(arrayBuffer)` → `[{ name, filled, rows }]`, one entry per tab, where `rows` is\n * an array-of-arrays (header row first) and `filled` says whether the tab has anything in it at\n * all. Async, so the caller can load its spreadsheet library lazily.\n */\nexport function FilePreview({\n file, onClose, fetchFile, officePdfUrl, renderMarkdown, parseWorkbook, onDownload, title,\n}) {\n const { url, name } = file || {};\n const [st, setSt] = useState({ kind: 'loading' });\n const [tab, setTab] = useState(0);\n // An HTML file opens as the page it is; Source shows what was written. The choice lives in the\n // header, beside the name, so it reads as a property of the file being looked at.\n const [view, setView] = useState('preview');\n\n useEffect(() => {\n if (!url) return undefined;\n let alive = true;\n let obj;\n setSt({ kind: 'loading' });\n setTab(0);\n setView('preview');\n const get = fetchFile || ((u) => fetch(u, { cache: 'no-store' }));\n\n (async () => {\n const res = await get(url);\n if (!res.ok) throw new Error(`${res.status}`);\n const mime = (res.headers.get('content-type') || '').toLowerCase();\n const kind = kindOf(name, mime);\n\n if (kind === 'office') {\n // The rendition needs the same transport, so it is fetched to a blob rather than handed\n // to an <iframe src> that would carry no credentials.\n if (!officePdfUrl) {\n setSt({ kind: 'binary', error: 'This format has no preview here. Download it to open it.' });\n return;\n }\n const r = await get(officePdfUrl(url));\n if (!r.ok) throw new Error(`${r.status}`);\n obj = URL.createObjectURL(await r.blob());\n if (alive) setSt({ kind: 'pdf', objUrl: obj });\n return;\n }\n if (kind === 'sheet') {\n if (!parseWorkbook) {\n setSt({ kind: 'binary', error: 'This format has no preview here. Download it to open it.' });\n return;\n }\n try {\n const sheets = await parseWorkbook(await res.arrayBuffer());\n // Open on the first sheet that has something: opening on an empty one reads as a broken\n // preview rather than as an empty tab.\n const first = sheets.findIndex((s) => s.filled);\n if (alive) { setTab(first < 0 ? 0 : first); setSt({ kind: 'sheet', sheets }); }\n } catch (e) {\n if (alive) setSt({ kind: 'binary', error: `This spreadsheet couldn’t be read (${String(e?.message || 'parse failed').slice(0, 80)}).` });\n }\n return;\n }\n if (kind === 'csv' || kind === 'markdown' || kind === 'code' || kind === 'html') {\n const text = await res.text();\n if (!alive) return;\n if (kind === 'csv') setSt({ kind: 'csv', rows: delimitedToRows(text, extOf(name) === 'tsv' ? '\\t' : ',') });\n else setSt({ kind, text: text.slice(0, 400000) });\n return;\n }\n if (kind === 'binary') { if (alive) setSt({ kind: 'binary' }); return; }\n obj = URL.createObjectURL(await res.blob());\n if (alive) setSt({ kind, objUrl: obj });\n })().catch(() => { if (alive) setSt({ kind: 'binary', error: 'Could not load this file.' }); });\n\n return () => { alive = false; if (obj) URL.revokeObjectURL(obj); };\n }, [url, name, fetchFile, officePdfUrl, parseWorkbook]);\n\n const download = () => (onDownload ? onDownload(url, name) : defaultDownload(url, name));\n\n return (\n <aside className=\"uic-fp\" aria-label={title || `Preview of ${name}`}>\n <header className=\"uic-fp-head\">\n <span className=\"uic-fp-ic\"><FileTypeIcon name={name} size={20} /></span>\n <span className=\"uic-fp-name\" title={name}>{name}</span>\n {st.kind === 'html' && (\n <div className=\"uic-fp-seg\" role=\"tablist\" aria-label=\"Show the page or its source\">\n {[['preview', 'Preview'], ['source', 'Source']].map(([id, label]) => (\n <button key={id} type=\"button\" role=\"tab\" aria-selected={view === id}\n className={'uic-fp-seg-btn' + (view === id ? ' is-on' : '')} onClick={() => setView(id)}>{label}</button>\n ))}\n </div>\n )}\n <button type=\"button\" className=\"uic-fp-btn\" aria-label={`Download ${name}`} title=\"Download\"\n onClick={download}><IcDownload /></button>\n {onClose && (\n <button type=\"button\" className=\"uic-fp-btn\" aria-label=\"Close preview\" title=\"Close\"\n onClick={onClose}><IcX size={18} /></button>\n )}\n </header>\n\n <div className=\"uic-fp-body\">\n {st.kind === 'loading' && <div className=\"uic-fp-pad\"><span className=\"uic-skel uic-fp-skel\" /></div>}\n {st.kind === 'image' && st.objUrl && <div className=\"uic-fp-center\"><img className=\"uic-fp-img\" src={st.objUrl} alt={name} /></div>}\n {st.kind === 'pdf' && st.objUrl && <iframe className=\"uic-fp-frame\" src={st.objUrl} title={name} />}\n {st.kind === 'video' && st.objUrl && <div className=\"uic-fp-center\"><video className=\"uic-fp-media\" src={st.objUrl} controls /></div>}\n {st.kind === 'audio' && st.objUrl && <div className=\"uic-fp-center\"><audio src={st.objUrl} controls /></div>}\n {st.kind === 'markdown' && (\n <div className=\"uic-fp-doc\">\n {renderMarkdown ? renderMarkdown(st.text || '') : <pre className=\"uic-fp-pre\">{st.text}</pre>}\n </div>\n )}\n {st.kind === 'code' && <CodeBlock code={st.text || ''} language={LANG[extOf(name)] || 'plaintext'} />}\n {st.kind === 'html' && view === 'source' && <CodeBlock code={st.text || ''} language=\"xml\" />}\n {st.kind === 'html' && view === 'preview' && (\n // The page runs in its own origin with scripts only: a mockup's own script and styles\n // work, and nothing in it can read the host page, its cookies or its storage.\n <iframe className=\"uic-fp-frame\" title={name} sandbox=\"allow-scripts\" srcDoc={st.text || ''} />\n )}\n {st.kind === 'csv' && <Grid rows={st.rows} />}\n {st.kind === 'sheet' && st.sheets && (\n <div className=\"uic-fp-xlsx\">\n {st.sheets[tab]?.filled ? <Grid rows={st.sheets[tab].rows} />\n : <div className=\"uic-fp-empty\">This sheet is empty.</div>}\n {/* Shown even for one sheet: the tab bar is what tells someone they are looking at a\n workbook, and hiding it is what made an empty first sheet read as a failure. */}\n <div className=\"uic-fp-tabs\">\n {st.sheets.map((s, i) => (\n <button key={s.name + i} type=\"button\"\n className={'uic-fp-tab' + (i === tab ? ' is-on' : '') + (s.filled ? '' : ' is-empty')}\n onClick={() => setTab(i)} title={s.filled ? s.name : `${s.name} (empty)`}>{s.name}</button>\n ))}\n </div>\n </div>\n )}\n {st.kind === 'binary' && (\n <div className=\"uic-fp-center\">\n <div className=\"uic-fp-fallback\">\n <FileTypeIcon name={name} size={56} />\n <p>{st.error || 'No inline preview for this file type.'}</p>\n <button type=\"button\" className=\"uic-fp-dl\" onClick={download}>Download</button>\n </div>\n </div>\n )}\n </div>\n </aside>\n );\n}\n","// Form primitives: a labelled field, and the three controls that go in one.\n//\n// Every surface in this stack had been hand-rolling `<label>Text<select className=\"…-input\">`,\n// which is why the same form looks different in each of them — different label weight, different\n// focus ring, a hint that is a paragraph in one place and a caption in another. These are the\n// smallest components that make that impossible.\n//\n// A Field owns the label, the hint and the error, so a control never has to render its own and\n// they never disagree about spacing. Passing `error` replaces the hint rather than stacking on it:\n// once something is wrong, the thing to read is what is wrong.\nimport { useId } from 'react';\nimport { Chevron } from './icons.jsx';\n\nexport function Field({ label, hint, error, htmlFor, required, children, className = '' }) {\n return (\n <div className={'uic-field' + (error ? ' is-error' : '') + (className ? ' ' + className : '')}>\n {label && (\n <label className=\"uic-field-label\" htmlFor={htmlFor}>\n {label}{required && <span className=\"uic-field-req\" aria-hidden=\"true\">*</span>}\n </label>\n )}\n {children}\n {error ? <p className=\"uic-field-err\">{error}</p>\n : hint ? <p className=\"uic-field-hint\">{hint}</p> : null}\n </div>\n );\n}\n\n/** A field whose control is generated for it — the common case, wired for accessibility. */\nfunction withField(Control) {\n return function Fielded({ label, hint, error, required, id, className, ...rest }) {\n const auto = useId();\n const inputId = id || auto;\n return (\n <Field label={label} hint={hint} error={error} required={required} htmlFor={inputId} className={className}>\n <Control id={inputId} invalid={!!error} required={required} {...rest} />\n </Field>\n );\n };\n}\n\nfunction BareInput({ invalid, ...rest }) {\n return <input className={'uic-input' + (invalid ? ' is-error' : '')} aria-invalid={invalid || undefined} {...rest} />;\n}\n\nfunction BareTextarea({ invalid, rows = 4, ...rest }) {\n return <textarea className={'uic-input uic-textarea' + (invalid ? ' is-error' : '')}\n rows={rows} aria-invalid={invalid || undefined} {...rest} />;\n}\n\n/** Options are [{value, label, disabled}] or plain strings. The chevron is drawn rather than left\n * to the platform, because the platform's differs per OS and the rest of this form does not. */\nfunction BareSelect({ invalid, options = [], placeholder, ...rest }) {\n return (\n <span className=\"uic-select-wrap\">\n <select className={'uic-input uic-select' + (invalid ? ' is-error' : '')}\n aria-invalid={invalid || undefined} {...rest}>\n {placeholder && <option value=\"\">{placeholder}</option>}\n {options.map((o) => {\n const opt = typeof o === 'string' ? { value: o, label: o } : o;\n return <option key={opt.value} value={opt.value} disabled={opt.disabled}>{opt.label}</option>;\n })}\n </select>\n <span className=\"uic-select-chev\" aria-hidden=\"true\"><Chevron dir=\"down\" size={14} /></span>\n </span>\n );\n}\n\nexport const Input = withField(BareInput);\nexport const Textarea = withField(BareTextarea);\nexport const Select = withField(BareSelect);\n\n/** The row a form ends with. `align` is 'end' by default because the primary action belongs where\n * the eye leaves the last control. */\nexport function FormActions({ children, align = 'end', className = '' }) {\n return <div className={`uic-form-actions is-${align}${className ? ' ' + className : ''}`}>{children}</div>;\n}\n\n/** The two buttons that row almost always holds, so their order stops being a per-form decision. */\nexport function Button({ variant = 'default', size = 'md', type = 'button', className = '', ...rest }) {\n return <button type={type} className={`uic-btn is-${variant} is-${size}${className ? ' ' + className : ''}`} {...rest} />;\n}\n","// Carousel — a horizontal strip of cards with edge buttons.\n//\n// It exists as a component rather than as a stylesheet plus a div because the parts that were\n// wrong in the copies are all behaviour, not paint: the buttons must disable at each end, must\n// not be there at all when everything already fits, and must scroll by an amount related to the\n// viewport. Four landings each hardcoded `scrollBy({ left: ±560 })` — the same magic number, in\n// four files, correct at no particular width.\n//\n// Item width is a custom property (--uic-car-item, default 236px) so a product sets the card size\n// from its own stylesheet without this component knowing what a card is.\nimport React, { useCallback, useEffect, useRef, useState } from 'react';\nimport { Chevron } from './icons.jsx';\n\n/**\n * label what this strip is, for the scroll region and the button names (\"Scroll <label> left\")\n * step px per press; defaults to 90% of the visible width, so a press always leaves a\n * landmark from the previous screenful on screen\n */\n// Both edge tests need the SAME tolerance. They did not: the end test allowed a pixel of slack\n// and the start test demanded scrollLeft <= 1, while scroll-snap parks the strip at its first\n// snap point — scrollLeft === 2 on a card with a border. So arriving at the start left the back\n// button enabled, and pressing it moved the strip two pixels: a control that looks live and does\n// nothing, which is the thing this component's own header promises not to ship.\nconst EDGE = 2;\n\nexport function Carousel(props) {\n const { label, step, children, classNames = {} } = props;\n const ref = useRef(null);\n const [edges, setEdges] = useState({ start: true, end: true, overflow: false });\n\n const measure = useCallback(() => {\n const el = ref.current;\n if (!el) return;\n const overflow = el.scrollWidth - el.clientWidth > EDGE;\n setEdges({\n overflow,\n start: el.scrollLeft <= EDGE,\n end: el.scrollLeft >= el.scrollWidth - el.clientWidth - EDGE,\n });\n }, []);\n\n useEffect(() => {\n const el = ref.current;\n if (!el) return undefined;\n measure();\n // Content arrives asynchronously (templates fetched after mount) and the container resizes\n // with the window, so \"does this overflow\" has to be answered again, not once.\n const ro = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(measure) : null;\n ro?.observe(el);\n for (const child of el.children) ro?.observe(child);\n return () => ro?.disconnect();\n }, [measure, children]);\n\n const scroll = (dir) => {\n const el = ref.current;\n if (!el) return;\n el.scrollBy({ left: dir * (step || Math.round(el.clientWidth * 0.9)), behavior: 'smooth' });\n };\n\n return (\n <div className={['uic-carousel-wrap', classNames.root || ''].filter(Boolean).join(' ')}>\n {edges.overflow ? (\n <button type=\"button\" className={['uic-carousel-nav is-left', classNames.button || ''].filter(Boolean).join(' ')}\n onClick={() => scroll(-1)} disabled={edges.start} aria-label={`Scroll ${label} left`}>\n <Chevron dir=\"left\" />\n </button>\n ) : null}\n <div className={['uic-carousel', classNames.viewport || ''].filter(Boolean).join(' ')}\n ref={ref} onScroll={measure} role=\"group\" aria-label={label}>\n {children}\n </div>\n {edges.overflow ? (\n <button type=\"button\" className={['uic-carousel-nav is-right', classNames.button || ''].filter(Boolean).join(' ')}\n onClick={() => scroll(1)} disabled={edges.end} aria-label={`Scroll ${label} right`}>\n <Chevron dir=\"right\" />\n </button>\n ) : null}\n </div>\n );\n}\n","// Card — art on top, a title row underneath, optional overlay and actions.\n//\n// The structure is the point. Every copy of this made the whole card a <button> and then put\n// more buttons inside it (a preview eye, rename, delete): interactive elements nested inside an\n// interactive element, which no assistive technology can present and which browsers resolve by\n// guessing. Here the root is a plain div, the primary action is ONE button covering art + title,\n// and `overlay` / `actions` are its siblings.\n//\n// `title` takes a node so an inline rename field can live there — pass onClick={undefined} while\n// editing, so the row is not simultaneously a text field and a link to somewhere else.\nimport React from 'react';\n\n/**\n * art the thumbnail node (this component gives it a box; what goes in it is yours)\n * title the name (node)\n * subtitle quiet trailing text, e.g. when it was last opened\n * onClick opens the thing; omit for a card that is only a display\n * selected this card is the current choice\n * overlay floats over the art on hover, and is ALWAYS visible on touch/narrow (there is no\n * hover to reveal it with)\n * actions sits in the title row, after the subtitle\n */\nexport function Card(props) {\n const { art, title, subtitle, onClick, selected = false, overlay, actions, classNames = {} } = props;\n const foot = (\n <span className=\"uic-card-foot\">\n <span className=\"uic-card-name\">{title}</span>\n {subtitle ? <span className=\"uic-card-sub\">{subtitle}</span> : null}\n </span>\n );\n return (\n <div className={['uic-card', selected ? 'is-selected' : '', classNames.root || '']\n .filter(Boolean).join(' ')}>\n {onClick ? (\n <button type=\"button\" className=\"uic-card-main\" onClick={onClick} aria-pressed={selected || undefined}>\n <span className=\"uic-card-art\">{art}</span>\n {foot}\n </button>\n ) : (\n <div className=\"uic-card-main\">\n <span className=\"uic-card-art\">{art}</span>\n {foot}\n </div>\n )}\n {overlay ? <div className=\"uic-card-overlay\">{overlay}</div> : null}\n {actions ? <div className=\"uic-card-actions\">{actions}</div> : null}\n </div>\n );\n}\n","// SearchField — the filter box that sits in a section header.\n//\n// Byte-identical in three apps; the fourth ships the stylesheet for it and no component, so its\n// lists have no search at all. Draws the package's own glyphs, so adopting it does not drag an\n// icon library into a product that had not chosen one.\nimport React from 'react';\nimport { IcSearch, IcX } from './icons.jsx';\n\n/** placeholder doubles as the accessible name — a search box next to a heading rarely has room\n * for a visible label, and \"Search templates\" is exactly what the label would have said. */\nexport function SearchField(props) {\n const { value, onChange, placeholder, clearLabel = 'Clear search', className } = props;\n return (\n <label className={['uic-search', className || ''].filter(Boolean).join(' ')}>\n <span className=\"uic-search-ic\" aria-hidden=\"true\"><IcSearch /></span>\n <input\n type=\"search\"\n value={value}\n placeholder={placeholder}\n aria-label={placeholder}\n onChange={(e) => onChange(e.target.value)}\n />\n {value ? (\n <button type=\"button\" className=\"uic-search-x\" aria-label={clearLabel} onClick={() => onChange('')}>\n <IcX size={12} />\n </button>\n ) : null}\n </label>\n );\n}\n","// CascadeMenu — a two-level choice in one panel. The first column lists the things you can pick;\n// the second lists the options of the one you pressed or arrowed onto; a press in the second\n// column IS the pick. A menu with a submenu, laid flat: both levels stay visible, so\n// nothing has to be hovered just right to stay open, and the reader sees \"harness, then model\"\n// as one gesture instead of a modal with a filter, a list, and a second control afterwards.\n//\n// It rides on Popover, so it portals to the body, flips to the side with room, clamps to the\n// viewport and scrolls inside the height it was given — the panel never runs off the screen.\n// Under `stackBelow` px of viewport the two columns cannot sit side by side, so the same panel\n// walks them as steps: pick in the first, the second replaces it with a way back.\n//\n// Choosing in the first column is a press or a focus, NOT a hover. A hover-driven second column\n// is the classic submenu trap: the pointer crossing other rows on its diagonal way to an option\n// swaps the options out from under it. Here the first column changes only on click or on\n// keyboard focus, so the path to an option is never a race.\n//\n// Keyboard: ↑↓ move within a column, → enters the options of the chosen item, ← returns to it,\n// Enter/Space press (native buttons), Escape closes (Popover). Focus lands inside on open and\n// goes back to the anchor on close.\nimport React, { Fragment, useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { Popover } from './Popover.jsx';\nimport { SearchField } from './SearchField.jsx';\nimport { Chevron, Svg } from './icons.jsx';\n\nconst Tick = () => <Svg s={14}><path d=\"M20 6 9 17l-5-5\" /></Svg>;\n\nconst FILTER_PAST = 8; // 'auto': a filter field appears once the first column is longer than this\n\nconst itemsOf = (groups) => groups.flatMap((g) => g.items);\n\n/**\n * open, anchorRef, onClose as Popover\n * label accessible name of the panel\n * groups [{ label, items: [{ id, label, icon, note }] }] — the first column, grouped;\n * a note is a small trailing word, e.g. 'fixed' on the one item a locked\n * chooser offers\n * optionsOf(item) -> [{ id, label, disabled, note, badge }] — the second column for one item;\n * a badge is a node at the row's end, e.g. which key serves a model, and\n * is what gives way (its own ellipsis) when the row is narrow\n * optionsFooter a node under the options, e.g. what the options without a badge mean\n * onPick(item, option)\n * value { item, option } — the current pair: its item opens first and its option\n * carries a check, so an editor of an existing choice shows where it stands\n * filter 'auto' (default) | true | false — a filter field over the first column\n * filterPlaceholder default 'Filter'\n * emptyText first column has no match; noOptionsText: the item offers nothing\n * optionsLabel accessible name of the second column, default 'Options'\n * backLabel the way back in stacked mode, default 'Back'\n * width side-by-side width, default 520; stackBelow: viewport px, default 560\n */\nexport function CascadeMenu(props) {\n const {\n open, anchorRef, onClose, label,\n groups = [], optionsOf, onPick,\n filter = 'auto', filterPlaceholder = 'Filter',\n emptyText = 'Nothing matches.', noOptionsText = 'Nothing to choose here.',\n optionsLabel = 'Options', backLabel = 'Back', optionsFooter,\n width = 520, stackBelow = 560, className, value,\n } = props;\n\n const rootRef = useRef(null);\n const [q, setQ] = useState('');\n const [activeId, setActiveId] = useState(null);\n const [stage, setStage] = useState('items');\n const [stacked, setStacked] = useState(false);\n\n // Filtering happens on the label people read, nothing else.\n const visible = useMemo(() => {\n const needle = q.trim().toLowerCase();\n if (!needle) return groups.filter((g) => g.items.length > 0);\n return groups\n .map((g) => ({ ...g, items: g.items.filter((it) => String(it.label).toLowerCase().includes(needle)) }))\n .filter((g) => g.items.length > 0);\n }, [groups, q]);\n const flat = useMemo(() => itemsOf(visible), [visible]);\n const active = flat.find((it) => it.id === activeId) || flat[0] || null;\n const options = useMemo(() => (active && optionsOf ? optionsOf(active) : []), [active, optionsOf]);\n const showFilter = filter === true || (filter === 'auto' && itemsOf(groups).length > FILTER_PAST);\n\n // Fresh every time it opens: no stale filter, the first item highlighted, the first step shown.\n useEffect(() => {\n if (!open) return undefined;\n setQ(''); setActiveId(value?.item ?? null); setStage('items');\n const measure = () => setStacked(window.innerWidth < stackBelow);\n measure();\n window.addEventListener('resize', measure);\n // Popover renders its children one effect later (it has to measure the anchor first), so the\n // first focusable lands in the next frame.\n const raf = requestAnimationFrame(() => {\n const first = rootRef.current?.querySelector('input, button:not(:disabled)');\n first?.focus({ preventScroll: true });\n });\n const anchor = anchorRef?.current;\n return () => {\n window.removeEventListener('resize', measure);\n cancelAnimationFrame(raf);\n // Close by Escape or by a pick: focus goes back where it came from. Close by a press\n // elsewhere: the browser moves focus to that press afterwards, so this does not fight it.\n anchor?.focus?.({ preventScroll: true });\n };\n }, [open, stackBelow]); // eslint-disable-line react-hooks/exhaustive-deps\n\n const focusIn = useCallback((col, index = 0) => {\n const list = rootRef.current?.querySelectorAll(`.uic-cascade-${col} .uic-pop-item:not(:disabled)`);\n if (!list || !list.length) return false;\n const i = Math.max(0, Math.min(index, list.length - 1));\n list[i].focus({ preventScroll: true });\n return true;\n }, []);\n\n const enterOptions = useCallback(() => {\n if (stacked) { setStage('options'); requestAnimationFrame(() => focusIn('options')); }\n else focusIn('options');\n }, [stacked, focusIn]);\n\n const onKey = (e) => {\n const el = document.activeElement;\n const col = el?.closest?.('.uic-cascade-col');\n const inItems = col?.classList.contains('uic-cascade-items');\n const inOptions = col?.classList.contains('uic-cascade-options');\n if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {\n if (!col) return;\n const list = Array.from(col.querySelectorAll('.uic-pop-item:not(:disabled)'));\n const i = list.indexOf(el);\n // From the filter field, ↓ steps onto the first row.\n const next = i < 0 ? 0 : i + (e.key === 'ArrowDown' ? 1 : -1);\n if (next < 0) { col.querySelector('input')?.focus(); e.preventDefault(); return; }\n if (next >= list.length) return;\n e.preventDefault();\n list[next].focus({ preventScroll: true });\n } else if (e.key === 'ArrowRight' && inItems) {\n e.preventDefault(); enterOptions();\n } else if (e.key === 'ArrowLeft' && inOptions) {\n e.preventDefault();\n if (stacked) { setStage('items'); requestAnimationFrame(() => focusIn('items', flat.indexOf(active))); }\n else focusIn('items', flat.indexOf(active));\n } else if (e.key === 'Enter' && el?.tagName === 'INPUT') {\n // Enter in the filter means \"this one\": on to its options.\n e.preventDefault(); enterOptions();\n }\n };\n\n const showItems = !stacked || stage === 'items';\n const showOptions = !stacked || stage === 'options';\n\n return (\n <Popover open={open} anchorRef={anchorRef} onClose={onClose} label={label}\n width={stacked ? 320 : width} minHeight={260}\n className={['uic-cascade-pop', className || ''].filter(Boolean).join(' ')}>\n <div ref={rootRef} className={'uic-cascade' + (stacked ? ' is-stacked' : '')} onKeyDown={onKey}>\n {showItems && (\n <div className=\"uic-cascade-col uic-cascade-items\">\n {showFilter ? (\n <SearchField className=\"uic-cascade-filter\" value={q} onChange={setQ} placeholder={filterPlaceholder} />\n ) : null}\n <div className=\"uic-pop-list\">\n {visible.map((g, gi) => (\n <Fragment key={g.label || gi}>\n {g.label ? <div className=\"uic-cascade-group\">{g.label}</div> : null}\n {g.items.map((it) => {\n const on = active?.id === it.id;\n return (\n <button key={it.id} type=\"button\"\n className={'uic-pop-item uic-cascade-item' + (on ? ' is-active' : '')}\n aria-expanded={on} aria-haspopup=\"true\"\n onFocus={() => setActiveId(it.id)}\n onClick={() => { setActiveId(it.id); enterOptions(); }}>\n {it.icon ? <span className=\"uic-cascade-ic\" aria-hidden=\"true\">{it.icon}</span> : null}\n <span className=\"uic-chip-t\">{it.label}</span>\n {it.note ? <span className=\"uic-cascade-note\">{it.note}</span> : null}\n <span className=\"uic-cascade-chev\" aria-hidden=\"true\"><Chevron dir=\"right\" size={14} /></span>\n </button>\n );\n })}\n </Fragment>\n ))}\n {flat.length === 0 ? <div className=\"uic-pop-note\">{emptyText}</div> : null}\n </div>\n </div>\n )}\n {showOptions && (\n <div className=\"uic-cascade-col uic-cascade-options\" role=\"group\" aria-label={optionsLabel}>\n <div className=\"uic-cascade-head\">\n {stacked ? (\n <button type=\"button\" className=\"uic-cascade-back\" aria-label={backLabel}\n onClick={() => { setStage('items'); requestAnimationFrame(() => focusIn('items', flat.indexOf(active))); }}>\n <Chevron dir=\"left\" size={14} />\n </button>\n ) : null}\n {active?.icon ? <span className=\"uic-cascade-ic\" aria-hidden=\"true\">{active.icon}</span> : null}\n <span className=\"uic-chip-t\">{active ? active.label : ''}</span>\n </div>\n <div className=\"uic-pop-list\">\n {options.map((o) => {\n const on = !!value && active?.id === value.item && o.id === value.option;\n return (\n <button key={o.id} type=\"button\"\n className={'uic-pop-item uic-cascade-opt' + (on ? ' is-on' : '') + (o.badge ? ' has-badge' : '')}\n aria-current={on ? 'true' : undefined}\n disabled={!!o.disabled} onClick={() => onPick?.(active, o)}>\n {value ? <span className=\"uic-pop-check\" aria-hidden=\"true\">{on ? <Tick /> : null}</span> : null}\n <span className=\"uic-chip-t\">{o.label}</span>\n {o.note ? <span className=\"uic-cascade-note\">{o.note}</span> : null}\n {o.badge || null}\n </button>\n );\n })}\n {active && options.length === 0 ? <div className=\"uic-pop-note\">{noOptionsText}</div> : null}\n </div>\n {optionsFooter || null}\n </div>\n )}\n </div>\n </Popover>\n );\n}\n","// Modal — a dialog whose body is yours: a preview, a big form, a comparison.\n//\n// useDialog() answers a QUESTION and resolves to a value (confirm/prompt/alert). This is the\n// other half: a surface with arbitrary content that the caller opens and closes itself. Products\n// were re-implementing it per feature, each with its own backdrop mousedown handler and its own\n// document keydown listener.\n//\n// It shares the dialog host's Escape ordering through the package's overlay stack (components/\n// overlay.js), so a Modal opened on top of a confirm takes the key and the confirm does not, and\n// both sit at the same z-index layer (--uic-z-overlay). It does NOT render inside DialogHost's\n// portal: that root is created from the host's private state and only exists while a dialog is\n// open, so there is nothing to render into and no API to reach it with. One stack, two roots, is\n// the honest arrangement — and it means Modal works in an app that never mounted DialogHost.\nimport React, { useCallback, useEffect, useId } from 'react';\nimport { createPortal } from 'react-dom';\nimport { IcX } from './icons.jsx';\nimport { useOverlayEscape } from './overlay.js';\n\n/**\n * open render it\n * onClose Escape, the ✕, or a click on the backdrop itself\n * title the heading (string or node); also names the dialog for assistive tech\n * description one quiet line under the title\n * actions buttons in the header, before the ✕ (e.g. \"Use this template\")\n * size 'sm' | 'md' | 'lg' | 'full' — or pass `width` for an exact px/any CSS width\n * labelledBy id of your own heading, when `title` is not where the name lives\n */\nexport function Modal(props) {\n const { open, onClose, title, description, actions, size = 'md', width,\n labelledBy, children, classNames = {} } = props;\n const titleId = useId();\n\n const escape = useCallback(() => onClose?.(), [onClose]);\n useOverlayEscape(open, escape);\n\n // A modal that leaves the page scrolling behind it drifts under the reader's fingers on a\n // touch device and loses their place in the list they opened it from.\n useEffect(() => {\n if (!open || typeof document === 'undefined') return undefined;\n const prev = document.body.style.overflow;\n document.body.style.overflow = 'hidden';\n return () => { document.body.style.overflow = prev; };\n }, [open]);\n\n if (!open || typeof document === 'undefined') return null;\n // mousedown, not click: a press that STARTED inside the card and ended on the backdrop (a drag\n // that overshot, a text selection) would otherwise close it out from under the person.\n const onBackdrop = (e) => { if (e.target === e.currentTarget) onClose?.(); };\n return createPortal(\n <div className={['uic-modal-backdrop', classNames.backdrop || ''].filter(Boolean).join(' ')}\n onMouseDown={onBackdrop}>\n <div className={['uic-modal', `is-${size}`, classNames.root || ''].filter(Boolean).join(' ')}\n style={width ? { width } : undefined}\n role=\"dialog\" aria-modal=\"true\"\n aria-labelledby={labelledBy || (title ? titleId : undefined)}>\n {(title || actions) ? (\n <div className=\"uic-modal-h\">\n <div className=\"uic-modal-title\">\n {title ? <h3 id={titleId}>{title}</h3> : null}\n {description ? <p>{description}</p> : null}\n </div>\n {actions}\n <button type=\"button\" className=\"uic-modal-x\" aria-label=\"Close\" onClick={onClose}>\n <IcX size={18} />\n </button>\n </div>\n ) : null}\n <div className={['uic-modal-b', classNames.body || ''].filter(Boolean).join(' ')}>\n {children}\n </div>\n </div>\n </div>,\n document.body,\n );\n}\n","// useTypewriter — cycle example prompts through a placeholder, typed out character by character.\n//\n// Three near-identical implementations existed; the differences between them were 24ms vs 26ms\n// per character and whether the list was shuffled. Those are not configuration, they are drift,\n// so there are no knobs for them here.\n//\n// The part worth sharing is the one thing all three already got right and nobody should have to\n// re-derive: prefers-reduced-motion turns the animation off and shows the first phrase, because\n// text that rewrites itself forever is exactly what that setting is about.\nimport { useEffect, useRef, useState } from 'react';\n\nconst CHAR_MS = 26; // per character while typing\nconst HOLD_MS = 2600; // a finished phrase stays long enough to read\n\n/**\n * phrases the lines to cycle (the product's own copy — it stays in the product)\n * active type only while this is true; a box the person is typing in stops animating\n * returns the text to show right now\n */\nexport function useTypewriter(phrases, { active = true } = {}) {\n const list = phrases && phrases.length ? phrases : [''];\n const [text, setText] = useState(list[0]);\n // Snapshot the list so a caller passing a fresh array literal every render does not restart\n // the animation on every render.\n const listRef = useRef(list);\n listRef.current = list;\n\n useEffect(() => {\n if (!active) return undefined;\n if (typeof window === 'undefined') return undefined;\n if (window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches) {\n setText(listRef.current[0]);\n return undefined;\n }\n let i = 0;\n let pos = 0;\n let timer;\n const tick = () => {\n const cur = listRef.current[i % listRef.current.length];\n if (pos <= cur.length) {\n setText(cur.slice(0, pos));\n pos += 1;\n timer = window.setTimeout(tick, CHAR_MS);\n } else {\n timer = window.setTimeout(() => { i += 1; pos = 0; tick(); }, HOLD_MS);\n }\n };\n tick();\n return () => window.clearTimeout(timer);\n }, [active]);\n\n return text;\n}\n","// Panel — the frame around one thing on a board: a header you can grab, a body, and the two\n// states that body spends most of its life in.\n//\n// The states are the reason this exists. A panel whose content is being fetched has to hold its\n// box (a grid that reflows as four requests land in four different orders is unreadable), and a\n// panel whose content FAILED has to show why, verbatim and selectable. Products keep replacing\n// that second one with \"Something went wrong\", which throws away the one string that tells the\n// person what to fix.\n//\n// `loading` blanks the body — the first fetch, when there is nothing to keep. `busy` leaves the\n// content up and marks the header — a refresh, where blanking a chart the person is reading to\n// redraw the same chart is worse than waiting.\nimport { Button } from './form.jsx';\n\n/**\n * title the panel's name\n * titleAs heading level, so a board fits YOUR document outline ('h3')\n * meta quiet second line under the title (when it was refreshed, what it counts)\n * actions controls in the header, after the title — never drag the panel\n * footer quiet strip under the body\n * loading no content yet: the body is a placeholder of the same size\n * busy content is up but being refreshed: the header shows it\n * error what went wrong, verbatim. Shown in monospace, selectable, and scrollable —\n * a query error is a thing people copy\n * errorDetail extra context under the message, folded away (the statement that failed)\n * onRetry absent → no retry control is drawn, rather than a dead one\n */\nexport function Panel(props) {\n const {\n title, titleAs: Heading = 'h3', meta, actions, footer,\n loading = false, loadingLabel = 'Loading',\n busy = false, busyLabel = 'Refreshing',\n error = null, errorTitle = 'This panel could not load',\n errorDetail = null, detailLabel = 'Details',\n onRetry, retryLabel = 'Try again',\n className = '', classNames = {}, children,\n } = props;\n\n const body = loading ? (\n <div className=\"uic-panel-load\">\n <span className=\"uic-panel-load-bar\" />\n <span className=\"uic-panel-load-bar\" />\n <span className=\"uic-panel-load-bar\" />\n <span className=\"uic-sr\">{loadingLabel}</span>\n </div>\n ) : error ? (\n <div className=\"uic-panel-fail\">\n <p className=\"uic-panel-fail-t\">{errorTitle}</p>\n <pre className=\"uic-panel-fail-m\">{error}</pre>\n {errorDetail ? (\n <details className=\"uic-panel-fail-d\">\n <summary>{detailLabel}</summary>\n <div className=\"uic-panel-fail-dd\">{errorDetail}</div>\n </details>\n ) : null}\n {onRetry ? (\n <div className=\"uic-panel-fail-act\">\n <Button size=\"sm\" onClick={onRetry}>{retryLabel}</Button>\n </div>\n ) : null}\n </div>\n ) : children;\n\n return (\n <section\n className={['uic-panel', className, classNames.root || ''].filter(Boolean).join(' ')}\n aria-busy={loading || busy || undefined}\n >\n <header className={['uic-panel-head', classNames.head || ''].filter(Boolean).join(' ')}>\n <div className=\"uic-panel-titles\">\n {title ? <Heading className=\"uic-panel-title\">{title}</Heading> : null}\n {meta ? <p className=\"uic-panel-meta\">{meta}</p> : null}\n </div>\n {actions ? <div className=\"uic-panel-acts\">{actions}</div> : null}\n </header>\n {/* One indeterminate line, not a percentage: nothing here knows how far along a refresh is. */}\n {busy ? <div className=\"uic-panel-busy\" role=\"status\" aria-label={busyLabel} /> : null}\n <div className={['uic-panel-body', classNames.body || ''].filter(Boolean).join(' ')}>{body}</div>\n {footer ? <footer className=\"uic-panel-foot\">{footer}</footer> : null}\n </section>\n );\n}\n","// PanelGrid — a column grid of panels you can drag and resize, and a read-only mode that is the\n// default. The layout is a prop: this component never owns it, it proposes the next one.\n//\n// Written here rather than taken from react-grid-layout on purpose. What a dashboard needs is\n// this file: cells → pixels, a pointer drag, a resize corner, and gravity. What the dependency\n// adds around that is three more packages (draggable / resizable / a deep-equal), a stylesheet\n// with its own hardcoded colours (its drop placeholder is literally `background: red`), and no\n// keyboard path at all. It is also not a peer any host here already owns, so every app that\n// imports a Button would pay for it. The subset below has no dependencies, themes from the same\n// --uic-* tokens as everything else, and arranges a panel from the keyboard.\nimport React, { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';\nimport { compact, layoutRows, moveItem, nudgeItem, resizeItem, sameLayout, sortLayout } from './layout.js';\n\n/** Measure the box we actually get. A grid inside a scroller that also holds a side panel gets a\n * stale width from anything that measures once — the observer reports every change. */\nfunction useMeasuredWidth() {\n const ref = useRef(null);\n const [width, setWidth] = useState(0);\n useLayoutEffect(() => {\n const el = ref.current;\n if (!el) return undefined;\n const measure = () => setWidth(el.clientWidth);\n measure();\n const ro = new ResizeObserver(measure);\n ro.observe(el);\n return () => ro.disconnect();\n }, []);\n return [ref, width];\n}\n\n// A press that lands on one of these is that control's press, not the start of a drag.\nconst NO_DRAG = 'button, a, input, select, textarea, [data-uic-nodrag]';\n\n/**\n * layout [{i, x, y, w, h, minW?, minH?, maxW?, maxH?, static?}] — cells, not pixels\n * children one element per layout entry, matched by `key`\n * cols columns across the full width (12)\n * rowHeight px per row (40)\n * gap px between cells (12)\n * editable false (default): nothing drags, nothing resizes, no handle is drawn\n * dragHandle selector a press must land inside to start a move ('.uic-panel-head')\n * stackAt below this container width the grid becomes ONE column in layout order and stops\n * being arrangeable — twelve columns across a phone is 32px each, and dragging a\n * panel between two cells nobody can see is not an interaction worth keeping\n * resizeLabel (id) => the handle's accessible name; name the panel in it\n * onLayoutChange(next) fires ONCE per interaction, on release — not per pixel, because the host\n * is usually writing the result to a document\n */\nexport function PanelGrid(props) {\n const {\n layout = [], children, cols = 12, rowHeight = 40, gap = 12,\n editable = false, dragHandle = '.uic-panel-head', stackAt = 640,\n onLayoutChange, resizeLabel, className = '',\n } = props;\n\n const [wrapRef, width] = useMeasuredWidth();\n // {id, mode, origin, px, py, dx, dy, preview} while a pointer interaction is live, else null.\n // The ref is what the pointer handlers read and write (they run between renders); the state is\n // the same value, kept only so React redraws.\n const [drag, setDrag] = useState(null);\n const dragRef = useRef(null);\n // A drag ends in a click on whatever was under the pointer. Swallow exactly that one.\n const swallowClick = useRef(false);\n\n const stacked = width > 0 && width < stackAt;\n const arrangeable = editable && !stacked;\n const live = drag ? drag.preview : layout;\n\n const colW = width > 0 ? (width - gap * (cols - 1)) / cols : 0;\n const cellW = colW + gap;\n const cellH = rowHeight + gap;\n const rowsToPx = (h) => h * rowHeight + (h - 1) * gap;\n\n // Stacked: one column, in reading order, each panel keeping its own height.\n const stack = useMemo(() => {\n if (!stacked) return null;\n const tops = new Map();\n let y = 0;\n for (const it of sortLayout(live)) {\n tops.set(it.i, y);\n y += rowsToPx(it.h || 1) + gap;\n }\n return { tops, height: Math.max(0, y - gap) };\n }, [stacked, live, rowHeight, gap]);\n\n const rows = layoutRows(live);\n const height = stacked ? stack.height : (rows ? rowsToPx(rows) : 0);\n\n const commit = useCallback((next) => {\n if (onLayoutChange && !sameLayout(next, layout)) onLayoutChange(next);\n }, [onLayoutChange, layout]);\n\n // ── pointer interaction ───────────────────────────────────────────────────\n // The listeners go on in the pointerdown handler itself, NOT in an effect keyed on the drag\n // state: an effect runs after React has re-rendered, and every pointer move that arrived in\n // between is simply gone. A quick flick then moves nothing at all.\n const detach = useRef(null);\n useEffect(() => () => detach.current?.(), []); // a drag must not outlive the grid\n\n const start = (id, mode) => (e) => {\n if (!arrangeable || e.button !== 0) return;\n const item = layout.find((it) => it.i === id);\n if (!item || item.static) return;\n if (mode === 'move' && (!e.target.closest(dragHandle) || e.target.closest(NO_DRAG))) return;\n e.preventDefault();\n detach.current?.();\n const begin = { id, mode, origin: item, px: e.clientX, py: e.clientY, dx: 0, dy: 0, preview: layout };\n dragRef.current = begin;\n setDrag(begin);\n\n const onMove = (ev) => {\n const d = dragRef.current;\n if (!d) return;\n const dx = ev.clientX - d.px;\n const dy = ev.clientY - d.py;\n if (Math.abs(dx) > 3 || Math.abs(dy) > 3) swallowClick.current = true;\n const cx = Math.round(dx / cellW);\n const cy = Math.round(dy / cellH);\n const preview = d.mode === 'move'\n ? moveItem(layout, d.id, d.origin.x + cx, d.origin.y + cy, cols)\n : resizeItem(layout, d.id, d.origin.w + cx, d.origin.h + cy, cols);\n dragRef.current = { ...d, dx, dy, preview };\n setDrag(dragRef.current);\n };\n const end = (commitIt) => () => {\n const d = dragRef.current;\n dragRef.current = null;\n off();\n setDrag(null);\n if (d && commitIt) commit(d.preview);\n };\n const onUp = end(true);\n // Escape abandons the interaction: the preview is dropped and nothing is committed.\n const onKey = (ev) => { if (ev.key === 'Escape') end(false)(); };\n function off() {\n detach.current = null;\n window.removeEventListener('pointermove', onMove);\n window.removeEventListener('pointerup', onUp);\n window.removeEventListener('pointercancel', onUp);\n window.removeEventListener('keydown', onKey);\n }\n detach.current = off;\n window.addEventListener('pointermove', onMove);\n window.addEventListener('pointerup', onUp);\n window.addEventListener('pointercancel', onUp);\n window.addEventListener('keydown', onKey);\n };\n\n const onClickCapture = (e) => {\n if (!swallowClick.current) return;\n swallowClick.current = false;\n e.stopPropagation();\n e.preventDefault();\n };\n\n // ── keyboard interaction ──────────────────────────────────────────────────\n // The same handle answers arrows (resize) and shift+arrows (move): a panel that can only be\n // arranged by dragging cannot be arranged by everyone.\n const onHandleKey = (id) => (e) => {\n const step = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] }[e.key];\n if (!step) return;\n const item = layout.find((it) => it.i === id);\n if (!item) return;\n e.preventDefault();\n commit(e.shiftKey\n ? nudgeItem(layout, id, step[0], step[1], cols)\n : resizeItem(layout, id, item.w + step[0], item.h + step[1], cols));\n };\n\n const boxOf = (it) => (stacked\n ? { left: 0, top: stack.tops.get(it.i), width, height: rowsToPx(it.h || 1) }\n : { left: it.x * cellW, top: it.y * cellH, width: it.w * colW + (it.w - 1) * gap, height: rowsToPx(it.h) });\n\n const byId = new Map(live.map((it) => [it.i, it]));\n const ghost = drag && drag.mode === 'move' && byId.has(drag.id) ? boxOf(byId.get(drag.id)) : null;\n const cls = ['uic-pg', arrangeable ? 'is-editable' : '', stacked ? 'is-stacked' : '', className]\n .filter(Boolean).join(' ');\n\n return (\n <div\n ref={wrapRef}\n className={cls}\n style={{ height }}\n onClickCapture={onClickCapture}\n // A cancelled pointer (a phone call, a lost pointer capture) leaves no click to swallow.\n // Clearing on the next press means a stale flag can never eat someone else's click.\n onPointerDownCapture={() => { swallowClick.current = false; }}\n >\n {ghost ? <div className=\"uic-pg-ghost\" aria-hidden=\"true\" style={ghost} /> : null}\n {width > 0 && React.Children.map(children, (child) => {\n if (!React.isValidElement(child) || child.key == null) return null;\n const id = String(child.key).replace(/^\\.\\$/, '');\n const it = byId.get(id);\n if (!it) return null; // no cell for this child: nowhere to put it\n const moving = drag && drag.id === id;\n // While moving, the panel follows the pointer in pixels and the ghost marks the cell it\n // would land in; a resize snaps, so the corner never lags the pointer's own cell.\n const offset = moving && drag.mode === 'move'\n ? { transform: `translate(${drag.dx}px, ${drag.dy}px)` } : null;\n return (\n <div\n className={'uic-pg-item' + (moving ? ' is-moving' : '')}\n style={{ ...boxOf(it), ...offset }}\n onPointerDown={arrangeable ? start(id, 'move') : undefined}\n >\n {child}\n {arrangeable && !it.static ? (\n <button\n type=\"button\"\n className=\"uic-pg-handle\"\n aria-label={resizeLabel ? resizeLabel(id) : 'Resize panel. Arrow keys resize it; shift with arrow keys moves it past its neighbours.'}\n onPointerDown={start(id, 'resize')}\n onKeyDown={onHandleKey(id)}\n >\n <svg width=\"10\" height=\"10\" viewBox=\"0 0 10 10\" aria-hidden=\"true\">\n <path d=\"M9 1v8H1\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.4\" strokeLinecap=\"round\" />\n </svg>\n </button>\n ) : null}\n </div>\n );\n })}\n </div>\n );\n}\n\n/** Gravity applied to a layout you built yourself. A new panel added with `y: Infinity` lands at\n * the bottom; this is what turns that into a real row. */\nexport function packLayout(layout, cols = 12) {\n const bottom = layoutRows(layout.filter((it) => Number.isFinite(it.y)));\n return compact(layout.map((it) => (Number.isFinite(it.y) ? it : { ...it, y: bottom })), cols);\n}\n","// Grid layout math for PanelGrid — pure functions over an array of {i, x, y, w, h}.\n//\n// Kept separate from the component because this is the part that is easy to get wrong and easy\n// to test: nothing here touches the DOM, React, or pixels. Coordinates are CELLS, not pixels —\n// x/w are columns, y/h are rows. The component owns the one conversion to pixels.\n//\n// Gravity is up and always on. A dashboard with holes punched in it looks broken rather than\n// deliberate, and \"the panel you dropped is where you dropped it, everything else flows around\n// it\" is the only rule a person has to learn.\n\n/** Sorted top-to-bottom, then left-to-right — the order gravity resolves in. */\nexport function sortLayout(layout) {\n return [...layout].sort((a, b) => (a.y - b.y) || (a.x - b.x));\n}\n\nfunction overlaps(a, b) {\n return a.i !== b.i\n && a.x < b.x + b.w && a.x + a.w > b.x\n && a.y < b.y + b.h && a.y + a.h > b.y;\n}\n\nfunction firstOverlap(placed, item) {\n for (const p of placed) if (overlaps(p, item)) return p;\n return null;\n}\n\n/** Cell bounds an item may occupy. min defaults to 1 cell; max defaults to the whole grid. */\nexport function clampItem(item, cols) {\n const minW = Math.max(1, item.minW || 1);\n const minH = Math.max(1, item.minH || 1);\n const w = Math.min(Math.max(item.w ?? minW, minW), Math.min(item.maxW || cols, cols));\n const h = Math.max(Math.min(item.h ?? minH, item.maxH || Infinity), minH);\n const x = Math.min(Math.max(item.x ?? 0, 0), cols - w);\n return { ...item, x, y: Math.max(0, item.y ?? 0), w, h };\n}\n\n/**\n * Float everything up, resolving overlaps on the way.\n *\n * `pinned` is the id being dragged, and it wins TIES: dropped onto the cell of a panel already\n * there, it keeps the cell and the other one moves, instead of the panel squirting out from under\n * the pointer because its neighbour happened to sort first. Only ties — a pin that always went\n * first would float above the panel it was just dragged below, so nudging a panel DOWN one row\n * could send it to the top of the board.\n */\nexport function compact(layout, cols, pinned) {\n const sorted = layout.map((it) => clampItem(it, cols))\n .sort((a, b) => (a.y - b.y) || (Number(b.i === pinned) - Number(a.i === pinned)) || (a.x - b.x));\n const statics = sorted.filter((it) => it.static);\n const rest = sorted.filter((it) => !it.static);\n const placed = [...statics];\n for (const item of rest) {\n let y = item.y;\n // Rise until something is in the way…\n while (y > 0 && !firstOverlap(placed, { ...item, y: y - 1 })) y--;\n // …and sink out of anything it is already inside (a drop, or a resize that grew downward).\n let hit;\n while ((hit = firstOverlap(placed, { ...item, y }))) y = hit.y + hit.h;\n placed.push({ ...item, y });\n }\n // Back into the caller's order: a layout array whose order shuffles every drag makes React\n // remount panels, and a remounted chart loses its animation and its tooltip.\n const byId = new Map(placed.map((it) => [it.i, it]));\n return layout.map((it) => byId.get(it.i) || it);\n}\n\n/** Move one item to a cell, then let gravity settle the rest around it. */\nexport function moveItem(layout, id, x, y, cols) {\n const next = layout.map((it) => (it.i === id && !it.static\n ? clampItem({ ...it, x, y: Math.max(0, y) }, cols)\n : it));\n return compact(next, cols, id);\n}\n\n/**\n * Move one item by one step, the way a keyboard means it.\n *\n * Sideways is literal. Vertically it is a SWAP with the neighbour above or below, because under\n * gravity \"down one row\" is not a thing that can happen: the row it vacates closes behind it and\n * it lands exactly where it started. A key that provably cannot move anything is a dead key, so\n * up/down step past the panel that is blocking, and do nothing only when there is genuinely\n * nothing to step past.\n */\nexport function nudgeItem(layout, id, dx, dy, cols) {\n const item = layout.find((it) => it.i === id);\n if (!item || item.static) return layout;\n if (dx) return moveItem(layout, id, item.x + dx, item.y, cols);\n const sameCols = layout.filter((o) => o.i !== id && o.x < item.x + item.w && o.x + o.w > item.x);\n if (dy < 0) {\n const above = sameCols.filter((o) => o.y + o.h <= item.y);\n if (!above.length) return layout;\n const near = above.reduce((a, b) => (a.y + a.h > b.y + b.h ? a : b));\n return moveItem(layout, id, item.x, near.y, cols); // takes its row; it is pushed down\n }\n const below = sameCols.filter((o) => o.y >= item.y + item.h);\n if (!below.length) return layout;\n const near = below.reduce((a, b) => (a.y < b.y ? a : b));\n return moveItem(layout, id, item.x, near.y + near.h, cols); // it floats up into the gap left\n}\n\n/** Resize one item from its top-left corner, then settle. */\nexport function resizeItem(layout, id, w, h, cols) {\n const next = layout.map((it) => (it.i === id && !it.static\n ? clampItem({ ...it, w, h }, cols)\n : it));\n return compact(next, cols, id);\n}\n\n/** Rows the layout occupies — the grid's height, which is knowable before any measurement. */\nexport function layoutRows(layout) {\n return layout.reduce((n, it) => Math.max(n, (it.y || 0) + (it.h || 1)), 0);\n}\n\n/** True when two layouts place every item identically — used to skip no-op commits. */\nexport function sameLayout(a, b) {\n if (a.length !== b.length) return false;\n const byId = new Map(b.map((it) => [it.i, it]));\n return a.every((it) => {\n const o = byId.get(it.i);\n return o && o.x === it.x && o.y === it.y && o.w === it.w && o.h === it.h;\n });\n}\n","// A timeline you can edit: lanes of clips against a ruler, with a playhead, trim handles, split,\n// and drag to reorder.\n//\n// ONE NUMBER IS THE COORDINATE SYSTEM. `pps` — pixels per second — converts time to x everywhere:\n// the ruler's ticks, a clip's width, the playhead, every gesture's inverse. Two places computing\n// that conversion is how a ruler and the blocks under it come to disagree, which is the one thing\n// a timeline cannot do and still be read.\n//\n// THE HOST OWNS THE DOCUMENT. Every gesture ends in a callback carrying SECONDS — onTrim, onSplit,\n// onMoveClip, onDeleteClip — and nothing here mutates anything. That is what lets the same\n// component drive a film's cut, a job's phases or a conversation's turns: it knows about time and\n// blocks and nothing about what a block means. It also puts undo where the document is.\n//\n// TIME THAT IS NOT KNOWN IS NOT DRAWN AS TIME. A clip whose duration is null gets a fixed\n// placeholder width and a hatched fill, never a guessed length — a width here is a measurement,\n// and one invented width makes every reading of the ruler above it worthless. Such a clip also\n// gets no trim handles: there is nothing to trim against a length nobody knows.\n//\n// ARTWORK IS ONE REAL FRAME, REPEATED. A filmstrip in a desktop editor shows successive frames\n// pulled from the file. There is no frame-extraction service behind this component, so it tiles\n// the ONE poster it was given at a fixed tile size rather than inventing distinct frames —\n// visibly the same image, which is honest about what is known, and still reads as a strip.\nimport { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';\n\nexport const TL_MIN_PPS = 4;\nexport const TL_MAX_PPS = 400;\nexport const TL_DEFAULT_PPS = 26;\n/** The sticky lane-label gutter. Lanes start at this x. */\nexport const TL_HEAD_W = 84;\n/** Snap magnetism in screen px. Alt bypasses it, the convention everywhere. */\nexport const TL_SNAP_PX = 6;\n/** Nothing may be trimmed shorter than this. */\nexport const TL_MIN_CLIP_S = 0.1;\n/** Pointer travel below which a press is a click, not a drag. */\nconst CLICK_SLOP = 3;\n\nconst LANE_H = 56;\nconst CLIP_INSET = 4;\nconst UNKNOWN_W = 46;\nconst MIN_CLIP_W = 18;\n\nconst clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v));\n\n/* ── ruler + label maths (pure) ─────────────────────────────────────────────────────────────── */\n\nconst TICK_STEPS = [0.1, 0.2, 0.5, 1, 2, 5, 10, 15, 30, 60, 120, 300, 600];\n\n/** The smallest step whose labels stay ~64px apart, so ticks thin out as you zoom out instead of\n * collapsing into a grey bar. */\nexport function majorTickStep(pps) {\n for (const s of TICK_STEPS) if (s * pps >= 64) return s;\n return TICK_STEPS[TICK_STEPS.length - 1];\n}\n\n/** m:ss, with tenths only when the step is sub-second — a label finer than its tick is noise. */\nexport function tickLabel(t, step = 1) {\n const m = Math.floor(t / 60);\n const s = t - m * 60;\n const whole = Math.floor(s + 1e-6);\n const base = `${m}:${String(whole).padStart(2, '0')}`;\n if (step >= 1) return base;\n const frac = Math.round((s - whole) * 10);\n return frac > 0 ? `${base}.${frac}` : base;\n}\n\n/** m:ss for a duration, and '' for anything unmeasured — never '0:00' for an unknown. */\nexport function durationLabel(seconds) {\n if (!Number.isFinite(seconds) || seconds < 0) return '';\n const m = Math.floor(seconds / 60);\n const s = Math.round(seconds - m * 60);\n return `${m}:${String(s).padStart(2, '0')}`;\n}\n\n/** Precise enough to trim against: m:ss.t */\nfunction exactLabel(seconds) {\n if (!Number.isFinite(seconds)) return '—';\n const m = Math.floor(Math.max(0, seconds) / 60);\n const s = Math.max(0, seconds) - m * 60;\n return `${m}:${s < 10 ? '0' : ''}${s.toFixed(1)}`;\n}\n\n/** Where each clip sits. A sequential lane runs its clips end to end (a cut); a placed lane puts\n * each at its own `start`. An unmeasured clip advances by its drawn width, so what follows it\n * stays honest about being approximate. */\nfunction layout(clips, pps, sequential) {\n let cursor = 0;\n return clips.map((c, i) => {\n const known = Number.isFinite(c.duration);\n const w = known ? Math.max(MIN_CLIP_W, c.duration * pps) : UNKNOWN_W;\n const t0 = sequential ? cursor : (c.start || 0);\n if (sequential) cursor += known ? c.duration : UNKNOWN_W / pps;\n return { clip: c, i, t0, x: t0 * pps, w, known };\n });\n}\n\n/** The nearest snap target within `tol` seconds, or the raw value. */\nfunction snapTo(t, targets, tol) {\n let best = null;\n let bestD = tol;\n for (const s of targets) {\n const d = Math.abs(s - t);\n if (d <= bestD) { bestD = d; best = s; }\n }\n return best === null ? { value: t, guide: null } : { value: best, guide: best };\n}\n\n/* ── the component ──────────────────────────────────────────────────────────────────────────── */\n\nexport function Timeline({\n tracks = [],\n currentTime = 0,\n onSeek,\n onSelectClip,\n selectedClipId = null,\n /** (clip, edge:'start'|'end', newDurationSeconds, track). Fires once, on release. */\n onTrim,\n /** (clip, atSecondsFromClipStart, track). */\n onSplit,\n /** Sequential lane: (clip, toIndex, track). Placed lane: (clip, newStartSeconds, track). */\n onMoveClip,\n onDeleteClip,\n /** Something was dropped on a lane: (payload, {trackId, seconds, index}). `trackId` is null when\n * it landed on the NEW-LANE strip below the last lane, which is how a layer gets created by\n * dropping rather than by a button nobody finds. */\n onDropClip,\n /** Reads the drag's payload out of a DataTransfer. Return null to refuse the drop, which is\n * what turns the lane's highlight off for things this timeline cannot take. */\n readDrop,\n /** Text on the strip below the last lane. Omit and no such strip is drawn. */\n newLaneLabel,\n laneAppend,\n zoomStorageKey = null,\n snapStorageKey = null,\n emptyLabel = 'Nothing here yet.',\n className = '',\n}) {\n const scroller = useRef(null);\n const innerRef = useRef(null);\n const [pps, setPps] = useState(() => {\n if (zoomStorageKey && typeof window !== 'undefined') {\n const n = parseFloat(window.localStorage.getItem(zoomStorageKey) || '');\n if (Number.isFinite(n)) return clamp(n, TL_MIN_PPS, TL_MAX_PPS);\n }\n return TL_DEFAULT_PPS;\n });\n const [snapping, setSnapping] = useState(() => (\n snapStorageKey && typeof window !== 'undefined'\n ? window.localStorage.getItem(snapStorageKey) !== '0' : true));\n /** The gesture in flight. A ref because pointer handlers must see it synchronously. */\n const gesture = useRef(null);\n /** What the gesture is doing right now: live preview geometry + annotation. */\n const [drag, setDrag] = useState(null);\n const anchor = useRef(null);\n /** Which lane the pointer is over during a drag, and where in time. Drawn as a marker so a drop\n * lands where it was aimed rather than wherever the list decides. */\n const [dropAt, setDropAt] = useState(null);\n\n const rows = useMemo(\n () => tracks.map((t) => ({ ...t, sequential: t.sequential !== false,\n laid: layout(t.clips || [], pps, t.sequential !== false) })),\n [tracks, pps]);\n\n const contentSeconds = useMemo(() => {\n let end = 0;\n for (const t of rows) for (const l of t.laid) end = Math.max(end, l.t0 + l.w / pps);\n return end;\n }, [rows, pps]);\n\n /** Every clip edge, zero, and the playhead: what a drag snaps to. */\n const snapTimes = useMemo(() => {\n const out = [0, currentTime];\n for (const t of rows) for (const l of t.laid) { out.push(l.t0); out.push(l.t0 + l.w / pps); }\n return out;\n }, [rows, pps, currentTime]);\n\n /* ── zoom ─────────────────────────────────────────────────────────────────────────────────── */\n\n const setZoom = useCallback((next, clientX) => {\n const v = clamp(next, TL_MIN_PPS, TL_MAX_PPS);\n const el = scroller.current;\n if (el) {\n const rect = el.getBoundingClientRect();\n const vx = clientX === undefined ? (rect.width + TL_HEAD_W) / 2 : clientX - rect.left;\n anchor.current = { t: Math.max(0, (el.scrollLeft + vx - TL_HEAD_W) / pps), vx };\n }\n setPps(v);\n if (zoomStorageKey && typeof window !== 'undefined') {\n try { window.localStorage.setItem(zoomStorageKey, String(v)); } catch { /* private mode */ }\n }\n }, [pps, zoomStorageKey]);\n\n const fitPps = useCallback((seconds) => {\n const el = scroller.current;\n if (!el || !(seconds > 0)) return null;\n const room = el.clientWidth - TL_HEAD_W - 56;\n return room > 0 ? clamp(room / seconds, TL_MIN_PPS, TL_MAX_PPS) : null;\n }, []);\n\n const fit = useCallback(() => {\n const v = fitPps(contentSeconds);\n if (v !== null) { setPps(v); if (scroller.current) scroller.current.scrollLeft = 0; }\n }, [fitPps, contentSeconds]);\n\n // Fit ONCE, when there is first something to fit: a one-second clip at a fixed default is a\n // sliver that reads as a broken control. Once, not on every change — re-fitting under someone\n // who just zoomed is the control fighting them. A stored zoom wins; they chose it.\n const fitted = useRef(false);\n useLayoutEffect(() => {\n if (fitted.current || !(contentSeconds > 0)) return;\n if (zoomStorageKey && typeof window !== 'undefined'\n && window.localStorage.getItem(zoomStorageKey)) { fitted.current = true; return; }\n const v = fitPps(contentSeconds);\n if (v !== null) { fitted.current = true; setPps(v); }\n }, [contentSeconds, fitPps, zoomStorageKey]);\n\n useLayoutEffect(() => {\n const a = anchor.current;\n if (!a || !scroller.current) return;\n anchor.current = null;\n scroller.current.scrollLeft = Math.max(0, TL_HEAD_W + a.t * pps - a.vx);\n }, [pps]);\n\n useEffect(() => {\n const el = scroller.current;\n if (!el) return undefined;\n const onWheel = (e) => {\n if (!(e.ctrlKey || e.metaKey)) return;\n e.preventDefault();\n setZoom(pps * Math.exp(-e.deltaY * 0.0022), e.clientX);\n };\n el.addEventListener('wheel', onWheel, { passive: false });\n return () => el.removeEventListener('wheel', onWheel);\n }, [pps, setZoom]);\n\n const timeAt = useCallback((clientX) => {\n const el = innerRef.current;\n if (!el) return 0;\n return Math.max(0, (clientX - el.getBoundingClientRect().left - TL_HEAD_W) / pps);\n }, [pps]);\n\n /* ── gestures ─────────────────────────────────────────────────────────────────────────────── */\n\n /** ONE pointer pipeline for scrub, trim and move. They differ in what they compute, not in how\n * the press, the movement threshold, the listeners and the release are handled. Writing that\n * three times is how one of them ends up without its cleanup and leaves the document mid-edit\n * when the pointer goes up outside the window. */\n const beginGesture = useCallback((e, spec) => {\n e.preventDefault();\n e.stopPropagation();\n gesture.current = { ...spec, startX: e.clientX, active: false, value: null };\n const move = (ev) => {\n const cur = gesture.current;\n if (!cur) return;\n if (!cur.active && Math.abs(ev.clientX - cur.startX) < CLICK_SLOP) return;\n cur.active = true;\n let t = timeAt(ev.clientX);\n let guide = null;\n if (snapping && !ev.altKey && cur.kind !== 'scrub') {\n const r = snapTo(t, cur.snapTimes || snapTimes, TL_SNAP_PX / pps);\n t = r.value; guide = r.guide;\n }\n cur.value = t;\n if (cur.kind === 'scrub') onSeek?.(t);\n else setDrag(cur.preview ? { ...cur.preview(t), guide } : { guide });\n };\n const up = () => {\n window.removeEventListener('pointermove', move);\n window.removeEventListener('pointerup', up);\n document.body.classList.remove('rui-tl-gesturing');\n const cur = gesture.current;\n gesture.current = null;\n setDrag(null);\n if (cur?.active && cur.value !== null) cur.commit?.(cur.value);\n else cur?.click?.();\n };\n document.body.classList.add('rui-tl-gesturing');\n window.addEventListener('pointermove', move);\n window.addEventListener('pointerup', up);\n }, [timeAt, snapping, snapTimes, pps, onSeek]);\n\n const onScrub = useCallback((e) => {\n if (!onSeek) return;\n onSeek(timeAt(e.clientX));\n beginGesture(e, { kind: 'scrub' });\n }, [onSeek, timeAt, beginGesture]);\n\n /* ── split ────────────────────────────────────────────────────────────────────────────────── */\n\n /** The clip the playhead is inside, far enough in that both halves would be legal. */\n const splitTarget = useMemo(() => {\n if (!onSplit) return null;\n for (const track of rows) {\n for (const l of track.laid) {\n if (!l.known) continue;\n if (currentTime > l.t0 + TL_MIN_CLIP_S && currentTime < l.t0 + l.clip.duration - TL_MIN_CLIP_S) {\n return { track, l };\n }\n }\n }\n return null;\n }, [rows, currentTime, onSplit]);\n\n const doSplit = useCallback(() => {\n if (!splitTarget) return;\n onSplit(splitTarget.l.clip, currentTime - splitTarget.l.t0, splitTarget.track);\n }, [splitTarget, currentTime, onSplit]);\n\n const selected = useMemo(() => {\n for (const track of rows) for (const l of track.laid) {\n if (l.clip.id === selectedClipId) return { track, l };\n }\n return null;\n }, [rows, selectedClipId]);\n\n const onKeyDown = useCallback((e) => {\n const tag = e.target?.tagName;\n if (tag === 'INPUT' || tag === 'TEXTAREA' || e.target?.isContentEditable) return;\n if (e.key === '+' || e.key === '=') { e.preventDefault(); setZoom(pps * 1.35); }\n else if (e.key === '-' || e.key === '_') { e.preventDefault(); setZoom(pps / 1.35); }\n else if (e.key === 'b' || e.key === 'B') { e.preventDefault(); doSplit(); }\n else if ((e.key === 'Delete' || e.key === 'Backspace') && selected && onDeleteClip) {\n e.preventDefault(); onDeleteClip(selected.l.clip, selected.track);\n }\n }, [pps, setZoom, doSplit, selected, onDeleteClip]);\n\n const toggleSnap = useCallback(() => {\n setSnapping((v) => {\n const next = !v;\n if (snapStorageKey && typeof window !== 'undefined') {\n try { window.localStorage.setItem(snapStorageKey, next ? '1' : '0'); } catch { /* ignore */ }\n }\n return next;\n });\n }, [snapStorageKey]);\n\n /* ── render ───────────────────────────────────────────────────────────────────────────────── */\n\n const major = majorTickStep(pps);\n const minor = major / 5;\n const laneW = Math.max(contentSeconds * pps + 140, 320);\n const ticks = [];\n for (let t = 0; t <= contentSeconds + major; t += major) ticks.push(t);\n\n return (\n <div className={`rui-tl ${className}`} onKeyDown={onKeyDown} tabIndex={0}>\n {/* ── toolbar ─────────────────────────────────────────────────────────────────────────\n The timeline's commands live in a bar, not in a pill floating over the lanes: chrome\n hovering in the corner of the content reads as debris. Every disabled control says WHY,\n because one that is off without a reason looks broken. */}\n <div className=\"rui-tl-bar\">\n {onSplit && (\n <button type=\"button\" className=\"rui-tl-btn\" onClick={doSplit} disabled={!splitTarget}\n title={splitTarget ? 'Split at the playhead (B)'\n : 'Move the playhead inside a clip to split it'}>\n <svg width=\"13\" height=\"13\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\"\n strokeWidth=\"2\" strokeLinecap=\"round\" aria-hidden=\"true\">\n <circle cx=\"6\" cy=\"6\" r=\"3\" /><circle cx=\"6\" cy=\"18\" r=\"3\" />\n <line x1=\"20\" y1=\"4\" x2=\"8.12\" y2=\"15.88\" />\n <line x1=\"14.47\" y1=\"14.48\" x2=\"20\" y2=\"20\" />\n <line x1=\"8.12\" y1=\"8.12\" x2=\"12\" y2=\"12\" />\n </svg>\n <span>Split</span>\n </button>\n )}\n {onDeleteClip && (\n <button type=\"button\" className=\"rui-tl-btn\" disabled={!selected}\n onClick={() => selected && onDeleteClip(selected.l.clip, selected.track)}\n title={selected ? 'Remove the selected clip' : 'Select a clip to remove it'}>\n Remove\n </button>\n )}\n <button type=\"button\" className={`rui-tl-btn${snapping ? ' is-on' : ''}`}\n onClick={toggleSnap} aria-pressed={snapping}\n title=\"Snap to clip edges and the playhead. Hold Alt while dragging to bypass.\">\n Snap\n </button>\n <span className=\"rui-tl-time\" aria-label=\"Playhead position\">{exactLabel(currentTime)}</span>\n <span className=\"rui-tl-spacer\" />\n <button type=\"button\" className=\"rui-tl-btn rui-tl-icon\" onClick={() => setZoom(pps / 1.35)}\n disabled={pps <= TL_MIN_PPS + 1e-6} aria-label=\"Zoom out\" title=\"Zoom out (−)\">−</button>\n <button type=\"button\" className=\"rui-tl-btn rui-tl-icon\" onClick={() => setZoom(pps * 1.35)}\n disabled={pps >= TL_MAX_PPS - 1e-6} aria-label=\"Zoom in\" title=\"Zoom in (+)\">+</button>\n <button type=\"button\" className=\"rui-tl-btn\" onClick={fit} disabled={!(contentSeconds > 0)}\n title=\"Fit the whole timeline in the panel\">Fit</button>\n </div>\n\n <div className=\"rui-tl-scroll\" ref={scroller}>\n <div className=\"rui-tl-inner\" ref={innerRef} style={{ width: TL_HEAD_W + laneW }}>\n\n {/* ── ruler ──────────────────────────────────────────────────────────────────────── */}\n <div className=\"rui-tl-row rui-tl-rulerrow\">\n <div className=\"rui-tl-head rui-tl-rulerhead\" aria-hidden=\"true\" />\n <div\n className=\"rui-tl-ruler\"\n style={{\n width: laneW,\n // Minor ticks are a repeating background, not elements: ten minutes at a fine zoom\n // is thousands of nodes carrying no information a stripe does not.\n backgroundImage:\n 'linear-gradient(90deg, var(--uic-line, #DDDFE6) 0 1px, transparent 1px),'\n + 'linear-gradient(90deg, var(--uic-line-soft, #EFF1F4) 0 1px, transparent 1px)',\n backgroundSize: `${major * pps}px 9px, ${minor * pps}px 5px`,\n }}\n onPointerDown={onScrub}\n role={onSeek ? 'slider' : undefined}\n aria-label={onSeek ? 'Playhead' : undefined}\n aria-valuemin={0} aria-valuemax={Math.round(contentSeconds)}\n aria-valuenow={Math.round(currentTime)}\n tabIndex={onSeek ? 0 : undefined}\n onKeyDown={onSeek ? (e) => {\n const step = e.shiftKey ? 5 : 1;\n if (e.key === 'ArrowLeft') { e.preventDefault(); onSeek(Math.max(0, currentTime - step)); }\n if (e.key === 'ArrowRight') { e.preventDefault(); onSeek(currentTime + step); }\n } : undefined}\n >\n {ticks.map((t) => (\n <span key={t} className=\"rui-tl-ticklbl\" style={{ left: t * pps }}>\n {tickLabel(t, major)}\n </span>\n ))}\n </div>\n </div>\n\n {/* ── lanes ──────────────────────────────────────────────────────────────────────── */}\n {rows.length === 0 && <p className=\"rui-tl-empty\">{emptyLabel}</p>}\n\n {rows.map((track) => (\n <div className=\"rui-tl-row\" key={track.id}>\n {/* A lane whose name does not explain it can say what it is for. \"Layer 2\" means\n nothing until something says it is drawn over Layer 1. */}\n <div className=\"rui-tl-head\" title={track.title || track.label}>\n {track.icon}\n <span className=\"rui-tl-headlbl\">{track.label}</span>\n </div>\n <div\n className={'rui-tl-lane' + (dropAt?.trackId === track.id ? ' is-dropping' : '')}\n style={{ width: laneW, height: LANE_H }}\n onPointerDown={(e) => { if (e.target === e.currentTarget) onScrub(e); }}\n onDragOver={onDropClip ? (e) => {\n if (!readDrop || readDrop(e.dataTransfer) === null) return;\n e.preventDefault(); // preventDefault IS the \"yes, drop here\"\n e.dataTransfer.dropEffect = 'copy';\n setDropAt({ trackId: track.id, t: timeAt(e.clientX) });\n } : undefined}\n onDragLeave={onDropClip ? (e) => {\n if (e.currentTarget.contains(e.relatedTarget)) return;\n setDropAt((d) => (d?.trackId === track.id ? null : d));\n } : undefined}\n onDrop={onDropClip ? (e) => {\n const payload = readDrop?.(e.dataTransfer) ?? null;\n setDropAt(null);\n if (payload === null) return;\n e.preventDefault();\n const t = timeAt(e.clientX);\n // Where in the ORDER it landed, for a lane that is a sequence.\n let index = 0;\n for (const other of track.laid) {\n if (t > other.t0 + (other.w / pps) / 2) index += 1;\n }\n onDropClip(payload, { trackId: track.id, seconds: t, index });\n } : undefined}>\n {track.laid.length === 0 && track.emptyLabel && (\n <p className=\"rui-tl-laneempty\">{track.emptyLabel}</p>\n )}\n {track.laid.map((l) => (\n <Clip\n key={l.clip.id ?? l.i}\n l={l} track={track} pps={pps}\n selected={selectedClipId === l.clip.id}\n drag={drag}\n onSelect={() => onSelectClip?.(l.clip, l.i)}\n beginGesture={beginGesture}\n onTrim={onTrim} onMoveClip={onMoveClip}\n snapTimes={snapTimes}\n />\n ))}\n {dropAt?.trackId === track.id && (\n <span className=\"rui-tl-dropmark\" style={{ left: dropAt.t * pps }}\n aria-hidden=\"true\" />\n )}\n {laneAppend && (\n <span className=\"rui-tl-append\"\n style={{ left: track.laid.reduce((n, x) => Math.max(n, x.x + x.w), 0) + 6 }}>\n {laneAppend(track)}\n </span>\n )}\n </div>\n </div>\n ))}\n\n {/* Drop here and a lane is created. It only exists when a drop is possible at all, and\n it says what it does — a bare dashed rectangle is a thing people avoid rather than\n aim at. */}\n {onDropClip && newLaneLabel && (\n <div className=\"rui-tl-row\">\n <div className=\"rui-tl-head rui-tl-newhead\" aria-hidden=\"true\" />\n <div\n className={'rui-tl-newlane' + (dropAt?.trackId === null ? ' is-dropping' : '')}\n style={{ width: laneW }}\n onDragOver={(e) => {\n if (!readDrop || readDrop(e.dataTransfer) === null) return;\n e.preventDefault();\n e.dataTransfer.dropEffect = 'copy';\n setDropAt({ trackId: null, t: timeAt(e.clientX) });\n }}\n onDragLeave={(e) => {\n if (e.currentTarget.contains(e.relatedTarget)) return;\n setDropAt((d) => (d?.trackId === null ? null : d));\n }}\n onDrop={(e) => {\n const payload = readDrop?.(e.dataTransfer) ?? null;\n setDropAt(null);\n if (payload === null) return;\n e.preventDefault();\n onDropClip(payload, { trackId: null, seconds: timeAt(e.clientX), index: 0 });\n }}\n >\n <span className=\"rui-tl-newlbl\">{newLaneLabel}</span>\n </div>\n </div>\n )}\n\n {/* A snap guide, drawn only while a gesture is actually locked onto something. */}\n {drag?.guide != null && (\n <div className=\"rui-tl-guide\" style={{ left: TL_HEAD_W + drag.guide * pps }}\n aria-hidden=\"true\" />\n )}\n\n {Number.isFinite(currentTime) && (\n <div className=\"rui-tl-playhead\" style={{ left: TL_HEAD_W + currentTime * pps }}\n aria-hidden=\"true\">\n <span className=\"rui-tl-playhead-grip\" />\n </div>\n )}\n\n {/* Numbers where the gesture is, so a trim is read off the clip and not off the ruler. */}\n {drag?.annotation && (\n <div className=\"rui-tl-annot\" style={{ left: TL_HEAD_W + (drag.annotAt || 0) * pps }}>\n {drag.annotation}\n </div>\n )}\n </div>\n </div>\n </div>\n );\n}\n\n/* ── one clip ───────────────────────────────────────────────────────────────────────────────── */\n\nfunction Clip({ l, track, pps, selected, drag, onSelect, beginGesture, onTrim, onMoveClip,\n snapTimes }) {\n const { clip, x, w, known, t0, i } = l;\n const live = drag?.clipId === clip.id ? drag : null;\n const width = live?.width ?? w;\n const left = live?.left ?? x;\n\n // A FIXED tile size, so zooming changes how many frames you see rather than stretching one.\n // That is the filmstrip convention; see the note at the top on these being one frame repeated.\n const tileW = Math.round((LANE_H - CLIP_INSET * 2) * (16 / 9));\n\n const startTrim = (e, edge) => {\n if (!onTrim || !known) return;\n // HOW FAR THIS EDGE CAN GO BACK OUT, not just in. A trim clamped to the clip's CURRENT length\n // can only ever shorten, so one stray drag makes a shot unrecoverable — the film is still in\n // the file and the UI will not give it back. `headroom` is what the host says is left on each\n // side beyond the present window; absent, the edge can only come in, which is the old\n // behaviour and the honest default when nobody has said otherwise.\n const room = clip.headroom || {};\n const outward = Math.max(0, Number(edge === 'end' ? room.end : room.start) || 0);\n const maxDur = clip.duration + outward;\n beginGesture(e, {\n kind: 'trim',\n snapTimes,\n preview: (t) => {\n const dur = edge === 'end'\n ? clamp(t - t0, TL_MIN_CLIP_S, maxDur)\n : clamp((t0 + clip.duration) - t, TL_MIN_CLIP_S, maxDur);\n const nextW = dur * pps;\n const nextLeft = edge === 'end' ? x : x + (w - nextW);\n return { clipId: clip.id, width: nextW, left: nextLeft,\n annotation: `${exactLabel(dur)} · ${edge === 'end' ? 'out' : 'in'}`,\n annotAt: (nextLeft + nextW) / pps };\n },\n commit: (t) => {\n const dur = edge === 'end'\n ? clamp(t - t0, TL_MIN_CLIP_S, maxDur)\n : clamp((t0 + clip.duration) - t, TL_MIN_CLIP_S, maxDur);\n if (Math.abs(dur - clip.duration) > 1e-3) onTrim(clip, edge, dur, track);\n },\n });\n };\n\n const startMove = (e) => {\n if (!onMoveClip) { onSelect(); return; }\n const half = (known ? clip.duration : 0) / 2;\n beginGesture(e, {\n kind: 'move',\n snapTimes,\n preview: (t) => {\n const at = Math.max(0, t - half);\n return { clipId: clip.id, left: at * pps, annotation: exactLabel(at), annotAt: at };\n },\n commit: (t) => {\n const at = Math.max(0, t - half);\n if (track.sequential) {\n // On a cut, POSITION MEANS ORDER. Which slot the clip's centre landed in is the answer,\n // and reordering is what the host is asked for — \"move this to 4.2s\" is not a thing a\n // magnetic track can honour, and pretending otherwise puts the drawing and the document\n // out of step the moment it re-renders.\n let idx = 0;\n for (const other of track.laid) {\n if (other.clip.id === clip.id) continue;\n if (at + half > other.t0 + (other.w / pps) / 2) idx += 1;\n }\n if (idx !== i) onMoveClip(clip, idx, track);\n } else if (Math.abs(at - t0) > 1e-3) {\n onMoveClip(clip, at, track);\n }\n },\n click: onSelect,\n });\n };\n\n return (\n <article\n className={'rui-tl-clip'\n + (clip.state ? ` is-${clip.state}` : '')\n + (known ? '' : ' is-unmeasured')\n + (selected ? ' is-selected' : '')\n + (live ? ' is-live' : '')}\n style={{ left, width, ...(clip.accent ? { '--rui-tl-accent': clip.accent } : null) }}\n title={clip.title || clip.label}\n tabIndex={0}\n onPointerDown={startMove}\n onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); onSelect(); } }}\n >\n {/* A poster tiles as a strip. With no poster but a playable file, the FILE's own first\n frame is shown — `preload=\"metadata\"` paints it without fetching the whole clip, and it\n is a real frame of the real thing rather than a stand-in. Only when there is neither\n does the block fall back to a glyph, which claims nothing. */}\n {clip.poster ? (\n <span className=\"rui-tl-strip\" style={{\n backgroundImage: `url(\"${String(clip.poster).replace(/\"/g, '\\\\\"')}\")`,\n backgroundSize: `${tileW}px 100%`,\n }} />\n ) : clip.video ? (\n <video className=\"rui-tl-frame\" src={clip.video} preload=\"metadata\" muted playsInline\n tabIndex={-1} aria-hidden=\"true\" />\n ) : (\n <span className=\"rui-tl-blank\" aria-hidden=\"true\">{clip.glyph}</span>\n )}\n\n {clip.badge && <span className=\"rui-tl-badge\">{clip.badge}</span>}\n {known && width > 46 && <span className=\"rui-tl-dur\">{durationLabel(clip.duration)}</span>}\n {clip.label && width > 104 && <span className=\"rui-tl-name\">{clip.label}</span>}\n\n {/* Trim handles, only on a measured clip: there is nothing to trim against a length nobody\n knows, and offering the gesture anyway would conjure a duration out of a drag. */}\n {onTrim && known && (\n <>\n <span className=\"rui-tl-trim l\" onPointerDown={(e) => startTrim(e, 'start')}\n role=\"separator\" aria-label={`Trim the start of ${clip.label || 'this clip'}`} />\n <span className=\"rui-tl-trim r\" onPointerDown={(e) => startTrim(e, 'end')}\n role=\"separator\" aria-label={`Trim the end of ${clip.label || 'this clip'}`} />\n </>\n )}\n </article>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACwBO,SAAS,0B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AC;AAAA,UACjE,gBAAgB,GAAG,KAAK;AAAA,QAC1B,GAAG,IACD,KAAK,QACP;AAAA,UAAC;AAAA;AAAA,YAAM,WAAU;AAAA,YAAe,KAAK,KAAK;AAAA,YAAO,SAAQ;AAAA,YAAW,OAAK;AAAA,YAAC,aAAW;AAAA,YAC9E,UAAU;AAAA,YAAI,eAAY;AAAA;AAAA,QAAO,IAExC,8CAAC,UAAK,WAAU,gBAAe,eAAY,QAAQ,eAAK,OAAM;AAAA,QAG/D,KAAK,SAAS,8CAAC,UAAK,WAAU,gBAAgB,eAAK,OAAM;AAAA,QACzD,SAAS,QAAQ,MAAM,8CAAC,UAAK,WAAU,cAAc,wBAAc,KAAK,QAAQ,GAAE;AAAA,QAClF,KAAK,SAAS,QAAQ,OAAO,8CAAC,UAAK,WAAU,eAAe,eAAK,OAAM;AAAA,QAIvE,UAAU,SACT,gFACE;AAAA;AAAA,YAAC;AAAA;AAAA,cAAK,WAAU;AAAA,cAAgB,eAAe,CAAC,MAAM,UAAU,GAAG,OAAO;AAAA,cACpE,MAAK;AAAA,cAAY,cAAY,qBAAqB,KAAK,SAAS,WAAW;AAAA;AAAA,UAAI;AAAA,UACrF;AAAA,YAAC;AAAA;AAAA,cAAK,WAAU;AAAA,cAAgB,eAAe,CAAC,MAAM,UAAU,GAAG,KAAK;AAAA,cAClE,MAAK;AAAA,cAAY,cAAY,mBAAmB,KAAK,SAAS,WAAW;AAAA;AAAA,UAAI;AAAA,WACrF;AAAA;AAAA;AAAA,EAEJ;AAEJ;","names":["import_react","import_react","import_jsx_runtime","React","import_react","import_jsx_runtime","React","import_react","import_jsx_runtime","import_react","import_react","import_jsx_runtime","Chip","import_jsx_runtime","listening","import_react","import_jsx_runtime","mod","React","import_react","import_jsx_runtime","clamp","import_react","import_jsx_runtime","import_react","import_react","import_jsx_runtime","stack","Field","import_react","import_react","import_jsx_runtime","import_react","import_jsx_runtime","CLIENT_ID","import_jsx_runtime","subtitle","import_react","import_react","import_react","import_react_dom","import_jsx_runtime","import_jsx_runtime","MentionInput","s","React","import_react_dom","import_jsx_runtime","import_react","import_jsx_runtime","import_jsx_runtime","bytesLabel","import_react","import_jsx_runtime","import_react","import_jsx_runtime","import_react","import_jsx_runtime","import_react","import_jsx_runtime","subtitle","import_react","import_jsx_runtime","import_react","import_jsx_runtime","onKey","import_react","import_react_dom","import_jsx_runtime","import_react","import_jsx_runtime","import_react","layout","near","import_jsx_runtime","layout","stack","onKey","React","import_react","import_jsx_runtime"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.js","../src/stream/responses.js","../src/state/blocks.js","../src/state/conversationStore.js","../src/state/turns.js","../src/components/icons.jsx","../src/components/toolMeta.js","../src/components/ToolSteps.jsx","../src/components/ChatMessages.jsx","../src/components/Composer.jsx","../src/components/ChatPanel.jsx","../src/components/Chip.jsx","../src/format.js","../src/input/dictate.js","../src/components/CodeBlock.jsx","../src/components/resizable.jsx","../src/components/TaskList.jsx","../src/components/Dialog.jsx","../src/components/overlay.js","../src/auth/client.js","../src/auth/AuthForm.jsx","../src/auth/GoogleButton.jsx","../src/auth/MicrosoftButton.jsx","../src/sheet/SheetGrid.jsx","../src/mention/MentionInput.jsx","../src/components/Popover.jsx","../src/mention/mentionModel.js","../src/collab/colors.js","../src/components/FileTypeIcon.jsx","../src/components/FileCard.jsx","../src/components/FilePreview.jsx","../src/components/form.jsx","../src/components/Carousel.jsx","../src/components/Card.jsx","../src/components/SearchField.jsx","../src/components/CascadeMenu.jsx","../src/components/Modal.jsx","../src/hooks/useTypewriter.js","../src/components/Panel.jsx","../src/grid/PanelGrid.jsx","../src/grid/layout.js","../src/timeline/Timeline.jsx"],"sourcesContent":["// UI Core — shared Conversational Agent surface (extracted from HarnessRouter).\n// Plain ESM React source: consumers alias this package (Vite resolve.alias / Next webpack alias\n// + tsconfig paths) and import straight from source. No build step. Only peer dep: react.\nexport { createResponsesDispatcher, readSSEStream, pumpResponsesStream } from './stream/responses.js';\nexport { withText, withReasoning, withStep, withResult, asstText } from './state/blocks.js';\nexport { createConversationStore } from './state/conversationStore.js';\n// Gateway turns -> the message shape ChatMessages/ChatPanel render. Also on reifyui/harness; it is\n// here too because ChatPanel's loadHistory takes messages, and converting history must not require\n// importing a transport. Pure function, no fetch.\nexport { turnsToMessages } from './state/turns.js';\nexport { Svg, Chevron, IcDownload, IcEye, IcTool, IcPlug, IcSkill, IcTerminal, IcDoc, IcList, IcGlobe, IcSearch, IcScroll, IcSpawn, IcCheck, IcThink, IcSend, IcX, IcMic, IcPaperclip, IcPanelRight } from './components/icons.jsx';\nexport { humanize, parseArgs, baseName, prettyJson, toolMeta, summarizeSteps } from './components/toolMeta.js';\nexport { ToolGroup, ToolRow } from './components/ToolSteps.jsx';\nexport { ChatMessages, ChatMessagesSkeleton, UserTurn, AssistantTurn, DEFAULT_STATUS_LABELS } from './components/ChatMessages.jsx';\nexport { Composer } from './components/Composer.jsx';\n// The whole conversation column beside a document — history, live turn, retry, attachments,\n// dictation, composer. Four products had a divergent copy of this; the transport and the product's\n// prose stay at the call site, everything else is here. Needs styles/chat.css.\nexport { ChatPanel } from './components/ChatPanel.jsx';\n// Voice input through the browser's own recogniser. Returns null where the API is absent, which\n// is what makes \"render no microphone\" the easy path and a disabled one impossible to reach for.\nexport { createDictation } from './input/dictate.js';\nexport { bytesLabel } from './format.js';\n// CodeBlock lazy-imports highlight.js — the consuming app must depend on highlight.js (^11),\n// same rule as mermaid for the Mermaid blocks. See components/CodeBlock.jsx.\nexport { CodeBlock } from './components/CodeBlock.jsx';\nexport { useResizablePane, PaneResizer } from './components/resizable.jsx';\n// Master list beside a conversation (runs/sessions): filter, status, cursor pagination.\n// Transport-agnostic — the consumer supplies fetchPage(cursor) -> {items, cursor}.\nexport { TaskList, taskStatusGroup } from './components/TaskList.jsx';\n// In-app alert/confirm/prompt. Native browser popups block the event loop and can't be styled,\n// which reads as a browser warning rather than as part of the product — these replace them with\n// the same awaited call-site shape. Needs styles/dialog.css and a <DialogHost> at the root.\nexport { DialogHost, useDialog } from './components/Dialog.jsx';\n// Shared product auth (extracted from ContextualGraph): the engine /v1/auth\n// client (configureAuth({product, engine}) once at boot) + the sign-in form\n// and Google SSO button. Consumers may also deep-import './auth/*'.\nexport {\n configureAuth, authConfig, SESSION_EVENT,\n getSession, clearSession, getToken, isAuthed,\n login, register, googleSignIn, microsoftSignIn, requestPasswordReset, switchOrg,\n refreshToken, handleAuthExpired, logout, authFetch, fetchBalance,\n} from './auth/client.js';\nexport { AuthForm } from './auth/AuthForm.jsx';\nexport { GoogleButton, GOOGLE_ENABLED } from './auth/GoogleButton.jsx';\nexport { MicrosoftButton, MICROSOFT_ENABLED, microsoftIdToken } from './auth/MicrosoftButton.jsx';\n// Shared AI-spreadsheet grid (reusable in the Sheets product AND studio Spaces).\nexport { SheetGrid, sheetToDelimited, sheetToAoA } from './sheet/SheetGrid.jsx';\n// Files, drawn the same wherever they appear. FileTypeIcon uses react-file-icon when it is\n// installed (an optional peer) and falls back to an extension badge when it is not.\nexport { FileTypeIcon, extOf } from './components/FileTypeIcon.jsx';\nexport { FileCard } from './components/FileCard.jsx';\nexport { FilePreview } from './components/FilePreview.jsx';\n// Form primitives. Every surface here had been hand-rolling label+select+textarea, which is why\n// the same form looked different in each of them.\nexport { Field, Input, Textarea, Select, FormActions, Button } from './components/form.jsx';\n// ── the library page: the surface a document product opens on ────────────────\n// Small, product-agnostic pieces that existed 3-6 times each across the products built on this\n// package, every copy slightly different. Needs styles/library.css (+ chip.css, preview.css).\nexport { Carousel } from './components/Carousel.jsx';\nexport { Card } from './components/Card.jsx';\nexport { Chip } from './components/Chip.jsx';\nexport { SearchField } from './components/SearchField.jsx';\n// Anchored panel with placement built in — flips, clamps to the viewport, closes on Escape and\n// outside press. Ten hand-rolled versions of this existed; one survived a phone.\nexport { Popover } from './components/Popover.jsx';\n// Two-level pick in one panel (items, then the highlighted item's options), on Popover.\nexport { CascadeMenu } from './components/CascadeMenu.jsx';\n// A dialog whose body is yours (useDialog answers a question; this holds content). Shares the\n// dialog host's Escape ordering and overlay layer. Needs styles/preview.css.\nexport { Modal } from './components/Modal.jsx';\nexport { useTypewriter } from './hooks/useTypewriter.js';\n// ── boards: a grid of panels ─────────────────────────────────────────────────\n// The frame around one thing on a board (and, crucially, the two states that thing spends most\n// of its life in: loading, and failed-with-a-message), plus the grid that arranges them.\n// Read-only is the default; nothing here depends on a charting library — the chart that usually\n// goes INSIDE a panel is at reifyui/chart, so a board of tables costs nothing extra.\n// Needs styles/panels.css (+ form.css when a panel offers a retry).\nexport { Panel } from './components/Panel.jsx';\nexport { PanelGrid, packLayout } from './grid/PanelGrid.jsx';\n\n// A timeline: lanes of clips against a ruler, with a playhead and pointer-anchored zoom. Product\n// neutral — it takes {start, duration} and draws them, and never invents a width for a duration\n// nobody measured. Needs styles/timeline.css.\nexport {\n Timeline, majorTickStep, tickLabel, durationLabel as timelineDurationLabel,\n TL_MIN_PPS, TL_MAX_PPS, TL_DEFAULT_PPS, TL_HEAD_W,\n} from './timeline/Timeline.jsx';\n// Mentions: a field that holds people, columns, files as pills; the menu at the caret; the\n// read-only renderer; and the token model ({{Name}} / @Name) hosts serialize through.\nexport { MentionInput, MentionText } from './mention/MentionInput.jsx';\nexport * as mention from './mention/mentionModel.js';\n","// OpenAI Responses SSE event parsing — extracted from HarnessRouter's chat client\n// (harnessrouter/src/lib/chat.ts streamResponse). Transport-agnostic: the caller does the\n// fetch/POST however it likes (BFF, broker, direct) and hands the response body (a\n// ReadableStream) plus a handlers object here.\n//\n// Two layers:\n// readSSEStream(body, onData) — raw SSE framing (blank-line separated, data: lines)\n// createResponsesDispatcher(handlers) — native Responses event -> handler dispatch\n// pumpResponsesStream(body, handlers) — both together; resolves to the response id\n//\n// Handlers (all optional):\n// onCreated(responseId) response.created\n// onSession(sessionId) response.created metadata.session_id (continuation)\n// onReasoningDelta(text) response.reasoning_summary_text.delta\n// onToolCall(name, args, callId) response.function_call_arguments.done (name + call_id\n// captured from the matching output_item.added, keyed by\n// output_index — the same pairing HR ships)\n// onToolResult(callId, output) function_call_output items\n// onTextDelta(text) response.output_text.delta\n// onFile({container_id,file_id,filename}) container_file_citation annotations\n// onDone(status, response) response.completed / .incomplete / .failed (a failed\n// response's own status distinguishes user cancels)\n// onError(message) error events\n\nexport function createResponsesDispatcher(h) {\n // function_call name + call_id live on output_item.added; arguments finalize on .done — key by\n // output_index. function_call_output (the tool result) carries the same call_id → pair them.\n const fnByIdx = {};\n const self = {\n responseId: null,\n dispatch(ev) {\n const t = ev.type;\n switch (t) {\n case 'response.created': {\n const resp = ev.response || {};\n self.responseId = resp.id || self.responseId;\n if (self.responseId) h.onCreated?.(self.responseId);\n const sid = (resp.metadata && resp.metadata.session_id) || '';\n if (sid) h.onSession?.(sid);\n break;\n }\n case 'response.reasoning_summary_text.delta':\n h.onReasoningDelta?.(ev.delta || '');\n break;\n case 'response.output_item.added': {\n const item = ev.item || {};\n if (item.type === 'function_call') {\n fnByIdx[ev.output_index] = { name: item.name || 'tool', callId: item.call_id || '' };\n } else if (item.type === 'function_call_output') {\n h.onToolResult?.(item.call_id || '', String(item.output ?? ''));\n }\n break;\n }\n case 'response.function_call_arguments.done': {\n const fn = fnByIdx[ev.output_index] || { name: 'tool', callId: '' };\n h.onToolCall?.(fn.name, ev.arguments || '', fn.callId);\n break;\n }\n case 'response.output_text.delta':\n h.onTextDelta?.(ev.delta || '');\n break;\n case 'response.output_text.annotation.added': {\n const a = ev.annotation || {};\n if (a.type === 'container_file_citation') {\n h.onFile?.({ container_id: a.container_id, file_id: a.file_id, filename: a.filename });\n }\n break;\n }\n case 'response.completed':\n h.onDone?.('completed', ev.response);\n break;\n case 'response.incomplete':\n h.onDone?.('incomplete', ev.response);\n break;\n case 'response.failed':\n // the response object's own status distinguishes a user cancel ('cancelled')\n // from a real failure — surface it so the UI can badge them differently\n h.onDone?.((ev.response && ev.response.status) || 'failed', ev.response);\n break;\n case 'error':\n h.onError?.(ev.message || 'stream error');\n break;\n default:\n break;\n }\n },\n };\n return self;\n}\n\n/** Read an SSE body stream, calling onData(dataString) per frame (data: lines joined). */\nexport async function readSSEStream(body, onData) {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buf = '';\n for (;;) {\n const { value, done } = await reader.read();\n if (done) break;\n buf += decoder.decode(value, { stream: true });\n let nl;\n // SSE frames are separated by a blank line; each frame has one or more `data:` lines.\n while ((nl = buf.indexOf('\\n\\n')) !== -1) {\n const frame = buf.slice(0, nl);\n buf = buf.slice(nl + 2);\n const data = frame.split('\\n').filter((l) => l.startsWith('data:')).map((l) => l.slice(5).trim()).join('');\n if (!data) continue;\n onData(data);\n }\n }\n}\n\n/**\n * Convenience: parse a Responses SSE body end-to-end, dispatching to handlers.\n * Resolves to the response id (for previous_response_id chaining), or null.\n */\nexport async function pumpResponsesStream(body, handlers) {\n const d = createResponsesDispatcher(handlers);\n await readSSEStream(body, (data) => {\n try { d.dispatch(JSON.parse(data)); } catch { /* ignore malformed frame */ }\n });\n return d.responseId;\n}\n","// Assistant-turn block state machine — extracted from HarnessRouter's workbench.\n// An assistant turn is an ORDERED list of blocks appended as stream events arrive, so tool\n// activity interleaves with prose in real time (never all tools hoisted to the top):\n// { kind: 'text', text } — streamed prose\n// { kind: 'tools', reasoning, steps: ToolStep[] } — a contiguous run of tool activity\n// ToolStep: { name, args, result?, callId? }\n\nexport function withText(blocks, d) {\n const out = blocks.slice(); const last = out[out.length - 1];\n if (last && last.kind === 'text') out[out.length - 1] = { kind: 'text', text: last.text + d };\n else out.push({ kind: 'text', text: d });\n return out;\n}\n\nexport function withReasoning(blocks, d) {\n const out = blocks.slice(); const last = out[out.length - 1];\n if (last && last.kind === 'tools') out[out.length - 1] = { ...last, reasoning: last.reasoning + d };\n else out.push({ kind: 'tools', reasoning: d, steps: [] });\n return out;\n}\n\nexport function withStep(blocks, step) {\n const out = blocks.slice(); const last = out[out.length - 1];\n if (last && last.kind === 'tools') out[out.length - 1] = { ...last, steps: [...last.steps, step] };\n else out.push({ kind: 'tools', reasoning: '', steps: [step] });\n return out;\n}\n\nexport function withResult(blocks, callId, output) {\n return blocks.map((b) => (b.kind !== 'tools' ? b\n : { ...b, steps: b.steps.map((t) => ((t.callId && t.callId === callId && t.result === undefined) ? { ...t, result: output } : t)) }));\n}\n\n/** All prose of an assistant message joined (for copy-to-clipboard etc.). */\nexport function asstText(a) {\n return a.blocks.filter((b) => b.kind === 'text').map((b) => b.text).join('\\n\\n');\n}\n","// Session-continuation store — extracted from HarnessRouter's workbench conv store.\n// A module-level (per createConversationStore() instance) map of conversation state keyed by\n// session id (or any stable key for a not-yet-allocated conversation), so:\n// - switching conversations never destroys an optimistic user message or an in-flight stream\n// - N concurrent turns all keep streaming into their own entries in the background\n// - a broadcast/bus event source can write to the same entry the POST stream writes to\n//\n// State shape (extend via patches — unknown keys pass through):\n// { msgs, busy, prevId, firstTurn, loaded }\n// prevId is the last response id (previous_response_id chaining = session continuation).\nimport { useSyncExternalStore } from 'react';\n\nexport function createConversationStore(makeInitial) {\n const initial = makeInitial || (() => ({ msgs: [], busy: false, prevId: null, firstTurn: true, loaded: false }));\n const store = new Map();\n const subs = new Map();\n\n function get(key) {\n let s = store.get(key);\n if (!s) { s = initial(); store.set(key, s); }\n return s;\n }\n function set(key, patch) {\n const cur = get(key);\n const p = typeof patch === 'function' ? patch(cur) : patch;\n store.set(key, { ...cur, ...p });\n subs.get(key)?.forEach((f) => f());\n }\n /** Rebind/seed a key directly (e.g. copy a new-conversation entry onto its real session id). */\n function seed(key, state) { store.set(key, state); subs.get(key)?.forEach((f) => f()); }\n /** Mutate the LAST assistant message of a conversation (streaming writes). */\n function updateLastAssistant(key, fn) {\n set(key, (s) => {\n const out = s.msgs.slice();\n for (let i = out.length - 1; i >= 0; i--) {\n if (out[i].role === 'assistant') { const a = { ...out[i] }; fn(a); out[i] = a; break; }\n }\n return { msgs: out };\n });\n }\n /** React hook: subscribe a component to one conversation's state. */\n function use(key) {\n return useSyncExternalStore(\n (cb) => {\n let set_ = subs.get(key);\n if (!set_) { set_ = new Set(); subs.set(key, set_); }\n set_.add(cb);\n return () => { set_.delete(cb); };\n },\n () => get(key),\n () => get(key),\n );\n }\n return { get, set, seed, updateLastAssistant, use };\n}\n","// Gateway turns -> the message shape ChatMessages renders.\n//\n// This lives in state/ rather than in the transport because it is a pure shape translation with\n// no network in it, and because ChatPanel (a root export) takes ChatMessage[] from its\n// loadHistory: a root consumer must be able to convert history without pulling the whole\n// HarnessRouter fetch layer into its bundle. reifyui/harness re-exports it, so the transport's\n// own callers keep importing it from where the rest of their transport lives.\n//\n// Four apps had each open-coded this function. Three of the four copies were byte-identical and\n// the fourth was the same logic with the status map inlined as a nested ternary.\n\nconst TURN_STATUS = {\n failed: 'failed', error: 'failed', cancelled: 'cancelled',\n incomplete: 'incomplete', max_turns: 'incomplete', timeout: 'incomplete',\n};\n\n/** Gateway turns -> ChatMessages' message shape. */\nexport function turnsToMessages(turns) {\n const out = [];\n for (const t of turns || []) {\n if (t.user) out.push({ role: 'user', text: t.user });\n const steps = (t.tools || []).map((x) => ({ name: x.name, args: x.arguments, result: x.result }));\n const blocks = [];\n if (steps.length) blocks.push({ kind: 'tools', reasoning: '', steps });\n if (t.assistant) blocks.push({ kind: 'text', text: t.assistant });\n const status = TURN_STATUS[t.status] || 'done';\n if (blocks.length || status !== 'done') out.push({ role: 'assistant', blocks, status });\n }\n return out;\n}\n","// Line-glyph icon set for the conversational surface (16-17px, currentColor stroke) —\n// extracted verbatim from HarnessRouter's workbench. Dependency-free (inline SVG only).\nimport React from 'react';\n\nexport function Svg({ children, s = 16 }) {\n return (\n <svg width={s} height={s} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\"\n strokeWidth=\"1.8\" strokeLinecap=\"round\" strokeLinejoin=\"round\">{children}</svg>\n );\n}\n\nexport function Chevron({ dir, size = 16 }) {\n const d = dir === 'left' ? 'M15 18l-6-6 6-6' : dir === 'right' ? 'M9 18l6-6-6-6' : 'M6 9l6 6 6-6';\n return (\n <svg width={size} height={size} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\"\n strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\"><path d={d} /></svg>\n );\n}\n\n// ── tool-step icons (activity timeline) ──\nexport const IcTool = () => <Svg s={17}><path d=\"M14.7 6.3a4 4 0 0 1-5.4 5.4L4 17v3h3l5.3-5.3a4 4 0 0 1 5.4-5.4l-2.3 2.3-1.7-1.7 2.3-2.3a4 4 0 0 0-1.6 0Z\" /></Svg>;\nexport const IcPlug = () => <Svg s={17}><path d=\"M9 2v6M15 2v6M6 8h12v3a6 6 0 0 1-12 0z\" /><path d=\"M12 17v5\" /></Svg>;\nexport const IcSkill = () => <Svg s={17}><path d=\"M9 18h6M10 22h4\" /><path d=\"M12 2a7 7 0 0 0-4 12.7c.6.5 1 1.3 1 2.1V18h6v-1.2c0-.8.4-1.6 1-2.1A7 7 0 0 0 12 2z\" /></Svg>;\nexport const IcTerminal = () => <Svg s={17}><rect x=\"3\" y=\"4\" width=\"18\" height=\"16\" rx=\"2\" /><path d=\"M7 9l3 3-3 3M13 15h4\" /></Svg>;\nexport const IcDoc = () => <Svg s={17}><path d=\"M14 3H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z\" /><path d=\"M14 3v6h6M8 13h8M8 17h6\" /></Svg>;\nexport const IcList = () => <Svg s={17}><path d=\"M8 6h12M8 12h12M8 18h12M3.5 6h.01M3.5 12h.01M3.5 18h.01\" /></Svg>;\nexport const IcGlobe = () => <Svg s={17}><circle cx=\"12\" cy=\"12\" r=\"9\" /><path d=\"M3 12h18M12 3a15 15 0 0 1 0 18a15 15 0 0 1 0-18z\" /></Svg>;\nexport const IcSearch = () => <Svg s={17}><circle cx=\"11\" cy=\"11\" r=\"7\" /><path d=\"m21 21-4.3-4.3\" /></Svg>;\nexport const IcScroll = () => <Svg s={17}><path d=\"M6 3h10a2 2 0 0 1 2 2v12a3 3 0 0 0 3 3H8a2 2 0 0 1-2-2V3z\" /><path d=\"M6 3a2 2 0 0 0-2 2v2h2M10 8h6M10 12h6\" /></Svg>;\nexport const IcSpawn = () => <Svg s={17}><circle cx=\"6\" cy=\"6\" r=\"3\" /><circle cx=\"18\" cy=\"18\" r=\"3\" /><path d=\"M6 9v3a3 3 0 0 0 3 3h6\" /></Svg>;\nexport const IcCheck = () => <Svg s={17}><circle cx=\"12\" cy=\"12\" r=\"9\" /><path d=\"m9 12 2 2 4-4\" /></Svg>;\nexport const IcThink = () => <Svg s={16}><path d=\"M9.5 2a5.5 5.5 0 0 0-3 10.1V15a2 2 0 0 0 2 2h3a2 2 0 0 0 2-2v-2.9A5.5 5.5 0 0 0 9.5 2zM9 20h4M10 22h2\" /></Svg>;\nexport const IcSend = () => <Svg s={16}><path d=\"M12 19V5\" /><path d=\"M5 12l7-7 7 7\" /></Svg>;\n\n// ── chrome glyphs (chat panel, chips, search) ──\n// The package draws its own so a consumer never inherits an icon-library dependency from a\n// component: four apps pull the same four glyphs out of lucide today purely to hand them to a\n// panel that could have drawn them itself.\nexport const IcX = ({ size = 14 }) => <Svg s={size}><path d=\"M18 6 6 18M6 6l12 12\" /></Svg>;\nexport const IcMic = ({ size = 15 }) => <Svg s={size}><rect x=\"9\" y=\"2\" width=\"6\" height=\"12\" rx=\"3\" /><path d=\"M5 11a7 7 0 0 0 14 0M12 18v4M8 22h8\" /></Svg>;\nexport const IcPaperclip = ({ size = 16 }) => <Svg s={size}><path d=\"M21.4 11.1 12.2 20.3a5.5 5.5 0 0 1-7.8-7.8l9.2-9.2a3.7 3.7 0 0 1 5.2 5.2l-9.2 9.2a1.8 1.8 0 0 1-2.6-2.6l8.5-8.5\" /></Svg>;\nexport const IcPanelRight = ({ size = 17 }) => <Svg s={size}><rect x=\"3\" y=\"4\" width=\"18\" height=\"16\" rx=\"2\" /><path d=\"M15 4v16\" /></Svg>;\nexport const IcDownload = ({ size = 16 }) => <Svg s={size}><path d=\"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4\" /><path d=\"M7 10l5 5 5-5\" /><path d=\"M12 15V3\" /></Svg>;\nexport const IcEye = ({ size = 15 }) => <Svg s={size}><path d=\"M2 12s3.6-7 10-7 10 7 10 7-3.6 7-10 7-10-7-10-7z\" /><circle cx=\"12\" cy=\"12\" r=\"3\" /></Svg>;\n","// Tool-step presentation metadata — extracted from HarnessRouter's workbench.\n// toolMeta(name, args) -> { Icon, label, chip? }: a rich end-user-facing row for one tool step.\n// summarizeSteps(steps) -> \"Ran 5 commands, read 2 files, wrote a file\" natural-language recap.\nimport {\n IcTool, IcPlug, IcSkill, IcTerminal, IcDoc, IcList, IcGlobe, IcSearch, IcScroll, IcSpawn,\n} from './icons.jsx';\n\nexport function humanize(s) {\n return (s || '').replace(/[_\\-]+/g, ' ').trim().replace(/\\b\\w/g, (c) => c.toUpperCase());\n}\nexport function parseArgs(args) {\n try { return (typeof args === 'string' ? JSON.parse(args) : args) || {}; } catch { return {}; }\n}\nexport function baseName(p) { return String(p || '').split('/').filter(Boolean).pop() || String(p || ''); }\nexport function prettyJson(s) { try { return JSON.stringify(JSON.parse(s), null, 2); } catch { return s || ''; } }\n\n// Rich end-user-facing metadata for one tool step: icon + label (+ optional filename/kind chip).\nexport function toolMeta(name, args) {\n const n = name || ''; const a = parseArgs(args);\n const mcp = n.match(/^mcp__(.+?)__(.+)$/);\n if (mcp) return { Icon: IcPlug, label: `${humanize(mcp[1])} · ${humanize(mcp[2])}` };\n switch (n) {\n case 'Skill': return { Icon: IcSkill, label: 'Skill', chip: String(a.command || a.name || a.skill || a.skill_name || '') || undefined };\n case 'ToolSearch': return { Icon: IcSearch, label: 'Finding tools' };\n case 'TaskCreate': return { Icon: IcList, label: 'Added task' + (a.subject ? `: ${a.subject}` : '') };\n case 'TaskUpdate': {\n const s = String(a.status || '');\n return { Icon: IcList, label: s === 'completed' ? 'Completed task' : s === 'in_progress' ? 'Started task' : 'Updated task' };\n }\n case 'Bash': {\n const cmd = String(a.command || '');\n const label = /^\\s*mkdir/.test(cmd) ? 'Create working directory' : /^\\s*(cd|ls|pwd|cat|find)\\b/.test(cmd) ? 'Inspected the workspace' : 'Ran a command';\n return { Icon: IcTerminal, label };\n }\n case 'Write': return { Icon: IcDoc, label: 'Wrote a file', chip: baseName(a.file_path || a.path) };\n case 'Edit': case 'MultiEdit': return { Icon: IcDoc, label: 'Edited a file', chip: baseName(a.file_path || a.path) };\n case 'Read': return { Icon: IcScroll, label: 'Read ' + (baseName(a.file_path || a.path) || 'a file') };\n case 'Glob': return { Icon: IcSearch, label: 'Found files' };\n case 'Grep': return { Icon: IcSearch, label: 'Searched code' };\n case 'LS': return { Icon: IcList, label: 'Listed files' };\n case 'WebSearch': return { Icon: IcGlobe, label: 'Searched the web' };\n case 'WebFetch': return { Icon: IcGlobe, label: 'Fetched a web page' };\n case 'Task': case 'Agent': return { Icon: IcSpawn, label: 'Ran a sub-agent' };\n default: return { Icon: IcTool, label: humanize(n) };\n }\n}\n\n// Natural-language summary for a group of steps, counted per operation type and concatenated,\n// e.g. \"Ran 5 commands\" or \"Ran 5 commands, read 2 files, wrote a file\".\nexport function summarizeSteps(steps) {\n // name -> a stable category key (Edit/MultiEdit collapse; mcp__*/unknown -> 'tool')\n const catOf = (n) => {\n if (/^mcp__/.test(n)) return 'tool';\n return ({ Bash: 'bash', Write: 'write', Edit: 'edit', MultiEdit: 'edit', Read: 'read', Glob: 'glob',\n Grep: 'grep', LS: 'ls', WebSearch: 'websearch', WebFetch: 'webfetch', Task: 'agent', Agent: 'agent',\n ToolSearch: 'toolsearch', Skill: 'skill', TaskCreate: 'taskcreate', TaskUpdate: 'taskupdate' })[n] || 'tool';\n };\n // category -> phrase(count). Lowercase; the first word of the whole summary is capitalized below.\n const phrase = (cat, c) => {\n const one = c === 1;\n switch (cat) {\n case 'bash': return one ? 'ran a command' : `ran ${c} commands`;\n case 'write': return one ? 'wrote a file' : `wrote ${c} files`;\n case 'edit': return one ? 'edited a file' : `edited ${c} files`;\n case 'read': return one ? 'read a file' : `read ${c} files`;\n case 'grep': return one ? 'searched code' : `searched code ${c} times`;\n case 'glob': return 'found files';\n case 'ls': return 'listed files';\n case 'websearch': return one ? 'searched the web' : `searched the web ${c} times`;\n case 'webfetch': return one ? 'fetched a page' : `fetched ${c} pages`;\n case 'agent': return one ? 'ran a sub-agent' : `ran ${c} sub-agents`;\n case 'toolsearch': return 'loaded tools';\n case 'skill': return one ? 'used a skill' : `used ${c} skills`;\n case 'taskcreate': return one ? 'added a task' : `added ${c} tasks`;\n case 'taskupdate': return one ? 'updated a task' : `updated ${c} tasks`;\n default: return one ? 'used a tool' : `used ${c} tools`;\n }\n };\n // count per category, preserving first-seen order\n const order = [];\n const counts = {};\n for (const s of steps) {\n const cat = catOf(s.name || '');\n if (!(cat in counts)) { counts[cat] = 0; order.push(cat); }\n counts[cat]++;\n }\n if (order.length === 0) return 'Working…';\n const parts = order.map((cat) => phrase(cat, counts[cat]));\n const j = parts.join(', ');\n return j.charAt(0).toUpperCase() + j.slice(1);\n}\n","// Activity timeline — extracted from HarnessRouter's workbench.\n// ToolGroup: a collapsible group whose summary is a natural-language recap (\"Ran 5 commands,\n// wrote a file\"); open while the turn runs, auto-collapses when it concludes. Each ToolRow\n// carries a typed icon + friendly label (+ filename chip) and expands to its Request / Result.\n//\n// Override slot: renderStep(step, idx) replaces the default ToolRow for a step (return\n// undefined to fall through to the default).\nimport React, { useEffect, useState } from 'react';\nimport { Chevron, IcThink, IcCheck } from './icons.jsx';\nimport { toolMeta, summarizeSteps, prettyJson } from './toolMeta.js';\n\n// Takes a single `props` object (destructured inside) so TSX consumers don't infer every slot\n// as required.\nexport function ToolGroup(props) {\n const {\n reasoning, steps, running,\n workingLabel = 'Working…', thinkingLabel = 'Thinking', doneLabel = 'Done', thoughtLabel = 'Thought process',\n renderStep,\n } = props;\n // Open while the turn runs; auto-collapse to a one-line recap once it concludes.\n const [open, setOpen] = useState(running);\n useEffect(() => { setOpen(running); }, [running]);\n if (!reasoning && steps.length === 0) return null;\n const summary = running ? workingLabel : (steps.length ? summarizeSteps(steps) : thoughtLabel);\n return (\n <div className={'wbx-acts' + (open ? ' open' : '')}>\n <button className=\"wbx-acts-sum\" onClick={() => setOpen((v) => !v)}>\n <Chevron dir={open ? 'down' : 'right'} size={13} /><span>{summary}</span>\n </button>\n {open && (\n <div className=\"wbx-acts-body\">\n {reasoning && (\n <div className=\"wbx-act\"><span className=\"wbx-act-ic-t thinking\"><IcThink /></span>\n <div className=\"wbx-act-main\"><div className=\"wbx-act-k\">{thinkingLabel}</div>\n <div className=\"wbx-act-v\">{reasoning}</div></div></div>\n )}\n {steps.map((s, j) => {\n if (renderStep) {\n const el = renderStep(s, j);\n if (el !== undefined) return <React.Fragment key={j}>{el}</React.Fragment>;\n }\n return <ToolRow key={j} step={s} />;\n })}\n {!running && (\n <div className=\"wbx-act\"><span className=\"wbx-act-ic-t done\"><IcCheck /></span>\n <div className=\"wbx-act-main\"><div className=\"wbx-act-k\">{doneLabel}</div></div></div>\n )}\n </div>\n )}\n </div>\n );\n}\n\nexport function ToolRow(props) {\n const { step, requestLabel = 'Request', resultLabel = 'Result' } = props;\n const [open, setOpen] = useState(false);\n const meta = toolMeta(step.name, step.args);\n const Icon = meta.Icon;\n const hasDetail = !!(step.args && step.args !== '{}') || step.result !== undefined;\n return (\n <div className=\"wbx-act\">\n <span className=\"wbx-act-ic-t\"><Icon /></span>\n <div className=\"wbx-act-main\">\n <button className={'wbx-act-row' + (open ? ' open' : '')} disabled={!hasDetail} onClick={() => setOpen((v) => !v)}>\n <span className=\"wbx-act-k\">{meta.label}</span>\n {meta.chip && <span className=\"wbx-act-chip\">{meta.chip}</span>}\n {hasDetail && <span className=\"wbx-act-exp\"><Chevron dir={open ? 'down' : 'right'} size={12} /></span>}\n </button>\n {open && (\n <div className=\"wbx-act-detail\">\n {step.args && step.args !== '{}' && (\n <div className=\"wbx-act-block\"><div className=\"wbx-act-block-h\">{requestLabel}</div>\n <pre className=\"wbx-act-pre\">{prettyJson(step.args)}</pre></div>\n )}\n {step.result !== undefined && (\n <div className=\"wbx-act-block\"><div className=\"wbx-act-block-h\">{resultLabel}</div>\n <pre className=\"wbx-act-pre\">{String(step.result).slice(0, 4000)}</pre></div>\n )}\n </div>\n )}\n </div>\n </div>\n );\n}\n","// Message list — extracted from HarnessRouter's workbench conversation render.\n// Messages:\n// { role: 'user', text, ... }\n// { role: 'assistant', blocks, status: 'running'|'done'|'failed'|'cancelled'|'incomplete', ... }\n// Assistant blocks render in stream order so tool activity interleaves with prose.\n//\n// Override slots (all optional):\n// renderMarkdown(text) markdown renderer for prose blocks (inject your ReactMarkdown;\n// default is a plain pre-wrap div — the package has no deps)\n// renderMessage(m, i) full custom render for a message (return undefined to fall through)\n// userExtras(m, i) extra content INSIDE the user bubble, before the text\n// (HR renders its attachment cards here)\n// workingExtra(m, i) extra content on the live Working row (HR's Stop button)\n// assistantFooter(m, i) content below a finished assistant turn (file cards, action row)\n// roleLabel(m, i) small caption above a turn (\"You\", the agent's name); none by default\n// renderStep(step, j) per-step override inside the activity timeline\n// statusLabels terminal badge copy per status\n// workingLabel / toolLabels live-indicator + timeline copy\nimport React from 'react';\nimport { ToolGroup } from './ToolSteps.jsx';\n\nexport const DEFAULT_STATUS_LABELS = {\n failed: '✕ Failed. See the output above for the reason',\n cancelled: '◼ Stopped by you',\n // Claims only what is true of every cause: an incomplete turn may have hit its step or time\n // budget, or been cut mid-flight (a replica restart under a live turn settles as incomplete).\n // Asserting \"step or time limit\" for all of them sent an operator debugging a limit that was\n // never reached. A host that knows the actual cause says so in its own chrome (statusLabels /\n // assistantFooter).\n incomplete: '◔ Stopped before finishing. Continue to resume',\n};\n\nconst defaultMarkdown = (text) => <div style={{ whiteSpace: 'pre-wrap' }}>{text}</div>;\n\n// Reduced motion: the typewriter is motion — render streamed text directly.\nconst REDUCED_MOTION = typeof window !== 'undefined'\n && typeof window.matchMedia === 'function'\n && window.matchMedia('(prefers-reduced-motion: reduce)').matches;\n\n// Typewriter reveal for the actively-streaming text block. Deltas arrive in ~1.2s bursts, so raw\n// rendering makes short answers pop in whole. This fills characters at a deliberate pace: reveal\n// the currently-pending text over ~REVEAL_SEC seconds, but never slower than MIN_CPS (so the last\n// characters don't drag) — and because the rate is (gap / REVEAL_SEC), a newly-arrived batch grows\n// the gap and automatically speeds the reveal to catch up. Snaps to full when streaming stops.\n//\n// The typewriter is a DELTA smoother, not an entrance animation: text already present at mount is\n// history (e.g. opening a running session loads the turn's progress-so-far as one snapshot) and\n// paints instantly — only text appended after mount animates. A turn started live in this tab\n// mounts with empty text, so its stream animates exactly as before.\nconst REVEAL_SEC = 3; // a pending burst fills over ~3s...\nconst MIN_CPS = 10; // ...unless the tail is small, then at least this many chars/sec\nfunction TypewriterText(props) {\n const { text, render } = props;\n const active = props.active && !REDUCED_MOTION;\n const [n, setN] = React.useState(() => (text ? text.length : 0));\n const textRef = React.useRef(text);\n textRef.current = text;\n const accRef = React.useRef(text ? text.length : 0); // float char position (setN renders the floor)\n React.useEffect(() => {\n if (!active) { setN(textRef.current ? textRef.current.length : 0); return undefined; }\n let raf; let prev = null;\n const tick = (t) => {\n if (prev == null) prev = t;\n const dt = Math.min(0.1, (t - prev) / 1000); // clamp dt so a backgrounded tab doesn't jump\n prev = t;\n const len = textRef.current ? textRef.current.length : 0;\n const gap = len - accRef.current;\n if (gap > 0) {\n const cps = Math.max(MIN_CPS, gap / REVEAL_SEC); // bigger backlog -> faster reveal\n accRef.current = Math.min(len, accRef.current + cps * dt);\n setN(Math.floor(accRef.current));\n }\n raf = requestAnimationFrame(tick);\n };\n raf = requestAnimationFrame(tick);\n return () => cancelAnimationFrame(raf);\n }, [active]);\n const shown = active ? (text || '').slice(0, n) : (text || '');\n return render(shown);\n}\n\n// NOTE: components take a single `props` object and destructure inside — TypeScript consumers\n// (HR is TSX) infer inline-destructured JS props as REQUIRED, which would force every slot.\nexport function UserTurn(props) {\n const { msg, children, label } = props;\n const bubble = (\n <div className=\"wbx-bubble-user\">\n {children}\n {msg.text && <div className=\"wbx-bubble-text\">{msg.text}</div>}\n </div>\n );\n // With a caption, caption and bubble share one column so the caption's left edge is the\n // bubble's left edge (the design), while the column itself still sits at the trailing side.\n return (\n <div className=\"wbx-turn user\">\n {label ? <div className=\"wbx-turn-body\"><div className=\"wbx-role\">{label}</div>{bubble}</div> : bubble}\n </div>\n );\n}\n\nexport function AssistantTurn(props) {\n const {\n msg,\n renderMarkdown = defaultMarkdown,\n workingLabel = 'Working…',\n workingExtra,\n statusLabels = DEFAULT_STATUS_LABELS,\n renderStep,\n toolLabels,\n footer,\n label,\n } = props;\n return (\n <div className=\"wbx-turn asst\">\n {label ? <div className=\"wbx-role\">{label}</div> : null}\n {msg.blocks.map((b, bi) => (b.kind === 'tools'\n ? <ToolGroup key={bi} reasoning={b.reasoning} steps={b.steps}\n running={msg.status === 'running' && bi === msg.blocks.length - 1}\n renderStep={renderStep} {...(toolLabels || {})} />\n : <div key={bi} className=\"wbx-md\"><TypewriterText text={b.text} render={renderMarkdown}\n active={msg.status === 'running' && bi === msg.blocks.length - 1} /></div>\n ))}\n {/* Live \"working\" indicator BELOW the last row for the whole running turn (not just before\n the first token) — long tool/think phases otherwise look frozen. */}\n {msg.status === 'running' && (\n <div className=\"wbx-working\" aria-label=\"Working\">\n <span className=\"wbx-working-dots\"><span /><span /><span /></span>\n <span className=\"wbx-working-txt\">{workingLabel}</span>\n {workingExtra}\n </div>\n )}\n {(msg.status === 'failed' || msg.status === 'cancelled' || msg.status === 'incomplete') && (\n <div className={'wbx-turnbadge ' + msg.status} role=\"status\">{statusLabels[msg.status]}</div>\n )}\n {footer}\n </div>\n );\n}\n\n// Loading placeholder for the conversation. Mirrors UserTurn/AssistantTurn geometry\n// exactly (same .wbx-turn / .wbx-bubble-user / .wbx-md classes), so when real history\n// streams in it lands with ZERO layout shift — assistant turns are full-width prose\n// lines, user turns are right-aligned brand-tinted bubbles a fraction of the column.\n// Themeable through the same --uic-* tokens as the live surface (light + dark), and\n// the wrapper is display:contents so the turns inherit the consumer's own inter-turn\n// spacing. Use on any conversational surface while history / the first tokens load:\n// {loading ? <ChatMessagesSkeleton /> : <ChatMessages ... />}\n// Pass `turns` to customize the mix (each {role:'user'|'assistant', lines:[widths],\n// width?} — user `width` is the bubble's fraction of the column).\nconst DEFAULT_SKELETON_TURNS = [\n { role: 'assistant', lines: ['94%', '82%', '58%'] },\n { role: 'user', width: '46%', lines: ['88%', '62%'] },\n { role: 'assistant', lines: ['90%', '97%', '71%'] },\n { role: 'user', width: '38%', lines: ['80%'] },\n];\n\nexport function ChatMessagesSkeleton(props) {\n const turns = (props && props.turns) || DEFAULT_SKELETON_TURNS;\n return (\n <div className=\"wbx-skel\" aria-busy=\"true\" aria-label=\"Loading conversation\">\n {turns.map((t, i) => (t.role === 'user' ? (\n <div key={i} className=\"wbx-turn user wbx-skel-turn\" aria-hidden=\"true\">\n <div className=\"wbx-bubble-user wbx-skel-lines\" style={{ width: t.width }}>\n {t.lines.map((w, j) => <span key={j} className=\"wbx-skel-bar\" style={{ width: w }} />)}\n </div>\n </div>\n ) : (\n <div key={i} className=\"wbx-turn asst wbx-skel-turn\" aria-hidden=\"true\">\n <div className=\"wbx-md wbx-skel-lines\">\n {t.lines.map((w, j) => <span key={j} className=\"wbx-skel-bar\" style={{ width: w }} />)}\n </div>\n </div>\n )))}\n </div>\n );\n}\n\nexport function ChatMessages(props) {\n const {\n messages,\n renderMarkdown,\n renderMessage,\n userExtras,\n workingExtra,\n assistantFooter,\n statusLabels,\n renderStep,\n workingLabel,\n toolLabels,\n roleLabel,\n } = props;\n return (\n <>\n {messages.map((m, i) => {\n if (renderMessage) {\n const el = renderMessage(m, i);\n if (el !== undefined) return <React.Fragment key={i}>{el}</React.Fragment>;\n }\n return m.role === 'user' ? (\n <UserTurn key={i} msg={m} label={roleLabel?.(m, i)}>{userExtras?.(m, i)}</UserTurn>\n ) : (\n <AssistantTurn key={i} msg={m}\n renderMarkdown={renderMarkdown}\n workingLabel={workingLabel}\n workingExtra={workingExtra?.(m, i)}\n statusLabels={statusLabels}\n renderStep={renderStep}\n toolLabels={toolLabels}\n label={roleLabel?.(m, i)}\n footer={assistantFooter?.(m, i)} />\n );\n })}\n </>\n );\n}\n","// Composer — extracted from HarnessRouter's workbench composer (textarea + bottom action row).\n// Enter sends (Shift+Enter for a newline). Auto-grows to fit content, capped at maxRows, then\n// scrolls (HR behavior; pass autoGrow={false} for a fixed-height textarea).\n//\n// Slots:\n// attachments node rendered ABOVE the textarea (attachment card row)\n// accessoriesLeft nodes before the flexible spacer (attach button, model select, mic, …)\n// accessoriesRight nodes after the spacer, before the send button\n// renderSend() replaces the default send button entirely\n// inline single-line layout: accessories, textarea and send share ONE row,\n// vertically aligned (the classic chat input). Buttons stick to the\n// bottom edge as the textarea grows, so multiline still reads right.\n// tray node rendered INSIDE the card, under the action row — one seamless\n// surface, no divider band. This is where a product puts the row that\n// belongs to the message being composed (Arena's harness+model chips,\n// a template picker, a recipient list) rather than to the app chrome.\n// onFiles(FileList) files dropped on the composer (or on dropTargetRef's element, when a\n// product wants the whole conversation to take a drop). The composer is\n// the one that lights up (.is-dropping) either way. Absent: no drop.\n// dropTargetRef a ref to a wider drop target than the composer itself\n// classNames { root, input, row } — each REPLACES the default class when provided,\n// so a product can restyle wholesale without fighting the package CSS\n//\n// NOTE: autoGrow and a CSS-driven min-height on the textarea are mutually exclusive — autoGrow\n// writes an explicit height on every keystroke, which the min-height then cannot raise. A fixed\n// multi-line box wants autoGrow={false} + rows.\nimport React, { useEffect, useRef, useState } from 'react';\nimport { IcSend } from './icons.jsx';\n\n// Takes a single `props` object (destructured inside) so TSX consumers don't infer every slot\n// as required.\nexport function Composer(props) {\n const {\n value,\n onChange,\n onSend,\n disabled = false,\n sendDisabled,\n placeholder,\n rows = 1,\n autoGrow = true,\n inline = false,\n maxRows = 15,\n autoFocus,\n // The composer on a landing page often has an ANIMATING placeholder (a typewriter cycling\n // through example prompts), and a placeholder is the textarea's only accessible name unless\n // one is given — so the field announces a different name every few seconds.\n inputAriaLabel,\n attachments,\n tray,\n onFiles,\n dropTargetRef,\n accessoriesLeft,\n accessoriesRight,\n renderSend,\n classNames = {},\n inputRef,\n } = props;\n const ownRef = useRef(null);\n const taRef = inputRef || ownRef;\n const rootRef = useRef(null);\n\n // Drag-and-drop attach. Native listeners on the target (the composer, or the wider element a\n // product names), so any element can take the drop; a depth counter, because children fire\n // their own enter/leave pairs and the highlight would flicker off while crossing them.\n const [dropping, setDropping] = useState(false);\n useEffect(() => {\n if (!onFiles || disabled) return undefined;\n const el = (dropTargetRef && dropTargetRef.current) || rootRef.current;\n if (!el) return undefined;\n let depth = 0;\n const hasFiles = (e) => Array.from((e.dataTransfer && e.dataTransfer.types) || []).includes('Files');\n const enter = (e) => { if (!hasFiles(e)) return; e.preventDefault(); depth += 1; setDropping(true); };\n const over = (e) => { if (!hasFiles(e)) return; e.preventDefault(); e.dataTransfer.dropEffect = 'copy'; };\n const leave = (e) => { if (!hasFiles(e)) return; e.preventDefault(); depth = Math.max(0, depth - 1); if (depth === 0) setDropping(false); };\n const drop = (e) => {\n if (!hasFiles(e)) return;\n e.preventDefault(); depth = 0; setDropping(false);\n if (e.dataTransfer.files && e.dataTransfer.files.length) onFiles(e.dataTransfer.files);\n };\n el.addEventListener('dragenter', enter); el.addEventListener('dragover', over);\n el.addEventListener('dragleave', leave); el.addEventListener('drop', drop);\n return () => {\n el.removeEventListener('dragenter', enter); el.removeEventListener('dragover', over);\n el.removeEventListener('dragleave', leave); el.removeEventListener('drop', drop);\n };\n }, [onFiles, disabled, dropTargetRef]);\n const rootClass = (classNames.root ?? 'wbx-composer') + (dropping ? ' is-dropping' : '');\n\n // Auto-grow the composer to fit its content, capped at ~maxRows rows (then it scrolls).\n useEffect(() => {\n if (!autoGrow) return;\n const el = taRef.current; if (!el) return;\n el.style.height = 'auto';\n const cs = getComputedStyle(el);\n const lh = parseFloat(cs.lineHeight) || 21;\n const max = lh * maxRows + parseFloat(cs.paddingTop || '0') + parseFloat(cs.paddingBottom || '0');\n el.style.height = Math.min(el.scrollHeight, max) + 'px';\n el.style.overflowY = el.scrollHeight > max ? 'auto' : 'hidden';\n }, [value, autoGrow, maxRows, taRef]);\n\n const sendEl = renderSend ? renderSend() : (\n <button type=\"button\" className=\"uic-send\" disabled={sendDisabled} onClick={() => onSend()} aria-label=\"Send message\">\n <IcSend />\n </button>\n );\n\n if (inline) {\n return (\n <div ref={rootRef} className={rootClass}>\n {attachments}\n <div className=\"uic-composer-line\">\n {accessoriesLeft}\n <textarea\n ref={taRef}\n className={classNames.input ?? 'wbx-composer-input'}\n rows={rows}\n value={value}\n placeholder={placeholder}\n aria-label={inputAriaLabel || placeholder}\n disabled={disabled}\n autoFocus={autoFocus}\n onChange={(e) => onChange(e.target.value)}\n onKeyDown={(e) => {\n if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); onSend(); }\n }}\n />\n {accessoriesRight}\n {sendEl}\n </div>\n {tray ? <div className=\"uic-composer-tray\">{tray}</div> : null}\n </div>\n );\n }\n\n return (\n <div ref={rootRef} className={rootClass}>\n {attachments}\n <textarea\n ref={taRef}\n className={classNames.input ?? 'wbx-composer-input'}\n placeholder={placeholder}\n value={value}\n disabled={disabled}\n rows={rows}\n autoFocus={autoFocus}\n aria-label={inputAriaLabel}\n onChange={(e) => onChange(e.target.value)}\n // Enter obeys sendDisabled, exactly as the send button does: two ways to trigger one\n // action must not disagree about whether it is available. (It still swallows the key —\n // a newline is not what Enter means in this box.) sendDisabled defaults to undefined,\n // so for a caller that never set it nothing changes.\n onKeyDown={(e) => {\n if (e.key !== 'Enter' || e.shiftKey) return;\n e.preventDefault();\n if (!sendDisabled) onSend();\n }}\n />\n <div className={classNames.row ?? 'wbx-composer-row'}>\n {accessoriesLeft}\n <span style={{ flex: 1 }} />\n {accessoriesRight}\n {renderSend ? renderSend() : (\n <button type=\"button\" className=\"uic-send\" disabled={sendDisabled} onClick={() => onSend()} aria-label=\"Send message\">\n <IcSend />\n </button>\n )}\n </div>\n {tray ? <div className=\"uic-composer-tray\">{tray}</div> : null}\n </div>\n );\n}\n","// ChatPanel — the whole conversational column beside a document: header, history, live turn,\n// connecting/retry state, attachments, dictation, composer.\n//\n// This existed four times (273 / 336 / 350 / 333 lines) in four products, and every copy had\n// drifted: one shipped a disabled paperclip labelled \"coming soon\", three shipped a disabled\n// microphone, one never showed that a turn was running when the turn had been started somewhere\n// else, one dropped its staged files before checking whether the send would even happen, and one\n// decided whether a session id was \"real\" by looking for the prefix \"new:\" in it.\n//\n// What is HERE is what is the same in all four: the state machine of a conversation.\n// What stays with the CALLER is everything that differs — the transport, the product's prose,\n// and where the panel sits in the page:\n//\n// runTurn run one turn and report it through `handlers`. The panel does not know whether\n// that is one stream, a stream with a fallback, or three requests.\n// loadHistory the conversation so far, already as ChatMessage[]. Callers write\n// `.then(turnsToMessages)`; a caller whose brand-new document has no session\n// short-circuits to [] here and never makes the request. The panel treats the\n// session id as opaque and never parses it, which is what makes that possible.\n//\n// The panel owns `busy` (its own turn is in flight) and takes `externalBusy` (a turn is running\n// that this tab did not start — another window, or the very first turn before the session is\n// queryable). While externalBusy is true and there is nothing local, it polls history so the\n// conversation appears, and when it goes false it reloads once so the final answer lands. A\n// panel that ignores externalBusy shows a blank \"describe what you want\" prompt while the agent\n// is visibly working, which is what one of the four copies did.\n//\n// Session ids: a document created from a landing page has no session until the first turn opens\n// one, so `sessionId` can change mid-stream from the caller's placeholder to the real id. That is\n// the same conversation renaming itself, not a reason to refetch over blocks arriving live — see\n// the adopt guard below.\nimport React, { useCallback, useEffect, useRef, useState } from 'react';\nimport { ChatMessages, ChatMessagesSkeleton } from './ChatMessages.jsx';\nimport { Composer } from './Composer.jsx';\nimport { Chip } from './Chip.jsx';\nimport { IcMic, IcPanelRight, IcPaperclip, IcSend } from './icons.jsx';\nimport { withReasoning, withResult, withStep, withText } from '../state/blocks.js';\nimport { bytesLabel } from '../format.js';\n\n// Not props. Every one of the four copies used these exact numbers, so there is nothing to\n// configure — a knob nobody turns is a knob that only makes the call sites longer.\nconst POLL_MS = 3000; // catch-up poll while a turn runs elsewhere\nconst RETRY_MS = 20000; // resend a message the gateway was not up to receive\nconst PIN_PX = 80; // \"close enough to the bottom\" to keep following the stream\n\n// ChatPanel's own defaults, NOT the package's DEFAULT_STATUS_LABELS. All four panels overrode\n// that export with these sentences; promoting them into the export would silently rewrite the\n// badges of every other consumer, which none of them asked for.\nconst PANEL_STATUS_LABELS = {\n failed: 'This turn failed. Please try again.',\n cancelled: 'Stopped',\n incomplete: 'The turn hit its limit. Send a follow up to continue.',\n};\n\nexport function ChatPanel(props) {\n const {\n sessionId,\n runTurn,\n loadHistory,\n onSessionStarted,\n onChanged,\n\n seed = '',\n onSeedConsumed,\n\n externalBusy = false,\n\n attachments = null,\n dictation = null,\n\n title = '',\n headerRight = null,\n collapsed = false,\n onToggleCollapse,\n width,\n\n placeholder = 'Message',\n emptyState = null,\n busyState,\n connectingLabel = 'connecting',\n connectingNote = 'Still connecting. Your message will be sent as soon as it is online.',\n workingLabel = 'Working…',\n statusLabels = PANEL_STATUS_LABELS,\n renderMarkdown,\n userExtras,\n toolLabels,\n classNames = {},\n } = props;\n\n const [messages, setMessages] = useState([]);\n const [draft, setDraft] = useState('');\n const [busy, setBusy] = useState(false);\n const [connecting, setConnecting] = useState(false);\n // A turn this tab started but can no longer hear: its stream broke after the gateway accepted\n // it. Its messages come from history until it settles.\n const [dropped, setDropped] = useState(false);\n const [histLoading, setHistLoading] = useState(true);\n const [staged, setStaged] = useState([]); // files picked, not yet sent\n const [attachErr, setAttachErr] = useState('');\n const [listening, setListening] = useState(false);\n\n const pendingRef = useRef(null); // { text, files } awaiting a live gateway\n const seededRef = useRef(false);\n const adoptedRef = useRef(null);\n const bodyRef = useRef(null);\n const fileRef = useRef(null);\n const pinnedRef = useRef(true);\n const prevExternalBusyRef = useRef(false);\n const prevIdRef = useRef(sessionId);\n\n // The callbacks arrive as fresh arrow functions on every render of the page, so they cannot be\n // effect dependencies without re-running the history load on every keystroke. Reading them\n // through a ref keeps the effects keyed on the things that actually changed (the session, the\n // busy flags) while still calling the CURRENT function.\n const api = useRef(null);\n api.current = { runTurn, loadHistory, onSessionStarted, onChanged, onSeedConsumed };\n\n // Stop listening when the panel goes away — the recogniser keeps the microphone otherwise.\n // Build `dictation` ONCE at the call site (useState(() => createDictation())): a fresh object\n // per render would stop the recogniser on every keystroke.\n useEffect(() => () => dictation?.stop(), [dictation]);\n\n // ── the message list ──────────────────────────────────────────────────────\n function updateLastAsst(fn) {\n setMessages((m) => {\n const out = m.slice();\n for (let i = out.length - 1; i >= 0; i -= 1) {\n if (out[i].role === 'assistant') { out[i] = fn({ ...out[i] }); break; }\n }\n return out;\n });\n }\n\n function dropRunningAsst() {\n setMessages((m) => (m.length && m[m.length - 1].role === 'assistant' && m[m.length - 1].status === 'running'\n ? m.slice(0, -1) : m));\n }\n\n // Follow the stream only when the reader is already at the bottom. Measured on scroll rather\n // than after the update, because by then the new content has already grown the distance.\n const onBodyScroll = () => {\n const el = bodyRef.current;\n if (el) pinnedRef.current = el.scrollHeight - el.scrollTop - el.clientHeight <= PIN_PX;\n };\n useEffect(() => {\n const el = bodyRef.current;\n if (el && pinnedRef.current) el.scrollTo({ top: el.scrollHeight });\n }, [messages, connecting, histLoading]);\n\n // ── running a turn ────────────────────────────────────────────────────────\n const deliver = useCallback(async (text, files = []) => {\n setBusy(true);\n setMessages((m) => [...m, { role: 'assistant', blocks: [], status: 'running' }]);\n try {\n const out = await api.current.runTurn({\n sessionId,\n text,\n attachments: files,\n handlers: {\n onSession: (sid) => {\n // Arm the adopt guard only when the id is genuinely CHANGING: a session reporting\n // the id it already has is not a rename and must not suppress a later reload.\n if (sid && sid !== sessionId) adoptedRef.current = sid;\n api.current.onSessionStarted?.(sid);\n },\n onReasoningDelta: (d) => updateLastAsst((a) => ({ ...a, blocks: withReasoning(a.blocks, d) })),\n onToolCall: (name, args, callId) => updateLastAsst((a) => ({ ...a, blocks: withStep(a.blocks, { name, args, callId }) })),\n onToolResult: (callId, output) => updateLastAsst((a) => ({ ...a, blocks: withResult(a.blocks, callId, output) })),\n onTextDelta: (d) => updateLastAsst((a) => ({ ...a, blocks: withText(a.blocks, d) })),\n onDone: (status) => updateLastAsst((a) => ({ ...a, status: status === 'completed' ? 'done' : status })),\n onError: () => updateLastAsst((a) => ({\n ...a,\n blocks: a.blocks.length ? a.blocks : withText([], 'Something went wrong. Please try again.'),\n status: 'failed',\n })),\n },\n }) || {};\n if (out.connecting) {\n // Not a failure: the gateway is still coming up. Take the turn back off the list and\n // hold the message — including its files — for the retry.\n dropRunningAsst();\n pendingRef.current = { text, files };\n setConnecting(true);\n return;\n }\n pendingRef.current = null;\n setConnecting(false);\n if (out.dropped) {\n // The turn is running and this tab lost its stream. Never resend: that starts a second\n // turn behind the first (a game played twice at once, a deck written twice). The message\n // stays as sent, the answer stays \"running\", and history fills it in below.\n setDropped(true);\n return;\n }\n updateLastAsst((a) => (a.status === 'running' ? { ...a, status: 'done' } : a));\n api.current.onChanged?.();\n } catch (e) {\n // A refused turn is an answer, not a gateway still coming up: a wall, a bad request, a\n // session busy with another turn. Say so on the message and leave it there; resending\n // every twenty seconds is what filled a pane with \"connecting\" over a game that was\n // playing fine (2026-09-22).\n updateLastAsst((a) => ({\n ...a,\n blocks: a.blocks.length ? a.blocks : withText([], (e && e.message) || 'The turn could not be started.'),\n status: 'failed',\n }));\n } finally {\n setBusy(false);\n }\n }, [sessionId]);\n\n const preparing = staged.some((f) => f.pending);\n const sendBlocked = busy || histLoading || preparing;\n\n function send() {\n const t = draft.trim();\n // The guard comes FIRST. One copy cleared its staged files above this line, so a send that\n // was refused (mid-turn, or with an empty box) silently threw the attachments away.\n if (!t || sendBlocked) return;\n // Sending ends the utterance: dictation is hands-free, and a recogniser still listening after\n // the message has gone types the next sentence into an empty box the person is not looking at.\n if (listening) { dictation?.stop(); setListening(false); }\n const files = staged;\n // The names ride on the message so the bubble shows what was sent with it. They are not\n // replayed from history — the transcript stores the person's text, not the files — so this is\n // what was attached in this session, not a claim about every past turn.\n setMessages((m) => [...m, { role: 'user', text: t, files: files.map((f) => f.name) }]);\n setDraft('');\n setStaged([]);\n setAttachErr('');\n deliver(t, files);\n }\n\n // ── history ───────────────────────────────────────────────────────────────\n // Keyed on sessionId. A placeholder id resolving to the real one is the SAME conversation, and\n // refetching there would setMessages() over blocks arriving live — the panel would show the\n // user's bubble and nothing else while the agent was visibly working. We know it is the same\n // conversation because our own stream just told us so.\n //\n // The guard is consumed on every run, not just the matching one: coming BACK to this id later\n // is a real reason to reload, and a guard that is never cleared would skip that too.\n useEffect(() => {\n const adopted = adoptedRef.current;\n adoptedRef.current = null;\n if (adopted && adopted === sessionId) { prevIdRef.current = sessionId; return undefined; }\n\n // A different document: drop the previous conversation instead of leaving it on screen\n // under a new title until (and only if) the new one turns out to be non-empty.\n if (prevIdRef.current !== sessionId) {\n prevIdRef.current = sessionId;\n setMessages([]);\n setHistLoading(true);\n setStaged([]);\n setAttachErr('');\n // A different document gets its own first message. The once-only latch is about not\n // resending THIS document's seed, not about one seed per panel for all time.\n seededRef.current = false;\n }\n\n // Fired before the await so the caller can strip ?seed= from the URL immediately — a refresh\n // or a back-button must never resend it. It fires whenever a seed was supplied, including\n // when history turns out to be non-empty and the seed is therefore skipped: making the URL\n // non-replayable is the point, and it is not conditional on the send.\n if (seed) api.current.onSeedConsumed?.();\n\n let dead = false;\n Promise.resolve(api.current.loadHistory(sessionId)).then((hist) => {\n if (dead) return;\n if (hist?.length) setMessages(hist);\n setHistLoading(false);\n if (seed && !seededRef.current && !hist?.length) {\n seededRef.current = true;\n setMessages([{ role: 'user', text: seed }]);\n deliver(seed);\n }\n }).catch(() => { if (!dead) setHistLoading(false); });\n return () => { dead = true; };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [sessionId]);\n\n // Retry a message the gateway was not up to receive.\n useEffect(() => {\n if (!connecting) return undefined;\n const iv = window.setInterval(() => {\n const p = pendingRef.current;\n if (p && !busy) deliver(p.text, p.files);\n }, RETRY_MS);\n return () => window.clearInterval(iv);\n }, [connecting, busy, deliver]);\n\n // A turn this tab started and lost the stream of: poll its history until the turn settles,\n // then one last reload for the final answer and whatever it changed.\n useEffect(() => {\n if (!dropped) return undefined;\n let dead = false;\n const tick = () => Promise.resolve(api.current.loadHistory(sessionId)).then((hist) => {\n if (dead || !hist?.length) return;\n const last = hist[hist.length - 1];\n const settled = !(last.role === 'assistant' && last.status === 'running')\n && !externalBusy;\n setMessages(hist);\n if (settled) { setDropped(false); api.current.onChanged?.(); }\n }).catch(() => {});\n const iv = window.setInterval(tick, POLL_MS);\n return () => { dead = true; window.clearInterval(iv); };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [dropped, externalBusy, sessionId]);\n\n // A turn may be running that this tab did not start. While that is true and nothing local is\n // streaming, poll history so its messages appear; when it ends, reload once so the final answer\n // and whatever it changed land here without a refresh.\n useEffect(() => {\n let dead = false;\n let poll;\n const reload = () => Promise.resolve(api.current.loadHistory(sessionId)).then((hist) => {\n // Never clobber a turn streaming in THIS tab, or a message still waiting to be sent.\n if (!dead && hist?.length && !busy && !pendingRef.current) setMessages(hist);\n }).catch(() => {});\n if (externalBusy && messages.length === 0 && !busy) poll = window.setInterval(reload, POLL_MS);\n if (prevExternalBusyRef.current && !externalBusy) {\n reload();\n api.current.onChanged?.();\n }\n prevExternalBusyRef.current = externalBusy;\n return () => { dead = true; if (poll) window.clearInterval(poll); };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [externalBusy, messages.length, busy, sessionId]);\n\n // ── attachments ───────────────────────────────────────────────────────────\n // Each file appears immediately as a pending chip and resolves in place. prepare() is a real\n // wait — a network upload for one product, base64 of up to 25 MB for another — and a picker\n // that looks inert for three seconds is how people pick the same file twice.\n function pick(list) {\n if (!attachments?.prepare) return;\n setAttachErr('');\n for (const file of list) {\n const entry = { name: file.name, size: file.size, pending: true };\n setStaged((cur) => [...cur, entry]);\n Promise.resolve(attachments.prepare(file)).then((ready) => {\n setStaged((cur) => cur.map((s) => (s === entry ? { name: entry.name, size: entry.size, ...ready } : s)));\n }).catch((e) => {\n // Drop the chip and say why on its own line. The alternative one copy shipped — leaving a\n // chip named \"(failed) report.pdf\" in the row — looks like a file that is going to be sent.\n setStaged((cur) => cur.filter((s) => s !== entry));\n setAttachErr(e?.message || `${file.name} could not be attached.`);\n });\n }\n }\n\n function toggleDictation() {\n if (!dictation) return;\n if (listening) { dictation.stop(); setListening(false); return; }\n setListening(true);\n dictation.start({\n onText: (text) => setDraft((cur) => (cur ? `${cur.replace(/\\s+$/, '')} ${text}` : text)),\n onEnd: () => setListening(false),\n onError: () => setListening(false),\n });\n }\n\n // ── render ────────────────────────────────────────────────────────────────\n const rootCls = ['uic-chat', collapsed ? 'is-collapsed' : '', classNames.root || '']\n .filter(Boolean).join(' ');\n const toggle = onToggleCollapse ? (\n <button type=\"button\" className=\"uic-panel-toggle\" onClick={onToggleCollapse}\n title={collapsed ? 'Show the conversation' : 'Hide the conversation'}\n aria-label={collapsed ? 'Show the conversation' : 'Hide the conversation'}\n aria-expanded={!collapsed}>\n <IcPanelRight />\n </button>\n ) : null;\n\n if (collapsed) {\n return (\n <aside className={rootCls}>\n <div className=\"uic-chat-h\">{toggle}</div>\n </aside>\n );\n }\n\n const empty = messages.length === 0;\n const attachControl = attachments ? (\n <>\n <input ref={fileRef} type=\"file\" hidden\n accept={attachments.accept}\n multiple={attachments.multiple !== false}\n onChange={(e) => { pick([...e.target.files]); e.target.value = ''; }} />\n <button type=\"button\" className=\"uic-chat-icon\" aria-label=\"Attach a file\"\n disabled={busy} onClick={() => fileRef.current?.click()}>\n <IcPaperclip />\n </button>\n </>\n ) : null;\n // No control for a capability we do not have: `dictation` is null wherever the browser has no\n // recogniser, and then there is no microphone at all — never a disabled one.\n const micControl = dictation ? (\n <button type=\"button\" className={'uic-chat-icon' + (listening ? ' is-on' : '')}\n aria-label={listening ? 'Stop dictating' : 'Dictate'} aria-pressed={listening}\n disabled={busy} onClick={toggleDictation}>\n <IcMic />\n </button>\n ) : null;\n const defaultBusyState = (\n <div className=\"uic-chat-empty\">\n <span className=\"uic-chat-pulse\" aria-hidden=\"true\" />\n <div className=\"uic-chat-empty-t\">{workingLabel}</div>\n </div>\n );\n\n return (\n <aside className={rootCls} style={width ? { flex: `0 0 ${width}px` } : undefined}>\n <div className=\"uic-chat-h\">\n {toggle}\n {title ? <span className=\"uic-chat-title\" title={title}>{title}</span> : null}\n {headerRight}\n {connecting ? <span className=\"uic-chat-conn\">{connectingLabel}</span> : null}\n {dropped ? <span className=\"uic-chat-conn\">{workingLabel}</span> : null}\n </div>\n\n <div className=\"uic-chat-body\" ref={bodyRef} onScroll={onBodyScroll} role=\"log\" aria-live=\"polite\">\n {histLoading ? <ChatMessagesSkeleton />\n : empty && externalBusy ? (busyState === undefined ? defaultBusyState : busyState)\n : empty ? emptyState\n : (\n <ChatMessages\n messages={messages}\n renderMarkdown={renderMarkdown}\n // The caller's slot falls through to the built-in file chips when it returns\n // undefined, the same contract ChatMessages already uses for renderMessage.\n userExtras={(m, i) => {\n const own = userExtras?.(m, i);\n if (own !== undefined) return own;\n if (!m.files?.length) return undefined;\n return (\n <span className=\"uic-chat-msg-files\">\n {m.files.map((n) => (\n <Chip key={n} icon={<IcPaperclip size={11} />} label={n} title={n} />\n ))}\n </span>\n );\n }}\n workingLabel={workingLabel}\n // All four panels wrote the same string twice, because ToolGroup carries its own\n // default. One label, one place.\n toolLabels={{ workingLabel, ...(toolLabels || {}) }}\n statusLabels={statusLabels}\n />\n )}\n {connecting ? (\n <div className=\"uic-chat-note\" role=\"status\">\n <span className=\"uic-chat-dot\" aria-hidden=\"true\" />\n {connectingNote}\n </div>\n ) : null}\n </div>\n\n <Composer\n value={draft}\n onChange={setDraft}\n onSend={send}\n disabled={histLoading}\n sendDisabled={sendBlocked || !draft.trim()}\n placeholder={placeholder}\n rows={2}\n autoGrow={false}\n classNames={{ root: 'uic-chat-cmp', input: 'uic-chat-cmp-input', row: 'uic-chat-cmp-row' }}\n attachments={(staged.length > 0 || attachErr) ? (\n <div className=\"uic-chat-files\">\n {staged.map((f, i) => (\n <Chip\n key={`${f.name}-${i}`}\n icon={<IcPaperclip size={11} />}\n title={f.name}\n label={<>\n <span className=\"uic-chip-t\">{f.name}</span>\n <span className=\"uic-chip-meta\">{f.pending ? '…' : bytesLabel(f.size)}</span>\n </>}\n onRemove={() => setStaged((c) => c.filter((_, j) => j !== i))}\n removeLabel={`Remove ${f.name}`}\n />\n ))}\n {attachErr ? <span className=\"uic-chat-file-err\">{attachErr}</span> : null}\n </div>\n ) : null}\n accessoriesLeft={attachControl}\n accessoriesRight={micControl}\n renderSend={() => (\n <button type=\"button\" className=\"uic-chat-send\" onClick={send}\n disabled={sendBlocked || !draft.trim()} aria-label=\"Send message\">\n <IcSend />\n </button>\n )}\n />\n </aside>\n );\n}\n","// Chip — a small labelled token: a staged file, a chosen template, a filter that is set.\n//\n// Three spellings of this existed across four apps, and the interactive ones were built as\n// <span role=\"button\" tabIndex={0}> with a keydown handler that only answered Enter (never\n// Space), inside another button. Here the pressable parts are real <button>s, so the keyboard,\n// the accessibility tree and the browser's own focus ring all work without being re-implemented.\n//\n// Width is CSS, not a prop: two of the copies set maxWidth 180 and 220 inline on the same\n// component in the same app. The label ellipsizes against the row it is in.\nimport React, { forwardRef } from 'react';\nimport { IcX } from './icons.jsx';\n\n/**\n * label the text (a node — e.g. name + a size span)\n * icon leading glyph\n * title native tooltip, usually the untruncated label\n * selected this chip stands for something chosen (brand fill)\n * onClick makes the chip itself a button\n * slot the dashed \"open slot\" look for a chip that stands for a choice not yet made\n * (+ add a file). Defaults to clickable-and-unselected, which is how every earlier\n * caller got it; pass slot={false} for a chip that is clickable AND already set,\n * e.g. a chosen route that opens its own editor.\n * onRemove adds a trailing ✕ button; removeLabel is REQUIRED with it, because \"✕\" alone tells\n * a screen reader nothing about which of five chips it removes\n * trailing a node rendered between the label and the ✕ — a compact control the chip carries,\n * e.g. a per-route model <select> in a comparison bar. It is the CALLER's control:\n * the chip never wraps it in its own press target, so a select inside a clickable\n * chip still opens instead of triggering the chip.\n * ref lands on the OUTERMOST element, the box a Popover or CascadeMenu anchors against.\n * ...rest goes onto the press target (aria-expanded, aria-haspopup, data-*), so a chip that\n * opens a menu can say so to assistive tech without the library naming every attribute.\n */\nexport const Chip = forwardRef(function Chip(props, ref) {\n const { label, icon, title, selected = false, onClick, onRemove, removeLabel, trailing, className,\n slot, ...rest } = props;\n const isSlot = slot ?? (Boolean(onClick) && !selected);\n const cls = ['uic-chip',\n selected ? 'is-selected' : '',\n isSlot ? 'is-open' : '',\n className || ''].filter(Boolean).join(' ');\n\n const body = (\n <>\n {icon ? <span className=\"uic-chip-ic\" aria-hidden=\"true\">{icon}</span> : null}\n <span className=\"uic-chip-l\">{label}</span>\n </>\n );\n\n // A chip that is both pressable and removable is two controls, so the outer element stays a\n // plain span and the press target becomes its own button — never a button inside a button.\n const trail = trailing ? <span className=\"uic-chip-tr\">{trailing}</span> : null;\n\n if (onClick && onRemove) {\n return (\n <span ref={ref} className={cls} title={title}>\n <button type=\"button\" className=\"uic-chip-press\" onClick={onClick} {...rest}>{body}</button>\n {trail}\n <button type=\"button\" className=\"uic-chip-x\" aria-label={removeLabel} onClick={onRemove}>\n <IcX size={12} />\n </button>\n </span>\n );\n }\n if (onClick) {\n // trailing needs its own interactivity, and a control inside a <button> is invalid HTML the\n // browser un-nests unpredictably — so a clickable chip that carries one keeps the split form.\n if (trailing) {\n return (\n <span ref={ref} className={cls} title={title}>\n <button type=\"button\" className=\"uic-chip-press\" onClick={onClick} {...rest}>{body}</button>\n {trail}\n </span>\n );\n }\n return <button ref={ref} type=\"button\" className={cls} title={title} onClick={onClick} {...rest}>{body}</button>;\n }\n return (\n <span ref={ref} className={cls} title={title} {...rest}>\n {body}\n {trail}\n {onRemove ? (\n <button type=\"button\" className=\"uic-chip-x\" aria-label={removeLabel} onClick={onRemove}>\n <IcX size={12} />\n </button>\n ) : null}\n </span>\n );\n});\n","// Formatting helpers shared by components that display file metadata.\n\n/** A byte count as a person reads it. Null/undefined renders as nothing, not as \"0 B\" — an\n * unknown size is not a size of zero. */\nexport function bytesLabel(n) {\n if (n == null) return '';\n if (n < 1024) return `${n} B`;\n if (n < 1048576) return `${Math.round(n / 1024)} KB`;\n return `${(n / 1048576).toFixed(1)} MB`;\n}\n","// Voice input, using the recogniser the browser already has.\n//\n// Chrome, Edge and Safari ship SpeechRecognition, and it is exactly the feature — speak, get text\n// in the box. Where the API is absent, createDictation() returns null and the caller renders no\n// button at all. A disabled microphone labelled \"coming soon\" is a control that does nothing,\n// which is worse than its absence: it says the product has a capability it does not have. Three\n// of the four panels this package now serves shipped exactly that button; returning null is what\n// makes the honest version the easy one to write.\n//\n// Nothing here is agent- or product-specific, which is why it is a root export rather than part\n// of a transport: it turns speech into a string and stops.\n\nconst Impl = typeof window !== 'undefined'\n ? (window.SpeechRecognition || window.webkitSpeechRecognition)\n : null;\n\nexport function createDictation({ lang } = {}) {\n if (!Impl) return null;\n let rec = null;\n\n return {\n /** onText fires once per finished phrase, so the draft grows as you speak rather than being\n * rewritten from scratch on every interim guess. */\n start({ onText, onEnd, onError }) {\n this.stop();\n rec = new Impl();\n rec.lang = lang || navigator.language || 'en-US';\n rec.continuous = true;\n rec.interimResults = false;\n rec.onresult = (e) => {\n for (let i = e.resultIndex; i < e.results.length; i += 1) {\n if (!e.results[i].isFinal) continue;\n const text = String(e.results[i][0]?.transcript || '').trim();\n if (text) onText?.(text);\n }\n };\n // 'no-speech' and 'aborted' are the two ways a quiet or cancelled session ends. Neither is\n // a failure worth telling anyone about; both just stop.\n rec.onerror = (e) => {\n rec = null;\n if (e.error === 'no-speech' || e.error === 'aborted') onEnd?.();\n else onError?.(e.error || 'Dictation stopped.');\n };\n rec.onend = () => { rec = null; onEnd?.(); };\n try {\n rec.start();\n } catch (e) {\n rec = null;\n onError?.(e?.message || 'Dictation could not start.');\n }\n },\n\n stop() {\n if (!rec) return;\n const r = rec;\n rec = null;\n try { r.stop(); } catch { /* already stopped */ }\n },\n };\n}\n","// Fenced code block with language-aware syntax highlighting (highlight.js core).\n//\n// Consumers wire this into their markdown renderer's `pre` override (see the ChatPanel /\n// workbench MD_COMPONENTS): a ```mermaid fence keeps rendering as a diagram; every other fence\n// renders here. Design notes (same lazy pattern as the Mermaid block):\n// - highlight.js is LAZY-loaded (dynamic import) — the core plus exactly one small grammar\n// chunk per language actually used, never the full-language bundle. Until it loads the block\n// renders as plain <pre><code>, byte-identical geometry, so there is no layout shift.\n// - Highlighting is DEBOUNCED: while a fence is still streaming in token by token we render\n// plain text and re-arm the timer; the block highlights once it settles. hljs itself never\n// throws on partial input, the debounce just avoids re-lexing on every token.\n// - Unknown / missing language: NO auto-detect, render plain. Wrong-language colors are worse\n// than none.\n// - `gremlin` maps to the groovy grammar (Gremlin is a Groovy DSL — closest match).\n// - Colors are token-driven: .wbx-code maps hljs classes onto five --uic-code-* custom\n// properties (keyword/string/comment/number/function) with defaults tuned for the dark\n// code-block background. See styles/chat.css + README \"Theming\".\n// highlight.js must be a dependency of the CONSUMING app (the dynamic import resolves in its\n// bundler) — same rule as mermaid.\nimport React from 'react';\n\nlet _hljsPromise = null;\nfunction loadHljs() {\n if (!_hljsPromise) {\n _hljsPromise = import('highlight.js/lib/core').then((m) => m.default || m);\n }\n return _hljsPromise;\n}\n\n// One static dynamic-import per grammar so each becomes its own code-split chunk and only the\n// languages that actually appear in a conversation ever download.\nconst GRAMMARS = {\n javascript: () => import('highlight.js/lib/languages/javascript'),\n typescript: () => import('highlight.js/lib/languages/typescript'),\n python: () => import('highlight.js/lib/languages/python'),\n json: () => import('highlight.js/lib/languages/json'),\n bash: () => import('highlight.js/lib/languages/bash'),\n sql: () => import('highlight.js/lib/languages/sql'),\n java: () => import('highlight.js/lib/languages/java'),\n go: () => import('highlight.js/lib/languages/go'),\n rust: () => import('highlight.js/lib/languages/rust'),\n xml: () => import('highlight.js/lib/languages/xml'),\n css: () => import('highlight.js/lib/languages/css'),\n yaml: () => import('highlight.js/lib/languages/yaml'),\n groovy: () => import('highlight.js/lib/languages/groovy'),\n};\n\n// Fence-tag aliases → canonical grammar name.\nconst ALIASES = {\n js: 'javascript', jsx: 'javascript', mjs: 'javascript', cjs: 'javascript', node: 'javascript',\n ts: 'typescript', tsx: 'typescript',\n py: 'python', python3: 'python',\n sh: 'bash', shell: 'bash', zsh: 'bash', console: 'bash',\n html: 'xml', xhtml: 'xml', svg: 'xml',\n yml: 'yaml',\n golang: 'go',\n rs: 'rust',\n jsonc: 'json',\n postgres: 'sql', postgresql: 'sql', mysql: 'sql', plsql: 'sql',\n gremlin: 'groovy',\n};\n\nfunction canonicalLang(tag) {\n const t = String(tag || '').toLowerCase();\n if (!t) return null;\n const name = ALIASES[t] || t;\n return GRAMMARS[name] ? name : null;\n}\n\n// canonical name -> Promise<hljs | null> (null = load failed; stay plain forever, never retry-loop)\nconst _ready = new Map();\nfunction ensureLanguage(name) {\n if (!_ready.has(name)) {\n const p = Promise.all([loadHljs(), GRAMMARS[name]()])\n .then(([hljs, mod]) => {\n if (!hljs.getLanguage(name)) hljs.registerLanguage(name, mod.default || mod);\n return hljs;\n })\n .catch(() => null);\n _ready.set(name, p);\n }\n return _ready.get(name);\n}\n\nexport function CodeBlock(props) {\n const { code, language, className } = props;\n const src = String(code || '');\n const lang = canonicalLang(language);\n const [hl, setHl] = React.useState(null); // { src, html } — html valid only for exactly that src\n\n React.useEffect(() => {\n if (!lang || !src) return undefined;\n let cancelled = false;\n // Debounce: during streaming the fence grows every few ms — wait for a quiet gap, then\n // highlight the settled source. hljs output is fully HTML-escaped (safe to inject).\n const timer = setTimeout(() => {\n ensureLanguage(lang).then((hljs) => {\n if (!hljs || cancelled) return;\n try {\n const out = hljs.highlight(src, { language: lang, ignoreIllegals: true });\n if (!cancelled) setHl({ src, html: out.value });\n } catch {\n /* stay plain */\n }\n });\n }, 200);\n return () => { cancelled = true; clearTimeout(timer); };\n }, [src, lang]);\n\n const html = hl && hl.src === src ? hl.html : null;\n const label = String(language || '').toLowerCase();\n return (\n <pre className={'wbx-code' + (className ? ' ' + className : '')}>\n {label ? <span className=\"wbx-code-lang\" aria-hidden=\"true\">{label}</span> : null}\n {html != null\n ? <code className={'hljs language-' + label} dangerouslySetInnerHTML={{ __html: html }} />\n : <code className={label ? 'language-' + label : undefined}>{src}</code>}\n </pre>\n );\n}\n","// Drag-to-resize pane primitive — drag mechanics lifted from HarnessRouter's workbench\n// useHResize (iframe/text-selection neutralization included), extended with:\n// - min/max clamps (absolute px and/or a viewport fraction, e.g. 60vw)\n// - per-user width persistence (localStorage, storageKey)\n// - double-click the divider to reset to the default width\n// - axis: 'x' (default, side-by-side panes) or 'y' (stacked panes, e.g. an artifact preview\n// under a narrow chat column, where splitting sideways would leave neither half readable)\n//\n// Usage:\n// const pane = useResizablePane({ initial: 340, min: 320, maxFraction: 0.6,\n// fromRight: true, storageKey: 'cg.chat.w' });\n// <PaneResizer pane={pane} />\n// <aside style={{ flex: `0 0 ${pane.width}px` }}>…</aside>\nimport React, { useCallback, useRef, useState } from 'react';\n\nexport function useResizablePane(opts = {}) {\n const {\n initial = 380,\n min = 240,\n max = null, // absolute px cap (null = none)\n maxFraction = null, // viewport-width fraction cap, e.g. 0.6 for 60vw (null = none)\n fromRight = false, // divider sits on the pane's LEFT/TOP edge (dragging toward it shrinks)\n storageKey = null, // persist the chosen size per user (localStorage)\n axis = 'x', // 'x' = width (col-resize), 'y' = height (row-resize)\n } = opts;\n const vertical = axis === 'y';\n // One clamp, one drag, one persistence path for both orientations: the axis only decides which\n // pointer coordinate and which viewport dimension are read.\n const coord = (e) => (vertical ? e.clientY : e.clientX);\n const viewportExtent = () => (typeof window === 'undefined' ? 0 : (vertical ? window.innerHeight : window.innerWidth));\n const cursor = vertical ? 'row-resize' : 'col-resize';\n\n const clamp = useCallback((x) => {\n let hi = max ?? Infinity;\n if (maxFraction && typeof window !== 'undefined') hi = Math.min(hi, Math.round(viewportExtent() * maxFraction));\n return Math.min(hi, Math.max(min, x));\n }, [min, max, maxFraction, vertical]); // eslint-disable-line react-hooks/exhaustive-deps\n\n const [width, setWidth] = useState(() => {\n if (storageKey && typeof window !== 'undefined') {\n try {\n const n = parseInt(window.localStorage.getItem(storageKey) || '', 10);\n if (Number.isFinite(n)) return clamp(n);\n } catch { /* private mode */ }\n }\n return initial;\n });\n const widthRef = useRef(width);\n widthRef.current = width;\n\n const persist = useCallback((w) => {\n if (!storageKey) return;\n try { window.localStorage.setItem(storageKey, String(w)); } catch { /* private mode */ }\n }, [storageKey]);\n\n const onMouseDown = useCallback((e) => {\n e.preventDefault();\n const sx = coord(e), base = widthRef.current, dir = fromRight ? -1 : 1;\n // While dragging, neutralize iframes/text-selection so an embedded preview can't swallow\n // mousemove/mouseup (which would strand the drag).\n document.body.classList.add('uic-resizing');\n const move = (ev) => setWidth(clamp(base + dir * (coord(ev) - sx)));\n const up = () => {\n window.removeEventListener('mousemove', move); window.removeEventListener('mouseup', up);\n document.body.style.cursor = ''; document.body.classList.remove('uic-resizing');\n persist(widthRef.current);\n };\n window.addEventListener('mousemove', move); window.addEventListener('mouseup', up);\n document.body.style.cursor = cursor;\n }, [clamp, fromRight, persist, vertical]); // eslint-disable-line react-hooks/exhaustive-deps\n\n // Touch / pen drags (pointer events). Mouse keeps the mousedown path above\n // untouched — this handler ignores mouse pointers so the two never double up.\n const onPointerDown = useCallback((e) => {\n if (e.pointerType === 'mouse') return;\n e.preventDefault();\n const sx = coord(e), base = widthRef.current, dir = fromRight ? -1 : 1;\n const el = e.currentTarget;\n document.body.classList.add('uic-resizing');\n try { el.setPointerCapture(e.pointerId); } catch { /* unsupported */ }\n const move = (ev) => setWidth(clamp(base + dir * (coord(ev) - sx)));\n const up = () => {\n el.removeEventListener('pointermove', move);\n el.removeEventListener('pointerup', up);\n el.removeEventListener('pointercancel', up);\n document.body.classList.remove('uic-resizing');\n persist(widthRef.current);\n };\n el.addEventListener('pointermove', move);\n el.addEventListener('pointerup', up);\n el.addEventListener('pointercancel', up);\n }, [clamp, fromRight, persist, vertical]); // eslint-disable-line react-hooks/exhaustive-deps\n\n // Keyboard resizing: move the pane edge by a signed px delta (clamped,\n // persisted). Positive delta = wider pane.\n const nudge = useCallback((delta) => {\n const w = clamp(widthRef.current + delta);\n setWidth(w);\n persist(w);\n }, [clamp, persist]);\n\n const reset = useCallback(() => {\n setWidth(initial);\n if (storageKey) { try { window.localStorage.removeItem(storageKey); } catch { /* private mode */ } }\n }, [initial, storageKey]);\n\n // Resolved clamp bounds for aria-valuemin/max on the divider.\n let maxResolved = max ?? null;\n if (maxFraction && typeof window !== 'undefined') {\n const frac = Math.round(viewportExtent() * maxFraction);\n maxResolved = maxResolved == null ? frac : Math.min(maxResolved, frac);\n }\n\n return { width, onMouseDown, onPointerDown, nudge, reset, min, max: maxResolved, fromRight, axis };\n}\n\n/** The grabbable divider (comfortable 7px hit area, col-resize cursor, dblclick = reset).\n * Keyboard: focus it (Tab) and use ArrowLeft/ArrowRight to move the divider\n * in 24px steps (Shift for 96px); touch drags work through pointer events.\n * Mouse drag and double-click reset behave exactly as before. */\nexport function PaneResizer(props) {\n const { pane, className, title = 'Drag to resize (double-click to reset)' } = props;\n const vertical = pane.axis === 'y';\n const onKeyDown = (e) => {\n const keys = vertical ? ['ArrowUp', 'ArrowDown'] : ['ArrowLeft', 'ArrowRight'];\n if (!keys.includes(e.key)) return;\n if (!pane.nudge) return;\n e.preventDefault();\n const step = e.shiftKey ? 96 : 24;\n // Arrows move the SEPARATOR: for a trailing pane (divider on its leading\n // edge) the forward key shrinks the pane; for a leading pane it grows it.\n const forward = e.key === 'ArrowRight' || e.key === 'ArrowDown';\n const dir = (forward ? 1 : -1) * (pane.fromRight ? -1 : 1);\n pane.nudge(dir * step);\n };\n return (\n <div\n className={className ?? (vertical ? 'uic-hresize' : 'uic-vresize')}\n role=\"separator\"\n // The separator's own orientation: a stacked (axis 'y') split is divided by a HORIZONTAL bar.\n aria-orientation={vertical ? 'horizontal' : 'vertical'}\n aria-label={title}\n aria-valuenow={Math.round(pane.width)}\n aria-valuemin={pane.min != null ? Math.round(pane.min) : undefined}\n aria-valuemax={pane.max != null ? Math.round(pane.max) : undefined}\n tabIndex={0}\n title={title}\n onMouseDown={pane.onMouseDown}\n onPointerDown={pane.onPointerDown}\n onKeyDown={onKeyDown}\n onDoubleClick={pane.reset}\n />\n );\n}\n","// TaskList — the master list beside an agent conversation: one row per run/session, with\n// live status, text filter, status filter, cursor pagination on scroll, and optional delete.\n//\n// Transport-agnostic, like everything else here. The consumer supplies `fetchPage`, which\n// returns `{ items, cursor }` for a given cursor ('' = first page). ReifyUI never decides how\n// you authenticate or where your API lives; it only decides how the result looks and behaves.\n//\n// Pagination model: the FIRST page is refetched on `refreshNonce` so live runs stay current,\n// while older pages accumulate in a tail. Merging de-duplicates by id, so a run that moves\n// between pages while you scroll cannot appear twice.\n//\n// Slots:\n// header node rendered above the filter row (e.g. a harness selector)\n// onNew when provided, renders the \"New task\" action\n// onDelete when provided, each row gets a delete affordance (confirm is the consumer's job\n// if it wants one — this only calls back)\n// renderMeta (item) => node, replaces the default right-hand status/time cell\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\n\nconst STATUS_GROUPS = {\n all: () => true,\n working: (s) => ['running', 'starting', 'queued', 'in_progress'].includes(s),\n done: (s) => ['done', 'completed'].includes(s),\n failed: (s) => ['failed', 'cancelled', 'incomplete', 'error'].includes(s),\n};\n\n/** Coarse bucket for the status dot — keeps colour logic in one place. */\nexport function taskStatusGroup(status) {\n const s = String(status || '').toLowerCase();\n for (const k of ['working', 'done', 'failed']) if (STATUS_GROUPS[k](s)) return k;\n return 'idle';\n}\n\nfunction relTime(ts) {\n const n = Number(ts) || 0;\n if (!n) return '';\n // Accept seconds or milliseconds — callers differ and a 1000x error is a silent wrong label.\n const ms = n > 1e12 ? n : n * 1000;\n const d = Math.max(0, Date.now() - ms) / 1000;\n if (d < 60) return 'just now';\n if (d < 3600) return `${Math.floor(d / 60)}m ago`;\n if (d < 86400) return `${Math.floor(d / 3600)}h ago`;\n return `${Math.floor(d / 86400)}d ago`;\n}\n\nexport function TaskList({\n fetchPage,\n selected,\n onSelect,\n onNew,\n onDelete,\n header,\n renderMeta,\n refreshNonce = 0,\n emptyLabel = 'No tasks yet',\n newLabel = 'New task',\n idKey = 'id',\n titleKey = 'title',\n statusKey = 'status',\n timeKey = 'updated_at',\n}) {\n const [head, setHead] = useState(null); // null = loading, [] = loaded-empty\n const [tail, setTail] = useState([]);\n const [cursor, setCursor] = useState('');\n const [loadingMore, setLoadingMore] = useState(false);\n const [q, setQ] = useState('');\n const [statusFilter, setStatusFilter] = useState('all');\n const alive = useRef(true);\n\n useEffect(() => () => { alive.current = false; }, []);\n\n // First page — refetched whenever the consumer bumps refreshNonce (poll, SSE, post-send).\n useEffect(() => {\n let ok = true;\n Promise.resolve(fetchPage(''))\n .then((r) => {\n if (!ok) return;\n setHead(Array.isArray(r?.items) ? r.items : []);\n setCursor(r?.cursor || '');\n })\n .catch(() => { if (ok) setHead((p) => p ?? []); }); // keep what we had; don't blank the list\n return () => { ok = false; };\n }, [fetchPage, refreshNonce]);\n\n const loadMore = useCallback(() => {\n if (!cursor || loadingMore) return;\n setLoadingMore(true);\n Promise.resolve(fetchPage(cursor))\n .then((r) => {\n if (!alive.current) return;\n if (Array.isArray(r?.items)) setTail((t) => [...t, ...r.items]);\n setCursor(r?.cursor || '');\n })\n .catch(() => { /* keep the cursor so the next scroll retries */ })\n .finally(() => { if (alive.current) setLoadingMore(false); });\n }, [cursor, loadingMore, fetchPage]);\n\n const items = useMemo(() => {\n const h = head || [];\n const seen = new Set(h.map((x) => x?.[idKey]));\n return [...h, ...tail.filter((t) => !seen.has(t?.[idKey]))];\n }, [head, tail, idKey]);\n\n const shown = useMemo(() => {\n const needle = q.trim().toLowerCase();\n const pass = STATUS_GROUPS[statusFilter] || STATUS_GROUPS.all;\n return items.filter((it) => {\n if (!pass(String(it?.[statusKey] || '').toLowerCase())) return false;\n if (!needle) return true;\n return String(it?.[titleKey] || '').toLowerCase().includes(needle);\n });\n }, [items, q, statusFilter, statusKey, titleKey]);\n\n const onScroll = (e) => {\n const el = e.currentTarget;\n if (el.scrollTop + el.clientHeight > el.scrollHeight - 140) loadMore();\n };\n\n return (\n <div className=\"rui-tasks\">\n {header ? <div className=\"rui-tasks-header\">{header}</div> : null}\n {onNew ? (\n <button type=\"button\" className=\"rui-tasks-new\" onClick={onNew}>+ {newLabel}</button>\n ) : null}\n\n <div className=\"rui-tasks-filters\">\n <input\n className=\"rui-tasks-search\"\n value={q}\n placeholder=\"Filter tasks…\"\n onChange={(e) => setQ(e.target.value)}\n aria-label=\"Filter tasks\"\n />\n <select\n className=\"rui-tasks-status\"\n value={statusFilter}\n onChange={(e) => setStatusFilter(e.target.value)}\n aria-label=\"Filter by status\"\n >\n <option value=\"all\">All</option>\n <option value=\"working\">Working</option>\n <option value=\"done\">Done</option>\n <option value=\"failed\">Failed</option>\n </select>\n </div>\n\n <div className=\"rui-tasks-list\" onScroll={onScroll}>\n {head === null ? (\n <div className=\"rui-tasks-empty\">Loading…</div>\n ) : shown.length === 0 ? (\n <div className=\"rui-tasks-empty\">{items.length ? 'No matching tasks' : emptyLabel}</div>\n ) : (\n shown.map((it) => {\n const id = it?.[idKey];\n const group = taskStatusGroup(it?.[statusKey]);\n return (\n <div\n key={id}\n className={`rui-task${id === selected ? ' is-selected' : ''}`}\n onClick={() => onSelect?.(id)}\n role=\"button\"\n tabIndex={0}\n onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') onSelect?.(id); }}\n >\n <div className=\"rui-task-main\">\n <div className=\"rui-task-title\">{it?.[titleKey] || 'Untitled task'}</div>\n <div className=\"rui-task-meta\">\n {renderMeta ? renderMeta(it) : (\n <>\n <span className={`rui-task-dot is-${group}`} />\n <span className=\"rui-task-status\">{it?.[statusKey] || ''}</span>\n {it?.[timeKey] ? <span className=\"rui-task-time\">{relTime(it[timeKey])}</span> : null}\n </>\n )}\n </div>\n </div>\n {onDelete ? (\n <button\n type=\"button\"\n className=\"rui-task-del\"\n aria-label=\"Delete task\"\n onClick={(e) => { e.stopPropagation(); onDelete(it); }}\n >×</button>\n ) : null}\n </div>\n );\n })\n )}\n {loadingMore ? <div className=\"rui-tasks-empty\">Loading more…</div> : null}\n </div>\n </div>\n );\n}\n","// Dialog — in-app replacements for window.alert / window.confirm / window.prompt.\n//\n// Agentic surfaces ask the user things constantly: confirm a destructive tool call, name a\n// workspace, acknowledge a failure. Native browser popups block the event loop, cannot be\n// styled, and look like a security warning rather than part of your product. This gives the\n// same call-site ergonomics — an awaited call that returns a value — without any of that.\n//\n// Usage:\n// 1. Mount <DialogHost> once, wrapping your app.\n// 2. Anywhere underneath:\n//\n// const { confirm, prompt, alert } = useDialog();\n//\n// if (await confirm({ title: 'Delete task', message: 'This cannot be undone.',\n// destructive: true, confirmLabel: 'Delete' })) { … }\n//\n// const name = await prompt({ title: 'New workspace', label: 'Name',\n// validate: (v) => v.length < 40 ? null : 'Too long' });\n// // string, or null when cancelled\n//\n// await alert({ title: 'Run failed', message: err, variant: 'error' });\n//\n// Dialogs stack rather than replace: a second caller layers on top instead of trampling the\n// first, because two independent code paths asking at once is normal in a streaming UI.\n//\n// Styling is one stylesheet away — import 'reifyui/styles/dialog.css' — and every colour is a\n// themeable variable, so it inherits the host app's palette.\nimport {\n createContext, useCallback, useContext, useEffect,\n useId, useMemo, useRef, useState,\n} from 'react';\nimport { createPortal } from 'react-dom';\nimport { useOverlayEscape } from './overlay.js';\n\nconst DialogCtx = createContext(null);\n\nconst LABELS = {\n en: { confirm: 'Confirm', cancel: 'Cancel', ok: 'OK', create: 'Create', required: 'Please enter a value' },\n zh: { confirm: '确认', cancel: '取消', ok: '好的', create: '创建', required: '请输入内容' },\n};\n\nlet _idSeq = 0;\n\n/**\n * Mount once near the root. `locale` picks a built-in label set ('en' | 'zh'); `labels`\n * overrides individual strings for any other language.\n */\nexport function DialogHost({ children, locale = 'en', labels }) {\n const [stack, setStack] = useState([]);\n const t = useMemo(\n () => ({ ...(LABELS[locale] || LABELS.en), ...(labels || {}) }),\n [locale, labels],\n );\n\n const open = useCallback((spec) => new Promise((resolve) => {\n setStack((s) => [...s, { id: `dlg_${++_idSeq}`, spec, resolve }]);\n }), []);\n\n const close = useCallback((id, value) => {\n setStack((s) => {\n const target = s.find((d) => d.id === id);\n if (target) target.resolve(value);\n return s.filter((d) => d.id !== id);\n });\n }, []);\n\n const ctx = useMemo(() => ({\n confirm: (opts) => open({ kind: 'confirm', ...opts }),\n prompt: (opts) => open({ kind: 'prompt', ...opts }),\n alert: (opts) => open({ kind: 'alert', ...opts }),\n create: (opts) => open({ kind: 'create', ...opts }),\n labels: t,\n }), [open, t]);\n\n return (\n <DialogCtx.Provider value={ctx}>\n {children}\n {stack.length > 0 && typeof document !== 'undefined' && createPortal(\n <div className=\"rui-dlg-root\" role=\"presentation\">\n {stack.map((d, i) => (\n <DialogShell key={d.id} dialog={d} isTop={i === stack.length - 1} onClose={close} t={t} />\n ))}\n </div>,\n document.body,\n )}\n </DialogCtx.Provider>\n );\n}\n\nexport function useDialog() {\n const ctx = useContext(DialogCtx);\n // Fail loudly rather than silently no-op: a confirm() that always resolves false would skip\n // the user's decision entirely, which is worse than a crash in development.\n if (!ctx) throw new Error('useDialog() called outside <DialogHost>');\n return ctx;\n}\n\n// A cancelled prompt/create yields null (no value); a cancelled confirm/alert yields false.\nconst cancelValue = (kind) => ((kind === 'prompt' || kind === 'create') ? null : false);\n\nfunction DialogShell({ dialog, isTop, onClose, t }) {\n const { id, spec } = dialog;\n const ref = useRef(null);\n const titleId = useId();\n\n // Escape goes through the package's shared overlay stack rather than a listener of our own, so\n // a Modal or Popover opened ON TOP of this dialog answers the key and this one does not.\n const escape = useCallback(() => onClose(id, cancelValue(spec.kind)), [id, onClose, spec.kind]);\n useOverlayEscape(isTop, escape);\n\n // Focus the field if there is one, else the primary action — so Enter does the obvious thing.\n useEffect(() => {\n if (!isTop || !ref.current) return;\n const el = ref.current.querySelector('input, textarea')\n || ref.current.querySelector('.rui-dlg-primary')\n || ref.current.querySelector('button');\n el?.focus();\n }, [isTop]);\n\n const onBackdrop = (e) => {\n if (e.target === e.currentTarget && isTop) onClose(id, cancelValue(spec.kind));\n };\n\n const done = (v) => onClose(id, v);\n\n return (\n <div className=\"rui-dlg-backdrop\" onClick={onBackdrop}>\n <div\n ref={ref}\n role=\"dialog\"\n aria-modal=\"true\"\n aria-labelledby={spec.title ? titleId : undefined}\n className={`rui-dlg-card${spec.kind === 'create' ? ' is-wide' : ''}`}\n >\n {spec.kind === 'alert' && <AlertBody spec={spec} onClose={done} t={t} titleId={titleId} />}\n {spec.kind === 'confirm' && <ConfirmBody spec={spec} onClose={done} t={t} titleId={titleId} />}\n {spec.kind === 'prompt' && <PromptBody spec={spec} onClose={done} t={t} titleId={titleId} />}\n {spec.kind === 'create' && <CreateBody spec={spec} onClose={done} t={t} titleId={titleId} />}\n </div>\n </div>\n );\n}\n\nfunction Header({ title, variant, titleId }) {\n if (!title) return null;\n return (\n <div className={`rui-dlg-h${variant ? ` is-${variant}` : ''}`}>\n <div className=\"rui-dlg-title\" id={titleId}>{title}</div>\n </div>\n );\n}\n\nconst Footer = ({ children }) => <div className=\"rui-dlg-f\">{children}</div>;\n\nfunction AlertBody({ spec, onClose, t, titleId }) {\n return (\n <>\n <Header title={spec.title} variant={spec.variant} titleId={titleId} />\n <div className=\"rui-dlg-b\">\n {spec.message ? <div className=\"rui-dlg-msg\">{spec.message}</div> : null}\n </div>\n <Footer>\n <button type=\"button\" className=\"rui-dlg-btn rui-dlg-primary\" onClick={() => onClose(true)}>\n {spec.confirmLabel || t.ok}\n </button>\n </Footer>\n </>\n );\n}\n\nfunction ConfirmBody({ spec, onClose, t, titleId }) {\n const destructive = !!spec.destructive;\n return (\n <>\n <Header title={spec.title} variant={destructive ? 'destructive' : spec.variant} titleId={titleId} />\n <div className=\"rui-dlg-b\">\n {spec.message ? <div className=\"rui-dlg-msg\">{spec.message}</div> : null}\n </div>\n <Footer>\n <button type=\"button\" className=\"rui-dlg-btn rui-dlg-secondary\" onClick={() => onClose(false)}>\n {spec.cancelLabel || t.cancel}\n </button>\n <button\n type=\"button\"\n className={`rui-dlg-btn rui-dlg-primary${destructive ? ' is-destructive' : ''}`}\n onClick={() => onClose(true)}\n >\n {spec.confirmLabel || t.confirm}\n </button>\n </Footer>\n </>\n );\n}\n\nfunction PromptBody({ spec, onClose, t, titleId }) {\n const [value, setValue] = useState(spec.defaultValue ?? '');\n const [err, setErr] = useState(null);\n const inputId = useId();\n const Field = spec.multiline ? 'textarea' : 'input';\n\n const submit = () => {\n const invalid = spec.validate?.(value);\n if (invalid) { setErr(String(invalid)); return; }\n if (spec.required !== false && !String(value).trim()) { setErr(t.required); return; }\n onClose(String(value));\n };\n\n return (\n <>\n <Header title={spec.title} variant={spec.variant} titleId={titleId} />\n <div className=\"rui-dlg-b\">\n {spec.message ? <div className=\"rui-dlg-msg\">{spec.message}</div> : null}\n {spec.label ? <label className=\"rui-dlg-label\" htmlFor={inputId}>{spec.label}</label> : null}\n <Field\n id={inputId}\n className={`rui-dlg-input${err ? ' is-err' : ''}`}\n type={spec.multiline ? undefined : (spec.inputType || 'text')}\n rows={spec.multiline ? (spec.rows || 4) : undefined}\n value={value}\n placeholder={spec.placeholder || ''}\n onChange={(e) => { setValue(e.target.value); if (err) setErr(null); }}\n onKeyDown={(e) => {\n if (e.key === 'Enter' && !e.shiftKey && !spec.multiline) { e.preventDefault(); submit(); }\n }}\n autoComplete=\"off\"\n spellCheck=\"false\"\n />\n {err ? <div className=\"rui-dlg-err\">{err}</div> : null}\n {!err && spec.help ? <div className=\"rui-dlg-help\">{spec.help}</div> : null}\n </div>\n <Footer>\n <button type=\"button\" className=\"rui-dlg-btn rui-dlg-secondary\" onClick={() => onClose(null)}>\n {spec.cancelLabel || t.cancel}\n </button>\n <button type=\"button\" className=\"rui-dlg-btn rui-dlg-primary\" onClick={submit}>\n {spec.confirmLabel || t.confirm}\n </button>\n </Footer>\n </>\n );\n}\n\n// Pick-a-type-then-name, for \"New …\" flows where the thing being created has variants. The\n// caller supplies `types: [{ kind, label, color, icon, choices? }]`, so this stays icon-library\n// agnostic. A type may offer a starting point (`choices: { label, load, defaultId }`, where\n// load() resolves to [{ id, name, description? }], typically templates); the list is fetched\n// when the type is first selected and the chosen id rides along as `choice`.\n// Resolves to { kind, name, choice? } or null.\nfunction CreateBody({ spec, onClose, t, titleId }) {\n const types = spec.types || [];\n const [kind, setKind] = useState(spec.defaultKind || types[0]?.kind || '');\n const [value, setValue] = useState(spec.defaultValue ?? '');\n const [err, setErr] = useState(null);\n const [lists, setLists] = useState({});\n const inputId = useId();\n const sel = types.find((x) => x.kind === kind) || types[0] || {};\n\n useEffect(() => {\n const ch = sel.choices;\n if (!ch || lists[kind]) return undefined;\n let dead = false;\n setLists((m) => ({ ...m, [kind]: { status: 'loading', items: [], chosen: ch.defaultId ?? null } }));\n Promise.resolve().then(() => ch.load()).then((items) => {\n if (dead) return;\n const arr = Array.isArray(items) ? items : [];\n const chosen = arr.some((it) => it.id === ch.defaultId) ? ch.defaultId : (arr[0]?.id ?? ch.defaultId ?? null);\n setLists((m) => ({ ...m, [kind]: { status: 'ready', items: arr, chosen } }));\n }).catch(() => {\n if (dead) return;\n setLists((m) => ({ ...m, [kind]: { status: 'failed', items: [], chosen: ch.defaultId ?? null } }));\n });\n return () => { dead = true; };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [kind]);\n const pick = (id) => setLists((m) => ({ ...m, [kind]: { ...m[kind], chosen: id } }));\n\n const submit = () => {\n if (spec.required !== false && !String(value).trim()) { setErr(t.required); return; }\n const entry = sel.choices ? lists[kind] : null;\n onClose({ kind, name: String(value).trim(), ...(entry ? { choice: entry.chosen } : {}) });\n };\n\n return (\n <>\n <Header title={spec.title} titleId={titleId} />\n <div className=\"rui-dlg-b\">\n {types.length > 0 ? (\n <div className=\"rui-dlg-typegrid\">\n {types.map((ty) => (\n <button\n key={ty.kind}\n type=\"button\"\n className={`rui-dlg-type${ty.kind === kind ? ' is-on' : ''}`}\n onClick={() => setKind(ty.kind)}\n >\n {ty.icon ? (\n <span className=\"rui-dlg-type-ic\" style={ty.color ? { color: ty.color, background: `${ty.color}1f` } : undefined}>\n {ty.icon}\n </span>\n ) : null}\n <span className=\"rui-dlg-type-lbl\">{ty.label}</span>\n </button>\n ))}\n </div>\n ) : null}\n <label className=\"rui-dlg-label\" htmlFor={inputId}>\n {spec.label || `${sel.label || 'Item'} name`}\n </label>\n <input\n id={inputId}\n className={`rui-dlg-input${err ? ' is-err' : ''}`}\n value={value}\n placeholder={spec.placeholder || 'Untitled'}\n onChange={(e) => { setValue(e.target.value); if (err) setErr(null); }}\n onKeyDown={(e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); submit(); } }}\n autoComplete=\"off\"\n spellCheck=\"false\"\n />\n {err ? <div className=\"rui-dlg-err\">{err}</div> : null}\n {sel.choices ? <ChoiceList label={sel.choices.label} entry={lists[kind]} onPick={pick} /> : null}\n </div>\n <Footer>\n <button type=\"button\" className=\"rui-dlg-btn rui-dlg-secondary\" onClick={() => onClose(null)}>\n {spec.cancelLabel || t.cancel}\n </button>\n <button type=\"button\" className=\"rui-dlg-btn rui-dlg-primary\" onClick={submit}>\n {spec.confirmLabel || t.create}\n </button>\n </Footer>\n </>\n );\n}\n\n// The starting-point list under the name: one row per choice, the chosen one marked; scrolls\n// past a handful so the dialog keeps its height on a phone.\nfunction ChoiceList({ label, entry, onPick }) {\n const labelId = useId();\n const status = entry?.status || 'loading';\n return (\n <div className=\"rui-dlg-choices\" role=\"radiogroup\" aria-labelledby={labelId}>\n <div className=\"rui-dlg-label\" id={labelId}>{label}</div>\n {status === 'loading' ? <div className=\"rui-dlg-help\">Loading</div> : null}\n {status === 'failed' ? <div className=\"rui-dlg-help\">The list could not be loaded. The default will be used.</div> : null}\n {status === 'ready' && entry.items.length > 0 ? (\n <div className=\"rui-dlg-choice-list\">\n {entry.items.map((it) => {\n const on = it.id === entry.chosen;\n return (\n <button key={it.id} type=\"button\" role=\"radio\" aria-checked={on}\n className={`rui-dlg-choice${on ? ' is-on' : ''}`} onClick={() => onPick(it.id)}>\n <span className=\"rui-dlg-choice-dot\" aria-hidden=\"true\" />\n <span className=\"rui-dlg-choice-text\">\n <span className=\"rui-dlg-choice-name\">{it.name}</span>\n {it.description ? <span className=\"rui-dlg-choice-desc\">{it.description}</span> : null}\n </span>\n </button>\n );\n })}\n </div>\n ) : null}\n </div>\n );\n}\n","// One Escape key, one stack.\n//\n// The package now has three things that float above the page — the dialog host, Modal and\n// Popover — and each of them wanting its own document keydown listener is how Escape ends up\n// closing two of them at once. They register here instead: the LAST one opened owns Escape, and\n// nothing below it hears the key.\n//\n// Deliberately not a React context: a Popover inside a Modal inside a dialog is a legitimate\n// arrangement, and the ordering that matters is the order they OPENED in, which is exactly what\n// an array push/splice records. A context would order them by tree position instead.\n//\n// Internal to the package (not exported from the root): a consumer that wants this behaviour\n// gets it by using the overlay components, not by wiring the stack itself.\nimport { useEffect } from 'react';\n\nconst stack = [];\nlet listening = false;\n\nfunction onKey(e) {\n if (e.key !== 'Escape') return;\n const top = stack[stack.length - 1];\n if (!top) return;\n e.preventDefault();\n top.onEscape?.();\n}\n\nfunction listen() {\n if (listening || typeof document === 'undefined') return;\n document.addEventListener('keydown', onKey);\n listening = true;\n}\n\nfunction unlisten() {\n if (!listening || stack.length) return;\n document.removeEventListener('keydown', onKey);\n listening = false;\n}\n\n/** Push while mounted-and-open. Returns the dispose. `onEscape` is read live, so a handler that\n * closes over changing state does not have to re-register. */\nexport function pushOverlay(entry) {\n stack.push(entry);\n listen();\n return () => {\n const i = stack.indexOf(entry);\n if (i >= 0) stack.splice(i, 1);\n unlisten();\n };\n}\n\n/**\n * Escape closes THIS overlay only while it is the top-most one.\n * `active` is false for an overlay that is closed, or that is not the top of its own local stack\n * (the dialog host layers several at once and only the last should answer).\n */\nexport function useOverlayEscape(active, onEscape) {\n useEffect(() => {\n if (!active) return undefined;\n // The entry object is stable for the life of this registration; onEscape is captured with it,\n // and the effect re-runs whenever the caller's handler identity changes.\n return pushOverlay({ onEscape });\n }, [active, onEscape]);\n}\n","// Shared product auth client — a thin client over the AgentStudio engine's\n// /v1/auth endpoints, extracted from ContextualGraph. Product apps configure\n// it ONCE at boot:\n//\n// configureAuth({ product: 'flowness', engine: ENGINE_URL, loginHash: '#/login' })\n//\n// The JWT is the source of truth; the decoded principal (member / orgs /\n// active org) is stored alongside it in localStorage under\n// `<product>.session`. Stateless on the server side: every request just\n// carries the Bearer token. All functions below read the live config, so\n// call order (configure first) is the only contract.\n/* eslint-env browser */\n\nconst _cfg = {\n // Same-origin. A product that forgets to configure gets the working default rather than the\n // engine's Azure FQDN, which no browser may call — its ingress admits only the VM that fronts\n // these apps, so a direct call 403s and reads as \"Failed to fetch\".\n engine: '/engine',\n product: '',\n loginHash: '#/login',\n};\n\nexport function configureAuth(cfg) {\n Object.assign(_cfg, cfg);\n if (!_cfg.product) throw new Error('configureAuth: product is required');\n}\n\nexport function authConfig() { return { ..._cfg }; }\n\nfunction sessionKey() { return `${_cfg.product}.session`; }\n\n/** Fired on every session write so chrome holding a snapshot can re-read. */\nexport const SESSION_EVENT = 'ui-core:session';\n\nexport function getSession() {\n try {\n const raw = window.localStorage.getItem(sessionKey());\n return raw ? JSON.parse(raw) : null;\n } catch {\n return null;\n }\n}\n\nfunction setSession(s) {\n window.localStorage.setItem(sessionKey(), JSON.stringify(s));\n window.dispatchEvent(new CustomEvent(SESSION_EVENT));\n}\n\nexport function clearSession() {\n window.localStorage.removeItem(sessionKey());\n window.dispatchEvent(new CustomEvent(SESSION_EVENT));\n}\n\nexport function getToken() {\n return getSession()?.token ?? null;\n}\n\nexport function isAuthed() {\n const s = getSession();\n return !!(s?.token && s?.orgId);\n}\n\nasync function readError(res) {\n try {\n const body = await res.json();\n return typeof body?.detail === 'string' ? body.detail : `request failed (${res.status})`;\n } catch {\n return `request failed (${res.status})`;\n }\n}\n\nfunction toSession(body) {\n return {\n token: body.token,\n member: body.member,\n orgs: body.orgs ?? [],\n orgId: body.org_id ?? null,\n };\n}\n\nasync function authPost(path, body, token = null) {\n const headers = { 'content-type': 'application/json' };\n if (token) headers.authorization = `Bearer ${token}`;\n const res = await fetch(`${_cfg.engine}${path}`, {\n method: 'POST',\n headers,\n body: body ? JSON.stringify(body) : undefined,\n });\n if (!res.ok) throw new Error(await readError(res));\n return res.json();\n}\n\nexport async function login(email, password) {\n const s = toSession(await authPost('/v1/auth/login', { email, password, product: _cfg.product }));\n setSession(s);\n return s;\n}\n\nexport async function register(email, password, name = '') {\n const s = toSession(await authPost('/v1/auth/register', { email, password, name, product: _cfg.product }));\n setSession(s);\n return s;\n}\n\nexport async function googleSignIn(credential) {\n const s = toSession(await authPost('/v1/auth/google', { credential, product: _cfg.product }));\n setSession(s);\n return s;\n}\n\n// Exchange a Microsoft (Entra) id token for a session, as googleSignIn does\n// with Google's. The engine answers a refusal with a sentence to show as is:\n// a personal account, a disabled member, or sign-in not configured.\nexport async function microsoftSignIn(credential) {\n const s = toSession(await authPost('/v1/auth/microsoft', { credential, product: _cfg.product }));\n setSession(s);\n return s;\n}\n\nexport async function requestPasswordReset(email) {\n await fetch(`${_cfg.engine}/v1/auth/request-password-reset`, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ email, product: _cfg.product }),\n });\n}\n\n/** Re-mint an org-scoped token for the chosen org. */\nexport async function switchOrg(orgId) {\n const current = getSession();\n if (!current) throw new Error('not authenticated');\n const body = await authPost('/v1/auth/switch-org', { org_id: orgId }, current.token);\n const next = { ...current, token: body.token, orgId: body.org_id };\n setSession(next);\n return next;\n}\n\n/** Slide the session: swap the still valid token for a fresh full TTL one. */\nexport async function refreshToken() {\n const cur = getSession();\n if (!cur?.token) return false;\n try {\n const res = await fetch(`${_cfg.engine}/v1/auth/refresh`, {\n method: 'POST',\n headers: { authorization: `Bearer ${cur.token}` },\n });\n if (res.status === 401) { handleAuthExpired(); return false; }\n if (!res.ok) return false;\n const body = await res.json();\n const now = getSession();\n if (body?.token && now) setSession({ ...now, token: body.token });\n return true;\n } catch {\n return false; // offline, keep the session and retry later\n }\n}\n\nlet redirecting = false;\n/** The token is dead: clear the session and land on the login route. */\nexport function handleAuthExpired() {\n if (redirecting) return;\n redirecting = true;\n clearSession();\n window.location.hash = _cfg.loginHash;\n setTimeout(() => { redirecting = false; }, 500);\n}\n\nexport function logout() {\n clearSession();\n window.location.hash = _cfg.loginHash;\n}\n\n/** fetch() with the Bearer token; a 401 fails closed into the login route. */\nexport async function authFetch(url, init = {}) {\n const headers = new Headers(init.headers);\n const token = getToken();\n if (token) headers.set('authorization', `Bearer ${token}`);\n const res = await fetch(url, { ...init, headers });\n if (res.status === 401) handleAuthExpired();\n return res;\n}\n\n/** GET the org's credit balance from the engine billing plane. */\nexport async function fetchBalance() {\n const res = await authFetch(`${_cfg.engine}/v1/billing/balance`);\n if (!res.ok) throw new Error(await readError(res));\n return res.json();\n}\n","// The complete sign-in unit (modeled on the HarnessRouter login screen),\n// extracted from ContextualGraph: brand mark on top, email + password with\n// the sign in button, Google SSO below, then the register / forgot password\n// links. Product-agnostic: the caller passes its brand node (`brand`) and\n// product display name (`productName`); auth calls ride the shared client\n// (configureAuth must have run at boot).\nimport { useState } from 'react';\nimport {\n login, register, googleSignIn, microsoftSignIn, requestPasswordReset, switchOrg,\n} from './client.js';\nimport { GoogleButton, GOOGLE_ENABLED } from './GoogleButton.jsx';\nimport { MicrosoftButton, MICROSOFT_ENABLED } from './MicrosoftButton.jsx';\n\nexport function AuthForm({ onDone, subtitle, brand = null, productName = '' }) {\n const [mode, setMode] = useState('signin'); // signin | register | forgot\n const [email, setEmail] = useState('');\n const [password, setPassword] = useState('');\n const [name, setName] = useState('');\n const [err, setErr] = useState('');\n const [busy, setBusy] = useState(false);\n const [choices, setChoices] = useState(null); // orgs, when the account has more than one\n const [resetSent, setResetSent] = useState(false);\n\n async function enter(orgId) {\n const session = await switchOrg(orgId);\n onDone(session);\n }\n\n // Route a freshly authenticated session: straight in, or via the org picker.\n async function afterAuth(session) {\n if (session.orgId) onDone(session);\n else if (session.orgs.length === 1) await enter(session.orgs[0].id);\n else if (session.orgs.length > 1) setChoices(session.orgs);\n else setErr('This account is not a member of any organization yet.');\n }\n\n async function submit(e) {\n e.preventDefault();\n setErr('');\n setBusy(true);\n try {\n if (mode === 'forgot') {\n await requestPasswordReset(email.trim());\n setResetSent(true);\n } else {\n const s = mode === 'register'\n ? await register(email.trim(), password, name.trim())\n : await login(email.trim(), password);\n await afterAuth(s);\n }\n } catch (ex) {\n setErr(ex instanceof Error ? ex.message : `${mode === 'register' ? 'Sign up' : 'Sign in'} failed.`);\n } finally {\n setBusy(false);\n }\n }\n\n async function onMicrosoft(credential) {\n setErr('');\n setBusy(true);\n try {\n await afterAuth(await microsoftSignIn(credential));\n } catch (ex) {\n setErr(ex instanceof Error ? ex.message : 'Microsoft sign in failed.');\n } finally {\n setBusy(false);\n }\n }\n\n async function onGoogle(credential) {\n setErr('');\n setBusy(true);\n try {\n await afterAuth(await googleSignIn(credential));\n } catch (ex) {\n setErr(ex instanceof Error ? ex.message : 'Google sign in failed.');\n } finally {\n setBusy(false);\n }\n }\n\n if (choices) {\n return (\n <div>\n <div className=\"logo\">{brand}</div>\n <h1>Choose workspace</h1>\n <div className=\"org-list\">\n {choices.map((o) => (\n <button\n key={o.id}\n type=\"button\"\n className=\"btn\"\n style={{ width: '100%', justifyContent: 'flex-start', height: 38 }}\n disabled={busy}\n onClick={() => {\n setBusy(true);\n enter(o.id).catch((ex) => {\n setErr(ex instanceof Error ? ex.message : 'Could not select the workspace.');\n setBusy(false);\n });\n }}\n >\n {o.name || o.id}\n </button>\n ))}\n </div>\n {err && <div className=\"auth-err\">{err}</div>}\n </div>\n );\n }\n\n return (\n <form onSubmit={submit}>\n <div className=\"logo\">{brand}</div>\n <h1>{mode === 'register' ? 'Create your account' : mode === 'forgot' ? 'Reset password' : 'Sign in'}</h1>\n <p className=\"sub\">\n {mode === 'register' ? 'Get started in seconds.'\n : mode === 'forgot' ? 'We will email you a reset link.'\n : (subtitle || 'Welcome back.')}\n </p>\n\n {mode === 'forgot' ? (\n resetSent ? (\n <>\n <div className=\"auth-note\">\n If an account exists for <b>{email.trim()}</b>, a password reset link is on its way. It is valid for 1 hour.\n </div>\n <button\n type=\"button\"\n className=\"btn primary lg\"\n style={{ width: '100%', marginTop: 14 }}\n onClick={() => { setErr(''); setResetSent(false); setMode('signin'); }}\n >\n Back to sign in\n </button>\n </>\n ) : (\n <>\n <div className=\"field\">\n <label>Email</label>\n <input className=\"input\" type=\"email\" value={email} onChange={(e) => setEmail(e.target.value)} autoFocus required autoComplete=\"email\" />\n </div>\n {err && <div className=\"auth-err\">{err}</div>}\n <button type=\"submit\" className=\"btn primary lg\" style={{ width: '100%', marginTop: 8 }} disabled={busy}>\n {busy ? 'Please wait...' : 'Send reset link'}\n </button>\n <p className=\"auth-switch\">\n <button type=\"button\" onClick={() => { setErr(''); setMode('signin'); }}>Back to sign in</button>\n </p>\n </>\n )\n ) : (\n <>\n {mode === 'register' && (\n <div className=\"field\">\n <label>Name</label>\n <input className=\"input\" value={name} onChange={(e) => setName(e.target.value)} autoComplete=\"name\" placeholder=\"Jane Doe\" />\n </div>\n )}\n <div className=\"field\">\n <label>Email</label>\n <input className=\"input\" type=\"email\" value={email} onChange={(e) => setEmail(e.target.value)} autoFocus required autoComplete=\"email\" />\n </div>\n <div className=\"field\">\n <div className=\"field-row\">\n <label>Password</label>\n {mode === 'signin' && (\n <button type=\"button\" className=\"link-sm\" onClick={() => { setErr(''); setResetSent(false); setMode('forgot'); }}>\n Forgot password?\n </button>\n )}\n </div>\n <input\n className=\"input\"\n type=\"password\"\n value={password}\n onChange={(e) => setPassword(e.target.value)}\n required\n autoComplete={mode === 'register' ? 'new-password' : 'current-password'}\n placeholder={mode === 'register' ? 'At least 8 characters' : ''}\n />\n </div>\n {err && <div className=\"auth-err\">{err}</div>}\n <button type=\"submit\" className=\"btn primary lg\" style={{ width: '100%', marginTop: 8 }} disabled={busy}>\n {busy ? 'Please wait...' : mode === 'register' ? 'Create account' : 'Sign in'}\n </button>\n\n {(GOOGLE_ENABLED || MICROSOFT_ENABLED) && <div className=\"auth-or\"><span>or</span></div>}\n {GOOGLE_ENABLED && <GoogleButton onCredential={onGoogle} onError={setErr} divider={false} />}\n {MICROSOFT_ENABLED && <MicrosoftButton onCredential={onMicrosoft} onError={setErr} disabled={busy} />}\n\n <p className=\"auth-switch\">\n {mode === 'register' ? 'Already have an account?' : `New to ${productName || 'the product'}?`}{' '}\n <button type=\"button\" onClick={() => { setErr(''); setMode(mode === 'register' ? 'signin' : 'register'); }}>\n {mode === 'register' ? 'Sign in' : 'Create one'}\n </button>\n </p>\n </>\n )}\n </form>\n );\n}\n","// Google Identity Services button (shared Epsilla user pool) — extracted from\n// ContextualGraph. On success it hands the id_token (credential) to the\n// caller, which exchanges it for a session via the engine's /v1/auth/google.\n//\n// The client id is the shared platform OAuth Web client (PUBLIC — Google\n// inlines it into every page); each product's origin must be listed on that\n// client's Authorized JavaScript origins. The whole block (the \"or\" divider\n// included) collapses when GIS cannot render, e.g. while an origin is not yet\n// authorized, so the form never shows a dead gap.\nimport { useEffect, useRef, useState } from 'react';\n\nconst CLIENT_ID = '247853836408-ojk91u8901hdlbkevid4fohmrfdot17l.apps.googleusercontent.com';\n\nexport function GoogleButton({ onCredential, onError, divider = true }) {\n const ref = useRef(null);\n const [failed, setFailed] = useState(false);\n // Keep the latest callbacks in a ref so the GIS button mounts exactly once\n // and never flickers when the parent re-renders on each keystroke.\n const cb = useRef({ onCredential, onError });\n cb.current = { onCredential, onError };\n\n useEffect(() => {\n if (!CLIENT_ID || !ref.current) return undefined;\n const SRC = 'https://accounts.google.com/gsi/client';\n let done = false;\n let drawn = 0;\n let observer = null;\n // Google draws its button at the width it is given (200 to 400 px). Give it\n // the width of the box it sits in, the form's, so it lines up with the inputs\n // and the Sign in button; draw it again when that width changes (a dialog\n // that becomes a sheet on a phone).\n const draw = () => {\n const g = window.google;\n if (!g?.accounts?.id || !ref.current) return;\n const box = ref.current.getBoundingClientRect().width || 320;\n const width = Math.round(Math.max(200, Math.min(400, box)));\n if (Math.abs(width - drawn) < 2) return;\n drawn = width;\n ref.current.innerHTML = '';\n g.accounts.id.renderButton(ref.current, {\n theme: 'outline', size: 'large', shape: 'pill', text: 'continue_with', width,\n });\n };\n const render = () => {\n if (done) return;\n const g = window.google;\n if (!g?.accounts?.id || !ref.current) return;\n done = true;\n try {\n g.accounts.id.initialize({\n client_id: CLIENT_ID,\n callback: (resp) => {\n if (resp?.credential) cb.current.onCredential(resp.credential);\n else cb.current.onError?.('Google sign in was cancelled.');\n },\n });\n draw();\n if (typeof ResizeObserver === 'function') {\n observer = new ResizeObserver(() => { try { draw(); } catch { /* keep the last drawing */ } });\n observer.observe(ref.current);\n }\n } catch {\n setFailed(true);\n }\n };\n let s = document.querySelector(`script[src=\"${SRC}\"]`);\n if (s && window.google) render();\n else {\n if (!s) {\n s = document.createElement('script');\n s.src = SRC;\n s.async = true;\n s.defer = true;\n document.head.appendChild(s);\n }\n s.addEventListener('load', render);\n }\n // If nothing rendered (script blocked, origin not authorized, offline),\n // collapse the block instead of leaving an empty gap.\n const check = window.setTimeout(() => {\n const iframe = ref.current?.querySelector('iframe');\n if (!iframe || iframe.getBoundingClientRect().height < 10) setFailed(true);\n }, 3500);\n return () => {\n s?.removeEventListener('load', render);\n window.clearTimeout(check);\n observer?.disconnect();\n };\n }, []);\n\n if (!CLIENT_ID || failed) return null;\n return (\n <>\n {divider && <div className=\"auth-or\"><span>or</span></div>}\n <div ref={ref} className=\"auth-gwrap\" />\n </>\n );\n}\n\nexport const GOOGLE_ENABLED = !!CLIENT_ID;\n","// Sign in with Microsoft (work and school accounts), the platform's\n// multi-tenant Entra application. Like GoogleButton, it only obtains an\n// OpenID Connect id token and hands it to the caller, which exchanges it for\n// a session at the engine's /v1/auth/microsoft.\n//\n// The token comes back in a popup, to <this origin>/auth/microsoft. That\n// address must be one of the application's registered SPA return addresses\n// (one per product host) and should serve a blank page: this window reads the\n// popup the moment it is back on our origin, before anything could run in it.\n// The client id is PUBLIC (it is in every authorize URL).\nimport { useRef, useState } from 'react';\n\nconst CLIENT_ID = 'cb5c1b6e-aca8-48dd-9da9-31320de30b73';\nconst AUTHORIZE = 'https://login.microsoftonline.com/organizations/oauth2/v2.0/authorize';\nconst RETURN_PATH = '/auth/microsoft';\nconst GIVE_UP_MS = 5 * 60 * 1000;\n\nexport const MICROSOFT_ENABLED = !!CLIENT_ID;\n\nfunction randomHex(bytes = 16) {\n const a = new Uint8Array(bytes);\n crypto.getRandomValues(a);\n return Array.from(a, (b) => b.toString(16).padStart(2, '0')).join('');\n}\n\nfunction jwtClaims(token) {\n try {\n const part = token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/');\n const bin = atob(part + '='.repeat((4 - (part.length % 4)) % 4));\n return JSON.parse(new TextDecoder().decode(Uint8Array.from(bin, (c) => c.charCodeAt(0))));\n } catch {\n return {};\n }\n}\n\n/** Open Microsoft's sign-in in a popup and resolve with the id token, or\n * reject with a sentence a person can read. */\nexport function microsoftIdToken() {\n return new Promise((resolve, reject) => {\n const state = randomHex();\n const nonce = randomHex();\n const back = `${window.location.origin}${RETURN_PATH}`;\n const url = `${AUTHORIZE}?${new URLSearchParams({\n client_id: CLIENT_ID, response_type: 'id_token', redirect_uri: back,\n scope: 'openid profile email', response_mode: 'fragment',\n state, nonce, prompt: 'select_account',\n })}`;\n const w = 480;\n const h = 640;\n const left = Math.max(0, window.screenX + (window.outerWidth - w) / 2);\n const top = Math.max(0, window.screenY + (window.outerHeight - h) / 2);\n const popup = window.open(url, 'microsoft-sign-in', `width=${w},height=${h},left=${left},top=${top}`);\n if (!popup) {\n reject(new Error('Allow pop-ups for this site to sign in with Microsoft.'));\n return;\n }\n const started = Date.now();\n const timer = window.setInterval(() => {\n if (popup.closed) {\n window.clearInterval(timer);\n reject(new Error('Microsoft sign in was cancelled.'));\n return;\n }\n if (Date.now() - started > GIVE_UP_MS) {\n window.clearInterval(timer);\n popup.close();\n reject(new Error('Microsoft sign in took too long. Try again.'));\n return;\n }\n let href = '';\n try { href = popup.location.href; } catch { return; } // still on Microsoft's pages\n if (!href.startsWith(back)) return;\n window.clearInterval(timer);\n const params = new URLSearchParams(popup.location.hash.replace(/^#/, ''));\n popup.close();\n if (params.get('error')) {\n const why = (params.get('error_description') || '').split(/\\r?\\n/)[0].replace(/^AADSTS\\d+:\\s*/, '');\n reject(new Error(why || 'Microsoft sign in did not complete.'));\n return;\n }\n const token = params.get('id_token') || '';\n if (!token || params.get('state') !== state || jwtClaims(token).nonce !== nonce) {\n reject(new Error('Microsoft sign in could not be confirmed. Try again.'));\n return;\n }\n resolve(token);\n }, 300);\n });\n}\n\nfunction MicrosoftLogo() {\n return (\n <svg width=\"18\" height=\"18\" viewBox=\"0 0 21 21\" aria-hidden=\"true\">\n <rect x=\"1\" y=\"1\" width=\"9\" height=\"9\" fill=\"#F25022\" />\n <rect x=\"11\" y=\"1\" width=\"9\" height=\"9\" fill=\"#7FBA00\" />\n <rect x=\"1\" y=\"11\" width=\"9\" height=\"9\" fill=\"#00A4EF\" />\n <rect x=\"11\" y=\"11\" width=\"9\" height=\"9\" fill=\"#FFB900\" />\n </svg>\n );\n}\n\nexport function MicrosoftButton({ onCredential, onError, disabled }) {\n const [waiting, setWaiting] = useState(false);\n const cb = useRef({ onCredential, onError });\n cb.current = { onCredential, onError };\n if (!CLIENT_ID) return null;\n\n async function start() {\n setWaiting(true);\n try {\n const token = await microsoftIdToken();\n await cb.current.onCredential(token);\n } catch (ex) {\n cb.current.onError?.(ex instanceof Error ? ex.message : 'Microsoft sign in failed.');\n } finally {\n setWaiting(false);\n }\n }\n\n return (\n <div className=\"auth-mswrap\">\n <button type=\"button\" className=\"auth-msbtn\" onClick={start} disabled={disabled || waiting}>\n <MicrosoftLogo />\n <span>{waiting ? 'Waiting for Microsoft...' : 'Sign in with Microsoft'}</span>\n </button>\n </div>\n );\n}\n","// SheetGrid — the reusable AI-spreadsheet grid (UI Core).\n//\n// Product-agnostic: it renders a sheet JSON and calls back for edits/runs.\n// The Sheets product (frontend-sheets) AND agentstudio studio Spaces both\n// mount it via @ui-core, so a Space can nest a sheet-typed element with the\n// same component. All I/O is injected — this file has no product API.\n//\n// Sheet shape (see backend/sheets sheet_model):\n// { meta{title,rev}, columns[{id,name,type,options?,compute?}],\n// rows[{id}], cells{ \"<rowId>:<colId>\": {value,status,error} } }\n//\n// Props:\n// sheet — the sheet JSON (required)\n// onRunCell(rowId, colId) — run one computed cell (optional)\n// ops — the document ops (useSheetCollab's sheetOps); every\n// edit is one op on this tab, never a whole-sheet replace\n// onRunColumn(colId) — batch-run a computed column (optional)\n// peers — this tab's other people: [{id, name, color, sel, typing}] (from\n// useSheetCollab); their selection is outlined and tinted in\n// their color, their in-progress text shows in the cell as they type\n// onPresence — ({sel, typing}) what THIS person selects and types, for peers\n// readOnly — no editing/running (template previews / embedded read views)\n// fetchBlobUrl(path) — async product-authed fetch -> object URL, for\n// inline images whose url is a product path\n// onOpenResource(ref) — open a referenced artifact (sheet/slides/…)\n//\n// Editing goes straight to the document: local edits are ops on it; the\n// host persists + (via realtime) rebroadcasts truth back through `sheet`.\nimport { useEffect, useMemo, useRef, useState } from 'react';\nimport { MentionInput } from '../mention/MentionInput.jsx';\nimport { createPortal } from 'react-dom';\nimport { withAlpha } from '../collab/colors.js';\n\nconst cellKey = (rowId, colId) => `${rowId}:${colId}`;\nconst uid = (p) => `${p}_${Math.random().toString(36).slice(2, 10)}`;\n\nconst TYPE_LABEL = {\n text: 'Text', number: 'Number', select: 'Select', tags: 'Tags',\n checkbox: 'Checkbox', date: 'Date', url: 'Link', resource: 'Resource', compute: 'Computed',\n};\n// A one-glyph mark per column type, for pills and pickers.\nconst TYPE_GLYPH = { text: 'Aa', number: '#', select: '▾', tags: '#', checkbox: '✓', date: '▦', url: '↗', resource: '◫', compute: '✦' };\n\nconst MANUAL_TYPES = ['text', 'number', 'select', 'tags', 'checkbox', 'date', 'url', 'resource'];\nconst COMPUTE_KINDS = [\n { kind: 'prompt', label: 'AI prompt' },\n { kind: 'harness', label: 'Agent (harness)' },\n { kind: 'workflow', label: 'Workflow' },\n { kind: 'image', label: 'Generate image' },\n];\nconst RESOURCE_KINDS = ['image', 'sheet', 'slides', 'workflow', 'graph'];\nconst RESOURCE_ICON = { image: '🖼', sheet: '▦', slides: '▤', workflow: '⚙', graph: '◉' };\n\n// Popovers render through a body portal with FIXED positioning — inside the\n// grid they'd be clipped by the scroll container and out-stacked by the\n// sticky header/row-number cells. anchor is a DOMRect captured at open time;\n// the box clamps to the viewport and flips above the anchor when the bottom\n// would overflow. A scroll OUTSIDE the box closes it (the anchor moved);\n// scrolling inside it (a long prompt, a long option list) is the box's own.\nfunction PopPortal({ anchor, width = 250, estHeight = 300, className, children, onClose }) {\n const boxRef = useRef(null);\n useEffect(() => {\n if (!onClose) return undefined;\n const close = (e) => {\n if (e?.type === 'scroll' && boxRef.current && e.target instanceof Node && boxRef.current.contains(e.target)) return;\n onClose();\n };\n window.addEventListener('scroll', close, true);\n window.addEventListener('resize', close);\n return () => { window.removeEventListener('scroll', close, true); window.removeEventListener('resize', close); };\n }, [onClose]);\n if (!anchor) return null;\n const left = Math.max(8, Math.min(anchor.right - width, window.innerWidth - width - 8));\n let top = anchor.bottom + 6;\n if (top + estHeight > window.innerHeight - 8) top = Math.max(8, anchor.top - estHeight - 6);\n return createPortal(\n <div ref={boxRef} className={className} style={{ position: 'fixed', top, left, width, zIndex: 1000 }}>\n {children}\n </div>,\n document.body,\n );\n}\n\n// Value styling. A column's `options` are its value vocabulary: each option is\n// a value and a color. A select column offers them as choices; EVERY column\n// type paints a cell whose value matches one as a pill in that color, so an\n// enumerated result (CORRECT / WRONG, HEALTHY / AT RISK) reads at a glance.\n// The palette is named so a color can mean something; an option that declares\n// no color takes the muted rotation.\nexport const PILL_PALETTE = [\n { name: 'green', color: '#D1FAE5' }, { name: 'red', color: '#FEE2E2' },\n { name: 'amber', color: '#FEF3C7' }, { name: 'blue', color: '#DBEAFE' },\n { name: 'purple', color: '#EDE9FE' }, { name: 'pink', color: '#FCE7F3' },\n { name: 'teal', color: '#CCFBF1' }, { name: 'gray', color: '#E5E7EB' },\n];\nconst PILL_FALLBACKS = ['#E0E7FF', '#FCE7F3', '#D1FAE5', '#FEF3C7', '#E0F2FE', '#F3E8FF', '#FFE4E6'];\n\nexport function normOptions(options) {\n return (options || []).map((o, i) => {\n if (typeof o === 'string') return { label: o, color: PILL_FALLBACKS[i % PILL_FALLBACKS.length] };\n return { label: o.label ?? String(o.value ?? ''), color: o.color || PILL_FALLBACKS[i % PILL_FALLBACKS.length] };\n });\n}\n\nconst sameValue = (a, b) => String(a).trim().toLowerCase() === String(b).trim().toLowerCase();\n\n/** The option a value matches (trimmed, case-insensitive), or null. */\nfunction optionFor(value, options) {\n if (value === undefined || value === null || value === '') return null;\n return normOptions(options).find((o) => sameValue(o.label, value)) || null;\n}\n\nfunction pillColor(label, options) {\n const hit = optionFor(label, options);\n if (hit) return hit.color;\n // stable fallback by hash so ad-hoc tags keep their color\n let h = 0;\n for (const ch of String(label)) h = (h * 31 + ch.charCodeAt(0)) >>> 0;\n return PILL_FALLBACKS[h % PILL_FALLBACKS.length];\n}\n\n// An inline image whose url may be a product path (needs authed fetch).\nfunction RefImage({ refVal, fetchBlobUrl }) {\n const [src, setSrc] = useState(/^https?:\\/\\//i.test(refVal.url || '') ? refVal.url : null);\n useEffect(() => {\n let dead = false; let obj = null;\n if (!src && refVal.url && fetchBlobUrl) {\n fetchBlobUrl(refVal.url).then((u) => { if (!dead) { obj = u; setSrc(u); } });\n }\n return () => { dead = true; if (obj) URL.revokeObjectURL(obj); };\n }, [refVal.url]);\n if (!src) return <span className=\"shg-refchip\">{RESOURCE_ICON.image} {refVal.name || 'image'}</span>;\n return <img className=\"shg-refimg\" src={src} alt={refVal.name || ''} title={refVal.name || ''} />;\n}\n\nfunction ResourceChip({ refVal, onOpen }) {\n const icon = RESOURCE_ICON[refVal.kind] || '◇';\n return (\n <button className=\"shg-refchip shg-refchip-btn\" title={`Open ${refVal.kind}`}\n onClick={(e) => { e.stopPropagation(); onOpen && onOpen(refVal); }}>\n <span className=\"shg-refchip-ic\">{icon}</span>\n <span className=\"shg-refchip-name\">{refVal.name || refVal.id || refVal.kind}</span>\n </button>\n );\n}\n\n// A small status dot for computed cells while work is pending or went wrong;\n// a finished cell is its value.\nfunction StatusDot({ status }) {\n if (!status || status === 'empty' || status === 'done') return null;\n return <span className={`shg-dot shg-dot-${status}`} title={status} />;\n}\n\nfunction CellValue({ cell, col, fetchBlobUrl, onOpenResource }) {\n const v = cell?.value;\n if (v === undefined || v === null || v === '') return <span className=\"shg-val-txt\" />;\n // A typed artifact ref renders the same whether hand-set (resource column)\n // or produced by a compute kind (e.g. Generate image).\n if (v && typeof v === 'object' && !Array.isArray(v) && v.kind) {\n if (v.kind === 'image') return <RefImage refVal={v} fetchBlobUrl={fetchBlobUrl} />;\n return <ResourceChip refVal={v} onOpen={onOpenResource} />;\n }\n const styled = col.type !== 'tags' && optionFor(v, col.options);\n if (styled) return <span className=\"shg-pill\" style={{ background: styled.color }}>{styled.label}</span>;\n switch (col.type) {\n case 'select':\n return <span className=\"shg-pill\" style={{ background: pillColor(String(v), col.options) }}>{String(v)}</span>;\n case 'tags': {\n const tags = Array.isArray(v) ? v : String(v).split(',').map((s) => s.trim()).filter(Boolean);\n return (\n <span className=\"shg-pills\">\n {tags.map((t) => (\n <span key={t} className=\"shg-pill\" style={{ background: pillColor(t, col.options) }}>{t}</span>\n ))}\n </span>\n );\n }\n case 'checkbox':\n return <span className={'shg-check' + (v ? ' on' : '')}>{v ? '✓' : ''}</span>;\n case 'url': {\n const href = /^https?:\\/\\//i.test(String(v)) ? String(v) : `https://${v}`;\n return <a className=\"shg-link\" href={href} target=\"_blank\" rel=\"noreferrer\" onClick={(e) => e.stopPropagation()}>{String(v)}</a>;\n }\n case 'number':\n return <span className=\"shg-val-txt shg-num\">{String(v)}</span>;\n default:\n return <span className=\"shg-val-txt\">{typeof v === 'object' ? JSON.stringify(v) : String(v)}</span>;\n }\n}\n\nexport function SheetGrid({ sheet, ops, onRunCell, onRunColumn, readOnly = false, fetchBlobUrl, onOpenResource, peers, onPresence }) {\n const columns = sheet?.columns || [];\n const rows = sheet?.rows || [];\n const cells = sheet?.cells || {};\n const tabId = sheet?.id;\n const canEdit = !readOnly && !!ops && !!tabId;\n const [editing, setEditing] = useState(null); // {rowId, colId, type}\n const [draft, setDraft] = useState('');\n const [menuCol, setMenuCol] = useState(null); // {id, rect} of the open column menu\n const [sizeDraft, setSizeDraft] = useState({}); // live {col:{id:w}, row:{id:h}} during a drag\n const [dnd, setDnd] = useState(null); // {kind:'col'|'row', id} being dragged\n const [dropAt, setDropAt] = useState(null); // {kind, id, after} current drop slot\n const inputRef = useRef(null);\n const dragRef = useRef(null);\n // Selection, Google Sheets style: a click selects, a drag or Shift extends\n // the range, a double click / Enter / typing edits the focus cell. Indexes\n // into this tab's rows and columns; presence carries the ids.\n const [sel, setSel] = useState(null); // {a:{r,c}, f:{r,c}}\n const dragSel = useRef(false);\n const rootRef = useRef(null);\n const presenceRef = useRef(onPresence);\n presenceRef.current = onPresence;\n const range = sel ? { r0: Math.min(sel.a.r, sel.f.r), r1: Math.max(sel.a.r, sel.f.r),\n c0: Math.min(sel.a.c, sel.f.c), c1: Math.max(sel.a.c, sel.f.c) } : null;\n const inSel = (ri, ci) => !!range && ri >= range.r0 && ri <= range.r1 && ci >= range.c0 && ci <= range.c1;\n const isFocus = (ri, ci) => !!sel && sel.f.r === ri && sel.f.c === ci;\n const clampSel = (p) => ({ r: Math.max(0, Math.min(p.r, rows.length - 1)), c: Math.max(0, Math.min(p.c, columns.length - 1)) });\n const moveFocus = (dr, dc, extend) => setSel((cur) => {\n if (!cur || !rows.length || !columns.length) return cur;\n const f = clampSel({ r: cur.f.r + dr, c: cur.f.c + dc });\n return { a: extend ? cur.a : f, f };\n });\n useEffect(() => {\n const up = () => { dragSel.current = false; };\n window.addEventListener('mouseup', up);\n return () => window.removeEventListener('mouseup', up);\n }, []);\n // Tell peers what this person selects and types.\n useEffect(() => {\n const fn = presenceRef.current;\n if (!fn) return;\n const ids = (p) => [rows[p.r]?.id, columns[p.c]?.id];\n fn({\n sel: sel && rows[sel.f.r] && columns[sel.f.c] ? { a: ids(sel.a), f: ids(sel.f) } : null,\n typing: editing && typeof draft === 'string' ? { key: cellKey(editing.rowId, editing.colId), text: draft } : null,\n });\n }, [sel, editing, draft, rows, columns]);\n // Peers on this tab: who has which cell in focus, which cells sit in their\n // ranges, and what they are typing where.\n const peerLayer = useMemo(() => {\n const focus = {}, tint = {}, typing = {};\n const rIdx = new Map(rows.map((r, i) => [r.id, i]));\n const cIdx = new Map(columns.map((c, i) => [c.id, i]));\n for (const p of peers || []) {\n if (p.typing && p.typing.key) typing[p.typing.key] = { text: p.typing.text, color: p.color, name: p.name };\n if (!p.sel || !p.sel.a || !p.sel.f) continue;\n const a = { r: rIdx.get(p.sel.a[0]), c: cIdx.get(p.sel.a[1]) }, f = { r: rIdx.get(p.sel.f[0]), c: cIdx.get(p.sel.f[1]) };\n if ([a.r, a.c, f.r, f.c].some((v) => v === undefined)) continue;\n focus[cellKey(p.sel.f[0], p.sel.f[1])] = p;\n for (let r = Math.min(a.r, f.r); r <= Math.max(a.r, f.r); r++) {\n for (let c = Math.min(a.c, f.c); c <= Math.max(a.c, f.c); c++) {\n const k = cellKey(rows[r].id, columns[c].id);\n if (!tint[k]) tint[k] = p.color;\n }\n }\n }\n return { focus, tint, typing };\n }, [peers, rows, columns]);\n\n // Drag-to-resize: live via sizeDraft, persisted into the sheet on release.\n const startResize = (e, kind, id, start) => {\n if (readOnly) return;\n e.preventDefault(); e.stopPropagation();\n const origin = kind === 'col' ? e.clientX : e.clientY;\n dragRef.current = { kind, id, start, origin, last: start };\n const onMove = (ev) => {\n const d = dragRef.current; if (!d) return;\n const delta = (d.kind === 'col' ? ev.clientX : ev.clientY) - d.origin;\n const next = Math.max(d.kind === 'col' ? 90 : 26, d.start + delta);\n d.last = next;\n setSizeDraft((sd) => ({ ...sd, [d.kind]: { ...(sd[d.kind] || {}), [d.id]: next } }));\n };\n const onUp = () => {\n const d = dragRef.current; dragRef.current = null;\n window.removeEventListener('mousemove', onMove);\n window.removeEventListener('mouseup', onUp);\n document.body.style.cursor = '';\n if (!d) return;\n setSizeDraft({});\n if (!canEdit) return;\n if (d.kind === 'col') { const c = columns.find((x) => x.id === d.id); if (c) ops.setColumn(tabId, { ...c, width: Math.round(d.last) }); }\n else { const r = rows.find((x) => x.id === d.id); if (r) ops.setRow(tabId, { ...r, height: Math.round(d.last) }); }\n };\n window.addEventListener('mousemove', onMove);\n window.addEventListener('mouseup', onUp);\n document.body.style.cursor = kind === 'col' ? 'col-resize' : 'row-resize';\n };\n const colWidth = (col) => (sizeDraft.col && sizeDraft.col[col.id]) || col.width || undefined;\n\n // Drag-to-reorder (columns by their header, rows by their number cell).\n const reorder = (kind, fromId, toId, after) => {\n if (!canEdit || fromId === toId) return;\n const arr = (kind === 'col' ? columns : rows).map((x) => x.id);\n const i = arr.indexOf(fromId);\n if (i < 0) return;\n arr.splice(i, 1);\n let j = arr.indexOf(toId);\n if (j < 0) return;\n if (after) j += 1;\n if (kind === 'col') ops.moveColumn(tabId, fromId, j); else ops.moveRow(tabId, fromId, j);\n };\n const dndProps = (kind, id) => (readOnly ? {} : {\n draggable: true,\n onDragStart: (e) => {\n if (e.target.closest && e.target.closest('.shg-resize-col, .shg-resize-row, input, button')) { e.preventDefault(); return; }\n e.dataTransfer.effectAllowed = 'move';\n e.dataTransfer.setData('text/plain', `${kind}:${id}`);\n setDnd({ kind, id });\n },\n onDragOver: (e) => {\n if (!dnd || dnd.kind !== kind || dnd.id === id) return;\n e.preventDefault();\n const r = e.currentTarget.getBoundingClientRect();\n const after = kind === 'col' ? e.clientX > r.x + r.width / 2 : e.clientY > r.y + r.height / 2;\n setDropAt((d) => (d && d.id === id && d.after === after ? d : { kind, id, after }));\n },\n onDrop: (e) => {\n e.preventDefault();\n if (dnd && dnd.kind === kind && dnd.id !== id) {\n const r = e.currentTarget.getBoundingClientRect();\n const after = kind === 'col' ? e.clientX > r.x + r.width / 2 : e.clientY > r.y + r.height / 2;\n reorder(kind, dnd.id, id, after);\n }\n setDnd(null); setDropAt(null);\n },\n onDragEnd: () => { setDnd(null); setDropAt(null); },\n });\n const dndClass = (kind, id) => {\n let cls = '';\n if (dnd && dnd.kind === kind && dnd.id === id) cls += ' shg-dragging';\n if (dropAt && dropAt.kind === kind && dropAt.id === id) {\n cls += dropAt.after ? (kind === 'col' ? ' shg-drop-after' : ' shg-drop-below')\n : (kind === 'col' ? ' shg-drop-before' : ' shg-drop-above');\n }\n return cls;\n };\n // The number gutter is FIXED: sized by the digit count of the row total so\n // it never stretches (an empty grid otherwise splits the table width).\n const numW = Math.max(40, 24 + String(rows.length || 1).length * 9);\n const numStyle = { width: numW, minWidth: numW, maxWidth: numW };\n const rowHeight = (row) => (sizeDraft.row && sizeDraft.row[row.id]) || row.height || undefined;\n\n useEffect(() => { if (editing && inputRef.current) inputRef.current.focus(); }, [editing]);\n\n const setCell = (rowId, colId, value) => {\n if (!canEdit) return;\n ops.setCell(tabId, cellKey(rowId, colId), { value, status: 'done', updated_at: Math.floor(Date.now() / 1000) });\n };\n\n const openEdit = (rowId, col, anchorEl, initial) => {\n if (!canEdit) return;\n if (col.type === 'compute') return; // computed cells aren't hand-edited\n if (col.type === 'checkbox') { // toggles directly\n const cur = cells[cellKey(rowId, col.id)];\n setCell(rowId, col.id, !(cur && cur.value));\n return;\n }\n const c = cells[cellKey(rowId, col.id)];\n const v = c?.value;\n if (col.type === 'tags') setDraft(initial ?? (Array.isArray(v) ? v.join(', ') : (v || '')));\n else if (col.type === 'resource') setDraft(v && typeof v === 'object' ? v : { kind: 'sheet', name: '', id: '', url: '' });\n else setDraft(initial ?? (v == null ? '' : String(v)));\n setEditing({ rowId, colId: col.id, type: col.type, rect: anchorEl?.getBoundingClientRect?.() || null });\n };\n\n const commitEdit = () => {\n if (!editing) return;\n const { rowId, colId, type } = editing;\n let value = draft;\n if (type === 'number') value = draft === '' ? null : Number(draft);\n else if (type === 'tags') value = draft ? draft.split(',').map((s) => s.trim()).filter(Boolean) : [];\n setCell(rowId, colId, value);\n setEditing(null);\n };\n\n const addColumn = () => canEdit && ops.setColumn(tabId, { id: uid('col'), name: `Column ${columns.length + 1}`, type: 'text' });\n const addRow = () => canEdit && ops.setRow(tabId, { id: uid('row') });\n const deleteColumn = (colId) => canEdit && ops.deleteColumn(tabId, colId);\n const deleteRow = (rowId) => canEdit && ops.deleteRow(tabId, rowId);\n const renameColumn = (colId, name) => {\n const c = columns.find((x) => x.id === colId);\n if (canEdit && c) ops.setColumn(tabId, { ...c, name });\n };\n const configureColumn = (colId, patch) => {\n const c = columns.find((x) => x.id === colId);\n if (!canEdit || !c) return;\n const next = { ...c, ...patch };\n if (patch.type && patch.type !== 'compute') delete next.compute;\n ops.setColumn(tabId, next);\n };\n\n // The selection as text: one line per row, tab between cells.\n const cellText = (c) => {\n const v = c?.value;\n if (v === undefined || v === null) return '';\n if (Array.isArray(v)) return v.join(', ');\n if (typeof v === 'object') return v.name || v.url || v.id || '';\n return String(v);\n };\n const copySelection = (e) => {\n if (!range || editing) return;\n const lines = [];\n for (let r = range.r0; r <= range.r1; r++) {\n const parts = [];\n for (let c = range.c0; c <= range.c1; c++) parts.push(cellText(cells[cellKey(rows[r].id, columns[c].id)]));\n lines.push(parts.join('\\t'));\n }\n e.clipboardData.setData('text/plain', lines.join('\\n'));\n e.preventDefault();\n };\n const pasteAt = (e) => {\n if (!sel || editing || !canEdit) return;\n const text = e.clipboardData.getData('text/plain');\n if (!text) return;\n e.preventDefault();\n const now = Math.floor(Date.now() / 1000);\n const patch = {};\n const lines = text.replace(/\\r/g, '').split('\\n');\n if (lines.length > 1 && lines[lines.length - 1] === '') lines.pop();\n lines.forEach((line, dr) => line.split('\\t').forEach((raw, dc) => {\n const row = rows[sel.f.r + dr], col = columns[sel.f.c + dc];\n if (!row || !col || col.type === 'compute') return;\n let value = raw;\n if (col.type === 'number') value = raw === '' ? null : Number(raw);\n else if (col.type === 'checkbox') value = /^(true|yes|1|✓)$/i.test(raw.trim());\n else if (col.type === 'tags') value = raw ? raw.split(',').map((x) => x.trim()).filter(Boolean) : [];\n patch[cellKey(row.id, col.id)] = value === null || value === '' ? null : { value, status: 'done', updated_at: now };\n }));\n if (Object.keys(patch).length) ops.setCells(tabId, patch);\n setSel({ a: sel.f, f: clampSel({ r: sel.f.r + lines.length - 1, c: sel.f.c + Math.max(...lines.map((l) => l.split('\\t').length)) - 1 }) });\n };\n const clearSelection = () => {\n if (!range || !canEdit) return;\n const patch = {};\n for (let r = range.r0; r <= range.r1; r++) {\n for (let c = range.c0; c <= range.c1; c++) {\n if (columns[c].type === 'compute') continue;\n const k = cellKey(rows[r].id, columns[c].id);\n if (cells[k]) patch[k] = null;\n }\n }\n if (Object.keys(patch).length) ops.setCells(tabId, patch);\n };\n const onKeyDown = (e) => {\n if (editing || menuCol) return;\n if (!sel) return;\n const meta = e.metaKey || e.ctrlKey;\n if (meta && (e.key === 'c' || e.key === 'v' || e.key === 'x')) return; // copy/paste events handle these\n const focusCell = () => ({ row: rows[sel.f.r], col: columns[sel.f.c] });\n switch (e.key) {\n case 'ArrowUp': e.preventDefault(); moveFocus(-1, 0, e.shiftKey); return;\n case 'ArrowDown': e.preventDefault(); moveFocus(1, 0, e.shiftKey); return;\n case 'ArrowLeft': e.preventDefault(); moveFocus(0, -1, e.shiftKey); return;\n case 'ArrowRight': e.preventDefault(); moveFocus(0, 1, e.shiftKey); return;\n case 'Tab': e.preventDefault(); moveFocus(0, e.shiftKey ? -1 : 1, false); return;\n case 'Escape': setSel(null); return;\n case 'Enter': case 'F2': {\n e.preventDefault();\n const { row, col } = focusCell();\n if (row && col) openEdit(row.id, col, rootRef.current?.querySelector(`[data-cell=\"${cellKey(row.id, col.id)}\"]`));\n return;\n }\n case 'Delete': case 'Backspace': e.preventDefault(); clearSelection(); return;\n default:\n }\n if (!meta && !e.altKey && e.key.length === 1) {\n const { row, col } = focusCell();\n if (row && col && col.type !== 'compute' && col.type !== 'checkbox') {\n e.preventDefault();\n openEdit(row.id, col, rootRef.current?.querySelector(`[data-cell=\"${cellKey(row.id, col.id)}\"]`), e.key);\n }\n }\n };\n\n // The inline editor for the editing cell, by type.\n const renderEditor = (col) => {\n if (col.type === 'resource') {\n const d = typeof draft === 'object' && draft ? draft : { kind: 'sheet' };\n const set = (k, v) => setDraft({ ...d, [k]: v });\n return (\n <PopPortal anchor={editing.rect} width={240} estHeight={230}\n className=\"shg-select-pop shg-ref-pop\" onClose={() => setEditing(null)}>\n <div onClick={(e) => e.stopPropagation()}>\n <select className=\"shg-menu-input\" value={d.kind || 'sheet'} onChange={(e) => set('kind', e.target.value)}>\n {RESOURCE_KINDS.map((k) => <option key={k} value={k}>{k}</option>)}\n </select>\n <input className=\"shg-menu-input\" placeholder=\"Name\" value={d.name || ''} onChange={(e) => set('name', e.target.value)} />\n <input className=\"shg-menu-input\" placeholder=\"Resource id (e.g. sheet.…)\" value={d.id || ''} onChange={(e) => set('id', e.target.value)} />\n <input className=\"shg-menu-input\" placeholder=\"or URL\" value={d.url || ''} onChange={(e) => set('url', e.target.value)} />\n <div className=\"shg-menu-actions\">\n <button className=\"shg-pop-clear\" onClick={() => { setCell(editing.rowId, editing.colId, null); setEditing(null); }}>Clear</button>\n <button className=\"shg-menu-apply\" onClick={() => { setCell(editing.rowId, editing.colId, d); setEditing(null); }}>Set</button>\n </div>\n </div>\n </PopPortal>\n );\n }\n if (col.type === 'select') {\n const opts = normOptions(col.options);\n return (\n <PopPortal anchor={editing.rect} width={190} estHeight={40 + opts.length * 30}\n className=\"shg-select-pop\" onClose={() => setEditing(null)}>\n {opts.length === 0 && <div className=\"shg-pop-note\">No options yet — add them in the column menu.</div>}\n {opts.map((o) => (\n <button key={o.label} className=\"shg-pill shg-pill-btn\" style={{ background: o.color }}\n onClick={(e) => { e.stopPropagation(); setCell(editing.rowId, editing.colId, o.label); setEditing(null); }}>\n {o.label}\n </button>\n ))}\n <button className=\"shg-pop-clear\"\n onClick={(e) => { e.stopPropagation(); setCell(editing.rowId, editing.colId, null); setEditing(null); }}>\n Clear\n </button>\n </PopPortal>\n );\n }\n const inputType = col.type === 'date' ? 'date' : col.type === 'number' ? 'number' : 'text';\n return (\n <input ref={inputRef} className=\"shg-input\" type={inputType} value={draft}\n placeholder={col.type === 'tags' ? 'tag, tag, …' : ''}\n onChange={(e) => setDraft(e.target.value)}\n onBlur={commitEdit}\n onKeyDown={(e) => {\n if (e.key === 'Enter') { e.preventDefault(); commitEdit(); moveFocus(1, 0, false); rootRef.current?.focus(); }\n else if (e.key === 'Tab') { e.preventDefault(); commitEdit(); moveFocus(0, e.shiftKey ? -1 : 1, false); rootRef.current?.focus(); }\n else if (e.key === 'Escape') { setEditing(null); rootRef.current?.focus(); }\n }} />\n );\n };\n\n return (\n <div className=\"shg\" ref={rootRef} tabIndex={0} onKeyDown={onKeyDown} onCopy={copySelection} onPaste={pasteAt}>\n <div className=\"shg-scroll\">\n <table className=\"shg-table\">\n <thead>\n <tr>\n <th className=\"shg-corner\" style={numStyle} />\n {columns.map((col) => (\n <th key={col.id}\n className={'shg-col' + (col.type === 'compute' ? ' shg-col-compute' : '') + dndClass('col', col.id)}\n style={colWidth(col) ? { width: colWidth(col), minWidth: colWidth(col), maxWidth: colWidth(col) } : undefined}\n {...dndProps('col', col.id)}>\n {!readOnly && (\n <span className=\"shg-resize-col\" onMouseDown={(e) => startResize(e, 'col', col.id, colWidth(col) || e.currentTarget.closest('th').offsetWidth)} />\n )}\n <div className=\"shg-col-h\">\n <ColumnHeader\n col={col} columns={columns} readOnly={readOnly}\n menuOpen={menuCol?.id === col.id}\n menuAnchor={menuCol?.id === col.id ? menuCol.rect : null}\n onMenu={(e) => setMenuCol(menuCol?.id === col.id ? null\n : { id: col.id, rect: e.currentTarget.getBoundingClientRect() })}\n onCloseMenu={() => setMenuCol(null)}\n onRename={renameColumn}\n onConfigure={configureColumn}\n onDelete={() => { setMenuCol(null); deleteColumn(col.id); }}\n onRun={col.type === 'compute' && onRunColumn ? () => onRunColumn(col.id) : null}\n width={colWidth(col)} />\n </div>\n </th>\n ))}\n {!readOnly && (\n <th className=\"shg-add-col\"><button className=\"shg-add\" onClick={addColumn} title=\"Add column\">+</button></th>\n )}\n </tr>\n </thead>\n <tbody>\n {rows.map((row, ri) => (\n <tr key={row.id}\n style={{\n ...(rowHeight(row) ? { height: rowHeight(row) } : null),\n '--shg-clamp': Math.max(1, Math.floor(((rowHeight(row) || 34) - 10) / 18)),\n }}>\n <td className={'shg-rownum' + dndClass('row', row.id)} style={numStyle}\n title=\"Drag to reorder\" {...dndProps('row', row.id)}>\n <span>{ri + 1}</span>\n {!readOnly && <button className=\"shg-rowdel\" onClick={() => deleteRow(row.id)} title=\"Delete row\">×</button>}\n {!readOnly && (\n <span className=\"shg-resize-row\" onMouseDown={(e) => startResize(e, 'row', row.id, rowHeight(row) || e.currentTarget.closest('tr').offsetHeight)} />\n )}\n </td>\n {columns.map((col, ci) => {\n const key = cellKey(row.id, col.id);\n const c = cells[key] || {};\n const isEditing = editing && editing.rowId === row.id && editing.colId === col.id;\n const peer = peerLayer.focus[key];\n const ghost = !isEditing && peerLayer.typing[key];\n const selected = inSel(ri, ci), focused = isFocus(ri, ci);\n const shadows = [];\n if (focused) shadows.push('inset 0 0 0 2px var(--brand, #0E7490)');\n if (peer) shadows.push(`inset 0 0 0 2px ${peer.color}`);\n const tint = !selected && peerLayer.tint[key];\n return (\n <td key={col.id} data-cell={key}\n className={'shg-cell' + (col.type === 'compute' ? ' shg-cell-compute' : '')\n + (c.status && col.type === 'compute' ? ` shg-cell-${c.status}` : '')\n + (selected ? ' shg-sel' : '') + (focused ? ' shg-focus' : '')\n + (peer ? ' shg-cell-peer' : '')}\n style={{ ...(shadows.length ? { boxShadow: shadows.join(', ') } : null),\n ...(tint ? { background: withAlpha(tint, 0.10) } : null) }}\n onMouseDown={(e) => {\n if (e.button !== 0 || isEditing) return;\n if (editing) commitEdit();\n const p = { r: ri, c: ci };\n setSel((cur) => (e.shiftKey && cur ? { a: cur.a, f: p } : { a: p, f: p }));\n dragSel.current = true;\n e.preventDefault();\n rootRef.current?.focus();\n }}\n onMouseEnter={() => { if (dragSel.current) setSel((cur) => (cur ? { a: cur.a, f: { r: ri, c: ci } } : cur)); }}\n onClick={(e) => { if (col.type === 'checkbox' && !isEditing) openEdit(row.id, col, e.currentTarget); }}\n onDoubleClick={(e) => { if (!isEditing) openEdit(row.id, col, e.currentTarget); }}\n title={c.error || ''}>\n {peer && <span className=\"shg-peer-flag\" style={{ background: peer.color }}>{peer.name}</span>}\n {isEditing ? renderEditor(col) : (\n <div className=\"shg-val\"\n style={{ maxWidth: (colWidth(col) ? colWidth(col) - 20 : 400) }}>\n {col.type === 'compute' && <StatusDot status={c.status} />}\n {ghost ? (\n <span className=\"shg-ghost\" style={{ color: ghost.color }} title={`${ghost.name} is typing`}>{ghost.text}</span>\n ) : (\n <CellValue cell={c} col={col} fetchBlobUrl={fetchBlobUrl} onOpenResource={onOpenResource} />\n )}\n {col.type === 'compute' && !readOnly && onRunCell && (\n <button className=\"shg-runcell\" title=\"Run this cell\"\n onClick={(e) => { e.stopPropagation(); onRunCell(row.id, col.id); }}>▶</button>\n )}\n </div>\n )}\n </td>\n );\n })}\n {!readOnly && <td className=\"shg-pad\" />}\n </tr>\n ))}\n {!readOnly && (\n <tr className=\"shg-ghost-row\" onClick={addRow}>\n <td className=\"shg-rownum shg-ghost-num\" style={numStyle}>+</td>\n <td className=\"shg-ghost-cell\" colSpan={columns.length + 1}>New row</td>\n </tr>\n )}\n </tbody>\n </table>\n </div>\n </div>\n );\n}\n\nfunction ColumnHeader({ col, columns, readOnly, menuOpen, menuAnchor, onMenu, onCloseMenu, onRename, onConfigure, onDelete, onRun, width }) {\n const [editing, setEditing] = useState(false);\n const [name, setName] = useState(col.name);\n useEffect(() => setName(col.name), [col.name]);\n // A narrow column keeps its name: the caption goes first, then the Run label.\n const w = Number(width) || 0;\n const fit = w && w < 160 ? ' tight' : w && w < 200 ? ' narrow' : '';\n return (\n <div className={'shg-colhdr' + fit}>\n <div className=\"shg-colhdr-main\">\n {editing && !readOnly ? (\n <input className=\"shg-colname-input\" value={name} autoFocus\n onChange={(e) => setName(e.target.value)}\n onBlur={() => { setEditing(false); if (name.trim() && name !== col.name) onRename(col.id, name.trim()); }}\n onKeyDown={(e) => { if (e.key === 'Enter') e.target.blur(); }} />\n ) : (\n <span className=\"shg-colname\" onDoubleClick={() => !readOnly && setEditing(true)} title={col.name}>{col.name}</span>\n )}\n <span className={'shg-coltype' + (col.type === 'compute' ? ' compute' : '')}>\n {TYPE_LABEL[col.type] || col.type}\n {col.type === 'compute' && col.compute?.kind ? ` · ${col.compute.kind}` : ''}\n </span>\n </div>\n {!readOnly && (\n <div className=\"shg-colhdr-tools\">\n {onRun && <button className=\"shg-colrun\" onClick={onRun} title=\"Run this column\" aria-label=\"Run this column\">▶<span className=\"shg-colrun-label\"> Run</span></button>}\n <button className=\"shg-colmenu-btn\" onClick={(e) => onMenu(e)} title=\"Column settings\">⋯</button>\n </div>\n )}\n {menuOpen && !readOnly && (\n <ColumnMenu col={col} columns={columns} anchor={menuAnchor}\n onApply={(patch) => { onConfigure(col.id, patch); onCloseMenu(); }}\n onDelete={onDelete} onClose={onCloseMenu} />\n )}\n </div>\n );\n}\n\n// The column's values as pills in one field: type a value and press Enter or\n// comma to add it, Backspace on an empty field removes the last, and clicking\n// a pill opens the palette to pick its color. Select and tags columns offer\n// these as choices; every column paints a matching value in its color.\nfunction ValuePills({ values, onChange }) {\n const [text, setText] = useState('');\n const [picking, setPicking] = useState(null); // index of the pill whose palette is open\n const add = () => {\n const label = text.trim();\n if (!label) return;\n if (!values.some((v) => sameValue(v.label, label))) onChange([...values, { label }]);\n setText('');\n };\n const remove = (i) => { onChange(values.filter((_, j) => j !== i)); setPicking(null); };\n const paint = (i, color) => { onChange(values.map((v, j) => (j === i ? { ...v, color } : v))); setPicking(null); };\n return (\n <div className=\"shg-values\" onClick={(e) => { if (e.target === e.currentTarget) e.currentTarget.querySelector('input')?.focus(); }}>\n {values.map((v, i) => (\n <span key={v.label} className=\"shg-value\">\n <button type=\"button\" className=\"shg-pill shg-pill-btn\"\n style={{ background: v.color || PILL_FALLBACKS[i % PILL_FALLBACKS.length] }}\n title=\"Pick a color\" aria-expanded={picking === i}\n onClick={(e) => { e.stopPropagation(); setPicking(picking === i ? null : i); }}>\n {v.label}\n <span className=\"shg-value-x\" role=\"button\" aria-label={`Remove ${v.label}`}\n onClick={(e) => { e.stopPropagation(); remove(i); }}>×</span>\n </button>\n {picking === i && (\n <span className=\"shg-swatches\" role=\"listbox\" aria-label={`Color for ${v.label}`}>\n {PILL_PALETTE.map((p) => (\n <button key={p.name} type=\"button\" role=\"option\" aria-selected={v.color === p.color}\n className={'shg-swatch' + (v.color === p.color ? ' on' : '')}\n style={{ background: p.color }} title={p.name}\n onClick={(e) => { e.stopPropagation(); paint(i, p.color); }} />\n ))}\n </span>\n )}\n </span>\n ))}\n <input className=\"shg-values-input\" value={text} placeholder={values.length ? '' : 'Type a value, press Enter'}\n onChange={(e) => setText(e.target.value)}\n onKeyDown={(e) => {\n if (e.key === 'Enter' || e.key === ',') { e.preventDefault(); add(); }\n else if (e.key === 'Backspace' && !text && values.length) remove(values.length - 1);\n }}\n onBlur={add} />\n </div>\n );\n}\n\n// The column configuration popover: type, options (select/tags), and the\n// compute mount (prompt / harness / workflow + deps). Product-agnostic —\n// plain controlled inputs, applied as one patch.\nfunction ColumnMenu({ col, columns, anchor, onApply, onDelete, onClose }) {\n const [type, setType] = useState(col.type || 'text');\n // The column's values, in order, each with the color it was given (or none).\n const [values, setValues] = useState(() => (col.options || []).map((o) =>\n (typeof o === 'string' ? { label: o } : { label: o.label ?? String(o.value ?? ''), ...(o.color ? { color: o.color } : {}) })));\n const comp = col.compute || {};\n const [kind, setKind] = useState(comp.kind || 'prompt');\n const [prompt, setPrompt] = useState(comp.prompt || '');\n const [harnessId, setHarnessId] = useState(comp.harness_id || '');\n const [wfSlug, setWfSlug] = useState(comp.workflow_slug || '');\n const [outKey, setOutKey] = useState(comp.output_key || '');\n const [deps, setDeps] = useState(new Set(comp.deps || []));\n const ref = useRef(null);\n\n useEffect(() => {\n // a press inside the prompt's mention menu (a portal on the body) is not \"outside\"\n const onDown = (e) => {\n if (ref.current && !ref.current.contains(e.target) && !(e.target.closest && e.target.closest('.uic-pop'))) onClose();\n };\n window.addEventListener('mousedown', onDown);\n return () => window.removeEventListener('mousedown', onDown);\n }, [onClose]);\n\n // What the prompt may read: the columns to the LEFT of this one (a row fills left to right,\n // so those hold values when this cell computes). The rest are shown, but say why not.\n const promptItems = useMemo(() => {\n const at = columns.findIndex((c) => c.id === col.id);\n return columns.filter((c) => c.id !== col.id).map((c) => {\n const idx = columns.findIndex((x) => x.id === c.id);\n const right = at >= 0 && idx > at;\n return {\n id: c.id, name: c.name, kind: c.type, section: right ? 'Fills after this column' : 'Columns',\n icon: TYPE_GLYPH[c.type] || 'Aa', description: TYPE_LABEL[c.type] || c.type,\n color: c.type === 'compute' ? '#7C3AED' : undefined,\n disabled: right ? 'to the right' : false,\n };\n });\n }, [columns, col.id]);\n\n const apply = () => {\n const patch = { type };\n // A value with a chosen color travels as {label, color}; the rest as labels.\n patch.options = values.map((v) => (v.color ? { label: v.label, color: v.color } : v.label));\n if (type === 'compute') {\n const compute = { kind, deps: [...deps] };\n if (kind === 'prompt') compute.prompt = prompt;\n if (kind === 'harness') { compute.harness_id = harnessId; compute.prompt = prompt; }\n if (kind === 'workflow') { compute.workflow_slug = wfSlug; compute.output_key = outKey; }\n patch.compute = compute;\n }\n onApply(patch);\n };\n\n return (\n <PopPortal anchor={anchor} width={250} estHeight={340} className=\"shg-menu\" onClose={onClose}>\n <div ref={ref} onClick={(e) => e.stopPropagation()}>\n <label className=\"shg-menu-lbl\">Type\n <select className=\"shg-menu-input\" value={type} onChange={(e) => setType(e.target.value)}>\n {MANUAL_TYPES.map((t) => <option key={t} value={t}>{TYPE_LABEL[t]}</option>)}\n <option value=\"compute\">Computed</option>\n </select>\n </label>\n\n <div className=\"shg-menu-lbl\">{type === 'select' || type === 'tags' ? 'Options' : 'Values'}\n <ValuePills values={values} onChange={setValues} />\n </div>\n\n {type === 'compute' && (\n <>\n <label className=\"shg-menu-lbl\">Runs\n <select className=\"shg-menu-input\" value={kind} onChange={(e) => setKind(e.target.value)}>\n {COMPUTE_KINDS.map((k) => <option key={k.kind} value={k.kind}>{k.label}</option>)}\n </select>\n </label>\n {(kind === 'prompt' || kind === 'harness') && (\n <div className=\"shg-menu-lbl\">Prompt\n <div className=\"shg-menu-input shg-menu-prompt\">\n <MentionInput\n value={prompt}\n onChange={(v, ms) => { setPrompt(v); setDeps(new Set(ms.map((m) => m.id))); }}\n items={promptItems}\n placeholder=\"Summarize @Company in one line\"\n menuTitle=\"Columns this cell can read\"\n emptyText=\"No column by that name\"\n label=\"Prompt\"\n />\n </div>\n <div className=\"shg-menu-hint\">Type @ to add a column from this row. Columns to the left fill first.</div>\n </div>\n )}\n {kind === 'harness' && (\n <label className=\"shg-menu-lbl\">Agent id\n <input className=\"shg-menu-input\" value={harnessId} onChange={(e) => setHarnessId(e.target.value)} placeholder=\"chrn_…\" />\n </label>\n )}\n {kind === 'workflow' && (\n <>\n <label className=\"shg-menu-lbl\">Workflow id\n <input className=\"shg-menu-input\" value={wfSlug} onChange={(e) => setWfSlug(e.target.value)} placeholder=\"my-workflow\" />\n </label>\n <label className=\"shg-menu-lbl\">Output key (optional)\n <input className=\"shg-menu-input\" value={outKey} onChange={(e) => setOutKey(e.target.value)} placeholder=\"summary\" />\n </label>\n </>\n )}\n </>\n )}\n\n <div className=\"shg-menu-actions\">\n <button className=\"shg-menu-del\" onClick={onDelete}>Delete column</button>\n <button className=\"shg-menu-apply\" onClick={apply}>Apply</button>\n </div>\n </div>\n </PopPortal>\n );\n}\n\n// ── Export helpers (CSV / TSV / array-of-arrays) ─────────────────────────────\nexport function sheetToDelimited(sheet, sep = ',') {\n const cols = sheet?.columns || [];\n const rows = sheet?.rows || [];\n const cells = sheet?.cells || {};\n const esc = (v) => {\n const s = v == null ? '' : (Array.isArray(v) ? v.join(', ') : (typeof v === 'object' ? JSON.stringify(v) : String(v)));\n if (sep === ',' && /[\",\\n]/.test(s)) return `\"${s.replace(/\"/g, '\"\"')}\"`;\n return s;\n };\n const header = cols.map((c) => esc(c.name)).join(sep);\n const body = rows.map((r) => cols.map((c) => {\n const cell = cells[cellKey(r.id, c.id)];\n return esc(cell ? cell.value : '');\n }).join(sep));\n return [header, ...body].join('\\n');\n}\n\n/** Rows as an array-of-arrays (header first) — feed to an xlsx writer. */\nexport function sheetToAoA(sheet) {\n const cols = sheet?.columns || [];\n const rows = sheet?.rows || [];\n const cells = sheet?.cells || {};\n const val = (v) => (v == null ? '' : (Array.isArray(v) ? v.join(', ') : (typeof v === 'object' ? JSON.stringify(v) : v)));\n return [cols.map((c) => c.name),\n ...rows.map((r) => cols.map((c) => val(cells[cellKey(r.id, c.id)]?.value)))];\n}\n","// MentionInput — a text field that can hold people, columns, files: anything a host offers.\n//\n// Type the trigger (\"@\" by default) and a menu opens at the caret with the host's items, searched\n// as you type (name, description, keywords). Pick one and it becomes a pill in the text: one\n// unit to the caret and to Backspace, with its icon and name, tinted by kind. Underneath, the\n// value is a plain string in the host's token format ({{Name}} for a sheet prompt, @Name for a\n// chat message) and a `mentions` list rides beside it, so a host never parses text to learn who\n// was mentioned. Loading a value turns the tokens it can resolve back into pills.\n//\n// items [{ id, name, kind?, section?, description?, keywords?, icon?, avatar?, color?,\n// disabled? (true | 'reason'), tag? }] the menu, in the host's order\n// format { open, close } token spelling; CURLY ({{Name}}) by default, AT for @Name\n// trigger the character that opens the menu ('@')\n// onChange(value, mentions)\n// onSubmit() when given with submitOnEnter, Enter submits and Shift+Enter breaks the line\n// ref { focus(), insertMention(item), clear(), el }\n//\n// The editor is a contentEditable whose DOM is read back into the model on every input; the\n// menu is a Popover anchored to the caret. No dependency beyond react and react-dom.\nimport React, { forwardRef, useCallback, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState } from 'react';\nimport { Popover } from '../components/Popover.jsx';\nimport { CURLY, makeResolver, parseValue, serializeSegments, mentionsOf, groupItems, activeTrigger } from './mentionModel.js';\n\nconst MENTION_ATTR = 'data-mention-id';\n\nfunction monogram(name) {\n const parts = String(name || '').trim().split(/\\s+/).filter(Boolean);\n return ((parts[0] || '')[0] || '') + ((parts[1] || '')[0] || '') || '?';\n}\n\n// The pill, as a DOM node (the editor is not React-managed inside).\nexport function buildPillNode(item) {\n const el = document.createElement('span');\n el.className = 'uic-mention';\n el.setAttribute(MENTION_ATTR, item.id);\n el.setAttribute('data-name', item.name);\n if (item.kind) el.setAttribute('data-kind', item.kind);\n el.setAttribute('contenteditable', 'false');\n if (item.description) el.title = item.description;\n if (item.color) el.style.setProperty('--uic-mention-color', item.color);\n const ic = document.createElement('span');\n ic.className = 'uic-mention-ic';\n if (item.avatar) { const img = document.createElement('img'); img.src = item.avatar; img.alt = ''; ic.appendChild(img); }\n else { ic.textContent = typeof item.icon === 'string' && item.icon ? item.icon : monogram(item.name); if (!(typeof item.icon === 'string' && item.icon)) ic.classList.add('is-mono'); }\n const nm = document.createElement('span');\n nm.className = 'uic-mention-name';\n nm.textContent = item.name;\n el.appendChild(ic);\n el.appendChild(nm);\n return el;\n}\n\n// DOM -> segments. Text nodes are text, <br> and block boundaries are line breaks, a pill is a\n// mention; the browser's own trailing <br> (it keeps one so the last empty line can be reached)\n// is not a newline of the user's.\nfunction readSegments(root, resolver) {\n const out = [];\n let buf = '';\n const flush = () => { if (buf) { out.push({ type: 'text', text: buf }); buf = ''; } };\n const walk = (node, isLastAtRoot) => {\n const kids = Array.from(node.childNodes);\n kids.forEach((k, i) => {\n const last = isLastAtRoot && i === kids.length - 1;\n // a contentEditable writes a trailing space as a no-break space; the value keeps plain ones\n if (k.nodeType === 3) { buf += k.data.replace(/\\u00a0/g, ' '); return; }\n if (k.nodeType !== 1) return;\n const tag = k.tagName;\n if (tag === 'BR') { if (!last) buf += '\\n'; return; }\n if (k.hasAttribute(MENTION_ATTR)) {\n flush();\n const id = k.getAttribute(MENTION_ATTR);\n const name = k.getAttribute('data-name') || '';\n const item = resolver.get(name) || { id, name, kind: k.getAttribute('data-kind') || null };\n out.push({ type: 'mention', id: item.id, name: item.name, kind: item.kind || null, item });\n return;\n }\n if (tag === 'DIV' || tag === 'P') {\n // a block after other content starts a new line\n if (out.length || buf) buf += '\\n';\n walk(k, last);\n return;\n }\n walk(k, last);\n });\n };\n walk(root, true);\n flush();\n return out;\n}\n\n// segments -> DOM\nfunction writeSegments(root, segments) {\n root.textContent = '';\n for (const s of segments) {\n if (s.type === 'mention') { root.appendChild(buildPillNode(s.item || s)); continue; }\n const lines = String(s.text).split('\\n');\n lines.forEach((line, i) => {\n if (i > 0) root.appendChild(document.createElement('br'));\n if (line) root.appendChild(document.createTextNode(line));\n });\n }\n // the reachable last line\n root.appendChild(document.createElement('br'));\n}\n\nfunction placeCaretAfter(node) {\n const sel = window.getSelection();\n if (!sel) return;\n const r = document.createRange();\n r.setStartAfter(node);\n r.collapse(true);\n sel.removeAllRanges();\n sel.addRange(r);\n}\n\nfunction selectionIn(root) {\n const sel = typeof window !== 'undefined' ? window.getSelection() : null;\n if (!sel || !sel.rangeCount) return null;\n const r = sel.getRangeAt(0);\n if (!root.contains(r.startContainer)) return null;\n return { sel, range: r };\n}\n\nexport const MentionInput = forwardRef(function MentionInput(props, ref) {\n const {\n value = '', onChange, items = [], format = CURLY, trigger = '@', placeholder, disabled = false,\n onSubmit, submitOnEnter = false, autoFocus = false, className = '', label, menuWidth = 360,\n menuTitle, emptyText = 'No match', renderIcon, onOpenChange, onFocus, onBlur, onKeyDown, id,\n } = props;\n const editorRef = useRef(null);\n const resolver = useMemo(() => makeResolver(items), [items]);\n const [menu, setMenu] = useState(null); // { node, start, query, rect }\n const [active, setActive] = useState(0);\n const [empty, setEmpty] = useState(!value);\n const listId = useMemo(() => `uic-mention-${Math.random().toString(36).slice(2, 8)}`, []);\n\n // ── model <-> DOM ──\n const emit = useCallback(() => {\n const root = editorRef.current;\n if (!root) return;\n const segs = readSegments(root, resolver);\n const next = serializeSegments(segs, format);\n setEmpty(!next);\n if (onChange) onChange(next, mentionsOf(segs));\n }, [resolver, format, onChange]);\n\n // A value that arrives from outside (a reset after send, a loaded prompt) is drawn; the one\n // the editor just emitted is already on screen, so the caret is left alone.\n useLayoutEffect(() => {\n const root = editorRef.current;\n if (!root) return;\n const current = serializeSegments(readSegments(root, resolver), format);\n if (current === (value || '')) return;\n writeSegments(root, parseValue(value || '', format, resolver));\n setEmpty(!value);\n }, [value, resolver, format]);\n\n useEffect(() => { if (autoFocus && editorRef.current) editorRef.current.focus(); }, [autoFocus]);\n\n // ── the menu at the caret ──\n const closeMenu = useCallback(() => setMenu(null), []);\n useEffect(() => { if (onOpenChange) onOpenChange(!!menu); }, [menu, onOpenChange]);\n const groups = useMemo(() => (menu ? groupItems(items, menu.query) : []), [items, menu]);\n const flat = useMemo(() => groups.flatMap((g) => g.items), [groups]);\n useEffect(() => { setActive(0); }, [menu && menu.query, groups.length]);\n\n const syncMenu = useCallback(() => {\n const root = editorRef.current;\n const s = root && selectionIn(root);\n if (!s || !s.range.collapsed) { setMenu(null); return; }\n const node = s.range.startContainer;\n if (node.nodeType !== 3) { setMenu(null); return; }\n const hit = activeTrigger(node.data.slice(0, s.range.startOffset), trigger);\n if (!hit) { setMenu(null); return; }\n const r = document.createRange();\n r.setStart(node, hit.start);\n r.setEnd(node, Math.min(node.data.length, hit.start + 1));\n const rect = r.getBoundingClientRect();\n setMenu({ node, start: hit.start, query: hit.query, rect: rect.width || rect.height ? rect : root.getBoundingClientRect() });\n }, [trigger]);\n\n const anchorRef = useMemo(() => ({\n current: {\n getBoundingClientRect: () => (menu ? menu.rect : new DOMRect()),\n contains: () => false,\n },\n }), [menu]);\n\n const insertPill = useCallback((item, replace) => {\n const root = editorRef.current;\n if (!root || !item || item.disabled) return;\n const pill = buildPillNode(item);\n const space = document.createTextNode(' ');\n if (replace && replace.node && replace.node.parentNode === root) {\n const { node, start, query } = replace;\n node.deleteData(start, trigger.length + query.length);\n const after = node.splitText(start);\n root.insertBefore(pill, after);\n root.insertBefore(space, after);\n } else {\n const s = selectionIn(root);\n if (s) { s.range.deleteContents(); s.range.insertNode(space); s.range.insertNode(pill); }\n else { root.appendChild(pill); root.appendChild(space); }\n }\n placeCaretAfter(space);\n setMenu(null);\n emit();\n }, [emit, trigger]);\n\n const pick = useCallback((item) => insertPill(item, menu), [insertPill, menu]);\n\n const insertText = useCallback((text) => {\n const root = editorRef.current;\n if (!root) return;\n root.focus();\n let done = false;\n try { done = document.execCommand('insertText', false, text); } catch { done = false; }\n if (!done) {\n const s = selectionIn(root);\n const tn = document.createTextNode(text);\n if (s) { s.range.deleteContents(); s.range.insertNode(tn); placeCaretAfter(tn); }\n else root.appendChild(tn);\n }\n emit();\n syncMenu();\n }, [emit, syncMenu]);\n\n // Markdown helpers for a host's formatting row: wrap what is selected (or leave the caret\n // between the marks), or start the current line with a prefix.\n const wrapSelection = useCallback((before, after = '') => {\n const root = editorRef.current;\n if (!root) return;\n root.focus();\n const s = selectionIn(root);\n const selected = s ? s.range.toString() : '';\n insertText(before + selected + after);\n if (!selected && after) {\n const sel = window.getSelection();\n for (let i = 0; i < after.length; i++) sel && sel.modify && sel.modify('move', 'backward', 'character');\n }\n }, [insertText]);\n const prefixLine = useCallback((prefix) => {\n const root = editorRef.current;\n if (!root) return;\n root.focus();\n const s = selectionIn(root);\n const node = s && s.range.startContainer;\n const before = node && node.nodeType === 3 ? node.data.slice(0, s.range.startOffset) : '';\n const atLineStart = !before || /\\n$/.test(before) || (node && node.nodeType !== 3);\n insertText((atLineStart ? '' : '\\n') + prefix);\n }, [insertText]);\n\n useImperativeHandle(ref, () => ({\n focus: () => editorRef.current && editorRef.current.focus(),\n clear: () => { const root = editorRef.current; if (root) { writeSegments(root, []); emit(); } },\n insertMention: (item) => insertPill(item, null),\n insertText,\n wrapSelection,\n prefixLine,\n get el() { return editorRef.current; },\n }), [emit, insertPill, insertText, wrapSelection, prefixLine]);\n\n // ── events ──\n const handleInput = () => { emit(); syncMenu(); };\n const handleKeyDown = (e) => {\n if (onKeyDown) onKeyDown(e);\n if (e.defaultPrevented) return;\n if (menu) {\n if (e.key === 'ArrowDown') { e.preventDefault(); setActive((a) => (flat.length ? (a + 1) % flat.length : 0)); return; }\n if (e.key === 'ArrowUp') { e.preventDefault(); setActive((a) => (flat.length ? (a - 1 + flat.length) % flat.length : 0)); return; }\n if ((e.key === 'Enter' || e.key === 'Tab') && flat.length) { e.preventDefault(); pick(flat[active]); return; }\n if (e.key === 'Escape') { e.preventDefault(); setMenu(null); return; }\n }\n if (e.key === 'Enter') {\n if (submitOnEnter && !e.shiftKey) { e.preventDefault(); if (onSubmit) onSubmit(); return; }\n e.preventDefault();\n insertText('\\n');\n }\n };\n const handlePaste = (e) => {\n e.preventDefault();\n const text = (e.clipboardData && e.clipboardData.getData('text/plain')) || '';\n if (!text) return;\n // pasted tokens the host knows become pills, the rest stays text\n const segs = parseValue(text, format, resolver);\n if (segs.every((s) => s.type === 'text')) { insertText(text); return; }\n const root = editorRef.current;\n const s = selectionIn(root);\n if (!s) { insertText(text); return; }\n s.range.deleteContents();\n const frag = document.createDocumentFragment();\n let lastNode = null;\n for (const seg of segs) {\n if (seg.type === 'mention') { lastNode = buildPillNode(seg.item || seg); frag.appendChild(lastNode); continue; }\n seg.text.split('\\n').forEach((line, i) => {\n if (i > 0) { lastNode = document.createElement('br'); frag.appendChild(lastNode); }\n if (line) { lastNode = document.createTextNode(line); frag.appendChild(lastNode); }\n });\n }\n s.range.insertNode(frag);\n if (lastNode) placeCaretAfter(lastNode);\n emit();\n syncMenu();\n };\n const handleBlur = (e) => { if (onBlur) onBlur(e); };\n const handleFocus = (e) => { if (onFocus) onFocus(e); };\n\n // the caret moving away from the trigger (a click, an arrow) closes the menu\n useEffect(() => {\n if (!menu) return undefined;\n const onSel = () => syncMenu();\n document.addEventListener('selectionchange', onSel);\n return () => document.removeEventListener('selectionchange', onSel);\n }, [menu, syncMenu]);\n\n // the active option stays in view: the list scrolls, never the page (scrollIntoView can\n // move the document under a host that watches it)\n useEffect(() => {\n if (!menu) return;\n const el = document.getElementById(`${listId}-${active}`);\n const list = el && el.closest('.uic-mention-menu');\n if (!el || !list) return;\n const top = el.offsetTop - list.offsetTop;\n const bottom = top + el.offsetHeight;\n if (top < list.scrollTop) list.scrollTop = top;\n else if (bottom > list.scrollTop + list.clientHeight) list.scrollTop = bottom - list.clientHeight;\n }, [active, menu, listId]);\n\n const iconOf = (item) => {\n if (renderIcon) { const n = renderIcon(item); if (n) return n; }\n if (item.avatar) return <img src={item.avatar} alt=\"\" />;\n if (typeof item.icon === 'string' && item.icon) return item.icon;\n if (item.icon) return item.icon;\n return <span className=\"is-mono\">{monogram(item.name)}</span>;\n };\n\n let index = -1;\n return (\n <div className={['uic-mention-field', disabled ? 'is-disabled' : '', className].filter(Boolean).join(' ')}>\n <div\n ref={editorRef}\n id={id}\n className={'uic-mention-editor' + (empty ? ' is-empty' : '')}\n contentEditable={!disabled}\n suppressContentEditableWarning\n role=\"textbox\"\n aria-multiline=\"true\"\n aria-label={label}\n aria-autocomplete=\"list\"\n aria-expanded={!!menu}\n aria-controls={menu ? listId : undefined}\n aria-activedescendant={menu && flat.length ? `${listId}-${active}` : undefined}\n data-placeholder={placeholder || ''}\n spellCheck=\"true\"\n onInput={handleInput}\n onKeyDown={handleKeyDown}\n onPaste={handlePaste}\n onFocus={handleFocus}\n onBlur={handleBlur}\n />\n <Popover open={!!menu} anchorRef={anchorRef} onClose={closeMenu} width={menuWidth} minHeight={120} className=\"uic-mention-pop\" label={menuTitle || 'Mentions'}>\n <div className=\"uic-mention-menu\" role=\"listbox\" id={listId} onMouseDown={(e) => e.preventDefault()}>\n {menuTitle ? <div className=\"uic-mention-head\">{menuTitle}</div> : null}\n {groups.map((g) => (\n <div className=\"uic-mention-group\" key={g.section || '_'}>\n {g.section ? <div className=\"uic-mention-sec\">{g.section}</div> : null}\n {g.items.map((item) => {\n index += 1;\n const i = index;\n const dis = !!item.disabled;\n const reason = typeof item.disabled === 'string' ? item.disabled : null;\n return (\n <button\n key={item.id} type=\"button\" id={`${listId}-${i}`} role=\"option\" aria-selected={i === active} aria-disabled={dis || undefined}\n className={'uic-mention-item' + (i === active ? ' is-active' : '') + (dis ? ' is-disabled' : '')}\n style={item.color ? { '--uic-mention-color': item.color } : undefined}\n onMouseEnter={() => setActive(i)}\n onClick={() => { if (!dis) pick(item); }}\n >\n <span className=\"uic-mention-ic\">{iconOf(item)}</span>\n <span className=\"uic-mention-text\">\n <span className=\"uic-mention-name\">{item.name}</span>\n {item.description ? <span className=\"uic-mention-desc\">{item.description}</span> : null}\n </span>\n {reason || item.tag ? <span className=\"uic-mention-tag\">{reason || item.tag}</span> : null}\n </button>\n );\n })}\n </div>\n ))}\n {!flat.length ? <div className=\"uic-mention-empty\">{emptyText}</div> : null}\n </div>\n </Popover>\n </div>\n );\n});\n\n// Read-only: a stored value drawn with its pills, for a message or a preview.\nexport function MentionText({ value, items = [], format = CURLY, className = '', renderIcon }) {\n const resolver = useMemo(() => makeResolver(items), [items]);\n const segs = useMemo(() => parseValue(value || '', format, resolver), [value, format, resolver]);\n return (\n <span className={['uic-mention-text-view', className].filter(Boolean).join(' ')}>\n {segs.map((s, i) => {\n if (s.type === 'text') return <React.Fragment key={i}>{s.text}</React.Fragment>;\n const item = s.item || s;\n const icon = renderIcon ? renderIcon(item) : null;\n return (\n <span key={i} className=\"uic-mention\" data-kind={s.kind || undefined} title={item.description || undefined}\n style={item.color ? { '--uic-mention-color': item.color } : undefined}>\n <span className={'uic-mention-ic' + (icon || (typeof item.icon === 'string' && item.icon) || item.avatar ? '' : ' is-mono')}>\n {icon || (item.avatar ? <img src={item.avatar} alt=\"\" /> : (typeof item.icon === 'string' && item.icon ? item.icon : monogram(item.name)))}\n </span>\n <span className=\"uic-mention-name\">{s.name}</span>\n </span>\n );\n })}\n </span>\n );\n}\n","// Popover — a panel anchored to a control: a menu, a picker, a row's overflow actions.\n//\n// Ten of these were hand-rolled across four apps, each with its own mousedown-outside listener,\n// and exactly ONE of the ten survived a 390px viewport: the other nine positioned themselves with\n// `position: absolute; bottom: 36px` and either ran off the screen or grew taller than it. That\n// one implementation's placement logic is what this component is, so placement is built IN and\n// is not separately exportable — a hook you can skip is how you ship the other nine again.\n//\n// It portals to the body and positions itself `fixed`, so it is never clipped by an ancestor's\n// overflow (the reason the absolute ones lived inside their own scroll containers).\nimport React, { useCallback, useEffect, useRef, useState } from 'react';\nimport { createPortal } from 'react-dom';\nimport { useOverlayEscape } from './overlay.js';\n\nconst GAP = 6; // between the anchor and the panel\nconst MARGIN = 8; // minimum clearance from the viewport edge\n\n/**\n * open render it\n * anchorRef ref to the control it belongs to; the panel positions against its box\n * onClose Escape, an outside pointerdown, or the caller's own reason\n * width preferred width; clamped to the viewport\n * minHeight never squeeze below this — flip to the other side instead\n * placement 'auto' (default) picks the side with more room; 'above'/'below' force one\n */\nexport function Popover(props) {\n const { open, anchorRef, onClose, width = 280, minHeight = 140, placement = 'auto',\n children, className, label } = props;\n const popRef = useRef(null);\n const [pos, setPos] = useState(null);\n\n useEffect(() => {\n if (!open) { setPos(null); return undefined; }\n const place = () => {\n const el = anchorRef?.current;\n if (!el) return;\n const r = el.getBoundingClientRect();\n const vw = window.innerWidth;\n const vh = window.innerHeight;\n const w = Math.min(width, vw - MARGIN * 2);\n const below = vh - r.bottom - GAP - MARGIN;\n const above = r.top - GAP - MARGIN;\n const up = placement === 'above'\n || (placement === 'auto' && below < minHeight && above > below);\n const maxHeight = Math.max(minHeight, Math.floor(up ? above : below));\n const left = Math.max(MARGIN, Math.min(r.left, vw - w - MARGIN));\n setPos(up\n ? { left, bottom: Math.round(vh - r.top + GAP), width: w, maxHeight }\n : { left, top: Math.round(r.bottom + GAP), width: w, maxHeight });\n };\n place();\n window.addEventListener('resize', place);\n // Capture phase: the anchor is usually inside a scrolling pane, and a scroll event on that\n // pane does not bubble to the window.\n window.addEventListener('scroll', place, true);\n return () => {\n window.removeEventListener('resize', place);\n window.removeEventListener('scroll', place, true);\n };\n }, [open, anchorRef, width, minHeight, placement]);\n\n useEffect(() => {\n if (!open) return undefined;\n const onDown = (e) => {\n if (popRef.current?.contains(e.target)) return;\n // The anchor closes it through its own onClick; treating the press as \"outside\" here would\n // close and immediately reopen it.\n if (anchorRef?.current?.contains(e.target)) return;\n onClose?.();\n };\n document.addEventListener('pointerdown', onDown);\n return () => document.removeEventListener('pointerdown', onDown);\n }, [open, anchorRef, onClose]);\n\n const escape = useCallback(() => onClose?.(), [onClose]);\n useOverlayEscape(open, escape);\n\n if (!open || !pos || typeof document === 'undefined') return null;\n return createPortal(\n <div ref={popRef} className={['uic-pop', className || ''].filter(Boolean).join(' ')}\n style={pos} role=\"dialog\" aria-label={label}>\n {children}\n </div>,\n document.body,\n );\n}\n","// The mention model: what a mention input holds, how it is written down, and how a menu is\n// searched. Pure functions, no DOM, no React, so the same code serves the editor, the\n// read-only renderer of a stored message, and a test.\n//\n// A value is a plain string with tokens in it. The token format belongs to the host:\n// { open: '{{', close: '}}' } a sheet prompt: \"Grade {{Answer}} against {{Gold}}\"\n// { open: '@', close: '' } a chat message: \"@Project Manager can you take CT-281\"\n// A token names the item (its `name`), so the string stays readable wherever it travels, and\n// the editor keeps a `mentions` list beside it ({id, name, kind}) so a host never parses text\n// to learn who was mentioned.\n\nexport const CURLY = Object.freeze({ open: '{{', close: '}}' });\nexport const AT = Object.freeze({ open: '@', close: '' });\n// A chat message carries the id too, as a markdown link a sanitizer lets through:\n// [@Project Manager](#m-member.bot.project_manager)\nexport const CHAT_LINK = Object.freeze({\n write: (item) => `[@${item.name}](#m-${item.id})`,\n pattern: /\\[@(?<name>[^\\]\\n]+)\\]\\(#m-(?<id>[^)\\s]+)\\)/g,\n});\n\n/** A resolver answers `name -> item | null`. Built from the items a host offers, longest names\n * first, so \"@Project Manager\" is not read as \"@Project\" + \" Manager\". */\nexport function makeResolver(items) {\n const byName = new Map();\n const byId = new Map();\n for (const it of items || []) {\n if (!it) continue;\n if (it.name) byName.set(it.name, it);\n if (it.id != null) byId.set(String(it.id), it);\n }\n const names = [...byName.keys()].sort((a, b) => b.length - a.length);\n return { get: (name) => byName.get(name) || null, byId: (id) => byId.get(String(id)) || null, names };\n}\n\n// A token spelled with its id parses even when the item is not offered any more (a member who\n// left, a column since renamed): the name in the token is what is shown.\nfunction parsePattern(text, format, resolver) {\n const out = [];\n const re = new RegExp(format.pattern.source, format.pattern.flags.includes('g') ? format.pattern.flags : format.pattern.flags + 'g');\n let last = 0;\n let m;\n while ((m = re.exec(text))) {\n if (m.index > last) out.push({ type: 'text', text: text.slice(last, m.index) });\n const id = m.groups && m.groups.id != null ? m.groups.id : null;\n const name = (m.groups && m.groups.name) || '';\n const item = (id != null && resolver && resolver.byId(id)) || (resolver && resolver.get(name)) || { id: id ?? name, name, kind: null };\n out.push({ type: 'mention', id: item.id, name: item.name || name, kind: item.kind || null, item });\n last = m.index + m[0].length;\n }\n if (last < text.length) out.push({ type: 'text', text: text.slice(last) });\n return out;\n}\n\n/** value -> segments: [{ type: 'text', text }] and [{ type: 'mention', id, name, kind, item }].\n * Only names the resolver knows become mentions; anything else stays text, verbatim. */\nexport function parseValue(value, format, resolver) {\n const text = value == null ? '' : String(value);\n if (format && format.pattern) return parsePattern(text, format, resolver);\n const { open, close } = format || CURLY;\n const out = [];\n let buf = '';\n let i = 0;\n const flush = () => { if (buf) { out.push({ type: 'text', text: buf }); buf = ''; } };\n while (i < text.length) {\n if (resolver && text.startsWith(open, i)) {\n // At a word boundary for the bare \"@\" form: \"email@host\" is not a mention.\n const boundary = close ? true : (i === 0 || /[\\s([{\"'>]/.test(text[i - 1]));\n let hit = null;\n if (boundary) {\n for (const name of resolver.names) {\n const start = i + open.length;\n if (text.startsWith(name, start)) {\n const end = start + name.length;\n if (!close || text.startsWith(close, end)) {\n // the bare form must end at a word boundary too\n if (close || end === text.length || /[\\s.,;:!?)\\]}\"']/.test(text[end])) { hit = { name, end: end + close.length }; break; }\n }\n }\n }\n }\n if (hit) {\n flush();\n const item = resolver.get(hit.name);\n out.push({ type: 'mention', id: item.id, name: item.name, kind: item.kind || null, item });\n i = hit.end;\n continue;\n }\n }\n buf += text[i];\n i += 1;\n }\n flush();\n return out;\n}\n\n/** segments -> value string in the host's format. */\nexport function serializeSegments(segments, format) {\n const f = format || CURLY;\n if (f.write) return (segments || []).map((s) => (s.type === 'mention' ? f.write(s.item || s) : s.text)).join('');\n const { open, close } = f;\n return (segments || []).map((s) => (s.type === 'mention' ? `${open}${s.name}${close}` : s.text)).join('');\n}\n\n/** The distinct mentions in a segment list, in order of first appearance. */\nexport function mentionsOf(segments) {\n const seen = new Set();\n const out = [];\n for (const s of segments || []) {\n if (s.type !== 'mention' || seen.has(s.id)) continue;\n seen.add(s.id);\n out.push({ id: s.id, name: s.name, kind: s.kind || null });\n }\n return out;\n}\n\n// ── search ──────────────────────────────────────────────────────────────────\n// Free text over name, description and keywords. A name that starts with the query ranks\n// first, then a word of the name, then anything containing it, then a subsequence (typing\n// \"pm\" finds \"Project Manager\"); a description or keyword match trails the name matches.\nfunction norm(s) { return String(s || '').toLowerCase(); }\n\nfunction subsequence(hay, needle) {\n let j = 0;\n for (let i = 0; i < hay.length && j < needle.length; i++) if (hay[i] === needle[j]) j++;\n return j === needle.length;\n}\n\nexport function scoreItem(item, query) {\n const q = norm(query).trim();\n if (!q) return 1;\n const name = norm(item.name);\n if (name === q) return 120;\n if (name.startsWith(q)) return 100;\n if (name.split(/[\\s_-]+/).some((w) => w.startsWith(q))) return 80;\n if (name.includes(q)) return 60;\n const initials = name.split(/[\\s_-]+/).map((w) => w[0]).join('');\n if (initials.startsWith(q)) return 50;\n if (subsequence(name, q)) return 30;\n const desc = norm(item.description);\n if (desc && desc.includes(q)) return 20;\n const kws = (item.keywords || []).map(norm);\n if (kws.some((k) => k.includes(q))) return 15;\n return 0;\n}\n\n/** Items that match, best first, stable within a score (host order wins ties). */\nexport function searchItems(items, query) {\n const scored = (items || []).map((it, i) => ({ it, i, s: scoreItem(it, query) })).filter((x) => x.s > 0);\n scored.sort((a, b) => b.s - a.s || a.i - b.i);\n return scored.map((x) => x.it);\n}\n\n/** Matching items grouped by section, sections in the order the host listed them\n * (items without a section share the unnamed group, first). */\nexport function groupItems(items, query) {\n const groups = new Map();\n for (const it of searchItems(items, query)) {\n const key = it.section || '';\n if (!groups.has(key)) groups.set(key, []);\n groups.get(key).push(it);\n }\n const order = [''];\n for (const it of items || []) { const k = it.section || ''; if (!order.includes(k)) order.push(k); }\n return order.filter((k) => groups.has(k)).map((k) => ({ section: k, items: groups.get(k) }));\n}\n\n/** Where a trigger is live in a piece of text ending at the caret: the query typed after it,\n * or null. A trigger counts only at a word start and only while the query has no line break\n * and is not too long to be a name someone is still typing. */\nexport function activeTrigger(textBeforeCaret, trigger = '@', maxLen = 48) {\n const at = textBeforeCaret.lastIndexOf(trigger);\n if (at < 0) return null;\n if (at > 0 && !/[\\s([{\"'>]/.test(textBeforeCaret[at - 1])) return null;\n const query = textBeforeCaret.slice(at + trigger.length);\n if (query.length > maxLen || /\\n/.test(query)) return null;\n return { start: at, query };\n}\n","// One palette for everyone who shows up in a shared document: the cursor in a\n// doc, the selection in a sheet, the drag on a graph canvas. A person's color\n// comes from their member id, so they look the same in every surface and to\n// every viewer, with no per-document assignment to disagree.\nexport const PEER_PALETTE = ['#1e40af', '#c2410c', '#15803d', '#6d28d9', '#be123c', '#0e7490', '#a16207', '#4338ca'];\n\nexport function peerColor(key) {\n let h = 0;\n for (const ch of String(key || '')) h = (h * 31 + ch.charCodeAt(0)) >>> 0;\n return PEER_PALETTE[h % PEER_PALETTE.length];\n}\n\n/** rgba() of a #rrggbb color. */\nexport function withAlpha(hex, alpha) {\n const m = /^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(String(hex || ''));\n if (!m) return hex;\n return `rgba(${parseInt(m[1], 16)}, ${parseInt(m[2], 16)}, ${parseInt(m[3], 16)}, ${alpha})`;\n}\n","// The coloured file-type glyph — pdf red, docx blue, xlsx green, pptx orange, py yellow.\n//\n// react-file-icon is the standard library for this and it is already what the HarnessRouter\n// console draws, so a file looks the same wherever it appears: a card under an answer, a card in\n// a spreadsheet cell, the header of a preview pane. Redrawing these per surface is how two\n// products end up disagreeing about what a .pptx looks like.\n//\n// The dependency is OPTIONAL. Where it is absent the extension is drawn as a plain badge rather\n// than nothing, because a file with no glyph still needs to be identifiable.\nimport { useEffect, useState } from 'react';\n\nexport function extOf(name) {\n const m = String(name || '').toLowerCase().match(/\\.([a-z0-9]+)$/);\n return m ? m[1] : '';\n}\n\nlet mod = null; // { FileIcon, defaultStyles } once resolved\nlet tried = false;\n\nexport function FileTypeIcon({ name, size = 36 }) {\n const [, force] = useState(0);\n const ext = extOf(name);\n\n useEffect(() => {\n if (tried || mod) return;\n tried = true;\n import('react-file-icon')\n .then((m) => { mod = m; force((n) => n + 1); })\n .catch(() => { /* not installed; the badge below is the answer */ });\n }, []);\n\n const box = { width: size, height: Math.round(size * 1.16), display: 'inline-block', flex: '0 0 auto' };\n\n if (!mod) {\n return (\n <span className=\"uic-fileglyph\" style={box} aria-hidden=\"true\">\n <span className=\"uic-fileglyph-ext\">{(ext || 'file').slice(0, 4)}</span>\n </span>\n );\n }\n const { FileIcon, defaultStyles } = mod;\n const style = defaultStyles?.[ext] || {};\n return (\n <span style={box}>\n <FileIcon extension={ext || undefined} {...style} />\n </span>\n );\n}\n","// One produced file, as a card: type glyph, name, what it is, download, preview.\n//\n// The same card under a chat answer and inside a spreadsheet cell. Those two started as different\n// things — a full-width row with a Preview button, and a bare text chip — which is how one surface\n// ends up with a download affordance the other never got.\n//\n// There is ONE card. There was briefly a `compact` variant for grid cells, which shrank the\n// actions to two 20px glyphs on a tinted background; it was a worse version of the thing it was\n// a variant of, which is what a variant usually is. A cell narrow enough to need a different card\n// is a cell too narrow to show the file at all — the name ellipsises and the card still works.\nimport { FileTypeIcon, extOf } from './FileTypeIcon.jsx';\nimport { IcDownload } from './icons.jsx';\n\n/** \"PPTX · output\" — what it is, then where it came from. `origin` is the caller's word. */\nfunction subtitle(name, origin, bytes) {\n const parts = [(extOf(name) || 'file').toUpperCase()];\n if (origin) parts.push(origin);\n if (bytes != null) parts.push(bytesLabel(bytes));\n return parts.join(' · ');\n}\n\nexport function bytesLabel(n) {\n if (n == null) return '';\n if (n < 1024) return `${n} B`;\n if (n < 1048576) return `${Math.round(n / 1024)} KB`;\n return `${(n / 1048576).toFixed(1)} MB`;\n}\n\nexport function FileCard({ name, origin = 'output', bytes, onPreview, onDownload, className = '' }) {\n // The whole card opens the preview, and the eye repeats it as an explicit target — a card that\n // is clickable without saying so is a card people do not click.\n const open = onPreview ? (e) => { e.stopPropagation(); onPreview(); } : undefined;\n return (\n <div className={'uic-filecard' + (open ? ' is-clickable' : '') + (className ? ' ' + className : '')}\n onClick={open}\n role={open ? 'button' : undefined}\n tabIndex={open ? 0 : undefined}\n onKeyDown={open ? (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); open(e); } } : undefined}\n title={name}>\n <span className=\"uic-filecard-ic\"><FileTypeIcon name={name} size={32} /></span>\n <span className=\"uic-filecard-meta\">\n <span className=\"uic-filecard-name\">{name}</span>\n <span className=\"uic-filecard-sub\">{subtitle(name, origin, bytes)}</span>\n </span>\n {onDownload && (\n <button type=\"button\" className=\"uic-filecard-dl\" aria-label={`Download ${name}`} title=\"Download\"\n onClick={(e) => { e.stopPropagation(); onDownload(); }}>\n <IcDownload size={18} />\n </button>\n )}\n {onPreview && (\n <button type=\"button\" className=\"uic-filecard-open\" aria-label={`Preview ${name}`} onClick={open}>\n Preview\n </button>\n )}\n </div>\n );\n}\n","// One produced file, rendered. Images, pdf, video, audio, Markdown, spreadsheets, delimited text\n// and code all render inline; anything else says so and offers the download.\n//\n// Ported from the HarnessRouter console, where it was already the answer, so a file previews the\n// same wherever it is opened. Two things changed on the way in, both because a package cannot\n// assume a product:\n//\n// - transport is injected. The console fetches with an auth header; a kit is same-origin and\n// needs none. `fetchFile` defaults to a plain fetch, which is right for same-origin callers.\n// - markdown, code and SPREADSHEETS render through props. The package does not depend on a\n// markdown library, and it already ships one code renderer (CodeBlock) — adding a second\n// highlighter to render the same text twice is the duplication this component exists to\n// argue against.\n//\n// `parseWorkbook` is the same rule, learned the hard way: this file used to `await\n// import('xlsx')` directly, which put a spreadsheet library in the dependency graph of every\n// app that imports anything from this package's root. A kit that shows slides, or charts,\n// and has never heard of a spreadsheet then fails to BUILD — Rollup cannot resolve a dynamic\n// import of a package that is not installed. The rule the chart entry states (\"an app that\n// imports a Button must not resolve a charting library\") was already being broken here.\n// Without the prop, spreadsheets fall through to the download, honestly labelled.\n//\n// `officePdfUrl` is how a caller offers a server-rendered PDF for formats no browser draws\n// (pptx, docx, odp). Without it those fall through to the download, honestly labelled.\nimport { useEffect, useState } from 'react';\nimport { FileTypeIcon, extOf } from './FileTypeIcon.jsx';\nimport { CodeBlock } from './CodeBlock.jsx';\nimport { IcDownload, IcX } from './icons.jsx';\n\nconst LANG = {\n js: 'javascript', mjs: 'javascript', cjs: 'javascript', jsx: 'javascript', ts: 'typescript',\n tsx: 'typescript', py: 'python', rb: 'ruby', go: 'go', rs: 'rust', java: 'java', c: 'c', h: 'c',\n cpp: 'cpp', hpp: 'cpp', cs: 'csharp', php: 'php', swift: 'swift', kt: 'kotlin', scala: 'scala',\n sh: 'bash', bash: 'bash', zsh: 'bash', sql: 'sql', css: 'css', scss: 'scss', less: 'less',\n html: 'xml', htm: 'xml', xml: 'xml', svg: 'xml', json: 'json', yaml: 'yaml', yml: 'yaml',\n toml: 'ini', ini: 'ini', r: 'r', lua: 'lua', pl: 'perl', dockerfile: 'dockerfile', diff: 'diff',\n md: 'markdown', txt: 'plaintext', log: 'plaintext', csv: 'plaintext',\n};\n\n// Presentations and word documents render faithfully through the server's PDF rendition.\n// Spreadsheets render as a real grid instead — a PDF of a sheet is the wrong mental model.\nconst OFFICE = new Set(['pptx', 'ppt', 'pptm', 'odp', 'doc', 'docx', 'odt', 'rtf']);\nconst SHEET = new Set(['xls', 'xlsx', 'xlsm', 'xlsb', 'ods']);\n\nfunction kindOf(name, mime = '') {\n const e = extOf(name);\n if (mime.startsWith('image/') || /^(png|jpe?g|gif|webp|svg|bmp|ico|avif)$/.test(e)) return 'image';\n if (mime === 'application/pdf' || e === 'pdf') return 'pdf';\n if (mime.startsWith('video/') || ['mp4', 'webm', 'mov', 'm4v'].includes(e)) return 'video';\n if (mime.startsWith('audio/') || ['mp3', 'wav', 'ogg', 'm4a', 'flac'].includes(e)) return 'audio';\n if (e === 'csv' || e === 'tsv') return 'csv';\n if (e === 'md' || e === 'markdown') return 'markdown';\n if (e === 'html' || e === 'htm') return 'html'; // the page itself, or its source: the header switches\n if (SHEET.has(e)) return 'sheet';\n if (OFFICE.has(e)) return 'office';\n if (mime.startsWith('text/') || LANG[e] || /^(txt|log|env|conf|cfg|gitignore)$/.test(e)) return 'code';\n return 'binary';\n}\n\nfunction delimitedToRows(text, sep) {\n return text.split(/\\r?\\n/).filter((l) => l.length).slice(0, 1000).map((line) => {\n const out = []; let cur = ''; let q = false;\n for (const ch of line) {\n if (ch === '\"') q = !q;\n else if (ch === sep && !q) { out.push(cur); cur = ''; }\n else cur += ch;\n }\n out.push(cur);\n return out.map((c) => c.replace(/^\"|\"$/g, ''));\n });\n}\n\nfunction Grid({ rows }) {\n if (!rows?.length) return <div className=\"uic-fp-empty\">This file is empty.</div>;\n const [head, ...body] = rows;\n return (\n <div className=\"uic-fp-sheet\">\n <table>\n <thead><tr>{head.map((c, i) => <th key={i}>{c}</th>)}</tr></thead>\n <tbody>{body.map((r, i) => <tr key={i}>{r.map((c, j) => <td key={j}>{c}</td>)}</tr>)}</tbody>\n </table>\n </div>\n );\n}\n\nconst defaultDownload = (url, name) => {\n const a = document.createElement('a');\n a.href = url; a.download = name; a.rel = 'noreferrer';\n document.body.appendChild(a); a.click(); a.remove();\n};\n\n/**\n * `parseWorkbook(arrayBuffer)` → `[{ name, filled, rows }]`, one entry per tab, where `rows` is\n * an array-of-arrays (header row first) and `filled` says whether the tab has anything in it at\n * all. Async, so the caller can load its spreadsheet library lazily.\n */\nexport function FilePreview({\n file, onClose, fetchFile, officePdfUrl, renderMarkdown, parseWorkbook, onDownload, title,\n}) {\n const { url, name } = file || {};\n const [st, setSt] = useState({ kind: 'loading' });\n const [tab, setTab] = useState(0);\n // An HTML file opens as the page it is; Source shows what was written. The choice lives in the\n // header, beside the name, so it reads as a property of the file being looked at.\n const [view, setView] = useState('preview');\n\n useEffect(() => {\n if (!url) return undefined;\n let alive = true;\n let obj;\n setSt({ kind: 'loading' });\n setTab(0);\n setView('preview');\n const get = fetchFile || ((u) => fetch(u, { cache: 'no-store' }));\n\n (async () => {\n const res = await get(url);\n if (!res.ok) throw new Error(`${res.status}`);\n const mime = (res.headers.get('content-type') || '').toLowerCase();\n const kind = kindOf(name, mime);\n\n if (kind === 'office') {\n // The rendition needs the same transport, so it is fetched to a blob rather than handed\n // to an <iframe src> that would carry no credentials.\n if (!officePdfUrl) {\n setSt({ kind: 'binary', error: 'This format has no preview here. Download it to open it.' });\n return;\n }\n const r = await get(officePdfUrl(url));\n if (!r.ok) throw new Error(`${r.status}`);\n obj = URL.createObjectURL(await r.blob());\n if (alive) setSt({ kind: 'pdf', objUrl: obj });\n return;\n }\n if (kind === 'sheet') {\n if (!parseWorkbook) {\n setSt({ kind: 'binary', error: 'This format has no preview here. Download it to open it.' });\n return;\n }\n try {\n const sheets = await parseWorkbook(await res.arrayBuffer());\n // Open on the first sheet that has something: opening on an empty one reads as a broken\n // preview rather than as an empty tab.\n const first = sheets.findIndex((s) => s.filled);\n if (alive) { setTab(first < 0 ? 0 : first); setSt({ kind: 'sheet', sheets }); }\n } catch (e) {\n if (alive) setSt({ kind: 'binary', error: `This spreadsheet couldn’t be read (${String(e?.message || 'parse failed').slice(0, 80)}).` });\n }\n return;\n }\n if (kind === 'csv' || kind === 'markdown' || kind === 'code' || kind === 'html') {\n const text = await res.text();\n if (!alive) return;\n if (kind === 'csv') setSt({ kind: 'csv', rows: delimitedToRows(text, extOf(name) === 'tsv' ? '\\t' : ',') });\n else setSt({ kind, text: text.slice(0, 400000) });\n return;\n }\n if (kind === 'binary') { if (alive) setSt({ kind: 'binary' }); return; }\n obj = URL.createObjectURL(await res.blob());\n if (alive) setSt({ kind, objUrl: obj });\n })().catch(() => { if (alive) setSt({ kind: 'binary', error: 'Could not load this file.' }); });\n\n return () => { alive = false; if (obj) URL.revokeObjectURL(obj); };\n }, [url, name, fetchFile, officePdfUrl, parseWorkbook]);\n\n const download = () => (onDownload ? onDownload(url, name) : defaultDownload(url, name));\n\n return (\n <aside className=\"uic-fp\" aria-label={title || `Preview of ${name}`}>\n <header className=\"uic-fp-head\">\n <span className=\"uic-fp-ic\"><FileTypeIcon name={name} size={20} /></span>\n <span className=\"uic-fp-name\" title={name}>{name}</span>\n {st.kind === 'html' && (\n <div className=\"uic-fp-seg\" role=\"tablist\" aria-label=\"Show the page or its source\">\n {[['preview', 'Preview'], ['source', 'Source']].map(([id, label]) => (\n <button key={id} type=\"button\" role=\"tab\" aria-selected={view === id}\n className={'uic-fp-seg-btn' + (view === id ? ' is-on' : '')} onClick={() => setView(id)}>{label}</button>\n ))}\n </div>\n )}\n <button type=\"button\" className=\"uic-fp-btn\" aria-label={`Download ${name}`} title=\"Download\"\n onClick={download}><IcDownload /></button>\n {onClose && (\n <button type=\"button\" className=\"uic-fp-btn\" aria-label=\"Close preview\" title=\"Close\"\n onClick={onClose}><IcX size={18} /></button>\n )}\n </header>\n\n <div className=\"uic-fp-body\">\n {st.kind === 'loading' && <div className=\"uic-fp-pad\"><span className=\"uic-skel uic-fp-skel\" /></div>}\n {st.kind === 'image' && st.objUrl && <div className=\"uic-fp-center\"><img className=\"uic-fp-img\" src={st.objUrl} alt={name} /></div>}\n {st.kind === 'pdf' && st.objUrl && <iframe className=\"uic-fp-frame\" src={st.objUrl} title={name} />}\n {st.kind === 'video' && st.objUrl && <div className=\"uic-fp-center\"><video className=\"uic-fp-media\" src={st.objUrl} controls /></div>}\n {st.kind === 'audio' && st.objUrl && <div className=\"uic-fp-center\"><audio src={st.objUrl} controls /></div>}\n {st.kind === 'markdown' && (\n <div className=\"uic-fp-doc\">\n {renderMarkdown ? renderMarkdown(st.text || '') : <pre className=\"uic-fp-pre\">{st.text}</pre>}\n </div>\n )}\n {st.kind === 'code' && <CodeBlock code={st.text || ''} language={LANG[extOf(name)] || 'plaintext'} />}\n {st.kind === 'html' && view === 'source' && <CodeBlock code={st.text || ''} language=\"xml\" />}\n {st.kind === 'html' && view === 'preview' && (\n // The page runs in its own origin with scripts only: a mockup's own script and styles\n // work, and nothing in it can read the host page, its cookies or its storage.\n <iframe className=\"uic-fp-frame\" title={name} sandbox=\"allow-scripts\" srcDoc={st.text || ''} />\n )}\n {st.kind === 'csv' && <Grid rows={st.rows} />}\n {st.kind === 'sheet' && st.sheets && (\n <div className=\"uic-fp-xlsx\">\n {st.sheets[tab]?.filled ? <Grid rows={st.sheets[tab].rows} />\n : <div className=\"uic-fp-empty\">This sheet is empty.</div>}\n {/* Shown even for one sheet: the tab bar is what tells someone they are looking at a\n workbook, and hiding it is what made an empty first sheet read as a failure. */}\n <div className=\"uic-fp-tabs\">\n {st.sheets.map((s, i) => (\n <button key={s.name + i} type=\"button\"\n className={'uic-fp-tab' + (i === tab ? ' is-on' : '') + (s.filled ? '' : ' is-empty')}\n onClick={() => setTab(i)} title={s.filled ? s.name : `${s.name} (empty)`}>{s.name}</button>\n ))}\n </div>\n </div>\n )}\n {st.kind === 'binary' && (\n <div className=\"uic-fp-center\">\n <div className=\"uic-fp-fallback\">\n <FileTypeIcon name={name} size={56} />\n <p>{st.error || 'No inline preview for this file type.'}</p>\n <button type=\"button\" className=\"uic-fp-dl\" onClick={download}>Download</button>\n </div>\n </div>\n )}\n </div>\n </aside>\n );\n}\n","// Form primitives: a labelled field, and the three controls that go in one.\n//\n// Every surface in this stack had been hand-rolling `<label>Text<select className=\"…-input\">`,\n// which is why the same form looks different in each of them — different label weight, different\n// focus ring, a hint that is a paragraph in one place and a caption in another. These are the\n// smallest components that make that impossible.\n//\n// A Field owns the label, the hint and the error, so a control never has to render its own and\n// they never disagree about spacing. Passing `error` replaces the hint rather than stacking on it:\n// once something is wrong, the thing to read is what is wrong.\nimport { useId } from 'react';\nimport { Chevron } from './icons.jsx';\n\nexport function Field({ label, hint, error, htmlFor, required, children, className = '' }) {\n return (\n <div className={'uic-field' + (error ? ' is-error' : '') + (className ? ' ' + className : '')}>\n {label && (\n <label className=\"uic-field-label\" htmlFor={htmlFor}>\n {label}{required && <span className=\"uic-field-req\" aria-hidden=\"true\">*</span>}\n </label>\n )}\n {children}\n {error ? <p className=\"uic-field-err\">{error}</p>\n : hint ? <p className=\"uic-field-hint\">{hint}</p> : null}\n </div>\n );\n}\n\n/** A field whose control is generated for it — the common case, wired for accessibility. */\nfunction withField(Control) {\n return function Fielded({ label, hint, error, required, id, className, ...rest }) {\n const auto = useId();\n const inputId = id || auto;\n return (\n <Field label={label} hint={hint} error={error} required={required} htmlFor={inputId} className={className}>\n <Control id={inputId} invalid={!!error} required={required} {...rest} />\n </Field>\n );\n };\n}\n\nfunction BareInput({ invalid, ...rest }) {\n return <input className={'uic-input' + (invalid ? ' is-error' : '')} aria-invalid={invalid || undefined} {...rest} />;\n}\n\nfunction BareTextarea({ invalid, rows = 4, ...rest }) {\n return <textarea className={'uic-input uic-textarea' + (invalid ? ' is-error' : '')}\n rows={rows} aria-invalid={invalid || undefined} {...rest} />;\n}\n\n/** Options are [{value, label, disabled}] or plain strings. The chevron is drawn rather than left\n * to the platform, because the platform's differs per OS and the rest of this form does not. */\nfunction BareSelect({ invalid, options = [], placeholder, ...rest }) {\n return (\n <span className=\"uic-select-wrap\">\n <select className={'uic-input uic-select' + (invalid ? ' is-error' : '')}\n aria-invalid={invalid || undefined} {...rest}>\n {placeholder && <option value=\"\">{placeholder}</option>}\n {options.map((o) => {\n const opt = typeof o === 'string' ? { value: o, label: o } : o;\n return <option key={opt.value} value={opt.value} disabled={opt.disabled}>{opt.label}</option>;\n })}\n </select>\n <span className=\"uic-select-chev\" aria-hidden=\"true\"><Chevron dir=\"down\" size={14} /></span>\n </span>\n );\n}\n\nexport const Input = withField(BareInput);\nexport const Textarea = withField(BareTextarea);\nexport const Select = withField(BareSelect);\n\n/** The row a form ends with. `align` is 'end' by default because the primary action belongs where\n * the eye leaves the last control. */\nexport function FormActions({ children, align = 'end', className = '' }) {\n return <div className={`uic-form-actions is-${align}${className ? ' ' + className : ''}`}>{children}</div>;\n}\n\n/** The two buttons that row almost always holds, so their order stops being a per-form decision. */\nexport function Button({ variant = 'default', size = 'md', type = 'button', className = '', ...rest }) {\n return <button type={type} className={`uic-btn is-${variant} is-${size}${className ? ' ' + className : ''}`} {...rest} />;\n}\n","// Carousel — a horizontal strip of cards with edge buttons.\n//\n// It exists as a component rather than as a stylesheet plus a div because the parts that were\n// wrong in the copies are all behaviour, not paint: the buttons must disable at each end, must\n// not be there at all when everything already fits, and must scroll by an amount related to the\n// viewport. Four landings each hardcoded `scrollBy({ left: ±560 })` — the same magic number, in\n// four files, correct at no particular width.\n//\n// Item width is a custom property (--uic-car-item, default 236px) so a product sets the card size\n// from its own stylesheet without this component knowing what a card is.\nimport React, { useCallback, useEffect, useRef, useState } from 'react';\nimport { Chevron } from './icons.jsx';\n\n/**\n * label what this strip is, for the scroll region and the button names (\"Scroll <label> left\")\n * step px per press; defaults to 90% of the visible width, so a press always leaves a\n * landmark from the previous screenful on screen\n */\n// Both edge tests need the SAME tolerance. They did not: the end test allowed a pixel of slack\n// and the start test demanded scrollLeft <= 1, while scroll-snap parks the strip at its first\n// snap point — scrollLeft === 2 on a card with a border. So arriving at the start left the back\n// button enabled, and pressing it moved the strip two pixels: a control that looks live and does\n// nothing, which is the thing this component's own header promises not to ship.\nconst EDGE = 2;\n\nexport function Carousel(props) {\n const { label, step, children, classNames = {} } = props;\n const ref = useRef(null);\n const [edges, setEdges] = useState({ start: true, end: true, overflow: false });\n\n const measure = useCallback(() => {\n const el = ref.current;\n if (!el) return;\n const overflow = el.scrollWidth - el.clientWidth > EDGE;\n setEdges({\n overflow,\n start: el.scrollLeft <= EDGE,\n end: el.scrollLeft >= el.scrollWidth - el.clientWidth - EDGE,\n });\n }, []);\n\n useEffect(() => {\n const el = ref.current;\n if (!el) return undefined;\n measure();\n // Content arrives asynchronously (templates fetched after mount) and the container resizes\n // with the window, so \"does this overflow\" has to be answered again, not once.\n const ro = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(measure) : null;\n ro?.observe(el);\n for (const child of el.children) ro?.observe(child);\n return () => ro?.disconnect();\n }, [measure, children]);\n\n const scroll = (dir) => {\n const el = ref.current;\n if (!el) return;\n el.scrollBy({ left: dir * (step || Math.round(el.clientWidth * 0.9)), behavior: 'smooth' });\n };\n\n return (\n <div className={['uic-carousel-wrap', classNames.root || ''].filter(Boolean).join(' ')}>\n {edges.overflow ? (\n <button type=\"button\" className={['uic-carousel-nav is-left', classNames.button || ''].filter(Boolean).join(' ')}\n onClick={() => scroll(-1)} disabled={edges.start} aria-label={`Scroll ${label} left`}>\n <Chevron dir=\"left\" />\n </button>\n ) : null}\n <div className={['uic-carousel', classNames.viewport || ''].filter(Boolean).join(' ')}\n ref={ref} onScroll={measure} role=\"group\" aria-label={label}>\n {children}\n </div>\n {edges.overflow ? (\n <button type=\"button\" className={['uic-carousel-nav is-right', classNames.button || ''].filter(Boolean).join(' ')}\n onClick={() => scroll(1)} disabled={edges.end} aria-label={`Scroll ${label} right`}>\n <Chevron dir=\"right\" />\n </button>\n ) : null}\n </div>\n );\n}\n","// Card — art on top, a title row underneath, optional overlay and actions.\n//\n// The structure is the point. Every copy of this made the whole card a <button> and then put\n// more buttons inside it (a preview eye, rename, delete): interactive elements nested inside an\n// interactive element, which no assistive technology can present and which browsers resolve by\n// guessing. Here the root is a plain div, the primary action is ONE button covering art + title,\n// and `overlay` / `actions` are its siblings.\n//\n// `title` takes a node so an inline rename field can live there — pass onClick={undefined} while\n// editing, so the row is not simultaneously a text field and a link to somewhere else.\nimport React from 'react';\n\n/**\n * art the thumbnail node (this component gives it a box; what goes in it is yours)\n * title the name (node)\n * subtitle quiet trailing text, e.g. when it was last opened\n * onClick opens the thing; omit for a card that is only a display\n * selected this card is the current choice\n * overlay floats over the art on hover, and is ALWAYS visible on touch/narrow (there is no\n * hover to reveal it with)\n * actions sits in the title row, after the subtitle\n */\nexport function Card(props) {\n const { art, title, subtitle, onClick, selected = false, overlay, actions, classNames = {} } = props;\n const foot = (\n <span className=\"uic-card-foot\">\n <span className=\"uic-card-name\">{title}</span>\n {subtitle ? <span className=\"uic-card-sub\">{subtitle}</span> : null}\n </span>\n );\n return (\n <div className={['uic-card', selected ? 'is-selected' : '', classNames.root || '']\n .filter(Boolean).join(' ')}>\n {onClick ? (\n <button type=\"button\" className=\"uic-card-main\" onClick={onClick} aria-pressed={selected || undefined}>\n <span className=\"uic-card-art\">{art}</span>\n {foot}\n </button>\n ) : (\n <div className=\"uic-card-main\">\n <span className=\"uic-card-art\">{art}</span>\n {foot}\n </div>\n )}\n {overlay ? <div className=\"uic-card-overlay\">{overlay}</div> : null}\n {actions ? <div className=\"uic-card-actions\">{actions}</div> : null}\n </div>\n );\n}\n","// SearchField — the filter box that sits in a section header.\n//\n// Byte-identical in three apps; the fourth ships the stylesheet for it and no component, so its\n// lists have no search at all. Draws the package's own glyphs, so adopting it does not drag an\n// icon library into a product that had not chosen one.\nimport React from 'react';\nimport { IcSearch, IcX } from './icons.jsx';\n\n/** placeholder doubles as the accessible name — a search box next to a heading rarely has room\n * for a visible label, and \"Search templates\" is exactly what the label would have said. */\nexport function SearchField(props) {\n const { value, onChange, placeholder, clearLabel = 'Clear search', className } = props;\n return (\n <label className={['uic-search', className || ''].filter(Boolean).join(' ')}>\n <span className=\"uic-search-ic\" aria-hidden=\"true\"><IcSearch /></span>\n <input\n type=\"search\"\n value={value}\n placeholder={placeholder}\n aria-label={placeholder}\n onChange={(e) => onChange(e.target.value)}\n />\n {value ? (\n <button type=\"button\" className=\"uic-search-x\" aria-label={clearLabel} onClick={() => onChange('')}>\n <IcX size={12} />\n </button>\n ) : null}\n </label>\n );\n}\n","// CascadeMenu — a two-level choice in one panel. The first column lists the things you can pick;\n// the second lists the options of the one you pressed or arrowed onto; a press in the second\n// column IS the pick. A menu with a submenu, laid flat: both levels stay visible, so\n// nothing has to be hovered just right to stay open, and the reader sees \"harness, then model\"\n// as one gesture instead of a modal with a filter, a list, and a second control afterwards.\n//\n// It rides on Popover, so it portals to the body, flips to the side with room, clamps to the\n// viewport and scrolls inside the height it was given — the panel never runs off the screen.\n// Under `stackBelow` px of viewport the two columns cannot sit side by side, so the same panel\n// walks them as steps: pick in the first, the second replaces it with a way back.\n//\n// Choosing in the first column is a press or a focus, NOT a hover. A hover-driven second column\n// is the classic submenu trap: the pointer crossing other rows on its diagonal way to an option\n// swaps the options out from under it. Here the first column changes only on click or on\n// keyboard focus, so the path to an option is never a race.\n//\n// Keyboard: ↑↓ move within a column, → enters the options of the chosen item, ← returns to it,\n// Enter/Space press (native buttons), Escape closes (Popover). Focus lands inside on open and\n// goes back to the anchor on close.\nimport React, { Fragment, useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { Popover } from './Popover.jsx';\nimport { SearchField } from './SearchField.jsx';\nimport { Chevron, Svg } from './icons.jsx';\n\nconst Tick = () => <Svg s={14}><path d=\"M20 6 9 17l-5-5\" /></Svg>;\n\nconst FILTER_PAST = 8; // 'auto': a filter field appears once the first column is longer than this\n\nconst itemsOf = (groups) => groups.flatMap((g) => g.items);\n\n/**\n * open, anchorRef, onClose as Popover\n * label accessible name of the panel\n * groups [{ label, items: [{ id, label, icon, note }] }] — the first column, grouped;\n * a note is a small trailing word, e.g. 'fixed' on the one item a locked\n * chooser offers\n * optionsOf(item) -> [{ id, label, disabled, note, badge }] — the second column for one item;\n * a badge is a node at the row's end, e.g. which key serves a model, and\n * is what gives way (its own ellipsis) when the row is narrow\n * optionsFooter a node under the options, e.g. what the options without a badge mean\n * onPick(item, option)\n * value { item, option } — the current pair: its item opens first and its option\n * carries a check, so an editor of an existing choice shows where it stands\n * filter 'auto' (default) | true | false — a filter field over the first column\n * filterPlaceholder default 'Filter'\n * emptyText first column has no match; noOptionsText: the item offers nothing\n * optionsLabel accessible name of the second column, default 'Options'\n * backLabel the way back in stacked mode, default 'Back'\n * width side-by-side width, default 520; stackBelow: viewport px, default 560\n */\nexport function CascadeMenu(props) {\n const {\n open, anchorRef, onClose, label,\n groups = [], optionsOf, onPick,\n filter = 'auto', filterPlaceholder = 'Filter',\n emptyText = 'Nothing matches.', noOptionsText = 'Nothing to choose here.',\n optionsLabel = 'Options', backLabel = 'Back', optionsFooter,\n width = 520, stackBelow = 560, className, value,\n } = props;\n\n const rootRef = useRef(null);\n const [q, setQ] = useState('');\n const [activeId, setActiveId] = useState(null);\n const [stage, setStage] = useState('items');\n const [stacked, setStacked] = useState(false);\n\n // Filtering happens on the label people read, nothing else.\n const visible = useMemo(() => {\n const needle = q.trim().toLowerCase();\n if (!needle) return groups.filter((g) => g.items.length > 0);\n return groups\n .map((g) => ({ ...g, items: g.items.filter((it) => String(it.label).toLowerCase().includes(needle)) }))\n .filter((g) => g.items.length > 0);\n }, [groups, q]);\n const flat = useMemo(() => itemsOf(visible), [visible]);\n const active = flat.find((it) => it.id === activeId) || flat[0] || null;\n const options = useMemo(() => (active && optionsOf ? optionsOf(active) : []), [active, optionsOf]);\n const showFilter = filter === true || (filter === 'auto' && itemsOf(groups).length > FILTER_PAST);\n\n // Fresh every time it opens: no stale filter, the first item highlighted, the first step shown.\n useEffect(() => {\n if (!open) return undefined;\n setQ(''); setActiveId(value?.item ?? null); setStage('items');\n const measure = () => setStacked(window.innerWidth < stackBelow);\n measure();\n window.addEventListener('resize', measure);\n // Popover renders its children one effect later (it has to measure the anchor first), so the\n // first focusable lands in the next frame.\n const raf = requestAnimationFrame(() => {\n const first = rootRef.current?.querySelector('input, button:not(:disabled)');\n first?.focus({ preventScroll: true });\n });\n const anchor = anchorRef?.current;\n return () => {\n window.removeEventListener('resize', measure);\n cancelAnimationFrame(raf);\n // Close by Escape or by a pick: focus goes back where it came from. Close by a press\n // elsewhere: the browser moves focus to that press afterwards, so this does not fight it.\n anchor?.focus?.({ preventScroll: true });\n };\n }, [open, stackBelow]); // eslint-disable-line react-hooks/exhaustive-deps\n\n const focusIn = useCallback((col, index = 0) => {\n const list = rootRef.current?.querySelectorAll(`.uic-cascade-${col} .uic-pop-item:not(:disabled)`);\n if (!list || !list.length) return false;\n const i = Math.max(0, Math.min(index, list.length - 1));\n list[i].focus({ preventScroll: true });\n return true;\n }, []);\n\n const enterOptions = useCallback(() => {\n if (stacked) { setStage('options'); requestAnimationFrame(() => focusIn('options')); }\n else focusIn('options');\n }, [stacked, focusIn]);\n\n const onKey = (e) => {\n const el = document.activeElement;\n const col = el?.closest?.('.uic-cascade-col');\n const inItems = col?.classList.contains('uic-cascade-items');\n const inOptions = col?.classList.contains('uic-cascade-options');\n if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {\n if (!col) return;\n const list = Array.from(col.querySelectorAll('.uic-pop-item:not(:disabled)'));\n const i = list.indexOf(el);\n // From the filter field, ↓ steps onto the first row.\n const next = i < 0 ? 0 : i + (e.key === 'ArrowDown' ? 1 : -1);\n if (next < 0) { col.querySelector('input')?.focus(); e.preventDefault(); return; }\n if (next >= list.length) return;\n e.preventDefault();\n list[next].focus({ preventScroll: true });\n } else if (e.key === 'ArrowRight' && inItems) {\n e.preventDefault(); enterOptions();\n } else if (e.key === 'ArrowLeft' && inOptions) {\n e.preventDefault();\n if (stacked) { setStage('items'); requestAnimationFrame(() => focusIn('items', flat.indexOf(active))); }\n else focusIn('items', flat.indexOf(active));\n } else if (e.key === 'Enter' && el?.tagName === 'INPUT') {\n // Enter in the filter means \"this one\": on to its options.\n e.preventDefault(); enterOptions();\n }\n };\n\n const showItems = !stacked || stage === 'items';\n const showOptions = !stacked || stage === 'options';\n\n return (\n <Popover open={open} anchorRef={anchorRef} onClose={onClose} label={label}\n width={stacked ? 320 : width} minHeight={260}\n className={['uic-cascade-pop', className || ''].filter(Boolean).join(' ')}>\n <div ref={rootRef} className={'uic-cascade' + (stacked ? ' is-stacked' : '')} onKeyDown={onKey}>\n {showItems && (\n <div className=\"uic-cascade-col uic-cascade-items\">\n {showFilter ? (\n <SearchField className=\"uic-cascade-filter\" value={q} onChange={setQ} placeholder={filterPlaceholder} />\n ) : null}\n <div className=\"uic-pop-list\">\n {visible.map((g, gi) => (\n <Fragment key={g.label || gi}>\n {g.label ? <div className=\"uic-cascade-group\">{g.label}</div> : null}\n {g.items.map((it) => {\n const on = active?.id === it.id;\n return (\n <button key={it.id} type=\"button\"\n className={'uic-pop-item uic-cascade-item' + (on ? ' is-active' : '')}\n aria-expanded={on} aria-haspopup=\"true\"\n onFocus={() => setActiveId(it.id)}\n onClick={() => { setActiveId(it.id); enterOptions(); }}>\n {it.icon ? <span className=\"uic-cascade-ic\" aria-hidden=\"true\">{it.icon}</span> : null}\n <span className=\"uic-chip-t\">{it.label}</span>\n {it.note ? <span className=\"uic-cascade-note\">{it.note}</span> : null}\n <span className=\"uic-cascade-chev\" aria-hidden=\"true\"><Chevron dir=\"right\" size={14} /></span>\n </button>\n );\n })}\n </Fragment>\n ))}\n {flat.length === 0 ? <div className=\"uic-pop-note\">{emptyText}</div> : null}\n </div>\n </div>\n )}\n {showOptions && (\n <div className=\"uic-cascade-col uic-cascade-options\" role=\"group\" aria-label={optionsLabel}>\n <div className=\"uic-cascade-head\">\n {stacked ? (\n <button type=\"button\" className=\"uic-cascade-back\" aria-label={backLabel}\n onClick={() => { setStage('items'); requestAnimationFrame(() => focusIn('items', flat.indexOf(active))); }}>\n <Chevron dir=\"left\" size={14} />\n </button>\n ) : null}\n {active?.icon ? <span className=\"uic-cascade-ic\" aria-hidden=\"true\">{active.icon}</span> : null}\n <span className=\"uic-chip-t\">{active ? active.label : ''}</span>\n </div>\n <div className=\"uic-pop-list\">\n {options.map((o) => {\n const on = !!value && active?.id === value.item && o.id === value.option;\n return (\n <button key={o.id} type=\"button\"\n className={'uic-pop-item uic-cascade-opt' + (on ? ' is-on' : '') + (o.badge ? ' has-badge' : '')}\n aria-current={on ? 'true' : undefined}\n disabled={!!o.disabled} onClick={() => onPick?.(active, o)}>\n {value ? <span className=\"uic-pop-check\" aria-hidden=\"true\">{on ? <Tick /> : null}</span> : null}\n <span className=\"uic-chip-t\">{o.label}</span>\n {o.note ? <span className=\"uic-cascade-note\">{o.note}</span> : null}\n {o.badge || null}\n </button>\n );\n })}\n {active && options.length === 0 ? <div className=\"uic-pop-note\">{noOptionsText}</div> : null}\n </div>\n {optionsFooter || null}\n </div>\n )}\n </div>\n </Popover>\n );\n}\n","// Modal — a dialog whose body is yours: a preview, a big form, a comparison.\n//\n// useDialog() answers a QUESTION and resolves to a value (confirm/prompt/alert). This is the\n// other half: a surface with arbitrary content that the caller opens and closes itself. Products\n// were re-implementing it per feature, each with its own backdrop mousedown handler and its own\n// document keydown listener.\n//\n// It shares the dialog host's Escape ordering through the package's overlay stack (components/\n// overlay.js), so a Modal opened on top of a confirm takes the key and the confirm does not, and\n// both sit at the same z-index layer (--uic-z-overlay). It does NOT render inside DialogHost's\n// portal: that root is created from the host's private state and only exists while a dialog is\n// open, so there is nothing to render into and no API to reach it with. One stack, two roots, is\n// the honest arrangement — and it means Modal works in an app that never mounted DialogHost.\nimport React, { useCallback, useEffect, useId } from 'react';\nimport { createPortal } from 'react-dom';\nimport { IcX } from './icons.jsx';\nimport { useOverlayEscape } from './overlay.js';\n\n/**\n * open render it\n * onClose Escape, the ✕, or a click on the backdrop itself\n * title the heading (string or node); also names the dialog for assistive tech\n * description one quiet line under the title\n * actions buttons in the header, before the ✕ (e.g. \"Use this template\")\n * size 'sm' | 'md' | 'lg' | 'full' — or pass `width` for an exact px/any CSS width\n * labelledBy id of your own heading, when `title` is not where the name lives\n */\nexport function Modal(props) {\n const { open, onClose, title, description, actions, size = 'md', width,\n labelledBy, children, classNames = {} } = props;\n const titleId = useId();\n\n const escape = useCallback(() => onClose?.(), [onClose]);\n useOverlayEscape(open, escape);\n\n // A modal that leaves the page scrolling behind it drifts under the reader's fingers on a\n // touch device and loses their place in the list they opened it from.\n useEffect(() => {\n if (!open || typeof document === 'undefined') return undefined;\n const prev = document.body.style.overflow;\n document.body.style.overflow = 'hidden';\n return () => { document.body.style.overflow = prev; };\n }, [open]);\n\n if (!open || typeof document === 'undefined') return null;\n // mousedown, not click: a press that STARTED inside the card and ended on the backdrop (a drag\n // that overshot, a text selection) would otherwise close it out from under the person.\n const onBackdrop = (e) => { if (e.target === e.currentTarget) onClose?.(); };\n return createPortal(\n <div className={['uic-modal-backdrop', classNames.backdrop || ''].filter(Boolean).join(' ')}\n onMouseDown={onBackdrop}>\n <div className={['uic-modal', `is-${size}`, classNames.root || ''].filter(Boolean).join(' ')}\n style={width ? { width } : undefined}\n role=\"dialog\" aria-modal=\"true\"\n aria-labelledby={labelledBy || (title ? titleId : undefined)}>\n {(title || actions) ? (\n <div className=\"uic-modal-h\">\n <div className=\"uic-modal-title\">\n {title ? <h3 id={titleId}>{title}</h3> : null}\n {description ? <p>{description}</p> : null}\n </div>\n {actions}\n <button type=\"button\" className=\"uic-modal-x\" aria-label=\"Close\" onClick={onClose}>\n <IcX size={18} />\n </button>\n </div>\n ) : null}\n <div className={['uic-modal-b', classNames.body || ''].filter(Boolean).join(' ')}>\n {children}\n </div>\n </div>\n </div>,\n document.body,\n );\n}\n","// useTypewriter — cycle example prompts through a placeholder, typed out character by character.\n//\n// Three near-identical implementations existed; the differences between them were 24ms vs 26ms\n// per character and whether the list was shuffled. Those are not configuration, they are drift,\n// so there are no knobs for them here.\n//\n// The part worth sharing is the one thing all three already got right and nobody should have to\n// re-derive: prefers-reduced-motion turns the animation off and shows the first phrase, because\n// text that rewrites itself forever is exactly what that setting is about.\nimport { useEffect, useRef, useState } from 'react';\n\nconst CHAR_MS = 26; // per character while typing\nconst HOLD_MS = 2600; // a finished phrase stays long enough to read\n\n/**\n * phrases the lines to cycle (the product's own copy — it stays in the product)\n * active type only while this is true; a box the person is typing in stops animating\n * returns the text to show right now\n */\nexport function useTypewriter(phrases, { active = true } = {}) {\n const list = phrases && phrases.length ? phrases : [''];\n const [text, setText] = useState(list[0]);\n // Snapshot the list so a caller passing a fresh array literal every render does not restart\n // the animation on every render.\n const listRef = useRef(list);\n listRef.current = list;\n\n useEffect(() => {\n if (!active) return undefined;\n if (typeof window === 'undefined') return undefined;\n if (window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches) {\n setText(listRef.current[0]);\n return undefined;\n }\n let i = 0;\n let pos = 0;\n let timer;\n const tick = () => {\n const cur = listRef.current[i % listRef.current.length];\n if (pos <= cur.length) {\n setText(cur.slice(0, pos));\n pos += 1;\n timer = window.setTimeout(tick, CHAR_MS);\n } else {\n timer = window.setTimeout(() => { i += 1; pos = 0; tick(); }, HOLD_MS);\n }\n };\n tick();\n return () => window.clearTimeout(timer);\n }, [active]);\n\n return text;\n}\n","// Panel — the frame around one thing on a board: a header you can grab, a body, and the two\n// states that body spends most of its life in.\n//\n// The states are the reason this exists. A panel whose content is being fetched has to hold its\n// box (a grid that reflows as four requests land in four different orders is unreadable), and a\n// panel whose content FAILED has to show why, verbatim and selectable. Products keep replacing\n// that second one with \"Something went wrong\", which throws away the one string that tells the\n// person what to fix.\n//\n// `loading` blanks the body — the first fetch, when there is nothing to keep. `busy` leaves the\n// content up and marks the header — a refresh, where blanking a chart the person is reading to\n// redraw the same chart is worse than waiting.\nimport { Button } from './form.jsx';\n\n/**\n * title the panel's name\n * titleAs heading level, so a board fits YOUR document outline ('h3')\n * meta quiet second line under the title (when it was refreshed, what it counts)\n * actions controls in the header, after the title — never drag the panel\n * footer quiet strip under the body\n * loading no content yet: the body is a placeholder of the same size\n * busy content is up but being refreshed: the header shows it\n * error what went wrong, verbatim. Shown in monospace, selectable, and scrollable —\n * a query error is a thing people copy\n * errorDetail extra context under the message, folded away (the statement that failed)\n * onRetry absent → no retry control is drawn, rather than a dead one\n */\nexport function Panel(props) {\n const {\n title, titleAs: Heading = 'h3', meta, actions, footer,\n loading = false, loadingLabel = 'Loading',\n busy = false, busyLabel = 'Refreshing',\n error = null, errorTitle = 'This panel could not load',\n errorDetail = null, detailLabel = 'Details',\n onRetry, retryLabel = 'Try again',\n className = '', classNames = {}, children,\n } = props;\n\n const body = loading ? (\n <div className=\"uic-panel-load\">\n <span className=\"uic-panel-load-bar\" />\n <span className=\"uic-panel-load-bar\" />\n <span className=\"uic-panel-load-bar\" />\n <span className=\"uic-sr\">{loadingLabel}</span>\n </div>\n ) : error ? (\n <div className=\"uic-panel-fail\">\n <p className=\"uic-panel-fail-t\">{errorTitle}</p>\n <pre className=\"uic-panel-fail-m\">{error}</pre>\n {errorDetail ? (\n <details className=\"uic-panel-fail-d\">\n <summary>{detailLabel}</summary>\n <div className=\"uic-panel-fail-dd\">{errorDetail}</div>\n </details>\n ) : null}\n {onRetry ? (\n <div className=\"uic-panel-fail-act\">\n <Button size=\"sm\" onClick={onRetry}>{retryLabel}</Button>\n </div>\n ) : null}\n </div>\n ) : children;\n\n return (\n <section\n className={['uic-panel', className, classNames.root || ''].filter(Boolean).join(' ')}\n aria-busy={loading || busy || undefined}\n >\n <header className={['uic-panel-head', classNames.head || ''].filter(Boolean).join(' ')}>\n <div className=\"uic-panel-titles\">\n {title ? <Heading className=\"uic-panel-title\">{title}</Heading> : null}\n {meta ? <p className=\"uic-panel-meta\">{meta}</p> : null}\n </div>\n {actions ? <div className=\"uic-panel-acts\">{actions}</div> : null}\n </header>\n {/* One indeterminate line, not a percentage: nothing here knows how far along a refresh is. */}\n {busy ? <div className=\"uic-panel-busy\" role=\"status\" aria-label={busyLabel} /> : null}\n <div className={['uic-panel-body', classNames.body || ''].filter(Boolean).join(' ')}>{body}</div>\n {footer ? <footer className=\"uic-panel-foot\">{footer}</footer> : null}\n </section>\n );\n}\n","// PanelGrid — a column grid of panels you can drag and resize, and a read-only mode that is the\n// default. The layout is a prop: this component never owns it, it proposes the next one.\n//\n// Written here rather than taken from react-grid-layout on purpose. What a dashboard needs is\n// this file: cells → pixels, a pointer drag, a resize corner, and gravity. What the dependency\n// adds around that is three more packages (draggable / resizable / a deep-equal), a stylesheet\n// with its own hardcoded colours (its drop placeholder is literally `background: red`), and no\n// keyboard path at all. It is also not a peer any host here already owns, so every app that\n// imports a Button would pay for it. The subset below has no dependencies, themes from the same\n// --uic-* tokens as everything else, and arranges a panel from the keyboard.\nimport React, { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';\nimport { compact, layoutRows, moveItem, nudgeItem, resizeItem, sameLayout, sortLayout } from './layout.js';\n\n/** Measure the box we actually get. A grid inside a scroller that also holds a side panel gets a\n * stale width from anything that measures once — the observer reports every change. */\nfunction useMeasuredWidth() {\n const ref = useRef(null);\n const [width, setWidth] = useState(0);\n useLayoutEffect(() => {\n const el = ref.current;\n if (!el) return undefined;\n const measure = () => setWidth(el.clientWidth);\n measure();\n const ro = new ResizeObserver(measure);\n ro.observe(el);\n return () => ro.disconnect();\n }, []);\n return [ref, width];\n}\n\n// A press that lands on one of these is that control's press, not the start of a drag.\nconst NO_DRAG = 'button, a, input, select, textarea, [data-uic-nodrag]';\n\n/**\n * layout [{i, x, y, w, h, minW?, minH?, maxW?, maxH?, static?}] — cells, not pixels\n * children one element per layout entry, matched by `key`\n * cols columns across the full width (12)\n * rowHeight px per row (40)\n * gap px between cells (12)\n * editable false (default): nothing drags, nothing resizes, no handle is drawn\n * dragHandle selector a press must land inside to start a move ('.uic-panel-head')\n * stackAt below this container width the grid becomes ONE column in layout order and stops\n * being arrangeable — twelve columns across a phone is 32px each, and dragging a\n * panel between two cells nobody can see is not an interaction worth keeping\n * resizeLabel (id) => the handle's accessible name; name the panel in it\n * onLayoutChange(next) fires ONCE per interaction, on release — not per pixel, because the host\n * is usually writing the result to a document\n */\nexport function PanelGrid(props) {\n const {\n layout = [], children, cols = 12, rowHeight = 40, gap = 12,\n editable = false, dragHandle = '.uic-panel-head', stackAt = 640,\n onLayoutChange, resizeLabel, className = '',\n } = props;\n\n const [wrapRef, width] = useMeasuredWidth();\n // {id, mode, origin, px, py, dx, dy, preview} while a pointer interaction is live, else null.\n // The ref is what the pointer handlers read and write (they run between renders); the state is\n // the same value, kept only so React redraws.\n const [drag, setDrag] = useState(null);\n const dragRef = useRef(null);\n // A drag ends in a click on whatever was under the pointer. Swallow exactly that one.\n const swallowClick = useRef(false);\n\n const stacked = width > 0 && width < stackAt;\n const arrangeable = editable && !stacked;\n const live = drag ? drag.preview : layout;\n\n const colW = width > 0 ? (width - gap * (cols - 1)) / cols : 0;\n const cellW = colW + gap;\n const cellH = rowHeight + gap;\n const rowsToPx = (h) => h * rowHeight + (h - 1) * gap;\n\n // Stacked: one column, in reading order, each panel keeping its own height.\n const stack = useMemo(() => {\n if (!stacked) return null;\n const tops = new Map();\n let y = 0;\n for (const it of sortLayout(live)) {\n tops.set(it.i, y);\n y += rowsToPx(it.h || 1) + gap;\n }\n return { tops, height: Math.max(0, y - gap) };\n }, [stacked, live, rowHeight, gap]);\n\n const rows = layoutRows(live);\n const height = stacked ? stack.height : (rows ? rowsToPx(rows) : 0);\n\n const commit = useCallback((next) => {\n if (onLayoutChange && !sameLayout(next, layout)) onLayoutChange(next);\n }, [onLayoutChange, layout]);\n\n // ── pointer interaction ───────────────────────────────────────────────────\n // The listeners go on in the pointerdown handler itself, NOT in an effect keyed on the drag\n // state: an effect runs after React has re-rendered, and every pointer move that arrived in\n // between is simply gone. A quick flick then moves nothing at all.\n const detach = useRef(null);\n useEffect(() => () => detach.current?.(), []); // a drag must not outlive the grid\n\n const start = (id, mode) => (e) => {\n if (!arrangeable || e.button !== 0) return;\n const item = layout.find((it) => it.i === id);\n if (!item || item.static) return;\n if (mode === 'move' && (!e.target.closest(dragHandle) || e.target.closest(NO_DRAG))) return;\n e.preventDefault();\n detach.current?.();\n const begin = { id, mode, origin: item, px: e.clientX, py: e.clientY, dx: 0, dy: 0, preview: layout };\n dragRef.current = begin;\n setDrag(begin);\n\n const onMove = (ev) => {\n const d = dragRef.current;\n if (!d) return;\n const dx = ev.clientX - d.px;\n const dy = ev.clientY - d.py;\n if (Math.abs(dx) > 3 || Math.abs(dy) > 3) swallowClick.current = true;\n const cx = Math.round(dx / cellW);\n const cy = Math.round(dy / cellH);\n const preview = d.mode === 'move'\n ? moveItem(layout, d.id, d.origin.x + cx, d.origin.y + cy, cols)\n : resizeItem(layout, d.id, d.origin.w + cx, d.origin.h + cy, cols);\n dragRef.current = { ...d, dx, dy, preview };\n setDrag(dragRef.current);\n };\n const end = (commitIt) => () => {\n const d = dragRef.current;\n dragRef.current = null;\n off();\n setDrag(null);\n if (d && commitIt) commit(d.preview);\n };\n const onUp = end(true);\n // Escape abandons the interaction: the preview is dropped and nothing is committed.\n const onKey = (ev) => { if (ev.key === 'Escape') end(false)(); };\n function off() {\n detach.current = null;\n window.removeEventListener('pointermove', onMove);\n window.removeEventListener('pointerup', onUp);\n window.removeEventListener('pointercancel', onUp);\n window.removeEventListener('keydown', onKey);\n }\n detach.current = off;\n window.addEventListener('pointermove', onMove);\n window.addEventListener('pointerup', onUp);\n window.addEventListener('pointercancel', onUp);\n window.addEventListener('keydown', onKey);\n };\n\n const onClickCapture = (e) => {\n if (!swallowClick.current) return;\n swallowClick.current = false;\n e.stopPropagation();\n e.preventDefault();\n };\n\n // ── keyboard interaction ──────────────────────────────────────────────────\n // The same handle answers arrows (resize) and shift+arrows (move): a panel that can only be\n // arranged by dragging cannot be arranged by everyone.\n const onHandleKey = (id) => (e) => {\n const step = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] }[e.key];\n if (!step) return;\n const item = layout.find((it) => it.i === id);\n if (!item) return;\n e.preventDefault();\n commit(e.shiftKey\n ? nudgeItem(layout, id, step[0], step[1], cols)\n : resizeItem(layout, id, item.w + step[0], item.h + step[1], cols));\n };\n\n const boxOf = (it) => (stacked\n ? { left: 0, top: stack.tops.get(it.i), width, height: rowsToPx(it.h || 1) }\n : { left: it.x * cellW, top: it.y * cellH, width: it.w * colW + (it.w - 1) * gap, height: rowsToPx(it.h) });\n\n const byId = new Map(live.map((it) => [it.i, it]));\n const ghost = drag && drag.mode === 'move' && byId.has(drag.id) ? boxOf(byId.get(drag.id)) : null;\n const cls = ['uic-pg', arrangeable ? 'is-editable' : '', stacked ? 'is-stacked' : '', className]\n .filter(Boolean).join(' ');\n\n return (\n <div\n ref={wrapRef}\n className={cls}\n style={{ height }}\n onClickCapture={onClickCapture}\n // A cancelled pointer (a phone call, a lost pointer capture) leaves no click to swallow.\n // Clearing on the next press means a stale flag can never eat someone else's click.\n onPointerDownCapture={() => { swallowClick.current = false; }}\n >\n {ghost ? <div className=\"uic-pg-ghost\" aria-hidden=\"true\" style={ghost} /> : null}\n {width > 0 && React.Children.map(children, (child) => {\n if (!React.isValidElement(child) || child.key == null) return null;\n const id = String(child.key).replace(/^\\.\\$/, '');\n const it = byId.get(id);\n if (!it) return null; // no cell for this child: nowhere to put it\n const moving = drag && drag.id === id;\n // While moving, the panel follows the pointer in pixels and the ghost marks the cell it\n // would land in; a resize snaps, so the corner never lags the pointer's own cell.\n const offset = moving && drag.mode === 'move'\n ? { transform: `translate(${drag.dx}px, ${drag.dy}px)` } : null;\n return (\n <div\n className={'uic-pg-item' + (moving ? ' is-moving' : '')}\n style={{ ...boxOf(it), ...offset }}\n onPointerDown={arrangeable ? start(id, 'move') : undefined}\n >\n {child}\n {arrangeable && !it.static ? (\n <button\n type=\"button\"\n className=\"uic-pg-handle\"\n aria-label={resizeLabel ? resizeLabel(id) : 'Resize panel. Arrow keys resize it; shift with arrow keys moves it past its neighbours.'}\n onPointerDown={start(id, 'resize')}\n onKeyDown={onHandleKey(id)}\n >\n <svg width=\"10\" height=\"10\" viewBox=\"0 0 10 10\" aria-hidden=\"true\">\n <path d=\"M9 1v8H1\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.4\" strokeLinecap=\"round\" />\n </svg>\n </button>\n ) : null}\n </div>\n );\n })}\n </div>\n );\n}\n\n/** Gravity applied to a layout you built yourself. A new panel added with `y: Infinity` lands at\n * the bottom; this is what turns that into a real row. */\nexport function packLayout(layout, cols = 12) {\n const bottom = layoutRows(layout.filter((it) => Number.isFinite(it.y)));\n return compact(layout.map((it) => (Number.isFinite(it.y) ? it : { ...it, y: bottom })), cols);\n}\n","// Grid layout math for PanelGrid — pure functions over an array of {i, x, y, w, h}.\n//\n// Kept separate from the component because this is the part that is easy to get wrong and easy\n// to test: nothing here touches the DOM, React, or pixels. Coordinates are CELLS, not pixels —\n// x/w are columns, y/h are rows. The component owns the one conversion to pixels.\n//\n// Gravity is up and always on. A dashboard with holes punched in it looks broken rather than\n// deliberate, and \"the panel you dropped is where you dropped it, everything else flows around\n// it\" is the only rule a person has to learn.\n\n/** Sorted top-to-bottom, then left-to-right — the order gravity resolves in. */\nexport function sortLayout(layout) {\n return [...layout].sort((a, b) => (a.y - b.y) || (a.x - b.x));\n}\n\nfunction overlaps(a, b) {\n return a.i !== b.i\n && a.x < b.x + b.w && a.x + a.w > b.x\n && a.y < b.y + b.h && a.y + a.h > b.y;\n}\n\nfunction firstOverlap(placed, item) {\n for (const p of placed) if (overlaps(p, item)) return p;\n return null;\n}\n\n/** Cell bounds an item may occupy. min defaults to 1 cell; max defaults to the whole grid. */\nexport function clampItem(item, cols) {\n const minW = Math.max(1, item.minW || 1);\n const minH = Math.max(1, item.minH || 1);\n const w = Math.min(Math.max(item.w ?? minW, minW), Math.min(item.maxW || cols, cols));\n const h = Math.max(Math.min(item.h ?? minH, item.maxH || Infinity), minH);\n const x = Math.min(Math.max(item.x ?? 0, 0), cols - w);\n return { ...item, x, y: Math.max(0, item.y ?? 0), w, h };\n}\n\n/**\n * Float everything up, resolving overlaps on the way.\n *\n * `pinned` is the id being dragged, and it wins TIES: dropped onto the cell of a panel already\n * there, it keeps the cell and the other one moves, instead of the panel squirting out from under\n * the pointer because its neighbour happened to sort first. Only ties — a pin that always went\n * first would float above the panel it was just dragged below, so nudging a panel DOWN one row\n * could send it to the top of the board.\n */\nexport function compact(layout, cols, pinned) {\n const sorted = layout.map((it) => clampItem(it, cols))\n .sort((a, b) => (a.y - b.y) || (Number(b.i === pinned) - Number(a.i === pinned)) || (a.x - b.x));\n const statics = sorted.filter((it) => it.static);\n const rest = sorted.filter((it) => !it.static);\n const placed = [...statics];\n for (const item of rest) {\n let y = item.y;\n // Rise until something is in the way…\n while (y > 0 && !firstOverlap(placed, { ...item, y: y - 1 })) y--;\n // …and sink out of anything it is already inside (a drop, or a resize that grew downward).\n let hit;\n while ((hit = firstOverlap(placed, { ...item, y }))) y = hit.y + hit.h;\n placed.push({ ...item, y });\n }\n // Back into the caller's order: a layout array whose order shuffles every drag makes React\n // remount panels, and a remounted chart loses its animation and its tooltip.\n const byId = new Map(placed.map((it) => [it.i, it]));\n return layout.map((it) => byId.get(it.i) || it);\n}\n\n/** Move one item to a cell, then let gravity settle the rest around it. */\nexport function moveItem(layout, id, x, y, cols) {\n const next = layout.map((it) => (it.i === id && !it.static\n ? clampItem({ ...it, x, y: Math.max(0, y) }, cols)\n : it));\n return compact(next, cols, id);\n}\n\n/**\n * Move one item by one step, the way a keyboard means it.\n *\n * Sideways is literal. Vertically it is a SWAP with the neighbour above or below, because under\n * gravity \"down one row\" is not a thing that can happen: the row it vacates closes behind it and\n * it lands exactly where it started. A key that provably cannot move anything is a dead key, so\n * up/down step past the panel that is blocking, and do nothing only when there is genuinely\n * nothing to step past.\n */\nexport function nudgeItem(layout, id, dx, dy, cols) {\n const item = layout.find((it) => it.i === id);\n if (!item || item.static) return layout;\n if (dx) return moveItem(layout, id, item.x + dx, item.y, cols);\n const sameCols = layout.filter((o) => o.i !== id && o.x < item.x + item.w && o.x + o.w > item.x);\n if (dy < 0) {\n const above = sameCols.filter((o) => o.y + o.h <= item.y);\n if (!above.length) return layout;\n const near = above.reduce((a, b) => (a.y + a.h > b.y + b.h ? a : b));\n return moveItem(layout, id, item.x, near.y, cols); // takes its row; it is pushed down\n }\n const below = sameCols.filter((o) => o.y >= item.y + item.h);\n if (!below.length) return layout;\n const near = below.reduce((a, b) => (a.y < b.y ? a : b));\n return moveItem(layout, id, item.x, near.y + near.h, cols); // it floats up into the gap left\n}\n\n/** Resize one item from its top-left corner, then settle. */\nexport function resizeItem(layout, id, w, h, cols) {\n const next = layout.map((it) => (it.i === id && !it.static\n ? clampItem({ ...it, w, h }, cols)\n : it));\n return compact(next, cols, id);\n}\n\n/** Rows the layout occupies — the grid's height, which is knowable before any measurement. */\nexport function layoutRows(layout) {\n return layout.reduce((n, it) => Math.max(n, (it.y || 0) + (it.h || 1)), 0);\n}\n\n/** True when two layouts place every item identically — used to skip no-op commits. */\nexport function sameLayout(a, b) {\n if (a.length !== b.length) return false;\n const byId = new Map(b.map((it) => [it.i, it]));\n return a.every((it) => {\n const o = byId.get(it.i);\n return o && o.x === it.x && o.y === it.y && o.w === it.w && o.h === it.h;\n });\n}\n","// A timeline you can edit: lanes of clips against a ruler, with a playhead, trim handles, split,\n// and drag to reorder.\n//\n// ONE NUMBER IS THE COORDINATE SYSTEM. `pps` — pixels per second — converts time to x everywhere:\n// the ruler's ticks, a clip's width, the playhead, every gesture's inverse. Two places computing\n// that conversion is how a ruler and the blocks under it come to disagree, which is the one thing\n// a timeline cannot do and still be read.\n//\n// THE HOST OWNS THE DOCUMENT. Every gesture ends in a callback carrying SECONDS — onTrim, onSplit,\n// onMoveClip, onDeleteClip — and nothing here mutates anything. That is what lets the same\n// component drive a film's cut, a job's phases or a conversation's turns: it knows about time and\n// blocks and nothing about what a block means. It also puts undo where the document is.\n//\n// TIME THAT IS NOT KNOWN IS NOT DRAWN AS TIME. A clip whose duration is null gets a fixed\n// placeholder width and a hatched fill, never a guessed length — a width here is a measurement,\n// and one invented width makes every reading of the ruler above it worthless. Such a clip also\n// gets no trim handles: there is nothing to trim against a length nobody knows.\n//\n// ARTWORK IS ONE REAL FRAME, REPEATED. A filmstrip in a desktop editor shows successive frames\n// pulled from the file. There is no frame-extraction service behind this component, so it tiles\n// the ONE poster it was given at a fixed tile size rather than inventing distinct frames —\n// visibly the same image, which is honest about what is known, and still reads as a strip.\nimport { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';\n\nexport const TL_MIN_PPS = 4;\nexport const TL_MAX_PPS = 400;\nexport const TL_DEFAULT_PPS = 26;\n/** The sticky lane-label gutter. Lanes start at this x. */\nexport const TL_HEAD_W = 84;\n/** Snap magnetism in screen px. Alt bypasses it, the convention everywhere. */\nexport const TL_SNAP_PX = 6;\n/** Nothing may be trimmed shorter than this. */\nexport const TL_MIN_CLIP_S = 0.1;\n/** Pointer travel below which a press is a click, not a drag. */\nconst CLICK_SLOP = 3;\n\nconst LANE_H = 56;\nconst CLIP_INSET = 4;\nconst UNKNOWN_W = 46;\nconst MIN_CLIP_W = 18;\n\nconst clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v));\n\n/* ── ruler + label maths (pure) ─────────────────────────────────────────────────────────────── */\n\nconst TICK_STEPS = [0.1, 0.2, 0.5, 1, 2, 5, 10, 15, 30, 60, 120, 300, 600];\n\n/** The smallest step whose labels stay ~64px apart, so ticks thin out as you zoom out instead of\n * collapsing into a grey bar. */\nexport function majorTickStep(pps) {\n for (const s of TICK_STEPS) if (s * pps >= 64) return s;\n return TICK_STEPS[TICK_STEPS.length - 1];\n}\n\n/** m:ss, with tenths only when the step is sub-second — a label finer than its tick is noise. */\nexport function tickLabel(t, step = 1) {\n const m = Math.floor(t / 60);\n const s = t - m * 60;\n const whole = Math.floor(s + 1e-6);\n const base = `${m}:${String(whole).padStart(2, '0')}`;\n if (step >= 1) return base;\n const frac = Math.round((s - whole) * 10);\n return frac > 0 ? `${base}.${frac}` : base;\n}\n\n/** m:ss for a duration, and '' for anything unmeasured — never '0:00' for an unknown. */\nexport function durationLabel(seconds) {\n if (!Number.isFinite(seconds) || seconds < 0) return '';\n const m = Math.floor(seconds / 60);\n const s = Math.round(seconds - m * 60);\n return `${m}:${String(s).padStart(2, '0')}`;\n}\n\n/** Precise enough to trim against: m:ss.t */\nfunction exactLabel(seconds) {\n if (!Number.isFinite(seconds)) return '—';\n const m = Math.floor(Math.max(0, seconds) / 60);\n const s = Math.max(0, seconds) - m * 60;\n return `${m}:${s < 10 ? '0' : ''}${s.toFixed(1)}`;\n}\n\n/** Where each clip sits. A sequential lane runs its clips end to end (a cut); a placed lane puts\n * each at its own `start`. An unmeasured clip advances by its drawn width, so what follows it\n * stays honest about being approximate. */\nfunction layout(clips, pps, sequential) {\n let cursor = 0;\n return clips.map((c, i) => {\n const known = Number.isFinite(c.duration);\n const w = known ? Math.max(MIN_CLIP_W, c.duration * pps) : UNKNOWN_W;\n const t0 = sequential ? cursor : (c.start || 0);\n if (sequential) cursor += known ? c.duration : UNKNOWN_W / pps;\n return { clip: c, i, t0, x: t0 * pps, w, known };\n });\n}\n\n/** The nearest snap target within `tol` seconds, or the raw value. */\nfunction snapTo(t, targets, tol) {\n let best = null;\n let bestD = tol;\n for (const s of targets) {\n const d = Math.abs(s - t);\n if (d <= bestD) { bestD = d; best = s; }\n }\n return best === null ? { value: t, guide: null } : { value: best, guide: best };\n}\n\n/* ── the component ──────────────────────────────────────────────────────────────────────────── */\n\nexport function Timeline({\n tracks = [],\n currentTime = 0,\n onSeek,\n onSelectClip,\n selectedClipId = null,\n /** (clip, edge:'start'|'end', newDurationSeconds, track). Fires once, on release. */\n onTrim,\n /** (clip, atSecondsFromClipStart, track). */\n onSplit,\n /** Sequential lane: (clip, toIndex, track). Placed lane: (clip, newStartSeconds, track). */\n onMoveClip,\n onDeleteClip,\n /** Something was dropped on a lane: (payload, {trackId, seconds, index}). `trackId` is null when\n * it landed on the NEW-LANE strip below the last lane, which is how a layer gets created by\n * dropping rather than by a button nobody finds. */\n onDropClip,\n /** Reads the drag's payload out of a DataTransfer. Return null to refuse the drop, which is\n * what turns the lane's highlight off for things this timeline cannot take. */\n readDrop,\n /** Text on the strip below the last lane. Omit and no such strip is drawn. */\n newLaneLabel,\n laneAppend,\n zoomStorageKey = null,\n snapStorageKey = null,\n emptyLabel = 'Nothing here yet.',\n className = '',\n}) {\n const scroller = useRef(null);\n const innerRef = useRef(null);\n const [pps, setPps] = useState(() => {\n if (zoomStorageKey && typeof window !== 'undefined') {\n const n = parseFloat(window.localStorage.getItem(zoomStorageKey) || '');\n if (Number.isFinite(n)) return clamp(n, TL_MIN_PPS, TL_MAX_PPS);\n }\n return TL_DEFAULT_PPS;\n });\n const [snapping, setSnapping] = useState(() => (\n snapStorageKey && typeof window !== 'undefined'\n ? window.localStorage.getItem(snapStorageKey) !== '0' : true));\n /** The gesture in flight. A ref because pointer handlers must see it synchronously. */\n const gesture = useRef(null);\n /** What the gesture is doing right now: live preview geometry + annotation. */\n const [drag, setDrag] = useState(null);\n const anchor = useRef(null);\n /** Which lane the pointer is over during a drag, and where in time. Drawn as a marker so a drop\n * lands where it was aimed rather than wherever the list decides. */\n const [dropAt, setDropAt] = useState(null);\n\n const rows = useMemo(\n () => tracks.map((t) => ({ ...t, sequential: t.sequential !== false,\n laid: layout(t.clips || [], pps, t.sequential !== false) })),\n [tracks, pps]);\n\n const contentSeconds = useMemo(() => {\n let end = 0;\n for (const t of rows) for (const l of t.laid) end = Math.max(end, l.t0 + l.w / pps);\n return end;\n }, [rows, pps]);\n\n /** Every clip edge, zero, and the playhead: what a drag snaps to. */\n const snapTimes = useMemo(() => {\n const out = [0, currentTime];\n for (const t of rows) for (const l of t.laid) { out.push(l.t0); out.push(l.t0 + l.w / pps); }\n return out;\n }, [rows, pps, currentTime]);\n\n /* ── zoom ─────────────────────────────────────────────────────────────────────────────────── */\n\n const setZoom = useCallback((next, clientX) => {\n const v = clamp(next, TL_MIN_PPS, TL_MAX_PPS);\n const el = scroller.current;\n if (el) {\n const rect = el.getBoundingClientRect();\n const vx = clientX === undefined ? (rect.width + TL_HEAD_W) / 2 : clientX - rect.left;\n anchor.current = { t: Math.max(0, (el.scrollLeft + vx - TL_HEAD_W) / pps), vx };\n }\n setPps(v);\n if (zoomStorageKey && typeof window !== 'undefined') {\n try { window.localStorage.setItem(zoomStorageKey, String(v)); } catch { /* private mode */ }\n }\n }, [pps, zoomStorageKey]);\n\n const fitPps = useCallback((seconds) => {\n const el = scroller.current;\n if (!el || !(seconds > 0)) return null;\n const room = el.clientWidth - TL_HEAD_W - 56;\n return room > 0 ? clamp(room / seconds, TL_MIN_PPS, TL_MAX_PPS) : null;\n }, []);\n\n const fit = useCallback(() => {\n const v = fitPps(contentSeconds);\n if (v !== null) { setPps(v); if (scroller.current) scroller.current.scrollLeft = 0; }\n }, [fitPps, contentSeconds]);\n\n // Fit ONCE, when there is first something to fit: a one-second clip at a fixed default is a\n // sliver that reads as a broken control. Once, not on every change — re-fitting under someone\n // who just zoomed is the control fighting them. A stored zoom wins; they chose it.\n const fitted = useRef(false);\n useLayoutEffect(() => {\n if (fitted.current || !(contentSeconds > 0)) return;\n if (zoomStorageKey && typeof window !== 'undefined'\n && window.localStorage.getItem(zoomStorageKey)) { fitted.current = true; return; }\n const v = fitPps(contentSeconds);\n if (v !== null) { fitted.current = true; setPps(v); }\n }, [contentSeconds, fitPps, zoomStorageKey]);\n\n useLayoutEffect(() => {\n const a = anchor.current;\n if (!a || !scroller.current) return;\n anchor.current = null;\n scroller.current.scrollLeft = Math.max(0, TL_HEAD_W + a.t * pps - a.vx);\n }, [pps]);\n\n useEffect(() => {\n const el = scroller.current;\n if (!el) return undefined;\n const onWheel = (e) => {\n if (!(e.ctrlKey || e.metaKey)) return;\n e.preventDefault();\n setZoom(pps * Math.exp(-e.deltaY * 0.0022), e.clientX);\n };\n el.addEventListener('wheel', onWheel, { passive: false });\n return () => el.removeEventListener('wheel', onWheel);\n }, [pps, setZoom]);\n\n const timeAt = useCallback((clientX) => {\n const el = innerRef.current;\n if (!el) return 0;\n return Math.max(0, (clientX - el.getBoundingClientRect().left - TL_HEAD_W) / pps);\n }, [pps]);\n\n /* ── gestures ─────────────────────────────────────────────────────────────────────────────── */\n\n /** ONE pointer pipeline for scrub, trim and move. They differ in what they compute, not in how\n * the press, the movement threshold, the listeners and the release are handled. Writing that\n * three times is how one of them ends up without its cleanup and leaves the document mid-edit\n * when the pointer goes up outside the window. */\n const beginGesture = useCallback((e, spec) => {\n e.preventDefault();\n e.stopPropagation();\n gesture.current = { ...spec, startX: e.clientX, active: false, value: null };\n const move = (ev) => {\n const cur = gesture.current;\n if (!cur) return;\n if (!cur.active && Math.abs(ev.clientX - cur.startX) < CLICK_SLOP) return;\n cur.active = true;\n let t = timeAt(ev.clientX);\n let guide = null;\n if (snapping && !ev.altKey && cur.kind !== 'scrub') {\n const r = snapTo(t, cur.snapTimes || snapTimes, TL_SNAP_PX / pps);\n t = r.value; guide = r.guide;\n }\n cur.value = t;\n if (cur.kind === 'scrub') onSeek?.(t);\n else setDrag(cur.preview ? { ...cur.preview(t), guide } : { guide });\n };\n const up = () => {\n window.removeEventListener('pointermove', move);\n window.removeEventListener('pointerup', up);\n document.body.classList.remove('rui-tl-gesturing');\n const cur = gesture.current;\n gesture.current = null;\n setDrag(null);\n if (cur?.active && cur.value !== null) cur.commit?.(cur.value);\n else cur?.click?.();\n };\n document.body.classList.add('rui-tl-gesturing');\n window.addEventListener('pointermove', move);\n window.addEventListener('pointerup', up);\n }, [timeAt, snapping, snapTimes, pps, onSeek]);\n\n const onScrub = useCallback((e) => {\n if (!onSeek) return;\n onSeek(timeAt(e.clientX));\n beginGesture(e, { kind: 'scrub' });\n }, [onSeek, timeAt, beginGesture]);\n\n /* ── split ────────────────────────────────────────────────────────────────────────────────── */\n\n /** The clip the playhead is inside, far enough in that both halves would be legal. */\n const splitTarget = useMemo(() => {\n if (!onSplit) return null;\n for (const track of rows) {\n for (const l of track.laid) {\n if (!l.known) continue;\n if (currentTime > l.t0 + TL_MIN_CLIP_S && currentTime < l.t0 + l.clip.duration - TL_MIN_CLIP_S) {\n return { track, l };\n }\n }\n }\n return null;\n }, [rows, currentTime, onSplit]);\n\n const doSplit = useCallback(() => {\n if (!splitTarget) return;\n onSplit(splitTarget.l.clip, currentTime - splitTarget.l.t0, splitTarget.track);\n }, [splitTarget, currentTime, onSplit]);\n\n const selected = useMemo(() => {\n for (const track of rows) for (const l of track.laid) {\n if (l.clip.id === selectedClipId) return { track, l };\n }\n return null;\n }, [rows, selectedClipId]);\n\n const onKeyDown = useCallback((e) => {\n const tag = e.target?.tagName;\n if (tag === 'INPUT' || tag === 'TEXTAREA' || e.target?.isContentEditable) return;\n if (e.key === '+' || e.key === '=') { e.preventDefault(); setZoom(pps * 1.35); }\n else if (e.key === '-' || e.key === '_') { e.preventDefault(); setZoom(pps / 1.35); }\n else if (e.key === 'b' || e.key === 'B') { e.preventDefault(); doSplit(); }\n else if ((e.key === 'Delete' || e.key === 'Backspace') && selected && onDeleteClip) {\n e.preventDefault(); onDeleteClip(selected.l.clip, selected.track);\n }\n }, [pps, setZoom, doSplit, selected, onDeleteClip]);\n\n const toggleSnap = useCallback(() => {\n setSnapping((v) => {\n const next = !v;\n if (snapStorageKey && typeof window !== 'undefined') {\n try { window.localStorage.setItem(snapStorageKey, next ? '1' : '0'); } catch { /* ignore */ }\n }\n return next;\n });\n }, [snapStorageKey]);\n\n /* ── render ───────────────────────────────────────────────────────────────────────────────── */\n\n const major = majorTickStep(pps);\n const minor = major / 5;\n const laneW = Math.max(contentSeconds * pps + 140, 320);\n const ticks = [];\n for (let t = 0; t <= contentSeconds + major; t += major) ticks.push(t);\n\n return (\n <div className={`rui-tl ${className}`} onKeyDown={onKeyDown} tabIndex={0}>\n {/* ── toolbar ─────────────────────────────────────────────────────────────────────────\n The timeline's commands live in a bar, not in a pill floating over the lanes: chrome\n hovering in the corner of the content reads as debris. Every disabled control says WHY,\n because one that is off without a reason looks broken. */}\n <div className=\"rui-tl-bar\">\n {onSplit && (\n <button type=\"button\" className=\"rui-tl-btn\" onClick={doSplit} disabled={!splitTarget}\n title={splitTarget ? 'Split at the playhead (B)'\n : 'Move the playhead inside a clip to split it'}>\n <svg width=\"13\" height=\"13\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\"\n strokeWidth=\"2\" strokeLinecap=\"round\" aria-hidden=\"true\">\n <circle cx=\"6\" cy=\"6\" r=\"3\" /><circle cx=\"6\" cy=\"18\" r=\"3\" />\n <line x1=\"20\" y1=\"4\" x2=\"8.12\" y2=\"15.88\" />\n <line x1=\"14.47\" y1=\"14.48\" x2=\"20\" y2=\"20\" />\n <line x1=\"8.12\" y1=\"8.12\" x2=\"12\" y2=\"12\" />\n </svg>\n <span>Split</span>\n </button>\n )}\n {onDeleteClip && (\n <button type=\"button\" className=\"rui-tl-btn\" disabled={!selected}\n onClick={() => selected && onDeleteClip(selected.l.clip, selected.track)}\n title={selected ? 'Remove the selected clip' : 'Select a clip to remove it'}>\n Remove\n </button>\n )}\n <button type=\"button\" className={`rui-tl-btn${snapping ? ' is-on' : ''}`}\n onClick={toggleSnap} aria-pressed={snapping}\n title=\"Snap to clip edges and the playhead. Hold Alt while dragging to bypass.\">\n Snap\n </button>\n <span className=\"rui-tl-time\" aria-label=\"Playhead position\">{exactLabel(currentTime)}</span>\n <span className=\"rui-tl-spacer\" />\n <button type=\"button\" className=\"rui-tl-btn rui-tl-icon\" onClick={() => setZoom(pps / 1.35)}\n disabled={pps <= TL_MIN_PPS + 1e-6} aria-label=\"Zoom out\" title=\"Zoom out (−)\">−</button>\n <button type=\"button\" className=\"rui-tl-btn rui-tl-icon\" onClick={() => setZoom(pps * 1.35)}\n disabled={pps >= TL_MAX_PPS - 1e-6} aria-label=\"Zoom in\" title=\"Zoom in (+)\">+</button>\n <button type=\"button\" className=\"rui-tl-btn\" onClick={fit} disabled={!(contentSeconds > 0)}\n title=\"Fit the whole timeline in the panel\">Fit</button>\n </div>\n\n <div className=\"rui-tl-scroll\" ref={scroller}>\n <div className=\"rui-tl-inner\" ref={innerRef} style={{ width: TL_HEAD_W + laneW }}>\n\n {/* ── ruler ──────────────────────────────────────────────────────────────────────── */}\n <div className=\"rui-tl-row rui-tl-rulerrow\">\n <div className=\"rui-tl-head rui-tl-rulerhead\" aria-hidden=\"true\" />\n <div\n className=\"rui-tl-ruler\"\n style={{\n width: laneW,\n // Minor ticks are a repeating background, not elements: ten minutes at a fine zoom\n // is thousands of nodes carrying no information a stripe does not.\n backgroundImage:\n 'linear-gradient(90deg, var(--uic-line, #DDDFE6) 0 1px, transparent 1px),'\n + 'linear-gradient(90deg, var(--uic-line-soft, #EFF1F4) 0 1px, transparent 1px)',\n backgroundSize: `${major * pps}px 9px, ${minor * pps}px 5px`,\n }}\n onPointerDown={onScrub}\n role={onSeek ? 'slider' : undefined}\n aria-label={onSeek ? 'Playhead' : undefined}\n aria-valuemin={0} aria-valuemax={Math.round(contentSeconds)}\n aria-valuenow={Math.round(currentTime)}\n tabIndex={onSeek ? 0 : undefined}\n onKeyDown={onSeek ? (e) => {\n const step = e.shiftKey ? 5 : 1;\n if (e.key === 'ArrowLeft') { e.preventDefault(); onSeek(Math.max(0, currentTime - step)); }\n if (e.key === 'ArrowRight') { e.preventDefault(); onSeek(currentTime + step); }\n } : undefined}\n >\n {ticks.map((t) => (\n <span key={t} className=\"rui-tl-ticklbl\" style={{ left: t * pps }}>\n {tickLabel(t, major)}\n </span>\n ))}\n </div>\n </div>\n\n {/* ── lanes ──────────────────────────────────────────────────────────────────────── */}\n {rows.length === 0 && <p className=\"rui-tl-empty\">{emptyLabel}</p>}\n\n {rows.map((track) => (\n <div className=\"rui-tl-row\" key={track.id}>\n {/* A lane whose name does not explain it can say what it is for. \"Layer 2\" means\n nothing until something says it is drawn over Layer 1. */}\n <div className=\"rui-tl-head\" title={track.title || track.label}>\n {track.icon}\n <span className=\"rui-tl-headlbl\">{track.label}</span>\n </div>\n <div\n className={'rui-tl-lane' + (dropAt?.trackId === track.id ? ' is-dropping' : '')}\n style={{ width: laneW, height: LANE_H }}\n onPointerDown={(e) => { if (e.target === e.currentTarget) onScrub(e); }}\n onDragOver={onDropClip ? (e) => {\n if (!readDrop || readDrop(e.dataTransfer) === null) return;\n e.preventDefault(); // preventDefault IS the \"yes, drop here\"\n e.dataTransfer.dropEffect = 'copy';\n setDropAt({ trackId: track.id, t: timeAt(e.clientX) });\n } : undefined}\n onDragLeave={onDropClip ? (e) => {\n if (e.currentTarget.contains(e.relatedTarget)) return;\n setDropAt((d) => (d?.trackId === track.id ? null : d));\n } : undefined}\n onDrop={onDropClip ? (e) => {\n const payload = readDrop?.(e.dataTransfer) ?? null;\n setDropAt(null);\n if (payload === null) return;\n e.preventDefault();\n const t = timeAt(e.clientX);\n // Where in the ORDER it landed, for a lane that is a sequence.\n let index = 0;\n for (const other of track.laid) {\n if (t > other.t0 + (other.w / pps) / 2) index += 1;\n }\n onDropClip(payload, { trackId: track.id, seconds: t, index });\n } : undefined}>\n {track.laid.length === 0 && track.emptyLabel && (\n <p className=\"rui-tl-laneempty\">{track.emptyLabel}</p>\n )}\n {track.laid.map((l) => (\n <Clip\n key={l.clip.id ?? l.i}\n l={l} track={track} pps={pps}\n selected={selectedClipId === l.clip.id}\n drag={drag}\n onSelect={() => onSelectClip?.(l.clip, l.i)}\n beginGesture={beginGesture}\n onTrim={onTrim} onMoveClip={onMoveClip}\n snapTimes={snapTimes}\n />\n ))}\n {dropAt?.trackId === track.id && (\n <span className=\"rui-tl-dropmark\" style={{ left: dropAt.t * pps }}\n aria-hidden=\"true\" />\n )}\n {laneAppend && (\n <span className=\"rui-tl-append\"\n style={{ left: track.laid.reduce((n, x) => Math.max(n, x.x + x.w), 0) + 6 }}>\n {laneAppend(track)}\n </span>\n )}\n </div>\n </div>\n ))}\n\n {/* Drop here and a lane is created. It only exists when a drop is possible at all, and\n it says what it does — a bare dashed rectangle is a thing people avoid rather than\n aim at. */}\n {onDropClip && newLaneLabel && (\n <div className=\"rui-tl-row\">\n <div className=\"rui-tl-head rui-tl-newhead\" aria-hidden=\"true\" />\n <div\n className={'rui-tl-newlane' + (dropAt?.trackId === null ? ' is-dropping' : '')}\n style={{ width: laneW }}\n onDragOver={(e) => {\n if (!readDrop || readDrop(e.dataTransfer) === null) return;\n e.preventDefault();\n e.dataTransfer.dropEffect = 'copy';\n setDropAt({ trackId: null, t: timeAt(e.clientX) });\n }}\n onDragLeave={(e) => {\n if (e.currentTarget.contains(e.relatedTarget)) return;\n setDropAt((d) => (d?.trackId === null ? null : d));\n }}\n onDrop={(e) => {\n const payload = readDrop?.(e.dataTransfer) ?? null;\n setDropAt(null);\n if (payload === null) return;\n e.preventDefault();\n onDropClip(payload, { trackId: null, seconds: timeAt(e.clientX), index: 0 });\n }}\n >\n <span className=\"rui-tl-newlbl\">{newLaneLabel}</span>\n </div>\n </div>\n )}\n\n {/* A snap guide, drawn only while a gesture is actually locked onto something. */}\n {drag?.guide != null && (\n <div className=\"rui-tl-guide\" style={{ left: TL_HEAD_W + drag.guide * pps }}\n aria-hidden=\"true\" />\n )}\n\n {Number.isFinite(currentTime) && (\n <div className=\"rui-tl-playhead\" style={{ left: TL_HEAD_W + currentTime * pps }}\n aria-hidden=\"true\">\n <span className=\"rui-tl-playhead-grip\" />\n </div>\n )}\n\n {/* Numbers where the gesture is, so a trim is read off the clip and not off the ruler. */}\n {drag?.annotation && (\n <div className=\"rui-tl-annot\" style={{ left: TL_HEAD_W + (drag.annotAt || 0) * pps }}>\n {drag.annotation}\n </div>\n )}\n </div>\n </div>\n </div>\n );\n}\n\n/* ── one clip ───────────────────────────────────────────────────────────────────────────────── */\n\nfunction Clip({ l, track, pps, selected, drag, onSelect, beginGesture, onTrim, onMoveClip,\n snapTimes }) {\n const { clip, x, w, known, t0, i } = l;\n const live = drag?.clipId === clip.id ? drag : null;\n const width = live?.width ?? w;\n const left = live?.left ?? x;\n\n // A FIXED tile size, so zooming changes how many frames you see rather than stretching one.\n // That is the filmstrip convention; see the note at the top on these being one frame repeated.\n const tileW = Math.round((LANE_H - CLIP_INSET * 2) * (16 / 9));\n\n const startTrim = (e, edge) => {\n if (!onTrim || !known) return;\n // HOW FAR THIS EDGE CAN GO BACK OUT, not just in. A trim clamped to the clip's CURRENT length\n // can only ever shorten, so one stray drag makes a shot unrecoverable — the film is still in\n // the file and the UI will not give it back. `headroom` is what the host says is left on each\n // side beyond the present window; absent, the edge can only come in, which is the old\n // behaviour and the honest default when nobody has said otherwise.\n const room = clip.headroom || {};\n const outward = Math.max(0, Number(edge === 'end' ? room.end : room.start) || 0);\n const maxDur = clip.duration + outward;\n beginGesture(e, {\n kind: 'trim',\n snapTimes,\n preview: (t) => {\n const dur = edge === 'end'\n ? clamp(t - t0, TL_MIN_CLIP_S, maxDur)\n : clamp((t0 + clip.duration) - t, TL_MIN_CLIP_S, maxDur);\n const nextW = dur * pps;\n const nextLeft = edge === 'end' ? x : x + (w - nextW);\n return { clipId: clip.id, width: nextW, left: nextLeft,\n annotation: `${exactLabel(dur)} · ${edge === 'end' ? 'out' : 'in'}`,\n annotAt: (nextLeft + nextW) / pps };\n },\n commit: (t) => {\n const dur = edge === 'end'\n ? clamp(t - t0, TL_MIN_CLIP_S, maxDur)\n : clamp((t0 + clip.duration) - t, TL_MIN_CLIP_S, maxDur);\n if (Math.abs(dur - clip.duration) > 1e-3) onTrim(clip, edge, dur, track);\n },\n });\n };\n\n const startMove = (e) => {\n if (!onMoveClip) { onSelect(); return; }\n const half = (known ? clip.duration : 0) / 2;\n beginGesture(e, {\n kind: 'move',\n snapTimes,\n preview: (t) => {\n const at = Math.max(0, t - half);\n return { clipId: clip.id, left: at * pps, annotation: exactLabel(at), annotAt: at };\n },\n commit: (t) => {\n const at = Math.max(0, t - half);\n if (track.sequential) {\n // On a cut, POSITION MEANS ORDER. Which slot the clip's centre landed in is the answer,\n // and reordering is what the host is asked for — \"move this to 4.2s\" is not a thing a\n // magnetic track can honour, and pretending otherwise puts the drawing and the document\n // out of step the moment it re-renders.\n let idx = 0;\n for (const other of track.laid) {\n if (other.clip.id === clip.id) continue;\n if (at + half > other.t0 + (other.w / pps) / 2) idx += 1;\n }\n if (idx !== i) onMoveClip(clip, idx, track);\n } else if (Math.abs(at - t0) > 1e-3) {\n onMoveClip(clip, at, track);\n }\n },\n click: onSelect,\n });\n };\n\n return (\n <article\n className={'rui-tl-clip'\n + (clip.state ? ` is-${clip.state}` : '')\n + (known ? '' : ' is-unmeasured')\n + (selected ? ' is-selected' : '')\n + (live ? ' is-live' : '')}\n style={{ left, width, ...(clip.accent ? { '--rui-tl-accent': clip.accent } : null) }}\n title={clip.title || clip.label}\n tabIndex={0}\n onPointerDown={startMove}\n onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); onSelect(); } }}\n >\n {/* A poster tiles as a strip. With no poster but a playable file, the FILE's own first\n frame is shown — `preload=\"metadata\"` paints it without fetching the whole clip, and it\n is a real frame of the real thing rather than a stand-in. Only when there is neither\n does the block fall back to a glyph, which claims nothing. */}\n {clip.poster ? (\n <span className=\"rui-tl-strip\" style={{\n backgroundImage: `url(\"${String(clip.poster).replace(/\"/g, '\\\\\"')}\")`,\n backgroundSize: `${tileW}px 100%`,\n }} />\n ) : clip.video ? (\n <video className=\"rui-tl-frame\" src={clip.video} preload=\"metadata\" muted playsInline\n tabIndex={-1} aria-hidden=\"true\" />\n ) : (\n <span className=\"rui-tl-blank\" aria-hidden=\"true\">{clip.glyph}</span>\n )}\n\n {clip.badge && <span className=\"rui-tl-badge\">{clip.badge}</span>}\n {known && width > 46 && <span className=\"rui-tl-dur\">{durationLabel(clip.duration)}</span>}\n {clip.label && width > 104 && <span className=\"rui-tl-name\">{clip.label}</span>}\n\n {/* Trim handles, only on a measured clip: there is nothing to trim against a length nobody\n knows, and offering the gesture anyway would conjure a duration out of a drag. */}\n {onTrim && known && (\n <>\n <span className=\"rui-tl-trim l\" onPointerDown={(e) => startTrim(e, 'start')}\n role=\"separator\" aria-label={`Trim the start of ${clip.label || 'this clip'}`} />\n <span className=\"rui-tl-trim r\" onPointerDown={(e) => startTrim(e, 'end')}\n role=\"separator\" aria-label={`Trim the end of ${clip.label || 'this clip'}`} />\n </>\n )}\n </article>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACwBO,SAAS,0BAA0B,GAAG;AAG3C,QAAM,UAAU,CAAC;AACjB,QAAM,OAAO;AAAA,IACX,YAAY;AAAA,IACZ,SAAS,IAAI;AACX,YAAM,IAAI,GAAG;AACb,cAAQ,GAAG;AAAA,QACT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K;AAAA,cAClE,MAAK;AAAA,cAAY,cAAY,mBAAmB,KAAK,SAAS,WAAW;AAAA;AAAA,UAAI;AAAA,WACrF;AAAA;AAAA;AAAA,EAEJ;AAEJ;","names":["import_react","import_react","import_jsx_runtime","React","import_react","import_jsx_runtime","React","import_react","import_jsx_runtime","import_react","import_react","import_jsx_runtime","Chip","import_jsx_runtime","listening","import_react","import_jsx_runtime","mod","React","import_react","import_jsx_runtime","clamp","import_react","import_jsx_runtime","import_react","import_react","import_jsx_runtime","stack","Field","import_react","import_react","import_jsx_runtime","import_react","import_jsx_runtime","CLIENT_ID","import_jsx_runtime","subtitle","import_react","import_react","import_react","import_react_dom","import_jsx_runtime","import_jsx_runtime","MentionInput","s","React","import_react_dom","import_jsx_runtime","import_react","import_jsx_runtime","import_jsx_runtime","bytesLabel","import_react","import_jsx_runtime","import_react","import_jsx_runtime","import_react","import_jsx_runtime","import_react","import_jsx_runtime","subtitle","import_react","import_jsx_runtime","import_react","import_jsx_runtime","onKey","import_react","import_react_dom","import_jsx_runtime","import_react","import_jsx_runtime","import_react","layout","near","import_jsx_runtime","layout","stack","onKey","React","import_react","import_jsx_runtime"]}
|