@hachej/boring-ui-kit 0.2.1 → 0.2.3

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/r/pi-chat.json ADDED
@@ -0,0 +1,264 @@
1
+ {
2
+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",
3
+ "name": "pi-chat",
4
+ "title": "Pi chat",
5
+ "description": "A complete Tailwind chat over the borrowed native chat controller: composer, messages, one collapsible activity block per turn (tool calls and reasoning), message queue, history, a human-in-the-loop question card, an Approve / Deny card for host tools wrapped with requireApproval optional artifact cards that open generated content in the host's panel, and feedback cards for the opt-in feedback tool (lists, and Show offers that the host page resolves). Chat only: no layout. Owned, editable source; no AI SDK. The optional pi-ambient and pi-workspace blocks build on it.",
6
+ "dependencies": [
7
+ "@hachej/boring-ui-kit@^0.2.3",
8
+ "@hachej/boring-files@^0.2.3",
9
+ "react@^19.0.0",
10
+ "react-dom@^19.0.0",
11
+ "marked@^17.0.6",
12
+ "entities@^8.1.0",
13
+ "@earendil-works/pi-durable@~1.1.0",
14
+ "@earendil-works/chord@~1.1.0",
15
+ "@earendil-works/pi-ai@~1.1.0",
16
+ "@modelcontextprotocol/sdk@^1.32.0",
17
+ "lucide-react@^1.51.0",
18
+ "use-stick-to-bottom@^1.1.6"
19
+ ],
20
+ "registryDependencies": [
21
+ "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.2.3/r/theme.json",
22
+ "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.2.3/r/utils.json",
23
+ "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.2.3/r/button.json"
24
+ ],
25
+ "files": [
26
+ {
27
+ "path": "registry/pi-chat/activity.tsx",
28
+ "content": "'use client';\n\nimport { useState } from 'react';\nimport type { ToolResultMessage } from '@earendil-works/pi-ai';\nimport { AlertCircleIcon, BrainIcon, CheckIcon, ChevronDownIcon, CircleSlashIcon, Loader2Icon } from 'lucide-react';\nimport { Shimmer } from './shimmer';\nimport { ToolCard, liveLabel } from './tool';\nimport type { ToolStatus } from './tool';\nimport type { Step } from './rows';\nimport { cn } from '../utils/utils';\nimport { useChatText } from './labels';\nimport type { ChatLabels } from './labels';\n\ntype Image = Extract<ToolResultMessage['content'][number], { type: 'image' }>;\nexport type ActivityState = 'running' | 'done' | 'failed' | 'stopped';\n\nconst stepStatus = (step: Step): ToolStatus => step.kind === 'tool' ? step.entry.status : step.streaming ? 'running' : 'completed';\n\n/** \"Used read ×3 · working_git\" for a few kinds of calls, \"Worked through N steps\" otherwise. */\nfunction summary(steps: readonly Step[], labels: ChatLabels): string | undefined {\n const counts = new Map<string, number>();\n for (const step of steps) if (step.kind === 'tool') counts.set(step.entry.call.name, (counts.get(step.entry.call.name) ?? 0) + 1);\n if (counts.size === 0 || counts.size > 4) return undefined;\n return [...counts].map(([name, count]) => `${labels.toolNoun(name)}${count > 1 ? ` ×${count}` : ''}`).join(' · ');\n}\n\n/** The one line a block shows while collapsed. Running: only the current step, replaced in place. */\nfunction header(steps: readonly Step[], state: ActivityState, streaming: boolean, labels: ChatLabels): string {\n if (state === 'running') {\n const running = steps.filter(step => stepStatus(step) === 'running');\n // While the model is still writing, the newest call is the current one; while calls execute, the first unfinished call is.\n const current = streaming ? running[running.length - 1] : running[0];\n if (!current) return labels.thinkingStep;\n return current.kind === 'tool' ? liveLabel(current.entry.call, labels) : labels.thinkingStep;\n }\n if (state === 'failed') {\n const failed = steps.flatMap(step => step.kind === 'tool' && step.entry.status === 'failed' ? [step.entry.call.name] : []);\n return labels.activityFailed(failed.length, [...new Set(failed)].join(' · '));\n }\n const used = summary(steps, labels);\n const tools = steps.some(step => step.kind === 'tool');\n if (used === undefined && state !== 'stopped') return tools ? labels.activityMany(steps.length) : labels.activityThought;\n return labels.activityUsed(used ?? (tools ? labels.activityMany(steps.length) : labels.activityThought), state === 'stopped');\n}\n\nfunction Dot({ status }: { readonly status: ToolStatus }) {\n return <span aria-hidden=\"true\" className={cn('relative z-10 mt-2 size-2 shrink-0 rounded-full ring-4 ring-background',\n status === 'running' ? 'animate-pulse bg-foreground motion-reduce:animate-none' : status === 'failed' ? 'bg-destructive' : status === 'completed' ? 'bg-muted-foreground/60' : 'bg-muted-foreground/30')} />;\n}\n\nfunction Thinking({ text, streaming, details }: { readonly text: string; readonly streaming: boolean; readonly details: boolean }) {\n const { labels } = useChatText();\n const [open, setOpen] = useState(false);\n return <div data-testid=\"reasoning\" data-state={open ? 'open' : 'closed'} data-streaming={streaming ? 'true' : undefined}>\n <button type=\"button\" aria-expanded={details ? open : undefined} disabled={!details} onClick={() => setOpen(value => !value)}\n className={cn('flex min-h-7 w-full items-center gap-2 rounded-md px-2 py-1 text-left text-sm text-muted-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring/60 focus-visible:ring-inset', details ? 'cursor-pointer hover:bg-muted/50' : 'cursor-default')}>\n <BrainIcon className=\"size-3.5 shrink-0\" aria-hidden=\"true\" />\n <Shimmer active={streaming} className=\"flex-1\">{streaming ? labels.thinking : labels.reasoning}</Shimmer>\n {details && <ChevronDownIcon className={cn('size-4 shrink-0 transition-transform motion-reduce:transition-none', open && 'rotate-180')} aria-hidden=\"true\" />}\n </button>\n {open && details && <div data-testid=\"reasoning-text\" className=\"mx-2 mb-1 max-h-72 overflow-y-auto border-l-2 border-border pl-3 text-sm leading-6 whitespace-pre-wrap text-muted-foreground [overflow-wrap:anywhere]\">{text}</div>}\n </div>;\n}\n\n/**\n * One activity block per uninterrupted run of steps in an assistant turn, after the \"Chain of Thought\" component of\n * Vercel AI Elements: a collapsible header and, inside, a vertical rail of steps with a status dot, a label and\n * optional detail. Collapsed it is one fixed-height line (the current step while running, a summary afterwards);\n * rows stay in the DOM, hidden. Failures open the block. `expert` rows have nothing to expand for successful calls.\n */\nexport function ActivityBlock({ steps, state, streaming, developer, onOpenImage }: {\n readonly steps: readonly Step[]; readonly state: ActivityState; readonly streaming: boolean; readonly developer: boolean; readonly onOpenImage?: (image: Image) => void;\n}) {\n const { labels } = useChatText();\n const [chosen, setChosen] = useState<boolean | undefined>();\n const open = chosen ?? state === 'failed';\n const label = header(steps, state, streaming, labels);\n const Icon = state === 'running' ? null : state === 'failed' ? AlertCircleIcon : state === 'stopped' ? CircleSlashIcon : CheckIcon;\n return <div data-testid=\"activity\" data-boring=\"activity\" data-state={state} data-open={open ? 'true' : 'false'} className=\"my-1.5\">\n <button type=\"button\" aria-expanded={open} onClick={() => setChosen(!open)}\n className=\"flex h-9 w-full cursor-pointer items-center gap-2 max-sm:h-10 pointer-coarse:h-10 rounded-lg border border-border bg-muted/40 px-3 text-left text-sm text-muted-foreground outline-none transition-colors hover:bg-muted/70 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/60 motion-reduce:transition-none\">\n {Icon ? <Icon aria-hidden=\"true\" className={cn('size-3.5 shrink-0', state === 'failed' ? 'text-destructive' : state === 'done' ? 'text-(--chat-success)' : '')} />\n : <Loader2Icon aria-hidden=\"true\" className=\"size-3.5 shrink-0 animate-spin motion-reduce:animate-none\" />}\n <span data-testid=\"activity-label\" aria-live={state === 'running' ? 'off' : undefined} className={cn('min-w-0 flex-1 truncate', state === 'failed' && 'text-destructive')}>\n <Shimmer active={state === 'running'}>{label}</Shimmer></span>\n <span data-testid=\"activity-count\" className=\"shrink-0 text-xs tabular-nums text-muted-foreground/80\">{labels.steps(steps.length)}</span>\n <ChevronDownIcon aria-hidden=\"true\" className={cn('size-4 shrink-0 transition-transform motion-reduce:transition-none', open && 'rotate-180')} />\n </button>\n <div hidden={!open} data-testid=\"activity-steps\" className=\"relative mt-2 pl-1.5\">\n <div aria-hidden=\"true\" className=\"absolute top-3 bottom-3 left-[9px] w-px bg-border\" />\n <ol className=\"m-0 flex list-none flex-col gap-0.5 p-0\">\n {steps.map(step => <li key={step.key} data-testid=\"activity-step\" data-kind={step.kind} data-status={stepStatus(step)} className=\"flex min-w-0 gap-2\">\n <Dot status={stepStatus(step)} />\n <div className=\"min-w-0 flex-1\">{step.kind === 'tool'\n ? <ToolCard entry={step.entry} compact details={developer || step.entry.status === 'failed'} {...(onOpenImage ? { onOpenImage } : {})} />\n : <Thinking text={step.text} streaming={step.streaming} details={developer} />}</div>\n </li>)}\n </ol>\n </div>\n </div>;\n}\n",
29
+ "type": "registry:component",
30
+ "target": "components/pi-chat/activity.tsx"
31
+ },
32
+ {
33
+ "path": "registry/pi-chat/artifact-card.tsx",
34
+ "content": "'use client';\n\nimport type { ComponentType } from 'react';\nimport { ChevronRightIcon, FileCodeIcon, FileTextIcon, GlobeIcon, ImageIcon, PenToolIcon } from 'lucide-react';\nimport { Shimmer } from './shimmer';\nimport { artifactKey, typeLabel } from './artifact';\nimport type { ArtifactDescriptor, ArtifactType } from './artifact';\nimport { cn } from '../utils/utils';\nimport { useChatText } from './labels';\n\nconst ICONS: Record<ArtifactType, ComponentType<{ readonly className?: string; readonly 'aria-hidden'?: boolean | 'true' }>> = {\n markdown: FileTextIcon, html: GlobeIcon, svg: ImageIcon, code: FileCodeIcon, canvas: PenToolIcon,\n};\n\n/**\n * An artifact in the transcript, as in Claude's chat apps: a compact card with a type icon, the title, the type and the\n * version. Clicking it asks the host to open the artifact. While the `present` call that makes it is still running it is a quiet\n * \"opening\" card with a shimmer. Rendered outside the activity block, like the question card.\n */\nexport function ArtifactCard({ artifact, pending, title, open = false, onOpen }: {\n readonly artifact?: ArtifactDescriptor | undefined;\n readonly pending?: 'presenting';\n readonly title?: string | undefined;\n readonly open?: boolean;\n readonly onOpen?: ((artifact: ArtifactDescriptor) => void) | undefined;\n}) {\n const { labels } = useChatText();\n if (!artifact) {\n return <div data-testid=\"artifact-card\" data-state={pending ?? 'presenting'} role=\"status\" aria-busy=\"true\"\n className=\"my-2 flex min-h-16 items-center gap-3 rounded-xl border border-dashed border-border bg-muted/30 px-3 py-2.5\">\n <span className=\"flex size-10 shrink-0 items-center justify-center rounded-lg bg-muted text-muted-foreground\"><FileTextIcon className=\"size-5\" aria-hidden=\"true\" /></span>\n <span className=\"min-w-0 flex-1\">\n <span data-testid=\"artifact-title\" className=\"block truncate text-sm font-medium\"><Shimmer>{title ?? labels.artifact}</Shimmer></span>\n <span className=\"block text-xs text-muted-foreground\"><Shimmer>{labels.opening}</Shimmer></span>\n </span>\n </div>;\n }\n const Icon = ICONS[artifact.type];\n return <button type=\"button\" data-testid=\"artifact-card\" data-state=\"ready\" data-artifact-id={artifactKey(artifact)} data-artifact-revision={artifact.revision} data-artifact-version={artifact.ordinal} data-artifact-type={artifact.type}\n data-open={open ? 'true' : undefined} aria-pressed={onOpen ? open : undefined} aria-label={labels.openArtifact(artifact.title, artifact.ordinal)} disabled={!onOpen}\n onClick={() => onOpen?.(artifact)}\n className={cn('group/artifact my-2 flex min-h-16 w-full max-w-md cursor-pointer items-center gap-3 rounded-xl border bg-card px-3 py-2.5 text-left text-card-foreground shadow-xs outline-none transition-[border-color,background-color,box-shadow] motion-reduce:transition-none',\n 'hover:border-ring/50 hover:bg-muted/40 hover:shadow-sm focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/60 disabled:cursor-default',\n open ? 'border-ring bg-muted/50' : 'border-border')}>\n <span className={cn('flex size-10 shrink-0 items-center justify-center rounded-lg transition-colors motion-reduce:transition-none', open ? 'bg-primary text-primary-foreground' : 'bg-muted text-muted-foreground group-hover/artifact:bg-background group-hover/artifact:text-foreground')}>\n <Icon className=\"size-5\" aria-hidden=\"true\" /></span>\n <span className=\"min-w-0 flex-1\">\n <span data-testid=\"artifact-title\" className=\"block truncate text-sm leading-5 font-medium\">{artifact.title}</span>\n <span className=\"block truncate text-xs leading-5 text-muted-foreground\"><span data-testid=\"artifact-type\">{typeLabel(artifact)}</span>{artifact.ordinal !== undefined && <> · <span data-testid=\"artifact-version\">{labels.version(artifact.ordinal)}</span></>}</span>\n </span>\n <span className=\"flex shrink-0 items-center gap-1 text-xs text-muted-foreground\">\n <span data-testid=\"artifact-hint\" className={cn(open ? 'font-medium text-foreground' : 'opacity-0 transition-opacity group-hover/artifact:opacity-100 group-focus-visible/artifact:opacity-100 motion-reduce:transition-none pointer-coarse:opacity-100 max-sm:opacity-100')}>{open ? labels.viewing : labels.open}</span>\n <ChevronRightIcon className=\"size-4\" aria-hidden=\"true\" />\n </span>\n </button>;\n}\n",
35
+ "type": "registry:component",
36
+ "target": "components/pi-chat/artifact-card.tsx"
37
+ },
38
+ {
39
+ "path": "registry/pi-chat/approval-card.tsx",
40
+ "content": "'use client';\n\nimport { useEffect, useRef, useState } from 'react';\nimport type { ToolCall, ToolResultMessage } from '@earendil-works/pi-ai';\nimport { CheckIcon, ShieldAlertIcon, XIcon } from 'lucide-react';\nimport { Button } from '../button/button';\nimport type { AnswerOutcome } from './question-card';\nimport { cn } from '../utils/utils';\nimport { useChatText } from './labels';\n\n// The strings `requireApproval` (`@hachej/boring-agent/approval`) asks with and puts at the start of a denial result.\nexport const APPROVE = 'Approve';\nexport const DENY = 'Deny';\nexport const DENIED_PREFIX = 'Denied by the person.';\n\n\n/** The arguments the call would run with, one line each. They come from the model's call itself: the card shows what will actually execute. */\nexport function describeArguments(call: ToolCall): { readonly name: string; readonly value: string }[] {\n return Object.entries(call.arguments as Record<string, unknown>).map(([name, value]) => {\n const text = typeof value === 'string' ? value : JSON.stringify(value) ?? '';\n return { name, value: text.length > 600 ? `${text.slice(0, 600)}…` : text };\n });\n}\n\n/**\n * The settled state. The wrapper records its decision in the call's details; a call that settled without one was never\n * decided (the run was stopped while it waited), so it is not shown as approved.\n */\nfunction decisionOf(result: ToolResultMessage | undefined, decision: 'approved' | 'denied' | 'cancelled' | undefined): 'pending' | 'denied' | 'approved' | 'cancelled' {\n if (!result) return 'pending';\n if (decision) return decision;\n const text = result.content.map(part => part.type === 'text' ? part.text : '').join('');\n return result.isError && text.startsWith(DENIED_PREFIX) ? 'denied' : 'cancelled';\n}\n\n/** Human approval for a gated tool call: pending (Approve and Deny), then approved or denied. Answering uses the host's `answer`. */\nexport function ApprovalCard({ call, result, answer, questionId, summary, decision, live = false }: {\n readonly call: ToolCall;\n /** The question ID bound to this call's assistant entry (`derive` provides it); answers use it, never the bare call ID. */\n readonly questionId?: string | undefined;\n /** The decision `requireApproval` recorded in the call's details (`derive` finds it). Without one, a settled call shows as not decided. */\n readonly decision?: 'approved' | 'denied' | 'cancelled' | undefined;\n /** The one-line summary `requireApproval` published for this call (`derive` finds it). Shown first; the raw arguments are then collapsed under it. */\n readonly summary?: string | undefined;\n readonly result: ToolResultMessage | undefined;\n readonly answer?: ((callId: string, answer: string) => Promise<AnswerOutcome>) | undefined;\n /** The call is still being generated by the model: it cannot be decided yet. */\n readonly live?: boolean;\n}) {\n const { labels } = useChatText();\n const [sent, setSent] = useState<string | undefined>();\n const [sending, setSending] = useState<string | undefined>();\n const [refusal, setRefusal] = useState<string | undefined>();\n const mounted = useRef(true);\n useEffect(() => { mounted.current = true; return () => { mounted.current = false; }; }, []);\n const settled = decisionOf(result, decision);\n // `pending` means the decision waits on the person; `writing` means the model is still generating the call.\n const state = settled !== 'pending' ? settled : sent === APPROVE ? 'approved-sent' : sent === DENY ? 'denied-sent' : live ? 'writing' : 'pending';\n const open = state === 'pending' || state === 'writing';\n const args = describeArguments(call);\n const busy = sending !== undefined || live;\n\n async function decide(value: string) {\n if (!answer || !questionId || busy) return;\n setRefusal(undefined); setSending(value);\n try {\n const outcome = await answer(questionId, value);\n if (outcome.kind === 'answered') setSent(value);\n else setRefusal(outcome.reason || labels.decisionRefused(outcome.kind));\n } catch (cause) { setRefusal(cause instanceof Error ? cause.message : labels.decisionNotSent); }\n finally { if (mounted.current) setSending(undefined); }\n }\n const approved = state === 'approved' || state === 'approved-sent', denied = state === 'denied' || state === 'denied-sent';\n\n return <section data-testid=\"approval-card\" data-state={state} data-call-id={call.id} data-tool={call.name} aria-label={labels.approvalNeeded}\n className={cn('my-2 rounded-xl border bg-card p-4 text-card-foreground shadow-xs', open ? 'border-(--chat-warning)/60' : 'border-border')}>\n <div className=\"flex items-start gap-3\">\n <span className={cn('mt-0.5 flex size-7 shrink-0 items-center justify-center rounded-lg', open ? 'bg-(--chat-warning-soft) text-(--chat-warning-soft-foreground)' : denied ? 'bg-destructive/10 text-destructive' : 'bg-muted text-muted-foreground')}>\n {approved ? <CheckIcon className=\"size-4\" aria-hidden=\"true\" /> : denied ? <XIcon className=\"size-4\" aria-hidden=\"true\" /> : <ShieldAlertIcon className=\"size-4\" aria-hidden=\"true\" />}\n </span>\n <div className=\"min-w-0 flex-1\">\n <p className=\"m-0 text-xs font-medium tracking-wider text-muted-foreground uppercase\">{open ? labels.needsApproval : approved ? labels.approved : denied ? labels.denied : labels.notDecided}</p>\n {summary && <p data-testid=\"approval-summary\" className=\"mt-1 mb-0 text-base leading-6 font-semibold [overflow-wrap:anywhere]\">{summary}</p>}\n <p data-testid=\"approval-tool\" className={cn('mb-0 [overflow-wrap:anywhere]', summary ? 'mt-1 text-xs text-muted-foreground' : 'mt-1 text-sm leading-6 font-medium')}>{labels.wantsToRun} <code className=\"rounded bg-muted px-1.5 py-0.5 font-mono text-sm\">{call.name}</code></p>\n {args.length > 0 && (() => {\n const list = <dl data-testid=\"approval-args\" className=\"mt-2 mb-0 grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-xs\">\n {args.map(item => [<dt key={`${item.name}:n`} className=\"text-muted-foreground\">{item.name}</dt>, <dd key={`${item.name}:v`} className=\"m-0 font-mono whitespace-pre-wrap [overflow-wrap:anywhere]\">{item.value}</dd>])}\n </dl>;\n // With a summary the raw arguments are the detail behind it; without one they are all the person has to decide on.\n return summary ? <details data-testid=\"approval-details\" className=\"mt-2 text-xs\"><summary className=\"cursor-pointer text-muted-foreground select-none\">{labels.arguments}</summary>{list}</details> : list;\n })()}\n {open && <>\n <div role=\"group\" aria-label={labels.decision} className=\"mt-3 flex flex-wrap gap-2\">\n <Button variant=\"default\" data-testid=\"approval-approve\" disabled={!answer || !questionId || busy} onClick={() => { void decide(APPROVE); }} className={cn('min-h-11 sm:min-h-9', sending === APPROVE && 'opacity-70')}><CheckIcon className=\"size-3.5\" aria-hidden=\"true\" />{labels.approve}</Button>\n <Button variant=\"outline\" data-testid=\"approval-deny\" disabled={!answer || !questionId || busy} onClick={() => { void decide(DENY); }} className={cn('min-h-11 sm:min-h-9', sending === DENY && 'border-ring')}><XIcon className=\"size-3.5\" aria-hidden=\"true\" />{labels.deny}</Button>\n </div>\n {live && <p className=\"mt-3 mb-0 text-xs text-muted-foreground\">{labels.stillWritingCall}</p>}\n {(!answer || !questionId) && !live && <p className=\"mt-3 mb-0 text-xs text-muted-foreground\">{labels.decidingUnavailable}</p>}\n </>}\n {(state === 'approved-sent' || state === 'denied-sent') && <p className=\"mt-2 mb-0 text-xs text-muted-foreground\">{labels.decisionSent(approved)}</p>}\n {refusal && open && <p role=\"alert\" data-testid=\"approval-refusal\" className=\"mt-3 mb-0 rounded-md bg-destructive/10 px-3 py-2 text-sm text-destructive\">{refusal}</p>}\n </div>\n </div>\n </section>;\n}\n",
41
+ "type": "registry:component",
42
+ "target": "components/pi-chat/approval-card.tsx"
43
+ },
44
+ {
45
+ "path": "registry/pi-chat/artifact.ts",
46
+ "content": "import type { ConversationView } from '@earendil-works/pi-durable';\nimport type { ToolCall, ToolResultMessage } from '@earendil-works/pi-ai';\n\n/*\n * Artifacts in the chat: substantial content (a document, an HTML page, an SVG, code, a canvas) that the transcript shows as a\n * card and the host opens in its own panel. The descriptor and `parseArtifact` mirror `@hachej/boring-agent/artifacts` on purpose: this\n * is a copied registry item and cannot import that package (it carries Pi runtime code). Keep the two validators in step;\n * `test/contracts/pi-chat-source.test.mjs` checks that they accept and refuse the same values.\n */\nexport const ARTIFACT_TYPES = ['markdown', 'html', 'svg', 'code', 'canvas'] as const;\nexport type ArtifactType = typeof ARTIFACT_TYPES[number];\n\n/** Structural twin of the `ResourceLocator` in `@hachej/boring-files`. */\nexport interface ArtifactTarget {\n readonly resource: { readonly providerId: string; readonly path: string };\n readonly view: { readonly kind: 'published' } | { readonly kind: 'working'; readonly viewId: string };\n}\nexport interface ArtifactDescriptor {\n readonly schema: 'boring.artifact';\n readonly version: 1;\n /** Set by the artifact tools; the descriptor of `present` has none (the file path is its identity). */\n readonly id?: string;\n readonly title: string;\n readonly type: ArtifactType;\n readonly mediaType: string;\n readonly language?: string;\n readonly target: ArtifactTarget;\n /** The revision this message produced. */\n readonly revision: string;\n /** The 1-based version number of this artifact (artifact tools only). */\n readonly ordinal?: number;\n}\n\n/** What identifies an artifact across its versions: its id, or for a presented file its path. */\nexport const artifactKey = (artifact: Pick<ArtifactDescriptor, 'id' | 'target'>): string => artifact.id ?? artifact.target.resource.path;\n\n/** What the host passes to `PiChat` to turn artifact tool results into cards. */\nexport interface ArtifactsConfig {\n /** The person clicked a card: show this artifact (and revision) in the host's panel. */\n readonly open: (artifact: ArtifactDescriptor) => void;\n /** True for the card whose artifact version is on display. */\n readonly isOpen?: (artifact: ArtifactDescriptor) => boolean;\n /** Recognise a descriptor in a successful tool result that does not carry one itself (for example a document save). */\n readonly detect?: (call: ToolCall, result: ToolResultMessage) => ArtifactDescriptor | undefined;\n}\n\nexport const PRESENT_TOOL = 'present';\n\n/** A `present` call with no result yet, while its conversation runs: its answer ID (`[assistantEntryId, callId]`) and the path it names. */\nexport interface PendingPresent { readonly id: string; readonly callId: string; readonly path: string }\n\n/** The path a `present` call or a page acknowledgement names, as the server compares it (a leading `./` is the same file). */\nexport const presentPath = (path: string): string => path.replace(/^\\.\\//, '');\n\n/**\n * The `present` calls still waiting for the page (the server's view-open record, `@hachej/boring-agent/artifacts`). Mirrors\n * the preview's pending-call scan (the feedback plug-in's `pendingBrowserTasks`): a call with no result, in a conversation that is running.\n */\nexport function pendingPresents(view: { readonly entries: readonly { readonly id: number | bigint | string; readonly model?: readonly unknown[] | undefined }[]; readonly docs?: Readonly<Record<string, unknown>> } | undefined): readonly PendingPresent[] {\n if (!view) return [];\n const live = view.docs?.['pi.live'] as { readonly run?: unknown } | undefined;\n if (!live?.run) return [];\n const calls = new Map<string, PendingPresent>();\n for (const entry of view.entries) for (const message of entry.model ?? []) {\n const item = message as { readonly role?: string; readonly content?: unknown; readonly toolCallId?: string };\n if (item.role === 'assistant' && Array.isArray(item.content)) {\n for (const part of item.content as { type?: string; id?: string; name?: string; arguments?: Record<string, unknown> }[]) {\n const path = part.arguments?.['path'];\n if (part.type === 'toolCall' && part.name === PRESENT_TOOL && typeof part.id === 'string' && typeof path === 'string') {\n calls.set(part.id, { id: JSON.stringify([Number(entry.id), part.id]), callId: part.id, path: presentPath(path) });\n }\n }\n }\n if (item.role === 'toolResult' && typeof item.toolCallId === 'string') calls.delete(item.toolCallId);\n }\n return [...calls.values()];\n}\n\nconst ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;\nconst LANGUAGE = /^[A-Za-z0-9+#._-]{1,32}$/;\nconst isObject = (value: unknown): value is Record<string, unknown> => value !== null && typeof value === 'object' && !Array.isArray(value);\nconst hasOnly = (value: Record<string, unknown>, keys: readonly string[]) => Object.keys(value).every(key => keys.includes(key));\n\n/** Strict shape check of an untrusted value. Returns a fresh copy or undefined. */\nexport function parseArtifact(value: unknown): ArtifactDescriptor | undefined {\n if (!isObject(value) || !hasOnly(value, ['schema', 'version', 'id', 'title', 'type', 'mediaType', 'language', 'target', 'revision', 'ordinal'])) return undefined;\n const { id, title, type, mediaType, language, target, revision, ordinal } = value;\n if (value['schema'] !== 'boring.artifact' || value['version'] !== 1) return undefined;\n if (id !== undefined && (typeof id !== 'string' || !ID.test(id))) return undefined;\n if (typeof title !== 'string' || !title.trim() || title.length > 200) return undefined;\n if (typeof type !== 'string' || !(ARTIFACT_TYPES as readonly string[]).includes(type)) return undefined;\n if (typeof mediaType !== 'string' || !/^[a-z0-9][a-z0-9!#$&^_.+-]*\\/[a-z0-9][a-z0-9!#$&^_.+-]*$/i.test(mediaType)) return undefined;\n if (language !== undefined && (typeof language !== 'string' || !LANGUAGE.test(language))) return undefined;\n if (typeof revision !== 'string' || !revision || revision.length > 256) return undefined;\n if (ordinal !== undefined && (typeof ordinal !== 'number' || !Number.isSafeInteger(ordinal) || ordinal < 1)) return undefined;\n if (!isObject(target) || !hasOnly(target, ['resource', 'view']) || !isObject(target['resource']) || !hasOnly(target['resource'], ['providerId', 'path'])) return undefined;\n const { providerId, path } = target['resource'];\n if (typeof providerId !== 'string' || !providerId || typeof path !== 'string' || !path || path.length > 512) return undefined;\n const view = target['view'];\n if (!isObject(view)) return undefined;\n let parsedView: ArtifactTarget['view'];\n if (view['kind'] === 'published' && hasOnly(view, ['kind'])) parsedView = { kind: 'published' };\n else if (view['kind'] === 'working' && hasOnly(view, ['kind', 'viewId']) && typeof view['viewId'] === 'string' && view['viewId']) parsedView = { kind: 'working', viewId: view['viewId'] };\n else return undefined;\n return { schema: 'boring.artifact', version: 1, ...(id === undefined ? {} : { id }), title, type: type as ArtifactType, mediaType, ...(language === undefined ? {} : { language: language as string }),\n target: { resource: { providerId, path }, view: parsedView }, revision, ...(ordinal === undefined ? {} : { ordinal }) };\n}\n\nconst TYPE_LABEL: Record<ArtifactType, string> = { markdown: 'Document', html: 'HTML page', svg: 'SVG image', code: 'Code', canvas: 'Canvas' };\nexport function typeLabel(artifact: Pick<ArtifactDescriptor, 'type' | 'language'>): string {\n return artifact.type === 'code' && artifact.language ? `Code · ${artifact.language}` : TYPE_LABEL[artifact.type];\n}\n\nconst textOf = (result: ToolResultMessage): string => result.content.map(part => part.type === 'text' ? part.text : '').join('');\n\n/**\n * The descriptor a successful tool result carries: the host's `detect` first, then the `artifact` key of a JSON text result.\n * Failed results never produce one, and a host callback that throws or returns something malformed is ignored. Without\n * the host's `detect`, only a result of `present` counts: any other tool whose text happens\n * to be that JSON (an MCP tool, `cat x.json`) cannot forge a card. A host with renamed tools says so in `detect`.\n */\nexport function detectArtifact(call: ToolCall, result: ToolResultMessage, detect?: ArtifactsConfig['detect']): ArtifactDescriptor | undefined {\n if (result.isError) return undefined;\n if (detect) {\n try { const found = parseArtifact(detect(call, result)); if (found) return found; } catch { /* a faulty host callback shows no card */ }\n }\n if (call.name !== PRESENT_TOOL) return undefined;\n const text = textOf(result);\n if (!text.includes('\"boring.artifact\"')) return undefined;\n try {\n const value: unknown = JSON.parse(text);\n return isObject(value) ? parseArtifact(value['artifact']) : undefined;\n } catch { return undefined; }\n}\n\n/** The title a still-running `present` call announces in its streamed arguments: the file name. */\nexport function pendingTitle(call: ToolCall): string | undefined {\n const path = (call.arguments as Record<string, unknown>)['path'];\n const title = typeof path === 'string' ? path.slice(path.lastIndexOf('/') + 1) : undefined;\n return title?.trim() ? title.trim().slice(0, 200) : undefined;\n}\n/** What a still-running `present` call will show: the file path. */\nexport function pendingId(call: ToolCall): string | undefined {\n const path = (call.arguments as Record<string, unknown>)['path'];\n return typeof path === 'string' && path ? path.replace(/^(\\.\\/)+/, '') : undefined;\n}\n\n/**\n * Every artifact version a conversation's tool results produced, oldest first. Hosts use it to list the versions known\n * from the conversation (a version switcher); the chat itself shows only the last version of an artifact per turn.\n */\nexport function collectArtifacts(view: ConversationView | undefined, detect?: ArtifactsConfig['detect']): ArtifactDescriptor[] {\n const calls = new Map<string, ToolCall>(), found: ArtifactDescriptor[] = [];\n for (const entry of view?.entries ?? []) for (const message of entry.model ?? []) {\n if (message.role === 'assistant') for (const part of message.content) { if (part.type === 'toolCall') calls.set(part.id, part); }\n else if (message.role === 'toolResult') {\n const call = calls.get(message.toolCallId);\n const descriptor = call && detectArtifact(call, message, detect);\n if (descriptor) found.push(descriptor);\n }\n }\n return found;\n}\n\n/** What the host's chat answer returns: the kind is all the presents bookkeeping reads. */\nexport interface PresentAnswer { readonly kind: string }\n\nexport interface PresentAcksHost {\n /** The chat's `answer` (the transport's `?op=answer`); undefined when the host has none. */\n readonly answer: (id: string, answer: string) => Promise<PresentAnswer> | undefined;\n /** Open the file in the panel; false when the panel refuses (unsaved changes the person keeps). */\n readonly open: (path: string) => boolean;\n /** This page's identity in the acknowledgement. */\n readonly instanceId: string;\n /** Test seams: the wait between retries and the clock of the retry bound. Default: real timers. */\n readonly wait?: (ms: number) => Promise<void>;\n readonly now?: () => number;\n}\n\n/** The page's state of the presents it must answer, as `AgentWorkspace` reads it on each change. */\nexport interface PresentContext {\n /** The person closed the panel in this turn. */\n readonly closedThisTurn: boolean;\n /** The open file has unsaved edits. */\n readonly unsaved: boolean;\n /** The screen is a phone (the panel is a sheet and is not opened for an agent). */\n readonly narrow: boolean;\n /** `autoOpen`: when false the panel is not opened for an agent; the call waits for a manual open. */\n readonly autoOpen: boolean;\n /** Whether the panel already shows this file. */\n readonly showing: (path: string) => boolean;\n}\n\n/**\n * The page's side of the view-open acknowledgement. A `present` call is confirmed only by a viewer's mount report (`shown`) of the\n * revision it names. A call is decided once; an answer the server denies (a revision the page showed before the agent wrote a new one)\n * keeps the call waiting for the next mount report, and an answer is retried briefly while the server has not recorded the call yet.\n */\nexport function createPresentAcks(host: PresentAcksHost) {\n const decided = new Set<string>();\n /** Calls waiting for their file's mount report: answer ID to path. */\n const mounting = new Map<string, string>();\n const wait = host.wait ?? (ms => new Promise<void>(resolve => setTimeout(resolve, ms)));\n const now = host.now ?? (() => Date.now());\n /** The last mount report: the file on screen and its revision. */\n let lastShown: { readonly path: string; readonly revision: string } | undefined;\n\n /** Sends one answer; returns the server's outcome kind, or undefined when it was not sent. Retries while the record is not written yet. */\n async function send(id: string, body: Record<string, string>): Promise<string | undefined> {\n const until = now() + 3000;\n for (;;) {\n try {\n const sent = host.answer(id, JSON.stringify(body));\n if (sent === undefined) return undefined;\n const outcome = await sent;\n if (outcome.kind !== 'unknown-question' || now() > until) return outcome.kind;\n } catch { return undefined; /* the call ends at its deadline as unconfirmed */ }\n await wait(20);\n }\n }\n /** Confirms a shown revision. The call keeps its entry while the answer is in flight, so a mount during the flight still confirms it. */\n async function confirm(id: string, path: string, revision: string): Promise<void> {\n const kind = await send(id, { kind: 'opened', instanceId: host.instanceId, path, revision });\n // Only an accepted or conflicting answer ends the call. A denial (another revision), a failed request or an unrecorded call keeps it waiting for a later mount or a live-call check.\n if (kind === 'answered' || kind === 'conflict') mounting.delete(id);\n }\n\n return {\n /** A viewer mounted and shows `path` at `revision`: confirms the calls waiting for that file. */\n shown(view: { readonly path: string; readonly revision: string }): void {\n for (const [id, path] of mounting) if (path === view.path) void confirm(id, path, view.revision);\n lastShown = view;\n },\n /** A viewer stopped showing `path` at `revision` (it unmounted, or a custom viewer or the canvas took the file): it no longer confirms. */\n hidden(view: { readonly path: string; readonly revision: string }): void {\n if (lastShown?.path === view.path && lastShown.revision === view.revision) lastShown = undefined;\n },\n /** The presents the server waits for: each is decided once, in order. Decided calls and waits that are no longer live are forgotten. */\n consider(calls: readonly PendingPresent[], context: PresentContext): void {\n const live = new Set(calls.map(call => call.id));\n for (const id of decided) if (!live.has(id)) decided.delete(id);\n for (const id of mounting.keys()) if (!live.has(id)) mounting.delete(id);\n for (const call of calls) {\n if (decided.has(call.id)) continue;\n decided.add(call.id);\n if (context.closedThisTurn) void send(call.id, { kind: 'refused', reason: 'closed by user' });\n else if (context.unsaved) void send(call.id, { kind: 'refused', reason: 'unsaved changes' });\n else if (context.narrow) void send(call.id, { kind: 'refused', reason: 'narrow screen' });\n else {\n mounting.set(call.id, call.path);\n if (lastShown?.path === call.path && context.showing(call.path)) void confirm(call.id, call.path, lastShown.revision);\n else if (context.autoOpen && !host.open(call.path)) {\n mounting.delete(call.id);\n void send(call.id, { kind: 'refused', reason: 'unsaved changes' });\n }\n }\n }\n },\n /** Calls still waiting for a mount (test and debugging view). */\n waiting: (): readonly string[] => [...mounting.keys()],\n };\n}\n\n/** What `createPresentAcks` returns. */\nexport type PresentAcks = ReturnType<typeof createPresentAcks>;\n",
47
+ "type": "registry:lib",
48
+ "target": "components/pi-chat/artifact.ts"
49
+ },
50
+ {
51
+ "path": "registry/pi-chat/code-block.tsx",
52
+ "content": "'use client';\n\nimport { useEffect, useRef, useState } from 'react';\nimport { CheckIcon, CopyIcon } from 'lucide-react';\nimport { Button } from '../button/button';\nimport { copyText, cn } from '../utils/utils';\nimport { useChatText } from './labels';\n\n/** Copy button with a short \"copied\" confirmation. Failures stay visible as a title instead of throwing. */\nexport function CopyButton({ text, label: given, onCopy, className, iconOnly = false }: { readonly text: string; readonly label?: string; readonly onCopy?: (text: string) => Promise<void>; readonly className?: string; readonly iconOnly?: boolean }) {\n const { labels } = useChatText();\n const label = given ?? labels.copy;\n const [state, setState] = useState<'idle' | 'copied' | 'failed'>('idle');\n const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);\n useEffect(() => () => clearTimeout(timer.current), []);\n const settle = (next: 'copied' | 'failed') => { setState(next); clearTimeout(timer.current); timer.current = setTimeout(() => setState('idle'), 1600); };\n return <Button size=\"sm\" className={cn('max-sm:min-w-10 pointer-coarse:min-w-10', className)} data-testid=\"copy\" aria-label={label} title={state === 'failed' ? labels.copyFailed : label}\n onClick={() => { copyText(text, onCopy).then(() => settle('copied'), () => settle('failed')); }}>\n {state === 'copied' ? <CheckIcon className=\"size-3.5\" /> : <CopyIcon className=\"size-3.5\" />}\n <span className={iconOnly ? 'sr-only' : 'sr-only md:not-sr-only'}>{state === 'copied' ? labels.copied : state === 'failed' ? labels.failed : label}</span>\n </Button>;\n}\n\n/** Fenced code: language label, copy action, horizontal scroll. Text only, never interpreted as markup. */\nexport function CodeBlock({ code, language, onCopy }: { readonly code: string; readonly language?: string; readonly onCopy?: (text: string) => Promise<void> }) {\n const { labels } = useChatText();\n const label = language?.trim().split(/\\s+/)[0]?.slice(0, 24);\n return <div data-testid=\"code-block\" className=\"my-3 overflow-hidden rounded-lg border border-border bg-muted/40 text-foreground\">\n <div className=\"flex h-8 items-center justify-between border-b border-border bg-muted/60 pr-1 pl-3\">\n <span data-testid=\"code-language\" className=\"font-mono text-xs tracking-wide text-muted-foreground lowercase\">{label || 'text'}</span>\n <CopyButton text={code} label={labels.copyCode} {...(onCopy ? { onCopy } : {})} className=\"h-6 text-xs text-muted-foreground\" />\n </div>\n <pre className=\"m-0 overflow-x-auto p-3 font-mono text-xs leading-5\"><code>{code}</code></pre>\n </div>;\n}\n",
53
+ "type": "registry:component",
54
+ "target": "components/pi-chat/code-block.tsx"
55
+ },
56
+ {
57
+ "path": "registry/pi-chat/composer.tsx",
58
+ "content": "'use client';\n\nimport { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';\nimport type { ChangeEvent, ClipboardEvent, DragEvent, KeyboardEvent, ReactNode, Ref } from 'react';\nimport { AlertCircleIcon, FileTextIcon, Loader2Icon, MessageSquareIcon, MousePointerClickIcon, SlashIcon, XIcon } from 'lucide-react';\nimport { Button } from '../button/button';\nimport { hasMention, mentionToken, mentionTrigger, removeMention, slashItems, slashQuery } from './config';\nimport type { MentionsConfig, SlashConfig, SlashItem } from './config';\nimport { MentionMenu } from './mention-menu';\nimport { SlashMenu } from './slash-menu';\nimport { useChatText } from './labels';\nimport { cn } from '../utils/utils';\n\nexport interface ComposerAttachment { readonly id: string; readonly name: string; readonly mimeType: string; readonly data: string }\n\nconst SAFE_IMAGE = /^image\\/(png|jpe?g|gif|webp)$/;\nconst BASE64 = /^[A-Za-z0-9+/=\\s]+$/;\n/** A data URL for a thumbnail, only for common image types and well-formed base64. */\nexport function thumbnail(mimeType: string, data: string): string | undefined {\n return SAFE_IMAGE.test(mimeType) && BASE64.test(data) ? `data:${mimeType};base64,${data}` : undefined;\n}\n\n/**\n * The optional Feedback entry point (FEEDBACK.md, \"UX\"): a button beside the \"+\" menu that starts feedback mode on the host's page,\n * and afterwards one chip for the pending feedback. The host owns everything else (the registry `feedback` item's\n * `useComposerFeedback` returns this shape). Absent: the composer is unchanged.\n */\nexport interface ComposerFeedback {\n /** Enters feedback mode on the page: the Feedback button. Absent: no Feedback button. */\n readonly start?: () => void;\n /**\n * Point mode for phones: the « Show in app » action. The host hides its panel while the person taps elements in the app, and the\n * draft comes back as the chip. Absent: no action.\n */\n readonly point?: () => void;\n /** Feedback mode is on: the button shows pressed. */\n readonly active?: boolean;\n /** Feedback is waiting to be sent with the next message: Send is allowed with no text. */\n readonly pending?: boolean;\n /** The pending feedback's chip, shown with the other chips. */\n readonly chip?: ReactNode;\n /** Feedback mode's controls while it is on, docked under the composer's row. */\n readonly bar?: ReactNode;\n /** Send: the text to send instead, with the feedback attached, or why it cannot be sent yet. */\n readonly attach?: (text: string) => Promise<{ readonly kind: 'ok'; readonly text: string } | { readonly kind: 'refused'; readonly reason: string }>;\n /** The message carrying the feedback was accepted. */\n readonly sent?: () => void;\n}\n\n/** One file being uploaded (or that failed to upload), shown as a chip until it settles or is dismissed. */\nexport interface PendingUpload { readonly id: string; readonly name: string; readonly state: 'uploading' | 'failed'; readonly error?: string }\n\nexport interface ComposerProps {\n /** `/` menu of commands and skills. Absent: no menu and no keyboard trigger. */\n readonly slash?: SlashConfig | undefined;\n /** Reports a failing command. */\n readonly onSlashError?: ((cause: unknown) => void) | undefined;\n /** `@` file picker. Absent: no picker. */\n readonly mentions?: MentionsConfig | undefined;\n /** Paths picked or uploaded as mentions; each shows as a chip while its `@path` is still in the text. */\n readonly mentionPaths?: readonly string[];\n readonly onMentionPicked?: ((path: string) => void) | undefined;\n readonly uploads?: readonly PendingUpload[];\n readonly onDismissUpload?: ((id: string) => void) | undefined;\n /** Extra controls in the bar (the model and effort pill) and a short note beside them. */\n readonly barStart?: ReactNode;\n readonly barNote?: ReactNode;\n readonly text: string;\n readonly onText: (text: string) => void;\n readonly attachments: readonly ComposerAttachment[];\n readonly onRemoveAttachment: (id: string) => void;\n /** The agent is working: the primary button stops it and Enter queues the message (steering is chosen on the queued message). */\n readonly working: boolean;\n /** A send would be refused right now (not connected, a submission in flight, uploading). */\n readonly sendBlocked: boolean;\n readonly disabled: boolean;\n readonly stopRequested: boolean;\n readonly onSend: () => void;\n readonly onStop: () => void;\n readonly uploading: boolean;\n readonly canAttach: boolean;\n readonly fileAccept: string;\n readonly onPickFiles: (files: readonly File[]) => void;\n readonly onKeyDown?: ((event: KeyboardEvent<HTMLTextAreaElement>) => void) | undefined;\n readonly textareaRef: Ref<HTMLTextAreaElement>;\n readonly placeholder?: string;\n /** Both layouts have the same controls (the + menu, `/` and `@` menus, the model and effort pill, Send/Stop). `inline` puts them in one compact row; `stacked` is the two-row chat composer. */\n readonly layout?: 'stacked' | 'inline';\n /** Host controls (for example a voice button) as round buttons between the model pill and the send button. */\n readonly barEnd?: ReactNode;\n /** The optional Feedback button and chip. */\n readonly feedback?: ComposerFeedback | undefined;\n}\n\n/** Round bar buttons share one look: a tinted circle, 44px so a thumb can hit it. */\nconst ROUND = 'inline-flex size-11 shrink-0 cursor-pointer items-center justify-center rounded-lg bg-muted text-foreground transition-colors outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring/60 disabled:pointer-events-none disabled:opacity-45 motion-reduce:transition-none';\n\n/** A bar button with a word: the same tint and 44px height as ROUND. */\nconst PILL = 'inline-flex h-11 shrink-0 cursor-pointer items-center justify-center gap-1.5 rounded-full bg-muted px-3.5 text-sm font-medium text-foreground transition-colors outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring/60 disabled:pointer-events-none disabled:opacity-45 motion-reduce:transition-none';\n\n/** The Feedback button (a round bar button beside the \"+\" menu in both layouts) and « Show in app », each when the host offers it. */\nfunction FeedbackButton({ feedback, disabled }: { readonly feedback: ComposerFeedback; readonly disabled: boolean }) {\n const { labels } = useChatText();\n const busy = disabled || feedback.active === true || feedback.pending === true;\n const { start, point } = feedback;\n return <>\n {start && <button type=\"button\" data-testid=\"composer-feedback\" aria-pressed={feedback.active === true} disabled={busy}\n title={labels.feedbackHint} onClick={() => start()}\n className={cn(ROUND, feedback.active && 'bg-accent')}>\n <MessageSquareIcon className=\"size-4\" aria-hidden=\"true\" /><span className=\"sr-only\">{labels.feedback}</span>\n </button>}\n {point && <button type=\"button\" data-testid=\"composer-point\" disabled={busy} title={labels.pointHint} onClick={() => point()}\n className={PILL}>\n <MousePointerClickIcon className=\"size-4\" aria-hidden=\"true\" /><span className=\"whitespace-nowrap\">{labels.point}</span>\n </button>}\n </>;\n}\n\n/** The \"+\" button and its small menu (Attach files, Commands). Arrow keys move, Enter picks, Escape and outside clicks close. */\nfunction PlusMenu({ disabled, onAttach, onCommands }: { readonly disabled: boolean; readonly onAttach?: (() => void) | undefined; readonly onCommands?: (() => void) | undefined }) {\n const { labels, icons } = useChatText();\n const [open, setOpen] = useState(false);\n const root = useRef<HTMLDivElement>(null), trigger = useRef<HTMLButtonElement>(null);\n useEffect(() => {\n if (!open) return;\n const outside = (event: MouseEvent) => { if (root.current && !root.current.contains(event.target as Node)) setOpen(false); };\n document.addEventListener('mousedown', outside);\n return () => document.removeEventListener('mousedown', outside);\n }, [open]);\n useEffect(() => { if (disabled) setOpen(false); }, [disabled]);\n const entries = [onAttach && { testid: 'composer-attach', label: labels.attachFiles, icon: <icons.attach className=\"size-4 text-muted-foreground\" aria-hidden=\"true\" />, run: onAttach },\n onCommands && { testid: 'composer-commands', label: labels.commands, icon: <SlashIcon className=\"size-4 text-muted-foreground\" aria-hidden=\"true\" />, run: onCommands }].filter(entry => entry);\n const onKeyDown = (event: KeyboardEvent) => {\n if (!open) return;\n const items = Array.from(root.current?.querySelectorAll<HTMLElement>('[role=menuitem]') ?? []);\n const at = items.indexOf(document.activeElement as HTMLElement);\n if (event.key === 'ArrowDown') { event.preventDefault(); items[(at + 1) % items.length]?.focus(); }\n else if (event.key === 'ArrowUp') { event.preventDefault(); items[(at - 1 + items.length) % items.length]?.focus(); }\n else if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); setOpen(false); trigger.current?.focus(); }\n };\n return <div ref={root} className=\"relative shrink-0\" onKeyDown={onKeyDown}>\n <button ref={trigger} type=\"button\" data-testid=\"composer-plus\" aria-label={labels.add} title={labels.add} aria-haspopup=\"menu\" aria-expanded={open} disabled={disabled} onClick={() => setOpen(value => !value)} className={ROUND}>\n <icons.add className=\"size-5\" aria-hidden=\"true\" /></button>\n {open && <div role=\"menu\" aria-label={labels.add} data-testid=\"composer-plus-menu\" className=\"absolute bottom-full left-0 z-30 mb-2 w-52 rounded-2xl border border-border bg-popover p-1.5 text-popover-foreground shadow-lg\">\n {entries.map((entry, index) => entry && <button key={entry.testid} type=\"button\" role=\"menuitem\" data-testid={entry.testid} autoFocus={index === 0}\n onClick={() => { setOpen(false); entry.run(); }}\n className=\"flex min-h-11 w-full cursor-pointer items-center gap-2.5 rounded-lg px-2.5 py-1.5 text-left text-sm text-foreground outline-none hover:bg-accent focus-visible:bg-accent\">{entry.icon}{entry.label}</button>)}\n </div>}\n </div>;\n}\n\nconst MAX_HEIGHT = 208;\n\n/** Prompt composer: auto-growing textarea, Enter to send, one primary Send/Stop button. While the agent works a message is queued. */\nexport function Composer(props: ComposerProps) {\n const { text, attachments, working, sendBlocked, disabled, stopRequested, uploading, canAttach } = props;\n const { labels, icons } = useChatText();\n const inner = useRef<HTMLTextAreaElement | null>(null);\n const composing = useRef(false);\n const [dragging, setDragging] = useState(false);\n const [caret, setCaret] = useState(0);\n // A menu closed with Escape stays closed until the text changes.\n const [dismissed, setDismissed] = useState<string | null>(null);\n useEffect(() => { setDismissed(value => value === null || value === text ? value : null); }, [text]);\n const pendingCaret = useRef<number | null>(null);\n const fileInput = useRef<HTMLInputElement>(null);\n const { slash, mentions } = props;\n const items = useMemo<SlashItem[]>(() => slash ? slashItems(slash) : [], [slash]);\n const setRef = (element: HTMLTextAreaElement | null) => {\n inner.current = element;\n if (typeof props.textareaRef === 'function') props.textareaRef(element); else if (props.textareaRef) (props.textareaRef as { current: HTMLTextAreaElement | null }).current = element;\n };\n useLayoutEffect(() => {\n const element = inner.current;\n if (!element) return;\n element.style.height = 'auto';\n element.style.height = `${Math.min(element.scrollHeight, MAX_HEIGHT)}px`;\n element.style.overflowY = element.scrollHeight > MAX_HEIGHT ? 'auto' : 'hidden';\n if (pendingCaret.current !== null) { element.setSelectionRange(pendingCaret.current, pendingCaret.current); element.focus(); pendingCaret.current = null; }\n }, [text]);\n\n const query = slash && items.length ? slashQuery(text, caret) : null;\n const trigger = query === null && mentions ? mentionTrigger(text, caret) : null;\n const slashOpen = query !== null && dismissed !== text, mentionOpen = trigger !== null && dismissed !== text;\n const menuOpen = slashOpen || mentionOpen;\n const edit = (next: string, position: number) => { pendingCaret.current = position; setCaret(position); props.onText(next); };\n const trackCaret = (element: HTMLTextAreaElement) => setCaret(element.selectionStart ?? element.value.length);\n const dismiss = () => setDismissed(text);\n const pickSlash = (item: SlashItem) => {\n const rest = text.slice(caret).replace(/^\\s+/, '');\n if (item.source === 'skill') return edit(`/${item.name} ${rest}`, item.name.length + 2);\n const command = slash?.commands?.find(candidate => candidate.name === item.name);\n props.onText(rest); setCaret(0);\n inner.current?.focus();\n if (!command) return;\n try { void Promise.resolve(command.run({ text: rest, setText: value => props.onText(value) })).catch(cause => props.onSlashError?.(cause)); }\n catch (cause) { props.onSlashError?.(cause); }\n };\n const pickMention = (path: string) => {\n if (!trigger) return;\n const token = `${mentionToken(path)} `;\n edit(`${text.slice(0, trigger.start)}${token}${text.slice(trigger.end)}`, trigger.start + token.length);\n props.onMentionPicked?.(path);\n };\n const openCommands = () => edit(`${text}${text && !/\\s$/.test(text) ? ' ' : ''}/`, text.length + (text && !/\\s$/.test(text) ? 2 : 1));\n const chips = (props.mentionPaths ?? []).filter(path => hasMention(text, path));\n const onChange = (event: ChangeEvent<HTMLTextAreaElement>) => { trackCaret(event.currentTarget); props.onText(event.currentTarget.value); };\n\n const { feedback } = props;\n const hasContent = text.trim().length > 0 || attachments.length > 0 || feedback?.pending === true;\n const canSubmit = hasContent && !sendBlocked && !disabled;\n const onKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {\n props.onKeyDown?.(event);\n if (event.defaultPrevented) return;\n // Never send while an input method editor is composing (Enter confirms the candidate).\n // A phone keyboard has no Shift+Enter: on a touch device Enter inserts a newline and the Send button sends.\n const touch = globalThis.matchMedia?.('(pointer: coarse)').matches === true;\n if (event.key === 'Enter' && !touch && !event.shiftKey && !composing.current && !event.nativeEvent.isComposing && event.keyCode !== 229) {\n event.preventDefault();\n if (canSubmit) props.onSend();\n }\n };\n const onPaste = (event: ClipboardEvent<HTMLTextAreaElement>) => {\n if (canAttach && event.clipboardData.files.length) { event.preventDefault(); props.onPickFiles(Array.from(event.clipboardData.files)); }\n };\n const drag = (event: DragEvent) => { if (canAttach) { event.preventDefault(); setDragging(event.type === 'dragover'); } };\n const drop = (event: DragEvent) => { if (!canAttach) return; event.preventDefault(); setDragging(false); props.onPickFiles(Array.from(event.dataTransfer.files)); };\n\n const chipRows = <>\n {(chips.length > 0 || (props.uploads?.length ?? 0) > 0 || Boolean(feedback?.chip)) && <div className=\"flex flex-wrap gap-2 px-3 pt-3\">\n {feedback?.chip}\n {chips.length > 0 && <ul data-testid=\"mention-chips\" aria-label={labels.mentionedFiles} className=\"m-0 contents list-none p-0\">\n {chips.map(path => <li key={path} data-testid=\"mention-chip\" data-path={path} title={path} className=\"flex h-9 max-w-full sm:max-w-[16rem] items-center gap-1.5 rounded-full border border-border bg-muted/50 py-1 pr-1 pl-2.5\">\n <FileTextIcon className=\"size-3.5 shrink-0 text-muted-foreground\" aria-hidden=\"true\" />\n <span className=\"min-w-0 flex-1 truncate text-xs font-medium\">{path}</span>\n <button type=\"button\" aria-label={labels.remove(path)} onClick={() => props.onText(removeMention(text, path))}\n className=\"flex size-5 shrink-0 cursor-pointer items-center justify-center rounded-md text-muted-foreground relative after:absolute after:-inset-3 after:content-[''] transition-colors outline-none hover:bg-background hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/60\"><XIcon className=\"size-3\" aria-hidden=\"true\" /></button>\n </li>)}\n </ul>}\n {(props.uploads?.length ?? 0) > 0 && <ul data-testid=\"uploads\" aria-label={labels.uploads} className=\"m-0 contents list-none p-0\">\n {props.uploads!.map(item => <li key={item.id} data-testid=\"upload-chip\" data-state={item.state} title={item.error ?? item.name}\n className={cn('flex h-9 max-w-full sm:max-w-[20rem] items-center gap-1.5 rounded-full border py-1 pr-1 pl-2.5', item.state === 'failed' ? 'border-destructive/40 bg-destructive/10' : 'border-border bg-muted/50')}>\n {item.state === 'failed' ? <AlertCircleIcon className=\"size-3.5 shrink-0 text-destructive\" aria-hidden=\"true\" />\n : <Loader2Icon className=\"size-3.5 shrink-0 animate-spin text-muted-foreground motion-reduce:animate-none\" aria-hidden=\"true\" />}\n <span className=\"min-w-0 flex-1 truncate text-xs font-medium\">{item.state === 'failed' ? labels.uploadFailed(item.name, item.error) : labels.uploading(item.name)}</span>\n {item.state === 'failed' && <button type=\"button\" aria-label={labels.dismiss(item.name)} onClick={() => props.onDismissUpload?.(item.id)}\n className=\"flex size-5 shrink-0 cursor-pointer items-center justify-center rounded-md text-muted-foreground relative after:absolute after:-inset-3 after:content-[''] transition-colors outline-none hover:bg-background hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/60\"><XIcon className=\"size-3\" aria-hidden=\"true\" /></button>}\n </li>)}\n </ul>}\n </div>}\n </>;\n const attachmentRow = attachments.length > 0 && <ul data-testid=\"attachments\" aria-label={labels.attachments} className=\"m-0 flex list-none flex-wrap gap-2 px-3 pt-3\">\n {attachments.map(attachment => {\n const src = thumbnail(attachment.mimeType, attachment.data);\n return <li key={attachment.id} data-testid=\"attachment\" className=\"flex h-9 max-w-full sm:max-w-[14rem] items-center gap-2 rounded-full border border-border bg-muted/50 py-1 pr-1 pl-1\">\n {src ? <img src={src} alt=\"\" className=\"size-7 shrink-0 rounded-full object-cover\" /> : <span className=\"size-7 shrink-0 rounded-full bg-muted\" />}\n <span className=\"min-w-0 flex-1 truncate text-xs font-medium\">{attachment.name}</span>\n <button type=\"button\" aria-label={labels.remove(attachment.name)} onClick={() => props.onRemoveAttachment(attachment.id)}\n className=\"flex size-5 shrink-0 cursor-pointer items-center justify-center rounded-md text-muted-foreground relative after:absolute after:-inset-3 after:content-[''] transition-colors outline-none hover:bg-background hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/60\"><XIcon className=\"size-3\" aria-hidden=\"true\" /></button>\n </li>;\n })}\n </ul>;\n const textareaEl = <textarea ref={setRef} data-testid=\"composer-input\" aria-label={labels.messageInput} rows={1} value={text} disabled={disabled}\n placeholder={props.placeholder ?? (working ? labels.placeholderWorking : labels.placeholder)}\n {...(slash || mentions ? { role: 'combobox', 'aria-expanded': menuOpen, 'aria-haspopup': 'listbox', 'aria-autocomplete': 'list' } as const : {})}\n onChange={onChange} onKeyDown={onKeyDown} onPaste={onPaste} onKeyUp={event => trackCaret(event.currentTarget)} onClick={event => trackCaret(event.currentTarget)}\n onCompositionStart={() => { composing.current = true; }} onCompositionEnd={() => { composing.current = false; }}\n className={props.layout === 'inline'\n ? 'block max-h-40 min-h-11 min-w-0 flex-1 resize-none order-first basis-full border-0 bg-transparent px-1.5 py-2.5 text-base leading-6 text-foreground outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed sm:text-sm'\n : 'block max-h-52 min-h-[3.5rem] w-full resize-none border-0 bg-transparent px-5 pt-4 pb-2 text-base leading-6 sm:text-sm text-foreground outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed'} />;\n const plus = (canAttach || items.length > 0) && <PlusMenu disabled={disabled} onAttach={canAttach ? () => fileInput.current?.click() : undefined} onCommands={items.length > 0 ? openCommands : undefined} />;\n const fileEl = canAttach && <input ref={fileInput} type=\"file\" multiple accept={props.fileAccept} disabled={disabled} tabIndex={-1} aria-hidden=\"true\" className=\"sr-only\" data-testid=\"composer-file\" data-attach=\"true\"\n onChange={event => { const files = Array.from(event.currentTarget.files ?? []); event.currentTarget.value = ''; props.onPickFiles(files); }} />;\n const send = working\n ? <Button variant=\"default\" size=\"icon\" data-testid=\"composer-submit\" data-state=\"stop\" aria-label={labels.stop} title={labels.stop} disabled={disabled || stopRequested} onClick={props.onStop} className=\"ml-auto size-11 shrink-0\">\n {stopRequested ? <Loader2Icon className=\"size-4 animate-spin motion-reduce:animate-none\" aria-hidden=\"true\" /> : <icons.stop className=\"size-4 fill-current\" aria-hidden=\"true\" />}</Button>\n : <Button variant=\"default\" size=\"icon\" type=\"submit\" data-testid=\"composer-submit\" data-state=\"send\" aria-label={labels.send} title={labels.sendHint} disabled={!canSubmit} className=\"ml-auto size-11 shrink-0 disabled:bg-muted disabled:text-muted-foreground disabled:opacity-100\">\n <icons.send className=\"size-5\" aria-hidden=\"true\" /></Button>;\n\n if (props.layout === 'inline') return <form data-testid=\"composer\" data-layout=\"inline\" onSubmit={event => { event.preventDefault(); if (canSubmit) props.onSend(); }} onDragOver={drag} onDragLeave={drag} onDrop={drop}\n className={cn('relative bg-card', dragging && 'rounded-2xl ring-2 ring-ring/40', disabled && 'opacity-70')}>\n {slashOpen && <SlashMenu query={query!} items={items} onSelect={pickSlash} onDismiss={dismiss} />}\n {mentionOpen && mentions && <MentionMenu query={trigger!.query} search={mentions.search} generation={mentions.generation} onSelect={pickMention} onDismiss={dismiss} />}\n {chipRows}\n {attachmentRow}\n <div className=\"flex flex-wrap items-center gap-1.5 px-2.5 py-2\">\n {fileEl}\n {plus}\n {feedback && <FeedbackButton feedback={feedback} disabled={disabled} />}\n {textareaEl}\n {props.barNote}\n {props.barStart}\n {props.barEnd}\n {uploading && !(props.uploads?.length) && <Loader2Icon role=\"status\" aria-label={labels.preparingAttachmentsShort} className=\"size-3.5 shrink-0 animate-spin text-muted-foreground motion-reduce:animate-none\" />}\n {working && hasContent && <Button variant=\"secondary\" size=\"sm\" data-testid=\"composer-queue\" disabled={!canSubmit} onClick={props.onSend} className=\"h-11 shrink-0 rounded-full px-4\"><icons.queue className=\"size-3.5\" aria-hidden=\"true\" />{labels.queue}</Button>}\n {send}\n </div>\n {feedback?.bar}\n </form>;\n\n return <form data-testid=\"composer\" onSubmit={event => { event.preventDefault(); if (canSubmit) props.onSend(); }} onDragOver={drag} onDragLeave={drag} onDrop={drop}\n className={cn('relative rounded-3xl border border-border bg-card shadow-sm transition-[border-color,box-shadow] focus-within:border-ring/60 focus-within:ring-[3px] focus-within:ring-ring/15 motion-reduce:transition-none',\n dragging && 'border-ring ring-[3px] ring-ring/20', disabled && 'opacity-70')}>\n {slashOpen && <SlashMenu query={query!} items={items} onSelect={pickSlash} onDismiss={dismiss} />}\n {mentionOpen && mentions && <MentionMenu query={trigger!.query} search={mentions.search} generation={mentions.generation} onSelect={pickMention} onDismiss={dismiss} />}\n {chipRows}\n {attachmentRow}\n {textareaEl}\n <div className=\"flex flex-nowrap items-center gap-x-2 px-3 pt-1 pb-3\">\n {fileEl}\n {plus}\n {feedback && <FeedbackButton feedback={feedback} disabled={disabled} />}\n {props.barStart}\n {props.barNote}\n {uploading && !(props.uploads?.length) && <span role=\"status\" className=\"inline-flex items-center gap-1 text-xs text-muted-foreground\"><Loader2Icon className=\"size-3 animate-spin motion-reduce:animate-none\" aria-hidden=\"true\" />{labels.preparingAttachments}</span>}\n <span className=\"flex-1\" />\n {props.barEnd}\n {working && hasContent && <Button variant=\"secondary\" size=\"sm\" data-testid=\"composer-queue\" disabled={!canSubmit} onClick={props.onSend} className=\"h-11 shrink-0 rounded-full px-4\">\n <icons.queue className=\"size-3.5\" aria-hidden=\"true\" />{labels.queue}</Button>}\n {send}\n </div>\n {feedback?.bar}\n </form>;\n}\n",
59
+ "type": "registry:component",
60
+ "target": "components/pi-chat/composer.tsx"
61
+ },
62
+ {
63
+ "path": "registry/pi-chat/config.ts",
64
+ "content": "import type { ReactNode } from 'react';\nimport type { BlockAction } from '../button/actions';\n\n/*\n * Composer features the host switches on by configuration. Each prop is optional: leave it out and the composer has\n * no menu, no button and no keyboard trigger for it. The current model and thinking level are read from the native\n * view's `pi.agent` document, so there is no extra state to keep in sync.\n */\n\n/** Where a `/` menu entry comes from. Skills and host commands are grouped separately in the menu. */\nexport type SlashSource = 'local' | 'extension' | 'prompt' | 'skill';\n\nexport interface SlashApi {\n /** Replace the composer text. */\n readonly setText: (text: string) => void;\n /** The composer text with the typed `/query` already removed. */\n readonly text: string;\n}\nexport interface SlashCommand {\n readonly name: string;\n readonly description?: string;\n /** Shown as a badge and as a filter chip; commands without one are grouped as `built-in`. */\n readonly sourcePlugin?: string;\n readonly run: (api: SlashApi) => void | Promise<void>;\n}\nexport interface SlashSkill {\n readonly name: string;\n readonly description: string;\n readonly sourcePlugin?: string;\n}\nexport interface SlashConfig {\n readonly commands?: readonly SlashCommand[];\n readonly skills?: readonly SlashSkill[];\n}\n\nexport interface MentionResult { readonly path: string; readonly kind?: 'file' | 'directory' }\nexport interface MentionsConfig {\n /** Workspace search for the `@` picker. Empty `query` asks for a default listing. Abort `signal` when the query changes. */\n readonly search: (query: string, signal: AbortSignal) => Promise<readonly MentionResult[]>;\n /** Open a mentioned workspace file (for example in the right panel). When given, a mention in a sent message is a button. */\n readonly open?: ((path: string) => void) | undefined;\n /** Changes whenever what `search` would return may have changed (a workspace change event, another workspace). An open picker searches again. */\n readonly generation?: string | number | undefined;\n /** Host-supplied look for a mention in a sent message (a plug-in such as feedback). Return undefined to keep the default mention. */\n readonly render?: ((path: string) => ReactNode | undefined) | undefined;\n}\n\nexport interface UploadResult {\n /** The host saved the file in the workspace: it becomes an `@path` mention. */\n readonly path?: string;\n /** Sent as a native image attachment. */\n readonly image?: { readonly data: string; readonly mimeType: string };\n readonly name: string;\n}\nexport interface AttachmentsConfig {\n /** The file input's `accept`. Any file when omitted. */\n readonly accept?: string;\n readonly upload: (files: File[], signal: AbortSignal) => Promise<readonly UploadResult[]>;\n}\n\n/** One past conversation in the history list. `title` is its name or first message; `updatedAt` is when it last had activity. */\nexport interface ConversationItem {\n readonly id: string;\n readonly title?: string | undefined;\n readonly updatedAt?: number | string | Date | undefined;\n /** A preview of the last message (the row's tooltip). */\n readonly lastMessage?: string | null | undefined;\n readonly archived?: boolean | undefined;\n}\n/** The host's conversations. Give it to `PiChat` and the header's History button opens a list of them instead of the earlier records of this one. */\nexport interface ConversationsConfig {\n readonly items: readonly ConversationItem[];\n /** The conversation that is open; it is marked in the list. */\n readonly activeId?: string | undefined;\n readonly onSelect: (id: string) => void;\n readonly onNew?: (() => void) | undefined;\n readonly loading?: boolean | undefined;\n /**\n * Server-side search: with it, a typed query (or the Archived filter) lists what this returns instead of filtering `items`\n * by title. Abort `signal` when the query changes.\n */\n readonly search?: ((query: string, options: { readonly archived: boolean }, signal: AbortSignal) => Promise<readonly ConversationItem[]>) | undefined;\n /** Each action below adds its button to the rows; the host refreshes `items` when it resolves. */\n readonly rename?: ((id: string, title: string) => Promise<void>) | undefined;\n /** Archive (`true`) or restore (`false`). With it, the list also offers an Archived filter (which needs `search`). */\n readonly archive?: ((id: string, archived: boolean) => Promise<void>) | undefined;\n readonly remove?: ((id: string) => Promise<void>) | undefined;\n /** Fork the open conversation after the entry of a settled reply: the reply's Fork button. */\n readonly fork?: ((atEntryId: string) => Promise<void>) | undefined;\n /**\n * Host actions on each row, after rename, archive and delete: `header` ones as buttons, `menu` ones in a \"…\" menu. Test ids\n * `conversation-action-<id>`, the menu `conversation-action-more`.\n */\n readonly rowActions?: ((item: ConversationItem) => readonly BlockAction[]) | undefined;\n}\n\n/** A settled reply, as host message actions receive it: its row key, its text and the native entry it ends with. */\nexport interface ReplyRef {\n readonly key: string; readonly text: string; readonly entryId?: string | undefined;\n /** When the last model round of the reply was written (ms), the same value as its message's `timestamp`: a host keys its own per-reply data on it. */\n readonly timestamp?: number | undefined;\n /** The model that wrote the last round of the reply, as its message names it (`provider` and `model` ids). */\n readonly model?: { readonly provider: string; readonly modelId: string } | undefined;\n /**\n * How long the model took to answer in the last round of the reply (ms): Pi's own `AssistantMessage.durationMs`, measured monotonically\n * and kept in the transcript. It excludes queue time, earlier rounds, tool runs and retry delays, and is absent for a message written\n * before Pi recorded it. It is never computed from the clock at render time.\n */\n readonly durationMs?: number | undefined;\n}\n\nexport interface ModelRef { readonly provider: string; readonly modelId: string }\nexport interface ModelConfig {\n readonly options: readonly (ModelRef & { readonly label?: string })[];\n /** Reject to refuse: the message is shown inline. */\n readonly change: (model: ModelRef) => Promise<void>;\n}\nexport interface EffortConfig {\n readonly options: readonly string[];\n readonly change: (level: string) => Promise<void>;\n}\n\n/** The unified, internal menu entry. */\nexport interface SlashItem {\n readonly name: string;\n readonly description: string;\n readonly source: SlashSource;\n readonly sourcePlugin?: string;\n}\n\nexport function slashItems(config: SlashConfig): SlashItem[] {\n return [\n ...(config.commands ?? []).map((command): SlashItem => ({ name: command.name, description: command.description ?? '', source: 'local', ...(command.sourcePlugin ? { sourcePlugin: command.sourcePlugin } : {}) })),\n ...(config.skills ?? []).map((skill): SlashItem => ({ name: skill.name, description: skill.description, source: 'skill', ...(skill.sourcePlugin ? { sourcePlugin: skill.sourcePlugin } : {}) })),\n ];\n}\n\n/** The group an item lives under in the filter chips: skills, its plugin, or `built-in`. */\nexport function slashGroup(item: Pick<SlashItem, 'source' | 'sourcePlugin'>): string {\n if (item.source === 'skill') return 'skills';\n return item.sourcePlugin || 'built-in';\n}\n\n/** `/` opens the menu only when the text before the caret is one `/token`, as in v2. */\nexport function slashQuery(text: string, caret: number): string | null {\n const match = /^\\/(\\S*)$/.exec(text.slice(0, caret));\n return match ? match[1]! : null;\n}\n\nexport interface MentionTrigger { readonly query: string; readonly start: number; readonly end: number }\n/** An `@` at the start or after whitespace, up to the caret. */\nexport function mentionTrigger(text: string, caret: number): MentionTrigger | null {\n const before = text.slice(0, caret);\n const match = /(^|\\s)@(\\S*)$/.exec(before);\n // A typed opening quote (`@\"Meeting`) is not part of the search; the token starts at the `@` either way.\n return match ? { query: match[2]!.replace(/^\"/, ''), start: before.length - match[2]!.length - 1, end: caret } : null;\n}\n\n/**\n * The text of a mention of `path`. A path with whitespace or a quote is written in double quotes, `@\"docs/Meeting notes.md\"`, with `\\`\n * and `\"` escaped, because a bare mention ends at a space. Any other path stays bare (`@docs/plan.md`), as it always was.\n */\nexport function mentionToken(path: string): string {\n return /[\\s\"]/.test(path) ? `@\"${path.replace(/[\\\\\"]/g, '\\\\$&')}\"` : `@${path}`;\n}\n/**\n * The `@` tokens of a message, bare or quoted: group 1 is the character before the `@` (or the start), group 2 the quoted body (escapes\n * still in it), group 3 the bare path. `test/contracts/pi-chat-source.test.mjs` keeps `mentionedPaths` in the agent package equal to this.\n */\nexport const MENTION_TOKEN = /(^|\\s)@(?:\"((?:[^\"\\\\]|\\\\.)*)\"|([^\\s]+))/g;\n\nconst escape = (value: string) => value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\nconst BOUNDARY = '[^A-Za-z0-9_./-]';\nexport function hasMention(text: string, path: string): boolean {\n return new RegExp(`(^|${BOUNDARY})${escape(mentionToken(path))}($|${BOUNDARY})`).test(text);\n}\nexport function removeMention(text: string, path: string): string {\n return text.replace(new RegExp(`(^|${BOUNDARY})${escape(mentionToken(path))}(?=$|${BOUNDARY})[ ]?`), '$1').replace(/^[ ]+/, '');\n}\n\nexport type Piece = { readonly text: string; readonly kind?: 'mention' | 'skill'; readonly value?: string };\n/** Split a sent message into plain text, `@path` mentions and a leading `/skill` token. */\nexport function pieces(text: string, options: { readonly mentions: boolean; readonly skills: readonly string[] }): Piece[] {\n const found: { start: number; end: number; kind: 'mention' | 'skill'; value: string }[] = [];\n const skill = options.skills.length ? new RegExp(`^/(${options.skills.map(escape).join('|')})(?=\\\\s|$)`).exec(text) : null;\n if (skill) found.push({ start: 0, end: skill[0].length, kind: 'skill', value: skill[1]! });\n if (options.mentions) {\n for (const match of text.matchAll(MENTION_TOKEN)) {\n // A quoted path keeps its punctuation (the closing quote ends it); a bare one drops trailing punctuation, as a sentence would.\n const quoted = match[2] !== undefined;\n const path = quoted ? match[2]!.replace(/\\\\(.)/g, '$1') : match[3]!.replace(/[.,;:!?)\\]}'\"]+$/, '');\n if (!path) continue;\n const start = match.index! + match[1]!.length;\n const end = quoted ? match.index! + match[0].length : start + 1 + path.length;\n found.push({ start, end, kind: 'mention', value: path });\n }\n }\n const out: Piece[] = [];\n let cursor = 0;\n for (const item of found.sort((a, b) => a.start - b.start)) {\n if (item.start < cursor) continue;\n if (item.start > cursor) out.push({ text: text.slice(cursor, item.start) });\n out.push({ text: text.slice(item.start, item.end), kind: item.kind, value: item.value });\n cursor = item.end;\n }\n if (cursor < text.length) out.push({ text: text.slice(cursor) });\n return out;\n}\n",
65
+ "type": "registry:lib",
66
+ "target": "components/pi-chat/config.ts"
67
+ },
68
+ {
69
+ "path": "registry/pi-chat/empty-state.tsx",
70
+ "content": "import type { ReactNode } from 'react';\nimport { useChatText } from './labels';\n\nexport interface Suggestion { readonly label: string; readonly hint?: string; readonly text: string }\n\n/** Shown before the first message: a quiet title and optional starter prompts that fill the composer. */\nexport function EmptyState({ title, description, avatar, suggestions, onSelect, children }: {\n readonly title: string; readonly description?: string; readonly avatar?: ReactNode; readonly suggestions?: readonly Suggestion[]; readonly onSelect?: (text: string) => void; readonly children?: ReactNode;\n}) {\n const { labels, icons } = useChatText();\n return <div data-testid=\"empty-state\" className=\"flex h-full flex-col items-center justify-center gap-5 px-6 text-center\">\n <span data-testid=\"empty-state-icon\" className=\"flex size-12 items-center justify-center overflow-hidden rounded-2xl border border-border bg-muted/50 text-muted-foreground [&>img]:size-full [&>img]:object-cover [&>svg]:size-6\">{avatar ?? <icons.agent className=\"size-6\" aria-hidden=\"true\" />}</span>\n <div className=\"space-y-1.5\">\n <p className=\"m-0 text-lg font-semibold tracking-tight\">{title}</p>\n <p className=\"m-0 max-w-sm text-sm text-muted-foreground\">{description ?? labels.emptyDescription}</p>\n </div>\n {children}\n {suggestions && suggestions.length > 0 && <ul className=\"m-0 grid w-full max-w-md list-none gap-2 p-0\">\n {suggestions.map(item => <li key={item.label}><button type=\"button\" onClick={() => onSelect?.(item.text)} data-testid=\"suggestion\"\n className=\"flex w-full cursor-pointer flex-col gap-0.5 rounded-xl border border-border bg-background px-4 py-3 text-left transition-colors outline-none hover:bg-muted/60 focus-visible:ring-2 focus-visible:ring-ring/60\">\n <span className=\"text-sm font-medium\">{item.label}</span>{item.hint && <span className=\"text-xs text-muted-foreground\">{item.hint}</span>}</button></li>)}\n </ul>}\n </div>;\n}\n",
71
+ "type": "registry:component",
72
+ "target": "components/pi-chat/empty-state.tsx"
73
+ },
74
+ {
75
+ "path": "registry/pi-chat/history.tsx",
76
+ "content": "'use client';\n\nimport { useEffect, useMemo, useRef, useState } from 'react';\nimport type { ReactNode } from 'react';\nimport type { EntryRecord } from '@earendil-works/pi-durable';\nimport type { AssistantMessage, Message } from '@earendil-works/pi-ai';\nimport type { ChatHistoryState } from '@hachej/boring-ui-kit/native-chat';\nimport { ArchiveIcon, ArchiveRestoreIcon, ArrowLeftIcon, CheckIcon, EllipsisIcon, MessageSquareIcon, PencilIcon, SearchIcon, Trash2Icon, XIcon } from 'lucide-react';\nimport { Button } from '../button/button';\nimport { ActionButton, ActionMenu, actionMenuItem, headerActions, menuActions } from '../button/actions';\nimport type { ConversationItem, ConversationsConfig, ReplyRef } from './config';\nimport { Markdown } from './markdown';\nimport { cn } from '../utils/utils';\nimport { isFileBlock, replyMeta } from './rows';\nimport { defaultChatLabels, useChatText } from './labels';\nimport type { ChatLabels } from './labels';\n\nconst DAY = 86_400_000;\nconst toMs = (value: ConversationItem['updatedAt']): number | undefined => {\n if (value === undefined) return undefined;\n const ms = value instanceof Date ? value.getTime() : typeof value === 'number' ? value : Date.parse(value);\n return Number.isFinite(ms) ? ms : undefined;\n};\n\n/** Short relative time for a list row: \"now\", \"5m\", \"3h\", \"Yesterday\", \"4d\", then a date. */\nexport function relativeTime(value: ConversationItem['updatedAt'], now = Date.now(), labels: Pick<ChatLabels, 'justNow' | 'yesterday'> = defaultChatLabels): string {\n const ms = toMs(value);\n if (ms === undefined) return '';\n const age = Math.max(0, now - ms);\n if (age < 60_000) return labels.justNow;\n if (age < 3_600_000) return `${Math.floor(age / 60_000)}m`;\n if (age < DAY) return `${Math.floor(age / 3_600_000)}h`;\n const days = Math.floor(age / DAY);\n if (days === 1) return labels.yesterday;\n if (days < 7) return `${days}d`;\n return new Date(ms).toLocaleDateString(undefined, { month: 'short', day: 'numeric', ...(days > 300 ? { year: 'numeric' } : {}) });\n}\n\ntype Group = 'today' | 'yesterday' | 'previousWeek' | 'older' | 'conversations';\nfunction groupOf(value: ConversationItem['updatedAt'], now: number): Group {\n const ms = toMs(value);\n if (ms === undefined) return 'conversations';\n const age = now - ms;\n return age < DAY ? 'today' : age < 2 * DAY ? 'yesterday' : age < 7 * DAY ? 'previousWeek' : 'older';\n}\nconst ORDER: readonly Group[] = ['today', 'yesterday', 'previousWeek', 'older', 'conversations'];\n\n/**\n * The searchable list of past conversations: a search box (server-side when the host offers `search`), the Archived filter, rows grouped by\n * recency with the open one marked, and the row actions the host offers (rename, archive, delete). It fills its container; `ConversationHistory`\n * puts it in a popover or sheet, the `pi-app` block in its sessions pane. `onPicked` runs after a row is chosen.\n */\nexport function ConversationList({ conversations, onPicked, autoFocus = false }: {\n readonly conversations: ConversationsConfig;\n readonly onPicked?: (() => void) | undefined;\n /** Focus the search box on mount (not on touch screens). */\n readonly autoFocus?: boolean;\n}) {\n const { labels } = useChatText();\n const [query, setQuery] = useState('');\n const [archived, setArchived] = useState(false);\n // Server-side results while a query is typed or the Archived filter is on (when the host offers `search`).\n const [found, setFound] = useState<{ readonly items: readonly ConversationItem[]; readonly loading: boolean } | null>(null);\n const [revision, setRevision] = useState(0);\n const [renaming, setRenaming] = useState<string | null>(null);\n const [confirming, setConfirming] = useState<string | null>(null);\n const [failure, setFailure] = useState<string | null>(null);\n const search = useRef<HTMLInputElement>(null);\n const now = useMemo(() => Date.now(), [conversations.items]); // eslint-disable-line react-hooks/exhaustive-deps\n useEffect(() => { if (autoFocus && !globalThis.matchMedia?.('(pointer: coarse)').matches) search.current?.focus(); }, [autoFocus]);\n const serverSearch = conversations.search;\n useEffect(() => {\n const needle = query.trim();\n if (!serverSearch || (!needle && !archived)) { setFound(null); return; }\n const controller = new AbortController();\n setFound(previous => ({ items: previous?.items ?? [], loading: true }));\n const timer = setTimeout(() => {\n serverSearch(needle, { archived }, controller.signal).then(items => { if (!controller.signal.aborted) setFound({ items, loading: false }); })\n .catch(() => { if (!controller.signal.aborted) setFound({ items: [], loading: false }); });\n }, 150);\n return () => { clearTimeout(timer); controller.abort(); };\n }, [serverSearch, query, archived, revision]);\n /** Runs one row action; the host refreshes `items`, and a server-side search runs again. */\n const run = (action: () => Promise<void>) => {\n setFailure(null);\n action().then(() => setRevision(value => value + 1), () => setFailure(labels.actionFailed));\n };\n const shown = useMemo(() => {\n const needle = query.trim().toLowerCase();\n const items = found ? found.items : conversations.items.filter(item => !item.archived && (!needle || (item.title ?? labels.untitled).toLowerCase().includes(needle)));\n const sorted = [...items].sort((a, b) => (toMs(b.updatedAt) ?? 0) - (toMs(a.updatedAt) ?? 0));\n const groups = new Map<Group, ConversationItem[]>();\n for (const item of sorted) { const key = groupOf(item.updatedAt, now); groups.set(key, [...(groups.get(key) ?? []), item]); }\n return ORDER.flatMap(key => groups.has(key) ? [{ key, items: groups.get(key)! }] : []);\n }, [conversations.items, found, query, now, labels.untitled]);\n const loading = found ? found.loading : conversations.loading;\n const action = 'text-muted-foreground';\n const total = shown.reduce((sum, group) => sum + group.items.length, 0);\n return <>\n <div className=\"relative flex shrink-0 items-center gap-2 border-b border-border px-3 py-2\">\n <SearchIcon className=\"pointer-events-none absolute top-1/2 left-5.5 size-4 -translate-y-1/2 text-muted-foreground\" aria-hidden=\"true\" />\n <input ref={search} type=\"search\" value={query} onChange={event => setQuery(event.currentTarget.value)} placeholder={labels.searchConversations} aria-label={labels.searchConversations} data-testid=\"conversation-search\"\n className=\"h-9 w-full rounded-lg border border-border bg-background pr-3 pl-8 text-base outline-none max-sm:h-11 pointer-coarse:h-11 placeholder:text-muted-foreground focus-visible:border-ring/60 focus-visible:ring-[3px] focus-visible:ring-ring/15 sm:text-sm\" />\n {conversations.archive && serverSearch && <Button size=\"sm\" variant={archived ? 'secondary' : 'ghost'} aria-pressed={archived} data-testid=\"conversations-archived\" className=\"shrink-0 text-muted-foreground\"\n onClick={() => setArchived(value => !value)}><ArchiveIcon className=\"size-3.5\" aria-hidden=\"true\" />{labels.archived}</Button>}\n </div>\n {failure && <p role=\"alert\" className=\"m-0 shrink-0 px-3 pt-2 text-xs text-destructive\">{failure}</p>}\n <div className=\"min-h-0 flex-1 overflow-y-auto overscroll-contain px-1.5 py-1.5\" aria-busy={loading ? 'true' : undefined}>\n {total === 0 && <p role=\"status\" data-testid=\"conversations-empty\" className=\"m-0 px-3 py-8 text-center text-sm text-muted-foreground\">\n {loading ? labels.loadingConversations : query.trim() ? labels.noMatch(query.trim()) : archived ? labels.noArchived : labels.noConversations}</p>}\n {shown.map(group => <section key={group.key} aria-label={labels[group.key]} className=\"mb-1\">\n <h4 className=\"m-0 px-2.5 pt-2 pb-1 text-xs font-medium tracking-wide text-muted-foreground\">{labels[group.key]}</h4>\n <ul className=\"m-0 list-none p-0\">\n {group.items.map(item => {\n const active = item.id === conversations.activeId;\n const title = item.title?.trim() || labels.untitled;\n const extra = conversations.rowActions?.(item);\n // A row has room for icons only: a header action without an icon goes in the row's \"…\" menu.\n const extraButtons = headerActions(extra).filter(entry => entry.icon), extraMenu = [...headerActions(extra).filter(entry => !entry.icon), ...menuActions(extra)];\n if (renaming === item.id && conversations.rename) {\n const rename = conversations.rename;\n return <li key={item.id}>\n <form className=\"flex min-h-10 items-center gap-2 px-2.5 py-1\" onSubmit={event => {\n event.preventDefault();\n const value = new FormData(event.currentTarget).get('title')?.toString().trim();\n setRenaming(null);\n if (value && value !== item.title) run(() => rename(item.id, value));\n }}>\n <PencilIcon className=\"size-4 shrink-0 text-muted-foreground\" aria-hidden=\"true\" />\n <input name=\"title\" autoFocus defaultValue={title} maxLength={200} aria-label={labels.conversationName} data-testid=\"conversation-rename-input\"\n onKeyDown={event => { if (event.key === 'Escape') { event.stopPropagation(); setRenaming(null); } }}\n className=\"h-8 min-w-0 flex-1 rounded-md border border-border bg-background px-2 text-base outline-none focus-visible:border-ring/60 focus-visible:ring-[3px] focus-visible:ring-ring/15 sm:text-sm\" />\n <Button type=\"submit\" size=\"sm\" variant=\"outline\" data-testid=\"conversation-rename-save\">{labels.save}</Button>\n </form>\n </li>;\n }\n return <li key={item.id} className=\"group/row relative flex items-center\">\n <button type=\"button\" data-testid=\"conversation-row\" data-conversation-id={item.id} data-active={active ? 'true' : undefined} aria-current={active ? 'true' : undefined}\n title={item.lastMessage ?? undefined}\n onClick={() => { if (!active) conversations.onSelect(item.id); onPicked?.(); }}\n className={cn('flex min-h-10 w-full min-w-0 cursor-pointer items-center gap-2.5 rounded-lg px-2.5 py-2 text-left text-sm outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring/60 max-sm:min-h-12 motion-reduce:transition-none',\n active ? 'bg-muted font-medium' : 'hover:bg-muted/60')}>\n <MessageSquareIcon className=\"size-4 shrink-0 text-muted-foreground\" aria-hidden=\"true\" />\n <span className=\"min-w-0 flex-1 truncate\">{title}</span>\n {active ? <span className=\"inline-flex shrink-0 items-center gap-1 text-xs text-muted-foreground\"><CheckIcon className=\"size-3.5\" aria-hidden=\"true\" />{labels.current}</span>\n : <span className=\"shrink-0 text-xs text-muted-foreground tabular-nums\">{relativeTime(item.updatedAt, now, labels)}</span>}\n </button>\n {(conversations.rename || conversations.archive || conversations.remove || extraButtons.length > 0 || extraMenu.length > 0) && <div data-testid=\"conversation-actions\"\n className={cn('flex shrink-0 items-center gap-0.5 pr-1 pointer-fine:absolute pointer-fine:right-1 pointer-fine:rounded-md pointer-fine:bg-background pointer-fine:shadow-sm',\n confirming === item.id ? '' : 'pointer-fine:opacity-0 pointer-fine:group-hover/row:opacity-100 pointer-fine:group-focus-within/row:opacity-100')}>\n {confirming === item.id && conversations.remove ? <>\n <Button size=\"sm\" variant=\"destructive\" data-testid=\"conversation-delete-confirm\" onClick={() => { const remove = conversations.remove!; setConfirming(null); run(() => remove(item.id)); }}>{labels.delete}</Button>\n <Button size=\"icon-sm\" variant=\"ghost\" aria-label={labels.keep} className={action} onClick={() => setConfirming(null)}><XIcon className=\"size-3.5\" aria-hidden=\"true\" /></Button>\n </> : <>\n {conversations.rename && <Button size=\"icon-sm\" variant=\"ghost\" aria-label={labels.renameItem(title)} title={labels.rename} data-testid=\"conversation-rename\" className={action} onClick={() => setRenaming(item.id)}><PencilIcon className=\"size-3.5\" aria-hidden=\"true\" /></Button>}\n {conversations.archive && <Button size=\"icon-sm\" variant=\"ghost\" aria-label={labels.archiveItem(title, item.archived === true)} title={item.archived ? labels.restore : labels.archive} data-testid=\"conversation-archive\" className={action}\n onClick={() => { const archive = conversations.archive!; run(() => archive(item.id, !item.archived)); }}>{item.archived ? <ArchiveRestoreIcon className=\"size-3.5\" aria-hidden=\"true\" /> : <ArchiveIcon className=\"size-3.5\" aria-hidden=\"true\" />}</Button>}\n {conversations.remove && <Button size=\"icon-sm\" variant=\"ghost\" aria-label={labels.deleteItem(title)} title={labels.delete} data-testid=\"conversation-delete\" className={action} onClick={() => setConfirming(item.id)}><Trash2Icon className=\"size-3.5\" aria-hidden=\"true\" /></Button>}\n {extraButtons.map(entry => <ActionButton key={entry.id} action={entry} testId=\"conversation-action\" className={action} />)}\n {extraMenu.length > 0 && <ActionMenu label={labels.moreActions} size=\"icon-sm\" testId=\"conversation-action-more\" icon={<EllipsisIcon className=\"size-3.5\" aria-hidden=\"true\" />}\n items={extraMenu.map(entry => actionMenuItem(entry, 'conversation-action'))} />}\n </>}\n </div>}\n </li>;\n })}\n </ul>\n </section>)}\n </div>\n </>;\n}\n\n/**\n * The list of past conversations in a dialog: a header with New, then `ConversationList`.\n * An anchored card on a wide screen and a full-screen sheet on a phone. Escape or a click outside closes it.\n */\nexport function ConversationHistory({ conversations, onClose, onBrowseEarlier, placement = 'below' }: {\n readonly conversations: ConversationsConfig;\n readonly onClose: () => void;\n /** When given, a footer action opens the earlier records of the open conversation. */\n readonly onBrowseEarlier?: (() => void) | undefined;\n /** `above` opens the card upwards from a bar docked at the bottom of the screen; the backdrop then covers the whole page. */\n readonly placement?: 'below' | 'above';\n}) {\n const { labels, icons } = useChatText();\n useEffect(() => {\n const escape = (event: KeyboardEvent) => { if (event.key === 'Escape') onClose(); };\n document.addEventListener('keydown', escape);\n return () => document.removeEventListener('keydown', escape);\n }, [onClose]);\n return <>\n <button type=\"button\" tabIndex={-1} aria-hidden=\"true\" data-testid=\"conversations-backdrop\" onClick={onClose} className={cn('z-20 hidden cursor-default sm:block', placement === 'above' ? 'fixed inset-0' : 'absolute inset-0')} />\n <section role=\"dialog\" aria-label={labels.historyDialog} data-testid=\"conversations\"\n className={cn('fixed inset-0 z-50 flex flex-col bg-background text-foreground sm:absolute sm:inset-auto sm:z-30 sm:w-[23rem] sm:rounded-2xl sm:border sm:border-border sm:shadow-lg',\n placement === 'above' ? 'sm:bottom-full sm:left-0 sm:mb-2 sm:max-h-[min(26rem,60dvh)]' : 'sm:top-12 sm:right-3 sm:max-h-[min(34rem,calc(100%-4rem))]')}>\n <header className=\"flex shrink-0 items-center gap-2 border-b border-border px-3 py-2.5 max-sm:pt-[max(0.625rem,env(safe-area-inset-top))]\">\n <Button size=\"icon-sm\" variant=\"ghost\" aria-label={labels.closeHistory} title={labels.close} data-testid=\"conversations-close\" onClick={onClose} className=\"sm:hidden\"><ArrowLeftIcon className=\"size-4\" aria-hidden=\"true\" /></Button>\n <h3 className=\"m-0 min-w-0 flex-1 font-(family-name:--chat-display) text-sm font-semibold tracking-tight\">{labels.history}</h3>\n {conversations.onNew && <Button size=\"sm\" variant=\"outline\" data-testid=\"conversation-new\" onClick={() => { conversations.onNew!(); onClose(); }}><icons.newChat className=\"size-3.5\" aria-hidden=\"true\" />{labels.newConversation}</Button>}\n <Button size=\"icon-sm\" variant=\"ghost\" aria-label={labels.closeHistory} title={labels.close} onClick={onClose} className=\"max-sm:hidden\"><XIcon className=\"size-4\" aria-hidden=\"true\" /></Button>\n </header>\n <ConversationList conversations={conversations} onPicked={onClose} autoFocus />\n {onBrowseEarlier && <footer className=\"shrink-0 border-t border-border p-1.5 max-sm:pb-[max(0.375rem,env(safe-area-inset-bottom))]\">\n <Button size=\"sm\" variant=\"ghost\" data-testid=\"history-earlier\" className=\"w-full justify-start text-muted-foreground\" onClick={() => { onBrowseEarlier(); onClose(); }}>\n <icons.history className=\"size-3.5\" aria-hidden=\"true\" />{labels.earlierInConversation}</Button>\n </footer>}\n </section>\n </>;\n}\n\nfunction line(message: Message, developer: boolean, labels: ChatLabels): { readonly role: string; readonly body: string; readonly assistant?: AssistantMessage } | undefined {\n if (message.role === 'system') return developer ? { role: labels.roleSystem, body: typeof message.content === 'string' ? message.content : message.content.map(part => part.text).join('\\n') } : undefined;\n if (message.role === 'toolResult') return { role: labels.roleToolResult(message.toolName, message.isError), body: message.content.map(part => part.type === 'text' ? part.text : '[image result]').join('\\n') };\n if (message.role === 'user') return { role: labels.roleUser, body: typeof message.content === 'string' ? message.content : message.content.filter(part => part.type !== 'text' || !isFileBlock(part.text)).map(part => part.type === 'text' ? part.text : '[image attachment]').join('\\n') };\n const body = message.content.map(part => part.type === 'text' ? part.text : part.type === 'toolCall' ? `[tool call: ${part.name}]` : developer ? `[reasoning]\\n${part.thinking}` : '').filter(Boolean).join('\\n\\n');\n return { role: labels.roleAssistant(message.stopReason === 'aborted' ? 'interrupted' : message.stopReason === 'error' ? 'failed' : 'ok'), body, ...(message.stopReason === 'error' || message.stopReason === 'aborted' ? {} : { assistant: message }) };\n}\n\ntype HistoryRow = { readonly key: string; readonly role: string; readonly body: string; readonly entryId: string; readonly assistant: AssistantMessage | undefined };\nconst replyText = (message: AssistantMessage) => message.content.flatMap(part => part.type === 'text' && part.text ? [part.text] : []).join('\\n\\n');\n\n/** Read-only older records of the open conversation, paged in by the controller. Historical tool results are not current actions. */\nexport function HistoryPanel({ history, developer, connected, onLoad, onClose, replyFooter }: {\n readonly history: ChatHistoryState; readonly developer: boolean; readonly connected: boolean; readonly onLoad: () => void; readonly onClose: () => void;\n /** The host's reply footer, shown under each earlier reply that has text. Earlier records get no actions. */\n readonly replyFooter?: ((reply: ReplyRef) => ReactNode) | undefined;\n}) {\n const { labels, icons } = useChatText();\n const entries: readonly EntryRecord[] = 'entries' in history ? history.entries : [];\n const rows = entries.flatMap((entry): HistoryRow[] => entry.model?.length\n ? entry.model.flatMap((message, index) => { const made = line(message, developer, labels); return made ? [{ key: `history:${entry.id}:${index}`, entryId: String(entry.id), assistant: undefined, ...made }] : []; })\n : [{ key: `history:${entry.id}`, role: labels.roleEvent, body: entry.head === undefined ? entry.kind : labels.contextBoundary, entryId: String(entry.id), assistant: undefined }]);\n const exhausted = history.kind === 'ready' && !history.hasMore;\n return <section aria-label={labels.earlierMessages} data-testid=\"history\" aria-live=\"off\" className=\"shrink-0 border-b border-border bg-muted/20\">\n <div className=\"mx-auto flex max-w-3xl items-center gap-2 px-4 py-2\">\n <icons.history className=\"size-4 text-muted-foreground\" aria-hidden=\"true\" />\n <h3 className=\"m-0 min-w-0 flex-1 truncate font-(family-name:--chat-display) text-sm font-medium\">{labels.earlierMessages} <span className=\"font-normal text-muted-foreground\">{labels.readOnly}</span></h3>\n <Button size=\"sm\" variant=\"outline\" data-testid=\"history-load\" onClick={onLoad} disabled={!connected || history.kind === 'loading' || history.kind === 'disabled' || exhausted}>\n {history.kind === 'error' ? labels.retry : history.kind === 'loading' ? labels.loadingShort : labels.loadEarlier}</Button>\n <Button size=\"icon-sm\" aria-label={labels.returnToConversation} title={labels.returnToConversation} onClick={onClose}><XIcon className=\"size-4\" aria-hidden=\"true\" /></Button>\n </div>\n <div className=\"mx-auto max-h-[40dvh] max-w-3xl space-y-3 overflow-y-auto px-4 pb-3\">\n {history.kind === 'error' && <p role=\"alert\" className=\"m-0 text-sm text-destructive\">{labels.historyFailed}</p>}\n {history.kind === 'idle' && <p className=\"m-0 text-sm text-muted-foreground\">{labels.loadPage}</p>}\n {rows.map(row => <article key={row.key} data-history-row-id={row.key} className=\"rounded-lg border border-border bg-background/60 px-3 py-2\">\n <p className=\"m-0 mb-1 text-xs font-medium tracking-wide text-muted-foreground uppercase\">{row.role}</p>\n <div className=\"text-sm opacity-90\"><Markdown text={row.body} /></div>\n {replyFooter && row.assistant && replyText(row.assistant) && replyFooter({ key: row.key, text: replyText(row.assistant), entryId: row.entryId, ...replyMeta(row.assistant) })}</article>)}\n {history.kind === 'ready' && !rows.length && <p className=\"m-0 text-sm text-muted-foreground\">{labels.noRecords}</p>}\n {exhausted && <p className=\"m-0 text-center text-xs text-muted-foreground\">{labels.beginning}</p>}\n </div>\n </section>;\n}\n",
77
+ "type": "registry:component",
78
+ "target": "components/pi-chat/history.tsx"
79
+ },
80
+ {
81
+ "path": "registry/pi-chat/markdown.tsx",
82
+ "content": "'use client';\n\nimport { createElement, Fragment, memo, useMemo } from 'react';\nimport type { ReactNode } from 'react';\nimport { Marked } from 'marked';\nimport { decodeHTML } from 'entities';\nimport { CodeBlock } from './code-block';\nimport { useChatText } from './labels';\nimport type { ChatLabels } from './labels';\n\n/*\n * Safe Markdown for model output. Tokens are mapped to React elements one by one: raw HTML is shown as text, images are\n * shown as their alt text (nothing is fetched), and a link is only rendered when it is a plain http(s) URL.\n * Ported from the v4 `@hachej/boring-ui-kit` chat markdown renderer; the styling is Tailwind and fenced code gets a code block card.\n */\nexport interface CommandMention { readonly name: string; readonly behavior: 'execute' | 'insert' }\nexport interface CommandMentions {\n readonly commands: readonly CommandMention[];\n readonly onActivate: (command: CommandMention) => void;\n}\n\nconst markdown = new Marked({ gfm: true, breaks: false, pedantic: false });\n\nfunction isRecord(value: unknown): value is Record<string, unknown> { return value !== null && typeof value === 'object' && !Array.isArray(value); }\nfunction text(value: unknown): string { return typeof value === 'string' ? value : ''; }\nfunction visible(value: unknown): string {\n if (!isRecord(value)) return '';\n if (value['type'] === 'br') return '\\n';\n if (Array.isArray(value['tokens'])) return value['tokens'].map(visible).join('');\n const content = text(value['text']);\n return value['type'] === 'text' && value['escaped'] !== true ? decodeHTML(content) : content;\n}\nfunction containsHtml(value: unknown): boolean {\n if (!isRecord(value)) return false;\n return value['type'] === 'html' || Array.isArray(value['tokens']) && value['tokens'].some(containsHtml);\n}\nfunction literal(value: string): ReactNode { return <span className=\"whitespace-pre-wrap\">{value}</span>; }\n\ninterface Context { readonly mentions: CommandMentions | undefined; readonly onCopy: ((text: string) => Promise<void>) | undefined; readonly labels: ChatLabels }\n\nfunction children(value: unknown, context: Context, before = '', after = '', inline = false): ReactNode {\n if (!Array.isArray(value)) return null;\n if (!context.mentions) return value.map((token: unknown, index) => <Fragment key={index}>{renderToken(token, context)}</Fragment>);\n const shown = value.map(visible), source = before + shown.join('') + after;\n const active = inline && value.some(containsHtml) ? { ...context, mentions: undefined } : context;\n let position = before.length;\n return value.map((token: unknown, index) => {\n const start = position;\n position += shown[index]?.length ?? 0;\n return <Fragment key={index}>{renderToken(token, active, source.slice(0, start), source.slice(position))}</Fragment>;\n });\n}\n\nconst mentionPattern = /(^|[\\s(\\[{\"'“‘])\\/([A-Za-z0-9_][A-Za-z0-9_-]*)(?=$|\\s|[.,;!?)}\\]\"'”’]+(?=$|\\s))/g;\nfunction mentionText(value: string, mentions: CommandMentions | undefined, before: string, after: string, labels: ChatLabels): ReactNode {\n if (!mentions?.commands.length || !value.includes('/')) return value;\n const commands = new Map(mentions.commands.filter(item => /^[A-Za-z0-9_][A-Za-z0-9_-]*$/.test(item.name)\n && (item.behavior === 'execute' || item.behavior === 'insert')).map(item => [item.name, item]));\n if (!commands.size) return value;\n const source = before + value + after, start = before.length, end = start + value.length;\n const pieces: ReactNode[] = [];\n let cursor = 0;\n for (const match of source.matchAll(mentionPattern)) {\n if (match.index === undefined) continue;\n const boundary = match[1] ?? '', name = match[2];\n if (!name) continue;\n const offset = match.index + boundary.length, limit = offset + name.length + 1;\n const command: CommandMention | undefined = commands.get(name);\n if (!command || offset < start || limit > end || offset - start < cursor) continue;\n const selected = { name: command.name, behavior: command.behavior };\n const at = offset - start;\n if (at > cursor) pieces.push(value.slice(cursor, at));\n pieces.push(<button key={at} type=\"button\" data-testid=\"command-mention\" aria-label={labels.runCommand(selected.name, selected.behavior === 'execute')}\n className=\"cursor-pointer rounded bg-muted px-1 font-mono text-[0.92em] text-foreground hover:bg-accent\" onClick={() => mentions.onActivate(selected)}>/{selected.name}</button>);\n cursor = limit - start;\n }\n if (!pieces.length) return value;\n if (cursor < value.length) pieces.push(value.slice(cursor));\n return pieces;\n}\n\nfunction linkTarget(value: unknown): string | undefined {\n if (typeof value !== 'string') return undefined;\n const decoded = decodeHTML(value);\n if (!/^https?:\\/\\//i.test(decoded) || /[\\u0000- \\u007f-\\u009f\\\\]/.test(decoded)) return undefined;\n const authority = /^https?:\\/\\/([^/?#]*)/i.exec(decoded)?.[1];\n if (!authority || authority.includes('@')) return undefined;\n try {\n const url = new URL(decoded);\n if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) return undefined;\n return url.href;\n } catch { return undefined; }\n}\n\nfunction cells(value: unknown, header: boolean, context: Context): ReactNode {\n if (!Array.isArray(value)) return null;\n return value.map((cell: unknown, index) => {\n if (!isRecord(cell)) return null;\n const alignment = cell['align'];\n const textAlign = alignment === 'left' || alignment === 'center' || alignment === 'right' ? alignment : undefined;\n return createElement(header ? 'th' : 'td', { key: index, style: { textAlign }, className: header ? 'px-3 py-1.5 font-semibold' : 'px-3 py-1.5', ...(header ? { scope: 'col' } : {}) },\n children(cell['tokens'], context, '', '', true));\n });\n}\n\nconst HEADINGS: Record<number, string> = {\n 1: 'mt-6 mb-2 text-xl font-semibold tracking-tight', 2: 'mt-5 mb-2 text-base font-semibold tracking-tight', 3: 'mt-4 mb-1.5 text-sm font-semibold',\n 4: 'mt-4 mb-1 text-sm font-semibold', 5: 'mt-3 mb-1 text-sm font-medium', 6: 'mt-3 mb-1 text-sm font-medium text-muted-foreground',\n};\n\n// Marked's extension token includes arbitrary fields. Narrow those fields here before creating React nodes.\nfunction renderToken(value: unknown, context: Context, before = '', after = ''): ReactNode {\n if (!isRecord(value)) return null;\n const raw = text(value['raw']), content = text(value['text']), mentions = context.mentions;\n switch (value['type']) {\n case 'space': case 'def': return null;\n case 'paragraph': return <p className=\"my-3 first:mt-0 last:mb-0\">{children(value['tokens'], context, '', '', true)}</p>;\n case 'heading': {\n const depth = value['depth'];\n return typeof depth === 'number' && Number.isInteger(depth) && depth >= 1 && depth <= 6\n ? createElement(`h${depth}`, { className: `${HEADINGS[depth]} first:mt-0` }, children(value['tokens'], context, '', '', true)) : literal(raw);\n }\n case 'text': return Array.isArray(value['tokens']) ? children(value['tokens'], context, before, after, true)\n : value['escaped'] === true ? literal(content) : mentionText(decodeHTML(content), mentions, before, after, context.labels);\n case 'escape': return content;\n case 'strong': return <strong className=\"font-semibold text-foreground\">{children(value['tokens'], context, before, after, true)}</strong>;\n case 'em': return <em>{children(value['tokens'], context, before, after, true)}</em>;\n case 'del': return <del className=\"text-muted-foreground\">{children(value['tokens'], context, before, after, true)}</del>;\n case 'blockquote': return <blockquote className=\"my-3 rounded-lg border border-border bg-muted/40 px-4 py-2 text-muted-foreground [&_p]:my-1\">{children(value['tokens'], context)}</blockquote>;\n case 'br': return <br />;\n case 'hr': return <hr className=\"my-5 border-border\" />;\n case 'codespan': return <code className=\"rounded-md bg-muted px-1.5 py-0.5 font-mono text-[0.85em] whitespace-pre-wrap\">{content}</code>;\n case 'code': return <CodeBlock code={content} {...(typeof value['lang'] === 'string' && value['lang'] ? { language: value['lang'] } : {})} {...(context.onCopy ? { onCopy: context.onCopy } : {})} />;\n case 'html': return value['block'] === true ? <pre className=\"my-3 overflow-x-auto rounded-lg bg-muted/50 p-3 font-mono text-xs whitespace-pre-wrap\">{raw}</pre> : literal(raw);\n case 'image': return literal(decodeHTML(content) || raw);\n case 'link': {\n const href = linkTarget(value['href']), title = typeof value['title'] === 'string' ? decodeHTML(value['title']) : undefined;\n return href ? <a href={href} title={title} target=\"_blank\" rel=\"noopener noreferrer\"\n className=\"font-medium text-foreground underline decoration-muted-foreground/50 underline-offset-4 hover:decoration-foreground\">{children(value['tokens'], context)}</a> : children(value['tokens'], context);\n }\n case 'list': {\n const start = value['start'];\n return value['ordered'] === true\n ? <ol start={typeof start === 'number' && Number.isSafeInteger(start) ? start : undefined} className=\"my-3 list-decimal ps-6 marker:text-muted-foreground\">{children(value['items'], context)}</ol>\n : <ul className=\"my-3 list-disc ps-6 marker:text-muted-foreground\">{children(value['items'], context)}</ul>;\n }\n case 'list_item': return <li className=\"ps-1 [&+li]:mt-1 [&>p]:my-1 [&>ol]:my-1 [&>ul]:my-1\">{children(value['tokens'], context, '', '', true)}</li>;\n case 'checkbox': return <input type=\"checkbox\" checked={value['checked'] === true} disabled readOnly aria-label={context.labels.taskStatus} className=\"me-1.5 align-middle accent-foreground\" />;\n case 'table': return <div className=\"my-3 overflow-x-auto rounded-lg border border-border\"><table className=\"w-full border-collapse text-left tabular-nums\">\n <thead className=\"bg-muted/50\">{<tr>{cells(value['header'], true, context)}</tr>}</thead>\n <tbody className=\"[&_tr]:border-t [&_tr]:border-border\">{Array.isArray(value['rows']) ? value['rows'].map((row: unknown, index) => <tr key={index}>{cells(row, false, context)}</tr>) : null}</tbody></table></div>;\n default: return literal(raw);\n }\n}\n\n/** One top-level block; unchanged blocks skip re-rendering while a long answer streams. */\nconst Block = memo(function Block({ token, context }: { readonly token: unknown; readonly context: Context }) {\n return <>{renderToken(token, context)}</>;\n}, (a, b) => isRecord(a.token) && isRecord(b.token) && a.token['raw'] === b.token['raw'] && a.token['type'] === b.token['type'] && a.context.mentions === b.context.mentions && a.context.onCopy === b.context.onCopy && a.context.labels === b.context.labels);\n\nexport const Markdown = memo(function Markdown({ text: source, commandMentions, onCopy, streaming = false }: {\n readonly text: string; readonly commandMentions?: CommandMentions; readonly onCopy?: (text: string) => Promise<void>; readonly streaming?: boolean;\n}) {\n const tokens = useMemo(() => { try { return markdown.lexer(source); } catch { return null; } }, [source]);\n const mentions = source.includes('/') && commandMentions?.commands.length ? commandMentions : undefined;\n const { labels } = useChatText();\n const context = useMemo<Context>(() => ({ mentions, onCopy, labels }), [mentions, onCopy, labels]);\n const body = useMemo(() => {\n if (!tokens) return literal(source);\n // With mentions enabled, positions are relative to the whole text, so render the token list as one unit.\n if (mentions) return children(tokens, context);\n return tokens.map((token, index) => <Block key={index} token={token} context={context} />);\n }, [tokens, source, mentions, context]);\n return <div data-testid=\"message-text\" data-streaming={streaming ? 'true' : undefined} className=\"min-w-0 text-sm leading-relaxed [overflow-wrap:anywhere]\">\n {body}\n </div>;\n});\n",
83
+ "type": "registry:component",
84
+ "target": "components/pi-chat/markdown.tsx"
85
+ },
86
+ {
87
+ "path": "registry/pi-chat/mention-menu.tsx",
88
+ "content": "'use client';\n\nimport { useEffect, useRef, useState } from 'react';\nimport { FileTextIcon, FolderIcon } from 'lucide-react';\nimport { usePickerKeyboard } from './picker-keyboard';\nimport type { MentionResult, MentionsConfig } from './config';\nimport { cn } from '../utils/utils';\nimport { useChatText } from './labels';\n\nfunction highlight(text: string, query: string) {\n const at = query ? text.toLowerCase().indexOf(query.toLowerCase()) : -1;\n if (at < 0) return <>{text}</>;\n return <>{text.slice(0, at)}<mark className=\"bg-transparent font-semibold text-foreground underline decoration-ring/60 underline-offset-2\">{text.slice(at, at + query.length)}</mark>{text.slice(at + query.length)}</>;\n}\n\n/** The `@` file picker, ported from v2's `MentionPicker`: debounced search, one highlighted row, name over path. */\nexport function MentionMenu({ query, search, generation, onSelect, onDismiss }: {\n readonly query: string;\n readonly generation?: MentionsConfig['generation'];\n readonly search: MentionsConfig['search'];\n readonly onSelect: (path: string) => void;\n readonly onDismiss: () => void;\n}) {\n const { labels } = useChatText();\n // Results are tagged with the search function that produced them: a binding switch hides the previous binding's rows at once.\n const [outcome, setOutcome] = useState<{ readonly search: MentionsConfig['search']; readonly results: readonly MentionResult[]; readonly failure: string | null }>();\n const shown = outcome?.search === search ? outcome : undefined;\n const results = shown?.results ?? [];\n const failure = shown?.failure ?? null;\n const [active, setActive] = useState(0);\n const list = useRef<HTMLUListElement>(null), container = useRef<HTMLDivElement>(null);\n const searcher = useRef(search); searcher.current = search;\n useEffect(() => {\n setActive(0);\n const abort = new AbortController();\n const timer = setTimeout(() => {\n searcher.current(query, abort.signal).then(found => { if (!abort.signal.aborted) setOutcome({ search, results: found.slice(0, 8), failure: null }); },\n cause => { if (!abort.signal.aborted) setOutcome({ search, results: [], failure: cause instanceof Error ? cause.message : labels.searchFailed }); });\n }, 120);\n return () => { clearTimeout(timer); abort.abort(); };\n }, [query, search, generation]);\n useEffect(() => {\n const outside = (event: MouseEvent) => { if (container.current && !container.current.contains(event.target as Node)) onDismiss(); };\n document.addEventListener('mousedown', outside);\n return () => document.removeEventListener('mousedown', outside);\n }, [onDismiss]);\n usePickerKeyboard({ count: results.length, activeIdx: active, setActiveIdx: setActive, listRef: list, onSelect: index => { const item = results[index]; if (item) onSelect(item.path); }, onDismiss });\n\n if (results.length === 0 && !failure) return null;\n return <div ref={container} data-testid=\"mention-menu\" className=\"absolute inset-x-0 bottom-full z-20 mb-2 overflow-hidden rounded-xl border border-border bg-popover text-popover-foreground shadow-lg\">\n {failure ? <div role=\"alert\" data-testid=\"mention-error\" className=\"px-3 py-2 text-xs text-destructive\">{failure}</div>\n : <ul ref={list} role=\"listbox\" aria-label={labels.workspaceFiles} className=\"m-0 max-h-[min(14rem,40dvh)] list-none overflow-y-auto p-0 py-1\">\n {results.map((item, index) => {\n const name = item.path.split('/').pop() ?? item.path;\n const Icon = item.kind === 'directory' ? FolderIcon : FileTextIcon;\n return <li key={item.path} role=\"option\" aria-selected={index === active} data-testid=\"mention-item\" data-path={item.path} title={item.path}\n onMouseEnter={() => setActive(index)} onMouseDown={event => { event.preventDefault(); onSelect(item.path); }}\n className={cn('flex cursor-pointer items-center gap-2.5 px-3 py-1.5 text-xs max-sm:min-h-11 pointer-coarse:min-h-11', index === active ? 'bg-accent text-foreground' : 'text-muted-foreground')}>\n <Icon className=\"size-3.5 shrink-0 opacity-70\" aria-hidden=\"true\" />\n <span className=\"flex min-w-0 flex-col gap-0.5\"><span className=\"truncate font-medium text-foreground\">{highlight(name, query)}</span>\n <span className=\"truncate text-xs opacity-70\">{item.path}</span></span>\n </li>;\n })}\n </ul>}\n </div>;\n}\n",
89
+ "type": "registry:component",
90
+ "target": "components/pi-chat/mention-menu.tsx"
91
+ },
92
+ {
93
+ "path": "registry/pi-chat/message.tsx",
94
+ "content": "'use client';\n\nimport type { ReactNode } from 'react';\nimport type { ImageContent, ToolResultMessage, UserMessage } from '@earendil-works/pi-ai';\nimport { AlertCircleIcon, CircleSlashIcon } from 'lucide-react';\nimport { CopyButton } from './code-block';\nimport { Markdown } from './markdown';\nimport type { CommandMentions } from './markdown';\nimport { ArtifactCard } from './artifact-card';\nimport type { ArtifactsConfig } from './artifact';\nimport { ApprovalCard } from './approval-card';\nimport { QuestionCard } from './question-card';\nimport type { AnswerOutcome } from './question-card';\nimport { ActivityBlock } from './activity';\nimport type { ActivityState } from './activity';\nimport { Shimmer } from './shimmer';\nimport { ToolCard } from './tool';\nimport { thumbnail } from './composer';\nimport { pieces } from './config';\nimport { isFileBlock, segments } from './rows';\nimport type { DeriveOptions, Row } from './rows';\nimport { Button } from '../button/button';\nimport { BlockActions } from '../button/actions';\nimport type { BlockAction } from '../button/actions';\nimport { useChatText } from './labels';\nimport type { ReplyRef } from './config';\nimport { cn } from '../utils/utils';\n\nexport interface RowContext {\n readonly developer: boolean;\n readonly groupTool: DeriveOptions['groupTool'];\n readonly commandMentions: CommandMentions | undefined;\n readonly onOpenImage: ((image: ImageContent) => void) | undefined;\n readonly onCopy: ((text: string) => Promise<void>) | undefined;\n /** Which tokens of a sent message get a styled treatment (`@path` mentions, a leading `/skill`). */\n readonly pieces: { readonly mentions: boolean; readonly skills: readonly string[]; readonly openMention?: ((path: string) => void) | undefined; readonly renderMention?: ((path: string) => ReactNode | undefined) | undefined } | undefined;\n readonly answer: ((questionId: string, answer: string) => Promise<AnswerOutcome>) | undefined;\n readonly artifacts: { readonly open: ArtifactsConfig['open']; readonly isOpen?: ArtifactsConfig['isOpen'] | undefined } | undefined;\n /** Replaces the default copy button under a settled reply (the ambient window adds feedback and the time); `host` holds the host's message actions. */\n readonly replyActions?: ((reply: { readonly key: string; readonly text: string; readonly timestamp?: number | undefined }, host: ReactNode) => ReactNode) | undefined;\n /** The host's actions for a settled reply (`messageActions`). */\n readonly messageActions?: ((reply: ReplyRef) => readonly BlockAction[]) | undefined;\n /** A line under a finished reply (not while it streams, runs a tool or waits to retry), after its actions (a host shows which model answered and how long it took). */\n readonly replyFooter?: ((reply: ReplyRef) => ReactNode) | undefined;\n /** Fork the conversation after a settled reply (its last native entry): adds a Fork button next to Copy. */\n readonly onFork?: ((entryId: string) => void) | undefined;\n}\n\nconst replyRef = (row: Extract<Row, { type: 'assistant' }>): ReplyRef => ({ key: row.key, text: row.text, entryId: row.entryId, timestamp: row.timestamp, model: row.model, durationMs: row.durationMs });\n\nfunction Image({ image, onOpenImage }: { readonly image: ImageContent; readonly onOpenImage: RowContext['onOpenImage'] }) {\n const { labels } = useChatText();\n const src = thumbnail(image.mimeType, image.data);\n return <button type=\"button\" data-testid=\"message-image\" disabled={!onOpenImage} aria-label={labels.openImage} onClick={() => onOpenImage?.(image)}\n className=\"block cursor-pointer overflow-hidden rounded-xl border border-border outline-none focus-visible:ring-2 focus-visible:ring-ring/60 disabled:cursor-default\">\n {src ? <img src={src} alt={labels.imageAttachment} className=\"max-h-48 max-w-full object-cover\" /> : <span className=\"block px-3 py-2 text-xs text-muted-foreground\">{labels.imageAttachment}</span>}\n </button>;\n}\n\nconst MENTION_CLASS = 'rounded-md bg-background px-1.5 py-0.5 font-mono text-sm font-medium text-foreground ring-1 ring-border';\n\n/** A `@path` mention in a sent message: the host's own look when its `render` returns one, else the default chip (a button when it can be opened). */\nfunction UserMention({ path, text, open, render }: { readonly path: string; readonly text: string; readonly open: ((path: string) => void) | undefined; readonly render: ((path: string) => ReactNode | undefined) | undefined }) {\n const custom = render?.(path);\n if (custom !== undefined) return <>{custom}</>;\n return open\n ? <button type=\"button\" data-testid=\"message-mention\" data-path={path} aria-label={`Open ${path}`} onClick={() => open(path)} className={cn(MENTION_CLASS, 'cursor-pointer outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring/60 pointer-coarse:inline-flex pointer-coarse:min-h-10 pointer-coarse:items-center')}>{text}</button>\n : <span data-testid=\"message-mention\" data-path={path} className={MENTION_CLASS}>{text}</span>;\n}\n\nfunction UserText({ text, context }: { readonly text: string; readonly context: RowContext }) {\n const open = context.pieces?.openMention;\n const render = context.pieces?.renderMention;\n return <div data-testid=\"user-text\" className=\"max-w-[85%] rounded-2xl rounded-br-md bg-muted px-4 py-2.5 text-sm leading-6 whitespace-pre-wrap text-foreground [overflow-wrap:anywhere]\">{context.pieces ? pieces(text, context.pieces).map((piece, at) => piece.kind === 'mention'\n ? <UserMention key={at} path={piece.value!} text={piece.text} open={open} render={render} />\n : piece.kind === 'skill' ? <span key={at} data-testid=\"message-skill\" data-skill={piece.value} className=\"rounded-md bg-primary/10 px-1.5 py-0.5 font-medium text-foreground\">{piece.text}</span>\n : piece.text) : text}</div>;\n}\n\nfunction UserBubble({ message, context }: { readonly message: UserMessage; readonly context: RowContext }) {\n const parts = typeof message.content === 'string' ? [{ type: 'text' as const, text: message.content }] : message.content;\n return <div className=\"flex flex-col items-end gap-2\">\n {parts.map((part, index) => part.type === 'text' ? (isFileBlock(part.text) ? null : <UserText key={index} text={part.text} context={context} />)\n : <Image key={index} image={part} onOpenImage={context.onOpenImage} />)}\n </div>;\n}\n\nfunction Notice({ tone, icon, children, testid }: { readonly tone: 'error' | 'muted'; readonly icon: ReactNode; readonly children: ReactNode; readonly testid: string }) {\n return <p role={tone === 'error' ? 'alert' : 'status'} data-testid={testid}\n className={cn('my-2 mb-0 flex items-start gap-2 rounded-lg px-3 py-2 text-sm', tone === 'error' ? 'bg-destructive/10 text-destructive' : 'bg-muted/60 text-muted-foreground')}>{icon}<span className=\"min-w-0 [overflow-wrap:anywhere]\">{children}</span></p>;\n}\n\nfunction resultText(message: ToolResultMessage): string { return message.content.map(part => part.type === 'text' ? part.text : '').join('\\n'); }\n\nexport function RowView({ row, context }: { readonly row: Row; readonly context: RowContext }) {\n const { labels, icons } = useChatText();\n switch (row.type) {\n case 'user': return <article data-row-id={row.key} data-role=\"user\"><UserBubble message={row.message} context={context} /></article>;\n case 'card': return <article data-row-id={row.key} data-role=\"event\">{row.card.content}</article>;\n case 'event': return <article data-row-id={row.key} data-role=\"event\" className=\"text-center text-xs text-muted-foreground\">{labels.event(row.label)}</article>;\n case 'system': return <article data-row-id={row.key} data-role=\"system\"><details className=\"rounded-lg border border-border bg-muted/30 px-3 py-2 text-xs text-muted-foreground\"><summary className=\"cursor-pointer max-sm:py-3 pointer-coarse:py-3\">{labels.systemContext}</summary>\n <pre className=\"mt-2 mb-0 whitespace-pre-wrap\">{row.text}</pre></details></article>;\n case 'orphan-result': return <article data-row-id={row.key} data-role=\"toolResult\"><Notice tone=\"error\" testid=\"tool-error\" icon={<AlertCircleIcon className=\"mt-0.5 size-4 shrink-0\" aria-hidden=\"true\" />}>\n <strong className=\"font-semibold\">{labels.toolFailed(row.message.toolName)}</strong><span className=\"mt-1 block font-mono text-xs whitespace-pre-wrap\">{resultText(row.message)}</span></Notice></article>;\n case 'assistant': {\n const settled = !row.streaming;\n const chunks = segments(row.parts, context.groupTool);\n const active = row.active === true || row.streaming;\n const lastText = [...row.parts].reverse().find(part => part.kind === 'text');\n const host = settled && row.text && context.messageActions\n ? <BlockActions actions={context.messageActions(replyRef(row))} testId=\"reply-action\" menuLabel={labels.moreActions} className=\"text-muted-foreground\" />\n : null;\n return <article data-row-id={row.key} data-role=\"assistant\" data-streaming={row.streaming ? 'true' : undefined} className=\"group/message\">\n <div className=\"space-y-3\">\n {chunks.map((chunk, at) => {\n if (chunk.kind === 'activity') {\n const failed = chunk.steps.some(step => step.kind === 'tool' && step.entry.status === 'failed');\n const unfinished = chunk.steps.some(step => step.kind === 'tool' && step.entry.status === 'unfinished');\n const state: ActivityState = failed || row.stopReason === 'error' ? 'failed' : row.stopReason === 'aborted' || (!active && unfinished) ? 'stopped' : active && at === chunks.length - 1 ? 'running' : 'done';\n return <ActivityBlock key={chunk.key} steps={chunk.steps} state={state} streaming={row.streaming} developer={context.developer} {...(context.onOpenImage ? { onOpenImage: context.onOpenImage } : {})} />;\n }\n const part = chunk.part;\n if (part.kind === 'text') return <Markdown key={part.key} text={part.text} streaming={row.streaming && part === lastText && row.parts[row.parts.length - 1] === part}\n {...(settled && context.commandMentions ? { commandMentions: context.commandMentions } : {})} {...(context.onCopy ? { onCopy: context.onCopy } : {})} />;\n if (part.kind === 'thinking') return null; // reasoning is a step of an activity block\n if (part.kind === 'approval') return <ApprovalCard key={part.key} call={part.call} result={part.result} questionId={part.questionId} answer={context.answer} summary={part.summary} decision={part.decision} live={part.live} />;\n if (part.kind === 'question') return <QuestionCard key={part.key} call={part.call} result={part.result} questionId={part.questionId} answer={context.answer} live={part.live} />;\n if (part.kind === 'artifact') return <ArtifactCard key={part.key} artifact={part.artifact} title={part.title} {...(part.state === 'ready' ? {} : { pending: part.state })}\n open={part.artifact !== undefined && (context.artifacts?.isOpen?.(part.artifact) ?? false)} onOpen={context.artifacts?.open} />;\n return part.entry.custom ? <div key={part.key}>{part.entry.custom}</div> : <ToolCard key={part.key} entry={part.entry} {...(context.onOpenImage ? { onOpenImage: context.onOpenImage } : {})} />;\n })}\n {row.streaming && row.parts.length === 0 && <p data-testid=\"working\" className=\"m-0 text-sm\"><Shimmer>{labels.thinking}</Shimmer></p>}\n </div>\n {row.stopReason === 'error' && <Notice tone=\"error\" testid=\"response-error\" icon={<AlertCircleIcon className=\"mt-0.5 size-4 shrink-0\" aria-hidden=\"true\" />}>{row.errorMessage ?? labels.responseFailed}</Notice>}\n {row.stopReason === 'aborted' && <Notice tone=\"muted\" testid=\"interrupted\" icon={<CircleSlashIcon className=\"mt-0.5 size-4 shrink-0\" aria-hidden=\"true\" />}>{labels.interrupted}</Notice>}\n {settled && row.text && context.replyActions?.({ key: row.key, text: row.text, timestamp: row.timestamp }, host)}\n {settled && row.text && !context.replyActions && <div className=\"mt-1 -ml-2 flex opacity-0 transition-opacity group-focus-within/message:opacity-100 group-hover/message:opacity-100 pointer-coarse:opacity-100 max-sm:opacity-100 motion-reduce:transition-none\">\n <CopyButton text={row.text} label={labels.copyResponse} {...(context.onCopy ? { onCopy: context.onCopy } : {})} className=\"text-muted-foreground\" />\n {context.onFork && row.entryId && <Button size=\"icon-sm\" variant=\"ghost\" aria-label={labels.fork} title={labels.forkHint} data-testid=\"fork-reply\"\n className=\"text-muted-foreground\" onClick={() => context.onFork!(row.entryId!)}><icons.fork className=\"size-3.5\" aria-hidden=\"true\" /></Button>}\n {host}</div>}\n {settled && !row.active && row.text && context.replyFooter?.(replyRef(row))}\n </article>;\n }\n }\n}\n",
95
+ "type": "registry:component",
96
+ "target": "components/pi-chat/message.tsx"
97
+ },
98
+ {
99
+ "path": "registry/pi-chat/notice.tsx",
100
+ "content": "'use client';\n\nimport type { ReactNode } from 'react';\nimport type { NativeChatSnapshot } from '@hachej/boring-ui-kit/native-chat';\nimport { Button } from '../button/button';\nimport { useChatText } from './labels';\nimport { cn } from '../utils/utils';\n\nexport function Notice({ tone = 'error', children, testid }: { readonly tone?: 'error' | 'info'; readonly children: ReactNode; readonly testid?: string }) {\n return <div role={tone === 'error' ? 'alert' : 'status'} {...(testid ? { 'data-testid': testid } : {})}\n className={cn('flex flex-wrap items-center gap-2 rounded-lg px-3 py-2 text-sm', tone === 'error' ? 'bg-destructive/10 text-destructive' : 'bg-muted/60 text-muted-foreground')}>{children}</div>;\n}\n\n/** What went wrong with sending or stopping, and the recovery for an unknown submission. Shared by every chat surface. */\nexport function ChatNotices({ state, error, onReconcile, onRetry }: {\n readonly state: Pick<NativeChatSnapshot, 'send' | 'stop'>;\n readonly error: string | null;\n readonly onReconcile: () => void;\n readonly onRetry: () => void;\n}) {\n const { labels } = useChatText();\n return <>\n {error && <Notice testid=\"chat-error\">{error}</Notice>}\n {state.send.kind === 'blocked' && <Notice testid=\"send-blocked\">{state.send.reason}</Notice>}\n {state.send.kind === 'unknown' && <Notice testid=\"send-unknown\"><span className=\"flex-1\">{labels.sendUnknown}</span>\n <Button size=\"sm\" variant=\"outline\" onClick={onReconcile}>{labels.checkSubmission}</Button>\n <Button size=\"sm\" variant=\"outline\" onClick={onRetry}>{labels.retrySame}</Button></Notice>}\n {state.stop === 'requested' && <Notice tone=\"info\" testid=\"stop-requested\">{labels.stopRequested}</Notice>}\n {state.stop === 'unconfirmed' && <Notice testid=\"stop-unconfirmed\">{labels.stopUnconfirmed}</Notice>}\n </>;\n}\n",
101
+ "type": "registry:component",
102
+ "target": "components/pi-chat/notice.tsx"
103
+ },
104
+ {
105
+ "path": "registry/pi-chat/pi-chat.tsx",
106
+ "content": "'use client';\n\nimport { useMemo, useRef, useState } from 'react';\nimport type { KeyboardEvent, ReactNode } from 'react';\nimport type { EntryRecord } from '@earendil-works/pi-durable';\nimport type { ImageContent, ToolCall, ToolResultMessage } from '@earendil-works/pi-ai';\nimport type { ChatAttachment, NativeChatController } from '@hachej/boring-ui-kit/native-chat';\nimport { Loader2Icon } from 'lucide-react';\nimport { Button } from '../button/button';\nimport { BlockActions } from '../button/actions';\nimport type { BlockAction } from '../button/actions';\nimport { Composer } from './composer';\nimport type { ComposerFeedback } from './composer';\nimport type { AttachmentsConfig, ConversationsConfig, EffortConfig, MentionsConfig, ModelConfig, SlashConfig } from './config';\nimport { EmptyState } from './empty-state';\nimport type { Suggestion } from './empty-state';\nimport { ConversationHistory, HistoryPanel } from './history';\nimport type { CommandMentions } from './markdown';\nimport { RowView } from './message';\nimport { MessageQueue } from './queue';\nimport { ChatNotices, Notice } from './notice';\nimport type { ArtifactsConfig } from './artifact';\nimport type { ChatCard, Mode } from './rows';\nimport { Shimmer } from './shimmer';\nimport { useChatSession, useTranscript } from './session';\nimport type { ChatFeatureProps, FilesHandler, PiChatActions } from './session';\nimport { ChatTextProvider, useChatText, useMergedText } from './labels';\nimport { chatTextFor } from './locale';\nimport type { ChatLocale } from './locale';\nimport type { ChatIcons, ChatLabels } from './labels';\nimport { cn } from '../utils/utils';\n\nexport type { PiChatActions } from './session';\nexport type { ChatCard, Mode } from './rows';\nexport type { AnswerOutcome } from './question-card';\nexport { artifactKey, collectArtifacts, detectArtifact, parseArtifact } from './artifact';\nexport type { ArtifactDescriptor, ArtifactsConfig, ArtifactTarget, ArtifactType } from './artifact';\nexport type { CommandMention, CommandMentions } from './markdown';\nexport type { Suggestion } from './empty-state';\nexport { ConversationList, relativeTime } from './history';\nexport { defaultChatIcons, defaultChatLabels } from './labels';\nexport type { ChatIcons, ChatLabels } from './labels';\nexport { frenchChatLabels } from './labels-fr';\nexport { chatTextFor } from './locale';\nexport type { ChatLocale } from './locale';\nexport { ActionMenu, BlockActions } from '../button/actions';\nexport type { BlockAction, BlockIcon } from '../button/actions';\nexport type { AttachmentsConfig, ConversationItem, ConversationsConfig, EffortConfig, MentionResult, MentionsConfig, ModelConfig, ModelRef, ReplyRef, SlashApi, SlashCommand, SlashConfig, SlashSkill, UploadResult } from './config';\n\nexport interface PiChatProps extends ChatFeatureProps {\n readonly controller: NativeChatController;\n /** Every word the chat shows (title, placeholder, buttons, notices, empty states): a partial object over `defaultChatLabels`. */\n /** The chat's language: `en` (default) or `fr`. `labels` override any of its words. */\n readonly locale?: ChatLocale | undefined;\n readonly labels?: Partial<ChatLabels> | undefined;\n /** The chat's icons (send, stop, history, attach, …): any component taking `className`, over `defaultChatIcons`. */\n readonly icons?: Partial<ChatIcons> | undefined;\n /** The agent's avatar (an image or an icon) before the title in the header, and in the empty state instead of the agent icon. */\n readonly avatar?: ReactNode;\n /** Host actions in the header beside History: `header` ones as buttons, `menu` ones in a \"…\" menu. Test ids `chat-action-<id>`, the menu `chat-action-more`. */\n readonly headerActions?: readonly BlockAction[] | undefined;\n readonly className?: string;\n readonly decisions?: ReactNode;\n readonly controls?: ReactNode;\n /** Host controls at the end of the composer bar (for example a microphone), like AmbientChat's tools slot. */\n readonly tools?: ReactNode;\n /** Rendered before the title in the header (for example a menu button on narrow screens). */\n readonly headerStart?: ReactNode;\n readonly onFiles?: FilesHandler;\n /** Shown instead of the default empty state before the first message. */\n readonly emptyState?: ReactNode;\n readonly suggestions?: readonly Suggestion[];\n /** Past conversations. The header's History button then opens a searchable list with the open one marked and a New action. Omit it and History pages through the earlier records of this conversation. */\n readonly conversations?: ConversationsConfig;\n /**\n * `false`: the host shows `conversations` itself (for example the `pi-app` sessions pane), so History pages through the earlier records of this\n * conversation while replies keep their Fork button (`conversations.fork`). Default `true`: History opens the list.\n */\n readonly historyList?: boolean;\n /** Show the header History button. Default true; paging remains available through the controller. */\n readonly showHistory?: boolean;\n /** Show the header connection badge. Default true; connection state still controls actions. */\n readonly showConnectionStatus?: boolean;\n /** The optional Feedback button in the composer (the registry `feedback` item's `useComposerFeedback`). Omit it and nothing changes. */\n readonly feedback?: ComposerFeedback;\n}\n\nconst PAGE = 60, MORE = 40;\n\n/** Borrows a concrete native controller; unmount releases presentation and uploads only. */\nexport function PiChat(props: PiChatProps) {\n const active = useRef(props.controller); active.current = props.controller;\n const [mount, setMount] = useState({ controller: props.controller, sequence: 0 });\n if (mount.controller !== props.controller) setMount({ controller: props.controller, sequence: mount.sequence + 1 });\n const text = useMergedText(props.labels, props.icons, chatTextFor(props.locale));\n return <ChatTextProvider value={text}><PiChatSession key={mount.sequence} {...props} activeController={active} /></ChatTextProvider>;\n}\n\nfunction ConnectionBadge({ kind }: { readonly kind: string }) {\n const { labels } = useChatText();\n const live = kind === 'connected';\n return <span data-testid=\"connection\" data-state={kind} role=\"status\" className=\"inline-flex items-center gap-1.5 rounded-full border border-border px-2.5 py-0.5 text-xs text-muted-foreground\">\n <span aria-hidden=\"true\" className={cn('size-1.5 rounded-full', live ? 'bg-(--chat-success)' : 'animate-pulse bg-(--chat-warning) motion-reduce:animate-none')} />\n {live ? labels.live : kind === 'connecting' || kind === 'idle' ? labels.connecting : labels.reconnecting}\n </span>;\n}\n\nfunction PiChatSession({ controller, mode = 'expert', className, actions, avatar, headerActions, decisions, controls, tools, headerStart, renderEntry, renderTool, groupTool, commandMentions,\n onOpenImage, onCopy, onComposerKeyDown, onFiles, fileAccept = 'image/*', emptyState, suggestions, messageActions, replyFooter, slash, mentions, attachments, model, effort, artifacts, conversations, historyList = true, showHistory = true, showConnectionStatus = true, feedback, activeController: active }: PiChatProps & { readonly activeController: { readonly current: NativeChatController } }) {\n const { labels, icons } = useChatText();\n const { title } = labels;\n const [browsingHistory, setBrowsingHistory] = useState(false);\n const [pickingConversation, setPickingConversation] = useState(false);\n const scrollToBottom = useRef<() => void>(() => {});\n // A reply's Fork button calls the host's latest `fork`; the row context changes only when forking is switched on or off.\n const fork = useRef(conversations?.fork); fork.current = conversations?.fork;\n const canFork = Boolean(conversations?.fork);\n const rowExtras = useMemo(() => canFork ? { onFork: (entryId: string) => { void fork.current?.(entryId).catch(() => {}); } } : undefined, [canFork]);\n const session = useChatSession({ controller, activeController: active, mode, actions, renderEntry, renderTool, groupTool, commandMentions, onOpenImage, onCopy, onComposerKeyDown, onFiles, fileAccept,\n slash, mentions, attachments, model, effort, artifacts, messageActions, replyFooter, afterSend: () => scrollToBottom.current(), feedback, rowExtras });\n const { state, derived, queued, queueActions, working, waitingForAnswer, connected, error, act, textarea, rowContext, composer, empty, loading, developer } = session;\n const { rows, pinned, retry } = derived;\n const transcript = useTranscript(rows, PAGE, MORE);\n const { stick, hidden } = transcript;\n scrollToBottom.current = () => { void stick.scrollToBottom('instant'); };\n const visible = transcript.visible(rows);\n const { barStart, barNote } = session.pickers();\n const connectionKind = state.connection.kind;\n\n return <section data-boring=\"pi-chat\" aria-label={title} className={cn('pi-chat relative flex h-full min-h-0 min-w-0 flex-col overflow-hidden bg-background text-foreground', className)}>\n <header className=\"flex shrink-0 items-center gap-2 border-b border-border px-3 py-2 sm:gap-3 sm:px-4 sm:py-2.5\">\n {headerStart}\n {avatar && <span data-testid=\"chat-avatar\" className=\"flex size-7 shrink-0 items-center justify-center overflow-hidden rounded-full [&>img]:size-full [&>img]:object-cover [&>svg]:size-4\">{avatar}</span>}\n <h2 className=\"m-0 min-w-0 flex-1 truncate font-(family-name:--chat-display) text-sm font-semibold tracking-tight\">{title}</h2>\n {showHistory && (conversations && historyList\n ? <Button size=\"sm\" data-testid=\"history-open\" className=\"text-muted-foreground\" aria-haspopup=\"dialog\" aria-expanded={pickingConversation} disabled={state.disposed}\n onClick={() => setPickingConversation(open => !open)}><icons.history className=\"size-3.5\" aria-hidden=\"true\" />{labels.history}</Button>\n : state.history.kind !== 'disabled' && !browsingHistory && <Button size=\"sm\" data-testid=\"history-open\" className=\"text-muted-foreground\" disabled={state.disposed || !connected}\n onClick={() => { setBrowsingHistory(true); act(controller.loadEarlier); }}><icons.history className=\"size-3.5\" aria-hidden=\"true\" />{labels.history}</Button>)}\n <BlockActions actions={headerActions} testId=\"chat-action\" menuLabel={labels.moreActions} />\n {showConnectionStatus && <ConnectionBadge kind={connectionKind} />}\n {controls}\n </header>\n\n {decisions && <div data-boring=\"required-decisions\" className=\"shrink-0 border-b border-border px-4 py-2\">{decisions}</div>}\n {pinned.length > 0 && <aside aria-label={labels.requiredActions} className=\"shrink-0 space-y-2 border-b border-border px-4 py-2\">{pinned.map(card => <div key={card.key}>{card.content}</div>)}</aside>}\n {(connectionKind === 'error' || connectionKind === 'closed') && <div className=\"shrink-0 px-4 pt-2\">\n <Notice tone={connectionKind === 'error' ? 'error' : 'info'} testid=\"connection-notice\">\n <span className=\"flex-1\">{connectionKind === 'error' ? labels.loadFailed : labels.disconnected}</span>\n {!state.disposed && <Button size=\"sm\" variant=\"outline\" onClick={() => act(controller.connect)}><icons.reconnect className=\"size-3.5\" aria-hidden=\"true\" />{labels.reconnect}</Button>}\n </Notice></div>}\n {pickingConversation && conversations && historyList && <ConversationHistory conversations={conversations} onClose={() => setPickingConversation(false)}\n onBrowseEarlier={state.history.kind !== 'disabled' && connected && Boolean(state.view?.entries.length) ? () => { setBrowsingHistory(true); act(controller.loadEarlier); } : undefined} />}\n {browsingHistory && state.history.kind !== 'disabled' && <HistoryPanel history={state.history} developer={developer} replyFooter={replyFooter} connected={!state.disposed && connected}\n onLoad={() => act(controller.loadEarlier)} onClose={() => { setBrowsingHistory(false); if (!state.disposed) controller.clearHistory(); }} />}\n\n <div className=\"relative min-h-0 flex-1\">\n <div ref={stick.scrollRef} data-testid=\"transcript-scroll\" className=\"h-full overflow-x-hidden overflow-y-auto overscroll-contain\">\n <div ref={stick.contentRef} role=\"log\" aria-label={labels.messages} aria-live=\"polite\" data-testid=\"transcript\" className=\"mx-auto flex min-h-full w-full max-w-3xl flex-col gap-6 px-3 pt-6 pb-8 sm:px-4\">\n {hidden > 0 && <div className=\"flex justify-center\"><Button size=\"sm\" variant=\"outline\" data-testid=\"show-earlier\" className=\"text-muted-foreground\" onClick={transcript.reveal}>{labels.showEarlier}</Button></div>}\n {visible.map(row => <RowView key={row.key} row={row} context={rowContext} />)}\n </div>\n </div>\n {(empty || loading) && <div className=\"pointer-events-none absolute inset-0\">\n <div className=\"pointer-events-auto h-full\">\n {loading ? <p role=\"status\" data-testid=\"loading\" className=\"flex h-full items-center justify-center gap-2 text-sm text-muted-foreground\"><Loader2Icon className=\"size-4 animate-spin motion-reduce:animate-none\" aria-hidden=\"true\" />{labels.loading}</p>\n : emptyState ?? <EmptyState title={title} description={labels.emptyDescription} {...(avatar ? { avatar } : {})} {...(suggestions ? { suggestions } : {})} onSelect={text => { controller.setText(text); textarea.current?.focus(); }} />}\n </div></div>}\n {!stick.isAtBottom && <Button variant=\"outline\" size=\"icon\" data-testid=\"jump-latest\" aria-label={labels.jumpToLatest} title={labels.jumpToLatest} onClick={() => { transcript.reset(); void stick.scrollToBottom(); }}\n className=\"absolute bottom-3 left-1/2 -translate-x-1/2 bg-background/95 shadow-md backdrop-blur\"><icons.jumpToLatest className=\"size-4\" aria-hidden=\"true\" /></Button>}\n </div>\n\n <footer className=\"shrink-0 px-3 pt-1 pb-[max(1rem,env(safe-area-inset-bottom))] sm:px-4\">\n <div className=\"mx-auto w-full max-w-3xl space-y-2\">\n <div aria-live=\"polite\" className=\"space-y-2 empty:hidden\">\n {working && <p role=\"status\" data-testid=\"agent-status\" className=\"m-0 flex items-center gap-2 px-1 text-xs text-muted-foreground\"><span aria-hidden=\"true\" className=\"size-1.5 animate-pulse rounded-full bg-(--chat-success) motion-reduce:animate-none\" />\n <Shimmer active={!waitingForAnswer}>{waitingForAnswer ? labels.waitingForAnswer : retry ? labels.retryPending : labels.agentWorking}</Shimmer></p>}\n {derived.compacting && <p role=\"status\" className=\"m-0 px-1 text-xs text-muted-foreground\">{labels.compacting}</p>}\n <ChatNotices state={state} error={error} onReconcile={() => act(controller.reconcile)} onRetry={() => act(controller.retrySameRequest)} />\n </div>\n <div>\n <MessageQueue items={queued} sending={state.outbox} withdraw={actions?.withdraw} actions={queueActions} />\n <Composer {...composer} barStart={barStart} barNote={barNote} barEnd={tools} />\n </div>\n </div>\n </footer>\n </section>;\n}\n",
107
+ "type": "registry:component",
108
+ "target": "components/pi-chat/pi-chat.tsx"
109
+ },
110
+ {
111
+ "path": "registry/pi-chat/picker-keyboard.ts",
112
+ "content": "'use client';\n\nimport { useEffect, useRef } from 'react';\nimport type { Dispatch, RefObject, SetStateAction } from 'react';\n\n/**\n * Keyboard navigation for a floating picker, ported from v2's `use-picker-keyboard`. It listens on the window in the\n * capture phase and stops handled keys, so the textarea keeps focus and Enter does not also send the message.\n */\nexport function usePickerKeyboard({ count, activeIdx, setActiveIdx, listRef, onSelect, onDismiss }: {\n readonly count: number;\n readonly activeIdx: number;\n readonly setActiveIdx: Dispatch<SetStateAction<number>>;\n readonly listRef: RefObject<HTMLElement | null>;\n readonly onSelect: (index: number) => void;\n readonly onDismiss: () => void;\n}) {\n const select = useRef(onSelect), dismiss = useRef(onDismiss);\n select.current = onSelect; dismiss.current = onDismiss;\n useEffect(() => {\n const handler = (event: KeyboardEvent) => {\n if (event.isComposing) return;\n const handled = () => { event.preventDefault(); event.stopPropagation(); };\n if (event.key === 'ArrowDown') { handled(); setActiveIdx(index => count === 0 ? 0 : (index + 1) % count); }\n else if (event.key === 'ArrowUp') { handled(); setActiveIdx(index => count === 0 ? 0 : (index - 1 + count) % count); }\n else if (event.key === 'Enter' || event.key === 'Tab') {\n if (count > 0) { handled(); select.current(activeIdx); }\n // Nothing to pick: close and let the key reach the textarea (Enter then sends as usual).\n else dismiss.current();\n } else if (event.key === 'Escape') { handled(); dismiss.current(); }\n };\n window.addEventListener('keydown', handler, { capture: true });\n return () => window.removeEventListener('keydown', handler, { capture: true });\n }, [count, activeIdx, setActiveIdx]);\n useEffect(() => { (listRef.current?.children[activeIdx] as HTMLElement | undefined)?.scrollIntoView({ block: 'nearest' }); }, [activeIdx, listRef]);\n}\n",
113
+ "type": "registry:lib",
114
+ "target": "components/pi-chat/picker-keyboard.ts"
115
+ },
116
+ {
117
+ "path": "registry/pi-chat/pickers.tsx",
118
+ "content": "'use client';\n\nimport { useEffect, useRef, useState } from 'react';\nimport { CheckIcon, ChevronDownIcon, Loader2Icon } from 'lucide-react';\nimport type { EffortConfig, ModelConfig, ModelRef } from './config';\nimport { cn } from '../utils/utils';\nimport { useChatText } from './labels';\n\ninterface Choice { readonly section: 'model' | 'effort'; readonly value: string; readonly label: string; readonly detail?: string }\n\nconst key = (model: ModelRef) => `${model.provider}/${model.modelId}`;\n\n/**\n * One pill for the model and the thinking level (\"GPT-5 mini · Medium\") that opens one listbox with a section for each\n * (arrow keys, Enter, Escape, outside click). Only the configured parts show; with neither there is no pill.\n */\nexport function ModelEffortPicker({ model, effort, currentModel, currentEffort, disabled, busy, onModel, onEffort }: {\n readonly model: ModelConfig | undefined; readonly effort: EffortConfig | undefined;\n readonly currentModel: ModelRef | undefined; readonly currentEffort: string | undefined;\n readonly disabled: boolean; readonly busy: 'model' | 'effort' | null;\n readonly onModel: (model: ModelRef) => void; readonly onEffort: (level: string) => void;\n}) {\n const { labels } = useChatText();\n const name = labels.effortName;\n const models: Choice[] = (model?.options ?? []).map(option => ({ section: 'model', value: key(option), label: option.label ?? option.modelId, detail: option.provider }));\n // A model or level outside the offered list is still shown, so the label never lies about what runs.\n if (model && currentModel && !models.some(choice => choice.value === key(currentModel))) models.unshift({ section: 'model', value: key(currentModel), label: currentModel.modelId, detail: currentModel.provider });\n const levels: Choice[] = (effort?.options ?? []).map(level => ({ section: 'effort', value: level, label: name(level), ...(labels.effortDetail(level) ? { detail: labels.effortDetail(level)! } : {}) }));\n if (effort && currentEffort && !levels.some(choice => choice.value === currentEffort)) levels.unshift({ section: 'effort', value: currentEffort, label: name(currentEffort) });\n const choices = [...models, ...levels];\n const modelValue = currentModel ? key(currentModel) : '';\n const isCurrent = (choice: Choice) => choice.value === (choice.section === 'model' ? modelValue : currentEffort);\n\n const [open, setOpen] = useState(false);\n const [active, setActive] = useState(0);\n const root = useRef<HTMLDivElement>(null), list = useRef<HTMLUListElement>(null), trigger = useRef<HTMLButtonElement>(null);\n const selected = Math.max(0, choices.findIndex(isCurrent));\n const close = () => { setOpen(false); trigger.current?.focus(); };\n useEffect(() => {\n if (!open) return;\n setActive(selected);\n const outside = (event: MouseEvent) => { if (root.current && !root.current.contains(event.target as Node)) setOpen(false); };\n document.addEventListener('mousedown', outside);\n return () => document.removeEventListener('mousedown', outside);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [open]);\n useEffect(() => { if (open) list.current?.querySelector<HTMLElement>('[data-active=true]')?.scrollIntoView({ block: 'nearest' }); }, [open, active]);\n useEffect(() => { if (disabled) setOpen(false); }, [disabled]);\n if (!choices.length) return null;\n\n const choose = (index: number) => {\n const choice = choices[index];\n setOpen(false);\n if (!choice || isCurrent(choice)) return;\n if (choice.section === 'effort') return onEffort(choice.value);\n const option = model?.options.find(item => key(item) === choice.value);\n if (option) onModel({ provider: option.provider, modelId: option.modelId });\n };\n const onKeyDown = (event: React.KeyboardEvent) => {\n if (!open) return;\n if (event.key === 'ArrowDown') { event.preventDefault(); setActive(index => (index + 1) % choices.length); }\n else if (event.key === 'ArrowUp') { event.preventDefault(); setActive(index => (index - 1 + choices.length) % choices.length); }\n else if (event.key === 'Enter' || event.key === ' ' || event.key === 'Tab') { event.preventDefault(); choose(active); trigger.current?.focus(); }\n else if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); close(); }\n };\n const modelLabel = model ? models.find(choice => choice.value === modelValue)?.label || currentModel?.modelId || labels.model : undefined;\n const effortLabel = effort ? currentEffort ? name(currentEffort) : labels.effortDefault : undefined;\n const summary = [modelLabel, effortLabel].filter(Boolean).join(' · ');\n const description = labels.modelSummary(modelLabel, effortLabel);\n const row = (choice: Choice, index: number) => <li key={`${choice.section}:${choice.value}`} role=\"option\" aria-selected={isCurrent(choice)} data-testid={`composer-${choice.section}-option`} data-value={choice.value} data-active={index === active}\n onMouseEnter={() => setActive(index)} onMouseDown={event => { event.preventDefault(); choose(index); trigger.current?.focus(); }}\n className={cn('flex cursor-pointer items-center gap-2 rounded-lg px-2.5 py-1.5 text-sm max-sm:min-h-11 pointer-coarse:min-h-11', index === active ? 'bg-accent text-foreground' : 'text-muted-foreground')}>\n <span className=\"flex min-w-0 flex-1 flex-col\"><span className=\"truncate font-medium text-foreground\">{choice.label}</span>\n {choice.detail && <span className=\"truncate text-xs opacity-70\">{choice.detail}</span>}</span>\n {isCurrent(choice) && <CheckIcon className=\"size-4 shrink-0\" aria-hidden=\"true\" />}\n </li>;\n const section = (title: string, items: readonly Choice[], offset: number) => items.length > 0 && <li role=\"presentation\" key={title}>\n <ul role=\"group\" aria-label={title} className=\"m-0 list-none p-0\">\n <li role=\"presentation\" className=\"px-2.5 pt-1.5 pb-1 text-xs font-medium text-muted-foreground\">{title}</li>\n {items.map((choice, index) => row(choice, offset + index))}\n </ul></li>;\n return <div ref={root} className=\"relative min-w-0 shrink\" onKeyDown={onKeyDown}>\n <button ref={trigger} type=\"button\" data-testid=\"composer-model\" data-value={modelValue} data-effort={currentEffort ?? ''} disabled={disabled} aria-haspopup=\"listbox\" aria-expanded={open} aria-label={description} title={description}\n onClick={() => setOpen(value => !value)}\n className=\"inline-flex h-11 min-w-0 max-w-full cursor-pointer items-center gap-1.5 rounded-full bg-muted px-4 text-sm font-medium text-foreground transition-colors outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring/60 disabled:cursor-not-allowed disabled:opacity-60 motion-reduce:transition-none max-sm:px-3\">\n {busy && <Loader2Icon className=\"size-3.5 shrink-0 animate-spin motion-reduce:animate-none\" aria-hidden=\"true\" />}\n <span data-testid=\"composer-model-label\" className=\"min-w-0 truncate\">{summary}</span>\n <ChevronDownIcon className=\"size-3.5 shrink-0 opacity-50\" aria-hidden=\"true\" />\n </button>\n {open && <ul ref={list} role=\"listbox\" aria-label={labels.modelAndEffort} data-testid=\"composer-model-menu\" className=\"absolute bottom-full left-0 z-20 mb-2 m-0 max-h-80 min-w-56 list-none overflow-y-auto rounded-2xl border border-border bg-popover p-1.5 text-popover-foreground shadow-lg max-sm:fixed max-sm:inset-x-0 max-sm:bottom-0 max-sm:mb-0 max-sm:max-h-[70dvh] max-sm:rounded-b-none max-sm:p-2 max-sm:pb-[max(0.5rem,env(safe-area-inset-bottom))]\">\n {model && section(labels.model, models, 0)}\n {effort && section(labels.effort, levels, models.length)}\n </ul>}\n </div>;\n}\n",
119
+ "type": "registry:component",
120
+ "target": "components/pi-chat/pickers.tsx"
121
+ },
122
+ {
123
+ "path": "registry/pi-chat/question-card.tsx",
124
+ "content": "'use client';\n\nimport { useEffect, useRef, useState } from 'react';\nimport type { FormEvent } from 'react';\nimport type { ToolCall, ToolResultMessage } from '@earendil-works/pi-ai';\nimport { CheckIcon, MessageCircleQuestionIcon, SendIcon } from 'lucide-react';\nimport { Button } from '../button/button';\nimport { cn } from '../utils/utils';\nimport { useChatText } from './labels';\n\n/** What the host answers when asked to resolve a pending question. */\nexport type AnswerOutcome = { readonly kind: 'answered' } | { readonly kind: 'denied' | 'conflict' | 'unknown-question'; readonly reason?: string };\nexport const ASK_USER_TOOL = 'ask_user';\n\ninterface Question { readonly question: string; readonly options: readonly string[]; readonly allowFreeText: boolean }\n\n/** Read `{ question, options?, allowFreeText? }` defensively: model arguments are untrusted input. */\nexport function parseQuestion(call: ToolCall): Question {\n const args = call.arguments as Record<string, unknown>;\n const options = Array.isArray(args['options']) ? args['options'].filter((item): item is string => typeof item === 'string' && item.length > 0).slice(0, 6) : [];\n return { question: typeof args['question'] === 'string' ? args['question'] : '', options, allowFreeText: args['allowFreeText'] === true };\n}\n\n/** The answered text from a result such as `{\"kind\":\"answered\",\"answer\":\"...\"}`; undefined when the call did not produce an answer. */\nexport function parseAnswer(result: ToolResultMessage | undefined): { readonly answer: string } | { readonly failure: string } | undefined {\n if (!result) return undefined;\n const text = result.content.map(part => part.type === 'text' ? part.text : '').join('');\n if (!result.isError) {\n try {\n const value: unknown = JSON.parse(text);\n if (value !== null && typeof value === 'object' && (value as { kind?: unknown }).kind === 'answered' && typeof (value as { answer?: unknown }).answer === 'string') return { answer: (value as { answer: string }).answer };\n } catch { /* fall through to the failure text */ }\n }\n return { failure: text || 'The question was not answered.' };\n}\n\n\n/** Human-in-the-loop question: writing (still generated, not answerable), pending (options and optional free text), then answered with the chosen answer. */\nexport function QuestionCard({ call, result, answer, questionId, live = false }: {\n readonly call: ToolCall;\n readonly result: ToolResultMessage | undefined;\n readonly questionId: string | undefined;\n readonly answer?: ((questionId: string, answer: string) => Promise<AnswerOutcome>) | undefined;\n /** The call is still being generated by the model: it cannot be answered yet. */\n readonly live?: boolean;\n}) {\n const { labels } = useChatText();\n const question = parseQuestion(call);\n const settled = parseAnswer(result);\n const [sent, setSent] = useState<string | undefined>();\n const [sending, setSending] = useState<string | undefined>();\n const [refusal, setRefusal] = useState<string | undefined>();\n const [text, setText] = useState('');\n const mounted = useRef(true);\n useEffect(() => { mounted.current = true; return () => { mounted.current = false; }; }, []);\n const current = settled && 'answer' in settled ? settled.answer : sent;\n // `pending` means the question waits on the person; `writing` means the model is still generating it (options may be partial).\n const state = settled ? ('failure' in settled ? 'failed' : 'answered') : sent !== undefined ? 'sent' : live ? 'writing' : 'pending';\n const open = state === 'pending' || state === 'writing';\n\n async function submit(value: string) {\n const trimmed = value.trim();\n if (!answer || !questionId || live || !trimmed || sending !== undefined) return;\n setRefusal(undefined); setSending(trimmed);\n try {\n const outcome = await answer(questionId, trimmed);\n if (outcome.kind === 'answered') setSent(trimmed);\n else setRefusal(outcome.reason || labels.answerRefused(outcome.kind));\n } catch (cause) { setRefusal(cause instanceof Error ? cause.message : labels.answerNotSent); }\n finally { if (mounted.current) setSending(undefined); }\n }\n const onSubmit = (event: FormEvent) => { event.preventDefault(); void submit(text); };\n const busy = sending !== undefined || live;\n\n return <section data-testid=\"question-card\" data-state={state} data-call-id={call.id} aria-label={labels.question}\n className={cn('my-2 rounded-xl border bg-card p-4 text-card-foreground shadow-xs', open ? 'border-ring/50' : 'border-border')}>\n <div className=\"flex items-start gap-3\">\n <span className={cn('mt-0.5 flex size-7 shrink-0 items-center justify-center rounded-lg', open ? 'bg-primary text-primary-foreground' : 'bg-muted text-muted-foreground')}>\n {state === 'answered' || state === 'sent' ? <CheckIcon className=\"size-4\" aria-hidden=\"true\" /> : <MessageCircleQuestionIcon className=\"size-4\" aria-hidden=\"true\" />}\n </span>\n <div className=\"min-w-0 flex-1\">\n <p className=\"m-0 text-xs font-medium tracking-wider text-muted-foreground uppercase\">{open ? labels.questionForYou : state === 'failed' ? labels.notAnswered : labels.answered}</p>\n <p data-testid=\"question-text\" className=\"mt-1 mb-0 text-sm leading-6 font-medium [overflow-wrap:anywhere]\">{question.question || labels.askedQuestion}</p>\n\n {open && <>\n {question.options.length > 0 && <div role=\"group\" aria-label={labels.answerOptions} className=\"mt-3 flex flex-wrap gap-2\">\n {question.options.map(option => <Button key={option} variant=\"outline\" data-testid=\"question-option\" data-option={option} disabled={!answer || !questionId || busy}\n onClick={() => { void submit(option); }} className={cn('h-auto min-h-11 max-w-full py-1.5 whitespace-normal sm:min-h-9', sending === option && 'border-ring')}>{option}</Button>)}\n </div>}\n {question.allowFreeText && <form onSubmit={onSubmit} className=\"mt-3 flex gap-2\">\n <input data-testid=\"question-input\" value={text} maxLength={2000} disabled={!answer || !questionId || busy} placeholder={question.options.length ? labels.ownAnswer : labels.typeAnswer}\n aria-label={labels.yourAnswerInput} onChange={event => setText(event.currentTarget.value)}\n className=\"h-11 min-w-0 flex-1 rounded-lg border border-input bg-background px-3 text-base outline-none sm:h-9 sm:text-sm placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring/60 disabled:opacity-50\" />\n <Button type=\"submit\" variant=\"default\" data-testid=\"question-submit\" disabled={!answer || !questionId || busy || !text.trim()}><SendIcon className=\"size-3.5\" aria-hidden=\"true\" />{labels.answer}</Button>\n </form>}\n {live && <p className=\"mt-3 mb-0 text-xs text-muted-foreground\">{labels.stillWritingQuestion}</p>}\n {!answer && !live && <p className=\"mt-3 mb-0 text-xs text-muted-foreground\">{labels.answeringUnavailable}</p>}\n </>}\n\n {(state === 'answered' || state === 'sent') && current !== undefined && <p className=\"mt-2 mb-0 text-sm text-muted-foreground\">{labels.yourAnswer} <span data-testid=\"question-answer\" className=\"rounded-md bg-muted px-1.5 py-0.5 font-medium text-foreground [overflow-wrap:anywhere]\">{current}</span>\n {state === 'sent' && <span className=\"ms-2 text-xs\">{labels.waitingForAgent}</span>}</p>}\n {state === 'failed' && settled && 'failure' in settled && <p role=\"alert\" className=\"mt-2 mb-0 text-sm text-destructive\">{settled.failure}</p>}\n {refusal && open && <p role=\"alert\" data-testid=\"question-refusal\" className=\"mt-3 mb-0 rounded-md bg-destructive/10 px-3 py-2 text-sm text-destructive\">{refusal}</p>}\n </div>\n </div>\n </section>;\n}\n",
125
+ "type": "registry:component",
126
+ "target": "components/pi-chat/question-card.tsx"
127
+ },
128
+ {
129
+ "path": "registry/pi-chat/queue.tsx",
130
+ "content": "'use client';\n\nimport { useEffect, useRef, useState } from 'react';\nimport type { ChatDraft } from '@hachej/boring-ui-kit/native-chat';\nimport { CornerDownRightIcon, EllipsisIcon, ListEndIcon, LoaderIcon, PencilIcon, RouteIcon, Trash2Icon } from 'lucide-react';\nimport { isFileBlock, type QueuedMessage } from './rows';\nimport { defaultChatLabels, useChatText } from './labels';\n\nexport type { QueuedMessage } from './rows';\n\n/** Display text of a queued submission: the text parts of its content, plus a count of images. */\nexport function queuedText(item: QueuedMessage, imagesLabel: (count: number) => string = defaultChatLabels.images): string {\n const content = item.content as unknown;\n if (typeof content === 'string') return content;\n if (!Array.isArray(content)) return '';\n const parts = content as readonly { type?: unknown; text?: unknown }[];\n const text = parts.flatMap(part => part?.type === 'text' && typeof part.text === 'string' && !isFileBlock(part.text) ? [part.text] : []).join('\\n');\n const images = parts.filter(part => part?.type === 'image').length;\n return images ? `${text}${text ? '\\n' : ''}${imagesLabel(images)}` : text;\n}\n\n/** What a queued message can be taken back for. Both take the message out of the queue first and throw when it is too late. */\nexport interface QueueActions {\n /** Take it out of the queue and put its text (and images) back in the composer. */\n readonly edit?: ((item: QueuedMessage) => Promise<void>) | undefined;\n /** Take it out of the queue and send it into the running turn now. */\n readonly steer?: ((item: QueuedMessage) => Promise<void>) | undefined;\n}\n\nconst rowButton = 'inline-flex shrink-0 cursor-pointer items-center justify-center gap-1 rounded-lg text-muted-foreground outline-none transition-colors hover:bg-background/70 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/60 disabled:pointer-events-none disabled:opacity-45 motion-reduce:transition-none';\n\n/** The \"…\" button of one queued message: a small menu of the secondary actions (Edit). */\nfunction MoreMenu({ disabled, onEdit }: { readonly disabled: boolean; readonly onEdit: () => void }) {\n const { labels } = useChatText();\n const [open, setOpen] = useState(false);\n const root = useRef<HTMLDivElement>(null), trigger = useRef<HTMLButtonElement>(null);\n useEffect(() => {\n if (!open) return;\n const outside = (event: MouseEvent) => { if (root.current && !root.current.contains(event.target as Node)) setOpen(false); };\n const escape = (event: KeyboardEvent) => { if (event.key === 'Escape') { event.stopPropagation(); setOpen(false); trigger.current?.focus(); } };\n document.addEventListener('mousedown', outside); document.addEventListener('keydown', escape, true);\n return () => { document.removeEventListener('mousedown', outside); document.removeEventListener('keydown', escape, true); };\n }, [open]);\n return <div ref={root} className=\"relative shrink-0\">\n <button ref={trigger} type=\"button\" data-testid=\"queue-more\" aria-label={labels.moreActions} title={labels.more} aria-haspopup=\"menu\" aria-expanded={open} disabled={disabled} onClick={() => setOpen(value => !value)}\n className={`${rowButton} size-8 max-sm:size-10`}><EllipsisIcon className=\"size-4\" aria-hidden=\"true\" /></button>\n {open && <div role=\"menu\" data-testid=\"queue-menu\" className=\"absolute right-0 bottom-full z-30 mb-1 w-40 rounded-xl border border-border bg-popover p-1 text-popover-foreground shadow-lg\">\n <button type=\"button\" role=\"menuitem\" data-testid=\"queue-edit\" autoFocus onClick={() => { setOpen(false); onEdit(); }}\n className=\"flex min-h-9 w-full cursor-pointer items-center gap-2 rounded-md px-2.5 py-1.5 text-left text-sm text-foreground outline-none hover:bg-accent focus-visible:bg-accent max-sm:min-h-10\"><PencilIcon className=\"size-3.5 text-muted-foreground\" aria-hidden=\"true\" />{labels.edit}</button>\n </div>}\n </div>;\n}\n\n/**\n * Messages sent while the agent was working, waiting for Pi to place them, drawn as a slim tab tucked behind the top edge of the composer\n * (render it directly above `Composer`; the composer overlaps its bottom). One row per message: icon, text, Steer, remove and a \"…\" menu\n * (Edit). The choice is made here, per message, never in the composer. Rows leave on their own once Pi starts them. `sending` are messages\n * sent from the composer that wait for the previous send to be confirmed (the controller's `outbox`): shown last, without actions.\n */\nexport function MessageQueue({ items, sending = [], withdraw, actions }: {\n readonly items: readonly QueuedMessage[];\n readonly sending?: readonly ChatDraft[] | undefined;\n readonly withdraw?: ((id: QueuedMessage['id']) => Promise<unknown>) | undefined;\n readonly actions?: QueueActions | undefined;\n}) {\n const { labels } = useChatText();\n const [failed, setFailed] = useState<string | undefined>();\n const [busy, setBusy] = useState<ReadonlySet<string>>(new Set());\n if (!items.length && !sending.length) return null;\n async function run(item: QueuedMessage, work: () => Promise<unknown>) {\n const id = String(item.id);\n setFailed(undefined); setBusy(current => new Set(current).add(id));\n try { await work(); }\n catch (cause) { setFailed(cause instanceof Error ? cause.message : labels.queueFailed); }\n finally { setBusy(current => { const next = new Set(current); next.delete(id); return next; }); }\n }\n const remove = (item: QueuedMessage) => run(item, async () => {\n const outcome = await withdraw!(item.id);\n if (outcome === 'already_placed' || outcome === 'settled') throw new Error(labels.tooLateToRemove);\n });\n return <section data-testid=\"queue\" aria-label={labels.queuedMessages} className=\"relative mx-3 -mb-3 rounded-t-2xl border border-b-0 border-border bg-muted pb-3 text-foreground\">\n <ul className=\"m-0 list-none p-0\">\n {items.map((item, index) => {\n const working = busy.has(String(item.id));\n const steering = item.mode === 'steer';\n return <li key={String(item.id)} data-testid=\"queue-item\" data-mode={item.mode} className={`flex min-h-10 items-center gap-1.5 pr-1.5 pl-3 ${index > 0 ? 'border-t border-border/70' : ''}`}>\n {steering ? <RouteIcon className=\"size-4 shrink-0 text-muted-foreground\" aria-label={labels.steering} /> : <ListEndIcon className=\"size-4 shrink-0 text-muted-foreground\" aria-label={labels.queued} />}\n <span data-testid=\"queue-text\" className=\"min-w-0 flex-1 truncate px-1 text-sm\">{queuedText(item, labels.images)}</span>\n {!steering && actions?.steer && <button type=\"button\" data-testid=\"queue-steer\" title={labels.steerHint} disabled={working} onClick={() => { void run(item, () => actions.steer!(item)); }}\n className={`${rowButton} h-8 px-2 text-sm max-sm:h-10 max-sm:px-2.5`}><CornerDownRightIcon className=\"size-3.5\" aria-hidden=\"true\" />{labels.steer}</button>}\n {steering && <span className=\"shrink-0 px-1 text-xs text-muted-foreground\">{labels.steering}</span>}\n <button type=\"button\" data-testid=\"queue-cancel\" aria-label={labels.removeQueued} title={labels.removeHint} disabled={!withdraw || working} onClick={() => { void remove(item); }}\n className={`${rowButton} size-8 max-sm:size-10`}><Trash2Icon className=\"size-3.5\" aria-hidden=\"true\" /></button>\n {actions?.edit && <MoreMenu disabled={working} onEdit={() => { void run(item, () => actions.edit!(item)); }} />}\n </li>;\n })}\n {sending.map((draft, index) => <li key={`sending-${index}`} data-testid=\"queue-sending\" className={`flex min-h-10 items-center gap-1.5 pr-1.5 pl-3 ${items.length + index > 0 ? 'border-t border-border/70' : ''}`}>\n <LoaderIcon className=\"size-4 shrink-0 animate-spin text-muted-foreground motion-reduce:animate-none\" aria-label={labels.sending} />\n <span data-testid=\"queue-text\" className=\"min-w-0 flex-1 truncate px-1 text-sm\">{draft.text}{draft.attachments.length ? `${draft.text ? '\\n' : ''}${labels.images(draft.attachments.length)}` : ''}</span>\n <span className=\"shrink-0 px-1 text-xs text-muted-foreground\">{labels.sending}</span>\n </li>)}\n </ul>\n {failed && <p role=\"alert\" data-testid=\"queue-error\" className=\"m-0 border-t border-border/70 px-3 py-2 text-xs text-destructive\">{failed}</p>}\n </section>;\n}\n",
131
+ "type": "registry:component",
132
+ "target": "components/pi-chat/queue.tsx"
133
+ },
134
+ {
135
+ "path": "registry/pi-chat/rows.ts",
136
+ "content": "import type { ReactNode } from 'react';\nimport type { ConversationView, EntryRecord, InboxItem, JsonObject } from '@earendil-works/pi-durable';\nimport type { JsonValue } from '@earendil-works/chord';\nimport type { AssistantMessage, Message, ToolCall, ToolResultMessage, UserMessage } from '@earendil-works/pi-ai';\nimport type { ToolEntry, ToolStatus } from './tool';\nimport { ASK_USER_TOOL } from './question-card';\nimport { PRESENT_TOOL, artifactKey, detectArtifact, pendingId, pendingTitle } from './artifact';\nimport type { ArtifactDescriptor, ArtifactsConfig } from './artifact';\n\n/** The host adds file content for `@path` mentions as parts that start like this; the message already shows the mention itself. */\nexport const isFileBlock = (text: string): boolean => text.startsWith('<file path=\"');\n\n/** A submission waiting in the native inbox (steer or follow-up); `queuedMessages` reads them from the view, the queue renders them. */\nexport type QueuedMessage = Extract<InboxItem, { readonly mode: 'steer' | 'followUp' }>;\n\n/*\n * The one message model is the native Pi view: entries (with their model messages) plus the live `pi.live` document.\n * This module turns a view into display rows with these semantics: tool calls are matched with tool results, expert mode hides successful tool details, the live\n * generation is appended as a streaming row whose key matches the row its committed message will take.\n */\n/** `required` pins the card above the transcript. `inline` (tool cards) keeps it in place in expert mode too, like the\n * question and artifact cards; other custom tool cards show only in developer mode or on failure. */\nexport interface ChatCard { readonly content: ReactNode; readonly required?: boolean; readonly inline?: boolean }\nexport type Mode = 'expert' | 'developer';\nexport type StreamPart = { readonly type: 'text'; readonly text: string } | { readonly type: 'thinking'; readonly thinking: string } | ToolCall;\n\nexport type Part =\n | { readonly kind: 'text'; readonly key: string; readonly text: string }\n | { readonly kind: 'thinking'; readonly key: string; readonly text: string; readonly streaming: boolean }\n | { readonly kind: 'question'; readonly key: string; readonly call: ToolCall; readonly result: ToolResultMessage | undefined; readonly live: boolean; readonly questionId: string | undefined }\n | { readonly kind: 'approval'; readonly key: string; readonly call: ToolCall; readonly result: ToolResultMessage | undefined; readonly live: boolean; /** The bound question ID the answer must use (as for `question`). */ readonly questionId: string | undefined; /** The one-line summary `requireApproval` published for this call. */ readonly summary: string; /** The decision it recorded, once made. */ readonly decision?: ApprovalDecision; /** The call's own step, shown in the activity block once it has a result. */ readonly entry?: ToolEntry }\n | { readonly kind: 'artifact'; readonly key: string; readonly call: ToolCall; readonly state: 'presenting' | 'ready'; readonly artifact: ArtifactDescriptor | undefined; readonly title: string | undefined; /** Set when the host's `detect` found the descriptor: the call stays a step of the activity block too. */ readonly entry?: ToolEntry }\n | { readonly kind: 'tool'; readonly key: string; readonly entry: ToolEntry };\n\nexport type Row =\n | { readonly key: string; readonly type: 'user'; readonly message: UserMessage }\n | { readonly key: string; readonly type: 'assistant'; readonly parts: readonly Part[]; readonly streaming: boolean; /** The turn is still running (the last row while a run is active). */ readonly active?: boolean; readonly stopReason?: AssistantMessage['stopReason']; readonly errorMessage?: string; readonly text: string; /** When the reply was written (the last round of a merged turn), in ms. Absent while it streams. */ readonly timestamp?: number; /** The model that wrote the last round of the reply. */ readonly model?: { readonly provider: string; readonly modelId: string }; /** How long the last round took to answer, in ms (Pi's `durationMs`). */ readonly durationMs?: number; /** The native entry of its last committed round: where a fork of the conversation after this reply starts. */ readonly entryId?: string }\n | { readonly key: string; readonly type: 'orphan-result'; readonly message: ToolResultMessage }\n | { readonly key: string; readonly type: 'system'; readonly text: string }\n | { readonly key: string; readonly type: 'event'; readonly label: string }\n | { readonly key: string; readonly type: 'card'; readonly card: ChatCard };\n\nexport function object(value: JsonValue | undefined): JsonObject | undefined {\n return value !== null && typeof value === 'object' && !Array.isArray(value) ? value : undefined;\n}\nexport function streamParts(value: JsonValue | undefined): StreamPart[] {\n if (!Array.isArray(value)) return [];\n return value.flatMap((item): StreamPart[] => {\n const part = object(item);\n if (part?.['type'] === 'text' && typeof part['text'] === 'string') return [{ type: 'text', text: part['text'] }];\n if (part?.['type'] === 'thinking' && typeof part['thinking'] === 'string') return [{ type: 'thinking', thinking: part['thinking'] }];\n const args = object(part?.['arguments']);\n if (part?.['type'] === 'toolCall' && typeof part['id'] === 'string' && typeof part['name'] === 'string' && args) return [{ type: 'toolCall', id: part['id'], name: part['name'], arguments: args }];\n return [];\n });\n}\n\nexport function queuedMessages(view: ConversationView | undefined): QueuedMessage[] {\n const items = object(view?.docs['pi.inbox'])?.['items'];\n if (!Array.isArray(items)) return [];\n return items.filter((item): item is QueuedMessage => {\n const value = object(item as JsonValue);\n return value !== undefined && (value['mode'] === 'steer' || value['mode'] === 'followUp') && value['id'] !== undefined;\n });\n}\n\nexport interface Derived {\n readonly rows: readonly Row[];\n /** Required entry and tool cards: pinned above the transcript. */\n readonly pinned: readonly { readonly key: string; readonly content: ReactNode }[];\n readonly run: JsonObject | undefined;\n readonly retry: JsonObject | undefined;\n readonly compacting: boolean;\n}\nexport interface DeriveOptions {\n readonly mode: Mode;\n readonly renderEntry: ((entry: EntryRecord) => ChatCard | undefined) | undefined;\n readonly renderTool: ((call: ToolCall, result: ToolResultMessage | undefined) => ChatCard | undefined) | undefined;\n readonly groupTool: ((call: ToolCall, result: ToolResultMessage) => boolean) | undefined;\n /** Turn artifact tool results into cards (`detect` recognises descriptors the tool result does not carry itself). */\n readonly artifacts?: { readonly detect?: ArtifactsConfig['detect'] | undefined } | undefined;\n}\n\n/** Key of `{ summary, decision? }` in a gated call's details: `APPROVAL_DETAILS` of `@hachej/boring-agent/approval` (a contract test keeps them equal). */\nexport const APPROVAL_DETAILS = 'boring.approval';\nexport type ApprovalDecision = 'approved' | 'denied' | 'cancelled';\n/** The approval record a gated call publishes: its summary and, once made, the decision (`approved`, `denied` or `cancelled`). */\nconst approvalRecord = (details: unknown): { summary: string; decision?: ApprovalDecision } | undefined => {\n const record = object(object(details as JsonValue | undefined)?.[APPROVAL_DETAILS]);\n const summary = record?.['summary'], decision = record?.['decision'];\n if (typeof summary !== 'string' || !summary.trim()) return undefined;\n return { summary: summary.trim(), ...(decision === 'approved' || decision === 'denied' || decision === 'cancelled' ? { decision } : {}) };\n};\n\nconst textOf = (message: Message): string => message.role === 'assistant' ? message.content.flatMap(part => part.type === 'text' ? [part.text] : []).join('\\n') : '';\n\nexport function derive(view: ConversationView | undefined, options: DeriveOptions): Derived {\n const { mode, renderEntry, renderTool } = options;\n const developer = mode === 'developer';\n const live = object(view?.docs['pi.live']);\n const run = object(live?.['run']), generation = object(live?.['generation']);\n const liveMessage = object(generation?.['message']), retry = object(generation?.['retry']);\n const taskId = run?.['taskId'];\n\n // Pass 1: match each result to its preceding invocation. Model call IDs may be reused.\n type Item = { readonly key: string; readonly entry: EntryRecord; readonly message?: Message; readonly card?: ChatCard };\n const items: Item[] = [], results = new Map<ToolCall, ToolResultMessage>(), counts = new Map<number, number>(), questionIds = new Map<ToolCall, string>();\n const pendingCalls = new Map<string, ToolCall>();\n for (const entry of view?.entries ?? []) {\n const custom = renderEntry?.(entry);\n const card = custom && (developer || custom.required) ? custom : undefined;\n if (card) items.push({ key: `entry:${entry.id}`, entry, card });\n if (!entry.model?.length) { if (!card && developer) items.push({ key: `entry:${entry.id}`, entry }); continue; }\n for (const [index, message] of entry.model.entries()) {\n if (message.role === 'assistant') for (const part of message.content) if (part.type === 'toolCall') { pendingCalls.set(part.id, part); questionIds.set(part, JSON.stringify([entry.id, part.id])); }\n if (message.role === 'toolResult') {\n const call = pendingCalls.get(message.toolCallId);\n if (call) { results.set(call, message); pendingCalls.delete(message.toolCallId); }\n }\n let key = `entry:${entry.id}:${index}`;\n if (message.role === 'assistant' && entry.byTaskId !== undefined) {\n const ordinal = counts.get(entry.byTaskId) ?? 0; counts.set(entry.byTaskId, ordinal + 1);\n key = `assistant:${entry.byTaskId}:${ordinal}`;\n }\n if (!card) items.push({ key, entry, message });\n }\n }\n const matched = new Set(results.values());\n\n const pinned: { key: string; content: ReactNode }[] = [];\n for (const item of items) if (item.card?.required) pinned.push({ key: item.key, content: item.card.content });\n\n const status = (result: ToolResultMessage | undefined): ToolStatus => result ? (result.isError ? 'failed' : 'completed') : run ? 'running' : 'unfinished';\n function toolPart(call: ToolCall, key: string, committed: boolean): Part | undefined {\n const result = results.get(call);\n if (call.name === ASK_USER_TOOL) return { kind: 'question', key, call, result, live: !committed, questionId: questionIds.get(call) };\n // A call gated by `requireApproval` identifies itself: it publishes its summary under APPROVAL_DETAILS before it asks.\n const record = approvalRecord(result ? result.details : (Array.isArray(live?.['tools']) ? live['tools'] : []).map(object).find(slot => slot?.['callId'] === call.id)?.['details']);\n if (record) return { kind: 'approval', key, call, result, live: !committed, questionId: questionIds.get(call), summary: record.summary, ...(record.decision ? { decision: record.decision } : {}), ...(result ? { entry: { key: `${key}:step`, call, result, status: status(result) } } : {}) };\n if (options.artifacts) {\n // A finished call that carries a descriptor becomes a card; a running `present` shows an \"opening\" card. A failed call stays an ordinary (failed) tool step.\n const artifact = result ? detectArtifact(call, result, options.artifacts.detect) : undefined;\n if (artifact) {\n // A tool whose own result carries the descriptor is replaced by its card; a host-detected card is shown in addition to the step.\n const own = result && detectArtifact(call, result);\n return { kind: 'artifact', key, call, state: 'ready', artifact, title: artifact.title, ...(own ? {} : { entry: { key, call, result, status: status(result) } }) };\n }\n if (!result && run && call.name === PRESENT_TOOL) {\n return { kind: 'artifact', key, call, state: 'presenting', artifact: undefined, title: pendingTitle(call) };\n }\n }\n const custom = committed ? renderTool?.(call, result) : undefined;\n if (custom?.required) { pinned.push({ key, content: custom.content }); return undefined; }\n if (custom && (developer || result?.isError || custom.inline)) return { kind: 'tool', key, entry: { key, call, result, status: status(result), custom: custom.content } };\n // A host that folds only some calls (`groupTool`) keeps the rest as cards, which expert mode hides unless they failed.\n if (!developer && !result?.isError && options.groupTool && !(result && safe(options.groupTool, { key, call, result, status: status(result) }))) return undefined;\n return { kind: 'tool', key, entry: { key, call, result, status: status(result) } };\n }\n function partsOf(content: readonly StreamPart[], rowKey: string, streaming: boolean, committed: boolean): Part[] {\n const parts: Part[] = [];\n for (const [index, part] of content.entries()) {\n if (part.type === 'text') { if (part.text.length) parts.push({ kind: 'text', key: `${rowKey}:text:${index}`, text: part.text }); }\n else if (part.type === 'thinking') { if (developer && part.thinking.length) parts.push({ kind: 'thinking', key: `${rowKey}:thinking:${index}`, text: part.thinking, streaming: streaming && index === content.length - 1 }); }\n else { const made = toolPart(part, `${rowKey}:tool:${index}`, committed); if ((made?.kind === 'artifact' || made?.kind === 'approval') && made.entry) parts.push({ kind: 'tool', key: `${made.key}:step`, entry: made.entry }); if (made) parts.push(made); }\n }\n return parts;\n }\n\n // Pass 2: rows.\n const rows: Row[] = [];\n for (const item of items) {\n if (item.card) { if (!item.card.required) rows.push({ key: item.key, type: 'card', card: item.card }); continue; }\n const message = item.message;\n if (!message) { if (developer) rows.push({ key: item.key, type: 'event', label: item.entry.kind }); continue; }\n if (message.role === 'system') {\n if (developer) rows.push({ key: item.key, type: 'system', text: typeof message.content === 'string' ? message.content : message.content.map(part => part.text).join('\\n') });\n } else if (message.role === 'toolResult') {\n // A result with its call is shown on the call's card. Only an unmatched failure gets its own row.\n if (message.isError && !matched.has(message)) rows.push({ key: item.key, type: 'orphan-result', message });\n } else if (message.role === 'user') rows.push({ key: item.key, type: 'user', message });\n else {\n const parts = partsOf(message.content, item.key, false, true);\n const interrupted = message.stopReason === 'error' || message.stopReason === 'aborted';\n if (parts.length || interrupted) rows.push({ key: item.key, type: 'assistant', parts, streaming: false, stopReason: message.stopReason, ...(message.errorMessage ? { errorMessage: message.errorMessage } : {}), text: textOf(message), ...replyMeta(message), entryId: String(item.entry.id) });\n else {\n // A final round with nothing to show adds no content, but it is still the round that ended the reply: its model, time and entry replace the earlier round's.\n const previous = rows[rows.length - 1];\n if (previous?.type === 'assistant' && !previous.stopReason?.match(/^(error|aborted)$/)) {\n const { timestamp: _t, model: _m, durationMs: _d, ...rest } = previous;\n rows[rows.length - 1] = { ...rest, ...replyMeta(message), entryId: String(item.entry.id) };\n }\n }\n }\n }\n if (typeof taskId === 'number' && liveMessage) {\n const key = `assistant:${taskId}:${counts.get(taskId) ?? 0}`, content = streamParts(liveMessage['content']);\n rows.push({ key, type: 'assistant', parts: partsOf(content, key, true, false), streaming: true, text: '' });\n }\n const merged = mergeTurns(rows).map(row => row.type === 'assistant' && options.artifacts ? { ...row, parts: oneCardPerArtifact(row.parts) } : row);\n const last = merged[merged.length - 1];\n if (run && last?.type === 'assistant') merged[merged.length - 1] = { ...last, active: true };\n return { rows: merged, pinned, run, retry, compacting: Array.isArray(live?.['compactions']) && live['compactions'].length > 0 };\n}\n\n/** What a reply reports about the model round that wrote it, read from Pi's own message (each field only when it is there). */\nexport function replyMeta(message: AssistantMessage): { readonly timestamp?: number; readonly model?: { readonly provider: string; readonly modelId: string }; readonly durationMs?: number } {\n return {\n ...(typeof message.timestamp === 'number' ? { timestamp: message.timestamp } : {}),\n ...(typeof message.provider === 'string' && typeof message.model === 'string' ? { model: { provider: message.provider, modelId: message.model } } : {}),\n ...(typeof message.durationMs === 'number' ? { durationMs: message.durationMs } : {}),\n };\n}\n\n/**\n * Pi commits one assistant message per model round, so a turn with tool use is several messages in a row.\n * They read as one answer: merge consecutive assistant rows (unless one ended in an error or stop) so tool calls\n * group across rounds and the turn has a single copy action. The first row's key is kept, so identity is stable.\n */\nfunction mergeTurns(rows: readonly Row[]): Row[] {\n const out: Row[] = [];\n for (const row of rows) {\n const last = out[out.length - 1];\n if (last?.type === 'assistant' && row.type === 'assistant' && !last.stopReason?.match(/^(error|aborted)$/)) {\n out[out.length - 1] = { key: last.key, type: 'assistant', parts: [...last.parts, ...row.parts], streaming: row.streaming,\n ...(row.stopReason ? { stopReason: row.stopReason } : {}), ...(row.errorMessage ? { errorMessage: row.errorMessage } : {}),\n text: [last.text, row.text].filter(Boolean).join('\\n\\n'), ...(row.timestamp !== undefined ? { timestamp: row.timestamp } : {}), ...(row.model ? { model: row.model } : {}), ...(row.durationMs !== undefined ? { durationMs: row.durationMs } : {}),\n ...(row.entryId !== undefined ? { entryId: row.entryId } : last.entryId !== undefined ? { entryId: last.entryId } : {}) };\n } else out.push(row);\n }\n return out;\n}\n\n/**\n * A turn that revises an artifact several times shows one card for it: the last version, at the place of the last step.\n * A running `present` of a file already shown takes over the title of its card.\n */\nfunction oneCardPerArtifact(parts: readonly Part[]): Part[] {\n const idOf = (part: Part) => part.kind === 'artifact' ? part.artifact ? artifactKey(part.artifact) : (part.state === 'presenting' ? pendingId(part.call) : undefined) : undefined;\n const last = new Map<string, number>();\n for (const [index, part] of parts.entries()) { const id = idOf(part); if (id !== undefined) last.set(id, index); }\n const out: Part[] = [];\n for (const [index, part] of parts.entries()) {\n const id = idOf(part);\n if (id === undefined || last.get(id) === index) {\n if (part.kind === 'artifact' && part.artifact === undefined && part.title === undefined && id !== undefined) {\n const earlier = parts.find(other => other.kind === 'artifact' && other.artifact !== undefined && artifactKey(other.artifact) === id);\n if (earlier?.kind === 'artifact') { out.push({ ...part, title: earlier.title }); continue; }\n }\n out.push(part);\n }\n }\n return out;\n}\n\n/** One step of an activity block: a default tool call or a stretch of reasoning. */\nexport type Step = { readonly kind: 'tool'; readonly key: string; readonly entry: ToolEntry }\n | { readonly kind: 'thinking'; readonly key: string; readonly text: string; readonly streaming: boolean };\n/** An assistant turn is text parts and activity blocks: one block per uninterrupted run of steps. */\nexport type Segment = { readonly kind: 'part'; readonly part: Part } | { readonly kind: 'activity'; readonly key: string; readonly steps: readonly Step[] };\nexport function segments(parts: readonly Part[], groupTool: DeriveOptions['groupTool']): Segment[] {\n const out: Segment[] = [];\n let run: Step[] = [];\n const flush = () => {\n const first = run[0];\n if (first) out.push({ kind: 'activity', key: `activity:${first.key}`, steps: run });\n run = [];\n };\n for (const part of parts) {\n if (part.kind === 'thinking') run.push({ kind: 'thinking', key: part.key, text: part.text, streaming: part.streaming });\n else if (part.kind === 'tool' && !part.entry.custom && (!groupTool || safe(groupTool, part.entry))) run.push({ kind: 'tool', key: part.key, entry: part.entry });\n else { flush(); out.push({ kind: 'part', part }); }\n }\n flush();\n return out;\n}\nfunction safe(groupTool: NonNullable<DeriveOptions['groupTool']>, entry: ToolEntry): boolean {\n try { return entry.result !== undefined && !entry.result.isError && groupTool(entry.call, entry.result) === true; } catch { return false; }\n}\n",
137
+ "type": "registry:lib",
138
+ "target": "components/pi-chat/rows.ts"
139
+ },
140
+ {
141
+ "path": "registry/pi-chat/session.tsx",
142
+ "content": "'use client';\n\nimport { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';\nimport type { KeyboardEvent, ReactNode } from 'react';\nimport type { EntryRecord } from '@earendil-works/pi-durable';\nimport type { ImageContent, ToolCall, ToolResultMessage } from '@earendil-works/pi-ai';\nimport type { ChatAttachment, NativeChatController } from '@hachej/boring-ui-kit/native-chat';\nimport { useStickToBottom } from 'use-stick-to-bottom';\nimport type { ComposerFeedback, PendingUpload } from './composer';\nimport type { AttachmentsConfig, EffortConfig, MentionsConfig, ModelConfig, ModelRef, SlashConfig } from './config';\nimport { mentionToken } from './config';\nimport { ModelEffortPicker } from './pickers';\nimport type { CommandMentions } from './markdown';\nimport type { RowContext } from './message';\nimport type { QueueActions, QueuedMessage } from './queue';\nimport type { AnswerOutcome } from './question-card';\nimport type { ArtifactsConfig } from './artifact';\nimport { derive, isFileBlock, object, queuedMessages } from './rows';\nimport type { ChatCard, Mode } from './rows';\nimport { useChatText } from './labels';\nimport type { BlockAction } from '../button/actions';\nimport type { ReplyRef } from './config';\n\n/** What the host lets the person do beyond typing. Pass `remote.answer` and `remote.withdraw` from `createRemoteChat()`. */\nexport interface PiChatActions {\n /** Resolve a pending `ask_user` question. Without it, question cards are read-only. */\n readonly answer?: (questionId: string, answer: string) => Promise<AnswerOutcome>;\n /** Withdraw a queued message before Pi places it. Without it, queued messages cannot be cancelled. */\n readonly withdraw?: (id: QueuedMessage['id']) => Promise<unknown>;\n}\n\n/** The props `PiChat` and `AmbientChat` both take and hand to `useChatSession`. */\nexport interface ChatFeatureProps {\n /** `expert` hides successful tool details and reasoning; `developer` shows everything. */\n readonly mode?: Mode;\n readonly actions?: PiChatActions;\n readonly renderEntry?: (entry: EntryRecord) => ChatCard | undefined;\n readonly renderTool?: (call: ToolCall, result: ToolResultMessage | undefined) => ChatCard | undefined;\n readonly groupTool?: (call: ToolCall, result: ToolResultMessage) => boolean;\n readonly commandMentions?: CommandMentions;\n readonly onOpenImage?: (image: ImageContent) => void;\n readonly onCopy?: (text: string) => Promise<void>;\n readonly onComposerKeyDown?: (event: KeyboardEvent<HTMLTextAreaElement>) => void;\n readonly fileAccept?: string;\n /** `/` menu of host commands and skills. Omit it and `/` is just text. */\n readonly slash?: SlashConfig;\n /** `@` workspace file mentions: a picker, composer chips and styled mentions in sent messages. */\n readonly mentions?: MentionsConfig;\n /** Attach button, paste and drop through the host's upload. Takes the place of `onFiles` and `fileAccept`. */\n readonly attachments?: AttachmentsConfig;\n /** Model picker in the composer bar. The current model comes from the view's `pi.agent` document. */\n readonly model?: ModelConfig;\n /** Thinking level picker in the composer bar. The current level comes from the view's `pi.agent` document. */\n readonly effort?: EffortConfig;\n /** Artifact cards: tool results that carry a descriptor become a card that opens the artifact in the host's panel. Omit it and nothing changes. */\n readonly artifacts?: ArtifactsConfig;\n /**\n * Host actions under each settled reply, beside Copy (and Fork): `header` ones as buttons, `menu` ones in a \"…\" menu. Test ids\n * `reply-action-<id>`, the menu `reply-action-more`.\n */\n readonly messageActions?: ((reply: ReplyRef) => readonly BlockAction[]) | undefined;\n /** A line under each settled reply (for example the model that answered and the time it took), for the host to show to some people only. */\n readonly replyFooter?: ((reply: ReplyRef) => ReactNode) | undefined;\n}\n\n\nexport type FilesHandler = (files: readonly File[], target: Pick<ReturnType<NativeChatController['getSnapshot']>, 'identity' | 'conversationId'> & { readonly signal: AbortSignal }) => Promise<readonly ChatAttachment[]>;\n\n/** The chat behaviour every surface over a `NativeChatController` shares (`PiChat`, `AmbientChat`): sending, queue actions, uploads, pickers, rows. */\nexport interface ChatSessionOptions extends Readonly<{ [Key in keyof ChatFeatureProps]: ChatFeatureProps[Key] | undefined }> {\n readonly controller: NativeChatController;\n /** The controller the host currently passes; a surface that outlives its controller stops acting on the old one. */\n readonly activeController: { readonly current: NativeChatController };\n readonly mode: Mode;\n readonly fileAccept: string;\n readonly onFiles?: FilesHandler | undefined;\n /** Runs after a message was accepted for sending (for example to scroll to the bottom). */\n readonly afterSend?: (() => void) | undefined;\n /** Extra attributes of the row context a surface needs (for example per-reply actions). */\n readonly rowExtras?: Partial<RowContext> | undefined;\n /** The optional Feedback button: when feedback is pending, Send attaches it to the message first. */\n readonly feedback?: ComposerFeedback | undefined;\n}\n\nexport function useChatSession(options: ChatSessionOptions) {\n const { controller, activeController: active, mode, actions, renderEntry, renderTool, groupTool, commandMentions, onOpenImage, onCopy, onComposerKeyDown, onFiles, fileAccept,\n slash, mentions, attachments, model, effort, artifacts, messageActions, replyFooter, afterSend, rowExtras, feedback } = options;\n const { labels } = useChatText();\n const state = useSyncExternalStore(controller.subscribe, controller.getSnapshot, controller.getSnapshot);\n const [error, setError] = useState<string | null>(null);\n const [uploading, setUploading] = useState(0);\n const [picked, setPicked] = useState<readonly string[]>([]);\n const [pending, setPending] = useState<readonly PendingUpload[]>([]);\n const [changing, setChanging] = useState<'model' | 'effort' | null>(null);\n const [changeError, setChangeError] = useState<string | null>(null);\n const [optimistic, setOptimistic] = useState<{ readonly model?: ModelRef; readonly effort?: string }>({});\n const uploadIds = useRef(0);\n const uploads = useRef(new Set<AbortController>()), mounted = useRef(false);\n const textarea = useRef<HTMLTextAreaElement | null>(null);\n const current = () => mounted.current && active.current === controller && !controller.getSnapshot().disposed;\n useEffect(() => {\n mounted.current = true;\n // A controller disposed before mount throws synchronously; the chat then renders its disposed state.\n if (!controller.getSnapshot().disposed) void controller.connect().catch(cause => { if (current()) setError(cause instanceof Error ? cause.message : labels.connectionFailed); });\n return () => { mounted.current = false; for (const upload of uploads.current) upload.abort(); uploads.current.clear(); };\n }, [controller]);\n\n const developer = mode === 'developer';\n // Only the recogniser takes part in deriving rows; which card is open changes without rebuilding them.\n const artifactDetect = useMemo(() => artifacts ? { detect: artifacts.detect } : undefined, [Boolean(artifacts), artifacts?.detect]); // eslint-disable-line react-hooks/exhaustive-deps\n const derived = useMemo(() => derive(state.view, { mode, renderEntry, renderTool, groupTool, artifacts: artifactDetect }), [state.view, mode, renderEntry, renderTool, groupTool, artifactDetect]);\n const queued = useMemo(() => queuedMessages(state.view), [state.view]);\n const { rows, run } = derived;\n\n const report = (cause: unknown) => { if (current()) setError(cause instanceof Error ? cause.message : labels.actionFailedShort); };\n const act = (action: () => Promise<unknown>) => {\n setError(null);\n try { void action().catch(report); } catch (cause) { report(cause); }\n };\n // A send being confirmed does not block the next one: the controller empties the composer at once and queues the next message behind it.\n // Only a submission whose outcome is unknown blocks, until it is checked or retried.\n const unconfirmed = state.send.kind === 'unknown';\n const connected = state.connection.kind === 'connected';\n const sendBlocked = uploading > 0 || state.disposed || !connected || unconfirmed;\n /** Puts a message back into the composer ahead of whatever is there now (nothing is dropped). */\n const putBack = (text: string, images: readonly ChatAttachment[]) => {\n if (controller.getSnapshot().disposed) return;\n const draft = controller.getSnapshot().draft;\n controller.setText([text, draft.text].filter(value => value.trim()).join('\\n'));\n if (images.length) controller.setAttachments([...images, ...draft.attachments.filter(item => !images.some(image => image.id === item.id))]);\n };\n const working = Boolean(run);\n const waitingForAnswer = rows.some(row => row.type === 'assistant' && row.parts.some(part => (part.kind === 'question' || part.kind === 'approval') && !part.live && !part.result));\n const send = () => {\n if (sendBlocked || !current()) return;\n const attach = feedback?.pending ? feedback.attach : undefined;\n if (attach) {\n // The pending feedback goes with this message: the host attaches it to the text, then the native send reads the draft.\n act(async () => {\n // Like any send, the composer empties at once; the person's own text comes back if the feedback or the message is refused.\n const typed = controller.getSnapshot().draft;\n controller.setText(''); controller.setAttachments([]);\n let attached: Awaited<ReturnType<typeof attach>>;\n try { attached = await attach(typed.text); }\n catch (cause) { putBack(typed.text, typed.attachments); throw cause; }\n if (attached.kind === 'refused') { putBack(typed.text, typed.attachments); throw new Error(attached.reason); }\n if (!current()) { putBack(typed.text, typed.attachments); return; }\n const submission = await controller.send('followUp', { text: attached.text, attachments: typed.attachments, restore: { text: typed.text, attachments: typed.attachments } });\n if (submission) feedback?.sent?.();\n });\n afterSend?.();\n textarea.current?.focus();\n return;\n }\n act(() => controller.send('followUp'));\n afterSend?.();\n textarea.current?.focus();\n };\n // A queued message is taken back (withdrawn) before it is edited or steered; if Pi already placed it, that is reported and nothing is lost.\n async function takeBack(item: QueuedMessage) {\n if (!actions?.withdraw) throw new Error(labels.queueLocked);\n const outcome = await actions.withdraw(item.id);\n if (outcome === 'already_placed' || outcome === 'settled') throw new Error(labels.tooLate);\n }\n const queuedContent = (item: QueuedMessage) => {\n const parts = Array.isArray(item.content) ? item.content as readonly { type?: unknown; text?: unknown; data?: unknown; mimeType?: unknown }[] : [];\n const text = typeof item.content === 'string' ? item.content : parts.flatMap(part => part?.type === 'text' && typeof part.text === 'string' && !isFileBlock(part.text) ? [part.text] : []).join('\\n');\n const images: ChatAttachment[] = parts.flatMap((part, index) => part?.type === 'image' && typeof part.data === 'string' && typeof part.mimeType === 'string'\n ? [{ id: `queued-${String(item.id)}-${index}`, name: `image-${index + 1}`, content: { type: 'image' as const, data: part.data, mimeType: part.mimeType } }] : []);\n return { text, images };\n };\n const queueActions: QueueActions | undefined = actions?.withdraw ? {\n edit: async item => {\n await takeBack(item);\n const { text, images } = queuedContent(item), draft = controller.getSnapshot().draft;\n controller.setText(draft.text.trim() ? `${text}\\n${draft.text}` : text);\n if (images.length) controller.setAttachments([...draft.attachments, ...images]);\n textarea.current?.focus();\n },\n steer: async item => {\n if (sendBlocked) throw new Error(labels.waitToSteer);\n await takeBack(item);\n const { text, images } = queuedContent(item);\n // Sent as explicit content, so the person's own draft is never touched; a refused steer comes back into the composer (the controller\n // puts it back), an unknown one is held for checking.\n try {\n const submission = await controller.send('steer', { text, attachments: images });\n if (!submission && current() && controller.getSnapshot().send.kind === 'blocked') setError(labels.steerRefused);\n } catch (cause) { putBack(text, images); if (current()) setError(cause instanceof Error ? cause.message : labels.steerFailed); }\n },\n } : undefined;\n const addMentions = (paths: readonly string[]) => {\n const text = controller.getSnapshot().draft.text;\n controller.setText(`${text}${text && !/\\s$/.test(text) ? ' ' : ''}${paths.map(mentionToken).join(' ')} `);\n setPicked(value => [...new Set([...value, ...paths])]);\n };\n async function upload(files: readonly File[]) {\n if ((!onFiles && !attachments) || !files.length || !current()) return;\n const abort = new AbortController(); uploads.current.add(abort); setUploading(value => value + 1);\n const ids = files.map(() => `upload-${++uploadIds.current}`);\n const settle = (failure?: string) => setPending(items => failure === undefined ? items.filter(item => !ids.includes(item.id))\n : items.map(item => ids.includes(item.id) ? { ...item, state: 'failed', error: failure } : item));\n setPending(items => [...items, ...files.map((file, index): PendingUpload => ({ id: ids[index]!, name: file.name, state: 'uploading' }))]);\n try {\n let added: readonly ChatAttachment[] = [];\n let paths: string[] = [];\n if (attachments) {\n for (const result of await attachments.upload([...files], abort.signal)) {\n if (result.image) added = [...added, { id: `image-${Date.now()}-${++uploadIds.current}`, name: result.name, content: { type: 'image', data: result.image.data, mimeType: result.image.mimeType } }];\n else if (result.path) paths = [...paths, result.path];\n }\n } else added = await onFiles!(files, { identity: state.identity, conversationId: state.conversationId, signal: abort.signal });\n if (current() && !abort.signal.aborted) {\n if (added.length) controller.setAttachments([...controller.getSnapshot().draft.attachments, ...added]);\n if (paths.length) addMentions(paths);\n settle();\n }\n } catch (cause) { if (!abort.signal.aborted) { settle(cause instanceof Error ? cause.message : labels.uploadFailedShort); if (!attachments) report(cause); } }\n finally { uploads.current.delete(abort); if (current()) setUploading(value => value - 1); }\n }\n const agentDoc = object(state.view?.docs['pi.agent']);\n const currentModel = object(agentDoc?.['model']);\n const viewModel: ModelRef | undefined = typeof currentModel?.['provider'] === 'string' && typeof currentModel['modelId'] === 'string' ? { provider: currentModel['provider'], modelId: currentModel['modelId'] } : undefined;\n const viewEffort = typeof agentDoc?.['thinkingLevel'] === 'string' ? agentDoc['thinkingLevel'] : undefined;\n // Show the accepted choice until the watch delivers it, so the label does not flicker back.\n useEffect(() => {\n const same = optimistic.model && viewModel && optimistic.model.provider === viewModel.provider && optimistic.model.modelId === viewModel.modelId;\n if (same || (optimistic.effort !== undefined && optimistic.effort === viewEffort)) setOptimistic(value => ({ ...(same ? {} : value.model ? { model: value.model } : {}), ...(optimistic.effort === viewEffort ? {} : value.effort ? { effort: value.effort } : {}) }));\n }, [optimistic, viewModel?.provider, viewModel?.modelId, viewEffort]);\n useEffect(() => { if (!state.draft.text) setPicked(value => value.length ? [] : value); }, [state.draft.text]);\n async function change(kind: 'model' | 'effort', apply: () => Promise<void>, accepted: () => void, rejected: () => void) {\n if (changing || !current()) return;\n setChanging(kind); setChangeError(null);\n try { await apply(); if (current()) accepted(); }\n catch (cause) { if (current()) { rejected(); setChangeError(cause instanceof Error && cause.message ? cause.message : labels.changeRefused); } }\n finally { if (current()) setChanging(null); }\n }\n const activateMention = (command: { readonly name: string; readonly behavior: 'execute' | 'insert' }) => {\n if (!current() || controller.getSnapshot().connection.kind !== 'connected') return;\n const catalog = commandMentions;\n const selected = catalog?.commands.find(item => item.name === command.name && item.behavior === command.behavior);\n if (catalog && selected) act(async () => catalog.onActivate({ name: selected.name, behavior: selected.behavior }));\n };\n const rowContext = useMemo<RowContext>(() => ({\n developer, groupTool, onOpenImage, onCopy,\n commandMentions: commandMentions ? { commands: commandMentions.commands, onActivate: activateMention } : undefined,\n answer: actions?.answer,\n artifacts: artifacts ? { open: artifacts.open, isOpen: artifacts.isOpen } : undefined,\n messageActions,\n replyFooter,\n pieces: slash?.skills?.length || mentions ? { mentions: Boolean(mentions), skills: (slash?.skills ?? []).map(skill => skill.name), openMention: mentions?.open, renderMention: mentions?.render } : undefined,\n ...rowExtras,\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }), [developer, groupTool, onOpenImage, onCopy, commandMentions, actions?.answer, slash?.skills, mentions, mentions?.open, mentions?.render, artifacts?.open, artifacts?.isOpen, messageActions, replyFooter, rowExtras]);\n\n /** The model-and-effort pill and the note that reports a refused change. */\n const pickers = () => {\n const disabled = changing !== null || state.disposed || !connected;\n const barStart = model || effort ? <ModelEffortPicker model={model} effort={effort} currentModel={optimistic.model ?? viewModel} currentEffort={optimistic.effort ?? viewEffort} disabled={disabled} busy={changing}\n onModel={next => void change('model', () => model!.change(next), () => setOptimistic(value => ({ ...value, model: next })), () => {})}\n onEffort={next => void change('effort', () => effort!.change(next), () => setOptimistic(value => ({ ...value, effort: next })), () => {})} /> : undefined;\n const barNote = changeError ? <button type=\"button\" role=\"alert\" data-testid=\"configure-error\" title={`${changeError} (${labels.dismissHint})`} onClick={() => setChangeError(null)}\n className=\"min-w-0 max-w-[16rem] cursor-pointer truncate rounded-md bg-destructive/10 px-2 py-1 text-xs text-destructive outline-none focus-visible:ring-2 focus-visible:ring-ring/60\">{changeError}</button> : undefined;\n return { barStart, barNote };\n };\n\n const empty = connected && !state.view?.entries.length && !rows.length;\n const loading = (state.connection.kind === 'idle' || state.connection.kind === 'connecting') && !state.view;\n\n /** Everything `Composer` needs from the session; a surface adds its layout and slots. */\n const composer = {\n text: state.draft.text, onText: (text: string) => controller.setText(text), onKeyDown: onComposerKeyDown, textareaRef: textarea,\n attachments: state.draft.attachments.map(item => ({ id: item.id, name: item.name, mimeType: item.content.mimeType, data: item.content.data })),\n onRemoveAttachment: (id: string) => controller.setAttachments(controller.getSnapshot().draft.attachments.filter(item => item.id !== id)),\n working, sendBlocked, disabled: state.disposed, stopRequested: state.stop === 'requested',\n onSend: send, onStop: () => act(controller.stop),\n uploading: uploading > 0, canAttach: Boolean(onFiles || attachments), fileAccept: attachments ? attachments.accept ?? '' : fileAccept, onPickFiles: (files: readonly File[]) => { void upload(files); },\n slash, onSlashError: report, mentions, mentionPaths: picked, onMentionPicked: (path: string) => setPicked(value => value.includes(path) ? value : [...value, path]),\n uploads: pending, onDismissUpload: (id: string) => setPending(items => items.filter(item => item.id !== id)),\n feedback,\n };\n\n return { state, derived, rows, queued, queueActions, working, waitingForAnswer, connected, sendBlocked, error, setError, report, act, current, textarea, rowContext, composer, pickers, empty, loading, developer };\n}\n\nexport type ChatSession = ReturnType<typeof useChatSession>;\n\n/** Scroll-to-bottom transcript with older rows revealed in pages as the person scrolls up. */\nexport function useTranscript(rows: readonly unknown[], page = 60, more = 40) {\n const [limit, setLimit] = useState(page);\n const anchor = useRef<{ readonly height: number; readonly top: number } | undefined>(undefined);\n // Growth re-pins at once: a spring trails the rows that grow after insert (streamed text, late images) and leaves the newest one under the composer.\n const library = useStickToBottom({ initial: 'instant', resize: 'instant' });\n // The scroller can mount later (AmbientChat starts collapsed) and unmount on collapse, so the element is held in state.\n const [scroller, setScroller] = useState<HTMLElement | null>(null);\n const scrollRef = useCallback((element: HTMLElement | null) => { library.scrollRef(element); setScroller(element); }, [library.scrollRef]);\n const stick = { ...library, scrollRef };\n // The library observes only the content. A shorter viewport (phone keyboard, a taller composer) leaves the newest row below the fold,\n // so re-pin when the viewport shrinks while the reader is at the bottom.\n useEffect(() => {\n if (!scroller || typeof ResizeObserver === 'undefined') return;\n let height = scroller.clientHeight;\n const observer = new ResizeObserver(() => {\n const shrank = scroller.clientHeight < height;\n height = scroller.clientHeight;\n if (shrank && library.state.isAtBottom) void library.scrollToBottom('instant');\n });\n observer.observe(scroller);\n return () => observer.disconnect();\n }, [scroller, library.state, library.scrollToBottom]);\n // The library ignores scroll events while it is absorbing a growth (a resize difference), so a scroll-up in that window would be\n // snapped back by its pending frame. Release the bottom lock as soon as the reader moves up. The library's own programmatic\n // writes are marked in ignoreScrollToTop, which its listener clears: this listener is a capture listener so it reads the mark first.\n useEffect(() => {\n if (!scroller) return;\n let last = scroller.scrollTop;\n const onScroll = () => {\n const top = scroller.scrollTop;\n const programmatic = library.state.ignoreScrollToTop === top;\n if (!programmatic && top < last && !library.state.isNearBottom && library.state.isAtBottom) library.stopScroll();\n last = top;\n };\n scroller.addEventListener('scroll', onScroll, { passive: true, capture: true });\n return () => scroller.removeEventListener('scroll', onScroll, { capture: true });\n }, [scroller, library.state, library.stopScroll]);\n const hidden = Math.max(0, rows.length - limit);\n // Reveal older rows when the person scrolls near the top, keeping the same rows in view.\n const reveal = useCallback(() => {\n if (scroller) anchor.current = { height: scroller.scrollHeight, top: scroller.scrollTop };\n setLimit(value => value + more);\n }, [scroller, more]);\n useLayoutEffect(() => {\n const saved = anchor.current;\n if (scroller && saved) { scroller.scrollTop = saved.top + scroller.scrollHeight - saved.height; anchor.current = undefined; }\n }, [limit, scroller]);\n useEffect(() => {\n if (!scroller) return;\n const onScroll = () => { if (scroller.scrollTop < 240 && scroller.scrollHeight > scroller.clientHeight && hidden > 0 && !anchor.current) reveal(); };\n scroller.addEventListener('scroll', onScroll, { passive: true });\n return () => scroller.removeEventListener('scroll', onScroll);\n }, [hidden, reveal, scroller]);\n return { stick, hidden, reveal, visible: <T,>(items: readonly T[]): readonly T[] => hidden ? items.slice(hidden) : items, reset: () => setLimit(page) };\n}\n",
143
+ "type": "registry:component",
144
+ "target": "components/pi-chat/session.tsx"
145
+ },
146
+ {
147
+ "path": "registry/pi-chat/shimmer.tsx",
148
+ "content": "import type { ElementType, ReactNode } from 'react';\nimport { cn } from '../utils/utils';\n\n/** Text with a moving highlight while `active` (styles: `.pi-chat-shimmer` in this item's css). Plain text otherwise. */\nexport function Shimmer({ children, active = true, as: Tag = 'span', className }: { readonly children: ReactNode; readonly active?: boolean; readonly as?: ElementType; readonly className?: string }) {\n return <Tag className={cn(active && 'pi-chat-shimmer motion-reduce:animate-none', className)}>{children}</Tag>;\n}\n",
149
+ "type": "registry:component",
150
+ "target": "components/pi-chat/shimmer.tsx"
151
+ },
152
+ {
153
+ "path": "registry/pi-chat/slash-menu.tsx",
154
+ "content": "'use client';\n\nimport { useEffect, useMemo, useRef, useState } from 'react';\nimport { usePickerKeyboard } from './picker-keyboard';\nimport { slashGroup } from './config';\nimport type { SlashItem } from './config';\nimport { cn } from '../utils/utils';\nimport { useChatText } from './labels';\n\nconst ALL = '__all__';\n\n/**\n * The `/` menu, ported from v2's `SlashCommandPicker`: a search box seeded from what was typed after `/`, filter chips\n * (All, built-in, skills, plugin names), then rows with a name, badges and a one line description.\n */\nexport function SlashMenu({ query, items, onSelect, onDismiss }: {\n readonly query: string;\n readonly items: readonly SlashItem[];\n readonly onSelect: (item: SlashItem) => void;\n readonly onDismiss: () => void;\n}) {\n const { labels } = useChatText();\n const [group, setGroup] = useState(ALL);\n const [search, setSearch] = useState(query);\n const [active, setActive] = useState(0);\n const container = useRef<HTMLDivElement>(null), list = useRef<HTMLUListElement>(null);\n // Follow the composer text.\n useEffect(() => { setSearch(query); setActive(0); }, [query]);\n const groups = useMemo(() => [...new Set(items.map(slashGroup))].sort((a, b) => a.localeCompare(b)), [items]);\n const filtered = useMemo(() => {\n const needle = search.trim().toLowerCase();\n return items.filter(item => (group === ALL || slashGroup(item) === group)\n && (!needle || item.name.toLowerCase().includes(needle) || item.description.toLowerCase().includes(needle)));\n }, [items, search, group]);\n useEffect(() => { setActive(index => filtered.length === 0 ? 0 : Math.min(index, filtered.length - 1)); }, [filtered.length]);\n useEffect(() => {\n const outside = (event: MouseEvent) => { if (container.current && !container.current.contains(event.target as Node)) onDismiss(); };\n document.addEventListener('mousedown', outside);\n return () => document.removeEventListener('mousedown', outside);\n }, [onDismiss]);\n usePickerKeyboard({ count: filtered.length, activeIdx: active, setActiveIdx: setActive, listRef: list, onSelect: index => { const item = filtered[index]; if (item) onSelect(item); }, onDismiss });\n\n const optionId = (index: number) => `pi-chat-slash-${index}`;\n return <div ref={container} data-testid=\"slash-menu\" className=\"absolute inset-x-0 bottom-full z-20 mb-2 overflow-hidden rounded-xl border border-border bg-popover text-popover-foreground shadow-lg\">\n <input aria-label={labels.searchCommands} data-testid=\"slash-search\" type=\"text\" autoComplete=\"off\" spellCheck={false} value={search}\n onChange={event => { setSearch(event.currentTarget.value); setActive(0); }}\n className=\"block w-full border-0 border-b border-border/60 bg-transparent px-3 py-2 text-base outline-none placeholder:text-muted-foreground sm:text-xs max-sm:min-h-11\" placeholder={labels.searchCommands} />\n <div role=\"tablist\" aria-label={labels.filterBySource} className=\"flex flex-wrap gap-1 border-b border-border/60 px-2 py-1.5\">\n {[ALL, ...groups].map(name => <button key={name} type=\"button\" role=\"tab\" aria-selected={group === name} data-testid=\"slash-chip\" data-group={name === ALL ? 'all' : name}\n onMouseDown={event => { event.preventDefault(); setGroup(name); setActive(0); }}\n className={cn('cursor-pointer rounded-full px-2 py-px text-xs font-medium transition-colors max-sm:min-h-10 max-sm:min-w-10 max-sm:px-3 pointer-coarse:min-h-10 pointer-coarse:min-w-10 motion-reduce:transition-none',\n group === name ? 'bg-foreground/10 text-foreground' : 'bg-muted text-muted-foreground hover:bg-muted/70')}>{name === ALL ? labels.allSources : labels.slashGroup(name)}</button>)}\n </div>\n {filtered.length === 0\n ? <div data-testid=\"slash-empty\" className=\"px-3 py-2 text-xs text-muted-foreground\">{labels.noCommands}</div>\n : <ul ref={list} role=\"listbox\" aria-label={labels.commands} className=\"m-0 max-h-[min(20rem,45dvh)] list-none overflow-y-auto p-0 py-1\">\n {filtered.map((item, index) => <li key={`${item.source}:${item.name}`} id={optionId(index)} role=\"option\" aria-selected={index === active} title={item.description || undefined}\n data-testid=\"slash-item\" data-name={item.name} data-source={item.source} data-active={index === active ? 'true' : undefined}\n onMouseEnter={() => setActive(index)} onMouseDown={event => { event.preventDefault(); onSelect(item); }}\n className={cn('flex cursor-pointer flex-col gap-0.5 px-3 py-1.5 text-xs max-sm:min-h-11 max-sm:justify-center pointer-coarse:min-h-11 pointer-coarse:justify-center', index === active ? 'bg-accent text-foreground' : 'text-muted-foreground')}>\n <span className=\"flex items-center gap-1.5\">\n <span className=\"font-medium text-foreground\">/{item.name}</span>\n {item.source === 'skill' && <span data-testid=\"slash-badge-skill\" className=\"rounded-sm bg-primary/10 px-1 py-px text-xs font-semibold tracking-wide text-foreground uppercase\">{labels.skillBadge}</span>}\n {item.sourcePlugin && <span data-testid=\"slash-badge-source\" className=\"rounded-sm bg-muted px-1 py-px text-xs font-medium text-muted-foreground\">{item.sourcePlugin}</span>}\n </span>\n {item.description && <span className=\"truncate text-xs opacity-70\">{item.description}</span>}\n </li>)}\n </ul>}\n </div>;\n}\n",
155
+ "type": "registry:component",
156
+ "target": "components/pi-chat/slash-menu.tsx"
157
+ },
158
+ {
159
+ "path": "registry/pi-chat/tool.tsx",
160
+ "content": "'use client';\n\nimport { useState } from 'react';\nimport type { ReactNode } from 'react';\nimport type { ToolCall, ToolResultMessage } from '@earendil-works/pi-ai';\nimport { AlertCircleIcon, CheckCircle2Icon, ChevronDownIcon, CircleDashedIcon, Loader2Icon, WrenchIcon } from 'lucide-react';\nimport { cn } from '../utils/utils';\nimport { defaultChatLabels, useChatText } from './labels';\nimport type { ChatLabels } from './labels';\n\nexport type ToolStatus = 'running' | 'completed' | 'failed' | 'unfinished';\nexport interface ToolEntry { readonly key: string; readonly call: ToolCall; readonly result: ToolResultMessage | undefined; readonly status: ToolStatus; readonly custom?: ReactNode }\n\nconst STATUS_LABEL = { running: 'toolRunning', completed: 'toolCompleted', failed: 'toolFailedStatus', unfinished: 'toolUnfinished' } as const satisfies Record<ToolStatus, keyof ChatLabels>;\nconst PREVIEW_KEYS = ['path', 'file_path', 'filePath', 'command', 'query', 'pattern', 'name', 'url', 'id'];\n\n/** A short hint of what the call acts on, shown next to its name. */\nexport function preview(args: ToolCall['arguments']): string {\n const values = args as Record<string, unknown>;\n for (const key of PREVIEW_KEYS) { const value = values[key]; if (typeof value === 'string' && value) return value.replace(/\\s+/g, ' ').slice(0, 90); }\n const first = Object.values(values).find(value => typeof value === 'string' && value);\n return typeof first === 'string' ? first.replace(/\\s+/g, ' ').slice(0, 90) : '';\n}\n\nexport function StatusIcon({ status, className }: { readonly status: ToolStatus; readonly className?: string }) {\n const cls = cn('size-4 shrink-0', className);\n if (status === 'running') return <Loader2Icon aria-hidden=\"true\" className={cn(cls, 'animate-spin text-muted-foreground motion-reduce:animate-none')} />;\n if (status === 'completed') return <CheckCircle2Icon aria-hidden=\"true\" className={cn(cls, 'text-(--chat-success)')} />;\n if (status === 'failed') return <AlertCircleIcon aria-hidden=\"true\" className={cn(cls, 'text-destructive')} />;\n return <CircleDashedIcon aria-hidden=\"true\" className={cn(cls, 'text-muted-foreground')} />;\n}\n\nfunction Section({ title, children }: { readonly title: string; readonly children: ReactNode }) {\n return <div className=\"space-y-1.5\"><h4 className=\"m-0 text-xs font-medium tracking-wider text-muted-foreground uppercase\">{title}</h4>{children}</div>;\n}\n\n/** A short live label for a call: \"Reading notes/consultation.md\", \"Running bash\", \"Running working_git\" (`labels.toolActivity`). */\nexport function liveLabel(call: ToolCall, labels: Pick<ChatLabels, 'toolActivity'> = defaultChatLabels): string {\n return labels.toolActivity(call.name, preview(call.arguments));\n}\n\n/**\n * One tool call: name, status, collapsible arguments and result. Failed calls open by default.\n * `compact` renders it as a row of an activity block (no card border); `details: false` (expert mode, successful call) has nothing to expand.\n */\nexport function ToolCard({ entry, onOpenImage, compact = false, details = true }: { readonly entry: ToolEntry; readonly compact?: boolean; readonly details?: boolean; readonly onOpenImage?: (image: Extract<ToolResultMessage['content'][number], { type: 'image' }>) => void }) {\n const { labels } = useChatText();\n const { call, result, status } = entry;\n const [chosen, setChosen] = useState<boolean | undefined>();\n const open = details && (chosen ?? status === 'failed');\n const setOpen = (update: (value: boolean) => boolean) => setChosen(update(open));\n const hint = preview(call.arguments);\n return <div data-testid=\"tool-card\" data-boring=\"tool-card\" data-status={status} data-tool={call.name} data-call-id={call.id}\n className={cn('overflow-hidden', compact ? 'rounded-md' : 'rounded-lg border bg-card text-card-foreground', !compact && (status === 'failed' ? 'border-destructive/40' : 'border-border'))}>\n <button type=\"button\" aria-expanded={details ? open : undefined} disabled={!details} onClick={() => setOpen(value => !value)}\n className={cn('flex w-full items-center gap-2 text-left outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring/60 focus-visible:ring-inset motion-reduce:transition-none',\n compact ? 'min-h-7 px-2 py-1 pointer-coarse:min-h-10' : 'min-h-9 px-3 py-1.5 pointer-coarse:min-h-10', details ? 'cursor-pointer hover:bg-muted/50' : 'cursor-default')}>\n <WrenchIcon aria-hidden=\"true\" className=\"size-3.5 shrink-0 text-muted-foreground\" />\n <span data-testid=\"tool-name\" className=\"shrink-0 font-mono text-sm font-medium\">{call.name}</span>\n {hint && <span className=\"min-w-0 flex-1 truncate font-mono text-xs text-muted-foreground\">{hint}</span>}\n {!hint && <span className=\"flex-1\" />}\n <span data-testid=\"tool-status\" className={cn('inline-flex shrink-0 items-center gap-1 rounded-full bg-muted px-2 py-0.5 text-xs font-medium', status === 'failed' ? 'text-destructive' : 'text-muted-foreground')}>\n <StatusIcon status={status} className=\"size-3\" />{labels[STATUS_LABEL[status]]}</span>\n {details && <ChevronDownIcon aria-hidden=\"true\" className={cn('size-4 shrink-0 text-muted-foreground transition-transform motion-reduce:transition-none', open && 'rotate-180')} />}\n </button>\n {details && <div hidden={!open} data-testid=\"tool-details\" className=\"space-y-3 border-t border-border bg-muted/20 p-3\">\n <Section title={labels.arguments}><pre className=\"m-0 max-h-60 overflow-auto rounded-md bg-muted/60 p-2.5 font-mono text-xs leading-5 whitespace-pre-wrap [overflow-wrap:anywhere]\">{JSON.stringify(call.arguments, null, 2)}</pre></Section>\n {result && <Section title={result.isError ? labels.error : labels.result}>\n <div role={result.isError ? 'alert' : undefined} className={cn('space-y-2 rounded-md p-2.5', result.isError ? 'bg-destructive/10 text-destructive' : 'bg-muted/60')}>\n {result.content.map((part, index) => part.type === 'text'\n ? <pre key={index} className=\"m-0 max-h-72 overflow-auto font-mono text-xs leading-5 whitespace-pre-wrap [overflow-wrap:anywhere]\">{part.text}</pre>\n : <button key={index} type=\"button\" disabled={!onOpenImage} onClick={() => onOpenImage?.(part)} className=\"cursor-pointer rounded-md border border-border bg-background px-2 py-1 text-xs disabled:cursor-default\">{labels.openImageResult}</button>)}\n {result.content.length === 0 && <span className=\"text-xs text-muted-foreground\">{labels.emptyResult}</span>}\n </div></Section>}\n </div>}\n </div>;\n}\n\n",
161
+ "type": "registry:component",
162
+ "target": "components/pi-chat/tool.tsx"
163
+ },
164
+ {
165
+ "path": "registry/pi-chat/use-remote-chat.ts",
166
+ "content": "import { useEffect, useLayoutEffect, useMemo, useState } from 'react';\nimport { createNativeChatController } from '@hachej/boring-ui-kit/native-chat';\nimport type { ChatIdentity, NativeChatController } from '@hachej/boring-ui-kit/native-chat';\nimport { createRemoteChat } from '@hachej/boring-ui-kit/remote-chat';\nimport type { RemoteChat } from '@hachej/boring-ui-kit/remote-chat';\nimport type { PiChatActions } from './pi-chat';\n\nexport type RemoteChatState =\n | { readonly status: 'connecting'; readonly conversationId: string | undefined }\n | { readonly status: 'offline'; readonly conversationId: string | undefined; readonly error: string }\n | { readonly status: 'ready'; readonly conversationId: string; readonly controller: NativeChatController; readonly actions: PiChatActions; readonly configure: RemoteChat['configure'] };\n\n/**\n * One native chat controller per selected conversation over the host's chat transport (`createChatTransportHandler` of\n * `@hachej/boring-agent/chat-transport`). `endpoint(id)` names the transport URL of a conversation; `fetch` is the host's authenticated fetch.\n * The remote chat reopens a dropped stream itself (the controller reads `reconnecting` meanwhile); it never means the task stopped.\n * A failed connect retries every second. The previous conversation's controller is never handed out: it is disposed on change.\n */\nexport function useRemoteChat({ conversationId, endpoint, fetch, identity }: {\n readonly conversationId: string | undefined;\n readonly endpoint: (conversationId: string) => string | URL;\n readonly fetch: (request: Request) => Promise<Response>;\n readonly identity: ChatIdentity | undefined;\n}): RemoteChatState {\n const url = conversationId === undefined ? undefined : String(endpoint(conversationId));\n const key = JSON.stringify([conversationId, url, identity?.runtimeId, identity?.scopeId, identity?.principalId]);\n const binding = useMemo(() => ({ key, fetch }), [key]); // eslint-disable-line react-hooks/exhaustive-deps\n useLayoutEffect(() => { binding.fetch = fetch; }, [binding, fetch]);\n const [stored, setStored] = useState<{ readonly binding: typeof binding; readonly chat: RemoteChatState }>();\n useEffect(() => {\n if (conversationId === undefined || !identity || url === undefined) return;\n const setChat = (chat: RemoteChatState) => setStored({ binding, chat });\n let disposed = false, controller: NativeChatController | undefined, remote: RemoteChat | undefined;\n setChat({ status: 'connecting', conversationId });\n void (async () => {\n while (!disposed) {\n try {\n remote = await createRemoteChat({ endpoint: url, fetch: request => binding.fetch(request) });\n if (disposed) return void remote.close();\n controller = createNativeChatController({ identity, ...remote });\n await controller.connect();\n if (disposed) return void controller.dispose();\n // Human-in-the-loop answers and queue withdrawal are optional on the transport: pass only what it offers.\n const actions: { answer?: RemoteChat['answer']; withdraw?: RemoteChat['withdraw'] } = {};\n if (typeof remote.answer === 'function') actions.answer = remote.answer;\n if (typeof remote.withdraw === 'function') actions.withdraw = remote.withdraw;\n setChat({ status: 'ready', controller, conversationId, actions, configure: remote.configure });\n return;\n } catch (error) {\n controller?.dispose(); controller = undefined; void remote?.close(); remote = undefined;\n if (disposed) return;\n setChat({ status: 'offline', conversationId, error: String((error as Error)?.message ?? error) });\n await new Promise(resolve => setTimeout(resolve, 1000));\n }\n }\n })();\n return () => { disposed = true; controller?.dispose(); void remote?.close(); };\n }, [binding]); // eslint-disable-line react-hooks/exhaustive-deps\n return identity && stored?.binding === binding ? stored.chat : { status: 'connecting', conversationId };\n}\n",
167
+ "type": "registry:hook",
168
+ "target": "components/pi-chat/use-remote-chat.ts"
169
+ },
170
+ {
171
+ "path": "registry/pi-chat/labels.ts",
172
+ "content": "/*\n * Every word the chat shows, and the icons it draws, as plain data. A host passes a partial `labels` (and `icons`) object to `PiChat`\n * (or `AmbientChat`, `AgentWorkspace`): what it leaves out keeps the default below. Strings that need a value are functions. No i18n\n * framework: an app that translates passes its own object per language.\n */\nimport { createContext, createElement, useContext, useMemo } from 'react';\nimport type { ReactNode } from 'react';\nimport { ArrowDownIcon, ArrowUpIcon, GitForkIcon, HistoryIcon, ListEndIcon, MessagesSquareIcon, PaperclipIcon, PlusIcon, RefreshCwIcon, SquareIcon } from 'lucide-react';\nimport type { BlockIcon } from '../button/actions';\nimport { withDefaults } from '../utils/utils';\n\nconst TOOL_VERBS: Readonly<Record<string, string>> = { read: 'Reading', write: 'Writing', edit: 'Editing', ls: 'Listing', list_files: 'Listing', find: 'Searching', grep: 'Searching', load_skill: 'Loading skill', bash: 'Running bash' };\nconst TOOL_NOUNS: Readonly<Record<string, string>> = { bash: 'command', read: 'read', write: 'write', edit: 'edit', find: 'find', grep: 'search', ls: 'list' };\n\nconst EFFORT_NAMES: Readonly<Record<string, string>> = { off: 'Off', minimal: 'Minimal', low: 'Low', medium: 'Medium', high: 'High', xhigh: 'Extra high', max: 'Max' };\nconst EFFORT_DETAILS: Readonly<Record<string, string>> = { off: 'No extra reasoning', minimal: 'Barely any reasoning', low: 'Light reasoning', medium: 'Balanced reasoning', high: 'Deep reasoning', xhigh: 'Deeper reasoning', max: 'Maximum reasoning' };\n\nexport const defaultChatLabels = {\n // Header and transcript\n /** The chat's name: the header title, the region's name and the empty state's title. */\n title: 'Conversation',\n history: 'History',\n live: 'Live',\n connecting: 'Connecting…',\n reconnecting: 'Reconnecting…',\n loadFailed: 'Conversation could not be loaded.',\n disconnected: 'Disconnected. Last observed messages remain visible.',\n reconnect: 'Reconnect',\n requiredActions: 'Required conversation actions',\n messages: 'Messages',\n showEarlier: 'Show earlier messages',\n loading: 'Loading conversation…',\n emptyDescription: 'Start a conversation.',\n jumpToLatest: 'Jump to latest',\n agentWorking: 'Agent is working',\n waitingForAnswer: 'Waiting for your answer',\n retryPending: 'Native retry pending',\n compacting: 'Native context compaction in progress',\n /** The \"…\" menu of host actions (header, replies). */\n moreActions: 'More actions',\n // Notices\n sendUnknown: 'Submission acknowledgement is unknown. The message is kept until you check or retry it.',\n checkSubmission: 'Check original submission',\n retrySame: 'Retry same request',\n stopRequested: 'Stop requested. Waiting for native confirmation.',\n stopUnconfirmed: 'Stop is unconfirmed. Work may still be running.',\n steerRefused: 'The message could not be steered; it is back in the message box.',\n tooLate: 'Too late: that message has already started.',\n tooLateToRemove: 'Too late to remove: that message has already started.',\n queueFailed: 'The message could not be changed.',\n queueLocked: 'Queued messages cannot be changed here.',\n waitToSteer: 'Wait for the current send to finish, then steer.',\n steerFailed: 'The message could not be steered.',\n connectionFailed: 'Connection failed',\n actionFailedShort: 'Action failed',\n uploadFailedShort: 'Upload failed',\n changeRefused: 'The change was refused',\n dismissHint: 'click to dismiss',\n // Composer\n placeholder: 'Message the agent…',\n placeholderWorking: 'Queue a message…',\n messageInput: 'Message',\n send: 'Send',\n sendHint: 'Send (Enter)',\n stop: 'Stop',\n queue: 'Queue',\n add: 'Add',\n attachFiles: 'Attach files',\n commands: 'Commands',\n feedback: 'Feedback',\n feedbackHint: 'Feedback: point at the page and say what is wrong',\n point: 'Show in app',\n pointHint: 'Show in the app: the panel steps aside, tap what you mean',\n remove: (name: string) => `Remove ${name}`,\n dismiss: (name: string) => `Dismiss ${name}`,\n uploading: (name: string) => `Uploading ${name}…`,\n uploadFailed: (name: string, error: string | undefined) => `${name}: ${error ?? 'upload failed'}`,\n preparingAttachments: 'Preparing attachments…',\n preparingAttachmentsShort: 'Preparing attachments',\n mentionedFiles: 'Mentioned files',\n uploads: 'Uploads',\n attachments: 'Attachments',\n searchCommands: 'Search commands',\n filterBySource: 'Filter by source',\n allSources: 'All',\n noCommands: 'No matching commands.',\n /** A `/` menu filter chip: `skills`, `built-in` or a plugin's name. */\n slashGroup: (group: string) => group,\n skillBadge: 'skill',\n workspaceFiles: 'Workspace files',\n searchFailed: 'Search failed',\n model: 'Model',\n effort: 'Effort',\n effortDefault: 'Default',\n modelAndEffort: 'Model and effort',\n modelSummary: (model: string | undefined, effort: string | undefined) => [model && `Model: ${model}`, effort && `Effort: ${effort}`].filter(Boolean).join(', '),\n /** A thinking level's name and short description in the picker. */\n effortName: (level: string) => EFFORT_NAMES[level] ?? level,\n effortDetail: (level: string): string | undefined => EFFORT_DETAILS[level],\n // Voice input (the microphone button beside the composer)\n voiceRecord: 'Record a message',\n voiceStop: 'Stop recording',\n voiceCancel: 'Cancel recording',\n voiceTranscribing: 'Transcribing…',\n voiceNothingHeard: 'Nothing was heard. Try again.',\n voiceTranscribeFailed: 'The recording could not be transcribed. Try again.',\n voiceDenied: 'Microphone blocked. Allow it for this site in the browser, then press record again.',\n voiceNoMicrophone: 'No microphone found. Connect one, then press record again.',\n voiceBusy: 'The microphone is busy or could not be opened. Close other apps using it and try again.',\n voiceInsecure: 'Recording needs a secure page (https or localhost).',\n voiceUnsupported: 'This browser cannot record audio here.',\n voiceStartFailed: 'The microphone could not be started.',\n // Queue\n queuedMessages: 'Queued messages',\n steer: 'Steer',\n steerHint: 'Send this into the running turn now',\n steering: 'Steering',\n queued: 'Queued',\n removeQueued: 'Remove queued message',\n removeHint: 'Remove',\n more: 'More',\n edit: 'Edit',\n sending: 'Sending',\n images: (count: number) => `[${count} image${count === 1 ? '' : 's'}]`,\n // Conversation list and history\n historyDialog: 'Conversation history',\n newConversation: 'New',\n untitled: 'New conversation',\n closeHistory: 'Close history',\n close: 'Close',\n earlierInConversation: 'Earlier messages in this conversation',\n searchConversations: 'Search conversations',\n archived: 'Archived',\n current: 'Current',\n noMatch: (query: string) => `No conversation matches “${query}”.`,\n noArchived: 'No archived conversations.',\n noConversations: 'No conversations yet.',\n loadingConversations: 'Loading conversations…',\n actionFailed: 'That did not work. Try again.',\n rename: 'Rename',\n renameItem: (title: string) => `Rename ${title}`,\n conversationName: 'Conversation name',\n save: 'Save',\n archive: 'Archive',\n restore: 'Restore',\n archiveItem: (title: string, archived: boolean) => `${archived ? 'Restore' : 'Archive'} ${title}`,\n delete: 'Delete',\n deleteItem: (title: string) => `Delete ${title}`,\n keep: 'Keep conversation',\n today: 'Today',\n yesterday: 'Yesterday',\n previousWeek: 'Previous 7 days',\n older: 'Older',\n conversations: 'Conversations',\n earlierMessages: 'Earlier messages',\n readOnly: '(read-only)',\n retry: 'Retry',\n loadingShort: 'Loading…',\n loadEarlier: 'Load earlier',\n returnToConversation: 'Return to active conversation',\n historyFailed: 'Conversation history could not be loaded. The previous page remains visible.',\n loadPage: 'Load a page to browse earlier messages.',\n noRecords: 'No records in this history page.',\n beginning: 'Beginning of conversation.',\n justNow: 'now',\n roleSystem: 'System',\n roleToolResult: (tool: string, failed: boolean) => `Tool result: ${tool}${failed ? ' (failed)' : ''}`,\n roleUser: 'You',\n roleAssistant: (outcome: 'ok' | 'interrupted' | 'failed'): string => outcome === 'interrupted' ? 'Assistant (interrupted)' : outcome === 'failed' ? 'Assistant (failed)' : 'Assistant',\n roleEvent: 'Event',\n contextBoundary: 'Context boundary',\n // Messages\n copy: 'Copy',\n copied: 'Copied',\n copyFailed: 'Copy failed',\n failed: 'Failed',\n copyResponse: 'Copy response',\n copyCode: 'Copy code',\n fork: 'Fork from here',\n forkHint: 'Fork from here: a new conversation with the messages up to this reply',\n responseFailed: 'The response failed',\n interrupted: 'Response interrupted',\n thinking: 'Thinking…',\n openImage: 'Open image attachment',\n imageAttachment: 'Image attachment',\n systemContext: 'System context',\n toolFailed: (tool: string) => `${tool} failed`,\n event: (label: string) => `Event: ${label}`,\n // Activity and tools\n reasoning: 'Reasoning',\n thinkingStep: 'Thinking',\n steps: (count: number) => `${count} ${count === 1 ? 'step' : 'steps'}`,\n toolRunning: 'Running',\n toolCompleted: 'Completed',\n toolFailedStatus: 'Failed',\n toolUnfinished: 'No result',\n arguments: 'Arguments',\n result: 'Result',\n error: 'Error',\n openImageResult: 'Open image result',\n emptyResult: 'Empty result',\n /** The live line of a running tool call; `hint` is what it acts on (a path, a command), possibly empty. */\n toolActivity: (tool: string, hint: string) => {\n const verb = TOOL_VERBS[tool] ?? `Running ${tool}`;\n return hint ? `${verb}${tool === 'bash' ? ':' : ''} ${hint}` : verb;\n },\n /** How a tool is named in a finished activity summary (\"Used read ×3 · command\"). */\n toolNoun: (tool: string) => TOOL_NOUNS[tool] ?? tool,\n // Approval and question cards\n approvalNeeded: 'Approval needed',\n needsApproval: 'Needs your approval',\n approve: 'Approve',\n deny: 'Deny',\n approved: 'Approved',\n denied: 'Denied',\n notDecided: 'Not decided: the run was stopped',\n wantsToRun: 'The agent wants to run',\n decision: 'Decision',\n stillWritingCall: 'The agent is still writing this call…',\n decidingUnavailable: 'Deciding is not available in this view.',\n decisionSent: (approved: boolean) => `${approved ? 'Approved.' : 'Denied.'} Waiting for the agent…`,\n decisionRefused: (kind: 'denied' | 'conflict' | 'unknown-question'): string => kind === 'denied' ? 'The host did not accept this answer.' : kind === 'conflict' ? 'This call was already decided.' : 'This call is no longer waiting for a decision.',\n decisionNotSent: 'The decision could not be sent.',\n waitingForAgent: 'Waiting for the agent…',\n question: 'Question',\n questionForYou: 'Question for you',\n notAnswered: 'Not answered',\n answered: 'Answered',\n askedQuestion: 'The agent asked a question.',\n answerOptions: 'Answer options',\n ownAnswer: 'Or type your own answer',\n typeAnswer: 'Type your answer',\n yourAnswerInput: 'Your answer',\n answer: 'Answer',\n stillWritingQuestion: 'The agent is still writing this question…',\n answeringUnavailable: 'Answering is not available in this view.',\n answerRefused: (kind: 'denied' | 'conflict' | 'unknown-question'): string => kind === 'denied' ? 'The host did not accept this answer.' : kind === 'conflict' ? 'This question was already answered.' : 'This question is no longer waiting for an answer.',\n answerNotSent: 'The answer could not be sent.',\n yourAnswer: 'Your answer:',\n // Artifact cards\n artifact: 'Artifact',\n opening: 'Opening…',\n viewing: 'Viewing',\n version: (ordinal: number) => `Version ${ordinal}`,\n runCommand: (name: string, execute: boolean) => `${execute ? 'Run' : 'Insert'} /${name} command`,\n taskStatus: 'Task status',\n activityFailed: (count: number, tools: string) => `${count > 1 ? `${count} steps failed` : 'Step failed'}: ${tools}`,\n activityUsed: (summary: string, stopped: boolean) => `${stopped ? 'Stopped · ' : 'Used '}${summary}`,\n activityThought: 'Thought it through',\n activityMany: (steps: number) => `Worked through ${steps} steps`,\n open: 'Open',\n openArtifact: (title: string, version: number | undefined) => version === undefined ? `Open ${title}` : `Open ${title}, version ${version}`,\n};\n\nexport type ChatLabels = typeof defaultChatLabels;\n\n/** The chat's icons. Any component that takes `className` (every lucide icon does). */\nexport const defaultChatIcons = {\n /** The agent's glyph in the empty state (the header shows the host's `avatar`, if any). */\n agent: MessagesSquareIcon as BlockIcon,\n send: ArrowUpIcon as BlockIcon,\n stop: SquareIcon as BlockIcon,\n history: HistoryIcon as BlockIcon,\n newChat: PlusIcon as BlockIcon,\n add: PlusIcon as BlockIcon,\n attach: PaperclipIcon as BlockIcon,\n queue: ListEndIcon as BlockIcon,\n jumpToLatest: ArrowDownIcon as BlockIcon,\n reconnect: RefreshCwIcon as BlockIcon,\n fork: GitForkIcon as BlockIcon,\n};\n\nexport type ChatIcons = typeof defaultChatIcons;\n\n/** What the chat's pieces read: the merged labels and icons. */\nexport interface ChatText { readonly labels: ChatLabels; readonly icons: ChatIcons }\n/** The defaults, as `useMergedText`'s base. */\nexport const defaultChatText: ChatText = { labels: defaultChatLabels, icons: defaultChatIcons };\nconst DEFAULT_TEXT = defaultChatText;\nconst ChatTextContext = createContext<ChatText>(DEFAULT_TEXT);\n\n/** The labels and icons of the surrounding chat (the defaults outside one). */\nexport const useChatText = (): ChatText => useContext(ChatTextContext);\n\n/** Merges the host's partial labels and icons over the defaults (or over `base`), keeping one object while they do not change. */\nexport function useMergedText<L extends ChatLabels = ChatLabels, I extends ChatIcons = ChatIcons>(labels: Partial<L> | undefined, icons: Partial<I> | undefined,\n base: { readonly labels: L; readonly icons: I } = DEFAULT_TEXT as { readonly labels: L; readonly icons: I }): { readonly labels: L; readonly icons: I } {\n return useMemo(() => ({ labels: withDefaults(base.labels, labels), icons: withDefaults(base.icons, icons) }), [labels, icons, base]);\n}\n\n/** Provides the chat's labels and icons to everything inside (composer, queue, rows, history). */\nexport function ChatTextProvider({ value, children }: { readonly value: ChatText; readonly children: ReactNode }) {\n return createElement(ChatTextContext.Provider, { value }, children);\n}\n",
173
+ "type": "registry:lib",
174
+ "target": "components/pi-chat/labels.ts"
175
+ },
176
+ {
177
+ "path": "registry/pi-chat/labels-fr.ts",
178
+ "content": "/* The chat's words in French, the `locale=\"fr\"` base of `PiChat`, `AmbientChat` and `AgentWorkspace`. Typed as `ChatLabels`, so a key added in English must be added here too. */\nimport type { ChatLabels } from './labels';\n\nconst TOOL_VERBS: Readonly<Record<string, string>> = { read: 'Lecture', write: 'Écriture', edit: 'Modification', ls: 'Liste', list_files: 'Liste', find: 'Recherche', grep: 'Recherche', load_skill: 'Chargement de la compétence', bash: 'Exécution bash' };\nconst TOOL_NOUNS: Readonly<Record<string, string>> = { bash: 'commande', read: 'lecture', write: 'écriture', edit: 'modification', find: 'recherche', grep: 'recherche', ls: 'liste' };\nconst EFFORT_NAMES: Readonly<Record<string, string>> = { off: 'Désactivé', minimal: 'Minimal', low: 'Faible', medium: 'Moyen', high: 'Élevé', xhigh: 'Très élevé', max: 'Maximum' };\nconst EFFORT_DETAILS: Readonly<Record<string, string>> = { off: 'Sans réflexion supplémentaire', minimal: 'Presque aucune réflexion', low: 'Réflexion légère', medium: 'Réflexion équilibrée', high: 'Réflexion approfondie', xhigh: 'Réflexion très approfondie', max: 'Réflexion maximale' };\n\nexport const frenchChatLabels: ChatLabels = {\n title: 'Conversation',\n history: 'Historique',\n live: 'En direct',\n connecting: 'Connexion…',\n reconnecting: 'Reconnexion…',\n loadFailed: 'La conversation n’a pas pu être chargée.',\n disconnected: 'Déconnecté. Les derniers messages reçus restent affichés.',\n reconnect: 'Se reconnecter',\n requiredActions: 'Actions requises dans la conversation',\n messages: 'Messages',\n showEarlier: 'Afficher les messages précédents',\n loading: 'Chargement de la conversation…',\n emptyDescription: 'Commencez une conversation.',\n jumpToLatest: 'Aller au dernier message',\n agentWorking: 'L’agent travaille',\n waitingForAnswer: 'En attente de votre réponse',\n retryPending: 'Nouvelle tentative en attente',\n compacting: 'Résumé du contexte en cours',\n moreActions: 'Plus d’actions',\n sendUnknown: 'L’envoi n’est pas confirmé. Le message est conservé jusqu’à ce que vous le vérifiiez ou le renvoyiez.',\n checkSubmission: 'Vérifier l’envoi',\n retrySame: 'Renvoyer la même demande',\n stopRequested: 'Arrêt demandé. En attente de confirmation.',\n stopUnconfirmed: 'Arrêt non confirmé. Le travail continue peut-être.',\n steerRefused: 'Le message n’a pas pu être ajouté en cours de réponse ; il est revenu dans la zone de saisie.',\n tooLate: 'Trop tard : ce message a déjà commencé.',\n tooLateToRemove: 'Trop tard pour le retirer : ce message a déjà commencé.',\n queueFailed: 'Le message n’a pas pu être modifié.',\n queueLocked: 'Les messages en attente ne peuvent pas être modifiés ici.',\n waitToSteer: 'Attendez la fin de l’envoi en cours, puis réessayez.',\n steerFailed: 'Le message n’a pas pu être ajouté en cours de réponse.',\n connectionFailed: 'Échec de la connexion',\n actionFailedShort: 'Échec de l’action',\n uploadFailedShort: 'Échec de l’envoi',\n changeRefused: 'La modification a été refusée',\n dismissHint: 'cliquez pour fermer',\n placeholder: 'Écrivez à l’agent…',\n placeholderWorking: 'Mettre un message en attente…',\n messageInput: 'Message',\n send: 'Envoyer',\n sendHint: 'Envoyer (Entrée)',\n stop: 'Arrêter',\n queue: 'Mettre en attente',\n add: 'Ajouter',\n attachFiles: 'Joindre des fichiers',\n // Voice input (the microphone button beside the composer)\n voiceRecord: 'Enregistrer un message',\n voiceStop: 'Arrêter l’enregistrement',\n voiceCancel: 'Annuler l’enregistrement',\n voiceTranscribing: 'Transcription…',\n voiceNothingHeard: 'Rien n’a été entendu. Réessayez.',\n voiceTranscribeFailed: 'L’enregistrement n’a pas pu être transcrit. Réessayez.',\n voiceDenied: 'Microphone bloqué. Autorisez-le pour ce site dans le navigateur, puis appuyez de nouveau sur enregistrer.',\n voiceNoMicrophone: 'Aucun microphone trouvé. Branchez-en un, puis appuyez de nouveau sur enregistrer.',\n voiceBusy: 'Le microphone est occupé ou n’a pas pu être ouvert. Fermez les autres applications qui l’utilisent et réessayez.',\n voiceInsecure: 'L’enregistrement exige une page sécurisée (https ou localhost).',\n voiceUnsupported: 'Ce navigateur ne peut pas enregistrer le son ici.',\n voiceStartFailed: 'Le microphone n’a pas pu être démarré.',\n commands: 'Commandes',\n feedback: 'Retour',\n feedbackHint: 'Retour : montrez l’endroit de la page et dites ce qui ne va pas',\n point: 'Montrer dans l’app',\n pointHint: 'Montrer dans l’app : le panneau s’efface, touchez ce dont vous parlez',\n remove: name => `Retirer ${name}`,\n dismiss: name => `Fermer ${name}`,\n uploading: name => `Envoi de ${name}…`,\n uploadFailed: (name, error) => `${name} : ${error ?? 'échec de l’envoi'}`,\n preparingAttachments: 'Préparation des pièces jointes…',\n preparingAttachmentsShort: 'Préparation des pièces jointes',\n mentionedFiles: 'Fichiers mentionnés',\n uploads: 'Envois',\n attachments: 'Pièces jointes',\n searchCommands: 'Rechercher une commande',\n filterBySource: 'Filtrer par source',\n allSources: 'Toutes',\n noCommands: 'Aucune commande ne correspond.',\n slashGroup: group => group === 'skills' ? 'compétences' : group === 'built-in' ? 'intégrées' : group,\n skillBadge: 'compétence',\n workspaceFiles: 'Fichiers de l’espace',\n searchFailed: 'La recherche a échoué',\n model: 'Modèle',\n effort: 'Effort',\n effortDefault: 'Par défaut',\n modelAndEffort: 'Modèle et effort',\n modelSummary: (model, effort) => [model && `Modèle : ${model}`, effort && `Effort : ${effort}`].filter(Boolean).join(', '),\n effortName: level => EFFORT_NAMES[level] ?? level,\n effortDetail: level => EFFORT_DETAILS[level],\n queuedMessages: 'Messages en attente',\n steer: 'Envoyer maintenant',\n steerHint: 'Ajouter ce message à la réponse en cours',\n steering: 'Envoi en cours de réponse',\n queued: 'En attente',\n removeQueued: 'Retirer le message en attente',\n removeHint: 'Retirer',\n more: 'Plus',\n edit: 'Modifier',\n sending: 'Envoi',\n images: count => `[${count} image${count === 1 ? '' : 's'}]`,\n historyDialog: 'Historique des conversations',\n newConversation: 'Nouvelle',\n untitled: 'Nouvelle conversation',\n closeHistory: 'Fermer l’historique',\n close: 'Fermer',\n earlierInConversation: 'Messages précédents de cette conversation',\n searchConversations: 'Rechercher une conversation',\n archived: 'Archivées',\n current: 'En cours',\n noMatch: query => `Aucune conversation ne correspond à « ${query} ».`,\n noArchived: 'Aucune conversation archivée.',\n noConversations: 'Aucune conversation pour le moment.',\n loadingConversations: 'Chargement des conversations…',\n actionFailed: 'Cela n’a pas fonctionné. Réessayez.',\n rename: 'Renommer',\n renameItem: title => `Renommer ${title}`,\n conversationName: 'Nom de la conversation',\n save: 'Enregistrer',\n archive: 'Archiver',\n restore: 'Restaurer',\n archiveItem: (title, archived) => `${archived ? 'Restaurer' : 'Archiver'} ${title}`,\n delete: 'Supprimer',\n deleteItem: title => `Supprimer ${title}`,\n keep: 'Garder la conversation',\n today: 'Aujourd’hui',\n yesterday: 'Hier',\n previousWeek: 'Les 7 derniers jours',\n older: 'Plus anciennes',\n conversations: 'Conversations',\n earlierMessages: 'Messages précédents',\n readOnly: '(lecture seule)',\n retry: 'Réessayer',\n loadingShort: 'Chargement…',\n loadEarlier: 'Charger les précédents',\n returnToConversation: 'Revenir à la conversation en cours',\n historyFailed: 'L’historique n’a pas pu être chargé. La page précédente reste affichée.',\n loadPage: 'Chargez une page pour parcourir les messages précédents.',\n noRecords: 'Aucun élément sur cette page d’historique.',\n beginning: 'Début de la conversation.',\n justNow: 'à l’instant',\n roleSystem: 'Système',\n roleToolResult: (tool, failed) => `Résultat de l’outil : ${tool}${failed ? ' (échec)' : ''}`,\n roleUser: 'Vous',\n roleAssistant: outcome => outcome === 'interrupted' ? 'Assistant (interrompu)' : outcome === 'failed' ? 'Assistant (échec)' : 'Assistant',\n roleEvent: 'Événement',\n contextBoundary: 'Limite du contexte',\n copy: 'Copier',\n copied: 'Copié',\n copyFailed: 'Échec de la copie',\n failed: 'Échec',\n copyResponse: 'Copier la réponse',\n copyCode: 'Copier le code',\n fork: 'Repartir d’ici',\n forkHint: 'Repartir d’ici : une nouvelle conversation avec les messages jusqu’à cette réponse',\n responseFailed: 'La réponse a échoué',\n interrupted: 'Réponse interrompue',\n thinking: 'Réflexion…',\n openImage: 'Ouvrir l’image jointe',\n imageAttachment: 'Image jointe',\n systemContext: 'Contexte système',\n toolFailed: tool => `Échec de ${tool}`,\n event: label => `Événement : ${label}`,\n reasoning: 'Réflexion',\n thinkingStep: 'Réflexion',\n steps: count => `${count} ${count === 1 ? 'étape' : 'étapes'}`,\n toolRunning: 'En cours',\n toolCompleted: 'Terminé',\n toolFailedStatus: 'Échec',\n toolUnfinished: 'Sans résultat',\n arguments: 'Arguments',\n result: 'Résultat',\n error: 'Erreur',\n openImageResult: 'Ouvrir l’image du résultat',\n emptyResult: 'Résultat vide',\n toolActivity: (tool, hint) => {\n const verb = TOOL_VERBS[tool] ?? `Exécution de ${tool}`;\n return hint ? `${verb}${tool === 'bash' ? ' :' : ''} ${hint}` : verb;\n },\n toolNoun: tool => TOOL_NOUNS[tool] ?? tool,\n approvalNeeded: 'Approbation requise',\n needsApproval: 'Votre approbation est nécessaire',\n approve: 'Approuver',\n deny: 'Refuser',\n approved: 'Approuvé',\n denied: 'Refusé',\n notDecided: 'Non décidé : l’exécution a été arrêtée',\n wantsToRun: 'L’agent souhaite exécuter',\n decision: 'Décision',\n stillWritingCall: 'L’agent est encore en train d’écrire cet appel…',\n decidingUnavailable: 'La décision n’est pas disponible dans cette vue.',\n decisionSent: approved => `${approved ? 'Approuvé.' : 'Refusé.'} En attente de l’agent…`,\n decisionRefused: kind => kind === 'denied' ? 'Cette réponse n’a pas été acceptée.' : kind === 'conflict' ? 'Cet appel a déjà été décidé.' : 'Cet appel n’attend plus de décision.',\n decisionNotSent: 'La décision n’a pas pu être envoyée.',\n waitingForAgent: 'En attente de l’agent…',\n question: 'Question',\n questionForYou: 'Une question pour vous',\n notAnswered: 'Sans réponse',\n answered: 'Répondu',\n askedQuestion: 'L’agent a posé une question.',\n answerOptions: 'Réponses possibles',\n ownAnswer: 'Ou écrivez votre propre réponse',\n typeAnswer: 'Écrivez votre réponse',\n yourAnswerInput: 'Votre réponse',\n answer: 'Répondre',\n stillWritingQuestion: 'L’agent est encore en train d’écrire cette question…',\n answeringUnavailable: 'La réponse n’est pas disponible dans cette vue.',\n answerRefused: kind => kind === 'denied' ? 'Cette réponse n’a pas été acceptée.' : kind === 'conflict' ? 'Cette question a déjà reçu une réponse.' : 'Cette question n’attend plus de réponse.',\n answerNotSent: 'La réponse n’a pas pu être envoyée.',\n yourAnswer: 'Votre réponse :',\n artifact: 'Document',\n opening: 'Ouverture…',\n viewing: 'Affiché',\n version: ordinal => `Version ${ordinal}`,\n runCommand: (name, execute) => `${execute ? 'Exécuter' : 'Insérer'} la commande /${name}`,\n taskStatus: 'État de la tâche',\n activityFailed: (count, tools) => `${count > 1 ? `${count} étapes ont échoué` : 'Une étape a échoué'} : ${tools}`,\n activityUsed: (summary, stopped) => `${stopped ? 'Arrêté · ' : 'Utilisé : '}${summary}`,\n activityThought: 'Réflexion terminée',\n activityMany: steps => `${steps} étapes réalisées`,\n open: 'Ouvrir',\n openArtifact: (title, version) => version === undefined ? `Ouvrir ${title}` : `Ouvrir ${title}, version ${version}`,\n};\n",
179
+ "type": "registry:lib",
180
+ "target": "components/pi-chat/labels-fr.ts"
181
+ },
182
+ {
183
+ "path": "registry/pi-chat/locale.ts",
184
+ "content": "/* The languages the chat ships with. `locale` picks the base words; a host's `labels` still override any of them. */\nimport { defaultChatIcons, defaultChatText } from './labels';\nimport type { ChatText } from './labels';\nimport { frenchChatLabels } from './labels-fr';\n\nexport type ChatLocale = 'en' | 'fr';\nconst TEXT: Readonly<Record<ChatLocale, ChatText>> = { en: defaultChatText, fr: { labels: frenchChatLabels, icons: defaultChatIcons } };\n/** The chat's base labels and icons for `locale` (English by default). */\nexport const chatTextFor = (locale: ChatLocale | undefined): ChatText => TEXT[locale ?? 'en'];\n",
185
+ "type": "registry:lib",
186
+ "target": "components/pi-chat/locale.ts"
187
+ }
188
+ ],
189
+ "css": {
190
+ "@layer base": {
191
+ ".pi-chat, .pi-chat *, .pi-chat *::before, .pi-chat *::after": {
192
+ "box-sizing": "border-box"
193
+ },
194
+ ".pi-chat :where(button, input, textarea)": {
195
+ "font": "inherit",
196
+ "color": "inherit",
197
+ "letter-spacing": "inherit"
198
+ },
199
+ ".pi-chat :where(button)": {
200
+ "background-color": "transparent",
201
+ "border": "0",
202
+ "padding": "0"
203
+ },
204
+ ".pi-chat :where(textarea, input)": {
205
+ "margin": "0"
206
+ },
207
+ ".pi-chat [hidden]": {
208
+ "display": "none"
209
+ }
210
+ },
211
+ "@layer components": {
212
+ ".pi-chat": {
213
+ "--chat-success": "var(--success, var(--primary))",
214
+ "--chat-warning": "var(--warning, var(--muted-foreground))",
215
+ "--chat-warning-soft": "var(--warning-soft, color-mix(in oklab, var(--chat-warning) 15%, var(--background)))",
216
+ "--chat-warning-soft-foreground": "var(--warning-soft-foreground, color-mix(in oklab, var(--chat-warning) 75%, var(--foreground)))",
217
+ "--chat-display": "var(--font-display, var(--font-sans))"
218
+ },
219
+ ".pi-chat:is(.dark, .dark *)": {
220
+ "--chat-warning-soft": "var(--warning-soft, color-mix(in oklab, var(--chat-warning) 26%, var(--background)))",
221
+ "--chat-warning-soft-foreground": "var(--warning-soft-foreground, color-mix(in oklab, var(--chat-warning) 55%, var(--foreground)))"
222
+ },
223
+ ".pi-chat-shimmer": {
224
+ "background-image": "linear-gradient(100deg, var(--muted-foreground) 35%, var(--foreground) 50%, var(--muted-foreground) 65%)",
225
+ "background-size": "250% 100%",
226
+ "background-clip": "text",
227
+ "-webkit-background-clip": "text",
228
+ "color": "transparent",
229
+ "animation": "pi-chat-shimmer 2.2s linear infinite"
230
+ },
231
+ ".pi-chat [data-testid=\"message-text\"][data-streaming=\"true\"] > :last-child:not([data-testid=\"code-block\"])::after": {
232
+ "content": "\"\"",
233
+ "display": "inline-block",
234
+ "width": "0.45em",
235
+ "height": "1.05em",
236
+ "margin-inline-start": "0.2em",
237
+ "vertical-align": "-0.15em",
238
+ "border-radius": "2px",
239
+ "background": "color-mix(in oklab, var(--foreground) 60%, transparent)",
240
+ "animation": "pi-chat-caret 1s steps(2, jump-none) infinite"
241
+ }
242
+ },
243
+ "@keyframes pi-chat-shimmer": {
244
+ "from": {
245
+ "background-position": "100% 0"
246
+ },
247
+ "to": {
248
+ "background-position": "0 0"
249
+ }
250
+ },
251
+ "@keyframes pi-chat-caret": {
252
+ "0%": {
253
+ "opacity": "1"
254
+ },
255
+ "50%": {
256
+ "opacity": "0.15"
257
+ },
258
+ "100%": {
259
+ "opacity": "1"
260
+ }
261
+ }
262
+ },
263
+ "type": "registry:block"
264
+ }