1"use client";23/**4 * Copilot — a floating clinical copilot, as copy-as-source.5 *6 * This is the second skin over `@zoblocks/copilot-react`. The antd skin7 * (`@zoblocks/copilot`) is the first. Both are thin: the engine, the8 * safety pipeline, the streaming announcement strategy, the combobox keyboard9 * model and the citation segmentation all live in the two npm packages, so the10 * two skins cannot drift on any of the parts where drifting would be an11 * accessibility or safety defect.12 *13 * That split is what lets this component stay copyable. A registry item that14 * had to carry the crisis classifier and the audit mapping inline would be15 * thousands of lines nobody would read before pasting, and a safety control16 * nobody reads is not a safety control.17 *18 * Three props are worth reading before you use it:19 *20 * `suppressed` — removes the component entirely. Set it while the clinician21 * is administering medication or signing orders. Interruptions during those22 * tasks measurably increase clinical errors, and the FDA's 2026 CDS guidance23 * moved time-critical use under the criterion about independent review for24 * the same reason. The most valuable thing this component does is disappear.25 *26 * `context` — the resolver. Without one, only modes that read nothing will27 * run. That is deliberate: reference lookup is the safest first deployment28 * and needs no BAA covering patient data in the model call.29 *30 * `provider` — targets *your* endpoint, never a model vendor. There is no31 * apiKey prop and no way to add one.32 */3334import * as React from "react";35import {36 ChevronDownIcon,37 CloseIcon,38 CopyIcon,39 InsertIcon,40 LockIcon,41 MicIcon,42 NewChatIcon,43 PersonIcon,44 SendIcon,45 ShortcutIcon,46 SparkIcon,47 StopIcon,48 ThoughtIcon,49 ThumbDownIcon,50 ThumbUpIcon,51 VerifyIcon,52 CopilotAnswerRegion,53 CopilotDockRegion,54 CopilotLiveRegion,55 CopilotRoot,56 citationLabel,57 modeIcon,58 segmentAnswer,59 useCopilot,60 useShortcutMenu,61 useSummonShortcut,62 type CopilotShortcut,63 type UseCopilotOptions,64} from "@zoblocks/copilot-react";65import { cn } from "@/lib/utils";6667export interface CopilotProps extends UseCopilotOptions {68 /**69 * Prompts offered before the reader types. They are starting points, not commands — each70 * still runs through its mode's contract.71 */72 shortcuts?: readonly CopilotShortcut[];73 /**74 * ARIA role for the dock. Defaults to `complementary`, so the copilot is findable and75 * skippable rather than an unnamed div.76 */77 role?: string;78 /** Where the dock sits. `inline` renders it in flow for a surface that has its own layout. */79 anchor?: "bottom-center" | "bottom-right" | "inline";80 /** Applied to the dock's outer element. */81 className?: string;82 /**83 * Called when the reader chooses to put an answer into the note they are writing. Receives84 * text; the host owns where it lands and what provenance it carries.85 */86 onInsert?: (text: string) => void;87 /**88 * Called when a safety classifier escalates. The host runs its own protocol — this component89 * never decides what happens next in a crisis.90 */91 onRiskProtocol?: () => void;92}9394export function Copilot({95 shortcuts = [],96 role,97 anchor = "bottom-center",98 className,99 onInsert,100 onRiskProtocol,101 ...options102}: CopilotProps) {103 const api = useCopilot(options);104 const [trayOpen, setTrayOpen] = React.useState(false);105 const fieldRef = React.useRef<HTMLInputElement>(null);106107 const menu = useShortcutMenu({108 shortcuts,109 draft: api.draft,110 ...(role !== undefined ? { role } : {}),111 onSelect: (shortcut) => {112 if (shortcut.modeId) api.setMode(shortcut.modeId);113 api.setDraft(shortcut.question);114 },115 onEscape: () => setTrayOpen(false),116 });117118 useSummonShortcut({ onSummon: () => fieldRef.current?.focus() });119120 const threadOpen = api.state.messages.length > 0 || api.state.status === "crisis";121122 // Collapsed, this is one button. A clinician who puts the assistant away has123 // to find it put away — anything that re-expands on its own teaches them that124 // dismissing it does not work.125 if (api.collapsed) {126 return (127 <CopilotRoot api={api}>128 <div129 data-zb-copilot=""130 data-zb-collapsed=""131 className={cn(132 "z-[900] flex justify-end",133 anchor !== "inline" &&134 "fixed inset-x-0 bottom-0 px-4 pb-[max(1rem,env(safe-area-inset-bottom))]",135 "pointer-events-none [&>*]:pointer-events-auto",136 className,137 )}138 >139 <CopilotLiveRegion message={api.announcer.message} />140 <button141 type="button"142 aria-label="Reopen the assistant"143 onClick={() => api.setCollapsed(false)}144 className="grid h-12 w-12 place-items-center rounded-full bg-[var(--zb-accent)] text-[var(--zb-text-on-accent)] shadow-lg"145 >146 <SparkIcon />147 </button>148 </div>149 </CopilotRoot>150 );151 }152153 return (154 <CopilotRoot api={api}>155 <div156 data-zb-copilot=""157 data-zb-status={api.state.status}158 className={cn(159 "z-[900] flex flex-col gap-2",160 // The dock centres; the thread docks to a side. A dock is a summons161 // bar and belongs where the eye already is, but a thread is something162 // you read *against* the record — centred, it sits on top of the163 // chart being discussed, and the first thing anyone does is drag it164 // out of the way.165 threadOpen ? "items-start" : "items-center",166 anchor !== "inline" &&167 "fixed inset-x-0 bottom-0 px-4 pb-[max(1rem,env(safe-area-inset-bottom))]",168 anchor === "bottom-right" && "items-end",169 "pointer-events-none [&>*]:pointer-events-auto",170 className,171 )}172 >173 <CopilotLiveRegion message={api.announcer.message} />174175 {threadOpen ? (176 <CopilotPanel177 api={api}178 {...(onInsert ? { onInsert } : {})}179 {...(onRiskProtocol ? { onRiskProtocol } : {})}180 />181 ) : (182 <CopilotDockRegion className="flex w-full max-w-2xl flex-col gap-1.5">183 {trayOpen ? (184 <div className="rounded-2xl border border-[var(--zb-border)] bg-[var(--zb-surface)] p-3 shadow-lg">185 <div role="group" aria-label="Change mode" className="mb-2 flex flex-wrap gap-1.5">186 {api.modes.map((mode) => (187 <button188 key={mode.id}189 type="button"190 aria-pressed={mode.id === api.mode.id}191 onClick={() => api.setMode(mode.id)}192 className={cn(193 "min-h-6 rounded-lg px-2.5 py-1 text-sm",194 mode.id === api.mode.id195 ? "bg-[var(--zb-accent)] text-[var(--zb-text-on-accent)]"196 : "border border-[var(--zb-border)] text-[var(--zb-text)]",197 )}198 >199 {mode.label}200 </button>201 ))}202 </div>203 <ul className="m-0 list-none p-0">204 {api.mode.suggestions.map((suggestion) => (205 <li206 key={suggestion.id}207 className="border-t border-[var(--zb-border)] first:border-t-0"208 >209 <button210 type="button"211 className="w-full px-1 py-2 text-start"212 onClick={() => {213 api.setDraft(suggestion.question ?? suggestion.label);214 setTrayOpen(false);215 }}216 >217 <span className="block text-sm text-[var(--zb-text)]">218 {suggestion.label}219 </span>220 {/* The scope, shown at the point of choice. */}221 {suggestion.reads ? (222 <span className="block text-xs text-[var(--zb-text-muted)]">223 {suggestion.reads}224 </span>225 ) : null}226 </button>227 </li>228 ))}229 </ul>230 </div>231 ) : null}232233 {menu.open ? (234 <ul235 {...menu.listProps}236 aria-label="Shortcuts"237 className="m-0 list-none rounded-2xl border border-[var(--zb-border)] bg-[var(--zb-surface)] p-2 shadow-lg"238 >239 {menu.items.map((item, index) => (240 <li241 key={item.id}242 {...menu.optionProps(index)}243 className="cursor-pointer rounded-lg px-2 py-1.5 text-sm aria-selected:bg-[color-mix(in_oklab,var(--zb-accent)_12%,transparent)]"244 >245 {item.label}246 </li>247 ))}248 </ul>249 ) : null}250251 <ScopeStrip api={api} onChange={() => setTrayOpen(true)} />252253 <div className="flex items-center gap-1.5 rounded-2xl border border-[var(--zb-border)] bg-[var(--zb-surface)] px-2 py-1.5 shadow-[0_1px_2px_rgb(0_0_0/0.05),0_12px_32px_-14px_rgb(0_0_0/0.22)]">254 {/* The square glyph. Also the "/" affordance, so the shortcut255 menu has a visible way in for anyone who never learns the key. */}256 <button257 type="button"258 aria-label="Shortcuts"259 onClick={() => api.setDraft(api.draft.startsWith("/") ? api.draft : "/")}260 className="grid size-8 shrink-0 place-items-center rounded-[10px] border border-[var(--zb-border)] bg-[var(--zb-bg-subtle)] text-base text-[var(--zb-text-muted)]"261 >262 <ShortcutIcon />263 </button>264265 <input266 ref={fieldRef}267 value={api.draft}268 aria-label="Clinical assistant"269 placeholder={270 api.mode.reads.length > 0 ? "Ask about this patient…" : "Search the evidence…"271 }272 onChange={(event) => api.setDraft(event.target.value)}273 onKeyDown={(event) => {274 menu.inputProps.onKeyDown(event);275 if (event.key === "Enter" && !menu.open) {276 event.preventDefault();277 void api.submit();278 }279 }}280 role={menu.inputProps.role}281 aria-expanded={menu.inputProps["aria-expanded"]}282 aria-controls={menu.inputProps["aria-controls"]}283 aria-autocomplete={menu.inputProps["aria-autocomplete"]}284 {...(menu.inputProps["aria-activedescendant"]285 ? { "aria-activedescendant": menu.inputProps["aria-activedescendant"] }286 : {})}287 className="min-w-0 flex-1 bg-transparent px-1 text-[var(--zb-text)] outline-none placeholder:text-[var(--zb-text-muted)] [@media(pointer:coarse)]:text-[length:max(16px,1em)]"288 />289290 {(() => {291 const ModeGlyph = modeIcon(api.mode.id);292 return (293 <button294 type="button"295 aria-expanded={trayOpen}296 onClick={() => setTrayOpen((open) => !open)}297 className="inline-flex min-h-8 shrink-0 items-center gap-1.5 rounded-[10px] border border-[var(--zb-border)] bg-[var(--zb-bg-subtle)] px-2.5 py-1 text-sm text-[var(--zb-text)]"298 >299 <ModeGlyph className="text-[var(--zb-text-muted)]" />300 {api.mode.label}301 </button>302 );303 })()}304305 {api.dictation.active ? (306 <button307 type="button"308 aria-label="Stop dictation"309 onClick={() => api.dictation.stop()}310 className="min-h-6 min-w-6 rounded-lg px-2 text-[var(--zb-status-normal)]"311 >312 <span className="inline-flex gap-[2px]" aria-hidden="true">313 <i className="block h-3 w-[2px] animate-pulse rounded bg-current" />314 <i className="block h-2 w-[2px] animate-pulse rounded bg-current [animation-delay:120ms]" />315 <i className="block h-3.5 w-[2px] animate-pulse rounded bg-current [animation-delay:240ms]" />316 </span>317 {/* Colour and motion alone would be a 1.4.1 failure, and in a318 consulting room it is also a privacy problem. */}319 <span className="sr-only">Microphone is live</span>320 </button>321 ) : (322 <button323 type="button"324 aria-label="Start dictation"325 onClick={api.dictation.start}326 disabled={api.state.status === "streaming" || api.state.status === "submitting"}327 className="grid size-8 shrink-0 place-items-center rounded-[10px] text-base text-[var(--zb-text-muted)] disabled:opacity-40"328 >329 <MicIcon />330 </button>331 )}332333 {api.state.status === "streaming" || api.state.status === "submitting" ? (334 <button335 type="button"336 onClick={api.stop}337 className="grid size-8 shrink-0 place-items-center rounded-[10px] border border-[var(--zb-border)] text-base"338 >339 <StopIcon />340 <span className="sr-only">Stop</span>341 </button>342 ) : (343 <button344 type="button"345 disabled={!api.canSubmit}346 onClick={() => void api.submit()}347 className="grid size-8 shrink-0 place-items-center rounded-[10px] bg-[var(--zb-accent)] text-base text-[var(--zb-text-on-accent)] disabled:opacity-40"348 >349 <SendIcon />350 <span className="sr-only">Send</span>351 </button>352 )}353 </div>354355 {/* Never dismissible. */}356 <p className="m-0 text-center text-xs text-[var(--zb-text-muted)]">357 Medical knowledge only. Not for autonomous decision making. Check sources and use your358 clinical judgement.359 </p>360 </CopilotDockRegion>361 )}362 </div>363 </CopilotRoot>364 );365}366367/**368 * The scope strip.369 *370 * The highest-value element on the surface, and the one that is easiest to371 * leave out. A clinician needs to know what the assistant can see *before*372 * they trust a summary, and — the part everyone omits — what it could not see.373 * A summary that silently excludes a protected record has created a false374 * belief that would not exist if the tool did not exist.375 */376function ScopeStrip({377 api,378 onChange,379}: {380 api: ReturnType<typeof useCopilot>;381 onChange: () => void;382}) {383 const { scope } = api;384385 // "Change" opens the mode tray rather than a scope picker of its own. Scope386 // *is* the mode's `reads` contract, so a second control that edited it387 // independently would let the two disagree — and the strip is the thing a388 // clinician is being asked to trust.389 const change = (390 <button391 type="button"392 onClick={onChange}393 className="rounded-full font-medium text-[var(--zb-accent)] underline underline-offset-2"394 >395 Change396 </button>397 );398399 // A pill that sizes to its own text, not a full-width bar. The strip is a400 // statement about *this* answer, and a bar spanning the dock reads as chrome —401 // which is exactly the thing people stop seeing.402 const shell =403 // `rounded-2xl` rather than a full pill: the category list is host-supplied404 // and a pill that wraps to three lines reads as a rendering fault.405 "m-0 mx-auto flex w-fit max-w-full flex-wrap items-center justify-center gap-x-2 gap-y-1 rounded-2xl border border-[var(--zb-border)] bg-[var(--zb-surface)] px-3 py-1 text-xs text-[var(--zb-text-muted)] shadow-[0_1px_2px_rgb(0_0_0/0.04)]";406407 if (scope.categories.length === 0) {408 return (409 <p className={shell}>410 <LockIcon className="shrink-0" />411 No patient data is being used412 {change}413 </p>414 );415 }416417 return (418 <p className={shell}>419 <PersonIcon className="shrink-0" />420 <span>421 Reading{" "}422 <strong className="font-semibold text-[var(--zb-text)]">423 {scope.subject?.display ?? scope.subject?.reference}424 </strong>425 {" · "}426 {scope.categories.join(", ")}427 </span>428 {scope.showWithheld ? (429 <span className="inline-flex items-center gap-1 rounded-full bg-[color-mix(in_oklab,var(--zb-status-high)_20%,transparent)] px-2 py-px text-[var(--zb-text)]">430 <LockIcon className="shrink-0" />431 {scope.withheldCount} record{scope.withheldCount === 1 ? "" : "s"} withheld432 </span>433 ) : null}434 {change}435 </p>436 );437}438439/**440 * A retrieved passage with the supporting clause marked.441 *442 * This is the difference between a citation and a verification. A source title443 * tells a clinician where an answer came from; it does not tell them the model444 * read that source correctly, and checking costs a tab, a search and a scan of445 * a forty-page guideline. Nobody pays that during a consultation — which is the446 * mechanism behind automation bias, an effort asymmetry rather than a character447 * flaw.448 *449 * Marking the clause makes the check a glance. `<mark>` rather than a styled450 * span because the semantics are exactly right and it survives forced-colours451 * mode, where a background tint would vanish and take the meaning with it.452 *453 * Offsets are host-supplied and clamped rather than trusted: a provider that454 * returns a stale range should mark the wrong words at worst, never throw away455 * the passage.456 */457export interface HighlightedPassageProps {458 /** The source passage, verbatim. Never re-flowed or truncated — a citation the reader cannot check against the original is not a citation. */459 text: string;460 /**461 * Character offsets of the span the answer drew on, as `[start, end]`.462 *463 * Out-of-range offsets highlight nothing rather than throwing: a citation464 * that points past the end of its own source is a bug in the caller, and465 * silently marking the wrong sentence would be worse than marking none.466 */467 at?: readonly [number, number];468}469470export function HighlightedPassage({ text, at }: HighlightedPassageProps) {471 if (!at) return <>{text}</>;472473 const start = Math.max(0, Math.min(at[0], text.length));474 const end = Math.max(start, Math.min(at[1], text.length));475 if (start === end) return <>{text}</>;476477 return (478 <>479 {text.slice(0, start)}480 <mark className="rounded bg-[color-mix(in_oklab,var(--zb-status-high)_28%,transparent)] px-0.5 text-[var(--zb-text)]">481 {text.slice(start, end)}482 </mark>483 {text.slice(end)}484 </>485 );486}487488function CopilotPanel({489 api,490 onInsert,491 onRiskProtocol,492}: {493 api: ReturnType<typeof useCopilot>;494 onInsert?: (text: string) => void;495 onRiskProtocol?: () => void;496}) {497 const modeSelectRef = React.useRef<HTMLSelectElement>(null);498499 return (500 <section501 aria-label="Assistant conversation"502 // A column, not a banner. The record stays readable beside it, which is503 // the whole reason a clinician opened a thread about that record.504 className="flex max-h-[min(78dvh,44rem)] w-full max-w-md flex-col overflow-hidden rounded-2xl border border-[var(--zb-border)] bg-[var(--zb-surface)] shadow-[0_1px_2px_rgb(0_0_0/0.05),0_16px_40px_-16px_rgb(0_0_0/0.28)]"505 >506 <header className="flex items-center justify-between border-b border-[var(--zb-border)] px-3 py-2">507 {api.threads.length > 1 ? (508 <label className="flex min-w-0 items-center gap-1">509 <span className="sr-only">Switch conversation</span>510 <select511 value={api.activeThreadId}512 onChange={(event) => api.switchThread(event.target.value)}513 className="min-w-0 max-w-[18rem] truncate bg-transparent text-sm font-semibold text-[var(--zb-text)] outline-none"514 >515 {api.threads.map((thread) => (516 <option key={thread.id} value={thread.id}>517 {thread.title}518 </option>519 ))}520 </select>521 <ChevronDownIcon />522 </label>523 ) : (524 <h2 className="m-0 truncate text-sm font-semibold text-[var(--zb-text)]">525 {api.threads[0]?.title ?? api.mode.label}526 </h2>527 )}528 <button529 type="button"530 onClick={api.newThread}531 className="min-h-6 min-w-6 shrink-0 rounded-lg border border-[var(--zb-border)] px-2 py-0.5 text-xs"532 >533 <NewChatIcon />534 <span className="sr-only">New chat</span>535 </button>536 <button537 type="button"538 aria-label="Put the assistant away"539 onClick={() => api.setCollapsed(true)}540 className="min-h-6 min-w-6 rounded-lg px-1"541 >542 <CloseIcon />543 </button>544 </header>545546 <div className="flex flex-1 flex-col gap-3 overflow-y-auto p-3">547 {api.state.messages.map((message) =>548 message.role === "clinician" ? (549 <p550 key={message.id}551 className="m-0 max-w-[80%] self-end rounded-xl bg-[color-mix(in_oklab,var(--zb-accent)_12%,transparent)] px-3 py-1.5 text-sm text-[var(--zb-text)]"552 >553 {message.text}554 </p>555 ) : (556 <article key={message.id} className="flex flex-col gap-1.5">557 {/* Collapsed by design: a visible chain of thought reads as558 evidence to a clinician, and it is not evidence. */}559 {message.answer?.reasoning ? (560 <details className="text-xs text-[var(--zb-text-muted)]">561 <summary className="flex cursor-pointer items-center gap-1 text-[0.65rem] uppercase tracking-wide [&::-webkit-details-marker]:hidden">562 <ThoughtIcon /> Reasoning563 </summary>564 <p className="m-0 mt-1 border-s-2 border-[var(--zb-border)] ps-2 leading-relaxed">565 {message.answer.reasoning}566 </p>567 </details>568 ) : null}569570 {message.answer ? (571 <span572 data-register={message.answer.register}573 className={cn(574 "self-start rounded px-1.5 py-0.5 text-[0.65rem] uppercase tracking-wide",575 // The status token's own paired ground, not a 15% mix of576 // the hue over whatever is behind it: on the docs panel the577 // mix measured 4.43:1 for this 10px label. The `-bg` tokens578 // are what the token build gates each status colour against.579 message.answer.register === "grounded" &&580 "bg-[var(--zb-status-normal-bg)] text-[var(--zb-status-normal)]",581 message.answer.register === "general" &&582 "bg-[var(--zb-status-high-bg)] text-[var(--zb-status-high)]",583 message.answer.register === "declined" &&584 "bg-[var(--zb-bg-subtle)] text-[var(--zb-text-muted)]",585 )}586 >587 {message.answer.register === "grounded"588 ? `Grounded · ${message.answer.sources.size}`589 : message.answer.register === "general"590 ? "General knowledge"591 : "Declined"}592 </span>593 ) : null}594595 {message.answer ? (596 <div597 data-register={message.answer.register}598 className={cn(599 "text-sm leading-relaxed text-[var(--zb-text)]",600 message.answer.register === "general" &&601 "border-s-[3px] border-[var(--zb-status-high)] ps-2.5",602 )}603 >604 {segmentAnswer(message.answer).map((segment, index) => (605 <span606 key={index}607 className={cn(608 segment.uncited &&609 "underline decoration-[var(--zb-status-high)] decoration-wavy underline-offset-4",610 )}611 {...(segment.uncited612 ? {613 title:614 "No source was cited for this sentence. Verify it before acting.",615 }616 : {})}617 >618 {segment.text}619 {segment.markers.map((marker) => (620 <button621 key={marker}622 type="button"623 onClick={() => api.openSourcesFor(message.id)}624 aria-label={citationLabel(marker, message.answer?.sources.get(marker))}625 className="ms-px align-super rounded bg-[color-mix(in_oklab,var(--zb-accent)_15%,transparent)] px-1 text-[0.65em]"626 >627 {marker}628 </button>629 ))}630 </span>631 ))}632 </div>633 ) : null}634635 <div className="flex flex-wrap items-center gap-2 text-xs">636 <button637 type="button"638 aria-label="Helpful"639 onClick={() => api.sendFeedbackFor(message.id, "up")}640 className="min-h-6 min-w-6 px-1"641 >642 <ThumbUpIcon />643 </button>644 <button645 type="button"646 aria-label="Not helpful"647 // No reason picker here, so record the thumbs-down at once.648 onClick={() =>649 api.sendFeedbackFor(message.id, "down", undefined, { askReason: false })650 }651 className="min-h-6 min-w-6 px-1"652 >653 <ThumbDownIcon />654 </button>655 <button656 type="button"657 aria-label="Copy"658 onClick={() => void navigator.clipboard?.writeText(message.text)}659 className="min-h-6 min-w-6 px-1"660 >661 <CopyIcon />662 </button>663 <button664 type="button"665 // This answer's sources, not the latest answer's.666 onClick={() => api.openSourcesFor(message.id)}667 className="inline-flex min-h-6 items-center gap-1 rounded-lg border border-[var(--zb-border)] px-2 py-0.5"668 >669 <VerifyIcon />670 Show sources671 </button>672 {onInsert ? (673 <button674 type="button"675 aria-label="Insert into note"676 onClick={() => onInsert(message.text)}677 className="min-h-6 min-w-6 px-1"678 >679 <InsertIcon />680 </button>681 ) : null}682 </div>683 </article>684 ),685 )}686687 {api.state.status === "streaming" && api.state.current ? (688 <CopilotAnswerRegion busy className="text-sm leading-relaxed text-[var(--zb-text)]">689 {api.state.current.text}690 </CopilotAnswerRegion>691 ) : null}692693 {api.state.status === "crisis" ? (694 <section695 role="alert"696 className="rounded-xl border border-[color-mix(in_oklab,var(--zb-status-critical)_45%,transparent)] border-s-[3px] border-s-[var(--zb-status-critical)] bg-[color-mix(in_oklab,var(--zb-status-critical)_6%,transparent)] p-3"697 >698 <h3 className="m-0 mb-1 text-sm font-semibold text-[var(--zb-status-critical)]">699 This needs a person, not a model700 </h3>701 <p className="m-0 mb-2 text-sm text-[var(--zb-text)]">702 {api.state.safety.crisis.audience === "user"703 ? "This assistant is not able to help with this. Please reach a person now."704 : "This assistant does not answer questions about a patient in immediate danger."}705 </p>706 <div className="flex flex-wrap gap-2">707 {onRiskProtocol ? (708 <button709 type="button"710 onClick={onRiskProtocol}711 className="min-h-6 rounded-lg bg-[var(--zb-status-critical)] px-2.5 py-1 text-sm text-[var(--zb-text-on-accent)]"712 >713 Open risk protocol714 </button>715 ) : null}716 {/* Resolved by locale. 988 works in the United States and nowhere717 else, so hardcoding it ships a bug to every other market. */}718 {api.crisisLines.map((line) =>719 line.number ? (720 <a721 key={line.label}722 href={`tel:${line.number}`}723 className="min-h-6 rounded-lg border border-[var(--zb-border)] px-2.5 py-1 text-sm"724 >725 {line.label} · {line.number}726 </a>727 ) : (728 <span729 key={line.label}730 className="px-2.5 py-1 text-sm text-[var(--zb-text-muted)]"731 >732 {line.label}733 </span>734 ),735 )}736 </div>737 </section>738 ) : null}739740 {api.state.status === "refused" && api.state.error ? (741 <div role="status" className="rounded-lg bg-[var(--zb-bg-subtle)] p-2.5 text-sm">742 <strong className="text-[var(--zb-text)]">Outside what this assistant answers</strong>743 <p className="m-0 text-[var(--zb-text-muted)]">{api.state.error.message}</p>744 </div>745 ) : null}746747 {api.state.status === "error" && api.state.error ? (748 <div749 role="alert"750 className="rounded-lg bg-[color-mix(in_oklab,var(--zb-status-critical)_8%,transparent)] p-2.5 text-sm"751 >752 <strong className="text-[var(--zb-text)]">The assistant could not answer</strong>753 <p className="m-0 text-[var(--zb-text-muted)]">{api.state.error.message}</p>754 {api.state.error.retryable && api.canRetry ? (755 <button756 type="button"757 onClick={() => void api.retry()}758 className="min-h-6 rounded-lg border border-[var(--zb-border)] px-2 py-0.5"759 >760 Try again761 </button>762 ) : null}763 </div>764 ) : null}765 </div>766767 {/* The verification surface. The passage itself, not a link — following a768 link costs a tab and a search, and people accept rather than pay it. */}769 {api.sourcesOpen ? (770 <section771 aria-label="Basis of this answer"772 className="max-h-72 overflow-y-auto border-t border-[var(--zb-border)] p-3"773 >774 <div className="mb-1 flex items-center justify-between">775 <strong className="text-sm text-[var(--zb-text)]">Basis of this answer</strong>776 <button777 type="button"778 aria-label="Close"779 onClick={api.closeSources}780 className="min-h-6 px-1"781 >782 ✕783 </button>784 </div>785 <ol className="m-0 list-none p-0">786 {/* Numbered by citation marker, so "2" here is "2" in the answer. */}787 {api.citations.map(({ marker, source }) => (788 <li789 key={source.id}790 className="border-t border-[var(--zb-border)] pt-2 first:border-t-0 first:pt-0"791 >792 <div className="flex items-baseline gap-1.5 text-sm">793 <span794 aria-hidden="true"795 className="rounded bg-[color-mix(in_oklab,var(--zb-accent)_15%,transparent)] px-1 text-xs"796 >797 {marker}798 </span>799 {source.url ? (800 <a801 href={source.url}802 target="_blank"803 rel="noreferrer noopener"804 className="text-[var(--zb-text)]"805 >806 {source.title}807 </a>808 ) : (809 <strong className="text-[var(--zb-text)]">{source.title}</strong>810 )}811 </div>812 <blockquote className="m-0 mt-1 border-s-2 border-[var(--zb-border)] ps-2 text-xs text-[var(--zb-text-muted)]">813 <HighlightedPassage814 text={source.passage}815 {...(source.highlight ? { at: source.highlight } : {})}816 />817 </blockquote>818 <p className="m-0 mt-1 text-[0.7rem] tabular-nums text-[var(--zb-text-muted)]">819 Retrieved {source.retrievedAt.slice(0, 10)}820 {source.version ? ` · ${source.version}` : ""} · {source.kind}821 {typeof source.score === "number" ? ` · match ${source.score.toFixed(2)}` : ""}822 </p>823 </li>824 ))}825 </ol>826 </section>827 ) : null}828829 <ScopeStrip api={api} onChange={() => modeSelectRef.current?.focus()} />830831 {/* The panel's own composer. Once the thread is open the dock is the wrong832 place to type: the answer being followed up on is up here, and making833 someone travel back down to ask about it is the kind of small friction834 that ends in a copy-paste into a chat window with none of this835 component's guarantees. */}836 <div className="border-t border-[var(--zb-border)] px-3 py-2">837 <input838 value={api.draft}839 aria-label="Ask a follow-up…"840 placeholder="Ask a follow-up…"841 disabled={api.state.status === "crisis"}842 onChange={(event) => api.setDraft(event.target.value)}843 onKeyDown={(event) => {844 if (event.key === "Enter") {845 event.preventDefault();846 void api.submit();847 }848 }}849 className="w-full bg-transparent text-sm text-[var(--zb-text)] outline-none [@media(pointer:coarse)]:text-[length:max(16px,1em)]"850 />851 <div className="mt-1 flex items-center gap-1">852 <button853 type="button"854 aria-label="Shortcuts"855 onClick={() => api.setDraft(api.draft.startsWith("/") ? api.draft : "/")}856 className="min-h-6 min-w-6 rounded-lg px-1"857 >858 <ShortcutIcon />859 </button>860861 {/* Mode has to survive the dock being hidden, or opening a thread862 would quietly remove the control that decides what the model may863 read — the one thing that must never be implicit. */}864 <label className="inline-flex items-center gap-1 rounded-lg border border-[var(--zb-border)] px-2 py-0.5 text-xs">865 <span className="sr-only">Change mode</span>866 <select867 ref={modeSelectRef}868 value={api.mode.id}869 onChange={(event) => api.setMode(event.target.value)}870 className="bg-transparent text-xs text-[var(--zb-text)] outline-none"871 >872 {api.modes.map((mode) => (873 <option key={mode.id} value={mode.id}>874 {mode.label}875 </option>876 ))}877 </select>878 </label>879880 <span className="flex-1" />881882 {api.dictation.active ? (883 <button884 type="button"885 aria-label="Stop dictation"886 onClick={() => api.dictation.stop()}887 className="min-h-6 min-w-6 rounded-lg px-1 text-[var(--zb-status-normal)]"888 >889 <MicIcon />890 <span className="sr-only">Microphone is live</span>891 </button>892 ) : (893 <button894 type="button"895 aria-label="Start dictation"896 onClick={api.dictation.start}897 // Disabled mid-answer: dictating would leave `streaming` and remove Stop.898 disabled={api.state.status === "streaming" || api.state.status === "submitting"}899 className="min-h-6 min-w-6 rounded-lg px-1 disabled:opacity-40"900 >901 <MicIcon />902 </button>903 )}904905 {api.state.status === "streaming" || api.state.status === "submitting" ? (906 <button907 type="button"908 aria-label="Stop"909 onClick={api.stop}910 className="min-h-6 min-w-6 rounded-lg border border-[var(--zb-border)] px-1"911 >912 <StopIcon />913 </button>914 ) : (915 <button916 type="button"917 aria-label="Send"918 disabled={!api.canSubmit}919 onClick={() => void api.submit()}920 className="min-h-6 min-w-6 rounded-lg bg-[var(--zb-accent)] px-1 text-[var(--zb-text-on-accent)] disabled:opacity-40"921 >922 <SendIcon />923 </button>924 )}925 </div>926 </div>927928 <p className="m-0 border-t border-[var(--zb-border)] px-3 py-2 text-center text-xs text-[var(--zb-text-muted)]">929 Medical knowledge only. Not for autonomous decision making. Check sources and use your930 clinical judgement.931 </p>932 </section>933 );934}