@hachej/boring-ui-kit 0.4.25 → 0.4.27

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.
Files changed (101) hide show
  1. package/README.md +40 -3
  2. package/dist/chat-artifacts.d.ts +157 -0
  3. package/dist/chat-artifacts.js +274 -0
  4. package/dist/chat-dictation.d.ts +27 -0
  5. package/dist/chat-dictation.js +71 -0
  6. package/dist/chat-react-controller.d.ts +25 -0
  7. package/dist/chat-react-controller.js +72 -0
  8. package/dist/chat-react-conversations.d.ts +40 -0
  9. package/dist/chat-react-conversations.js +68 -0
  10. package/dist/chat-react-draft.d.ts +11 -0
  11. package/dist/chat-react-draft.js +91 -0
  12. package/dist/chat-react-remote.d.ts +33 -0
  13. package/dist/chat-react-remote.js +72 -0
  14. package/dist/chat-react-session.d.ts +170 -0
  15. package/dist/chat-react-session.js +367 -0
  16. package/dist/chat-react-transcript.d.ts +39 -0
  17. package/dist/chat-react-transcript.js +123 -0
  18. package/dist/chat-react.d.ts +62 -0
  19. package/dist/chat-react.js +95 -0
  20. package/dist/chat-text.d.ts +131 -0
  21. package/dist/chat-text.js +220 -0
  22. package/dist/chat-view.d.ts +2 -17
  23. package/dist/chat-view.js +1 -0
  24. package/dist/chat-voice-message.d.ts +65 -0
  25. package/dist/chat-voice-message.js +235 -0
  26. package/dist/chat-voice.d.ts +7 -0
  27. package/dist/chat-voice.js +4 -0
  28. package/dist/experience-catalog.d.ts +2 -2
  29. package/dist/experience-region-tree.d.ts +1 -1
  30. package/dist/markdown-editor-labels.d.ts +83 -0
  31. package/dist/markdown-editor-labels.js +75 -0
  32. package/dist/markdown-editor.d.ts +7 -1
  33. package/dist/markdown-editor.js +28 -18
  34. package/dist/markdown-extensions.d.ts +4 -2
  35. package/dist/markdown-extensions.js +2 -2
  36. package/dist/markdown-preserved.d.ts +5 -1
  37. package/dist/markdown-preserved.js +15 -4
  38. package/dist/markdown-proposal-diff.d.ts +3 -1
  39. package/dist/markdown-proposal-diff.js +6 -5
  40. package/dist/run-notifications.d.ts +42 -0
  41. package/dist/run-notifications.js +67 -0
  42. package/dist/shared-chat/index.d.ts +1 -1
  43. package/dist/shared-chat/index.js +5 -4
  44. package/dist/text-draft-controls.d.ts +5 -1
  45. package/dist/text-draft-controls.js +6 -5
  46. package/dist/text-draft-labels.d.ts +26 -0
  47. package/dist/text-draft-labels.js +47 -0
  48. package/dist/voice-attempt.d.ts +33 -0
  49. package/dist/voice-attempt.js +122 -0
  50. package/dist/voice-capture.d.ts +12 -0
  51. package/dist/voice-capture.js +17 -2
  52. package/package.json +14 -2
  53. package/r/agent-target.json +5 -9
  54. package/r/app-shell.json +19 -28
  55. package/r/board-viewer.json +8 -11
  56. package/r/button.json +2 -9
  57. package/r/diagram-viewer.json +0 -5
  58. package/r/dock.json +2 -2
  59. package/r/documents.json +13 -18
  60. package/r/feedback-preview.json +1 -7
  61. package/r/feedback.json +12 -19
  62. package/r/file-tree.json +4 -14
  63. package/r/highlights.json +4 -9
  64. package/r/html-viewer.json +3 -3
  65. package/r/looks-viewer.json +3 -6
  66. package/r/maquette-viewer.json +2 -20
  67. package/r/markdown-editor.json +4 -7
  68. package/r/mockup-viewer.json +2 -5
  69. package/r/pi-ambient.json +11 -19
  70. package/r/pi-app-kinds.json +10 -10
  71. package/r/pi-app.json +17 -27
  72. package/r/pi-artifacts.json +3 -4
  73. package/r/pi-chat-approval.json +2 -5
  74. package/r/pi-chat-attachments.json +2 -4
  75. package/r/pi-chat-markdown.json +3 -5
  76. package/r/pi-chat-mentions.json +2 -3
  77. package/r/pi-chat-pickers.json +2 -4
  78. package/r/pi-chat-plugins.json +11 -11
  79. package/r/pi-chat-question.json +1 -7
  80. package/r/pi-chat-slash.json +3 -6
  81. package/r/pi-chat-subagent.json +3 -8
  82. package/r/pi-chat-voice.json +7 -10
  83. package/r/pi-chat.json +25 -53
  84. package/r/pi-workspace.json +4 -7
  85. package/r/placed-agent.json +4 -5
  86. package/r/provider-setup.json +2 -8
  87. package/r/record-viewer.json +0 -9
  88. package/r/registry.json +182 -403
  89. package/r/requests-board.json +2 -10
  90. package/r/shared-chat.json +10 -24
  91. package/r/task-list-viewer.json +3 -9
  92. package/r/utils.json +14 -2
  93. package/r/version-history.json +3 -5
  94. package/r/viewer-code.json +2 -3
  95. package/r/viewer-frame.json +9 -17
  96. package/r/viewer-html.json +4 -5
  97. package/r/viewer-image.json +3 -4
  98. package/r/viewer-markdown.json +6 -8
  99. package/r/viewer-pdf.json +5 -7
  100. package/r/viewers.json +6 -6
  101. package/r/windows.json +3 -8
package/r/pi-chat.json CHANGED
@@ -4,9 +4,9 @@
4
4
  "title": "Pi chat",
5
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 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 question, approval, sub-agent and artifact cards are separate items (pi-chat-question, pi-chat-approval, pi-chat-subagent, pi-artifacts); without them a question or an approval shows a \"waiting for your answer\" notice, a sub-agent call is an ordinary tool step and no artifact is offered. The optional pi-ambient and pi-workspace blocks build on it.",
6
6
  "dependencies": [
7
- "@hachej/boring-ui-kit@^0.4.25",
8
- "@hachej/boring-files@^0.4.25",
9
- "@hachej/boring-feedback@^0.4.25",
7
+ "@hachej/boring-ui-kit@^0.4.27",
8
+ "@hachej/boring-files@^0.4.27",
9
+ "@hachej/boring-feedback@^0.4.27",
10
10
  "react@^19.0.0",
11
11
  "react-dom@^19.0.0",
12
12
  "@base-ui/react@1.9.0",
@@ -19,41 +19,13 @@
19
19
  "zod@^4.6.5"
20
20
  ],
21
21
  "registryDependencies": [
22
- "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.25/r/utils.json",
23
- "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.25/r/button.json",
24
- "dialog",
25
- "tooltip",
26
- "trace",
27
- "message",
28
- "message-scroller",
29
- "bubble",
30
- "attachment",
31
- "badge",
32
- "alert",
33
- "card",
34
- "spinner",
35
- "collapsible",
36
- "drawer",
37
- "button",
38
- "toggle",
39
- "dropdown-menu",
40
- "empty",
41
- "input",
42
- "input-group",
43
- "popover",
44
- "scroll-area",
45
- "separator",
46
- "sidebar",
47
- "badge",
48
- "item",
49
- "drawer",
50
- "alert",
51
- "avatar"
22
+ "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.27/r/utils.json",
23
+ "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.27/r/button.json"
52
24
  ],
53
25
  "files": [
54
26
  {
55
27
  "path": "registry/pi-chat/activity.tsx",
56
- "content": "'use client';\n\nimport { useState } from 'react';\nimport type { ToolResultMessage } from '@earendil-works/pi-ai';\nimport { AlertCircleIcon, BrainIcon, CheckIcon, CircleSlashIcon } from 'lucide-react';\nimport { Spinner } from '@/components/ui/spinner';\nimport { Trace, TraceCollapsible, TraceCollapsibleContent, TraceCollapsibleTrigger, TraceDescription, TraceIcon, TraceLine, TraceTitle } from '@/components/ui/trace';\nimport { ToolCard, liveLabel } from './tool';\nimport type { ToolStatus } from './tool';\nimport type { Step } from './rows';\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\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\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 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 Thinking({ text, streaming, details }: { readonly text: string; readonly streaming: boolean; readonly details: boolean }) {\n const { labels } = useChatText();\n const [open, setOpen] = useState(false);\n const line = <TraceLine {...(streaming ? { status: 'running' } : {})}>\n <TraceIcon><BrainIcon /></TraceIcon><TraceTitle>{streaming ? labels.thinking : labels.reasoning}</TraceTitle>\n </TraceLine>;\n return <TraceCollapsible data-testid=\"reasoning\" data-state={open ? 'open' : 'closed'} data-streaming={streaming ? 'true' : undefined} open={details && open} onOpenChange={setOpen}>\n {details ? <TraceCollapsibleTrigger className=\"min-h-8 max-sm:min-h-11 pointer-coarse:min-h-11\">{line}</TraceCollapsibleTrigger> : line}\n {details && <TraceCollapsibleContent><div data-testid=\"reasoning-text\" className=\"max-h-72 overflow-y-auto text-sm whitespace-pre-wrap [overflow-wrap:anywhere]\">{text}</div></TraceCollapsibleContent>}\n </TraceCollapsible>;\n}\n\n/** Presentation only: native Pi steps and host cards keep their existing ownership and order. */\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 Icon = state === 'running' ? Spinner : state === 'failed' ? AlertCircleIcon : state === 'stopped' ? CircleSlashIcon : CheckIcon;\n return <Trace data-testid=\"activity\" data-boring=\"activity\" data-state={state} data-open={open ? 'true' : 'false'} className=\"my-1.5\">\n <TraceCollapsible open={open} onOpenChange={setChosen}>\n <TraceCollapsibleTrigger className=\"min-h-8 max-sm:min-h-11 pointer-coarse:min-h-11\">\n <TraceLine {...(state === 'running' ? { status: 'running' } : state === 'failed' ? { status: 'error' } : {})}>\n <TraceIcon><Icon aria-hidden=\"true\" /></TraceIcon>\n <TraceTitle data-testid=\"activity-label\">{header(steps, state, streaming, labels)}</TraceTitle>\n <TraceDescription data-testid=\"activity-count\">{labels.steps(steps.length)}</TraceDescription>\n </TraceLine>\n </TraceCollapsibleTrigger>\n <TraceCollapsibleContent>\n <Trace data-testid=\"activity-steps\">\n {steps.map(step => <div key={step.key} data-testid=\"activity-step\" data-kind={step.kind} data-status={stepStatus(step)}>\n {step.kind === 'tool'\n ? <ToolCard entry={step.entry} details={developer || step.entry.status === 'failed'} {...(onOpenImage ? { onOpenImage } : {})} />\n : <Thinking text={step.text} streaming={step.streaming} details={developer} />}\n </div>)}\n </Trace>\n </TraceCollapsibleContent>\n </TraceCollapsible>\n </Trace>;\n}\n",
28
+ "content": "'use client';\n\nimport { useState } from 'react';\nimport type { ToolResultMessage } from '@earendil-works/pi-ai';\nimport { AlertCircleIcon, BrainIcon, CheckIcon, CircleSlashIcon } from 'lucide-react';\nimport { Spinner } from '@/components/ui/spinner';\nimport { Trace, TraceCollapsible, TraceCollapsibleContent, TraceCollapsibleTrigger, TraceDescription, TraceIcon, TraceLine, TraceTitle } from '@/components/ui/trace';\nimport { ToolCard, liveLabel } from './tool';\nimport type { ToolStatus } from './tool';\nimport type { Step } from './rows';\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\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\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 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 Thinking({ text, streaming, details }: { readonly text: string; readonly streaming: boolean; readonly details: boolean }) {\n const { labels } = useChatText();\n const [open, setOpen] = useState(false);\n const line = <TraceLine {...(streaming ? { status: 'running' } : {})}>\n <TraceIcon><BrainIcon /></TraceIcon><TraceTitle>{streaming ? labels.thinking : labels.reasoning}</TraceTitle>\n </TraceLine>;\n return <TraceCollapsible data-testid=\"reasoning\" data-state={open ? 'open' : 'closed'} data-streaming={streaming ? 'true' : undefined} open={details && open} onOpenChange={setOpen}>\n {details ? <TraceCollapsibleTrigger className=\"min-h-8 max-md:min-h-11 pointer-coarse:min-h-11\">{line}</TraceCollapsibleTrigger> : line}\n {details && <TraceCollapsibleContent><div data-testid=\"reasoning-text\" className=\"max-h-72 overflow-y-auto text-sm whitespace-pre-wrap [overflow-wrap:anywhere]\">{text}</div></TraceCollapsibleContent>}\n </TraceCollapsible>;\n}\n\n/** Presentation only: native Pi steps and host cards keep their existing ownership and order. */\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 Icon = state === 'running' ? Spinner : state === 'failed' ? AlertCircleIcon : state === 'stopped' ? CircleSlashIcon : CheckIcon;\n return <Trace data-testid=\"activity\" data-boring=\"activity\" data-state={state} data-open={open ? 'true' : 'false'} className=\"my-1.5\">\n <TraceCollapsible open={open} onOpenChange={setChosen}>\n <TraceCollapsibleTrigger className=\"min-h-8 max-md:min-h-11 pointer-coarse:min-h-11\">\n <TraceLine {...(state === 'running' ? { status: 'running' } : state === 'failed' ? { status: 'error' } : {})}>\n <TraceIcon><Icon aria-hidden=\"true\" /></TraceIcon>\n <TraceTitle data-testid=\"activity-label\">{header(steps, state, streaming, labels)}</TraceTitle>\n <TraceDescription data-testid=\"activity-count\">{labels.steps(steps.length)}</TraceDescription>\n </TraceLine>\n </TraceCollapsibleTrigger>\n <TraceCollapsibleContent>\n <Trace data-testid=\"activity-steps\">\n {steps.map(step => <div key={step.key} data-testid=\"activity-step\" data-kind={step.kind} data-status={stepStatus(step)}>\n {step.kind === 'tool'\n ? <ToolCard entry={step.entry} details={developer || step.entry.status === 'failed'} {...(onOpenImage ? { onOpenImage } : {})} />\n : <Thinking text={step.text} streaming={step.streaming} details={developer} />}\n </div>)}\n </Trace>\n </TraceCollapsibleContent>\n </TraceCollapsible>\n </Trace>;\n}\n",
57
29
  "type": "registry:component",
58
30
  "target": "components/pi-chat/activity.tsx"
59
31
  },
@@ -65,37 +37,37 @@
65
37
  },
66
38
  {
67
39
  "path": "registry/pi-chat/composer.tsx",
68
- "content": "'use client';\n\nimport { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';\nimport type { ChangeEvent, ClipboardEvent, ComponentProps, DragEvent, KeyboardEvent, ReactNode, Ref } from 'react';\nimport { AlertCircleIcon, FileTextIcon, Loader2Icon, MessageSquarePlusIcon, SlashIcon, XIcon } from 'lucide-react';\nimport { Attachment, AttachmentAction, AttachmentActions, AttachmentContent, AttachmentMedia, AttachmentTitle } from '@/components/ui/attachment';\nimport { Button } from '@/components/ui/button';\nimport { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';\nimport { Input } from '@/components/ui/input';\nimport { InputGroup, InputGroupAddon, InputGroupTextarea } from '@/components/ui/input-group';\nimport { Toggle } from '@/components/ui/toggle';\nimport { hasMention, isLongPaste, mentionToken, mentionTrigger, removeMention, slashItems, slashQuery } from './config';\nimport type { AttachmentsConfig, MentionsConfig, PastedText, PasteToFile, SlashConfig, SlashItem } from './config';\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 annotate toggle (FEEDBACK.md, \"UX\"): one button in the composer's row that arms element targeting on the host's page,\n * and one count chip for the notes taken. Send attaches them. 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 /** The annotate toggle: arms targeting on the page (point mode on touch and compact screens), or stops it when it is on. */\n readonly annotate: () => void;\n /** Annotating is on: the toggle shows pressed. */\n readonly active: boolean;\n /** Notes taken and waiting to be sent with the next message; above zero, Send is allowed with no text. */\n readonly count: number;\n /** Removes the notes (the count chip's remove button). */\n readonly clear: () => void;\n /** Send: the text to send instead, with the notes attached, or why they 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 notes 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 {\n readonly id: string; readonly name: string; readonly state: 'uploading' | 'failed'; readonly error?: string;\n /** A pasted text file: abandons the upload and puts the text back in the message (its restore button, or Ctrl+Z). */\n readonly cancel?: (() => void) | undefined;\n /** The message text right after the paste was accepted: Ctrl+Z restores only while the text is still this (any later edit leaves it alone). */\n readonly restoreWhile?: string | undefined;\n}\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 /** A paste above `pasteToFile`'s limits, taken by the composer: the host uploads it as a file. Absent: pastes stay inline. */\n readonly onPasteText?: ((paste: PastedText) => void) | undefined;\n readonly pasteToFile?: PasteToFile | 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 /** Optional host mode/model chips beside the attach control. */\n readonly chips?: ReactNode;\n /** Optional host context above the input. */\n readonly quote?: ReactNode;\n readonly text: string;\n readonly onText: (text: string) => void;\n readonly attachments: readonly ComposerAttachment[];\n /** Host-owned content contributes to send readiness. */\n readonly hasFiles?: boolean;\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 /** The phone camera sheet (`attachments.Camera`, from `pi-chat-attachments`). Without it there is no Take a photo entry. */\n readonly camera?: AttachmentsConfig['Camera'];\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 /** `card` (default): chips, then full-width text, then a row of controls, in the host's shadcn InputGroup. `pill` puts the text between\n * the controls on one row. `stacked` and `inline` are compatibility values that render as `card`. */\n readonly layout?: 'card' | 'pill' | '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 /** Host controls at the very left edge of the bar, before \"+\" (`PiChat`'s `composerStart`). */\n readonly start?: ReactNode;\n /** A control shown in place of Send while there is nothing to send (WhatsApp's microphone): Send comes back as soon as there is text or a file. */\n readonly whenEmpty?: ReactNode;\n /** The optional Feedback button and chip. */\n readonly feedback?: ComposerFeedback | undefined;\n}\n\n/** The annotate toggle beside the \"+\" menu in both layouts. */\nfunction AnnotateButton({ feedback, disabled }: { readonly feedback: ComposerFeedback; readonly disabled: boolean }) {\n const { labels } = useChatText();\n return <Toggle className=\"min-h-11 min-w-11\" data-testid=\"composer-annotate\" pressed={feedback.active} disabled={disabled}\n aria-label={labels.annotate} title={labels.annotateHint} onPressedChange={() => feedback.annotate()}>\n <MessageSquarePlusIcon data-icon=\"inline-start\" aria-hidden=\"true\" />\n </Toggle>;\n}\n\n/**\n * One chip above the text (a mention, an upload, an attachment or the notes count) as the host's shadcn Attachment. The remove\n * buttons keep a 44px touch target on coarse pointers; negative margins let it extend beyond the chip instead of growing it.\n */\nfunction Chip({ media, image = false, label, actions, ...props }: ComponentProps<typeof Attachment> & { readonly media: ReactNode; readonly image?: boolean; readonly label: ReactNode; readonly actions?: ReactNode }) {\n return <Attachment size=\"xs\" role=\"listitem\" {...props}>\n <AttachmentMedia variant={image ? 'image' : 'icon'}>{media}</AttachmentMedia>\n <AttachmentContent><AttachmentTitle>{label}</AttachmentTitle></AttachmentContent>\n {actions && <AttachmentActions className=\"max-sm:-my-2.5 pointer-coarse:-my-2.5\">{actions}</AttachmentActions>}\n </Attachment>;\n}\n\nfunction RemoveChip({ label, onClick }: { readonly label: string; readonly onClick: () => void }) {\n return <AttachmentAction aria-label={label} title={label} onClick={onClick}><XIcon aria-hidden=\"true\" /></AttachmentAction>;\n}\n\n/** The count chip: how many notes go with the next message, and a way to drop them. */\nfunction NotesChip({ feedback }: { readonly feedback: ComposerFeedback }) {\n const { labels } = useChatText();\n return <Chip data-testid=\"feedback-count\" data-count={feedback.count} media={<MessageSquarePlusIcon aria-hidden=\"true\" />} label={labels.annotateNotes(feedback.count)}\n actions={<AttachmentAction data-testid=\"feedback-count-clear\" aria-label={labels.annotateClear} title={labels.annotateClear} onClick={() => feedback.clear()}><XIcon aria-hidden=\"true\" /></AttachmentAction>} />;\n}\n\n/** Whether a file input's `accept` admits a JPEG photo (empty admits everything). */\nexport function acceptsPhotos(accept: string): boolean {\n const tokens = accept.split(',').map(token => token.trim().toLowerCase()).filter(Boolean);\n return tokens.length === 0 || tokens.some(token => token === 'image/*' || token === '*/*' || token === 'image/jpeg' || token === '.jpg' || token === '.jpeg');\n}\n\n/** True on a touch-first device (a phone or tablet); false on the server, so the menu renders the same there. */\nfunction useCoarsePointer(): boolean {\n const [coarse, setCoarse] = useState(() => globalThis.matchMedia?.('(pointer: coarse)').matches ?? false);\n useEffect(() => {\n const query = globalThis.matchMedia?.('(pointer: coarse)');\n if (!query) return;\n const update = () => setCoarse(query.matches);\n update();\n query.addEventListener?.('change', update);\n return () => query.removeEventListener?.('change', update);\n }, []);\n return coarse;\n}\n\n/** The \"+\" button and the host's shadcn dropdown menu (Attach files, Take a photo, Commands). */\nfunction PlusActions({ disabled, onAttach, onTakePhoto, onCommands, textarea }: { readonly disabled: boolean; readonly onAttach?: (() => void) | undefined; readonly onTakePhoto?: (() => void) | undefined; readonly onCommands?: (() => void) | undefined; readonly textarea: { readonly current: HTMLTextAreaElement | null } }) {\n const { labels, icons } = useChatText();\n const [open, setOpen] = useState(false);\n // Commands puts `/` in the message: focus goes back to the text, not to the \"+\" button.\n const toText = useRef(false);\n useEffect(() => { if (disabled) setOpen(false); }, [disabled]);\n return <DropdownMenu open={open} onOpenChange={setOpen}>\n <DropdownMenuTrigger render={<Button variant=\"ghost\" size=\"icon\" />} data-testid=\"composer-plus\" aria-label={labels.add} title={labels.add} disabled={disabled}>\n <icons.add data-icon=\"inline-start\" aria-hidden=\"true\" /></DropdownMenuTrigger>\n <DropdownMenuContent side=\"top\" align=\"start\" aria-label={labels.add} data-testid=\"composer-plus-menu\" className=\"w-52\"\n finalFocus={() => { const text = toText.current; toText.current = false; return text ? textarea.current : true; }}>\n {onAttach && <DropdownMenuItem data-testid=\"composer-attach\" onClick={onAttach} className=\"max-sm:min-h-11 pointer-coarse:min-h-11\">\n <icons.attach aria-hidden=\"true\" />{labels.attachFiles}</DropdownMenuItem>}\n {onTakePhoto && <DropdownMenuItem data-testid=\"composer-take-photo\" onClick={onTakePhoto} className=\"max-sm:min-h-11 pointer-coarse:min-h-11\">\n <icons.camera aria-hidden=\"true\" />{labels.takePhoto}</DropdownMenuItem>}\n {onCommands && <DropdownMenuItem data-testid=\"composer-commands\" onClick={() => { toText.current = true; onCommands(); }} className=\"max-sm:min-h-11 pointer-coarse:min-h-11\">\n <SlashIcon aria-hidden=\"true\" />{labels.commands}</DropdownMenuItem>}\n </DropdownMenuContent>\n </DropdownMenu>;\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, layout = 'card' } = 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 // The camera sheet lives here, not in the menu: the menu content unmounts as soon as it closes.\n const [cameraOpen, setCameraOpen] = useState(false);\n const coarse = useCoarsePointer();\n // A feature shows only when its config carries the component that draws it (`pi-chat-slash`, `pi-chat-mentions`, `pi-chat-attachments`).\n const Camera = props.camera, Slash = props.slash?.Picker, Mention = props.mentions?.Picker;\n const canPhoto = canAttach && coarse && acceptsPhotos(props.fileAccept) && Camera !== undefined;\n const slash = Slash ? props.slash : undefined, mentions = Mention ? props.mentions : undefined;\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 const resize = () => {\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 };\n resize();\n if (pendingCaret.current !== null) { element.setSelectionRange(pendingCaret.current, pendingCaret.current); element.focus(); pendingCaret.current = null; }\n if (typeof ResizeObserver === 'undefined') return;\n let width = element.clientWidth;\n const observer = new ResizeObserver(() => {\n const next = element.clientWidth;\n if (next === width) return;\n width = next; resize();\n });\n observer.observe(element);\n return () => observer.disconnect();\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 || props.hasFiles || (feedback?.count ?? 0) > 0;\n const canSubmit = hasContent && !sendBlocked && !disabled;\n const onKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {\n props.onKeyDown?.(event);\n if (event.defaultPrevented) return;\n // Ctrl+Z right after a paste that is still uploading puts the pasted text back, instead of undoing the paste in the textarea.\n const undo = (props.uploads ?? []).filter(item => item.state === 'uploading' && item.cancel && item.restoreWhile === props.text).pop();\n if (undo && (event.ctrlKey || event.metaKey) && !event.shiftKey && !event.altKey && event.key.toLowerCase() === 'z') { event.preventDefault(); undo.cancel!(); 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)); return; }\n if (!props.onPasteText) return;\n const pasted = event.clipboardData.getData('text/plain');\n if (!isLongPaste(pasted, props.pasteToFile)) return;\n event.preventDefault();\n props.onPasteText({ text: pasted, start: event.currentTarget.selectionStart, end: event.currentTarget.selectionEnd });\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 chipList = (props.quote || chips.length > 0 || (props.uploads?.length ?? 0) > 0 || (feedback?.count ?? 0) > 0 || attachments.length > 0) && <>\n {props.quote}\n {feedback && feedback.count > 0 && <div role=\"list\" className=\"contents\"><NotesChip feedback={feedback} /></div>}\n {chips.length > 0 && <div role=\"list\" data-testid=\"mention-chips\" aria-label={labels.mentionedFiles} className=\"contents\">\n {chips.map(path => <Chip key={path} data-testid=\"mention-chip\" data-path={path} title={props.mentions?.label?.(path) ?? path} className=\"max-w-full sm:max-w-[16rem]\"\n media={props.mentions?.icon ?? <FileTextIcon aria-hidden=\"true\" />} label={props.mentions?.label?.(path) ?? path} actions={<RemoveChip label={labels.remove(props.mentions?.label?.(path) ?? path)} onClick={() => props.onText(removeMention(text, path))} />} />)}\n </div>}\n {(props.uploads?.length ?? 0) > 0 && <div role=\"list\" data-testid=\"uploads\" aria-label={labels.uploads} className=\"contents\">\n {props.uploads!.map(item => <Chip key={item.id} data-testid=\"upload-chip\" state={item.state === 'failed' ? 'error' : 'uploading'} data-state={item.state} title={item.error ?? item.name} className=\"max-w-full sm:max-w-[20rem]\"\n media={item.state === 'failed' ? <AlertCircleIcon className=\"text-destructive\" aria-hidden=\"true\" /> : <Loader2Icon className=\"animate-spin motion-reduce:animate-none\" aria-hidden=\"true\" />}\n label={item.state === 'failed' ? labels.uploadFailed(item.name, item.error) : labels.uploading(item.name)}\n actions={<>\n {item.cancel && <RemoveChip label={labels.restorePaste} onClick={() => item.cancel!()} />}\n {item.state === 'failed' && <RemoveChip label={labels.dismiss(item.name)} onClick={() => props.onDismissUpload?.(item.id)} />}\n </>} />)}\n </div>}\n {attachments.length > 0 && <div role=\"list\" data-testid=\"attachments\" aria-label={labels.attachments} className=\"contents\">\n {attachments.map(attachment => {\n const src = thumbnail(attachment.mimeType, attachment.data);\n return <Chip key={attachment.id} data-testid=\"attachment\" className=\"max-w-full sm:max-w-[14rem]\" image={!!src}\n media={src ? <img src={src} alt=\"\" /> : <FileTextIcon aria-hidden=\"true\" />} label={attachment.name}\n actions={<RemoveChip label={labels.remove(attachment.name)} onClick={() => props.onRemoveAttachment(attachment.id)} />} />;\n })}\n </div>}\n </>;\n const pill = layout === 'pill';\n const textareaEl = <InputGroupTextarea 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={pill ? 'max-h-52 min-h-0 min-w-0' : 'max-h-52 min-h-11'} />;\n const plus = (canAttach || items.length > 0) && <PlusActions disabled={disabled} textarea={inner} onAttach={canAttach ? () => fileInput.current?.click() : undefined} onTakePhoto={canPhoto ? () => setCameraOpen(true) : undefined} onCommands={items.length > 0 ? openCommands : undefined} />;\n // One child slot either way, so a composer without `start` keeps its exact markup (React ids included).\n const startAndPlus = props.start ? <><div data-testid=\"composer-start\" className=\"flex shrink-0 items-center gap-1\">{props.start}</div>{plus}</> : plus;\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=\"shrink-0\">\n {stopRequested ? <Loader2Icon data-icon=\"inline-start\" className=\"animate-spin motion-reduce:animate-none\" aria-hidden=\"true\" /> : <icons.stop data-icon=\"inline-start\" aria-hidden=\"true\" />}</Button>\n : props.whenEmpty && !hasContent ? <div data-testid=\"composer-when-empty\" className=\"flex shrink-0 items-center\">{props.whenEmpty}</div>\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=\"shrink-0\">\n <icons.send data-icon=\"inline-start\" aria-hidden=\"true\" /></Button>;\n const end = <>\n {props.barStart}\n {props.chips && <div className=\"flex min-w-0 items-center gap-2\">{props.chips}</div>}\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 {!pill && <span className=\"min-w-0 flex-1\" />}\n {props.barEnd && <div data-testid=\"composer-tools\" className=\"flex shrink-0 items-center gap-2\">{props.barEnd}</div>}\n {working && hasContent && <Button variant=\"ghost\" size=\"icon\" data-testid=\"composer-queue\" aria-label={labels.queue} title={labels.queue} disabled={!canSubmit} onClick={props.onSend} className=\"shrink-0\">\n <icons.queue data-icon=\"inline-start\" aria-hidden=\"true\" /></Button>}\n {send}\n </>;\n\n // One shadcn InputGroup: the chips, the text and a row of controls (`card`, also used for the `stacked` and `inline` compatibility\n // values), or one row with the text between the controls (`pill`, chips above it). Its look is the host's; ours is layout only.\n return <form data-testid=\"composer\" data-layout={layout} data-dragging={dragging || undefined} onSubmit={event => { event.preventDefault(); if (canSubmit) props.onSend(); }} onDragOver={drag} onDragLeave={drag} onDrop={drop}\n className={cn('relative flex flex-col gap-2', pill && '@container/composer')}>\n {fileEl}\n {slashOpen && Slash && <Slash query={query!} items={items} onSelect={pickSlash} onDismiss={dismiss} />}\n {mentionOpen && mentions && Mention && <Mention query={trigger!.query} listLabel={mentions.listLabel} renderOption={mentions.renderOption} search={mentions.search} generation={mentions.generation} onSelect={pickMention} onDismiss={dismiss} />}\n {pill && chipList && <div className=\"flex flex-wrap gap-2\">{chipList}</div>}\n {pill ? <InputGroup>\n <InputGroupAddon>{startAndPlus}{feedback && <AnnotateButton feedback={feedback} disabled={disabled} />}</InputGroupAddon>\n {textareaEl}\n <InputGroupAddon align=\"inline-end\" data-testid=\"composer-controls\">{end}</InputGroupAddon>\n </InputGroup> : <InputGroup>\n {chipList && <InputGroupAddon align=\"block-start\" className=\"flex-wrap\">{chipList}</InputGroupAddon>}\n {textareaEl}\n <InputGroupAddon align=\"block-end\" data-testid=\"composer-controls\">\n {startAndPlus}\n {feedback && <AnnotateButton feedback={feedback} disabled={disabled} />}\n {end}\n </InputGroupAddon>\n </InputGroup>}\n {cameraOpen && Camera && <Camera onClose={() => setCameraOpen(false)} onCapture={file => { setCameraOpen(false); props.onPickFiles([file]); }} />}\n </form>;\n}\n",
40
+ "content": "'use client';\n\nimport { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';\nimport type { ChangeEvent, ClipboardEvent, ComponentProps, DragEvent, KeyboardEvent, ReactNode, Ref } from 'react';\nimport { AlertCircleIcon, FileTextIcon, Loader2Icon, MessageSquarePlusIcon, SlashIcon, XIcon } from 'lucide-react';\nimport { Attachment, AttachmentAction, AttachmentActions, AttachmentContent, AttachmentMedia, AttachmentTitle } from '@/components/ui/attachment';\nimport { Button } from '@/components/ui/button';\nimport { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';\nimport { Input } from '@/components/ui/input';\nimport { InputGroup, InputGroupAddon, InputGroupTextarea } from '@/components/ui/input-group';\nimport { Toggle } from '@/components/ui/toggle';\nimport { hasMention, isLongPaste, kindMentionDraft, mentionedPaths, mentionKind, mentionToken, mentionTrigger, removeMention, slashItems, slashQuery, writeKindMentionDraft } from '@hachej/boring-ui-kit/chat-text';\nimport type { PasteToFile, SlashItem } from '@hachej/boring-ui-kit/chat-text';\nimport type { AttachmentsConfig, MentionsConfig, PastedText, SlashConfig } from './config';\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 annotate toggle (FEEDBACK.md, \"UX\"): one button in the composer's row that arms element targeting on the host's page,\n * and one count chip for the notes taken. Send attaches them. The host owns everything else (the registry `feedback` item's\n * `useComposerFeedback` returns this shape). Absent: the composer is unchanged.\n */\nexport interface ComposerFeedback extends ChatSessionFeedback {\n /** The annotate toggle: arms targeting on the page (point mode on touch and compact screens), or stops it when it is on. */\n readonly annotate: () => void;\n /** Annotating is on: the toggle shows pressed. */\n readonly active: boolean;\n /** Notes taken and waiting to be sent with the next message; above zero, Send is allowed with no text. */\n readonly count: number;\n /** Removes the notes (the count chip's remove button). */\n readonly clear: () => void;\n\n}\n\n/** One file being uploaded (or that failed to upload), shown as a chip until it settles or is dismissed. */\nexport type { PendingUpload } from '@hachej/boring-ui-kit/chat-react';\nimport type { PendingUpload, ChatSessionFeedback } from '@hachej/boring-ui-kit/chat-react';\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 /** A paste above `pasteToFile`'s limits, taken by the composer: the host uploads it as a file. Absent: pastes stay inline. */\n readonly onPasteText?: ((paste: PastedText) => void) | undefined;\n readonly pasteToFile?: PasteToFile | 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 /** Optional host mode/model chips beside the attach control. */\n readonly chips?: ReactNode;\n /** Optional host context above the input. */\n readonly quote?: ReactNode;\n readonly text: string;\n readonly onText: (text: string) => void;\n readonly attachments: readonly ComposerAttachment[];\n /** Host-owned content contributes to send readiness. */\n readonly hasFiles?: boolean;\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 /** The phone camera sheet (`attachments.Camera`, from `pi-chat-attachments`). Without it there is no Take a photo entry. */\n readonly camera?: AttachmentsConfig['Camera'];\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 /** `card` (default): chips, then full-width text, then a row of controls, in the host's shadcn InputGroup. `pill` puts the text between\n * the controls on one row. `stacked` and `inline` are compatibility values that render as `card`. */\n readonly layout?: 'card' | 'pill' | '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 /** Host controls at the very left edge of the bar, before \"+\" (`PiChat`'s `composerStart`). */\n readonly start?: ReactNode;\n /** A control shown in place of Send while there is nothing to send (WhatsApp's microphone): Send comes back as soon as there is text or a file. */\n readonly whenEmpty?: ReactNode;\n /** An active capture replaces the editable input and ordinary controls with this one recording row. */\n readonly recording?: ReactNode;\n /** The optional Feedback button and chip. */\n readonly feedback?: ComposerFeedback | undefined;\n}\n\n/** The annotate toggle beside the \"+\" menu in both layouts. */\nfunction AnnotateButton({ feedback, disabled }: { readonly feedback: ComposerFeedback; readonly disabled: boolean }) {\n const { labels } = useChatText();\n return <Toggle className=\"min-h-11 min-w-11\" data-testid=\"composer-annotate\" pressed={feedback.active} disabled={disabled}\n aria-label={labels.annotate} title={labels.annotateHint} onPressedChange={() => feedback.annotate()}>\n <MessageSquarePlusIcon data-icon=\"inline-start\" aria-hidden=\"true\" />\n </Toggle>;\n}\n\n/**\n * One chip above the text (a mention, an upload, an attachment or the notes count) as the host's shadcn Attachment. The remove\n * buttons keep a 44px touch target on coarse pointers; negative margins let it extend beyond the chip instead of growing it.\n */\nfunction Chip({ media, image = false, label, actions, ...props }: ComponentProps<typeof Attachment> & { readonly media: ReactNode; readonly image?: boolean; readonly label: ReactNode; readonly actions?: ReactNode }) {\n return <Attachment size=\"xs\" role=\"listitem\" {...props}>\n <AttachmentMedia variant={image ? 'image' : 'icon'}>{media}</AttachmentMedia>\n <AttachmentContent><AttachmentTitle>{label}</AttachmentTitle></AttachmentContent>\n {actions && <AttachmentActions className=\"max-md:-my-2.5 pointer-coarse:-my-2.5\">{actions}</AttachmentActions>}\n </Attachment>;\n}\n\nfunction RemoveChip({ label, onClick }: { readonly label: string; readonly onClick: () => void }) {\n return <AttachmentAction aria-label={label} title={label} onClick={onClick}><XIcon aria-hidden=\"true\" /></AttachmentAction>;\n}\n\n/** The count chip: how many notes go with the next message, and a way to drop them. */\nfunction NotesChip({ feedback }: { readonly feedback: ComposerFeedback }) {\n const { labels } = useChatText();\n return <Chip data-testid=\"feedback-count\" data-count={feedback.count} media={<MessageSquarePlusIcon aria-hidden=\"true\" />} label={labels.annotateNotes(feedback.count)}\n actions={<AttachmentAction data-testid=\"feedback-count-clear\" aria-label={labels.annotateClear} title={labels.annotateClear} onClick={() => feedback.clear()}><XIcon aria-hidden=\"true\" /></AttachmentAction>} />;\n}\n\n/** Whether a file input's `accept` admits a JPEG photo (empty admits everything). */\nexport function acceptsPhotos(accept: string): boolean {\n const tokens = accept.split(',').map(token => token.trim().toLowerCase()).filter(Boolean);\n return tokens.length === 0 || tokens.some(token => token === 'image/*' || token === '*/*' || token === 'image/jpeg' || token === '.jpg' || token === '.jpeg');\n}\n\n/** True on a touch-first device (a phone or tablet); false on the server, so the menu renders the same there. */\nfunction useCoarsePointer(): boolean {\n const [coarse, setCoarse] = useState(() => globalThis.matchMedia?.('(pointer: coarse)').matches ?? false);\n useEffect(() => {\n const query = globalThis.matchMedia?.('(pointer: coarse)');\n if (!query) return;\n const update = () => setCoarse(query.matches);\n update();\n query.addEventListener?.('change', update);\n return () => query.removeEventListener?.('change', update);\n }, []);\n return coarse;\n}\n\n/** The \"+\" button and the host's shadcn dropdown menu (Attach files, Take a photo, Commands). */\nfunction PlusActions({ disabled, onAttach, onTakePhoto, onCommands, textarea }: { readonly disabled: boolean; readonly onAttach?: (() => void) | undefined; readonly onTakePhoto?: (() => void) | undefined; readonly onCommands?: (() => void) | undefined; readonly textarea: { readonly current: HTMLTextAreaElement | null } }) {\n const { labels, icons } = useChatText();\n const [open, setOpen] = useState(false);\n // Commands puts `/` in the message: focus goes back to the text, not to the \"+\" button.\n const toText = useRef(false);\n // eslint-disable-next-line react-hooks/set-state-in-effect -- a menu left open when the composer gets disabled closes once, after commit\n useEffect(() => { if (disabled) setOpen(false); }, [disabled]);\n return <DropdownMenu open={open} onOpenChange={setOpen}>\n <DropdownMenuTrigger render={<Button variant=\"ghost\" size=\"icon\" />} data-testid=\"composer-plus\" aria-label={labels.add} title={labels.add} disabled={disabled}>\n <icons.add data-icon=\"inline-start\" aria-hidden=\"true\" /></DropdownMenuTrigger>\n <DropdownMenuContent side=\"top\" align=\"start\" aria-label={labels.add} data-testid=\"composer-plus-menu\" className=\"w-52\"\n finalFocus={() => { const text = toText.current; toText.current = false; return text ? textarea.current : true; }}>\n {onAttach && <DropdownMenuItem data-testid=\"composer-attach\" onClick={onAttach} className=\"max-md:min-h-11 pointer-coarse:min-h-11\">\n <icons.attach aria-hidden=\"true\" />{labels.attachFiles}</DropdownMenuItem>}\n {onTakePhoto && <DropdownMenuItem data-testid=\"composer-take-photo\" onClick={onTakePhoto} className=\"max-md:min-h-11 pointer-coarse:min-h-11\">\n <icons.camera aria-hidden=\"true\" />{labels.takePhoto}</DropdownMenuItem>}\n {onCommands && <DropdownMenuItem data-testid=\"composer-commands\" onClick={() => { toText.current = true; onCommands(); }} className=\"max-md:min-h-11 pointer-coarse:min-h-11\">\n <SlashIcon aria-hidden=\"true\" />{labels.commands}</DropdownMenuItem>}\n </DropdownMenuContent>\n </DropdownMenu>;\n}\n\nconst MAX_HEIGHT = 208;\n\n/** Hands the textarea to the caller's ref, a callback or an object. */\nfunction assignRef(ref: Ref<HTMLTextAreaElement>, element: HTMLTextAreaElement | null) {\n if (typeof ref === 'function') ref(element); else if (ref) (ref as { current: HTMLTextAreaElement | null }).current = element;\n}\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 { attachments, working, sendBlocked, disabled, stopRequested, uploading, canAttach, layout = 'card' } = props;\n const draft = kindMentionDraft(props.text, props.mentions);\n const text = draft.text;\n const tokens = useRef(draft.tokens);\n useLayoutEffect(() => { tokens.current = draft.tokens; });\n // An asynchronous slash command must use today's tokens, not restore a chip removed since it began.\n const onText = (next: string) => props.onText(writeKindMentionDraft(next, tokens.current, props.slash?.skills?.map(skill => skill.name)));\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 // eslint-disable-next-line react-hooks/set-state-in-effect -- new text re-arms a dismissed menu once, after commit; the updater keeps the value when nothing changed\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 // The camera sheet lives here, not in the menu: the menu content unmounts as soon as it closes.\n const [cameraOpen, setCameraOpen] = useState(false);\n const coarse = useCoarsePointer();\n // A feature shows only when its config carries the component that draws it (`pi-chat-slash`, `pi-chat-mentions`, `pi-chat-attachments`).\n const Camera = props.camera, Slash = props.slash?.Picker, Mention = props.mentions?.Picker;\n const canPhoto = canAttach && coarse && acceptsPhotos(props.fileAccept) && Camera !== undefined;\n const slash = Slash ? props.slash : undefined, mentions = Mention ? props.mentions : undefined;\n const items = useMemo<SlashItem[]>(() => slash ? slashItems(slash) : [], [slash]);\n const recording = Boolean(props.recording);\n const setRef = (element: HTMLTextAreaElement | null) => {\n inner.current = element;\n assignRef(props.textareaRef, element);\n };\n useLayoutEffect(() => {\n if (recording) return;\n const element = inner.current;\n if (!element) return;\n const resize = () => {\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 };\n resize();\n if (pendingCaret.current !== null) { element.setSelectionRange(pendingCaret.current, pendingCaret.current); element.focus(); pendingCaret.current = null; }\n if (typeof ResizeObserver === 'undefined') return;\n let width = element.clientWidth;\n const observer = new ResizeObserver(() => {\n const next = element.clientWidth;\n if (next === width) return;\n width = next; resize();\n });\n observer.observe(element);\n return () => observer.disconnect();\n }, [text, recording]);\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); 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 onText(rest); setCaret(0);\n inner.current?.focus();\n if (!command) return;\n try { void Promise.resolve(command.run({ text: rest, setText: value => 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 = [...new Set([...(props.mentionPaths ?? []), ...mentionedPaths(props.text).filter(path => mentionKind(path, props.mentions))])].filter(path => hasMention(props.text, path));\n const onChange = (event: ChangeEvent<HTMLTextAreaElement>) => { trackCaret(event.currentTarget); onText(event.currentTarget.value); };\n\n const { feedback } = props;\n const hasContent = props.text.trim().length > 0 || attachments.length > 0 || props.hasFiles || (feedback?.count ?? 0) > 0;\n const canSubmit = hasContent && !sendBlocked && !disabled && !props.recording;\n const onKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {\n props.onKeyDown?.(event);\n if (event.defaultPrevented) return;\n // Ctrl+Z right after a paste that is still uploading puts the pasted text back, instead of undoing the paste in the textarea.\n const undo = (props.uploads ?? []).filter(item => item.state === 'uploading' && item.cancel && item.restoreWhile === props.text).pop();\n if (undo && (event.ctrlKey || event.metaKey) && !event.shiftKey && !event.altKey && event.key.toLowerCase() === 'z') { event.preventDefault(); undo.cancel!(); 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)); return; }\n if (!props.onPasteText) return;\n const pasted = event.clipboardData.getData('text/plain');\n if (!isLongPaste(pasted, props.pasteToFile)) return;\n event.preventDefault();\n props.onPasteText({ text: pasted, start: event.currentTarget.selectionStart, end: event.currentTarget.selectionEnd });\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 chipList = (props.quote || chips.length > 0 || (props.uploads?.length ?? 0) > 0 || (feedback?.count ?? 0) > 0 || attachments.length > 0) && <>\n {props.quote}\n {feedback && feedback.count > 0 && <div role=\"list\" className=\"contents\"><NotesChip feedback={feedback} /></div>}\n {chips.length > 0 && <div role=\"list\" data-testid=\"mention-chips\" aria-label={labels.mentionedFiles} className=\"contents\">\n {chips.map(path => {\n const registered = mentionKind(path, props.mentions);\n const label = registered ? registered.kind.label(registered.path) : props.mentions?.label?.(path) ?? path;\n return <Chip key={path} data-testid=\"mention-chip\" data-path={path} title={label} className=\"max-w-full md:max-w-[16rem]\"\n media={registered?.kind.icon ?? props.mentions?.icon ?? <FileTextIcon aria-hidden=\"true\" />} label={label}\n actions={<RemoveChip label={labels.remove(label)} onClick={() => props.onText(removeMention(props.text, path))} />} />;\n })}\n </div>}\n {(props.uploads?.length ?? 0) > 0 && <div role=\"list\" data-testid=\"uploads\" aria-label={labels.uploads} className=\"contents\">\n {props.uploads!.map(item => <Chip key={item.id} data-testid=\"upload-chip\" state={item.state === 'failed' ? 'error' : 'uploading'} data-state={item.state} title={item.error ?? item.name} className=\"max-w-full md:max-w-[20rem]\"\n media={item.state === 'failed' ? <AlertCircleIcon className=\"text-destructive\" aria-hidden=\"true\" /> : <Loader2Icon className=\"animate-spin motion-reduce:animate-none\" aria-hidden=\"true\" />}\n label={item.state === 'failed' ? labels.uploadFailed(item.name, item.error) : labels.uploading(item.name)}\n actions={<>\n {item.cancel && <RemoveChip label={labels.restorePaste} onClick={() => item.cancel!()} />}\n {item.state === 'failed' && <RemoveChip label={labels.dismiss(item.name)} onClick={() => props.onDismissUpload?.(item.id)} />}\n </>} />)}\n </div>}\n {attachments.length > 0 && <div role=\"list\" data-testid=\"attachments\" aria-label={labels.attachments} className=\"contents\">\n {attachments.map(attachment => {\n const src = thumbnail(attachment.mimeType, attachment.data);\n return <Chip key={attachment.id} data-testid=\"attachment\" className=\"max-w-full md:max-w-[14rem]\" image={!!src}\n media={src ? <img src={src} alt=\"\" /> : <FileTextIcon aria-hidden=\"true\" />} label={attachment.name}\n actions={<RemoveChip label={labels.remove(attachment.name)} onClick={() => props.onRemoveAttachment(attachment.id)} />} />;\n })}\n </div>}\n </>;\n const pill = layout === 'pill';\n const textareaEl = <InputGroupTextarea 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={pill ? 'max-h-52 min-h-0 min-w-0' : 'max-h-52 min-h-11'} />;\n const plus = (canAttach || items.length > 0) && <PlusActions disabled={disabled} textarea={inner} onAttach={canAttach ? () => fileInput.current?.click() : undefined} onTakePhoto={canPhoto ? () => setCameraOpen(true) : undefined} onCommands={items.length > 0 ? openCommands : undefined} />;\n // One child slot either way, so a composer without `start` keeps its exact markup (React ids included).\n const startAndPlus = props.start ? <><div data-testid=\"composer-start\" className=\"flex shrink-0 items-center gap-1\">{props.start}</div>{plus}</> : plus;\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=\"shrink-0\">\n {stopRequested ? <Loader2Icon data-icon=\"inline-start\" className=\"animate-spin motion-reduce:animate-none\" aria-hidden=\"true\" /> : <icons.stop data-icon=\"inline-start\" aria-hidden=\"true\" />}</Button>\n : props.whenEmpty && !hasContent ? <div data-testid=\"composer-when-empty\" className=\"flex shrink-0 items-center\">{props.whenEmpty}</div>\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=\"shrink-0\">\n <icons.send data-icon=\"inline-start\" aria-hidden=\"true\" /></Button>;\n const end = <>\n {props.barStart}\n {props.chips && <div className=\"flex min-w-0 items-center gap-2\">{props.chips}</div>}\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 {!pill && <span className=\"min-w-0 flex-1\" />}\n {props.barEnd && <div data-testid=\"composer-tools\" className=\"flex min-w-0 items-center gap-2\">{props.barEnd}</div>}\n {working && hasContent && <Button variant=\"ghost\" size=\"icon\" data-testid=\"composer-queue\" aria-label={labels.queue} title={labels.queue} disabled={!canSubmit} onClick={props.onSend} className=\"shrink-0\">\n <icons.queue data-icon=\"inline-start\" aria-hidden=\"true\" /></Button>}\n {send}\n </>;\n\n // One shadcn InputGroup: the chips, the text and a row of controls (`card`, also used for the `stacked` and `inline` compatibility\n // values), or one row with the text between the controls (`pill`, chips above it). Its look is the host's; ours is layout only.\n return <form data-testid=\"composer\" data-layout={layout} data-dragging={dragging || undefined} onSubmit={event => { event.preventDefault(); if (canSubmit) props.onSend(); }} onDragOver={drag} onDragLeave={drag} onDrop={drop}\n className={cn('relative flex flex-col gap-2', pill && '@container/composer')}>\n {fileEl}\n {slashOpen && Slash && <Slash query={query!} items={items} onSelect={pickSlash} onDismiss={dismiss} />}\n {mentionOpen && mentions && Mention && <Mention query={trigger!.query} listLabel={mentions.listLabel} renderOption={mentions.renderOption} search={mentions.search} generation={mentions.generation} onSelect={pickMention} onDismiss={dismiss} />}\n {pill && !props.recording && chipList && <div className=\"flex flex-wrap gap-2\">{chipList}</div>}\n {props.recording ? <InputGroup>\n {chipList && <InputGroupAddon align=\"block-start\" className=\"flex-wrap\">{chipList}</InputGroupAddon>}\n <InputGroupAddon align=\"block-end\" data-testid=\"composer-controls\" className=\"w-full\">{props.recording}</InputGroupAddon>\n </InputGroup> : pill ? <InputGroup>\n <InputGroupAddon>{startAndPlus}{feedback && <AnnotateButton feedback={feedback} disabled={disabled} />}</InputGroupAddon>\n {textareaEl}\n <InputGroupAddon align=\"inline-end\" data-testid=\"composer-controls\">{end}</InputGroupAddon>\n </InputGroup> : <InputGroup>\n {chipList && <InputGroupAddon align=\"block-start\" className=\"flex-wrap\">{chipList}</InputGroupAddon>}\n {textareaEl}\n <InputGroupAddon align=\"block-end\" data-testid=\"composer-controls\">\n {startAndPlus}\n {feedback && <AnnotateButton feedback={feedback} disabled={disabled} />}\n {end}\n </InputGroupAddon>\n </InputGroup>}\n {cameraOpen && Camera && <Camera onClose={() => setCameraOpen(false)} onCapture={file => { setCameraOpen(false); props.onPickFiles([file]); }} />}\n </form>;\n}\n",
69
41
  "type": "registry:component",
70
42
  "target": "components/pi-chat/composer.tsx"
71
43
  },
72
44
  {
73
45
  "path": "registry/pi-chat/conversation-files.tsx",
74
- "content": "'use client';\n\nimport { useEffect, useState } from 'react';\nimport { FileTextIcon, ShapesIcon } from 'lucide-react';\nimport { Button } from '@/components/ui/button';\nimport { Drawer, DrawerContent, DrawerTitle, DrawerTrigger } from '@/components/ui/drawer';\nimport { DropdownMenu, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';\nimport { useChatText } from './labels';\n\n/** A conversation's observed file, opened only through the host's existing callback. */\nexport interface ConversationFile {\n readonly id: string;\n readonly name: string;\n readonly open: (() => void) | undefined;\n}\n\n/** Conversation files, not a second workspace: the native menu on desktop and the installed drawer on phones. */\nexport function ConversationFiles({ files }: { readonly files: readonly ConversationFile[] }) {\n const { labels } = useChatText();\n const [open, setOpen] = useState(false);\n const [phone, setPhone] = useState(() => globalThis.matchMedia?.('(max-width: 640px)').matches === true);\n useEffect(() => {\n const media = globalThis.matchMedia?.('(max-width: 640px)');\n if (!media) return;\n const change = () => { setPhone(media.matches); setOpen(false); };\n media.addEventListener('change', change);\n return () => media.removeEventListener('change', change);\n }, []);\n const available = files.filter(file => file.open);\n if (!available.length) return null;\n const trigger = <Button variant=\"outline\" data-testid=\"conversation-files\" className=\"mb-3 max-w-full gap-2\"><ShapesIcon data-icon=\"inline-start\" aria-hidden=\"true\" />{labels.artifacts}<span className=\"text-muted-foreground\">· {available.length}</span></Button>;\n const label = (file: ConversationFile) => <><FileTextIcon data-icon=\"inline-start\" className=\"shrink-0\" aria-hidden=\"true\" /><span className=\"min-w-0 truncate\">{file.name}</span></>;\n const select = (file: ConversationFile) => { setOpen(false); file.open?.(); };\n return phone ? <Drawer open={open} onOpenChange={setOpen} showSwipeHandle><DrawerTrigger render={trigger} /><DrawerContent data-testid=\"conversation-files-list\" className=\"pi-chat max-h-[80dvh]\">\n <div className=\"flex min-h-0 flex-col px-2 pt-2 pb-[env(safe-area-inset-bottom)]\"><div className=\"px-2\"><DrawerTitle className=\"m-0\">{labels.artifacts}</DrawerTitle></div>\n <ul className=\"m-0 max-h-[60dvh] list-none overflow-y-auto p-0\">{available.map(file => <li key={file.id} className=\"flex min-h-12\"><Button variant=\"ghost\" size=\"sm\" data-testid=\"conversation-file\" data-file={file.id} className=\"h-auto w-full justify-start gap-2 text-start\" onClick={() => select(file)}>{label(file)}</Button></li>)}</ul>\n </div></DrawerContent></Drawer>\n : <DropdownMenu open={open} onOpenChange={setOpen}><DropdownMenuTrigger render={trigger} /><DropdownMenuContent side=\"top\" align=\"start\" sideOffset={6} data-testid=\"conversation-files-list\" aria-label={labels.artifacts} onKeyDown={event => { if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); setOpen(false); } }} className=\"pi-chat w-80 max-w-[calc(100vw-32px)]\">\n <DropdownMenuGroup className=\"max-h-[60dvh] overflow-y-auto\"><DropdownMenuLabel>{labels.artifacts}</DropdownMenuLabel>\n {available.map(file => <DropdownMenuItem key={file.id} data-testid=\"conversation-file\" data-file={file.id} className=\"min-h-8 pointer-coarse:min-h-12\" onClick={() => select(file)}>{label(file)}</DropdownMenuItem>)}\n </DropdownMenuGroup></DropdownMenuContent></DropdownMenu>;\n}\n",
46
+ "content": "'use client';\n\nimport { useEffect, useState } from 'react';\nimport { FileTextIcon, ShapesIcon } from 'lucide-react';\nimport { Button } from '@/components/ui/button';\nimport { Drawer, DrawerContent, DrawerTitle, DrawerTrigger } from '@/components/ui/drawer';\nimport { DropdownMenu, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';\nimport { useChatText } from './labels';\nimport { usePhone } from '../utils/use-media';\n\n/** A conversation's observed file, opened only through the host's existing callback. */\nexport type { ConversationFile } from '@hachej/boring-ui-kit/chat-react';\nimport type { ConversationFile } from '@hachej/boring-ui-kit/chat-react';\n\n/** Conversation files, not a second workspace: the native menu on desktop and the installed drawer on phones. */\nexport function ConversationFiles({ files }: { readonly files: readonly ConversationFile[] }) {\n const { labels } = useChatText();\n const [open, setOpen] = useState(false);\n const phone = usePhone();\n // eslint-disable-next-line react-hooks/set-state-in-effect -- switching presentation closes the old menu once, after commit\n useEffect(() => { setOpen(false); }, [phone]);\n const available = files.filter(file => file.open);\n if (!available.length) return null;\n const trigger = <Button variant=\"outline\" data-testid=\"conversation-files\" className=\"mb-3 max-w-full gap-2\"><ShapesIcon data-icon=\"inline-start\" aria-hidden=\"true\" />{labels.artifacts}<span className=\"text-muted-foreground\">· {available.length}</span></Button>;\n const label = (file: ConversationFile) => <><FileTextIcon data-icon=\"inline-start\" className=\"shrink-0\" aria-hidden=\"true\" /><span className=\"min-w-0 truncate\">{file.name}</span></>;\n const select = (file: ConversationFile) => { setOpen(false); file.open?.(); };\n return phone ? <Drawer open={open} onOpenChange={setOpen} showSwipeHandle><DrawerTrigger render={trigger} /><DrawerContent data-testid=\"conversation-files-list\" className=\"pi-chat max-h-[80dvh]\">\n <div className=\"flex min-h-0 flex-col px-2 pt-2 pb-[env(safe-area-inset-bottom)]\"><div className=\"px-2\"><DrawerTitle className=\"m-0\">{labels.artifacts}</DrawerTitle></div>\n <ul className=\"m-0 max-h-[60dvh] list-none overflow-y-auto p-0\">{available.map(file => <li key={file.id} className=\"flex min-h-12\"><Button variant=\"ghost\" size=\"sm\" data-testid=\"conversation-file\" data-file={file.id} className=\"h-auto w-full justify-start gap-2 text-start\" onClick={() => select(file)}>{label(file)}</Button></li>)}</ul>\n </div></DrawerContent></Drawer>\n : <DropdownMenu open={open} onOpenChange={setOpen}><DropdownMenuTrigger render={trigger} /><DropdownMenuContent side=\"top\" align=\"start\" sideOffset={6} data-testid=\"conversation-files-list\" aria-label={labels.artifacts} onKeyDown={event => { if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); setOpen(false); } }} className=\"pi-chat w-80 max-w-[calc(100vw-32px)]\">\n <DropdownMenuGroup className=\"max-h-[60dvh] overflow-y-auto\"><DropdownMenuLabel>{labels.artifacts}</DropdownMenuLabel>\n {available.map(file => <DropdownMenuItem key={file.id} data-testid=\"conversation-file\" data-file={file.id} className=\"min-h-8 pointer-coarse:min-h-12\" onClick={() => select(file)}>{label(file)}</DropdownMenuItem>)}\n </DropdownMenuGroup></DropdownMenuContent></DropdownMenu>;\n}\n",
75
47
  "type": "registry:component",
76
48
  "target": "components/pi-chat/conversation-files.tsx"
77
49
  },
78
50
  {
79
51
  "path": "registry/pi-chat/config.ts",
80
- "content": "import type { ComponentType, ReactNode } from 'react';\nimport type { ToolCall, ToolResultMessage } from '@earendil-works/pi-ai';\nimport type { ChatController } from '@hachej/boring-ui-kit/native-chat';\nimport type { ApprovalDecision, ArtifactDetect, ArtifactRecognise, ChatArtifact, SubagentRenderer as ViewSubagentRenderer } from '@hachej/boring-ui-kit/chat-view';\nimport type { BlockAction } from '../button/actions';\nimport type { ChatLabels } from './labels';\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. The component that draws a feature comes from its own\n * registry item and rides on the config (`Picker`, `Camera`, `useRecorder` with `Button` and `Bubble`): without it the feature is\n * simply not offered (no menu, no pill, no camera entry, no record button). `withChatPlugins` of `pi-chat-plugins` fills them all in.\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 /** The `/` menu (`SlashPicker` of `pi-chat-slash`). Without it there is no `/` menu and no Commands entry. */\n readonly Picker?: ComponentType<SlashPickerProps> | undefined;\n}\n\nexport interface MentionResult { readonly path: string; readonly kind?: 'file' | 'directory'; readonly label?: string }\nexport interface MentionsConfig {\n /** Accessible name and optional option/media presentation for a host catalog. */\n readonly listLabel?: string;\n readonly icon?: ReactNode;\n readonly renderOption?: (item: MentionResult, query: string) => ReactNode;\n readonly label?: (id: string) => string;\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 /** Sent-message rendering, independent of the composer's token presentation. */\n readonly renderSent?: ((path: string) => ReactNode | undefined) | undefined;\n /**\n * Upload bytes through the host's provider. Image cards read thumbnails; voice bubbles read audio only on Play.\n * Thumbnails accept png, jpeg, gif and webp. Audio must retain its recorded audio MIME type.\n */\n readonly preview?: PreviewRead | undefined;\n /** Optional authorized playback URL, requested only on Play; otherwise voice audio uses `preview`. */\n readonly audioUrl?: AudioUrlRead | undefined;\n /** The `@` picker (`MentionPicker` of `pi-chat-mentions`). Without it typing `@` opens nothing. */\n readonly Picker?: ComponentType<MentionPickerProps> | undefined;\n}\nexport type AudioUrlRead = (path: string, signal: AbortSignal) => Promise<string | undefined>;\n/** Reads an upload for its thumbnail or lazy voice playback: its media type and base64 data, or undefined. */\nexport type PreviewRead = (path: string, signal: AbortSignal) => Promise<{ readonly mimeType: string; readonly data: string } | undefined>;\n\n/** Paste-to-file thresholds: a paste with more characters or more lines than these becomes a file. Defaults 2000 and 40. */\nexport interface PasteToFile { readonly minChars?: number | undefined; readonly minLines?: number | undefined }\n/** A paste the composer took, with the textarea range it replaces (restored if the upload is cancelled). */\nexport interface PastedText { readonly text: string; readonly start: number; readonly end: number }\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 instead of a path mention when both are supplied. */\n readonly image?: { readonly data: string; readonly mimeType: string };\n readonly name: string;\n}\nexport interface VoiceMessageConfig {\n readonly transcribe: (audio: Blob, signal: AbortSignal) => Promise<string>;\n /** Capture limit (default five minutes). Upload and send still wait for release. */\n readonly maxMs?: number;\n /** Same workspace upload contract as `attachments.upload`, used instead when supplied. Preserve the voice- filename prefix. */\n readonly upload?: AttachmentsConfig['upload'];\n /** The recorder (`useVoiceMessage` of `pi-chat-voice`). Without it there is no voice message: no button, no pending bubble. */\n readonly useRecorder?: VoiceRecorderHook | undefined;\n /** The hold-to-record button at the end of the composer bar (`VoiceMessageButton` of `pi-chat-voice`). */\n readonly Button?: ComponentType<VoiceMessageButtonProps> | undefined;\n /** A voice message on its way: recording, transcribing, uploading (`PendingVoiceBubble` of `pi-chat-voice`). */\n readonly Bubble?: ComponentType<PendingVoiceBubbleProps> | undefined;\n}\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 /** The full-screen camera the attach menu opens on a phone (`CameraSheet` of `pi-chat-attachments`). Without it there is no Take a photo entry. */\n readonly Camera?: ComponentType<CameraSheetProps> | undefined;\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 * Sum of the model rounds that form the reply (ms): Pi's own `AssistantMessage.durationMs`, measured monotonically\n * and kept in the transcript. It excludes queue time, 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 /** The one model-and-effort pill (`ModelEffortPicker` of `pi-chat-pickers`; `effort.Picker` is used when only it is set). Without one there is no pill. */\n readonly Picker?: ComponentType<ModelEffortPickerProps> | undefined;\n}\nexport interface EffortConfig {\n readonly options: readonly string[];\n readonly change: (level: string) => Promise<void>;\n /** The one model-and-effort pill, when `model` does not carry one (`ModelEffortPicker` of `pi-chat-pickers`). */\n readonly Picker?: ComponentType<ModelEffortPickerProps> | undefined;\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\n/** Upload paths are `uploads/<name>`: the attachments of a message, shown as cards rather than as text. */\nexport const isUploadPath = (path: string): boolean => path.startsWith('uploads/');\n\nexport type FileKind = 'document' | 'image' | 'pdf' | 'sheet' | 'slides' | 'audio' | 'file';\nconst KIND_BY_EXTENSION: Readonly<Record<string, FileKind>> = {\n png: 'image', jpg: 'image', jpeg: 'image', gif: 'image', webp: 'image', svg: 'image', bmp: 'image', avif: 'image',\n pdf: 'pdf',\n webm: 'audio', ogg: 'audio', m4a: 'audio', mp4: 'audio', mp3: 'audio', wav: 'audio',\n csv: 'sheet', tsv: 'sheet', xls: 'sheet', xlsx: 'sheet', xlsm: 'sheet', ods: 'sheet', numbers: 'sheet',\n ppt: 'slides', pptx: 'slides', odp: 'slides', key: 'slides',\n md: 'document', markdown: 'document', txt: 'document', doc: 'document', docx: 'document', odt: 'document', rtf: 'document',\n};\n/** The card's kind, from the extension alone. */\nexport function fileKind(path: string): FileKind {\n const extension = /\\.([^./]+)$/.exec(path)?.[1]?.toLowerCase() ?? '';\n return KIND_BY_EXTENSION[extension] ?? 'file';\n}\n/** Recorded voice uses a reserved upload filename prefix; other audio remains a plain file card. */\nexport const isVoicePath = (path: string): boolean => /^uploads\\/voice-[^/]+$/.test(path) && fileKind(path) === 'audio';\n\n/** The name a card shows: the upload's file name without the random suffix `uploadPath` adds (`report-1a2b3c4d.pdf` is `report.pdf`). */\nexport function displayName(path: string): string {\n const name = path.slice(path.lastIndexOf('/') + 1);\n return name.replace(/-[0-9a-f]{8}(?=\\.[^.]*$|$)/i, '');\n}\n\n/**\n * The pieces a message shows once `hidden` ones are taken out: a space that a removed piece leaves at a join is dropped, and the ends are\n * trimmed where it was. The message's own text is not changed, only what the bubble draws.\n */\nexport function visibleParts(parts: readonly Piece[], hidden: (part: Piece) => boolean): Piece[] {\n const out: Piece[] = [];\n let gap = false;\n for (const part of parts) {\n if (hidden(part)) { gap = true; continue; }\n const prev = out[out.length - 1];\n const joins = gap && part.kind === undefined && (prev === undefined || (prev.kind === undefined && /\\s$/.test(prev.text)));\n out.push(joins ? { text: part.text.replace(/^\\s+/, '') } : part);\n gap = false;\n }\n const last = out[out.length - 1];\n if (gap && last && last.kind === undefined) out[out.length - 1] = { text: last.text.replace(/\\s+$/, '') };\n return out.filter(part => part.kind !== undefined || part.text !== '');\n}\n\n/** Whether pasted text is long enough to become a file. `more` than the limits: the characters, or the lines, of the text. */\nexport function isLongPaste(text: string, limits: PasteToFile = {}): boolean {\n const { minChars = 2000, minLines = 40 } = limits;\n return text.length > minChars || text.split('\\n').length > minLines;\n}\n/** Markdown in pasted text: a heading, a list or quote item, a fence, a table row, emphasis or a link. Anything else is plain text. */\nexport function looksLikeMarkdown(text: string): boolean {\n return /^\\s{0,3}(#{1,6}\\s|[-*+]\\s|\\d+[.)]\\s|>\\s|```|~~~)/m.test(text) || /\\*\\*[^*\\n]+\\*\\*|\\]\\([^)\\n]+\\)|^\\|.*\\|\\s*$/m.test(text);\n}\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[]; readonly uploads?: boolean }): 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 || options.uploads) {\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 || (!options.mentions && !isUploadPath(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\n/** Props of the slash picker that `SlashConfig.Picker` carries. */\nexport interface SlashPickerProps {\n readonly query: string;\n readonly items: readonly SlashItem[];\n readonly onSelect: (item: SlashItem) => void;\n readonly onDismiss: () => void;\n}\n\n/** Props of the mention picker that `MentionsConfig.Picker` carries. */\nexport interface MentionPickerProps {\n readonly query: string;\n readonly listLabel?: MentionsConfig['listLabel'];\n readonly renderOption?: MentionsConfig['renderOption'];\n readonly generation?: MentionsConfig['generation'];\n readonly search: MentionsConfig['search'];\n readonly onSelect: (path: string) => void;\n readonly onDismiss: () => void;\n}\n\n/** Props of the model and effort picker that `ModelConfig.Picker` or `EffortConfig.Picker` carries. */\nexport interface ModelEffortPickerProps {\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\nexport type VoicePhase = 'starting' | 'recording' | 'processing' | 'transcribe-failed' | 'upload-failed' | 'sending' | 'unconfirmed' | 'blocked';\n/** A voice message on its way: recorded, then transcribed, uploaded and sent. */\nexport interface PendingVoice {\n readonly id: number;\n readonly path: string | undefined;\n readonly phase: VoicePhase;\n readonly seconds: number;\n readonly retry: () => void;\n readonly audioOnly: (() => void) | undefined;\n readonly discard: () => void;\n}\n/** The recorder the chat hands to the voice button. */\nexport interface VoiceMessageHandle {\n readonly canStart: boolean;\n readonly phase: VoicePhase | 'idle';\n readonly seconds: number;\n readonly captureSequence: number;\n readonly problem: string | undefined;\n readonly pending: readonly PendingVoice[];\n readonly start: () => void;\n readonly finish: () => void;\n readonly cancel: () => void;\n}\n/** Props of the hold-to-record button that `VoiceMessageConfig.Button` carries. */\n/** `primary`: the button stands in for Send (`voiceReplacesSend`), so it takes Send's primary look. */\nexport interface VoiceMessageButtonProps { readonly voice: VoiceMessageHandle; readonly disabled?: boolean; readonly primary?: boolean }\n/** Props of a pending voice message bubble that `VoiceMessageConfig.Bubble` carries. */\nexport interface PendingVoiceBubbleProps { readonly pending: PendingVoice | undefined }\n/** What the chat hands its recorder (`VoiceMessageConfig.useRecorder`). `config` is undefined when voice is off. */\nexport interface VoiceRecorderOptions {\n readonly controller: ChatController | undefined;\n readonly config: VoiceMessageConfig | undefined;\n readonly attachments?: AttachmentsConfig | undefined;\n readonly labels: ChatLabels;\n readonly admitted?: (() => void) | undefined;\n readonly activeController?: { readonly current: ChatController } | undefined;\n}\n/** A React hook: the chat calls it on every render of a mounted chat (a new hook remounts the chat). */\nexport type VoiceRecorderHook = (options: VoiceRecorderOptions) => VoiceMessageHandle;\n\n/** Props of the phone camera sheet that `AttachmentsConfig.Camera` carries. */\nexport interface CameraSheetProps {\n /** The photo, as a JPEG File scaled to at most `CAMERA_MAX_SIDE` on its longest side (or the phone camera's own file, from the fallback). */\n readonly onCapture: (file: File) => void;\n readonly onClose: () => void;\n /** Opens the camera; defaults to the browser's, when it has one. */\n readonly getUserMedia?: ((constraints: MediaStreamConstraints) => Promise<MediaStream>) | undefined;\n}\n\n/** A `/command` a settled reply may turn into a button (`commandMentions`; drawn by a text renderer such as `pi-chat-markdown`). */\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\n/** A recording's length as m:ss. */\nexport const voiceClock = (seconds: number) => `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`;\n\n/*\n * The cards of a reply are items too (`pi-chat-question`, `pi-chat-approval`, `pi-chat-subagent`, `pi-artifacts`). The core keeps only what\n * it needs to place them: the props each card receives, and a visible \"waiting for your answer\" notice when a question or an approval has\n * no card, so a run never waits silently. `withChatPlugins` of `pi-chat-plugins` plugs every card in.\n */\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 };\n/** `ask_user` calls are question rows; `ApprovalDecision` is what `requireApproval` records (both owned by the kit's chat view). */\nexport { ASK_USER_TOOL } from '@hachej/boring-ui-kit/chat-view';\nexport type { ApprovalDecision } from '@hachej/boring-ui-kit/chat-view';\n\n/** Props of the question card that `ChatCards.question` carries (`QuestionCard` of `pi-chat-question`). */\nexport interface QuestionCardProps {\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/** Props of the approval card that `ChatCards.approval` carries (`ApprovalCard` of `pi-chat-approval`). Answering uses the host's `answer`. */\nexport interface ApprovalCardProps {\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?: ApprovalDecision | 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/**\n * Draws a tool call that ran a sub-agent (`subagentCard` of `pi-chat-subagent`), from the details its running slot published (`details`)\n * or that it finished with. Undefined: the call is not a sub-agent call and stays an ordinary tool step.\n */\nexport type SubagentRenderer = ViewSubagentRenderer<ReactNode>;\n\n/** The cards the chat draws for a human decision or a sub-agent. Each one left out has no card (see `PiChat`'s `cards`). */\nexport interface ChatCards {\n /** An `ask_user` question (`QuestionCard` of `pi-chat-question`). Without it the chat says it waits for an answer, with no answer UI. */\n readonly question?: ComponentType<QuestionCardProps> | undefined;\n /** A call gated by `requireApproval` (`ApprovalCard` of `pi-chat-approval`). Without it the chat says it waits for an answer, with no answer UI. */\n readonly approval?: ComponentType<ApprovalCardProps> | undefined;\n /** A sub-agent call (`subagentCard` of `pi-chat-subagent`). Without it the call is an ordinary tool step. */\n readonly subagent?: SubagentRenderer | undefined;\n}\n\n/** An artifact a tool call made, as the chat places it (owned by the kit's chat view). */\nexport type { ChatArtifact };\n/** Props of the artifact card that `ArtifactsConfig.Card` carries (`PluggedArtifactCard` of `pi-artifacts`). */\nexport interface ChatArtifactCardProps {\n readonly artifact: ChatArtifact;\n readonly open: boolean;\n readonly onOpen: (() => void) | undefined;\n readonly kinds: readonly unknown[] | undefined;\n}\n/**\n * Artifact cards, as the core sees `ArtifactsConfig` of `pi-artifacts`: the host's opener and the item's `recognise` and `Card`. Without\n * `recognise` and `Card` no artifact is offered: the calls stay ordinary tool steps.\n */\nexport interface ChatArtifactsConfig {\n readonly kinds?: readonly unknown[] | undefined;\n readonly open: (artifact: never) => void;\n readonly isOpen?: ((artifact: never) => boolean) | undefined;\n readonly detect?: ArtifactDetect | undefined;\n /** The artifact a call made, or that a running call (`running`) is making; undefined for any other call. */\n readonly recognise?: ArtifactRecognise | undefined;\n readonly Card?: ComponentType<ChatArtifactCardProps> | undefined;\n}\n",
52
+ "content": "import type { ComponentType, ReactNode } from 'react';\nimport type { ToolCall, ToolResultMessage } from '@earendil-works/pi-ai';\nimport type { SlashItem } from '@hachej/boring-ui-kit/chat-text';\nimport type { VoiceMessageConfig as KitVoiceMessageConfig, PendingVoice, VoiceMessageHandle, VoiceRecorderOptions as KitVoiceRecorderOptions } from '@hachej/boring-ui-kit/chat-react/voice';\nexport type { PendingVoice, VoiceMessageHandle, VoicePhase } from '@hachej/boring-ui-kit/chat-react/voice';\nimport type { ApprovalDecision, ArtifactDetect, ArtifactRecognise, ChatArtifact, SubagentRenderer as ViewSubagentRenderer } from '@hachej/boring-ui-kit/chat-view';\nimport type { BlockAction } from '../button/actions';\nimport type { ChatLabels } from './labels';\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. The component that draws a feature comes from its own\n * registry item and rides on the config (`Picker`, `Camera`, `useRecorder` with `Button` and `Bubble`): without it the feature is\n * simply not offered (no menu, no pill, no camera entry, no record button). `withChatPlugins` of `pi-chat-plugins` fills them all in.\n */\n\n/** Where a `/` menu entry comes from (the kit's `chat-text`). */\nexport type { SlashSource } from '@hachej/boring-ui-kit/chat-text';\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 /** The `/` menu (`SlashPicker` of `pi-chat-slash`). Without it there is no `/` menu and no Commands entry. */\n readonly Picker?: ComponentType<SlashPickerProps> | undefined;\n}\n\nexport interface MentionResult { readonly path: string; readonly kind?: 'file' | 'directory'; readonly label?: string }\nexport interface MentionKind {\n readonly label: (path: string) => string;\n readonly icon: ReactNode;\n readonly open?: ((path: string) => void) | undefined;\n readonly renderSent?: ((path: string) => ReactNode | undefined) | undefined;\n}\nexport interface MentionsConfig {\n /** App mentions use `@prefix:path` (or the existing quoted token for spaces). Prefixes match [a-z][a-z0-9-]*. No picker is required. */\n readonly kinds?: Readonly<Record<string, MentionKind>> | undefined;\n /** Accessible name and optional option/media presentation for a host catalog. */\n readonly listLabel?: string;\n readonly icon?: ReactNode;\n readonly renderOption?: (item: MentionResult, query: string) => ReactNode;\n readonly label?: (id: string) => string;\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 /** Sent-message rendering, independent of the composer's token presentation. */\n readonly renderSent?: ((path: string) => ReactNode | undefined) | undefined;\n /**\n * Upload bytes through the host's provider. Image cards read thumbnails; voice bubbles read audio only on Play.\n * Thumbnails accept png, jpeg, gif and webp. Audio must retain its recorded audio MIME type.\n */\n readonly preview?: PreviewRead | undefined;\n /** Optional authorized playback URL, requested only on Play; otherwise voice audio uses `preview`. */\n readonly audioUrl?: AudioUrlRead | undefined;\n /** The `@` picker (`MentionPicker` of `pi-chat-mentions`). Without it typing `@` opens nothing. */\n readonly Picker?: ComponentType<MentionPickerProps> | undefined;\n}\nexport type AudioUrlRead = (path: string, signal: AbortSignal) => Promise<string | undefined>;\n/** Reads an upload for its thumbnail or lazy voice playback: its media type and base64 data, or undefined. */\nexport type PreviewRead = (path: string, signal: AbortSignal) => Promise<{ readonly mimeType: string; readonly data: string } | undefined>;\n\n/** Paste-to-file thresholds (the kit's `chat-text`): a paste with more characters or more lines than these becomes a file. */\nexport type { PasteToFile } from '@hachej/boring-ui-kit/chat-text';\n/** A paste the composer took, with the textarea range it replaces (restored if the upload is cancelled). */\n// Compatibility exports for one release; session contracts are owned by the kit.\nexport type { PastedText, UploadResult, ModelRef } from '@hachej/boring-ui-kit/chat-react';\nimport type { UploadResult, ModelRef } from '@hachej/boring-ui-kit/chat-react';\nexport interface VoiceMessageConfig extends KitVoiceMessageConfig {\n /** Same workspace upload contract as `attachments.upload`, used instead when supplied. Preserve the voice- filename prefix. */\n readonly upload?: AttachmentsConfig['upload'];\n /** The recorder (`useVoiceMessage` of `pi-chat-voice`). Without it there is no voice message: no button, no pending bubble. */\n readonly useRecorder?: VoiceRecorderHook | undefined;\n /** The hold-to-record button at the end of the composer bar (`VoiceMessageButton` of `pi-chat-voice`). */\n readonly Button?: ComponentType<VoiceMessageButtonProps> | undefined;\n /** A voice message on its way: recording, transcribing, uploading (`PendingVoiceBubble` of `pi-chat-voice`). */\n readonly Bubble?: ComponentType<PendingVoiceBubbleProps> | undefined;\n}\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 /** The full-screen camera the attach menu opens on a phone (`CameraSheet` of `pi-chat-attachments`). Without it there is no Take a photo entry. */\n readonly Camera?: ComponentType<CameraSheetProps> | undefined;\n}\n\n// Compatibility type export for one release.\nexport type { ConversationItem } from '@hachej/boring-ui-kit/chat-react';\nimport type { ConversationItem } from '@hachej/boring-ui-kit/chat-react';\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 * Sum of the model rounds that form the reply (ms): Pi's own `AssistantMessage.durationMs`, measured monotonically\n * and kept in the transcript. It excludes queue time, 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 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 /** The one model-and-effort pill (`ModelEffortPicker` of `pi-chat-pickers`; `effort.Picker` is used when only it is set). Without one there is no pill. */\n readonly Picker?: ComponentType<ModelEffortPickerProps> | undefined;\n}\nexport interface EffortConfig {\n readonly options: readonly string[];\n readonly change: (level: string) => Promise<void>;\n /** The one model-and-effort pill, when `model` does not carry one (`ModelEffortPicker` of `pi-chat-pickers`). */\n readonly Picker?: ComponentType<ModelEffortPickerProps> | undefined;\n}\n\n/*\n * The text grammar (slash menu, `@mention` tokens, message pieces, file kinds, paste and draft rules) is the kit's `chat-text`; it is\n * re-exported here so the items that import it from `pi-chat/config` keep compiling.\n */\nexport { appendToDraft, displayName, fileKind, hasMention, isLongPaste, isUploadPath, isVoicePath, looksLikeMarkdown, MENTION_TOKEN, mentionedPaths, mentionKind, mentionToken, mentionTrigger, pieces, prependToDraft, removeMention, slashGroup, slashItems, slashQuery, visibleParts, withoutKindMentions, withoutMentions } from '@hachej/boring-ui-kit/chat-text';\nexport type { FileKind, MentionTrigger, Piece, SlashItem } from '@hachej/boring-ui-kit/chat-text';\n\n/** Props of the slash picker that `SlashConfig.Picker` carries. */\nexport interface SlashPickerProps {\n readonly query: string;\n readonly items: readonly SlashItem[];\n readonly onSelect: (item: SlashItem) => void;\n readonly onDismiss: () => void;\n}\n\n/** Props of the mention picker that `MentionsConfig.Picker` carries. */\nexport interface MentionPickerProps {\n readonly query: string;\n readonly listLabel?: MentionsConfig['listLabel'];\n readonly renderOption?: MentionsConfig['renderOption'];\n readonly generation?: MentionsConfig['generation'];\n readonly search: MentionsConfig['search'];\n readonly onSelect: (path: string) => void;\n readonly onDismiss: () => void;\n}\n\n/** Props of the model and effort picker that `ModelConfig.Picker` or `EffortConfig.Picker` carries. */\nexport interface ModelEffortPickerProps {\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\n/** Props of the tap-to-record button that `VoiceMessageConfig.Button` carries. */\n/** `primary`: the button stands in for Send (`voiceReplacesSend`), so it takes Send's primary look. */\nexport interface VoiceMessageButtonProps {\n readonly voice: VoiceMessageHandle;\n readonly disabled?: boolean;\n readonly primary?: boolean;\n readonly testId?: string;\n}\n/** Props of a pending voice message bubble that `VoiceMessageConfig.Bubble` carries. */\nexport interface PendingVoiceBubbleProps { readonly pending: PendingVoice | undefined }\n/** What the chat hands its recorder (`VoiceMessageConfig.useRecorder`). `config` is undefined when voice is off. */\nexport interface VoiceRecorderOptions extends KitVoiceRecorderOptions {\n readonly config: VoiceMessageConfig | undefined;\n readonly attachments?: AttachmentsConfig | undefined;\n readonly labels: ChatLabels;\n}\n/** A React hook: the chat calls it on every render of a mounted chat (a new hook remounts the chat). */\nexport type VoiceRecorderHook = (options: VoiceRecorderOptions) => VoiceMessageHandle;\n\n/** Props of the phone camera sheet that `AttachmentsConfig.Camera` carries. */\nexport interface CameraSheetProps {\n /** The photo, as a JPEG File scaled to at most `CAMERA_MAX_SIDE` on its longest side (or the phone camera's own file, from the fallback). */\n readonly onCapture: (file: File) => void;\n readonly onClose: () => void;\n /** Opens the camera; defaults to the browser's, when it has one. */\n readonly getUserMedia?: ((constraints: MediaStreamConstraints) => Promise<MediaStream>) | undefined;\n}\n\n/** A `/command` a settled reply may turn into a button (`commandMentions`; drawn by a text renderer such as `pi-chat-markdown`). */\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\n/** A recording's length as m:ss. */\nexport const voiceClock = (seconds: number) => `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`;\n\n/*\n * The cards of a reply are items too (`pi-chat-question`, `pi-chat-approval`, `pi-chat-subagent`, `pi-artifacts`). The core keeps only what\n * it needs to place them: the props each card receives, and a visible \"waiting for your answer\" notice when a question or an approval has\n * no card, so a run never waits silently. `withChatPlugins` of `pi-chat-plugins` plugs every card in.\n */\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 };\n/** `ask_user` calls are question rows; `ApprovalDecision` is what `requireApproval` records (both owned by the kit's chat view). */\nexport { ASK_USER_TOOL } from '@hachej/boring-ui-kit/chat-view';\nexport type { ApprovalDecision } from '@hachej/boring-ui-kit/chat-view';\n\n/** Props of the question card that `ChatCards.question` carries (`QuestionCard` of `pi-chat-question`). */\nexport interface QuestionCardProps {\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/** Props of the approval card that `ChatCards.approval` carries (`ApprovalCard` of `pi-chat-approval`). Answering uses the host's `answer`. */\nexport interface ApprovalCardProps {\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?: ApprovalDecision | 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/**\n * Draws a tool call that ran a sub-agent (`subagentCard` of `pi-chat-subagent`), from the details its running slot published (`details`)\n * or that it finished with. Undefined: the call is not a sub-agent call and stays an ordinary tool step.\n */\nexport type SubagentRenderer = ViewSubagentRenderer<ReactNode>;\n\n/** The cards the chat draws for a human decision or a sub-agent. Each one left out has no card (see `PiChat`'s `cards`). */\nexport interface ChatCards {\n /** An `ask_user` question (`QuestionCard` of `pi-chat-question`). Without it the chat says it waits for an answer, with no answer UI. */\n readonly question?: ComponentType<QuestionCardProps> | undefined;\n /** A call gated by `requireApproval` (`ApprovalCard` of `pi-chat-approval`). Without it the chat says it waits for an answer, with no answer UI. */\n readonly approval?: ComponentType<ApprovalCardProps> | undefined;\n /** A sub-agent call (`subagentCard` of `pi-chat-subagent`). Without it the call is an ordinary tool step. */\n readonly subagent?: SubagentRenderer | undefined;\n}\n\n/** An artifact a tool call made, as the chat places it (owned by the kit's chat view). */\nexport type { ChatArtifact };\n/** Props of the artifact card that `ArtifactsConfig.Card` carries (`PluggedArtifactCard` of `pi-artifacts`). */\nexport interface ChatArtifactCardProps {\n readonly artifact: ChatArtifact;\n readonly open: boolean;\n readonly onOpen: (() => void) | undefined;\n readonly kinds: readonly unknown[] | undefined;\n}\n/**\n * Artifact cards, as the core sees `ArtifactsConfig` of `pi-artifacts`: the host's opener and the item's `recognise` and `Card`. Without\n * `recognise` and `Card` no artifact is offered: the calls stay ordinary tool steps.\n */\nexport interface ChatArtifactsConfig {\n readonly kinds?: readonly unknown[] | undefined;\n readonly open: (artifact: never) => void;\n readonly isOpen?: ((artifact: never) => boolean) | undefined;\n readonly detect?: ArtifactDetect | undefined;\n /** The artifact a call made, or that a running call (`running`) is making; undefined for any other call. */\n readonly recognise?: ArtifactRecognise | undefined;\n readonly Card?: ComponentType<ChatArtifactCardProps> | undefined;\n}\n",
81
53
  "type": "registry:lib",
82
54
  "target": "components/pi-chat/config.ts"
83
55
  },
84
56
  {
85
57
  "path": "registry/pi-chat/empty-state.tsx",
86
- "content": "import type { ReactNode } from 'react';\nimport { Button } from '@/components/ui/button';\nimport { Empty, EmptyContent, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from '@/components/ui/empty';\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 } = useChatText();\n return <Empty data-testid=\"empty-state\" className=\"mx-auto min-h-full w-full max-w-[720px] max-sm:mb-24\">\n <EmptyHeader>\n {avatar && <EmptyMedia data-testid=\"empty-state-icon\"><span className=\"flex size-8 items-center justify-center overflow-hidden [&>img]:size-full [&>img]:object-cover [&>svg]:size-5\">{avatar}</span></EmptyMedia>}\n <EmptyTitle>{title}</EmptyTitle>\n <EmptyDescription>{description ?? labels.emptyDescription}</EmptyDescription>\n </EmptyHeader>\n {(children || (suggestions && suggestions.length > 0)) && <EmptyContent>\n {children}\n {suggestions && suggestions.length > 0 && <ul className=\"m-0 flex w-full max-w-lg list-none flex-wrap justify-center gap-2 p-0\">\n {suggestions.map(item => <li key={item.label}><Button variant=\"ghost\" onClick={() => onSelect?.(item.text)} data-testid=\"suggestion\"\n className=\"h-auto flex-col gap-1 whitespace-normal\">\n <span>{item.label}</span>{item.hint && <span>{item.hint}</span>}</Button></li>)}\n </ul>}\n </EmptyContent>}\n </Empty>;\n}\n",
58
+ "content": "import type { ReactNode } from 'react';\nimport { Button } from '@/components/ui/button';\nimport { Empty, EmptyContent, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from '@/components/ui/empty';\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 } = useChatText();\n return <Empty data-testid=\"empty-state\" className=\"mx-auto min-h-full w-full max-w-[720px] max-md:mb-24\">\n <EmptyHeader>\n {avatar && <EmptyMedia data-testid=\"empty-state-icon\"><span className=\"flex size-8 items-center justify-center overflow-hidden [&>img]:size-full [&>img]:object-cover [&>svg]:size-5\">{avatar}</span></EmptyMedia>}\n <EmptyTitle>{title}</EmptyTitle>\n <EmptyDescription>{description ?? labels.emptyDescription}</EmptyDescription>\n </EmptyHeader>\n {(children || (suggestions && suggestions.length > 0)) && <EmptyContent>\n {children}\n {suggestions && suggestions.length > 0 && <ul className=\"m-0 flex w-full max-w-lg list-none flex-wrap justify-center gap-2 p-0\">\n {suggestions.map(item => <li key={item.label}><Button variant=\"ghost\" onClick={() => onSelect?.(item.text)} data-testid=\"suggestion\"\n className=\"h-auto flex-col gap-1 whitespace-normal\">\n <span>{item.label}</span>{item.hint && <span>{item.hint}</span>}</Button></li>)}\n </ul>}\n </EmptyContent>}\n </Empty>;\n}\n",
87
59
  "type": "registry:component",
88
60
  "target": "components/pi-chat/empty-state.tsx"
89
61
  },
90
62
  {
91
63
  "path": "registry/pi-chat/history.tsx",
92
- "content": "'use client';\n\nimport { Fragment, useEffect, useMemo, useRef, useState } from 'react';\nimport type { ReactNode } from 'react';\nimport type { ChatHistoryState } from '@hachej/boring-ui-kit/native-chat';\nimport { ArchiveIcon, ArchiveRestoreIcon, ArrowLeftIcon, CheckIcon, EllipsisIcon, Loader2Icon, MessageSquareIcon, PencilIcon, SearchIcon, Trash2Icon, XIcon } from 'lucide-react';\nimport { Button } from '@/components/ui/button';\nimport { Drawer, DrawerContent, DrawerTitle } from '@/components/ui/drawer';\nimport { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuPortal, DropdownMenuSeparator, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';\nimport { Input } from '@/components/ui/input';\nimport { InputGroup, InputGroupAddon, InputGroupInput } from '@/components/ui/input-group';\nimport { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';\nimport { ScrollArea } from '@/components/ui/scroll-area';\nimport { Separator } from '@/components/ui/separator';\nimport { SidebarGroup, SidebarGroupLabel, SidebarMenu, SidebarMenuItem } from '@/components/ui/sidebar';\nimport { Toggle } from '@/components/ui/toggle';\nimport { ActionButton, actionMenuItem, headerActions, menuActions } from '../button/actions';\nimport type { BlockAction, MenuItem } from '../button/actions';\nimport type { ConversationItem, ConversationsConfig } from './config';\nimport { cn } from '../utils/utils';\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 start = new Date(now); start.setHours(0, 0, 0, 0);\n const age = start.getTime() - ms;\n return age <= 0 ? 'today' : age <= DAY ? 'yesterday' : age < 7 * DAY ? 'previousWeek' : 'older';\n}\nconst ORDER: readonly Group[] = ['today', 'yesterday', 'previousWeek', 'older', 'conversations'];\n\n/** The row's \"…\" menu: host actions in the consumer's shadcn dropdown-menu. */\nfunction RowActions({ label, items }: { readonly label: string; readonly items: readonly MenuItem[] }) {\n const portal = useRef<HTMLElement | null>(null);\n return <DropdownMenu>\n <DropdownMenuTrigger render={<Button ref={node => { portal.current = node?.ownerDocument.body ?? null; }} variant=\"ghost\" size=\"icon-sm\" aria-label={label} title={label} data-testid=\"conversation-action-more\"><EllipsisIcon data-icon=\"inline-start\" aria-hidden=\"true\" /></Button>} />\n <DropdownMenuPortal container={portal}>\n <DropdownMenuContent align=\"end\" aria-label={label} data-testid=\"conversation-action-more-list\" className=\"w-64 max-w-[calc(100vw-1rem)]\">\n {items.map(item => <Fragment key={item.id}>\n {item.separatorBefore && <DropdownMenuSeparator />}\n <DropdownMenuItem variant={item.destructive ? 'destructive' : 'default'} disabled={item.disabled} data-testid={item.testId ?? `conversation-action-more-${item.id}`} data-item={item.id} onClick={item.onSelect} className=\"min-h-8 max-sm:min-h-10 pointer-coarse:min-h-10\">\n {item.icon}{item.label}\n </DropdownMenuItem>\n </Fragment>)}\n </DropdownMenuContent>\n </DropdownMenuPortal>\n </DropdownMenu>;\n}\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, searchMode = 'disclosure', rowActionLayout = 'menu', navigation }: {\n readonly conversations: ConversationsConfig;\n /** `inline` retains the always-visible search field. */\n readonly searchMode?: 'disclosure' | 'inline';\n /** `inline` retains the separate rename/archive/delete buttons. */\n readonly rowActionLayout?: 'menu' | 'inline';\n readonly navigation?: ReactNode;\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 [searchOpen, setSearchOpen] = useState(autoFocus || searchMode === 'inline');\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 total = shown.reduce((sum, group) => sum + group.items.length, 0);\n const rowActionItems = (item: ConversationItem, extraButtons: readonly BlockAction[], extraMenu: readonly BlockAction[]): MenuItem[] => [\n ...(conversations.rename ? [{ id: 'rename', icon: <PencilIcon />, label: labels.rename, testId: 'conversation-rename', onSelect: () => setRenaming(item.id) }] : []),\n ...(conversations.archive ? [{ id: 'archive', icon: item.archived ? <ArchiveRestoreIcon /> : <ArchiveIcon />, label: item.archived ? labels.restore : labels.archive, testId: 'conversation-archive', onSelect: () => run(() => conversations.archive!(item.id, !item.archived)) }] : []),\n ...(conversations.remove ? [{ id: 'delete', icon: <Trash2Icon />, destructive: true, separatorBefore: true, label: labels.delete, testId: 'conversation-delete', onSelect: () => setConfirming(item.id) }] : []),\n ...[...extraButtons, ...extraMenu].map(entry => actionMenuItem(entry, 'conversation-action')),\n ];\n return <>\n {!searchOpen && <Button variant=\"ghost\" data-testid=\"conversation-search-open\" className=\"mx-2 justify-start\" onClick={() => { setSearchOpen(true); requestAnimationFrame(() => search.current?.focus()); }}><SearchIcon data-icon=\"inline-start\" aria-hidden=\"true\" />{labels.search}</Button>}\n {searchOpen && <div className=\"shrink-0 px-3 py-2\">\n <InputGroup>\n <InputGroupAddon><SearchIcon aria-hidden=\"true\" /></InputGroupAddon>\n <InputGroupInput ref={search} type=\"search\" value={query} onChange={event => setQuery(event.currentTarget.value)} placeholder={labels.searchConversations} aria-label={labels.searchConversations} data-testid=\"conversation-search\" />\n {conversations.archive && serverSearch && <InputGroupAddon align=\"inline-end\"><Toggle pressed={archived} aria-label={labels.archived} title={labels.archived} data-testid=\"conversations-archived\"\n onPressedChange={setArchived}><ArchiveIcon data-icon=\"inline-start\" aria-hidden=\"true\" />{labels.archived}</Toggle></InputGroupAddon>}\n </InputGroup>\n </div>}\n {navigation}\n {failure && <p role=\"alert\" className=\"m-0 shrink-0 px-3 pt-2 text-xs text-destructive\">{failure}</p>}\n <ScrollArea className=\"min-h-0 flex-1\" 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 => <SidebarGroup key={group.key} aria-label={labels[group.key]} role=\"group\">\n <SidebarGroupLabel render={<h4 />}>{labels[group.key]}</SidebarGroupLabel>\n <SidebarMenu>\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 <SidebarMenuItem key={item.id}>\n <form className=\"flex items-center gap-2\" 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=\"min-w-0 flex-1\" />\n <Button type=\"submit\" size=\"sm\" variant=\"outline\" data-testid=\"conversation-rename-save\">{labels.save}</Button>\n </form>\n </SidebarMenuItem>;\n }\n return <SidebarMenuItem key={item.id} className=\"flex items-center gap-0.5\">\n <Button type=\"button\" variant={active ? 'secondary' : 'ghost'} 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=\"h-auto min-h-10 min-w-0 flex-1 justify-start max-sm:min-h-12\">\n <MessageSquareIcon data-icon=\"inline-start\" aria-hidden=\"true\" />\n <span className=\"min-w-0 flex-1 truncate text-left\">{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\" /><span className=\"sr-only\">{labels.current}</span></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', confirming === item.id ? '' : 'opacity-0 group-hover/menu-item:opacity-100 group-focus-within/menu-item:opacity-100 pointer-coarse: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} title={labels.keep} onClick={() => setConfirming(null)}><XIcon data-icon=\"inline-start\" aria-hidden=\"true\" /></Button>\n </> : rowActionLayout === 'menu' ? <RowActions label={labels.moreActions} items={rowActionItems(item, extraButtons, extraMenu)} /> : <>\n {conversations.rename && <Button size=\"icon-sm\" variant=\"ghost\" aria-label={labels.renameItem(title)} title={labels.rename} data-testid=\"conversation-rename\" onClick={() => setRenaming(item.id)}><PencilIcon data-icon=\"inline-start\" 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\"\n onClick={() => { const archive = conversations.archive!; run(() => archive(item.id, !item.archived)); }}>{item.archived ? <ArchiveRestoreIcon data-icon=\"inline-start\" aria-hidden=\"true\" /> : <ArchiveIcon data-icon=\"inline-start\" 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\" onClick={() => setConfirming(item.id)}><Trash2Icon data-icon=\"inline-start\" aria-hidden=\"true\" /></Button>}\n {extraButtons.map(entry => <ActionButton key={entry.id} action={entry} testId=\"conversation-action\" />)}\n {extraMenu.length > 0 && <RowActions label={labels.moreActions} items={extraMenu.map(entry => actionMenuItem(entry, 'conversation-action'))} />}\n </>}\n </div>}\n </SidebarMenuItem>;\n })}\n </SidebarMenu>\n </SidebarGroup>)}\n </ScrollArea>\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 bottom drawer on a phone. Escape or a click outside closes it.\n */\nexport function ConversationHistory({ conversations, onClose, placement = 'below' }: {\n readonly conversations: ConversationsConfig;\n readonly onClose: () => void;\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 const [phone, setPhone] = useState(() => globalThis.matchMedia?.('(max-width: 640px)').matches === true);\n useEffect(() => { const media = globalThis.matchMedia?.('(max-width: 640px)'); if (!media) return; const change = () => setPhone(media.matches); media.addEventListener('change', change); return () => media.removeEventListener('change', change); }, []);\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 const content = <>\n <header className=\"flex shrink-0 items-center gap-2 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 data-icon=\"inline-start\" aria-hidden=\"true\" /></Button>\n <h3 className=\"m-0 min-w-0 flex-1 text-sm font-semibold\">{labels.history}</h3>\n {conversations.onNew && <Button size=\"sm\" variant=\"outline\" data-testid=\"conversation-new\" onClick={() => { conversations.onNew!(); onClose(); }}><icons.newChat data-icon=\"inline-start\" 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 data-icon=\"inline-start\" aria-hidden=\"true\" /></Button>\n </header>\n <Separator />\n <ConversationList conversations={conversations} onPicked={onClose} autoFocus />\n </>;\n return phone ? <Drawer open showSwipeHandle onOpenChange={next => { if (!next) onClose(); }}><DrawerContent data-testid=\"conversations\" aria-label={labels.historyDialog} className=\"pi-chat min-h-[80dvh]\"><DrawerTitle className=\"sr-only\">{labels.historyDialog}</DrawerTitle><div className=\"flex min-h-0 flex-1 flex-col pb-[env(safe-area-inset-bottom)]\">{content}</div></DrawerContent></Drawer>\n : <Popover open onOpenChange={next => { if (!next) onClose(); }} modal={false}>\n <PopoverTrigger nativeButton={false} render={<span aria-hidden=\"true\" className={cn('pointer-events-none absolute', placement === 'above' ? 'bottom-0 left-0' : 'top-12 right-3')} />} />\n <PopoverContent role=\"dialog\" aria-label={labels.historyDialog} data-testid=\"conversations\" side={placement === 'above' ? 'top' : 'bottom'} align={placement === 'above' ? 'start' : 'end'} className=\"pi-chat w-[23rem] max-w-[calc(100vw-1rem)] max-h-[min(34rem,70dvh)]\">{content}</PopoverContent>\n </Popover>;\n}\n\n/** The only history chrome inside the normal transcript: a sentinel, spinner and accessible fallback. */\nexport function TranscriptHistory({ history, connected, onLoad, sentinelRef, hidden, loaded }: {\n readonly history: ChatHistoryState;\n readonly connected: boolean;\n readonly onLoad: () => void;\n readonly sentinelRef: (element: HTMLDivElement | null) => void;\n readonly hidden: number;\n readonly loaded: number;\n}) {\n const { labels } = useChatText();\n if (history.kind === 'disabled' && hidden === 0) return null;\n const exhausted = hidden === 0 && history.kind === 'ready' && !history.hasMore;\n return <div ref={sentinelRef} data-testid=\"transcript-history\" className=\"flex min-h-8 shrink-0 items-center justify-center text-xs text-muted-foreground\">\n <Button variant=\"ghost\" data-testid=\"transcript-history-load\" className=\"sr-only focus:not-sr-only\" disabled={!connected || history.kind === 'loading' || exhausted} onClick={onLoad}>{labels.loadEarlierMessages}</Button>\n {history.kind === 'loading' && <Loader2Icon className=\"size-4 animate-spin motion-reduce:animate-none\" aria-label={labels.loadingShort} />}\n {history.kind === 'error' && <span role=\"alert\">{labels.historyFailed}</span>}\n {exhausted && <span>{labels.beginning}</span>}\n <span role=\"status\" aria-live=\"polite\" className=\"sr-only\">{loaded > 0 ? labels.earlierMessagesLoaded(loaded) : ''}</span>\n </div>;\n}\n",
64
+ "content": "'use client';\n\nimport { usePhone } from '../utils/use-media';\n\nimport { Fragment, useEffect, useMemo, useRef, useState } from 'react';\nimport type { ReactNode } from 'react';\nimport type { ChatHistoryState } from '@hachej/boring-ui-kit/native-chat';\nimport { ArchiveIcon, ArchiveRestoreIcon, ArrowLeftIcon, CheckIcon, EllipsisIcon, Loader2Icon, MessageSquareIcon, PencilIcon, SearchIcon, Trash2Icon, XIcon } from 'lucide-react';\nimport { Button } from '@/components/ui/button';\nimport { Drawer, DrawerContent, DrawerTitle } from '@/components/ui/drawer';\nimport { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuPortal, DropdownMenuSeparator, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';\nimport { Input } from '@/components/ui/input';\nimport { InputGroup, InputGroupAddon, InputGroupInput } from '@/components/ui/input-group';\nimport { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';\nimport { ScrollArea } from '@/components/ui/scroll-area';\nimport { Separator } from '@/components/ui/separator';\nimport { SidebarGroup, SidebarGroupLabel, SidebarMenu, SidebarMenuItem } from '@/components/ui/sidebar';\nimport { Toggle } from '@/components/ui/toggle';\nimport { ActionButton, actionMenuItem, headerActions, menuActions } from '../button/actions';\nimport type { BlockAction, MenuItem } from '../button/actions';\nimport type { ConversationItem, ConversationsConfig } from './config';\nimport { cn } from '../utils/utils';\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 start = new Date(now); start.setHours(0, 0, 0, 0);\n const age = start.getTime() - ms;\n return age <= 0 ? 'today' : age <= DAY ? 'yesterday' : age < 7 * DAY ? 'previousWeek' : 'older';\n}\nconst ORDER: readonly Group[] = ['today', 'yesterday', 'previousWeek', 'older', 'conversations'];\n\n/** The row's \"…\" menu: host actions in the consumer's shadcn dropdown-menu. */\nfunction RowActions({ label, items }: { readonly label: string; readonly items: readonly MenuItem[] }) {\n const portal = useRef<HTMLElement | null>(null);\n return <DropdownMenu>\n <DropdownMenuTrigger render={<Button ref={node => { portal.current = node?.ownerDocument.body ?? null; }} variant=\"ghost\" size=\"icon-sm\" aria-label={label} title={label} data-testid=\"conversation-action-more\"><EllipsisIcon data-icon=\"inline-start\" aria-hidden=\"true\" /></Button>} />\n <DropdownMenuPortal container={portal}>\n <DropdownMenuContent align=\"end\" aria-label={label} data-testid=\"conversation-action-more-list\" className=\"w-64 max-w-[calc(100vw-1rem)]\">\n {items.map(item => <Fragment key={item.id}>\n {item.separatorBefore && <DropdownMenuSeparator />}\n <DropdownMenuItem variant={item.destructive ? 'destructive' : 'default'} disabled={item.disabled} data-testid={item.testId ?? `conversation-action-more-${item.id}`} data-item={item.id} onClick={item.onSelect} className=\"min-h-8 max-md:min-h-10 pointer-coarse:min-h-10\">\n {item.icon}{item.label}\n </DropdownMenuItem>\n </Fragment>)}\n </DropdownMenuContent>\n </DropdownMenuPortal>\n </DropdownMenu>;\n}\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, searchMode = 'disclosure', rowActionLayout = 'menu', navigation }: {\n readonly conversations: ConversationsConfig;\n /** `inline` retains the always-visible search field. */\n readonly searchMode?: 'disclosure' | 'inline';\n /** `inline` retains the separate rename/archive/delete buttons. */\n readonly rowActionLayout?: 'menu' | 'inline';\n readonly navigation?: ReactNode;\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 [searchOpen, setSearchOpen] = useState(autoFocus || searchMode === 'inline');\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 // The time the list arrived: rows group and age against it until the host sends new items.\n // eslint-disable-next-line react-hooks/purity, react-hooks/exhaustive-deps -- read once per items list on purpose, so rows keep one clock between list updates\n const now = useMemo(() => Date.now(), [conversations.items]);\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 // eslint-disable-next-line react-hooks/set-state-in-effect -- leaving server search drops its results once, after commit\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 total = shown.reduce((sum, group) => sum + group.items.length, 0);\n const rowActionItems = (item: ConversationItem, extraButtons: readonly BlockAction[], extraMenu: readonly BlockAction[]): MenuItem[] => [\n ...(conversations.rename ? [{ id: 'rename', icon: <PencilIcon />, label: labels.rename, testId: 'conversation-rename', onSelect: () => setRenaming(item.id) }] : []),\n ...(conversations.archive ? [{ id: 'archive', icon: item.archived ? <ArchiveRestoreIcon /> : <ArchiveIcon />, label: item.archived ? labels.restore : labels.archive, testId: 'conversation-archive', onSelect: () => run(() => conversations.archive!(item.id, !item.archived)) }] : []),\n ...(conversations.remove ? [{ id: 'delete', icon: <Trash2Icon />, destructive: true, separatorBefore: true, label: labels.delete, testId: 'conversation-delete', onSelect: () => setConfirming(item.id) }] : []),\n ...[...extraButtons, ...extraMenu].map(entry => actionMenuItem(entry, 'conversation-action')),\n ];\n return <>\n {!searchOpen && <Button variant=\"ghost\" data-testid=\"conversation-search-open\" className=\"mx-2 justify-start\" onClick={() => { setSearchOpen(true); requestAnimationFrame(() => search.current?.focus()); }}><SearchIcon data-icon=\"inline-start\" aria-hidden=\"true\" />{labels.search}</Button>}\n {searchOpen && <div className=\"shrink-0 px-3 py-2\">\n <InputGroup>\n <InputGroupAddon><SearchIcon aria-hidden=\"true\" /></InputGroupAddon>\n <InputGroupInput ref={search} type=\"search\" value={query} onChange={event => setQuery(event.currentTarget.value)} placeholder={labels.searchConversations} aria-label={labels.searchConversations} data-testid=\"conversation-search\" />\n {conversations.archive && serverSearch && <InputGroupAddon align=\"inline-end\"><Toggle pressed={archived} aria-label={labels.archived} title={labels.archived} data-testid=\"conversations-archived\"\n onPressedChange={setArchived}><ArchiveIcon data-icon=\"inline-start\" aria-hidden=\"true\" />{labels.archived}</Toggle></InputGroupAddon>}\n </InputGroup>\n </div>}\n {navigation}\n {failure && <p role=\"alert\" className=\"m-0 shrink-0 px-3 pt-2 text-xs text-destructive\">{failure}</p>}\n <ScrollArea className=\"min-h-0 flex-1\" 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 => <SidebarGroup key={group.key} aria-label={labels[group.key]} role=\"group\">\n <SidebarGroupLabel render={<h4 />}>{labels[group.key]}</SidebarGroupLabel>\n <SidebarMenu>\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 <SidebarMenuItem key={item.id}>\n <form className=\"flex items-center gap-2\" 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=\"min-w-0 flex-1\" />\n <Button type=\"submit\" size=\"sm\" variant=\"outline\" data-testid=\"conversation-rename-save\">{labels.save}</Button>\n </form>\n </SidebarMenuItem>;\n }\n return <SidebarMenuItem key={item.id} className=\"flex items-center gap-0.5\">\n <Button type=\"button\" variant={active ? 'secondary' : 'ghost'} 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=\"h-auto min-h-10 min-w-0 flex-1 justify-start max-md:min-h-12\">\n <MessageSquareIcon data-icon=\"inline-start\" aria-hidden=\"true\" />\n <span className=\"min-w-0 flex-1 truncate text-left\">{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\" /><span className=\"sr-only\">{labels.current}</span></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', confirming === item.id ? '' : 'opacity-0 group-hover/menu-item:opacity-100 group-focus-within/menu-item:opacity-100 pointer-coarse: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} title={labels.keep} onClick={() => setConfirming(null)}><XIcon data-icon=\"inline-start\" aria-hidden=\"true\" /></Button>\n </> : rowActionLayout === 'menu' ? <RowActions label={labels.moreActions} items={rowActionItems(item, extraButtons, extraMenu)} /> : <>\n {conversations.rename && <Button size=\"icon-sm\" variant=\"ghost\" aria-label={labels.renameItem(title)} title={labels.rename} data-testid=\"conversation-rename\" onClick={() => setRenaming(item.id)}><PencilIcon data-icon=\"inline-start\" 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\"\n onClick={() => { const archive = conversations.archive!; run(() => archive(item.id, !item.archived)); }}>{item.archived ? <ArchiveRestoreIcon data-icon=\"inline-start\" aria-hidden=\"true\" /> : <ArchiveIcon data-icon=\"inline-start\" 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\" onClick={() => setConfirming(item.id)}><Trash2Icon data-icon=\"inline-start\" aria-hidden=\"true\" /></Button>}\n {extraButtons.map(entry => <ActionButton key={entry.id} action={entry} testId=\"conversation-action\" />)}\n {extraMenu.length > 0 && <RowActions label={labels.moreActions} items={extraMenu.map(entry => actionMenuItem(entry, 'conversation-action'))} />}\n </>}\n </div>}\n </SidebarMenuItem>;\n })}\n </SidebarMenu>\n </SidebarGroup>)}\n </ScrollArea>\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 bottom drawer on a phone. Escape or a click outside closes it.\n */\nexport function ConversationHistory({ conversations, onClose, placement = 'below' }: {\n readonly conversations: ConversationsConfig;\n readonly onClose: () => void;\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 const phone = usePhone();\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 const content = <>\n <header className=\"flex shrink-0 items-center gap-2 px-3 py-2.5 max-md: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=\"md:hidden\"><ArrowLeftIcon data-icon=\"inline-start\" aria-hidden=\"true\" /></Button>\n <h3 className=\"m-0 min-w-0 flex-1 text-sm font-semibold\">{labels.history}</h3>\n {conversations.onNew && <Button size=\"sm\" variant=\"outline\" data-testid=\"conversation-new\" onClick={() => { conversations.onNew!(); onClose(); }}><icons.newChat data-icon=\"inline-start\" aria-hidden=\"true\" />{labels.newConversation}</Button>}\n <Button size=\"icon-sm\" variant=\"ghost\" aria-label={labels.closeHistory} title={labels.close} onClick={onClose} className=\"max-md:hidden\"><XIcon data-icon=\"inline-start\" aria-hidden=\"true\" /></Button>\n </header>\n <Separator />\n <ConversationList conversations={conversations} onPicked={onClose} autoFocus />\n </>;\n return phone ? <Drawer open showSwipeHandle onOpenChange={next => { if (!next) onClose(); }}><DrawerContent data-testid=\"conversations\" aria-label={labels.historyDialog} className=\"pi-chat min-h-[80dvh]\"><DrawerTitle className=\"sr-only\">{labels.historyDialog}</DrawerTitle><div className=\"flex min-h-0 flex-1 flex-col pb-[env(safe-area-inset-bottom)]\">{content}</div></DrawerContent></Drawer>\n : <Popover open onOpenChange={next => { if (!next) onClose(); }} modal={false}>\n <PopoverTrigger nativeButton={false} render={<span aria-hidden=\"true\" className={cn('pointer-events-none absolute', placement === 'above' ? 'bottom-0 left-0' : 'top-12 right-3')} />} />\n <PopoverContent role=\"dialog\" aria-label={labels.historyDialog} data-testid=\"conversations\" side={placement === 'above' ? 'top' : 'bottom'} align={placement === 'above' ? 'start' : 'end'} className=\"pi-chat w-[23rem] max-w-[calc(100vw-1rem)] max-h-[min(34rem,70dvh)]\">{content}</PopoverContent>\n </Popover>;\n}\n\n/** The only history chrome inside the normal transcript: a sentinel, spinner and accessible fallback. */\nexport function TranscriptHistory({ history, connected, onLoad, sentinelRef, hidden, loaded }: {\n readonly history: ChatHistoryState;\n readonly connected: boolean;\n readonly onLoad: () => void;\n readonly sentinelRef: (element: HTMLDivElement | null) => void;\n readonly hidden: number;\n readonly loaded: number;\n}) {\n const { labels } = useChatText();\n if (history.kind === 'disabled' && hidden === 0) return null;\n const exhausted = hidden === 0 && history.kind === 'ready' && !history.hasMore;\n return <div ref={sentinelRef} data-testid=\"transcript-history\" className=\"flex min-h-8 shrink-0 items-center justify-center text-xs text-muted-foreground\">\n <Button variant=\"ghost\" data-testid=\"transcript-history-load\" className=\"sr-only focus:not-sr-only\" disabled={!connected || history.kind === 'loading' || exhausted} onClick={onLoad}>{labels.loadEarlierMessages}</Button>\n {history.kind === 'loading' && <Loader2Icon className=\"size-4 animate-spin motion-reduce:animate-none\" aria-label={labels.loadingShort} />}\n {history.kind === 'error' && <span role=\"alert\">{labels.historyFailed}</span>}\n {exhausted && <span>{labels.beginning}</span>}\n <span role=\"status\" aria-live=\"polite\" className=\"sr-only\">{loaded > 0 ? labels.earlierMessagesLoaded(loaded) : ''}</span>\n </div>;\n}\n",
93
65
  "type": "registry:component",
94
66
  "target": "components/pi-chat/history.tsx"
95
67
  },
96
68
  {
97
69
  "path": "registry/pi-chat/image-viewer.tsx",
98
- "content": "'use client';\n\nimport { useRef, useState } from 'react';\nimport type { PointerEvent } from 'react';\nimport type { ImageContent } from '@earendil-works/pi-ai';\nimport { ChevronLeftIcon, ChevronRightIcon, XIcon } from 'lucide-react';\nimport { Button } from '@/components/ui/button';\nimport { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog';\nimport { thumbnail } from './composer';\nimport { useChatText } from './labels';\nimport type { ChatLabels } from './labels';\n\ntype Point = { readonly x: number; readonly y: number };\ntype View = { readonly scale: number; readonly x: number; readonly y: number };\ntype Gesture = {\n readonly pointers: Map<number, Point>;\n basis: { readonly mode: 'pan' | 'pinch' | 'pinch-pan' | 'swipe'; readonly point: Point; readonly distance: number; readonly view: View } | undefined;\n tap: { readonly at: number; readonly point: Point } | undefined;\n view: View;\n pointerType: string;\n};\nconst FIT: View = { scale: 1, x: 0, y: 0 };\nconst distance = (a: Point, b: Point) => Math.hypot(a.x - b.x, a.y - b.y);\nconst midpoint = (a: Point, b: Point): Point => ({ x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 });\n\n/** Presentation only: local raster bytes, one message's gallery, and the host's native Dialog lifecycle. */\nexport function ImageViewer({ images, index, onIndexChange, onClose, labels: supplied, testId = 'image-viewer' }: {\n readonly images: readonly ImageContent[]; readonly index: number; readonly onIndexChange: (index: number) => void; readonly onClose: () => void;\n readonly labels?: ChatLabels | undefined; readonly testId?: string | undefined;\n}) {\n const { labels: defaults } = useChatText();\n const labels = supplied ?? defaults;\n const src = images[index] && thumbnail(images[index]!.mimeType, images[index]!.data);\n const move = (offset: number) => onIndexChange((index + offset + images.length) % images.length);\n if (!src) return null;\n return <Dialog open onOpenChange={open => { if (!open) onClose(); }}><DialogContent showCloseButton={false} aria-describedby={undefined} data-testid=\"image-viewer\"\n className=\"pi-chat flex min-h-0 flex-col overflow-hidden max-sm:inset-0 max-sm:max-h-dvh max-sm:min-h-dvh max-sm:max-w-none max-sm:translate-x-0 max-sm:translate-y-0 sm:max-h-[90dvh] sm:min-h-[80dvh] sm:max-w-5xl\"\n onKeyDown={event => {\n if (event.key === 'ArrowLeft' || event.key === 'ArrowRight') { event.preventDefault(); event.stopPropagation(); move(event.key === 'ArrowLeft' ? -1 : 1); }\n }}>\n <DialogTitle className=\"sr-only\">{labels.imageAttachment}</DialogTitle>\n <div className=\"flex shrink-0 items-center justify-between gap-2 pt-[env(safe-area-inset-top)]\">\n <span aria-live=\"polite\" data-testid=\"image-viewer-count\">{labels.imagePosition(index + 1, images.length)}</span>\n <div className=\"flex items-center gap-2\">\n {images.length > 1 && <>\n <Button variant=\"ghost\" size=\"icon\" className=\"min-h-12! min-w-12!\" aria-label={labels.previousImage} onClick={() => move(-1)}><ChevronLeftIcon data-icon=\"inline-start\" aria-hidden=\"true\" /></Button>\n <Button variant=\"ghost\" size=\"icon\" className=\"min-h-12! min-w-12!\" aria-label={labels.nextImage} onClick={() => move(1)}><ChevronRightIcon data-icon=\"inline-start\" aria-hidden=\"true\" /></Button>\n </>}\n <Button variant=\"ghost\" size=\"icon\" className=\"min-h-12! min-w-12!\" data-testid={`${testId}-close`} aria-label={labels.close} onClick={onClose}\n onTouchEnd={event => {\n // Pinch can suppress clicks; cancel the compatibility click before exposing the page beneath the close target.\n const point = event.changedTouches[0], box = event.currentTarget.getBoundingClientRect();\n if (point && point.clientX >= box.left && point.clientX <= box.right && point.clientY >= box.top && point.clientY <= box.bottom) { event.preventDefault(); onClose(); }\n }}><XIcon data-icon=\"inline-start\" aria-hidden=\"true\" /></Button>\n </div>\n </div>\n <ImageSurface key={`${index}:${src}`} src={src} alt={labels.imagePosition(index + 1, images.length)} onClose={onClose} testId={testId} />\n </DialogContent></Dialog>;\n}\n\nfunction ImageSurface({ src, alt, onClose, testId }: { readonly src: string; readonly alt: string; readonly onClose: () => void; readonly testId: string }) {\n const [view, setView] = useState(FIT);\n const image = useRef<HTMLImageElement>(null);\n const gesture = useRef<Gesture>({ pointers: new Map(), basis: undefined, tap: undefined, view: FIT, pointerType: '' });\n const update = (next: View) => { gesture.current.view = next; setView(next); };\n const bounded = (scale: number, x: number, y: number, element: HTMLElement): View => {\n const box = element.getBoundingClientRect();\n const maxX = Math.max(0, ((image.current?.clientWidth || box.width) * scale - box.width) / 2), maxY = Math.max(0, ((image.current?.clientHeight || box.height) * scale - box.height) / 2);\n return { scale, x: Math.max(-maxX, Math.min(maxX, x)), y: Math.max(-maxY, Math.min(maxY, y)) };\n };\n const zoom = (point: Point, element: HTMLElement) => {\n const state = gesture.current;\n state.tap = undefined;\n if (state.view.scale > 1) { update(FIT); return; }\n const box = element.getBoundingClientRect();\n update(bounded(2, box.left + box.width / 2 - point.x, box.top + box.height / 2 - point.y, element));\n };\n const rebase = (mode?: 'pan' | 'pinch-pan') => {\n const state = gesture.current, points = [...state.pointers.values()], first = points[0];\n state.basis = first ? { mode: points.length > 1 ? 'pinch' : mode ?? (state.view.scale > 1 ? 'pan' : 'swipe'), point: points[1] ? midpoint(first, points[1]) : first,\n distance: points[1] ? Math.max(1, distance(first, points[1])) : 0, view: state.view } : undefined;\n };\n const pointer = (event: PointerEvent<HTMLDivElement>) => ({ x: event.clientX, y: event.clientY });\n const end = (event: PointerEvent<HTMLDivElement>, cancelled: boolean) => {\n const state = gesture.current, basis = state.basis;\n if (!state.pointers.has(event.pointerId) || !basis) return;\n const point = pointer(event), dx = point.x - basis.point.x, dy = point.y - basis.point.y;\n state.pointers.delete(event.pointerId);\n if (!cancelled && basis.mode === 'swipe' && state.view.scale === 1 && dy > 96 && dy > Math.abs(dx) * 1.25) { onClose(); return; }\n if (!cancelled && event.pointerType === 'touch' && basis.mode !== 'pinch' && basis.mode !== 'pinch-pan' && Math.hypot(dx, dy) < 12) {\n if (state.tap && event.timeStamp - state.tap.at < 300 && distance(point, state.tap.point) < 24) zoom(point, event.currentTarget);\n else state.tap = { at: event.timeStamp, point };\n } else state.tap = undefined;\n rebase(basis.mode === 'pinch' || basis.mode === 'pinch-pan' ? 'pinch-pan' : 'pan');\n };\n return <div data-testid=\"image-viewer-surface\" data-scale={view.scale} className=\"relative min-h-0 flex-1 touch-none overflow-hidden max-sm:-mx-4 max-sm:-mb-4\"\n onDoubleClick={event => { if (gesture.current.pointerType === 'touch') return; event.preventDefault(); zoom({ x: event.clientX, y: event.clientY }, event.currentTarget); }}\n onPointerDown={event => {\n if (event.pointerType === 'mouse' && event.button !== 0) return;\n event.preventDefault(); event.currentTarget.setPointerCapture?.(event.pointerId);\n gesture.current.pointerType = event.pointerType; gesture.current.pointers.set(event.pointerId, pointer(event)); rebase();\n }}\n onPointerMove={event => {\n const state = gesture.current;\n if (!state.pointers.has(event.pointerId) || !state.basis) return;\n event.preventDefault(); state.pointers.set(event.pointerId, pointer(event));\n const points = [...state.pointers.values()], basis = state.basis, first = points[0]!;\n if (points[1]) {\n const centre = midpoint(first, points[1]), box = event.currentTarget.getBoundingClientRect();\n const scale = Math.max(1, Math.min(5, basis.view.scale * distance(first, points[1]) / basis.distance)), ratio = scale / basis.view.scale;\n update(bounded(scale, centre.x - box.left - box.width / 2 + (basis.view.x - basis.point.x + box.left + box.width / 2) * ratio,\n centre.y - box.top - box.height / 2 + (basis.view.y - basis.point.y + box.top + box.height / 2) * ratio, event.currentTarget));\n } else if (basis.mode === 'pan' || basis.mode === 'pinch-pan') update(bounded(basis.view.scale, basis.view.x + first.x - basis.point.x, basis.view.y + first.y - basis.point.y, event.currentTarget));\n }}\n onPointerUp={event => end(event, false)} onPointerCancel={event => end(event, true)} onLostPointerCapture={event => end(event, true)}>\n <div className=\"absolute inset-0 flex items-center justify-center\">\n <img ref={image} data-testid={`${testId}-image`} src={src} alt={alt} draggable={false} className=\"max-h-full max-w-full select-none object-contain\" style={{ transform: `translate(${view.x}px, ${view.y}px) scale(${view.scale})` }} />\n </div>\n </div>;\n}\n",
70
+ "content": "'use client';\n\nimport { useRef, useState } from 'react';\nimport type { PointerEvent } from 'react';\nimport type { ImageContent } from '@earendil-works/pi-ai';\nimport { ChevronLeftIcon, ChevronRightIcon, XIcon } from 'lucide-react';\nimport { Button } from '@/components/ui/button';\nimport { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog';\nimport { thumbnail } from './composer';\nimport { useChatText } from './labels';\nimport type { ChatLabels } from './labels';\n\ntype Point = { readonly x: number; readonly y: number };\ntype View = { readonly scale: number; readonly x: number; readonly y: number };\ntype Gesture = {\n readonly pointers: Map<number, Point>;\n basis: { readonly mode: 'pan' | 'pinch' | 'pinch-pan' | 'swipe'; readonly point: Point; readonly distance: number; readonly view: View } | undefined;\n tap: { readonly at: number; readonly point: Point } | undefined;\n view: View;\n pointerType: string;\n};\nconst FIT: View = { scale: 1, x: 0, y: 0 };\nconst distance = (a: Point, b: Point) => Math.hypot(a.x - b.x, a.y - b.y);\nconst midpoint = (a: Point, b: Point): Point => ({ x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 });\n\n/** Presentation only: local raster bytes, one message's gallery, and the host's native Dialog lifecycle. */\nexport function ImageViewer({ images, index, onIndexChange, onClose, labels: supplied, testId = 'image-viewer' }: {\n readonly images: readonly ImageContent[]; readonly index: number; readonly onIndexChange: (index: number) => void; readonly onClose: () => void;\n readonly labels?: ChatLabels | undefined; readonly testId?: string | undefined;\n}) {\n const { labels: defaults } = useChatText();\n const labels = supplied ?? defaults;\n const src = images[index] && thumbnail(images[index]!.mimeType, images[index]!.data);\n const move = (offset: number) => onIndexChange((index + offset + images.length) % images.length);\n if (!src) return null;\n return <Dialog open onOpenChange={open => { if (!open) onClose(); }}><DialogContent showCloseButton={false} aria-describedby={undefined} data-testid=\"image-viewer\"\n className=\"pi-chat flex min-h-0 flex-col overflow-hidden max-md:inset-0 max-md:max-h-dvh max-md:min-h-dvh max-md:max-w-none max-md:translate-x-0 max-md:translate-y-0 md:max-h-[90dvh] md:min-h-[80dvh] md:max-w-5xl\"\n onKeyDown={event => {\n if (event.key === 'ArrowLeft' || event.key === 'ArrowRight') { event.preventDefault(); event.stopPropagation(); move(event.key === 'ArrowLeft' ? -1 : 1); }\n }}>\n <DialogTitle className=\"sr-only\">{labels.imageAttachment}</DialogTitle>\n <div className=\"flex shrink-0 items-center justify-between gap-2 pt-[env(safe-area-inset-top)]\">\n <span aria-live=\"polite\" data-testid=\"image-viewer-count\">{labels.imagePosition(index + 1, images.length)}</span>\n <div className=\"flex items-center gap-2\">\n {images.length > 1 && <>\n <Button variant=\"ghost\" size=\"icon\" className=\"min-h-12! min-w-12!\" aria-label={labels.previousImage} onClick={() => move(-1)}><ChevronLeftIcon data-icon=\"inline-start\" aria-hidden=\"true\" /></Button>\n <Button variant=\"ghost\" size=\"icon\" className=\"min-h-12! min-w-12!\" aria-label={labels.nextImage} onClick={() => move(1)}><ChevronRightIcon data-icon=\"inline-start\" aria-hidden=\"true\" /></Button>\n </>}\n <Button variant=\"ghost\" size=\"icon\" className=\"min-h-12! min-w-12!\" data-testid={`${testId}-close`} aria-label={labels.close} onClick={onClose}\n onTouchEnd={event => {\n // Pinch can suppress clicks; cancel the compatibility click before exposing the page beneath the close target.\n const point = event.changedTouches[0], box = event.currentTarget.getBoundingClientRect();\n if (point && point.clientX >= box.left && point.clientX <= box.right && point.clientY >= box.top && point.clientY <= box.bottom) { event.preventDefault(); onClose(); }\n }}><XIcon data-icon=\"inline-start\" aria-hidden=\"true\" /></Button>\n </div>\n </div>\n <ImageSurface key={`${index}:${src}`} src={src} alt={labels.imagePosition(index + 1, images.length)} onClose={onClose} testId={testId} />\n </DialogContent></Dialog>;\n}\n\nfunction ImageSurface({ src, alt, onClose, testId }: { readonly src: string; readonly alt: string; readonly onClose: () => void; readonly testId: string }) {\n const [view, setView] = useState(FIT);\n const image = useRef<HTMLImageElement>(null);\n const gesture = useRef<Gesture>({ pointers: new Map(), basis: undefined, tap: undefined, view: FIT, pointerType: '' });\n const update = (next: View) => { gesture.current.view = next; setView(next); };\n const bounded = (scale: number, x: number, y: number, element: HTMLElement): View => {\n const box = element.getBoundingClientRect();\n const maxX = Math.max(0, ((image.current?.clientWidth || box.width) * scale - box.width) / 2), maxY = Math.max(0, ((image.current?.clientHeight || box.height) * scale - box.height) / 2);\n return { scale, x: Math.max(-maxX, Math.min(maxX, x)), y: Math.max(-maxY, Math.min(maxY, y)) };\n };\n const zoom = (point: Point, element: HTMLElement) => {\n const state = gesture.current;\n state.tap = undefined;\n if (state.view.scale > 1) { update(FIT); return; }\n const box = element.getBoundingClientRect();\n update(bounded(2, box.left + box.width / 2 - point.x, box.top + box.height / 2 - point.y, element));\n };\n const rebase = (mode?: 'pan' | 'pinch-pan') => {\n const state = gesture.current, points = [...state.pointers.values()], first = points[0];\n state.basis = first ? { mode: points.length > 1 ? 'pinch' : mode ?? (state.view.scale > 1 ? 'pan' : 'swipe'), point: points[1] ? midpoint(first, points[1]) : first,\n distance: points[1] ? Math.max(1, distance(first, points[1])) : 0, view: state.view } : undefined;\n };\n const pointer = (event: PointerEvent<HTMLDivElement>) => ({ x: event.clientX, y: event.clientY });\n const end = (event: PointerEvent<HTMLDivElement>, cancelled: boolean) => {\n const state = gesture.current, basis = state.basis;\n if (!state.pointers.has(event.pointerId) || !basis) return;\n const point = pointer(event), dx = point.x - basis.point.x, dy = point.y - basis.point.y;\n state.pointers.delete(event.pointerId);\n if (!cancelled && basis.mode === 'swipe' && state.view.scale === 1 && dy > 96 && dy > Math.abs(dx) * 1.25) { onClose(); return; }\n if (!cancelled && event.pointerType === 'touch' && basis.mode !== 'pinch' && basis.mode !== 'pinch-pan' && Math.hypot(dx, dy) < 12) {\n if (state.tap && event.timeStamp - state.tap.at < 300 && distance(point, state.tap.point) < 24) zoom(point, event.currentTarget);\n else state.tap = { at: event.timeStamp, point };\n } else state.tap = undefined;\n rebase(basis.mode === 'pinch' || basis.mode === 'pinch-pan' ? 'pinch-pan' : 'pan');\n };\n return <div data-testid=\"image-viewer-surface\" data-scale={view.scale} className=\"relative min-h-0 flex-1 touch-none overflow-hidden max-md:-mx-4 max-md:-mb-4\"\n onDoubleClick={event => { if (gesture.current.pointerType === 'touch') return; event.preventDefault(); zoom({ x: event.clientX, y: event.clientY }, event.currentTarget); }}\n onPointerDown={event => {\n if (event.pointerType === 'mouse' && event.button !== 0) return;\n event.preventDefault(); event.currentTarget.setPointerCapture?.(event.pointerId);\n gesture.current.pointerType = event.pointerType; gesture.current.pointers.set(event.pointerId, pointer(event)); rebase();\n }}\n onPointerMove={event => {\n const state = gesture.current;\n if (!state.pointers.has(event.pointerId) || !state.basis) return;\n event.preventDefault(); state.pointers.set(event.pointerId, pointer(event));\n const points = [...state.pointers.values()], basis = state.basis, first = points[0]!;\n if (points[1]) {\n const centre = midpoint(first, points[1]), box = event.currentTarget.getBoundingClientRect();\n const scale = Math.max(1, Math.min(5, basis.view.scale * distance(first, points[1]) / basis.distance)), ratio = scale / basis.view.scale;\n update(bounded(scale, centre.x - box.left - box.width / 2 + (basis.view.x - basis.point.x + box.left + box.width / 2) * ratio,\n centre.y - box.top - box.height / 2 + (basis.view.y - basis.point.y + box.top + box.height / 2) * ratio, event.currentTarget));\n } else if (basis.mode === 'pan' || basis.mode === 'pinch-pan') update(bounded(basis.view.scale, basis.view.x + first.x - basis.point.x, basis.view.y + first.y - basis.point.y, event.currentTarget));\n }}\n onPointerUp={event => end(event, false)} onPointerCancel={event => end(event, true)} onLostPointerCapture={event => end(event, true)}>\n <div className=\"absolute inset-0 flex items-center justify-center\">\n <img ref={image} data-testid={`${testId}-image`} src={src} alt={alt} draggable={false} className=\"max-h-full max-w-full select-none object-contain\" style={{ transform: `translate(${view.x}px, ${view.y}px) scale(${view.scale})` }} />\n </div>\n </div>;\n}\n",
99
71
  "type": "registry:component",
100
72
  "target": "components/pi-chat/image-viewer.tsx"
101
73
  },
@@ -113,31 +85,31 @@
113
85
  },
114
86
  {
115
87
  "path": "registry/pi-chat/message.tsx",
116
- "content": "'use client';\n\nimport { Fragment, memo, useEffect, useMemo, useRef, useState } from 'react';\nimport type { ReactNode } from 'react';\nimport type { ImageContent, ToolResultMessage, UserMessage } from '@earendil-works/pi-ai';\nimport { AlertCircleIcon, CircleSlashIcon, ClockIcon, FileAudioIcon, FileIcon, FileSpreadsheetIcon, FileTextIcon, ImageIcon, PauseIcon, PlayIcon, PresentationIcon } from 'lucide-react';\nimport { CopyButton } from './code-block';\nimport type { AnswerOutcome, ChatArtifactsConfig, ChatCards, CommandMentions } from './config';\nimport { feedbackContent } from './feedback-content';\nimport { SentFeedback } from './sent-feedback';\nimport { ActivityBlock } from './activity';\nimport type { ActivityState } from './activity';\nimport { Shimmer } from './shimmer';\nimport { ToolCard } from './tool';\nimport { thumbnail } from './composer';\nimport { ImageViewer } from './image-viewer';\nimport { displayName, fileKind, isUploadPath, isVoicePath, pieces, visibleParts } from './config';\nimport type { AudioUrlRead, FileKind, Piece, PreviewRead } from './config';\nimport { voiceClock } from './config';\nimport { Spinner } from '@/components/ui/spinner';\nimport { isFileBlock, segments, targetContent, waits } from './rows';\nimport type { DeriveOptions, Row } from './rows';\nimport { Button } from '@/components/ui/button';\nimport { BlockActions } from '../button/actions';\nimport type { BlockAction } from '../button/actions';\nimport { useChatText } from './labels';\nimport { cn } from '../utils/utils';\nimport type { ReplyRef } from './config';\nimport { Message, MessageContent, MessageFooter } from '@/components/ui/message';\nimport { Bubble, BubbleContent } from '@/components/ui/bubble';\nimport { MessageScrollerItem } from '@/components/ui/message-scroller';\nimport { Attachment, AttachmentContent, AttachmentDescription, AttachmentMedia, AttachmentTitle, AttachmentTrigger } from '@/components/ui/attachment';\nimport { Badge } from '@/components/ui/badge';\nimport { Alert, AlertDescription } from '@/components/ui/alert';\nimport { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';\n\n/** One assistant text part, as `renderText` receives it. `streaming` is true while the model still writes it. */\nexport interface ChatTextPart {\n readonly text: string;\n readonly streaming: boolean;\n /** Draws an `@path` mention (when mentions are on). */\n readonly renderMention?: ((path: string, text: string) => ReactNode) | undefined;\n /** The `/` commands a settled reply may turn into buttons. */\n readonly commandMentions?: CommandMentions | undefined;\n readonly onCopy?: ((text: string) => Promise<void>) | undefined;\n}\n/** The default text renderer: the reply as plain text. `markdownText` of `pi-chat-markdown` draws it as Markdown. */\nconst plainText = ({ text, streaming }: ChatTextPart): ReactNode =>\n <div data-testid=\"message-text\" data-streaming={streaming ? 'true' : undefined} className=\"min-w-0 whitespace-pre-wrap [overflow-wrap:anywhere]\">{text}</div>;\n\nexport type { ChatCards } from './config';\n\nexport interface RowContext {\n /** `messaging`: primary bubble for me, muted bubble for the reply, a tail on the first bubble of a run and the time inside (`PiChat messageStyle`). */\n readonly messageStyle?: 'default' | 'messaging' | undefined;\n readonly developer: boolean;\n /** Draws an assistant text part. Default: plain text (`markdownText` of `pi-chat-markdown` draws Markdown). */\n readonly renderText?: ((part: ChatTextPart) => ReactNode) | undefined;\n readonly cards?: ChatCards | undefined;\n /** `presentation=\"natural\"`: no \"working\" shimmer in a reply (the chat shows one status instead). */\n readonly natural?: boolean | undefined;\n readonly groupTool: DeriveOptions['groupTool'];\n readonly commandMentions: CommandMentions | undefined;\n /** Host openers keep their single image argument; the workspace's default also accepts the message gallery. */\n readonly onOpenImage: ((image: ImageContent, gallery?: readonly 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 uploads?: boolean; readonly skills: readonly string[]; readonly openMention?: ((path: string) => void) | undefined; readonly renderMention?: ((path: string) => ReactNode | undefined) | undefined;\n readonly preview?: PreviewRead | undefined; readonly audioUrl?: AudioUrlRead | undefined } | undefined;\n readonly fileChanges?: boolean | undefined;\n /** Opens a file card through the host's workspace opener. */\n readonly openFile?: ((path: string) => void) | undefined;\n readonly answer: ((questionId: string, answer: string) => Promise<AnswerOutcome>) | undefined;\n readonly artifacts: { readonly open: ChatArtifactsConfig['open']; readonly isOpen?: ChatArtifactsConfig['isOpen'] | undefined; readonly kinds?: ChatArtifactsConfig['kinds']; readonly Card: NonNullable<ChatArtifactsConfig['Card']> } | 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 readonly historicalMessageActions?: boolean | undefined;\n /** Host-owned per-answer unread indicator; rendering never marks an answer seen. */\n readonly unread?: ((reply: ReplyRef) => ReactNode) | undefined;\n readonly replyError?: ((reply: ReplyRef) => ReactNode) | 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 ImageThumbnails({ images, onOpenImage }: { readonly images: readonly ImageContent[]; readonly onOpenImage: RowContext['onOpenImage'] }) {\n const { labels } = useChatText();\n if (!images.length) return null;\n return <div data-testid=\"message-images\" data-slot=\"message-images\" className={cn('grid max-w-full gap-2', images.length === 1 ? 'w-60' : 'w-120 grid-cols-2')}>\n {images.map((image, at) => <div key={at} className=\"relative min-h-12 min-w-12 self-start\">\n <img src={thumbnail(image.mimeType, image.data)} alt={labels.imageAttachment} className=\"block h-auto w-full rounded-(--radius-xl)\" />\n <Button variant=\"link\" className=\"absolute inset-0 h-auto min-h-12 min-w-12 w-full\" data-testid=\"message-image\" aria-label={images.length > 1 ? `${labels.openImage}, ${labels.imagePosition(at + 1, images.length)}` : labels.openImage} onClick={() => onOpenImage?.(image, images)} />\n </div>)}\n </div>;\n}\n\n/** Inline sent mention; workspace openers and host renderers keep their existing authority. */\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 ? <span role=\"link\" tabIndex={0} className=\"font-medium text-primary\" data-testid=\"message-mention\" data-path={path} aria-label={`Open ${path}`} onClick={() => open(path)} onKeyDown={event => { if (event.key === 'Enter') { event.preventDefault(); open(path); } }}>{text}</span>\n : <span className=\"font-medium text-primary\" data-testid=\"message-mention\" data-path={path}>{text}</span>;\n}\n\n/** The icon a file card shows for its kind. */\nfunction FileGlyph({ kind }: { readonly kind: FileKind }) {\n switch (kind) {\n case 'image': return <ImageIcon aria-hidden=\"true\" />;\n case 'sheet': return <FileSpreadsheetIcon aria-hidden=\"true\" />;\n case 'audio': return <FileAudioIcon aria-hidden=\"true\" />;\n case 'slides': return <PresentationIcon aria-hidden=\"true\" />;\n case 'document': return <FileTextIcon aria-hidden=\"true\" />;\n default: return <FileIcon aria-hidden=\"true\" />;\n }\n}\n\n/** A file a person sent (an `uploads/` mention): its icon or thumbnail, name and type. A button when it can be opened. */\nfunction FileCard({ path, open, preview, change }: { readonly path: string; readonly open: ((path: string) => void) | undefined; readonly preview: PreviewRead | undefined; readonly change?: 'created' | 'edited' }) {\n const { labels } = useChatText();\n const kind = fileKind(path), name = change ? path.split('/').pop() || path : displayName(path);\n const [src, setSrc] = useState<string | undefined>();\n // A thumbnail belongs to the provider that read it: a new provider, or a read that is refused or unavailable, shows the icon.\n useEffect(() => {\n setSrc(undefined);\n if (kind !== 'image' || !preview) return;\n const abort = new AbortController();\n preview(path, abort.signal).then(\n read => { if (!abort.signal.aborted) setSrc(read ? thumbnail(read.mimeType, read.data) : undefined); },\n () => { if (!abort.signal.aborted) setSrc(undefined); });\n return () => abort.abort();\n }, [kind, path, preview]);\n return <Attachment className=\"max-w-64\" {...(!open ? { 'data-testid': 'message-mention', 'data-path': path } : {})}>\n <AttachmentMedia variant={src ? 'image' : 'icon'}>{src ? <img src={src} alt=\"\" /> : <FileGlyph kind={kind} />}</AttachmentMedia>\n <AttachmentContent>\n <AttachmentTitle>{name}</AttachmentTitle>\n <AttachmentDescription>{change ? labels.fileChange[change] : labels.fileKind[kind]}</AttachmentDescription>\n </AttachmentContent>\n {open && <AttachmentTrigger data-testid=\"message-mention\" data-path={path} aria-label={labels.openFile(name)} onClick={() => open(path)} />}\n </Attachment>;\n}\n\n/** The file cards of a message, above its text bubble. */\nfunction FileCards({ paths, open, preview }: { readonly paths: readonly string[]; readonly open: ((path: string) => void) | undefined; readonly preview: PreviewRead | undefined }) {\n return <ul data-testid=\"message-files\" className=\"m-0 flex max-w-[85%] list-none flex-wrap justify-end gap-2 p-0\">\n {paths.map(path => <li key={path} data-testid=\"message-file\"><FileCard path={path} open={open} preview={preview} /></li>)}\n </ul>;\n}\n\n/** Retained audio is read only on Play, through the same authorized workspace preview as file cards. */\nexport function VoiceBubble({ path, transcript, preview, audioUrl, align = 'end' }: { readonly path: string; readonly transcript: ReactNode; readonly preview: PreviewRead | undefined; readonly audioUrl: AudioUrlRead | undefined; readonly align?: 'start' | 'end' }) {\n const { labels } = useChatText();\n const audio = useRef<HTMLAudioElement>(null), work = useRef<AbortController | null>(null), loadingRequest = useRef(false);\n const [playing, setPlaying] = useState(false), [loading, setLoading] = useState(false), [failed, setFailed] = useState(false), [duration, setDuration] = useState<number>();\n const source = useRef<string | undefined>(undefined), loader = useRef<() => Promise<boolean>>(async () => false);\n useEffect(() => {\n const element = audio.current;\n let objectUrl: string | undefined;\n source.current = undefined; loadingRequest.current = false; setPlaying(false); setLoading(false); setFailed(false); setDuration(undefined);\n const release = () => { if (objectUrl) { URL.revokeObjectURL(objectUrl); objectUrl = undefined; } };\n const abort = new AbortController(); work.current = abort;\n const load = async () => {\n release();\n const signed = await audioUrl?.(path, abort.signal);\n if (abort.signal.aborted) return;\n if (signed) {\n const url = new URL(signed, window.location.href);\n if (url.protocol !== 'https:' && url.protocol !== 'http:') throw new Error('Unsupported audio URL');\n source.current = url.href;\n } else {\n const read = await preview?.(path, abort.signal);\n if (abort.signal.aborted) return;\n if (!read || !/^audio\\/(?:webm|ogg|mp4|m4a|x-m4a|mpeg|mp3|wav|x-wav)(?:;|$)/i.test(read.mimeType)) throw new Error('Audio unavailable');\n const bytes = Uint8Array.from(atob(read.data), character => character.charCodeAt(0));\n // MediaRecorder WebM often has no finite metadata duration; decode only these already-requested bytes.\n try {\n if (typeof OfflineAudioContext === 'function') void new OfflineAudioContext(1, 1, 48_000).decodeAudioData(bytes.slice().buffer).then(buffer => {\n if (!abort.signal.aborted && Number.isFinite(buffer.duration)) setDuration(Math.round(buffer.duration));\n }).catch(() => {});\n } catch { /* Optional duration decoding must not prevent native playback. */ }\n objectUrl = URL.createObjectURL(new Blob([bytes], { type: read.mimeType })); source.current = objectUrl;\n }\n if (element && source.current) element.src = source.current;\n };\n // A loader belongs to this path/provider epoch, not to a later row with the same DOM node.\n loader.current = async () => { await load(); return !abort.signal.aborted; };\n return () => { abort.abort(); if (work.current === abort) work.current = null; element?.pause(); element?.removeAttribute('src'); element?.load(); source.current = undefined; release(); };\n }, [path, preview, audioUrl]);\n const toggle = async () => {\n const element = audio.current, abort = work.current;\n if (!element || !abort || loadingRequest.current) return;\n if (!element.paused) { element.pause(); return; }\n loadingRequest.current = true; setFailed(false); setLoading(true);\n try {\n if (!source.current && !await loader.current()) return;\n if (!abort.signal.aborted) await element.play();\n } catch { if (!abort.signal.aborted) setFailed(true); }\n finally { if (work.current === abort && !abort.signal.aborted) { loadingRequest.current = false; setLoading(false); } }\n };\n return <Bubble variant=\"muted\" align={align} data-testid=\"voice-bubble\"><BubbleContent>\n <div className=\"flex items-center gap-2\">\n <Button variant=\"ghost\" size=\"icon\" data-testid=\"voice-play\" aria-label={playing ? labels.voicePause : labels.voicePlay} disabled={loading || (!preview && !audioUrl)} onClick={() => { void toggle(); }}>\n {loading ? <Spinner data-icon=\"inline-start\" aria-hidden=\"true\" /> : playing ? <PauseIcon data-icon=\"inline-start\" aria-hidden=\"true\" /> : <PlayIcon data-icon=\"inline-start\" aria-hidden=\"true\" />}\n </Button>\n <span data-testid=\"voice-duration\">{duration === undefined ? '--:--' : voiceClock(duration)}</span>\n <audio ref={audio} preload=\"none\" onPlay={() => { setPlaying(true); setFailed(false); }} onPause={() => setPlaying(false)} onEnded={() => {\n setPlaying(false); const element = audio.current;\n if (element && !Number.isFinite(element.duration) && Number.isFinite(element.currentTime)) setDuration(Math.round(element.currentTime));\n }} onError={() => { setFailed(true); setPlaying(false); source.current = undefined; }} onDurationChange={() => {\n const element = audio.current; if (element && Number.isFinite(element.duration)) setDuration(Math.round(element.duration));\n }} onLoadedMetadata={() => {\n const element = audio.current; if (element && Number.isFinite(element.duration)) setDuration(Math.round(element.duration));\n }} />\n </div>\n {failed && <p role=\"alert\">{labels.voicePlayFailed}</p>}\n {transcript && <div data-testid=\"user-text\" className=\"whitespace-pre-wrap\">{transcript}</div>}\n </BubbleContent></Bubble>;\n}\n\n/**\n * A text part of a sent message. Its `uploads/` mentions become file cards above the bubble and leave the text; the message content keeps\n * them (only what is drawn changes).\n */\n/** `variant` picks the bubble: `muted` (the chat's user bubble) or `default` (the theme's primary, used for my own messages in a shared chat). */\n/** `decoration` sits inside the Bubble before its content (a tail); `header` and `footer` inside the content, around the text (a quote, the time). */\nexport function MessageText({ text, context, align = 'end', variant = 'muted', decoration, header, footer }: { readonly text: string; readonly context: Pick<RowContext, 'pieces' | 'openFile'>; readonly align?: 'start' | 'end'; readonly variant?: 'muted' | 'default'; readonly decoration?: ReactNode; readonly header?: ReactNode; readonly footer?: ReactNode }) {\n const framed = decoration !== undefined || header !== undefined || footer !== undefined;\n const wrap = (body: ReactNode) => <Bubble variant={variant} align={align}>{decoration}<BubbleContent data-testid=\"user-text\" className={framed ? 'relative' : undefined}>{header}{body}{footer}</BubbleContent></Bubble>;\n const target = targetContent(text);\n if (target) return <>\n <Badge variant=\"secondary\" data-testid=\"message-target\" title={JSON.stringify(target.target)} className=\"max-w-full truncate\">{target.label}</Badge>\n <MessageText text={target.speech} context={context} align={align} variant={variant} decoration={decoration} header={header} footer={footer} />\n </>;\n const feedback = feedbackContent(text);\n if (feedback) return <>\n {feedback.before && <MessageText text={feedback.before} context={context} align={align} variant={variant} />}\n <SentFeedback report={feedback.report} align={align} />\n {feedback.after && <MessageText text={feedback.after} context={context} align={align} variant={variant} />}\n </>;\n const open = context.pieces?.openMention;\n const render = context.pieces?.renderMention;\n const styledUploads = Boolean(context.pieces?.mentions || context.pieces?.uploads);\n const all = pieces(text, { mentions: context.pieces?.mentions ?? false, uploads: true, skills: context.pieces?.skills ?? [] }).map((piece): Piece =>\n !styledUploads && piece.kind === 'mention' && isUploadPath(piece.value!) && !isVoicePath(piece.value!) ? { text: piece.text } : piece);\n const isFile = (piece: Piece) => piece.kind === 'mention' && isUploadPath(piece.value!);\n const files = all.filter(isFile).map(piece => piece.value!);\n const voice = files.find(isVoicePath), cards = files.filter(path => path !== voice);\n if (!context.pieces && !voice) return wrap(<span className=\"whitespace-pre-wrap\">{text}</span>);\n const shown = files.length ? visibleParts(all, isFile) : all;\n const empty = shown.every(piece => piece.kind === undefined && piece.text === '');\n const content = shown.map((piece, at) => piece.kind === 'mention'\n ? <UserMention key={at} path={piece.value!} text={piece.text} open={open} render={render} />\n : piece.kind === 'skill' ? <Badge key={at} variant=\"secondary\" data-testid=\"message-skill\" data-skill={piece.value}>{piece.text}</Badge>\n : piece.text);\n return <>\n {cards.length > 0 && <FileCards paths={cards} open={context.openFile ?? open} preview={context.pieces?.preview} />}\n {voice ? <VoiceBubble path={voice} transcript={empty ? null : content} preview={context.pieces?.preview} audioUrl={context.pieces?.audioUrl} align={align} />\n : !(files.length > 0 && empty) && wrap(<span className=\"whitespace-pre-wrap\">{content}</span>)}\n </>;\n}\n\n/** A messenger's tail on the first bubble of a run. Its square part fills the bubble's top corner under the (positioned) content. */\nexport function BubbleTail({ side }: { readonly side: 'start' | 'end' }) {\n return <svg data-testid=\"bubble-tail\" data-side={side} aria-hidden=\"true\" viewBox=\"0 0 22 14\" width=\"22\" height=\"14\"\n className={`pointer-events-none absolute top-0 ${side === 'end' ? '-end-2 -scale-x-100 fill-primary' : '-start-2 fill-muted'}`}><path d=\"M0 0H22V14H8V9C8 5 5 2 0 0Z\" /></svg>;\n}\n/** Text whose last line leaves room for the time at the bottom right of the bubble (the spacer rides at the end of the last paragraph). */\nexport const clockRoom = \"[&_:is(p,li):last-child]:after:inline-block [&_:is(p,li):last-child]:after:w-14 [&_:is(p,li):last-child]:after:content-['']\";\n/** Room for a floating clock after plain inline text. */\nexport const ClockSpacer = () => <span aria-hidden=\"true\" className=\"inline-block w-14\" />;\n/**\n * The time inside a bubble (« 14:02 »). `floating` pins it bottom right over the room the text left; otherwise it sits in the line.\n * `text` and `title` replace the chat's own clock and date labels, and `className` the size (the shared chat brings its own).\n */\nexport function MessageClock({ at, tone, floating = true, pending = false, text, title, className }: { readonly at: string; readonly tone: 'muted' | 'primary'; readonly floating?: boolean; readonly pending?: boolean | undefined; readonly text?: string | undefined; readonly title?: string | undefined; readonly className?: string | undefined }) {\n const { labels } = useChatText();\n // Not confirmed by the host yet: a small clock where the time will be.\n if (pending) return <span data-testid=\"message-pending\" role=\"img\" aria-label={labels.sending} title={labels.sending}\n className={`${floating ? 'absolute end-3 bottom-1.5' : 'shrink-0 self-end'} leading-none ${tone === 'primary' ? 'opacity-80' : 'text-muted-foreground'}`}><ClockIcon aria-hidden=\"true\" className=\"size-3\" /></span>;\n return <time data-testid=\"message-time\" dateTime={at} title={title ?? labels.messageTimestamp(at)}\n className={cn(floating ? 'absolute end-3 bottom-1.5' : 'shrink-0 self-end', 'text-xs leading-none whitespace-nowrap tabular-nums', tone === 'primary' ? 'opacity-80' : 'text-muted-foreground', className)}>{text ?? labels.messageClock(at)}</time>;\n}\nconst isoAt = (ms: number | undefined) => ms !== undefined && Number.isFinite(ms) ? new Date(ms).toISOString() : undefined;\n\nfunction UserBubble({ message, images, context, align = 'end', lead = false }: { readonly message: UserMessage; readonly images: readonly ImageContent[]; readonly context: RowContext; readonly align?: 'start' | 'end'; readonly lead?: boolean }) {\n const messaging = context.messageStyle === 'messaging', at = isoAt(message.timestamp);\n const parts = typeof message.content === 'string' ? [{ type: 'text' as const, text: message.content }] : message.content;\n return <Message align={align}><MessageContent>\n <ImageThumbnails images={images} onOpenImage={context.onOpenImage} />\n {parts.map((part, index) => part.type === 'text' ? (isFileBlock(part.text) ? null : messaging\n ? <MessageText key={index} text={part.text} context={context} align={align} variant=\"default\" decoration={lead ? <BubbleTail side=\"end\" /> : undefined}\n footer={at ? <><ClockSpacer /><MessageClock at={at} tone=\"primary\" /></> : undefined} />\n : <MessageText key={index} text={part.text} context={context} align={align} />)\n : null)}\n </MessageContent></Message>;\n}\n\nfunction Notice({ tone, icon, children, testid }: { readonly tone: 'error' | 'muted'; readonly icon: ReactNode; readonly children: ReactNode; readonly testid: string }) {\n return <Alert variant={tone === 'error' ? 'destructive' : 'default'} role={tone === 'error' ? 'alert' : 'status'} data-testid={testid}>\n {icon}<AlertDescription>{children}</AlertDescription>\n </Alert>;\n}\n\n/**\n * A question or an approval waits for the person but this chat has no card for it (no `pi-chat-question` or `pi-chat-approval`): say so,\n * so the run is never silently blocked. It offers no answer UI.\n */\nfunction AnswerWaiting({ kind }: { readonly kind: 'question' | 'approval' }) {\n const { labels } = useChatText();\n return <Alert role=\"status\" data-testid=\"answer-waiting\" data-kind={kind}>\n <AlertCircleIcon className=\"mt-0.5 size-4 shrink-0\" aria-hidden=\"true\" /><AlertDescription>{labels.waitingForAnswer}</AlertDescription>\n </Alert>;\n}\n\nfunction resultText(message: ToolResultMessage): string { return message.content.map(part => part.type === 'text' ? part.text : '').join('\\n'); }\n\nfunction messageImages(row: Row): readonly ImageContent[] {\n const images = (content: ToolResultMessage['content']) => content.flatMap(part => part.type === 'image' && thumbnail(part.mimeType, part.data) ? [part] : []);\n if (row.type === 'user') return typeof row.message.content === 'string' ? [] : images(row.message.content);\n if (row.type === 'orphan-result') return images(row.message.content);\n return row.type === 'assistant' ? row.images?.filter(image => thumbnail(image.mimeType, image.data)) ?? row.parts.flatMap(part => part.kind === 'tool' && part.entry.result ? images(part.entry.result.content) : []) : [];\n}\n\n/**\n * A run of transcript rows as one scroller item (`useRowChunks`). Memoized, like each row: a row renders again only when its own row\n * or the chat's row context changes, never on a scroll or another row's update. Pass stable callbacks (`messageActions`, `unread`…)\n * so the context stays the same.\n */\nexport const TranscriptChunk = memo(function TranscriptChunk({ rows, context }: { readonly rows: readonly Row[]; readonly context: RowContext }) {\n return <MessageScrollerItem messageId={rows[0]!.key} data-transcript-chunk=\"\" className=\"flex flex-col [content-visibility:visible] [gap:inherit]\">\n {rows.map(row => <TranscriptRow key={row.key} row={row} context={context} />)}\n </MessageScrollerItem>;\n});\nconst TranscriptRow = memo(function TranscriptRow({ row, context }: { readonly row: Row; readonly context: RowContext }) {\n return <div data-row-key={row.key} className=\"min-w-0 shrink-0\"><RowView row={row} context={context} /></div>;\n});\n\nexport function RowView({ row, context }: { readonly row: Row; readonly context: RowContext }) {\n const images = messageImages(row);\n const [selection, setSelection] = useState<{ readonly index: number; readonly images: readonly ImageContent[]; readonly key: string; readonly opener: RowContext['onOpenImage'] }>();\n const current = selection && selection.key === row.key && selection.opener === context.onOpenImage && selection.images.length === images.length\n && selection.images.every((image, at) => image.mimeType === images[at]?.mimeType && image.data === images[at]?.data) ? selection : undefined;\n useEffect(() => { if (selection && !current) setSelection(undefined); }, [selection, current]);\n const openImage: NonNullable<RowContext['onOpenImage']> = image => {\n if (!thumbnail(image.mimeType, image.data)) return;\n if (context.onOpenImage) { context.onOpenImage(image, images); return; }\n const index = images.indexOf(image);\n if (index >= 0) setSelection({ index, images, key: row.key, opener: context.onOpenImage });\n };\n return <><RowBody row={row} images={images} context={{ ...context, onOpenImage: openImage }} />\n {current && <ImageViewer images={images} index={current.index} onIndexChange={index => setSelection({ ...current, index })} onClose={() => setSelection(undefined)} />}\n </>;\n}\n\nfunction RowBody({ row, images, context: liveContext }: { readonly row: Row; readonly images: readonly ImageContent[]; readonly context: RowContext }) {\n const context: RowContext = row.historical ? { ...liveContext, answer: undefined, onFork: undefined, messageActions: liveContext.historicalMessageActions ? liveContext.messageActions : undefined, replyActions: undefined, commandMentions: undefined } : liveContext;\n const { labels, icons } = useChatText();\n const renderMention = useMemo(() => context.pieces?.mentions ? (path: string, text: string) => <UserMention path={path} text={text} open={context.pieces?.openMention} render={context.pieces?.renderMention} /> : undefined, [context.pieces]);\n switch (row.type) {\n case 'user': return <article data-row-id={row.key} data-role=\"user\" aria-live={row.historical ? 'off' : undefined}><UserBubble message={row.message} images={images} context={context} lead={row.lead === true} /></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\"><Collapsible>\n <CollapsibleTrigger render={<Button variant=\"ghost\" />}>{labels.systemContext}</CollapsibleTrigger>\n <CollapsibleContent><pre className=\"whitespace-pre-wrap\">{row.text}</pre></CollapsibleContent>\n </Collapsible></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><ImageThumbnails images={images} onOpenImage={context.onOpenImage} /></article>;\n case 'assistant': {\n const settled = !row.streaming;\n const nativeActions = settled;\n const files = new Map<string, 'created' | 'edited'>();\n if (context.fileChanges) for (const part of row.parts) {\n if (part.kind !== 'tool' || part.entry.status !== 'completed') continue;\n const { call, result } = part.entry;\n const path = call.arguments['path'];\n if (!result || result.isError || result.toolName !== call.name || (call.name !== 'write' && call.name !== 'edit') || typeof path !== 'string' || !path.trim()) continue;\n const normalized = path.replace(/^(\\.\\/)+/, '');\n if (normalized) files.set(normalized, files.get(normalized) === 'created' || call.name === 'write' ? 'created' : 'edited');\n }\n const chunks = segments(row.parts, context.groupTool);\n const { question: Question, approval: Approval } = context.cards ?? {};\n const active = row.active === true || row.streaming;\n const lastText = [...row.parts].reverse().find(part => part.kind === 'text');\n const firstText = row.parts.find(part => part.kind === 'text');\n const host = nativeActions && row.text && context.messageActions\n ? <BlockActions iconOnly actions={context.messageActions(replyRef(row))} testId=\"reply-action\" menuLabel={labels.moreActions} />\n : null;\n const unread = nativeActions && row.text ? context.unread?.(replyRef(row)) : null;\n const footer = nativeActions && !row.active && row.text ? context.replyFooter?.(replyRef(row)) : null;\n return <article data-row-id={row.key} data-role=\"assistant\" aria-live={row.historical ? 'off' : undefined} data-streaming={row.streaming ? 'true' : undefined} className=\"group/message\">\n <Message><MessageContent>\n <div className=\"flex flex-col gap-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 === 'card') return <div key={part.key}>{part.content}</div>;\n if (part.kind === 'text') {\n const text = (context.renderText ?? plainText)({ text: part.text, renderMention, 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 (context.messageStyle !== 'messaging') return <Bubble key={part.key} variant=\"ghost\"><BubbleContent>{text}</BubbleContent></Bubble>;\n const time = part === lastText ? isoAt(row.timestamp) : undefined;\n return <Bubble key={part.key} variant=\"muted\" align=\"start\">{row.lead && part === firstText && <BubbleTail side=\"start\" />}\n <BubbleContent data-testid=\"reply-text\" className=\"relative\"><div className={time ? clockRoom : undefined}>{text}</div>{time && <MessageClock at={time} tone=\"muted\" />}</BubbleContent></Bubble>;\n }\n if (part.kind === 'thinking') return null; // reasoning is a step of an activity block\n if (part.kind === 'approval') return Approval ? <Approval 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 : waits(part) ? <AnswerWaiting key={part.key} kind=\"approval\" /> : null;\n if (part.kind === 'subagent') return <Fragment key={part.key}>{part.content}</Fragment>;\n if (part.kind === 'question') return Question ? <Question key={part.key} call={part.call} result={part.result} questionId={part.questionId} answer={context.answer} live={part.live} />\n : waits(part) ? <AnswerWaiting key={part.key} kind=\"question\" /> : null;\n if (part.kind === 'artifact') {\n const { artifact } = part, artifacts = context.artifacts;\n if (!artifacts || (artifact.path !== undefined && files.has(artifact.path.replace(/^(\\.\\/)+/, '')))) return null;\n const descriptor = artifact.descriptor as never;\n return <artifacts.Card key={part.key} artifact={artifact} open={artifact.state === 'ready' && (artifacts.isOpen?.(descriptor) ?? false)}\n onOpen={artifact.state === 'ready' && artifacts.open ? () => artifacts.open(descriptor) : undefined} kinds={artifacts.kinds} />;\n }\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 <ImageThumbnails images={images} onOpenImage={context.onOpenImage} />\n {files.size > 0 && <ul data-testid=\"reply-files\" className=\"m-0 flex list-none flex-wrap gap-2 p-0\">\n {[...files].map(([path, change]) => <li key={path} data-testid=\"message-file\"><FileCard path={path} change={change} open={context.openFile} preview={context.pieces?.preview} /></li>)}\n </ul>}\n {row.streaming && row.parts.length === 0 && !context.natural && <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\" />}>{context.replyError?.(replyRef(row)) ?? 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 {unread != null && unread !== false && <div data-testid=\"reply-unread\" className=\"flex flex-col items-start\">{unread}</div>}\n {nativeActions && row.text && context.replyActions?.({ key: row.key, text: row.text, timestamp: row.timestamp }, host)}\n {nativeActions && 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 iconOnly text={row.text} label={labels.copyResponse} {...(context.onCopy ? { onCopy: context.onCopy } : {})} />\n {context.onFork && row.entryId && <Button size=\"icon-sm\" variant=\"ghost\" aria-label={labels.fork} title={labels.forkHint} data-testid=\"fork-reply\"\n onClick={() => context.onFork!(row.entryId!)}><icons.fork data-icon=\"inline-start\" aria-hidden=\"true\" /></Button>}\n {host}</div>}\n {footer != null && footer !== false && <MessageFooter>{footer}</MessageFooter>}\n </MessageContent></Message>\n </article>;\n }\n }\n}\n",
88
+ "content": "'use client';\n\nimport { Fragment, memo, useEffect, useMemo, useRef, useState } from 'react';\nimport type { ReactNode } from 'react';\nimport type { ImageContent, ToolResultMessage, UserMessage } from '@earendil-works/pi-ai';\nimport { AlertCircleIcon, CircleSlashIcon, ClockIcon, FileAudioIcon, FileIcon, FileSpreadsheetIcon, FileTextIcon, ImageIcon, PauseIcon, PlayIcon, PresentationIcon } from 'lucide-react';\nimport { CopyButton } from './code-block';\nimport type { AnswerOutcome, ChatArtifactsConfig, ChatCards, CommandMentions } from './config';\nimport { feedbackContent } from './feedback-content';\nimport { SentFeedback } from './sent-feedback';\nimport { ActivityBlock } from './activity';\nimport type { ActivityState } from './activity';\nimport { Shimmer } from './shimmer';\nimport { ToolCard } from './tool';\nimport { thumbnail } from './composer';\nimport { ImageViewer } from './image-viewer';\nimport { displayName, fileKind, isUploadPath, isVoicePath, mentionKind, pieces, visibleParts } from '@hachej/boring-ui-kit/chat-text';\nimport type { FileKind, Piece } from '@hachej/boring-ui-kit/chat-text';\nimport type { AudioUrlRead, MentionsConfig, PreviewRead } from './config';\nimport { voiceClock } from './config';\nimport { Spinner } from '@/components/ui/spinner';\nimport { isFileBlock, segments, targetContent, waits } from './rows';\nimport type { DeriveOptions, Row } from './rows';\nimport { Button } from '@/components/ui/button';\nimport { BlockActions } from '../button/actions';\nimport type { BlockAction } from '../button/actions';\nimport { useChatText } from './labels';\nimport { cn } from '../utils/utils';\nimport type { ReplyRef } from './config';\nimport { Message, MessageContent, MessageFooter } from '@/components/ui/message';\nimport { Bubble, BubbleContent } from '@/components/ui/bubble';\nimport { MessageScrollerItem } from '@/components/ui/message-scroller';\nimport { Attachment, AttachmentContent, AttachmentDescription, AttachmentMedia, AttachmentTitle, AttachmentTrigger } from '@/components/ui/attachment';\nimport { Badge } from '@/components/ui/badge';\nimport { Alert, AlertDescription } from '@/components/ui/alert';\nimport { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';\n\n/** One assistant text part, as `renderText` receives it. `streaming` is true while the model still writes it. */\nexport interface ChatTextPart {\n readonly text: string;\n readonly streaming: boolean;\n /** Draws an `@path` mention (when mentions are on). */\n readonly renderMention?: ((path: string, text: string) => ReactNode) | undefined;\n /** The `/` commands a settled reply may turn into buttons. */\n readonly commandMentions?: CommandMentions | undefined;\n readonly onCopy?: ((text: string) => Promise<void>) | undefined;\n}\n/** The default text renderer: the reply as plain text. `markdownText` of `pi-chat-markdown` draws it as Markdown. */\nconst plainText = ({ text, streaming }: ChatTextPart): ReactNode =>\n <div data-testid=\"message-text\" data-streaming={streaming ? 'true' : undefined} className=\"min-w-0 whitespace-pre-wrap [overflow-wrap:anywhere]\">{text}</div>;\n\nexport type { ChatCards } from './config';\n\nexport interface RowContext {\n /** `messaging`: primary bubble for me, muted bubble for the reply, a tail on the first bubble of a run and the time inside (`PiChat messageStyle`). */\n readonly messageStyle?: 'default' | 'messaging' | undefined;\n readonly developer: boolean;\n /** Draws an assistant text part. Default: plain text (`markdownText` of `pi-chat-markdown` draws Markdown). */\n readonly renderText?: ((part: ChatTextPart) => ReactNode) | undefined;\n readonly cards?: ChatCards | undefined;\n /** `presentation=\"natural\"`: no \"working\" shimmer in a reply (the chat shows one status instead). */\n readonly natural?: boolean | undefined;\n readonly groupTool: DeriveOptions['groupTool'];\n readonly commandMentions: CommandMentions | undefined;\n /** Host openers keep their single image argument; the workspace's default also accepts the message gallery. */\n readonly onOpenImage: ((image: ImageContent, gallery?: readonly 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 kinds?: MentionsConfig['kinds']; readonly mentions: boolean; readonly uploads?: boolean; readonly skills: readonly string[]; readonly openMention?: ((path: string) => void) | undefined; readonly renderMention?: ((path: string) => ReactNode | undefined) | undefined;\n readonly preview?: PreviewRead | undefined; readonly audioUrl?: AudioUrlRead | undefined } | undefined;\n readonly voiceReplay?: boolean | undefined;\n readonly fileChanges?: boolean | undefined;\n /** Opens a file card through the host's workspace opener. */\n readonly openFile?: ((path: string) => void) | undefined;\n readonly answer: ((questionId: string, answer: string) => Promise<AnswerOutcome>) | undefined;\n readonly artifacts: { readonly open: ChatArtifactsConfig['open']; readonly isOpen?: ChatArtifactsConfig['isOpen'] | undefined; readonly kinds?: ChatArtifactsConfig['kinds']; readonly Card: NonNullable<ChatArtifactsConfig['Card']> } | 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 readonly historicalMessageActions?: boolean | undefined;\n /** Host-owned per-answer unread indicator; rendering never marks an answer seen. */\n readonly unread?: ((reply: ReplyRef) => ReactNode) | undefined;\n readonly replyError?: ((reply: ReplyRef) => ReactNode) | 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 ImageThumbnails({ images, onOpenImage }: { readonly images: readonly ImageContent[]; readonly onOpenImage: RowContext['onOpenImage'] }) {\n const { labels } = useChatText();\n if (!images.length) return null;\n return <div data-testid=\"message-images\" data-slot=\"message-images\" className={cn('grid max-w-full gap-2', images.length === 1 ? 'w-60' : 'w-120 grid-cols-2')}>\n {images.map((image, at) => <div key={at} className=\"relative min-h-12 min-w-12 self-start\">\n <img src={thumbnail(image.mimeType, image.data)} alt={labels.imageAttachment} className=\"block h-auto w-full rounded-(--radius-xl)\" />\n <Button variant=\"link\" className=\"absolute inset-0 h-auto min-h-12 min-w-12 w-full\" data-testid=\"message-image\" aria-label={images.length > 1 ? `${labels.openImage}, ${labels.imagePosition(at + 1, images.length)}` : labels.openImage} onClick={() => onOpenImage?.(image, images)} />\n </div>)}\n </div>;\n}\n\n/** Inline sent mention; workspace openers and host renderers keep their existing authority. */\nfunction UserMention({ path, text, open, render, kinds }: { readonly path: string; readonly text: string; readonly open: ((path: string) => void) | undefined; readonly render: ((path: string) => ReactNode | undefined) | undefined; readonly kinds?: MentionsConfig['kinds'] }) {\n const registered = mentionKind(path, { kinds });\n const custom = registered ? registered.kind.renderSent?.(registered.path) : render?.(path);\n if (custom !== undefined) return <>{custom}</>;\n const label = registered ? registered.kind.label(registered.path) : text;\n const activate = registered ? registered.kind.open ? () => registered.kind.open!(registered.path) : undefined : open ? () => open(path) : undefined;\n const content = <>{registered?.kind.icon}{label}</>;\n const className = 'inline-flex items-center gap-1 align-middle font-medium text-primary';\n return activate\n ? <span role=\"link\" tabIndex={0} className={className} data-testid=\"message-mention\" data-path={path} aria-label={`Open ${label}`} onClick={activate} onKeyDown={event => { if (event.key === 'Enter') { event.preventDefault(); activate(); } }}>{content}</span>\n : <span className={className} data-testid=\"message-mention\" data-path={path}>{content}</span>;\n}\n\n/** The icon a file card shows for its kind. */\nfunction FileGlyph({ kind }: { readonly kind: FileKind }) {\n switch (kind) {\n case 'image': return <ImageIcon aria-hidden=\"true\" />;\n case 'sheet': return <FileSpreadsheetIcon aria-hidden=\"true\" />;\n case 'audio': return <FileAudioIcon aria-hidden=\"true\" />;\n case 'slides': return <PresentationIcon aria-hidden=\"true\" />;\n case 'document': return <FileTextIcon aria-hidden=\"true\" />;\n default: return <FileIcon aria-hidden=\"true\" />;\n }\n}\n\n/** A file a person sent (an `uploads/` mention): its icon or thumbnail, name and type. A button when it can be opened. */\nfunction FileCard({ path, open, preview, change }: { readonly path: string; readonly open: ((path: string) => void) | undefined; readonly preview: PreviewRead | undefined; readonly change?: 'created' | 'edited' }) {\n const { labels } = useChatText();\n const kind = fileKind(path), name = change ? path.split('/').pop() || path : displayName(path);\n const [thumb, setThumb] = useState<{ readonly path: string; readonly preview: PreviewRead; readonly src: string | undefined }>();\n // A thumbnail belongs to the provider that read it: a new provider, or a read that is refused or unavailable, shows the icon.\n const src = kind === 'image' && thumb?.path === path && thumb.preview === preview ? thumb.src : undefined;\n useEffect(() => {\n if (kind !== 'image' || !preview) return;\n const abort = new AbortController();\n preview(path, abort.signal).then(\n read => { if (!abort.signal.aborted) setThumb({ path, preview, src: read ? thumbnail(read.mimeType, read.data) : undefined }); },\n () => { if (!abort.signal.aborted) setThumb({ path, preview, src: undefined }); });\n return () => abort.abort();\n }, [kind, path, preview]);\n return <Attachment className=\"max-w-64\" {...(!open ? { 'data-testid': 'message-mention', 'data-path': path } : {})}>\n <AttachmentMedia variant={src ? 'image' : 'icon'}>{src ? <img src={src} alt=\"\" /> : <FileGlyph kind={kind} />}</AttachmentMedia>\n <AttachmentContent>\n <AttachmentTitle>{name}</AttachmentTitle>\n <AttachmentDescription>{change ? labels.fileChange[change] : labels.fileKind[kind]}</AttachmentDescription>\n </AttachmentContent>\n {open && <AttachmentTrigger data-testid=\"message-mention\" data-path={path} aria-label={labels.openFile(name)} onClick={() => open(path)} />}\n </Attachment>;\n}\n\n/** The file cards of a message, above its text bubble. */\nfunction FileCards({ paths, open, preview }: { readonly paths: readonly string[]; readonly open: ((path: string) => void) | undefined; readonly preview: PreviewRead | undefined }) {\n return <ul data-testid=\"message-files\" className=\"m-0 flex max-w-[85%] list-none flex-wrap justify-end gap-2 p-0\">\n {paths.map(path => <li key={path} data-testid=\"message-file\"><FileCard path={path} open={open} preview={preview} /></li>)}\n </ul>;\n}\n\ninterface VoiceBubbleProps {\n readonly path: string; readonly transcript: ReactNode; readonly preview: PreviewRead | undefined; readonly audioUrl: AudioUrlRead | undefined; readonly align?: 'start' | 'end'; readonly replay?: boolean | undefined;\n}\n/** Voice messages show their transcript by default; the retained audio player is an explicit presentation choice. */\nexport function VoiceBubble({ replay = false, ...props }: VoiceBubbleProps) {\n const { labels } = useChatText();\n return replay ? <VoiceReplayBubble {...props} /> : <Bubble variant=\"muted\" align={props.align ?? 'end'} data-testid=\"voice-bubble\"><BubbleContent data-testid=\"user-text\" className=\"whitespace-pre-wrap\">{props.transcript ?? <span data-testid=\"voice-transcript-unavailable\">{labels.voiceTranscriptUnavailable}</span>}</BubbleContent></Bubble>;\n}\n\n/** Retained audio is read only on Play, through the same authorized workspace preview as file cards. */\nfunction VoiceReplayBubble({ path, transcript, preview, audioUrl, align = 'end' }: VoiceBubbleProps) {\n const { labels } = useChatText();\n const audio = useRef<HTMLAudioElement>(null), work = useRef<AbortController | null>(null), loadingRequest = useRef(false);\n const [playing, setPlaying] = useState(false), [loading, setLoading] = useState(false), [failed, setFailed] = useState(false), [duration, setDuration] = useState<number>();\n const source = useRef<string | undefined>(undefined), loader = useRef<() => Promise<boolean>>(async () => false);\n useEffect(() => {\n const element = audio.current;\n let objectUrl: string | undefined;\n // eslint-disable-next-line react-hooks/set-state-in-effect -- another recording or provider resets the player this effect owns, once per source\n source.current = undefined; loadingRequest.current = false; setPlaying(false); setLoading(false); setFailed(false); setDuration(undefined);\n const release = () => { if (objectUrl) { URL.revokeObjectURL(objectUrl); objectUrl = undefined; } };\n const abort = new AbortController(); work.current = abort;\n const load = async () => {\n release();\n const signed = await audioUrl?.(path, abort.signal);\n if (abort.signal.aborted) return;\n if (signed) {\n const url = new URL(signed, window.location.href);\n if (url.protocol !== 'https:' && url.protocol !== 'http:') throw new Error('Unsupported audio URL');\n source.current = url.href;\n } else {\n const read = await preview?.(path, abort.signal);\n if (abort.signal.aborted) return;\n if (!read || !/^audio\\/(?:webm|ogg|mp4|m4a|x-m4a|mpeg|mp3|wav|x-wav)(?:;|$)/i.test(read.mimeType)) throw new Error('Audio unavailable');\n const bytes = Uint8Array.from(atob(read.data), character => character.charCodeAt(0));\n // MediaRecorder WebM often has no finite metadata duration; decode only these already-requested bytes.\n try {\n if (typeof OfflineAudioContext === 'function') void new OfflineAudioContext(1, 1, 48_000).decodeAudioData(bytes.slice().buffer).then(buffer => {\n if (!abort.signal.aborted && Number.isFinite(buffer.duration)) setDuration(Math.round(buffer.duration));\n }).catch(() => {});\n } catch { /* Optional duration decoding must not prevent native playback. */ }\n objectUrl = URL.createObjectURL(new Blob([bytes], { type: read.mimeType })); source.current = objectUrl;\n }\n if (element && source.current) element.src = source.current;\n };\n // A loader belongs to this path/provider epoch, not to a later row with the same DOM node.\n loader.current = async () => { await load(); return !abort.signal.aborted; };\n return () => { abort.abort(); if (work.current === abort) work.current = null; element?.pause(); element?.removeAttribute('src'); element?.load(); source.current = undefined; release(); };\n }, [path, preview, audioUrl]);\n const toggle = async () => {\n const element = audio.current, abort = work.current;\n if (!element || !abort || loadingRequest.current) return;\n if (!element.paused) { element.pause(); return; }\n loadingRequest.current = true; setFailed(false); setLoading(true);\n try {\n if (!source.current && !await loader.current()) return;\n if (!abort.signal.aborted) await element.play();\n } catch { if (!abort.signal.aborted) setFailed(true); }\n finally { if (work.current === abort && !abort.signal.aborted) { loadingRequest.current = false; setLoading(false); } }\n };\n return <Bubble variant=\"muted\" align={align} data-testid=\"voice-bubble\"><BubbleContent>\n <div className=\"flex items-center gap-2\">\n <Button variant=\"ghost\" size=\"icon\" data-testid=\"voice-play\" aria-label={playing ? labels.voicePause : labels.voicePlay} disabled={loading || (!preview && !audioUrl)} onClick={() => { void toggle(); }}>\n {loading ? <Spinner data-icon=\"inline-start\" aria-hidden=\"true\" /> : playing ? <PauseIcon data-icon=\"inline-start\" aria-hidden=\"true\" /> : <PlayIcon data-icon=\"inline-start\" aria-hidden=\"true\" />}\n </Button>\n <span data-testid=\"voice-duration\">{duration === undefined ? '--:--' : voiceClock(duration)}</span>\n <audio ref={audio} preload=\"none\" onPlay={() => { setPlaying(true); setFailed(false); }} onPause={() => setPlaying(false)} onEnded={() => {\n setPlaying(false); const element = audio.current;\n if (element && !Number.isFinite(element.duration) && Number.isFinite(element.currentTime)) setDuration(Math.round(element.currentTime));\n }} onError={() => { setFailed(true); setPlaying(false); source.current = undefined; }} onDurationChange={() => {\n const element = audio.current; if (element && Number.isFinite(element.duration)) setDuration(Math.round(element.duration));\n }} onLoadedMetadata={() => {\n const element = audio.current; if (element && Number.isFinite(element.duration)) setDuration(Math.round(element.duration));\n }} />\n </div>\n {failed && <p role=\"alert\">{labels.voicePlayFailed}</p>}\n {transcript && <div data-testid=\"user-text\" className=\"whitespace-pre-wrap\">{transcript}</div>}\n </BubbleContent></Bubble>;\n}\n\n/**\n * A text part of a sent message. Its `uploads/` mentions become file cards above the bubble and leave the text; the message content keeps\n * them (only what is drawn changes).\n */\n/** `variant` picks the bubble: `muted` (the chat's user bubble) or `default` (the theme's primary, used for my own messages in a shared chat). */\n/** `decoration` sits inside the Bubble before its content (a tail); `header` and `footer` inside the content, around the text (a quote, the time). */\nexport function MessageText({ text, context, align = 'end', variant = 'muted', decoration, header, footer }: { readonly text: string; readonly context: Pick<RowContext, 'pieces' | 'openFile' | 'voiceReplay'>; readonly align?: 'start' | 'end'; readonly variant?: 'muted' | 'default'; readonly decoration?: ReactNode; readonly header?: ReactNode; readonly footer?: ReactNode }) {\n const framed = decoration !== undefined || header !== undefined || footer !== undefined;\n const wrap = (body: ReactNode) => <Bubble variant={variant} align={align}>{decoration}<BubbleContent data-testid=\"user-text\" className={framed ? 'relative' : undefined}>{header}{body}{footer}</BubbleContent></Bubble>;\n const target = targetContent(text);\n if (target) return <>\n <Badge variant=\"secondary\" data-testid=\"message-target\" title={JSON.stringify(target.target)} className=\"max-w-full truncate\">{target.label}</Badge>\n <MessageText text={target.speech} context={context} align={align} variant={variant} decoration={decoration} header={header} footer={footer} />\n </>;\n const feedback = feedbackContent(text);\n if (feedback) return <>\n {feedback.before && <MessageText text={feedback.before} context={context} align={align} variant={variant} />}\n <SentFeedback report={feedback.report} align={align} />\n {feedback.after && <MessageText text={feedback.after} context={context} align={align} variant={variant} />}\n </>;\n const open = context.pieces?.openMention;\n const render = context.pieces?.renderMention;\n const styledUploads = Boolean(context.pieces?.mentions || context.pieces?.uploads);\n const all = pieces(text, { mentions: context.pieces?.mentions ?? false, uploads: true, skills: context.pieces?.skills ?? [] }).map((piece): Piece =>\n !styledUploads && piece.kind === 'mention' && isUploadPath(piece.value!) && !isVoicePath(piece.value!) ? { text: piece.text } : piece);\n const isFile = (piece: Piece) => piece.kind === 'mention' && isUploadPath(piece.value!);\n const files = all.filter(isFile).map(piece => piece.value!);\n const voice = files.find(isVoicePath), cards = files.filter(path => path !== voice);\n if (!context.pieces && !voice) return wrap(<span className=\"whitespace-pre-wrap\">{text}</span>);\n const shown = files.length ? visibleParts(all, isFile) : all;\n const empty = shown.every(piece => piece.kind === undefined && piece.text === '');\n const content = shown.map((piece, at) => piece.kind === 'mention'\n ? <UserMention key={at} path={piece.value!} text={piece.text} open={open} render={render} kinds={context.pieces?.kinds} />\n : piece.kind === 'skill' ? <Badge key={at} variant=\"secondary\" data-testid=\"message-skill\" data-skill={piece.value}>{piece.text}</Badge>\n : piece.text);\n return <>\n {cards.length > 0 && <FileCards paths={cards} open={context.openFile ?? open} preview={context.pieces?.preview} />}\n {voice ? <VoiceBubble path={voice} transcript={empty ? null : content} preview={context.pieces?.preview} audioUrl={context.pieces?.audioUrl} align={align} replay={context.voiceReplay} />\n : !(files.length > 0 && empty) && wrap(<span className=\"whitespace-pre-wrap\">{content}</span>)}\n </>;\n}\n\n/** A messenger's tail on the first bubble of a run. Its square part fills the bubble's top corner under the (positioned) content. */\nexport function BubbleTail({ side }: { readonly side: 'start' | 'end' }) {\n return <svg data-testid=\"bubble-tail\" data-side={side} aria-hidden=\"true\" viewBox=\"0 0 22 14\" width=\"22\" height=\"14\"\n className={`pointer-events-none absolute top-0 ${side === 'end' ? '-end-2 -scale-x-100 fill-primary' : '-start-2 fill-muted'}`}><path d=\"M0 0H22V14H8V9C8 5 5 2 0 0Z\" /></svg>;\n}\n/** Text whose last line leaves room for the time at the bottom right of the bubble (the spacer rides at the end of the last paragraph). */\nexport const clockRoom = \"[&_:is(p,li):last-child]:after:inline-block [&_:is(p,li):last-child]:after:w-14 [&_:is(p,li):last-child]:after:content-['']\";\n/** Room for a floating clock after plain inline text. */\nexport const ClockSpacer = () => <span aria-hidden=\"true\" className=\"inline-block w-14\" />;\n/**\n * The time inside a bubble (« 14:02 »). `floating` pins it bottom right over the room the text left; otherwise it sits in the line.\n * `text` and `title` replace the chat's own clock and date labels, and `className` the size (the shared chat brings its own).\n */\nexport function MessageClock({ at, tone, floating = true, pending = false, text, title, className }: { readonly at: string; readonly tone: 'muted' | 'primary'; readonly floating?: boolean; readonly pending?: boolean | undefined; readonly text?: string | undefined; readonly title?: string | undefined; readonly className?: string | undefined }) {\n const { labels } = useChatText();\n // Not confirmed by the host yet: a small clock where the time will be.\n if (pending) return <span data-testid=\"message-pending\" role=\"img\" aria-label={labels.sending} title={labels.sending}\n className={`${floating ? 'absolute end-3 bottom-1.5' : 'shrink-0 self-end'} leading-none ${tone === 'primary' ? 'opacity-80' : 'text-muted-foreground'}`}><ClockIcon aria-hidden=\"true\" className=\"size-3\" /></span>;\n return <time data-testid=\"message-time\" dateTime={at} title={title ?? labels.messageTimestamp(at)}\n className={cn(floating ? 'absolute end-3 bottom-1.5' : 'shrink-0 self-end', 'text-xs leading-none whitespace-nowrap tabular-nums', tone === 'primary' ? 'opacity-80' : 'text-muted-foreground', className)}>{text ?? labels.messageClock(at)}</time>;\n}\nconst isoAt = (ms: number | undefined) => ms !== undefined && Number.isFinite(ms) ? new Date(ms).toISOString() : undefined;\n\nfunction UserBubble({ message, images, context, align = 'end', lead = false }: { readonly message: UserMessage; readonly images: readonly ImageContent[]; readonly context: RowContext; readonly align?: 'start' | 'end'; readonly lead?: boolean }) {\n const messaging = context.messageStyle === 'messaging', at = isoAt(message.timestamp);\n const parts = typeof message.content === 'string' ? [{ type: 'text' as const, text: message.content }] : message.content;\n return <Message align={align}><MessageContent>\n <ImageThumbnails images={images} onOpenImage={context.onOpenImage} />\n {parts.map((part, index) => part.type === 'text' ? (isFileBlock(part.text) ? null : messaging\n ? <MessageText key={index} text={part.text} context={context} align={align} variant=\"default\" decoration={lead ? <BubbleTail side=\"end\" /> : undefined}\n footer={at ? <><ClockSpacer /><MessageClock at={at} tone=\"primary\" /></> : undefined} />\n : <MessageText key={index} text={part.text} context={context} align={align} />)\n : null)}\n </MessageContent></Message>;\n}\n\nfunction Notice({ tone, icon, children, testid }: { readonly tone: 'error' | 'muted'; readonly icon: ReactNode; readonly children: ReactNode; readonly testid: string }) {\n return <Alert variant={tone === 'error' ? 'destructive' : 'default'} role={tone === 'error' ? 'alert' : 'status'} data-testid={testid}>\n {icon}<AlertDescription>{children}</AlertDescription>\n </Alert>;\n}\n\n/**\n * A question or an approval waits for the person but this chat has no card for it (no `pi-chat-question` or `pi-chat-approval`): say so,\n * so the run is never silently blocked. It offers no answer UI.\n */\nfunction AnswerWaiting({ kind }: { readonly kind: 'question' | 'approval' }) {\n const { labels } = useChatText();\n return <Alert role=\"status\" data-testid=\"answer-waiting\" data-kind={kind}>\n <AlertCircleIcon className=\"mt-0.5 size-4 shrink-0\" aria-hidden=\"true\" /><AlertDescription>{labels.waitingForAnswer}</AlertDescription>\n </Alert>;\n}\n\nfunction resultText(message: ToolResultMessage): string { return message.content.map(part => part.type === 'text' ? part.text : '').join('\\n'); }\n\nfunction messageImages(row: Row): readonly ImageContent[] {\n const images = (content: ToolResultMessage['content']) => content.flatMap(part => part.type === 'image' && thumbnail(part.mimeType, part.data) ? [part] : []);\n if (row.type === 'user') return typeof row.message.content === 'string' ? [] : images(row.message.content);\n if (row.type === 'orphan-result') return images(row.message.content);\n return row.type === 'assistant' ? row.images?.filter(image => thumbnail(image.mimeType, image.data)) ?? row.parts.flatMap(part => part.kind === 'tool' && part.entry.result ? images(part.entry.result.content) : []) : [];\n}\n\n/**\n * A run of transcript rows as one scroller item (`useRowChunks`). Memoized, like each row: a row renders again only when its own row\n * or the chat's row context changes, never on a scroll or another row's update. Pass stable callbacks (`messageActions`, `unread`…)\n * so the context stays the same.\n */\nexport const TranscriptChunk = memo(function TranscriptChunk({ rows, context }: { readonly rows: readonly Row[]; readonly context: RowContext }) {\n return <MessageScrollerItem messageId={rows[0]!.key} data-transcript-chunk=\"\" className=\"flex flex-col [content-visibility:visible] [gap:inherit]\">\n {rows.map(row => <TranscriptRow key={row.key} row={row} context={context} />)}\n </MessageScrollerItem>;\n});\nconst TranscriptRow = memo(function TranscriptRow({ row, context }: { readonly row: Row; readonly context: RowContext }) {\n return <div data-row-key={row.key} className=\"min-w-0 shrink-0\"><RowView row={row} context={context} /></div>;\n});\n\nexport function RowView({ row, context }: { readonly row: Row; readonly context: RowContext }) {\n const images = messageImages(row);\n const [selection, setSelection] = useState<{ readonly index: number; readonly images: readonly ImageContent[]; readonly key: string; readonly opener: RowContext['onOpenImage'] }>();\n const current = selection && selection.key === row.key && selection.opener === context.onOpenImage && selection.images.length === images.length\n && selection.images.every((image, at) => image.mimeType === images[at]?.mimeType && image.data === images[at]?.data) ? selection : undefined;\n // eslint-disable-next-line react-hooks/set-state-in-effect -- a stale selection (other row, opener or images) is dropped once, after commit\n useEffect(() => { if (selection && !current) setSelection(undefined); }, [selection, current]);\n const openImage: NonNullable<RowContext['onOpenImage']> = image => {\n if (!thumbnail(image.mimeType, image.data)) return;\n if (context.onOpenImage) { context.onOpenImage(image, images); return; }\n const index = images.indexOf(image);\n if (index >= 0) setSelection({ index, images, key: row.key, opener: context.onOpenImage });\n };\n return <><RowBody row={row} images={images} context={{ ...context, onOpenImage: openImage }} />\n {current && <ImageViewer images={images} index={current.index} onIndexChange={index => setSelection({ ...current, index })} onClose={() => setSelection(undefined)} />}\n </>;\n}\n\nfunction RowBody({ row, images, context: liveContext }: { readonly row: Row; readonly images: readonly ImageContent[]; readonly context: RowContext }) {\n const context: RowContext = row.historical ? { ...liveContext, answer: undefined, onFork: undefined, messageActions: liveContext.historicalMessageActions ? liveContext.messageActions : undefined, replyActions: undefined, commandMentions: undefined } : liveContext;\n const { labels, icons } = useChatText();\n const renderMention = useMemo(() => context.pieces?.mentions ? (path: string, text: string) => <UserMention path={path} text={text} open={context.pieces?.openMention} render={context.pieces?.renderMention} kinds={context.pieces?.kinds} /> : undefined, [context.pieces]);\n switch (row.type) {\n case 'user': return <article data-row-id={row.key} data-role=\"user\" aria-live={row.historical ? 'off' : undefined}><UserBubble message={row.message} images={images} context={context} lead={row.lead === true} /></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\"><Collapsible>\n <CollapsibleTrigger render={<Button variant=\"ghost\" />}>{labels.systemContext}</CollapsibleTrigger>\n <CollapsibleContent><pre className=\"whitespace-pre-wrap\">{row.text}</pre></CollapsibleContent>\n </Collapsible></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><ImageThumbnails images={images} onOpenImage={context.onOpenImage} /></article>;\n case 'assistant': {\n const settled = !row.streaming;\n const nativeActions = settled;\n const files = new Map<string, 'created' | 'edited'>();\n if (context.fileChanges) for (const part of row.parts) {\n if (part.kind !== 'tool' || part.entry.status !== 'completed') continue;\n const { call, result } = part.entry;\n const path = call.arguments['path'];\n if (!result || result.isError || result.toolName !== call.name || (call.name !== 'write' && call.name !== 'edit') || typeof path !== 'string' || !path.trim()) continue;\n const normalized = path.replace(/^(\\.\\/)+/, '');\n if (normalized) files.set(normalized, files.get(normalized) === 'created' || call.name === 'write' ? 'created' : 'edited');\n }\n const chunks = segments(row.parts, context.groupTool);\n const { question: Question, approval: Approval } = context.cards ?? {};\n const active = row.active === true || row.streaming;\n const lastText = [...row.parts].reverse().find(part => part.kind === 'text');\n const firstText = row.parts.find(part => part.kind === 'text');\n const host = nativeActions && row.text && context.messageActions\n ? <BlockActions iconOnly actions={context.messageActions(replyRef(row))} testId=\"reply-action\" menuLabel={labels.moreActions} />\n : null;\n const unread = nativeActions && row.text ? context.unread?.(replyRef(row)) : null;\n const footer = nativeActions && !row.active && row.text ? context.replyFooter?.(replyRef(row)) : null;\n return <article data-row-id={row.key} data-role=\"assistant\" aria-live={row.historical ? 'off' : undefined} data-streaming={row.streaming ? 'true' : undefined} className=\"group/message\">\n <Message><MessageContent>\n <div className=\"flex flex-col gap-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 === 'card') return <div key={part.key}>{part.content}</div>;\n if (part.kind === 'text') {\n const text = (context.renderText ?? plainText)({ text: part.text, renderMention, 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 (context.messageStyle !== 'messaging') return <Bubble key={part.key} variant=\"ghost\"><BubbleContent>{text}</BubbleContent></Bubble>;\n const time = part === lastText ? isoAt(row.timestamp) : undefined;\n return <Bubble key={part.key} variant=\"muted\" align=\"start\">{row.lead && part === firstText && <BubbleTail side=\"start\" />}\n <BubbleContent data-testid=\"reply-text\" className=\"relative\"><div className={time ? clockRoom : undefined}>{text}</div>{time && <MessageClock at={time} tone=\"muted\" />}</BubbleContent></Bubble>;\n }\n if (part.kind === 'thinking') return null; // reasoning is a step of an activity block\n if (part.kind === 'approval') return Approval ? <Approval 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 : waits(part) ? <AnswerWaiting key={part.key} kind=\"approval\" /> : null;\n if (part.kind === 'subagent') return <Fragment key={part.key}>{part.content}</Fragment>;\n if (part.kind === 'question') return Question ? <Question key={part.key} call={part.call} result={part.result} questionId={part.questionId} answer={context.answer} live={part.live} />\n : waits(part) ? <AnswerWaiting key={part.key} kind=\"question\" /> : null;\n if (part.kind === 'artifact') {\n const { artifact } = part, artifacts = context.artifacts;\n if (!artifacts || (artifact.path !== undefined && files.has(artifact.path.replace(/^(\\.\\/)+/, '')))) return null;\n const descriptor = artifact.descriptor as never;\n return <artifacts.Card key={part.key} artifact={artifact} open={artifact.state === 'ready' && (artifacts.isOpen?.(descriptor) ?? false)}\n onOpen={artifact.state === 'ready' && artifacts.open ? () => artifacts.open(descriptor) : undefined} kinds={artifacts.kinds} />;\n }\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 <ImageThumbnails images={images} onOpenImage={context.onOpenImage} />\n {files.size > 0 && <ul data-testid=\"reply-files\" className=\"m-0 flex list-none flex-wrap gap-2 p-0\">\n {[...files].map(([path, change]) => <li key={path} data-testid=\"message-file\"><FileCard path={path} change={change} open={context.openFile} preview={context.pieces?.preview} /></li>)}\n </ul>}\n {row.streaming && row.parts.length === 0 && !context.natural && <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\" />}>{context.replyError?.(replyRef(row)) ?? 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 {unread != null && unread !== false && <div data-testid=\"reply-unread\" className=\"flex flex-col items-start\">{unread}</div>}\n {nativeActions && row.text && context.replyActions?.({ key: row.key, text: row.text, timestamp: row.timestamp }, host)}\n {nativeActions && 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-md:opacity-100 motion-reduce:transition-none\">\n <CopyButton iconOnly text={row.text} label={labels.copyResponse} {...(context.onCopy ? { onCopy: context.onCopy } : {})} />\n {context.onFork && row.entryId && <Button size=\"icon-sm\" variant=\"ghost\" aria-label={labels.fork} title={labels.forkHint} data-testid=\"fork-reply\"\n onClick={() => context.onFork!(row.entryId!)}><icons.fork data-icon=\"inline-start\" aria-hidden=\"true\" /></Button>}\n {host}</div>}\n {footer != null && footer !== false && <MessageFooter>{footer}</MessageFooter>}\n </MessageContent></Message>\n </article>;\n }\n }\n}\n",
117
89
  "type": "registry:component",
118
90
  "target": "components/pi-chat/message.tsx"
119
91
  },
120
92
  {
121
93
  "path": "registry/pi-chat/notice.tsx",
122
- "content": "'use client';\n\nimport type { ReactNode } from 'react';\nimport type { ChatSnapshot } from '@hachej/boring-ui-kit/native-chat';\nimport { Button } from '@/components/ui/button';\nimport { Alert } from '@/components/ui/alert';\nimport { Shimmer } from './shimmer';\nimport { useChatText } from './labels';\n\nexport function Notice({ tone = 'error', children, testid }: { readonly tone?: 'error' | 'info'; readonly children: ReactNode; readonly testid?: string }) {\n return <Alert variant={tone === 'error' ? 'destructive' : 'default'} role={tone === 'error' ? 'alert' : 'status'} {...(testid ? { 'data-testid': testid } : {})}\n className=\"flex flex-wrap items-center gap-2\">{children}</Alert>;\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, natural = false }: {\n readonly state: Pick<ChatSnapshot, 'send' | 'stop'>;\n readonly error: string | null;\n readonly onReconcile: () => void;\n readonly onRetry: () => void;\n /** `presentation=\"natural\"`: a blocked send shows a plain label, not the controller's reason. */\n readonly natural?: boolean;\n}) {\n const { labels } = useChatText();\n return <>\n {error && <Notice testid=\"chat-error\">{error}</Notice>}\n {state.send.kind === 'blocked' && <Notice testid=\"send-blocked\">{natural ? labels.sendUnavailable : state.send.reason}</Notice>}\n {state.send.kind === 'unknown' && <Notice testid=\"send-unknown\"><span className=\"flex-1\">{'reason' in state.send ? state.send.reason : labels.sendUnknown}</span>\n <Button size=\"sm\" variant=\"outline\" onClick={onReconcile}>{labels.checkSubmission}</Button>\n {(!('retryable' in state.send) || state.send.retryable) && <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\n/** `presentation=\"natural\"`: whether the one \"preparing\" status shows (owned by the kit's chat view). */\nexport { preparing } from '@hachej/boring-ui-kit/chat-view';\n\n/** The one status line of natural presentation. */\nexport function PreparingStatus({ children }: { readonly children?: ReactNode }) {\n const { labels } = useChatText();\n return <p role=\"status\" data-testid=\"preparing\" className=\"m-0 flex items-center gap-2 px-1 text-xs text-muted-foreground\"><Shimmer>{children ?? labels.preparing}</Shimmer></p>;\n}\n",
94
+ "content": "'use client';\n\nimport type { ReactNode } from 'react';\nimport type { ChatSnapshot } from '@hachej/boring-ui-kit/native-chat';\nimport { Button } from '@/components/ui/button';\nimport { Alert } from '@/components/ui/alert';\nimport { Shimmer } from './shimmer';\nimport { useChatText } from './labels';\n\nexport function Notice({ tone = 'error', children, testid }: { readonly tone?: 'error' | 'info'; readonly children: ReactNode; readonly testid?: string }) {\n return <Alert variant={tone === 'error' ? 'destructive' : 'default'} role={tone === 'error' ? 'alert' : 'status'} {...(testid ? { 'data-testid': testid } : {})}\n className=\"flex flex-wrap items-center gap-2\">{children}</Alert>;\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, natural = false }: {\n readonly state: Pick<ChatSnapshot, 'send' | 'stop'>;\n readonly error: string | null;\n readonly onReconcile: () => void;\n readonly onRetry: () => void;\n /** `presentation=\"natural\"`: a blocked send shows a plain label, not the controller's reason. */\n readonly natural?: boolean;\n}) {\n const { labels } = useChatText();\n return <>\n {error && <Notice testid=\"chat-error\">{error}</Notice>}\n {state.send.kind === 'blocked' && <Notice testid=\"send-blocked\">{natural ? labels.sendUnavailable : state.send.reason}</Notice>}\n {state.send.kind === 'unknown' && <Notice testid=\"send-unknown\"><span className=\"flex-1\">{'reason' in state.send ? state.send.reason : labels.sendUnknown}</span>\n <Button size=\"sm\" variant=\"outline\" onClick={onReconcile}>{labels.checkSubmission}</Button>\n {(!('retryable' in state.send) || state.send.retryable) && <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\n/** `presentation=\"natural\"`: whether the one \"preparing\" status shows (owned by the kit's chat view). */\nexport { preparing } from '@hachej/boring-ui-kit/chat-view';\nimport { preparing } from '@hachej/boring-ui-kit/chat-view';\n\n/** The one status line of natural presentation. */\nexport function PreparingStatus({ children }: { readonly children?: ReactNode }) {\n const { labels } = useChatText();\n return <p role=\"status\" data-testid=\"preparing\" className=\"m-0 flex items-center gap-2 px-1 text-xs text-muted-foreground\"><Shimmer>{children ?? labels.preparing}</Shimmer></p>;\n}\n\n/** Shared full/compact connection presentation; custom host recovery content is never lost in Ambient. */\nexport function ChatConnectionNotice({ state, onReconnect, renderConnectionError, compact = false, fallback }: {\n readonly state: Pick<ChatSnapshot, 'connection' | 'disposed'>;\n readonly onReconnect: () => void;\n readonly renderConnectionError?: ((error: unknown) => ReactNode) | undefined;\n readonly compact?: boolean;\n /** Surface-specific copy; a host error renderer still takes precedence. */\n readonly fallback?: { readonly error: ReactNode; readonly closed: ReactNode };\n}) {\n const { labels, icons } = useChatText();\n const connection = state.connection;\n if (connection.kind !== 'error' && connection.kind !== 'closed') return null;\n return <Notice tone={compact ? 'info' : connection.kind === 'error' ? 'error' : 'info'} testid=\"connection-notice\">\n <span className=\"flex-1\">{connection.kind === 'error' ? renderConnectionError ? renderConnectionError(connection.error) : fallback?.error ?? labels.loadFailed : fallback?.closed ?? labels.disconnected}</span>\n {!state.disposed && <Button size=\"sm\" variant=\"outline\" onClick={onReconnect}>{!compact && <icons.reconnect data-icon=\"inline-start\" aria-hidden=\"true\" />}{labels.reconnect}</Button>}\n </Notice>;\n}\n\n/** PiChat and Ambient choose the same natural/developer status without owning another run lifecycle. */\nexport function ChatStatusLine({ natural, working, waitingForAnswer, derived, stop }: {\n readonly natural: boolean; readonly working: boolean; readonly waitingForAnswer: boolean;\n readonly derived: Pick<import('./rows').Derived, 'run' | 'retry' | 'compacting' | 'stageStatus'>;\n readonly stop: ChatSnapshot['stop'];\n}) {\n const { labels } = useChatText();\n if (natural) return preparing({ natural, waitingForAnswer, run: derived.run, retry: derived.retry, compacting: derived.compacting, stop }) ? <PreparingStatus>{derived.stageStatus}</PreparingStatus> : null;\n return <>\n {working && <p role=\"status\" data-testid=\"agent-status\" className=\"m-0 flex items-center gap-2 px-1 text-xs text-muted-foreground\">\n <Shimmer active={!waitingForAnswer}>{waitingForAnswer ? labels.waitingForAnswer : derived.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 </>;\n}\n",
123
95
  "type": "registry:component",
124
96
  "target": "components/pi-chat/notice.tsx"
125
97
  },
126
98
  {
127
99
  "path": "registry/pi-chat/pi-chat.tsx",
128
- "content": "'use client';\n\nimport { useEffect, useMemo, useRef, useState } from 'react';\nimport type { ReactNode } from 'react';\nimport type { ChatController } from '@hachej/boring-ui-kit/native-chat';\nimport { Loader2Icon } from 'lucide-react';\nimport { Button } from '@/components/ui/button';\nimport { Avatar, AvatarFallback } from '@/components/ui/avatar';\nimport { Badge } from '@/components/ui/badge';\nimport { Input } from '@/components/ui/input';\nimport { Separator } from '@/components/ui/separator';\nimport { MessageScroller, MessageScrollerProvider, MessageScrollerViewport, MessageScrollerContent, MessageScrollerItem, MessageScrollerButton } from '@/components/ui/message-scroller';\nimport { BlockActions } from '../button/actions';\nimport type { BlockAction } from '../button/actions';\nimport { Composer } from './composer';\nimport type { ComposerFeedback, ComposerProps } from './composer';\nimport { ConversationFiles } from './conversation-files';\nimport type { AttachmentsConfig, ConversationsConfig, PendingVoice, VoiceMessageConfig, VoiceMessageHandle, VoiceRecorderHook } from './config';\nimport { displayName } from './config';\nimport { EmptyState } from './empty-state';\nimport type { Suggestion } from './empty-state';\nimport { ConversationHistory, TranscriptHistory } from './history';\nimport { TranscriptChunk } from './message';\nimport { markLeads } from './rows';\nimport type { Row } from './rows';\nimport { MessageQueue } from './queue';\nimport { ChatNotices, Notice, PreparingStatus, preparing } from './notice';\nimport { Shimmer } from './shimmer';\nimport { PAGE_FIRST, PAGE_MORE, useChatSession, useRowChunks, useTranscript } from './session';\nimport { useChatDraft } from './use-chat-draft';\nimport { useChatPlacement } from './use-remote-chat';\nimport type { ChatPlacement } from './use-remote-chat';\nimport type { ChatFeatureProps, ChatPaging, FilesHandler } 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 { ChatPaging, PiChatActions } from './session';\nexport type { ChatCard, Mode } from './rows';\nexport type { AnswerOutcome, ApprovalCardProps, ApprovalDecision, ChatArtifact, ChatArtifactCardProps, ChatArtifactsConfig, ChatCards, QuestionCardProps, SubagentRenderer } from './config';\nexport { ASK_USER_TOOL } from './config';\nexport type { ChatTextPart } from './message';\nexport type { MentionPickerProps, ModelEffortPickerProps, SlashPickerProps } from './config';\nexport type { PendingVoice, PendingVoiceBubbleProps, VoiceMessageButtonProps, VoiceMessageHandle } from './config';\nexport type { CameraSheetProps, VoiceRecorderHook, VoiceRecorderOptions } from './config';\nexport { voiceClock } from './config';\nexport { ChatTextProvider } from './labels';\nexport type { CommandMention, CommandMentions } from './config';\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 { BlockActions } from '../button/actions';\nexport { useChatDraft } from './use-chat-draft';\nexport { useConversations } from './use-conversations';\nexport type { ChatController, ChatSnapshot } from '@hachej/boring-ui-kit/native-chat';\nexport { MessageText, VoiceBubble } from './message';\nexport { useTranscript } from './session';\nexport type { BlockAction, BlockIcon } from '../button/actions';\nexport type { AudioUrlRead, VoiceMessageConfig, AttachmentsConfig, ConversationItem, ConversationsConfig, EffortConfig, FileKind, MentionResult, MentionsConfig, ModelConfig, ModelRef, PasteToFile, PreviewRead, ReplyRef, SlashApi, SlashCommand, SlashConfig, SlashSkill, UploadResult } from './config';\n\nexport interface ChatTimeline {\n readonly count: number;\n readonly render: (context: { readonly focusComposer: () => void; readonly openFile?: ((path: string) => void) | undefined; readonly pendingVoice?: ReactNode; readonly paging?: ChatPaging | undefined }) => ReactNode;\n readonly afterSend?: () => void;\n}\n\nexport interface PiChatProps extends ChatFeatureProps {\n /** Optional host transcript. Absent: native rows, history and scroll behavior are unchanged. */\n readonly timeline?: ChatTimeline | undefined;\n /** Authorized host errors may provide their own message. */\n readonly renderConnectionError?: ((error: unknown) => ReactNode) | undefined;\n readonly controller: ChatController;\n /** Where this chat is shown, reported with each submit (advisory, never authority). `docked` by default; a host that floats or tucks the same chat in a drawer says `floating`. */\n readonly placement?: ChatPlacement | undefined;\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 /**\n * How a message looks. `default` (today): my message is a muted bubble on the right, the reply plain text. `messaging`: a messenger look\n * for a one-to-one conversation: my message a primary bubble on the right, the reply a muted bubble on the left, a tail on the first\n * bubble of each run and the time inside. Tool steps, traces, voice and cards are unchanged. Theme tokens only.\n */\n readonly messageStyle?: 'default' | 'messaging' | 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 /** `false` lets the host supply one shared header around chat and viewers. Default true. */\n readonly header?: boolean;\n readonly className?: string;\n /** Pad the chat's bottom by how far it reaches below the visual viewport (the phone's soft keyboard). Default true; `false` for a host that already follows the keyboard itself, such as a bottom drawer whose lower part sits off screen by design. */\n readonly keyboardInset?: boolean;\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 /** Host controls at the left edge of the composer bar, before \"+\" (for example an app's own menu). Absent: nothing changes. */\n readonly composerStart?: ReactNode;\n /** With `voiceMessage`: the microphone takes Send's place while there is nothing to send, and Send comes back with the first character or file (WhatsApp's composer). Default false. */\n readonly voiceReplacesSend?: boolean;\n /** Hold-to-send one retained audio upload plus transcript. Omit to keep the existing composer unchanged. */\n readonly voiceMessage?: VoiceMessageConfig | undefined;\n /** Local voice rows owned by the shell's shared microphone; rendered with the native transcript, never the composer. */\n readonly pendingVoice?: readonly PendingVoice[] | undefined;\n /** Host content under the composer (for example a collapsed list of the person's requests). Absent: nothing is shown. */\n readonly belowComposer?: 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 /** The phone camera's Take a photo entry for an `onFiles` chat (`CameraSheet` of `pi-chat-attachments`); with `attachments`, set `attachments.Camera` instead. */\n readonly camera?: AttachmentsConfig['Camera'];\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 /** Empty desktop composition. `centered` puts the composer beneath the greeting; `docked` keeps the former layout. Phones always dock it. */\n readonly emptyLayout?: 'centered' | 'docked';\n /** Two-row reference composer by default. Explicitly select `pill`, `stacked` or `inline` for the earlier layouts. */\n readonly composerLayout?: ComposerProps['layout'];\n /** A conversation title, separate from the agent name, with optional click-to-rename. */\n readonly conversationTitle?: string | undefined;\n readonly onRenameTitle?: ((title: string) => void | Promise<void>) | undefined;\n /** Show the header connection badge. Default false; connection state still controls actions and failures stay visible. */\n readonly showConnectionStatus?: boolean;\n /** The optional annotate toggle and notes chip in the composer (the registry `feedback` item's `useComposerFeedback`). Omit it and nothing changes. */\n readonly feedback?: ComposerFeedback;\n /** Keeps the composer's half-typed message in localStorage under this key (a conversation id), across reloads and tabs; see `useChatDraft`. Omit it and nothing is stored. */\n readonly draftKey?: string | undefined;\n}\n\ntype TranscriptRow = { readonly key: string; readonly kind: 'native'; readonly row: Row }\n | { readonly key: string; readonly kind: 'voice'; readonly voice: PendingVoice };\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 // A new controller or a new voice recorder hook starts a fresh session, so the recorder's hooks keep their order.\n const recorder = props.voiceMessage?.useRecorder ?? noVoice;\n const [mount, setMount] = useState({ controller: props.controller, recorder, sequence: 0 });\n if (mount.controller !== props.controller || mount.recorder !== recorder) setMount({ controller: props.controller, recorder, sequence: mount.sequence + 1 });\n const text = useMergedText(props.labels, props.icons, chatTextFor(props.locale));\n return <ChatTextProvider value={text}><MessageScrollerProvider key={mount.sequence} autoScroll><PiChatSession {...props} activeController={active} /></MessageScrollerProvider></ChatTextProvider>;\n}\n\nfunction ConnectionBadge({ kind }: { readonly kind: string }) {\n const { labels } = useChatText();\n const live = kind === 'connected';\n return <Badge variant={live ? 'outline' : 'secondary'} data-testid=\"connection\" data-state={kind} role=\"status\">\n {live ? labels.live : kind === 'connecting' || kind === 'idle' ? labels.connecting : labels.reconnecting}\n </Badge>;\n}\n\n/** No voice message: without `voiceMessage.useRecorder` (from `pi-chat-voice`) the chat records nothing. */\nconst silent: VoiceMessageHandle = { canStart: false, phase: 'idle', seconds: 0, captureSequence: 0, problem: undefined, pending: [], start: () => {}, finish: () => {}, cancel: () => {} };\nconst noVoice: VoiceRecorderHook = () => silent;\n/** A shell's pending voice row when no `voiceMessage.Bubble` is plugged in: nothing to draw. */\nfunction NoVoiceBubble(_: { readonly pending: PendingVoice | undefined }) { return null; }\n\nfunction PiChatSession({ controller, placement = 'docked', mode = 'expert', presentation, messageStyle = 'default', className, keyboardInset = true, actions, avatar, headerActions, header = true, decisions, controls, tools, composerStart, voiceReplacesSend = false, voiceMessage, pendingVoice, belowComposer, composerChips, composerHeader, composerHasContent, onPickFiles, timeline, renderConnectionError, headerStart, renderEntry, hideLine, displayLimit, paging, historicalMessageActions, unread, replyError, renderTool, toolRenderers, renderText, cards, groupTool, commandMentions,\n onOpenImage, onCopy, onComposerKeyDown, onFiles, camera, fileAccept = 'image/*', emptyState, suggestions, messageActions, replyFooter, slash, mentions, attachments, model, effort, artifacts, conversations, historyList = true, showHistory = true, showConnectionStatus = false, emptyLayout = 'centered', composerLayout = 'card', conversationTitle, onRenameTitle, feedback, draftKey, onOpenFile, fileChanges, pasteToFile, activeController: active }: PiChatProps & { readonly activeController: { readonly current: ChatController } }) {\n const { labels, icons } = useChatText();\n useChatDraft(controller, draftKey);\n useChatPlacement(controller, placement);\n const { title } = labels;\n const [pickingConversation, setPickingConversation] = useState(false);\n const scrollToBottom = useRef<() => void>(() => {});\n const voice = (voiceMessage?.useRecorder ?? noVoice)({ controller, config: voiceMessage, attachments, labels, activeController: active, admitted: () => timeline ? timeline.afterSend?.() : scrollToBottom.current() });\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 || messageStyle === 'messaging' ? { ...(canFork ? { onFork: (entryId: string) => { void fork.current?.(entryId).catch(() => {}); } } : {}), ...(messageStyle === 'messaging' ? { messageStyle } : {}) } : undefined, [canFork, messageStyle]);\n const session = useChatSession({ controller, activeController: active, mode, presentation, actions, renderEntry, hideLine, historicalMessageActions, unread, replyError, renderTool, toolRenderers, renderText, cards, groupTool, commandMentions, onOpenImage, onCopy, onComposerKeyDown, onFiles, camera, fileAccept,\n slash, mentions, attachments, model, effort, artifacts, messageActions, replyFooter, afterSend: () => timeline ? timeline.afterSend?.() : scrollToBottom.current(), feedback, rowExtras, onOpenFile, fileChanges, pasteToFile, composerChips, composerHeader, composerHasContent, onPickFiles });\n const { state, derived, rows: nativeRows, queued, queueActions, working, waitingForAnswer, connected, error, act, textarea, rowContext, composer, files, loading } = session;\n const voiceRows = pendingVoice ?? voice.pending;\n const VoiceButton = voiceMessage?.Button, VoiceBubbleView = voiceMessage?.Bubble ?? NoVoiceBubble;\n const rows = useMemo(() => messageStyle === 'messaging' ? markLeads(nativeRows) : nativeRows, [nativeRows, messageStyle]);\n const transcriptRows: readonly TranscriptRow[] = [\n ...rows.map(row => ({ key: row.key, kind: 'native' as const, row })),\n ...voiceRows.map(voice => ({ key: `voice:${voice.id}`, kind: 'voice' as const, voice })),\n ];\n const pendingRows = voiceRows.map(item => <MessageScrollerItem key={`voice:${item.id}`} messageId={`voice:${item.id}`} data-local-voice=\"\" className=\"[content-visibility:visible]\"><VoiceBubbleView pending={item} /></MessageScrollerItem>);\n const empty = (timeline ? timeline.count === 0 : session.empty) && voiceRows.length === 0;\n const conversationFiles = new Map(files.map(file => [file.id, file]));\n for (const item of voiceRows) if (item.path && !conversationFiles.has(`file:${item.path}`)) {\n const path = item.path, open = onOpenFile ?? mentions?.open;\n conversationFiles.set(`file:${path}`, { id: `file:${path}`, name: displayName(path), open: open ? () => open(path) : undefined });\n }\n const { pinned, retry } = derived;\n const showPreparing = preparing({ natural: session.natural, waitingForAnswer, run: derived.run, retry, compacting: derived.compacting, stop: state.stop });\n const transcript = useTranscript(transcriptRows, displayLimit ?? paging?.first ?? PAGE_FIRST, paging?.more ?? PAGE_MORE, { state: state.history, connected: !state.disposed && connected, load: controller.loadEarlier }, displayLimit === undefined);\n const { stick, hidden } = transcript;\n scrollToBottom.current = () => { transcript.reset(); void stick.scrollToBottom('instant'); };\n const visible = transcript.visible(transcriptRows);\n // Native rows come before pending voice rows, so the hidden ones are the oldest native rows.\n const chunks = useRowChunks(useMemo(() => rows.slice(Math.min(rows.length, hidden)), [rows, hidden]));\n const { barStart, barNote } = session.pickers();\n const connectionKind = state.connection.kind;\n const [renamingTitle, setRenamingTitle] = useState(false);\n const [titleError, setTitleError] = useState(false);\n const page = useRef<HTMLElement>(null);\n useEffect(() => {\n const viewport = globalThis.visualViewport;\n if (!keyboardInset || !viewport) return;\n const element = page.current;\n if (!element) return;\n const measure = () => element.style.setProperty('--composer-keyboard-inset', `${Math.max(0, element.getBoundingClientRect().bottom - viewport.height - viewport.offsetTop)}px`);\n const observer = typeof ResizeObserver === 'undefined' ? undefined : new ResizeObserver(measure);\n observer?.observe(element);\n measure(); viewport.addEventListener('resize', measure); viewport.addEventListener('scroll', measure);\n return () => { observer?.disconnect(); viewport.removeEventListener('resize', measure); viewport.removeEventListener('scroll', measure); };\n }, []);\n\n return <section ref={page} data-boring=\"pi-chat\" data-connection={connectionKind} data-empty={empty && !loading ? emptyLayout : undefined} aria-label={title} className={cn('pi-chat relative box-border flex h-full min-h-0 min-w-0 flex-col overflow-hidden bg-background text-foreground ', keyboardInset && 'max-[641px]:pb-(--composer-keyboard-inset)', empty && emptyLayout === 'centered' && 'min-[641px]:justify-center', className)}>\n {header && <header className={cn(empty && emptyLayout === 'centered' && 'min-[641px]:absolute min-[641px]:inset-x-0 min-[641px]:top-0', 'flex h-13 shrink-0 items-center gap-2 px-3 sm:gap-3 sm:px-4')}>\n {headerStart}\n {avatar && <Avatar data-testid=\"chat-avatar\" className=\"overflow-hidden\"><AvatarFallback className=\"*:max-h-full *:max-w-full\">{avatar}</AvatarFallback></Avatar>}\n {renamingTitle && onRenameTitle ? <form className=\"min-w-0 flex-1\" onSubmit={event => { event.preventDefault(); const value = new FormData(event.currentTarget).get('title')?.toString().trim(); if (value) { setTitleError(false); void Promise.resolve().then(() => onRenameTitle(value)).catch(() => setTitleError(true)); } setRenamingTitle(false); }}>\n <Input name=\"title\" aria-label={labels.conversationName} maxLength={200} autoFocus defaultValue={conversationTitle ?? title} onBlur={() => setRenamingTitle(false)} onKeyDown={event => { if (event.key === 'Escape') setRenamingTitle(false); }} className=\"w-full min-w-0\" />\n </form> : <h2 className=\"m-0 min-w-0 flex-1 truncate font-(family-name:--chat-display) text-sm font-medium tracking-tight max-[641px]:text-center\">{onRenameTitle ? <Button variant=\"ghost\" className=\"max-w-full\" onClick={() => setRenamingTitle(true)}><span className=\"truncate\">{conversationTitle ?? title}</span></Button> : conversationTitle ?? title}</h2>}\n {showHistory && conversations && historyList && <Button variant=\"ghost\" size=\"sm\" data-testid=\"history-open\" aria-haspopup=\"dialog\" aria-expanded={pickingConversation} disabled={state.disposed}\n onClick={() => setPickingConversation(open => !open)}><icons.history data-icon=\"inline-start\" 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 {titleError && <p role=\"alert\" className=\"m-0 shrink-0 px-4 py-2 text-sm text-destructive\">{labels.actionFailed}</p>}\n {decisions && <><div data-boring=\"required-decisions\" className=\"shrink-0 px-4 py-2\">{decisions}</div><Separator /></>}\n {pinned.length > 0 && <><aside aria-label={labels.requiredActions} className=\"shrink-0 space-y-2 px-4 py-2\">{pinned.map(card => <div key={card.key}>{card.content}</div>)}</aside><Separator /></>}\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' ? state.connection.kind === 'error' && renderConnectionError ? renderConnectionError(state.connection.error) : labels.loadFailed : labels.disconnected}</span>\n {!state.disposed && <Button size=\"sm\" variant=\"outline\" onClick={() => act(controller.connect)}><icons.reconnect data-icon=\"inline-start\" aria-hidden=\"true\" />{labels.reconnect}</Button>}\n </Notice></div>}\n {pickingConversation && conversations && historyList && <ConversationHistory conversations={conversations} onClose={() => setPickingConversation(false)} />}\n\n <div data-testid=\"conversation-content\" className={cn('relative min-h-0 flex-1', empty && emptyLayout === 'centered' && 'min-[641px]:min-h-60 min-[641px]:flex-none')}>\n {timeline ? timeline.render({ focusComposer: () => textarea.current?.focus(), openFile: onOpenFile ?? mentions?.open, pendingVoice: pendingRows, paging }) : <MessageScroller>\n <MessageScrollerViewport ref={stick.scrollRef} data-testid=\"transcript-scroll\" aria-label={labels.messages} className=\"min-h-0 flex-1 scrollbar-thumb-border scrollbar-track-transparent\">\n {!empty && <TranscriptHistory history={state.history} connected={!state.disposed && connected} onLoad={transcript.reveal} sentinelRef={transcript.sentinelRef} hidden={hidden} loaded={transcript.loaded} />}\n <div className=\"mx-auto w-full max-w-[720px] px-4 pt-6 pb-8 sm:px-6\">\n <MessageScrollerContent aria-label={labels.messages} aria-live=\"polite\" data-testid=\"transcript\">\n {chunks.map(run => <TranscriptChunk key={run[0]!.key} rows={run} context={rowContext} />)}\n {visible.map(item => item.kind === 'voice' && <MessageScrollerItem key={item.key} messageId={item.key} data-local-voice=\"\" className=\"[content-visibility:visible]\"><VoiceBubbleView pending={item.voice} /></MessageScrollerItem>)}\n </MessageScrollerContent>\n </div>\n </MessageScrollerViewport>\n {!empty && <div data-testid=\"transcript-navigation\" className=\"flex h-12 shrink-0 items-center justify-center\">{!stick.isAtBottom && <MessageScrollerButton className=\"static inset-auto translate-x-0\" data-testid=\"jump-latest\" aria-label={labels.jumpToLatest} title={labels.jumpToLatest} onClick={transcript.reset}><icons.jumpToLatest aria-hidden=\"true\" /></MessageScrollerButton>}</div>}\n </MessageScroller>}\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 </div>\n\n <footer data-testid=\"composer-dock\" className=\"shrink-0 px-4 pt-2 pb-[max(1rem,env(safe-area-inset-bottom))] sm:px-6\">\n <div className=\"mx-auto w-full max-w-[720px] space-y-2\">\n <div {...(session.natural ? {} : { 'aria-live': 'polite' as const })} className=\"space-y-2 empty:hidden\">\n {session.natural ? showPreparing && <PreparingStatus>{derived.stageStatus}</PreparingStatus> : working && <p role=\"status\" data-testid=\"agent-status\" className=\"m-0 flex items-center gap-2 px-1 text-xs text-muted-foreground\">\n <Shimmer active={!waitingForAnswer}>{waitingForAnswer ? labels.waitingForAnswer : retry ? labels.retryPending : labels.agentWorking}</Shimmer></p>}\n {!session.natural && derived.compacting && <p role=\"status\" className=\"m-0 px-1 text-xs text-muted-foreground\">{labels.compacting}</p>}\n <ChatNotices natural={session.natural} state={state} error={error} onReconcile={() => act(controller.reconcile)} onRetry={() => act(controller.retrySameRequest)} />\n </div>\n <div>\n <ConversationFiles files={[...conversationFiles.values()]} />\n <MessageQueue items={queued} sending={state.outbox} withdraw={actions?.withdraw} actions={queueActions} />\n {voice.problem && <p role=\"alert\" data-testid=\"voice-message-problem\">{voice.problem}</p>}\n <Composer {...composer} layout={composerLayout} placeholder={labels.placeholder === 'Message the agent…' ? `Message ${title}…` : labels.placeholder} barStart={barStart} barNote={barNote} start={composerStart}\n {...(voiceMessage && VoiceButton && voiceReplacesSend ? { barEnd: tools, whenEmpty: <VoiceButton voice={voice} primary disabled={state.disposed || !connected || state.send.kind === 'unknown'} /> }\n : { barEnd: voiceMessage && VoiceButton ? <>{tools}<VoiceButton voice={voice} disabled={state.disposed || !connected || state.send.kind === 'unknown'} /></> : tools })} />\n {belowComposer !== undefined && <div data-testid=\"below-composer\" className=\"pt-2\">{belowComposer}</div>}\n </div>\n </div>\n </footer>\n </section>;\n}\n",
100
+ "content": "'use client';\n\nimport { useKeyboardInset } from '../utils/use-media';\n\nimport { useLayoutEffect, useMemo, useRef, useState } from 'react';\nimport type { ReactNode } from 'react';\nimport type { ChatController } from '@hachej/boring-ui-kit/native-chat';\nimport { Loader2Icon } from 'lucide-react';\nimport { Button } from '@/components/ui/button';\nimport { Avatar, AvatarFallback } from '@/components/ui/avatar';\nimport { Badge } from '@/components/ui/badge';\nimport { Input } from '@/components/ui/input';\nimport { Separator } from '@/components/ui/separator';\nimport { MessageScroller, MessageScrollerProvider, MessageScrollerViewport, MessageScrollerContent, MessageScrollerItem, MessageScrollerButton } from '@/components/ui/message-scroller';\nimport { BlockActions } from '../button/actions';\nimport type { BlockAction } from '../button/actions';\nimport { Composer } from './composer';\nimport type { ComposerFeedback, ComposerProps } from './composer';\nimport { ConversationFiles } from './conversation-files';\nimport type { AttachmentsConfig, ConversationsConfig, PendingVoice, VoiceMessageConfig, VoiceMessageHandle, VoiceRecorderHook } from './config';\nimport { displayName } from '@hachej/boring-ui-kit/chat-text';\nimport { EmptyState } from './empty-state';\nimport type { Suggestion } from './empty-state';\nimport { ConversationHistory, TranscriptHistory } from './history';\nimport { TranscriptChunk } from './message';\nimport { markLeads } from './rows';\nimport type { Row } from './rows';\nimport { MessageQueue } from './queue';\nimport { ChatNotices, ChatConnectionNotice, ChatStatusLine } from './notice';\nimport { PAGE_FIRST, PAGE_MORE, useChatSession, useRowChunks, useTranscript } from './session';\nimport { useChatDraft } from './use-chat-draft';\nimport { useChatPlacement } from './use-remote-chat';\nimport type { ChatPlacement } from './use-remote-chat';\nimport type { ChatFeatureProps, ChatPaging, FilesHandler } 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 { ChatPaging, PiChatActions } from './session';\nexport type { ChatCard, Mode } from './rows';\nexport type { AnswerOutcome, ApprovalCardProps, ApprovalDecision, ChatArtifact, ChatArtifactCardProps, ChatArtifactsConfig, ChatCards, QuestionCardProps, SubagentRenderer } from './config';\nexport { ASK_USER_TOOL } from './config';\nexport type { ChatTextPart } from './message';\nexport type { MentionPickerProps, ModelEffortPickerProps, SlashPickerProps } from './config';\nexport type { PendingVoice, PendingVoiceBubbleProps, VoiceMessageButtonProps, VoiceMessageHandle } from './config';\nexport type { CameraSheetProps, VoiceRecorderHook, VoiceRecorderOptions } from './config';\nexport { voiceClock } from './config';\nexport { ChatTextProvider } from './labels';\nexport type { CommandMention, CommandMentions } from './config';\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 { BlockActions } from '../button/actions';\nexport { useChatDraft } from './use-chat-draft';\nexport { useConversations } from './use-conversations';\nexport type { ChatController, ChatSnapshot } from '@hachej/boring-ui-kit/native-chat';\nexport { MessageText, VoiceBubble } from './message';\nexport { useTranscript } from './session';\nexport type { BlockAction, BlockIcon } from '../button/actions';\nexport type { AudioUrlRead, VoiceMessageConfig, AttachmentsConfig, ConversationItem, ConversationsConfig, EffortConfig, FileKind, MentionResult, MentionsConfig, ModelConfig, ModelRef, PasteToFile, PreviewRead, ReplyRef, SlashApi, SlashCommand, SlashConfig, SlashSkill, UploadResult } from './config';\n\nexport interface ChatTimeline {\n readonly count: number;\n readonly render: (context: { readonly focusComposer: () => void; readonly openFile?: ((path: string) => void) | undefined; readonly pendingVoice?: ReactNode; readonly paging?: ChatPaging | undefined }) => ReactNode;\n readonly afterSend?: () => void;\n}\n\nexport interface PiChatProps extends ChatFeatureProps {\n /** Optional host transcript. Absent: native rows, history and scroll behavior are unchanged. */\n readonly timeline?: ChatTimeline | undefined;\n /** Authorized host errors may provide their own message. */\n readonly renderConnectionError?: ((error: unknown) => ReactNode) | undefined;\n readonly controller: ChatController;\n /** Where this chat is shown, reported with each submit (advisory, never authority). `docked` by default; a host that floats or tucks the same chat in a drawer says `floating`. */\n readonly placement?: ChatPlacement | undefined;\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 /**\n * How a message looks. `default` (today): my message is a muted bubble on the right, the reply plain text. `messaging`: a messenger look\n * for a one-to-one conversation: my message a primary bubble on the right, the reply a muted bubble on the left, a tail on the first\n * bubble of each run and the time inside. Tool steps, traces, voice and cards are unchanged. Theme tokens only.\n */\n readonly messageStyle?: 'default' | 'messaging' | 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 /** `false` lets the host supply one shared header around chat and viewers. Default true. */\n readonly header?: boolean;\n readonly className?: string;\n /** Pad the chat's bottom by how far it reaches below the visual viewport (the phone's soft keyboard). Default true; `false` for a host that already follows the keyboard itself, such as a bottom drawer whose lower part sits off screen by design. */\n readonly keyboardInset?: boolean;\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 /** Host controls at the left edge of the composer bar, before \"+\" (for example an app's own menu). Absent: nothing changes. */\n readonly composerStart?: ReactNode;\n /** With `voiceMessage`: the microphone takes Send's place while there is nothing to send, and Send comes back with the first character or file (WhatsApp's composer). Default false. */\n readonly voiceReplacesSend?: boolean;\n /** Hold-to-send one retained audio upload plus transcript. Omit to keep the existing composer unchanged. */\n readonly voiceMessage?: VoiceMessageConfig | undefined;\n /** Local voice rows owned by the shell's shared microphone; rendered with the native transcript, never the composer. */\n readonly pendingVoice?: readonly PendingVoice[] | undefined;\n /** Host content under the composer (for example a collapsed list of the person's requests). Absent: nothing is shown. */\n readonly belowComposer?: 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 /** The phone camera's Take a photo entry for an `onFiles` chat (`CameraSheet` of `pi-chat-attachments`); with `attachments`, set `attachments.Camera` instead. */\n readonly camera?: AttachmentsConfig['Camera'];\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 /** Empty desktop composition. `centered` puts the composer beneath the greeting; `docked` keeps the former layout. Phones always dock it. */\n readonly emptyLayout?: 'centered' | 'docked';\n /** Two-row reference composer by default. Explicitly select `pill`, `stacked` or `inline` for the earlier layouts. */\n readonly composerLayout?: ComposerProps['layout'];\n /** A shell-owned capture uses the same recording-row replacement as native voice messages. */\n readonly composerRecording?: ReactNode;\n /** A conversation title, separate from the agent name, with optional click-to-rename. */\n readonly conversationTitle?: string | undefined;\n readonly onRenameTitle?: ((title: string) => void | Promise<void>) | undefined;\n /** Show the header connection badge. Default false; connection state still controls actions and failures stay visible. */\n readonly showConnectionStatus?: boolean;\n /** The optional annotate toggle and notes chip in the composer (the registry `feedback` item's `useComposerFeedback`). Omit it and nothing changes. */\n readonly feedback?: ComposerFeedback;\n /** Keeps the composer's half-typed message in localStorage under this key (a conversation id), across reloads and tabs; see `useChatDraft`. Omit it and nothing is stored. */\n readonly draftKey?: string | undefined;\n}\n\ntype TranscriptRow = { readonly key: string; readonly kind: 'native'; readonly row: Row }\n | { readonly key: string; readonly kind: 'voice'; readonly voice: PendingVoice };\n\n/** Borrows a concrete native controller; unmount releases presentation and uploads only. */\nexport function PiChat(props: PiChatProps) {\n const active = useRef(props.controller);\n useLayoutEffect(() => { active.current = props.controller; });\n // A new controller or a new voice recorder hook starts a fresh session, so the recorder's hooks keep their order.\n const recorder = props.voiceMessage?.useRecorder ?? noVoice;\n const [mount, setMount] = useState({ controller: props.controller, recorder, sequence: 0 });\n if (mount.controller !== props.controller || mount.recorder !== recorder) setMount({ controller: props.controller, recorder, sequence: mount.sequence + 1 });\n const text = useMergedText(props.labels, props.icons, chatTextFor(props.locale));\n return <ChatTextProvider value={text}><MessageScrollerProvider key={mount.sequence} autoScroll><PiChatSession {...props} activeController={active} /></MessageScrollerProvider></ChatTextProvider>;\n}\n\nfunction ConnectionBadge({ kind }: { readonly kind: string }) {\n const { labels } = useChatText();\n const live = kind === 'connected';\n return <Badge variant={live ? 'outline' : 'secondary'} data-testid=\"connection\" data-state={kind} role=\"status\">\n {live ? labels.live : kind === 'connecting' || kind === 'idle' ? labels.connecting : labels.reconnecting}\n </Badge>;\n}\n\n/** No voice message: without `voiceMessage.useRecorder` (from `pi-chat-voice`) the chat records nothing. */\nconst silent: VoiceMessageHandle = { canStart: false, phase: 'idle', seconds: 0, captureSequence: 0, problem: undefined, pending: [], start: () => {}, finish: () => {}, cancel: () => {} };\nconst noVoice: VoiceRecorderHook = () => silent;\n/** A shell's pending voice row when no `voiceMessage.Bubble` is plugged in: nothing to draw. */\nfunction NoVoiceBubble(_: { readonly pending: PendingVoice | undefined }) { return null; }\n\nfunction PiChatSession({ controller, placement = 'docked', mode = 'expert', presentation, voiceReplay, messageStyle = 'default', className, keyboardInset = true, actions, avatar, headerActions, header = true, decisions, controls, tools, composerStart, voiceReplacesSend = false, voiceMessage, pendingVoice, belowComposer, composerChips, composerHeader, composerHasContent, onPickFiles, timeline, renderConnectionError, headerStart, renderEntry, hideLine, displayLimit, paging, historicalMessageActions, unread, replyError, renderTool, toolRenderers, renderText, cards, groupTool, commandMentions,\n onOpenImage, onCopy, onComposerKeyDown, onFiles, camera, fileAccept = 'image/*', emptyState, suggestions, messageActions, replyFooter, slash, mentions, attachments, model, effort, artifacts, conversations, historyList = true, showHistory = true, showConnectionStatus = false, emptyLayout = 'centered', composerLayout = 'card', composerRecording, conversationTitle, onRenameTitle, feedback, draftKey, onOpenFile, fileChanges, pasteToFile, activeController: active }: PiChatProps & { readonly activeController: { readonly current: ChatController } }) {\n const { labels, icons } = useChatText();\n useChatDraft(controller, draftKey);\n useChatPlacement(controller, placement);\n const { title } = labels;\n const [pickingConversation, setPickingConversation] = useState(false);\n const scrollToBottom = useRef<() => void>(() => {});\n const useRecorder = voiceMessage?.useRecorder ?? noVoice;\n // eslint-disable-next-line react-hooks/refs -- the recorder is the host's hook, picked by prop, so the compiler cannot see it calls admitted only after a recording is admitted, never during render.\n const voice = useRecorder({ controller, config: voiceMessage, attachments, labels, activeController: active, admitted: () => timeline ? timeline.afterSend?.() : scrollToBottom.current() });\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);\n useLayoutEffect(() => { fork.current = conversations?.fork; });\n const canFork = Boolean(conversations?.fork);\n const rowExtras = useMemo(() => canFork || messageStyle === 'messaging' ? { ...(canFork ? { onFork: (entryId: string) => { void fork.current?.(entryId).catch(() => {}); } } : {}), ...(messageStyle === 'messaging' ? { messageStyle } : {}) } : undefined, [canFork, messageStyle]);\n const session = useChatSession({ controller, activeController: active, mode, presentation, voiceReplay, actions, renderEntry, hideLine, historicalMessageActions, unread, replyError, renderTool, toolRenderers, renderText, cards, groupTool, commandMentions, onOpenImage, onCopy, onComposerKeyDown, onFiles, camera, fileAccept,\n slash, mentions, attachments, model, effort, artifacts, messageActions, replyFooter, afterSend: () => timeline ? timeline.afterSend?.() : scrollToBottom.current(), feedback, rowExtras, onOpenFile, fileChanges, pasteToFile, composerChips, composerHeader, composerHasContent, onPickFiles });\n const { state, derived, rows: nativeRows, queued, queueActions, working, waitingForAnswer, connected, error, act, textarea, rowContext, composer, files, loading } = session;\n const voiceRows = pendingVoice ?? voice.pending;\n const VoiceButton = voiceMessage?.Button, VoiceBubbleView = voiceMessage?.Bubble ?? NoVoiceBubble;\n const rows = useMemo(() => messageStyle === 'messaging' ? markLeads(nativeRows) : nativeRows, [nativeRows, messageStyle]);\n const transcriptRows: readonly TranscriptRow[] = [\n ...rows.map(row => ({ key: row.key, kind: 'native' as const, row })),\n ...voiceRows.map(voice => ({ key: `voice:${voice.id}`, kind: 'voice' as const, voice })),\n ];\n const pendingRows = voiceRows.map(item => <MessageScrollerItem key={`voice:${item.id}`} messageId={`voice:${item.id}`} data-local-voice=\"\" className=\"[content-visibility:visible]\"><VoiceBubbleView pending={item} /></MessageScrollerItem>);\n const empty = (timeline ? timeline.count === 0 : session.empty) && voiceRows.length === 0;\n const conversationFiles = new Map(files.map(file => [file.id, file]));\n for (const item of voiceRows) if (item.path && !conversationFiles.has(`file:${item.path}`)) {\n const path = item.path, open = onOpenFile ?? mentions?.open;\n conversationFiles.set(`file:${path}`, { id: `file:${path}`, name: displayName(path), open: open ? () => open(path) : undefined });\n }\n const { pinned } = derived;\n const transcript = useTranscript(transcriptRows, displayLimit ?? paging?.first ?? PAGE_FIRST, paging?.more ?? PAGE_MORE, { state: state.history, connected: !state.disposed && connected, load: controller.loadEarlier }, displayLimit === undefined);\n const { stick, hidden } = transcript, { scrollRef, isAtBottom } = stick;\n useLayoutEffect(() => { scrollToBottom.current = () => { transcript.reset(); void stick.scrollToBottom('instant'); }; });\n const visible = transcript.visible(transcriptRows);\n // Native rows come before pending voice rows, so the hidden ones are the oldest native rows.\n const chunks = useRowChunks(useMemo(() => rows.slice(Math.min(rows.length, hidden)), [rows, hidden]));\n const { barStart, barNote } = session.pickers();\n const connectionKind = state.connection.kind;\n const [renamingTitle, setRenamingTitle] = useState(false);\n const [titleError, setTitleError] = useState(false);\n const page = useRef<HTMLElement>(null);\n useKeyboardInset(page, keyboardInset);\n\n return <section ref={page} data-boring=\"pi-chat\" data-connection={connectionKind} data-empty={empty && !loading ? emptyLayout : undefined} aria-label={title} className={cn('pi-chat relative box-border flex h-full min-h-0 min-w-0 flex-col overflow-hidden bg-background text-foreground ', keyboardInset && 'max-md:pb-(--composer-keyboard-inset)', empty && emptyLayout === 'centered' && 'md:justify-center', className)}>\n {header && <header className={cn(empty && emptyLayout === 'centered' && 'md:absolute md:inset-x-0 md:top-0', 'flex h-13 shrink-0 items-center gap-2 px-3 md:gap-3 md:px-4')}>\n {headerStart}\n {avatar && <Avatar data-testid=\"chat-avatar\" className=\"overflow-hidden\"><AvatarFallback className=\"*:max-h-full *:max-w-full\">{avatar}</AvatarFallback></Avatar>}\n {renamingTitle && onRenameTitle ? <form className=\"min-w-0 flex-1\" onSubmit={event => { event.preventDefault(); const value = new FormData(event.currentTarget).get('title')?.toString().trim(); if (value) { setTitleError(false); void Promise.resolve().then(() => onRenameTitle(value)).catch(() => setTitleError(true)); } setRenamingTitle(false); }}>\n <Input name=\"title\" aria-label={labels.conversationName} maxLength={200} autoFocus defaultValue={conversationTitle ?? title} onBlur={() => setRenamingTitle(false)} onKeyDown={event => { if (event.key === 'Escape') setRenamingTitle(false); }} className=\"w-full min-w-0\" />\n </form> : <h2 className=\"m-0 min-w-0 flex-1 truncate font-(family-name:--chat-display) text-sm font-medium tracking-tight max-md:text-center\">{onRenameTitle ? <Button variant=\"ghost\" className=\"max-w-full\" onClick={() => setRenamingTitle(true)}><span className=\"truncate\">{conversationTitle ?? title}</span></Button> : conversationTitle ?? title}</h2>}\n {showHistory && conversations && historyList && <Button variant=\"ghost\" size=\"sm\" data-testid=\"history-open\" aria-haspopup=\"dialog\" aria-expanded={pickingConversation} disabled={state.disposed}\n onClick={() => setPickingConversation(open => !open)}><icons.history data-icon=\"inline-start\" 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 {titleError && <p role=\"alert\" className=\"m-0 shrink-0 px-4 py-2 text-sm text-destructive\">{labels.actionFailed}</p>}\n {decisions && <><div data-boring=\"required-decisions\" className=\"shrink-0 px-4 py-2\">{decisions}</div><Separator /></>}\n {pinned.length > 0 && <><aside aria-label={labels.requiredActions} className=\"shrink-0 space-y-2 px-4 py-2\">{pinned.map(card => <div key={card.key}>{card.content}</div>)}</aside><Separator /></>}\n {(connectionKind === 'error' || connectionKind === 'closed') && <div className=\"shrink-0 px-4 pt-2\">\n <ChatConnectionNotice state={state} renderConnectionError={renderConnectionError} onReconnect={() => act(controller.connect)} /></div>}\n {pickingConversation && conversations && historyList && <ConversationHistory conversations={conversations} onClose={() => setPickingConversation(false)} />}\n\n <div data-testid=\"conversation-content\" className={cn('relative min-h-0 flex-1', empty && emptyLayout === 'centered' && 'md:min-h-60 md:flex-none')}>\n {timeline ? timeline.render({ focusComposer: () => textarea.current?.focus(), openFile: onOpenFile ?? mentions?.open, pendingVoice: pendingRows, paging }) : <MessageScroller>\n <MessageScrollerViewport ref={scrollRef} data-testid=\"transcript-scroll\" aria-label={labels.messages} className=\"min-h-0 flex-1 scrollbar-thumb-border scrollbar-track-transparent\">\n {!empty && <TranscriptHistory history={state.history} connected={!state.disposed && connected} onLoad={transcript.reveal} sentinelRef={transcript.sentinelRef} hidden={hidden} loaded={transcript.loaded} />}\n <div className=\"mx-auto w-full max-w-[720px] px-4 pt-6 pb-8 md:px-6\">\n <MessageScrollerContent aria-label={labels.messages} aria-live=\"polite\" data-testid=\"transcript\">\n {chunks.map(run => <TranscriptChunk key={run[0]!.key} rows={run} context={rowContext} />)}\n {visible.map(item => item.kind === 'voice' && <MessageScrollerItem key={item.key} messageId={item.key} data-local-voice=\"\" className=\"[content-visibility:visible]\"><VoiceBubbleView pending={item.voice} /></MessageScrollerItem>)}\n </MessageScrollerContent>\n </div>\n </MessageScrollerViewport>\n {!empty && <div data-testid=\"transcript-navigation\" className=\"flex h-12 shrink-0 items-center justify-center\">{!isAtBottom && <MessageScrollerButton className=\"static inset-auto translate-x-0\" data-testid=\"jump-latest\" aria-label={labels.jumpToLatest} title={labels.jumpToLatest} onClick={transcript.reset}><icons.jumpToLatest aria-hidden=\"true\" /></MessageScrollerButton>}</div>}\n </MessageScroller>}\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 </div>\n\n <footer data-testid=\"composer-dock\" className=\"shrink-0 px-4 pt-2 pb-[max(1rem,env(safe-area-inset-bottom))] md:px-6\">\n <div className=\"mx-auto w-full max-w-[720px] space-y-2\">\n <div {...(session.natural ? {} : { 'aria-live': 'polite' as const })} className=\"space-y-2 empty:hidden\">\n <ChatStatusLine natural={session.natural} working={working} waitingForAnswer={waitingForAnswer} derived={derived} stop={state.stop} />\n <ChatNotices natural={session.natural} state={state} error={error} onReconcile={() => act(controller.reconcile)} onRetry={() => act(controller.retrySameRequest)} />\n </div>\n <div>\n <ConversationFiles files={[...conversationFiles.values()]} />\n <MessageQueue items={queued} sending={state.outbox} withdraw={actions?.withdraw} actions={queueActions} />\n {voice.problem && <p role=\"alert\" data-testid=\"voice-message-problem\">{voice.problem}</p>}\n <Composer {...composer} recording={composerRecording ?? (VoiceButton && (voice.phase === 'starting' || voice.phase === 'recording') ? <VoiceButton voice={voice} /> : undefined)} layout={composerLayout} placeholder={labels.placeholder === 'Message the agent…' ? `Message ${title}…` : labels.placeholder} barStart={barStart} barNote={barNote} start={composerStart}\n {...(voiceMessage && VoiceButton && voiceReplacesSend ? { barEnd: tools, whenEmpty: <VoiceButton voice={voice} primary disabled={state.disposed || !connected || state.send.kind === 'unknown'} /> }\n : { barEnd: voiceMessage && VoiceButton ? <>{tools}<VoiceButton voice={voice} disabled={state.disposed || !connected || state.send.kind === 'unknown'} /></> : tools })} />\n {belowComposer !== undefined && <div data-testid=\"below-composer\" className=\"pt-2\">{belowComposer}</div>}\n </div>\n </div>\n </footer>\n </section>;\n}\n",
129
101
  "type": "registry:component",
130
102
  "target": "components/pi-chat/pi-chat.tsx"
131
103
  },
132
104
  {
133
105
  "path": "registry/pi-chat/picker-keyboard.ts",
134
- "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",
106
+ "content": "'use client';\n\nimport { useEffect, useLayoutEffect, 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 useLayoutEffect(() => { 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",
135
107
  "type": "registry:lib",
136
108
  "target": "components/pi-chat/picker-keyboard.ts"
137
109
  },
138
110
  {
139
111
  "path": "registry/pi-chat/queue.tsx",
140
- "content": "'use client';\n\nimport { useState } from 'react';\nimport type { ChatDraft } from '@hachej/boring-ui-kit/native-chat';\nimport { CornerDownRightIcon, EllipsisIcon, ListEndIcon, PencilIcon, RouteIcon, Trash2Icon } from 'lucide-react';\nimport { DropdownMenu, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';\nimport { Card, CardContent } from '@/components/ui/card';\nimport { Alert, AlertDescription } from '@/components/ui/alert';\nimport { Spinner } from '@/components/ui/spinner';\nimport { TraceIcon, TraceLine, TraceTitle } from '@/components/ui/trace';\nimport { Button } from '@/components/ui/button';\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\n/** The \"…\" button of one queued message: a small menu of the secondary actions (Edit). */\nfunction QueueEditAction({ disabled, onEdit }: { readonly disabled: boolean; readonly onEdit: () => void }) {\n const { labels } = useChatText();\n return <DropdownMenu>\n <DropdownMenuTrigger render={<Button variant=\"ghost\" size=\"icon\" />} data-testid=\"queue-more\" aria-label={labels.moreActions} title={labels.more} disabled={disabled}>\n <EllipsisIcon data-icon=\"inline-start\" aria-hidden=\"true\" />\n </DropdownMenuTrigger>\n <DropdownMenuContent side=\"top\" align=\"end\" data-testid=\"queue-menu\">\n <DropdownMenuGroup><DropdownMenuItem data-testid=\"queue-edit\" onClick={onEdit}><PencilIcon aria-hidden=\"true\" />{labels.edit}</DropdownMenuItem></DropdownMenuGroup>\n </DropdownMenuContent>\n </DropdownMenu>;\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 pb-3\">\n <Card size=\"sm\"><CardContent><ul className=\"m-0 flex list-none flex-col p-0\">\n {items.map(item => {\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\">\n <TraceLine status=\"pending\" className=\"min-w-0 flex-1\">\n <TraceIcon>{steering ? <RouteIcon /> : <ListEndIcon />}</TraceIcon>\n <TraceTitle><span className=\"sr-only\">{steering ? labels.steering : labels.queued}: </span><span data-testid=\"queue-text\">{queuedText(item, labels.images)}</span></TraceTitle>\n </TraceLine>\n {!steering && actions?.steer && <Button variant=\"ghost\" size=\"icon\" data-testid=\"queue-steer\" aria-label={labels.steer} title={labels.steerHint} disabled={working} onClick={() => { void run(item, () => actions.steer!(item)); }}>\n <CornerDownRightIcon data-icon=\"inline-start\" aria-hidden=\"true\" /></Button>}\n <Button variant=\"ghost\" size=\"icon\" data-testid=\"queue-cancel\" aria-label={labels.removeQueued} title={labels.removeHint} disabled={!withdraw || working} onClick={() => { void remove(item); }}>\n <Trash2Icon data-icon=\"inline-start\" aria-hidden=\"true\" /></Button>\n {actions?.edit && <QueueEditAction 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\">\n <TraceLine status=\"running\" className=\"min-w-0 flex-1\">\n <TraceIcon><Spinner aria-hidden=\"true\" /></TraceIcon>\n <TraceTitle data-testid=\"queue-text\">{draft.text}{draft.attachments.length ? `${draft.text ? '\\n' : ''}${labels.images(draft.attachments.length)}` : ''}</TraceTitle>\n </TraceLine>\n <span className=\"shrink-0 px-1 text-xs text-muted-foreground\">{labels.sending}</span>\n </li>)}\n </ul></CardContent></Card>\n {failed && <Alert variant=\"destructive\" data-testid=\"queue-error\"><AlertDescription>{failed}</AlertDescription></Alert>}\n </section>;\n}\n",
112
+ "content": "'use client';\n\nimport { useState } from 'react';\nimport type { ChatDraft } from '@hachej/boring-ui-kit/native-chat';\nimport { CornerDownRightIcon, EllipsisIcon, ListEndIcon, PencilIcon, RouteIcon, Trash2Icon } from 'lucide-react';\nimport { DropdownMenu, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';\nimport { Card, CardContent } from '@/components/ui/card';\nimport { Alert, AlertDescription } from '@/components/ui/alert';\nimport { Spinner } from '@/components/ui/spinner';\nimport { TraceIcon, TraceLine, TraceTitle } from '@/components/ui/trace';\nimport { Button } from '@/components/ui/button';\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 type { QueueActions } from '@hachej/boring-ui-kit/chat-react';\nimport type { QueueActions } from '@hachej/boring-ui-kit/chat-react';\n\n/** The \"…\" button of one queued message: a small menu of the secondary actions (Edit). */\nfunction QueueEditAction({ disabled, onEdit }: { readonly disabled: boolean; readonly onEdit: () => void }) {\n const { labels } = useChatText();\n return <DropdownMenu>\n <DropdownMenuTrigger render={<Button variant=\"ghost\" size=\"icon\" />} data-testid=\"queue-more\" aria-label={labels.moreActions} title={labels.more} disabled={disabled}>\n <EllipsisIcon data-icon=\"inline-start\" aria-hidden=\"true\" />\n </DropdownMenuTrigger>\n <DropdownMenuContent side=\"top\" align=\"end\" data-testid=\"queue-menu\">\n <DropdownMenuGroup><DropdownMenuItem data-testid=\"queue-edit\" onClick={onEdit}><PencilIcon aria-hidden=\"true\" />{labels.edit}</DropdownMenuItem></DropdownMenuGroup>\n </DropdownMenuContent>\n </DropdownMenu>;\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 pb-3\">\n <Card size=\"sm\"><CardContent><ul className=\"m-0 flex list-none flex-col p-0\">\n {items.map(item => {\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\">\n <TraceLine status=\"pending\" className=\"min-w-0 flex-1\">\n <TraceIcon>{steering ? <RouteIcon /> : <ListEndIcon />}</TraceIcon>\n <TraceTitle><span className=\"sr-only\">{steering ? labels.steering : labels.queued}: </span><span data-testid=\"queue-text\">{queuedText(item, labels.images)}</span></TraceTitle>\n </TraceLine>\n {!steering && actions?.steer && <Button variant=\"ghost\" size=\"icon\" data-testid=\"queue-steer\" aria-label={labels.steer} title={labels.steerHint} disabled={working} onClick={() => { void run(item, () => actions.steer!(item)); }}>\n <CornerDownRightIcon data-icon=\"inline-start\" aria-hidden=\"true\" /></Button>}\n <Button variant=\"ghost\" size=\"icon\" data-testid=\"queue-cancel\" aria-label={labels.removeQueued} title={labels.removeHint} disabled={!withdraw || working} onClick={() => { void remove(item); }}>\n <Trash2Icon data-icon=\"inline-start\" aria-hidden=\"true\" /></Button>\n {actions?.edit && <QueueEditAction 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\">\n <TraceLine status=\"running\" className=\"min-w-0 flex-1\">\n <TraceIcon><Spinner aria-hidden=\"true\" /></TraceIcon>\n <TraceTitle data-testid=\"queue-text\">{draft.text}{draft.attachments.length ? `${draft.text ? '\\n' : ''}${labels.images(draft.attachments.length)}` : ''}</TraceTitle>\n </TraceLine>\n <span className=\"shrink-0 px-1 text-xs text-muted-foreground\">{labels.sending}</span>\n </li>)}\n </ul></CardContent></Card>\n {failed && <Alert variant=\"destructive\" data-testid=\"queue-error\"><AlertDescription>{failed}</AlertDescription></Alert>}\n </section>;\n}\n",
141
113
  "type": "registry:component",
142
114
  "target": "components/pi-chat/queue.tsx"
143
115
  },
@@ -149,7 +121,7 @@
149
121
  },
150
122
  {
151
123
  "path": "registry/pi-chat/session.tsx",
152
- "content": "'use client';\n\nimport { startTransition, 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, ChatHistoryState } from '@hachej/boring-ui-kit/native-chat';\nimport type { ChatController } from '@hachej/boring-ui-kit/native-chat';\nimport { useMessageScroller, useMessageScrollerScrollable } from '@/components/ui/message-scroller';\nimport { Button } from '@/components/ui/button';\nimport type { ComposerFeedback, ComposerProps, PendingUpload } from './composer';\nimport type { ConversationFile } from './conversation-files';\nimport type { AttachmentsConfig, EffortConfig, MentionsConfig, ModelConfig, ModelRef, PastedText, PasteToFile, SlashConfig } from './config';\nimport { displayName, looksLikeMarkdown, mentionToken, pieces } from './config';\nimport type { CommandMentions } from './config';\nimport type { ChatCards, ChatTextPart, RowContext } from './message';\nimport type { QueueActions, QueuedMessage } from './queue';\nimport type { AnswerOutcome, ChatArtifactsConfig } from './config';\nimport { derive, isFileBlock, object, queuedMessages, waitingForAnswer as waitsForAnswer } from './rows';\nimport type { ChatCard, Mode, Row } 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 /** `natural` shows only messages, replies and question, approval and artifact cards, with one \"Preparing…\" status while the agent works: no tool steps, reasoning, file discovery or raw error text. Omit it and nothing changes. */\n readonly presentation?: 'natural';\n readonly actions?: PiChatActions;\n readonly renderEntry?: (entry: EntryRecord) => ChatCard | undefined;\n /** Omit complete assistant lines from display, copy and actions. Live trailing fragments wait for a newline or settlement. Not transport redaction. */\n readonly hideLine?: (line: string) => boolean;\n /** Initial number of displayed rows (default 60). An explicit limit uses Show earlier, not automatic paging; nothing is deleted. */\n readonly displayLimit?: number;\n /** Automatic paging: rows shown first (default 60) and rows added each time the reader reaches the top (default 40). Ignored with `displayLimit`. */\n readonly paging?: ChatPaging;\n /** Explicitly enable messageActions for paged history too; other historical controls remain inert. */\n readonly historicalMessageActions?: boolean;\n /** Host-rendered unread indicator, keyed by the reply. The host owns seen state and its persistence. */\n readonly unread?: (reply: ReplyRef) => ReactNode;\n /** Message inside the single native response-error notice. Null/undefined keeps the default; native status and metadata stay unchanged. */\n readonly replyError?: (reply: ReplyRef) => ReactNode;\n /** Card for any tool call; the catch-all after `toolRenderers`. */\n readonly renderTool?: (call: ToolCall, result: ToolResultMessage | undefined) => ChatCard | undefined;\n /** Cards for tool calls, keyed by tool name (same contract as `renderTool`). An entry that returns undefined falls back to `renderTool`. */\n readonly toolRenderers?: Readonly<Record<string, (call: ToolCall, result: ToolResultMessage | undefined) => ChatCard | undefined>> | undefined;\n /** Draws an assistant text part. Default: plain text (`markdownText` of `pi-chat-markdown` draws Markdown). */\n readonly renderText?: ((part: ChatTextPart) => ReactNode) | undefined;\n /**\n * The question, approval and sub-agent cards (`pi-chat-question`, `pi-chat-approval`, `pi-chat-subagent`; `withChatPlugins` adds them all).\n * Without a question or approval card the chat shows that it waits for the person's answer, with no answer UI; without the sub-agent card a\n * sub-agent call is an ordinary tool step.\n */\n readonly cards?: ChatCards | 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 /** Optional pills at the left of the composer's controls row. */\n readonly composerChips?: ComposerProps['chips'];\n /** Contextual host content above the input, for example a removable quote. */\n readonly composerHeader?: ReactNode;\n /** Host-owned content participates in send readiness without native image attachments. */\n readonly composerHasContent?: boolean;\n /** Retain files for the host's send operation instead of uploading immediately. */\n readonly onPickFiles?: (files: readonly File[]) => void;\n /** `/` menu of host commands and skills. Omit it and `/` is just text. */\n readonly slash?: SlashConfig;\n /** Show successful native write/edit paths as file cards under each reply. Off by default: only hosts with workspace file tools should opt in. */\n readonly fileChanges?: boolean;\n /** Opens a file from an upload or write/edit card. Falls back to mentions.open. */\n readonly onOpenFile?: (path: string) => void;\n /** Pastes above these limits become a file through `attachments` (on by default, 2000 characters or 40 lines). Needs `attachments`. */\n readonly pasteToFile?: PasteToFile;\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 /**\n * Artifact cards: tool results that carry a descriptor become a card that opens the artifact in the host's panel. The card and its recogniser\n * come from `pi-artifacts` (`withChatPlugins` adds them); without them, or without this prop, no artifact is offered.\n */\n readonly artifacts?: ChatArtifactsConfig;\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<ChatController['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: ChatController;\n /** The controller the host currently passes; a surface that outlives its controller stops acting on the old one. */\n readonly activeController: { readonly current: ChatController };\n readonly mode: Mode;\n readonly fileAccept: string;\n readonly onFiles?: FilesHandler | undefined;\n /** The phone camera for an `onFiles` chat (`attachments.Camera` is used with `attachments`). */\n readonly camera?: AttachmentsConfig['Camera'];\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 annotate toggle: when notes are pending (`count` > 0), Send attaches them to the message first. */\n readonly feedback?: ComposerFeedback | undefined;\n}\n\nexport function useChatSession(options: ChatSessionOptions) {\n const { controller, activeController: active, mode, presentation, actions, renderEntry, hideLine, historicalMessageActions, unread, replyError, renderTool: catchAll, toolRenderers, renderText, cards, groupTool, commandMentions, onOpenImage, onCopy, onComposerKeyDown, onFiles, fileAccept,\n slash, mentions, attachments, model, effort, artifacts, messageActions, replyFooter, afterSend, rowExtras, feedback, onOpenFile, fileChanges, pasteToFile, composerChips, composerHeader, composerHasContent, onPickFiles } = 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 natural = presentation === 'natural';\n // A tool's own renderer comes first; `renderTool` stays the catch-all.\n const renderTool = useMemo(() => toolRenderers ? (call: ToolCall, result: ToolResultMessage | undefined) => (Object.hasOwn(toolRenderers, call.name) ? toolRenderers[call.name]?.(call, result) : undefined) ?? catchAll?.(call, result) : catchAll, [toolRenderers, catchAll]);\n const developer = mode === 'developer' && !natural;\n // Only the recogniser takes part in deriving rows; which card is open changes without rebuilding them.\n const offered = artifacts?.recognise && artifacts.Card ? artifacts : undefined;\n const artifactDetect = useMemo(() => offered?.recognise ? { recognise: offered.recognise, detect: offered.detect } : undefined, [offered?.recognise, offered?.detect]);\n const subagent = cards?.subagent;\n const derived = useMemo(() => derive(state.view, { mode, presentation, hideLine, renderEntry, renderTool, groupTool, artifacts: artifactDetect, subagent }), [state.view, mode, presentation, hideLine, renderEntry, renderTool, groupTool, artifactDetect, subagent]);\n const queued = useMemo(() => queuedMessages(state.view), [state.view]);\n const { run } = derived;\n const earlier = useMemo<readonly Row[]>(() => {\n if (!state.view || !('entries' in state.history)) return [];\n const activeIds = new Set(state.view.entries.map(entry => entry.id));\n const entries = state.history.entries.filter(entry => !activeIds.has(entry.id));\n return derive({ ...state.view, entries, docs: {} }, { mode, presentation, hideLine, renderEntry: undefined, renderTool: undefined, groupTool: undefined, artifacts: artifactDetect, subagent }).rows\n .map(row => ({ ...row, key: `history:${row.key}`, historical: true }));\n }, [state.view, state.history, mode, presentation, hideLine, artifactDetect, subagent]);\n const rows = useMemo(() => [...earlier, ...derived.rows], [earlier, derived.rows]);\n const files = useMemo(() => {\n const found = new Map<string, ConversationFile>();\n const open = onOpenFile ?? mentions?.open;\n const add = (path: string) => {\n const normalized = path.replace(/^\\.\\//, '');\n const id = `file:${normalized}`;\n if (!found.has(id)) found.set(id, { id, name: displayName(normalized), open: open ? () => open(normalized) : undefined });\n };\n for (const path of picked) add(path);\n for (const item of state.draft.attachments) found.set(`draft:${item.id}`, { id: `draft:${item.id}`, name: item.name, open: onOpenImage ? () => onOpenImage(item.content) : undefined });\n for (const row of derived.rows) {\n if (row.type === 'user') {\n const content = typeof row.message.content === 'string' ? [{ type: 'text' as const, text: row.message.content }] : row.message.content;\n for (const [index, part] of content.entries()) {\n if (part.type === 'text' && !isFileBlock(part.text)) for (const piece of pieces(part.text, { mentions: true, skills: [] })) { if (piece.kind === 'mention' && piece.value) add(piece.value); }\n if (part.type === 'image') { const id = `image:${row.key}:${index}`; found.set(id, { id, name: labels.imageAttachment, open: onOpenImage ? () => onOpenImage(part) : undefined }); }\n }\n }\n if (row.type !== 'assistant') continue;\n for (const part of row.parts) {\n if (part.kind === 'artifact' && part.artifact.state === 'ready' && part.artifact.path !== undefined) {\n const descriptor = part.artifact.descriptor as never, id = `file:${part.artifact.path.replace(/^\\.\\//, '')}`;\n found.set(id, { id, name: displayName(part.artifact.path), open: artifacts?.open ? () => artifacts.open(descriptor) : undefined });\n }\n if (!natural && part.kind === 'tool' && part.entry.result && !part.entry.result.isError && ['read', 'write', 'edit'].includes(part.entry.call.name)) {\n const path = part.entry.call.arguments['path'];\n if (typeof path === 'string') add(path);\n }\n }\n }\n return [...found.values()];\n }, [rows, picked, state.draft.attachments, artifacts, onOpenFile, mentions?.open, onOpenImage, labels.imageAttachment]);\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 = waitsForAnswer(derived.rows);\n const send = () => {\n if (sendBlocked || !current()) return;\n const attach = feedback && feedback.count > 0 ? 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 /** Uploads files; `restore` (a pasted text) is what their pending cards undo: it abandons the upload and puts the text back. */\n async function upload(files: readonly File[], paste?: { readonly restore: () => void; readonly after: string }) {\n if (!files.length || !current()) return;\n if (onPickFiles) { onPickFiles(files); return; }\n if (!onFiles && !attachments) 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 const cancel = paste && (() => { abort.abort(); setPending(items => items.filter(item => !ids.includes(item.id))); paste.restore(); });\n setPending(items => [...items, ...files.map((file, index): PendingUpload => ({ id: ids[index]!, name: file.name, state: 'uploading',\n ...(cancel && paste ? { cancel, restoreWhile: paste.after } : {}) }))]);\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 /** A paste the composer took: saved as a file under `uploads/` (Send then references it). Cancelling puts the text back where it was pasted. */\n const pasteText = (paste: PastedText) => {\n if (!attachments || !current()) return;\n const at = new Date(), two = (value: number) => String(value).padStart(2, '0');\n const stamp = `${at.getFullYear()}-${two(at.getMonth() + 1)}-${two(at.getDate())} ${two(at.getHours())}-${two(at.getMinutes())}-${two(at.getSeconds())}`;\n const markdown = looksLikeMarkdown(paste.text);\n const file = new File([paste.text], `${labels.pastedFileName(stamp)}${markdown ? '.md' : '.txt'}`, { type: markdown ? 'text/markdown' : 'text/plain' });\n // The pasted text replaces its selection when the paste is accepted, so the draft shows what is left. Restoring inserts the text at\n // the same place and deletes nothing: whatever was typed since stays.\n const draft = controller.getSnapshot().draft.text;\n const start = Math.min(paste.start, draft.length), end = Math.min(Math.max(paste.end, start), draft.length);\n const after = `${draft.slice(0, start)}${draft.slice(end)}`;\n controller.setText(after);\n const restore = () => {\n if (!current()) return;\n const now = controller.getSnapshot().draft.text;\n const at = Math.min(start, now.length);\n controller.setText(`${now.slice(0, at)}${paste.text}${now.slice(at)}`);\n textarea.current?.focus();\n };\n void upload([file], { restore, after });\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, natural, renderText, cards, groupTool, onOpenImage, onCopy, openFile: onOpenFile ?? mentions?.open, fileChanges,\n commandMentions: commandMentions ? { commands: commandMentions.commands, onActivate: activateMention } : undefined,\n answer: actions?.answer,\n artifacts: offered?.Card ? { open: offered.open, isOpen: offered.isOpen, kinds: offered.kinds, Card: offered.Card } : undefined,\n messageActions, historicalMessageActions, unread, replyError,\n replyFooter,\n pieces: slash?.skills?.length || mentions || attachments ? { mentions: Boolean(mentions), uploads: Boolean(attachments), skills: (slash?.skills ?? []).map(skill => skill.name), openMention: mentions?.open, renderMention: mentions?.renderSent ?? mentions?.render, preview: mentions?.preview, audioUrl: mentions?.audioUrl } : undefined,\n ...rowExtras,\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }), [controller, developer, natural, renderText, cards, groupTool, onOpenImage, onCopy, onOpenFile, fileChanges, commandMentions, actions?.answer, slash?.skills, mentions, mentions?.open, mentions?.render, mentions?.renderSent, mentions?.preview, mentions?.audioUrl, attachments, offered?.open, offered?.isOpen, offered?.kinds, offered?.Card, messageActions, historicalMessageActions, unread, replyError, 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 // The pill is drawn by the component the config carries (`pi-chat-pickers`); without one there is no pill.\n const Picker = model?.Picker ?? effort?.Picker;\n const barStart = (model || effort) && Picker ? <Picker 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 variant=\"ghost\" size=\"sm\" role=\"alert\" data-testid=\"configure-error\" title={`${changeError} (${labels.dismissHint})`} onClick={() => setChangeError(null)}\n className=\"min-w-0 max-w-[16rem]\"><span className=\"truncate\">{changeError}</span></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 const camera = attachments ? attachments.Camera : options.camera;\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 hasFiles: Boolean(composerHasContent),\n uploading: uploading > 0, canAttach: Boolean(onPickFiles || onFiles || attachments), ...(camera ? { camera } : {}), 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 onPasteText: attachments ? pasteText : undefined, pasteToFile,\n quote: composerHeader,\n feedback, chips: composerChips,\n };\n\n return { state, derived, rows, queued, queueActions, working, waitingForAnswer, connected, sendBlocked, error, setError, report, act, current, textarea, rowContext, composer, files, pickers, empty, loading, developer, natural };\n}\n\nexport type ChatSession = ReturnType<typeof useChatSession>;\n\nexport interface ChatPaging { readonly first?: number; readonly more?: number }\nexport const PAGE_FIRST = 60, PAGE_MORE = 40, CHUNK = 20;\n\n/**\n * Rows grouped into runs of at most `size` keys, kept stable across renders. Rows already placed never change run: rows revealed\n * above form new runs (the run nearest the old top is the full one), rows added below fill the last run, then start new ones.\n */\nexport function chunkKeys(previous: readonly (readonly string[])[], keys: readonly string[], size = CHUNK): string[][] {\n const owner = new Map<string, number>();\n previous.forEach((run, index) => { for (const key of run) owner.set(key, index); });\n const known = keys.findIndex(key => owner.has(key));\n const lead = known < 0 ? keys.length : known;\n const runs: string[][] = [];\n for (let end = lead; end > 0; end -= size) runs.unshift(keys.slice(Math.max(0, end - size), end));\n let current: string[] = [], from: number | undefined;\n for (const key of keys.slice(lead)) {\n const placed = owner.get(key);\n if (!current.length || (placed !== undefined ? placed !== from : current.length >= size)) { current = []; runs.push(current); from = placed; }\n current.push(key);\n }\n return runs;\n}\n\n/**\n * The scroller measures every one of its items on each scroll event and frame (@shadcn/react 0.3.1), so a long transcript gives it\n * runs of `CHUNK` rows instead of single rows: 500 messages are 25 measurements, not 500. A run keeps its element while rows are\n * revealed above it, so the scroller's prepend anchor still holds; a run's array is reused while its rows are unchanged.\n */\nexport function useRowChunks<T extends { readonly key: string }>(rows: readonly T[], size = CHUNK): readonly (readonly T[])[] {\n const previous = useRef<{ readonly keys: readonly (readonly string[])[]; readonly runs: ReadonlyMap<string, readonly T[]> }>({ keys: [], runs: new Map() });\n return useMemo(() => {\n const byKey = new Map(rows.map(row => [row.key, row]));\n const keys = chunkKeys(previous.current.keys, rows.map(row => row.key), size);\n const runs = keys.map(run => {\n const items = run.map(key => byKey.get(key)!);\n const before = previous.current.runs.get(run[0]!);\n return before && before.length === items.length && before.every((item, index) => item === items[index]) ? before : items;\n });\n previous.current = { keys, runs: new Map(runs.map(run => [run[0]!.key, run])) };\n return runs;\n }, [rows, size]);\n}\n\n/** One scroll root for current and archived rows. Native paging stays in the borrowed controller. */\nexport function useTranscript(rows: readonly { readonly key: string }[], page = PAGE_FIRST, more = PAGE_MORE, history?: { readonly state: ChatHistoryState; readonly connected: boolean; readonly load: () => Promise<void> }, automatic = true) {\n if (!Number.isSafeInteger(page) || page < 1) throw new TypeError('Chat displayLimit must be a positive integer');\n if (!Number.isSafeInteger(more) || more < 1) throw new TypeError('Chat paging.more must be a positive integer');\n const [limit, setLimit] = useState(page);\n const [sentinel, setSentinel] = useState<HTMLDivElement | null>(null);\n const [loaded, setLoaded] = useState(0);\n const pending = useRef(false);\n const anchor = useRef<{ readonly length: number; readonly limit: number } | undefined>(undefined);\n const { scrollToEnd } = useMessageScroller();\n const scrollable = useMessageScrollerScrollable();\n const [scroller, setScroller] = useState<HTMLDivElement | null>(null);\n const scrollToBottom = useCallback((behavior?: 'instant') => scrollToEnd({ behavior: behavior === 'instant' ? 'instant' : 'smooth' }), [scrollToEnd]);\n const stick = { scrollRef: setScroller, scrollToBottom, isAtBottom: !scrollable.end };\n const hidden = Math.max(0, rows.length - limit);\n const reveal = useCallback(() => {\n if (pending.current || anchor.current) return;\n const state = history?.state;\n if (hidden === 0 && (!history?.connected || !state || state.kind === 'disabled' || state.kind === 'loading' || state.kind === 'ready' && !state.hasMore)) return;\n anchor.current = { length: rows.length, limit };\n // A revealed page renders as a transition: React mounts it in small slices, so scrolling stays responsive meanwhile.\n if (hidden > 0) startTransition(() => setLimit(value => value + more));\n else if (history) {\n pending.current = true;\n void Promise.resolve().then(history.load).catch(() => { anchor.current = undefined; }).finally(() => { pending.current = false; });\n }\n }, [hidden, history?.state, history?.connected, history?.load, rows.length, limit, more]);\n useLayoutEffect(() => {\n const saved = anchor.current;\n if (!scroller || !saved || history?.state.kind === 'loading') return;\n const added = Math.max(0, rows.length - saved.length);\n if (limit < saved.limit + added) { startTransition(() => setLimit(saved.limit + added)); return; }\n anchor.current = undefined;\n setLoaded(count => count + Math.max(0, Math.min(rows.length, limit) - Math.min(saved.length, saved.limit)));\n }, [rows, limit, scroller, history?.state]);\n // Automatic paging: the sentinel near the top, once the reader has been away from the top (so the mount, which starts at the\n // top before the scroller settles at the end, loads nothing). A fast scroll lands on 0 before the sentinel is seen: the scroll\n // listener and every new observer (after each page) check again, instead of the reader's distance at that one moment.\n const near = useRef(false), away = useRef(false), revealNow = useRef(reveal);\n revealNow.current = reveal;\n useEffect(() => {\n if (!automatic || !scroller) return;\n const onScroll = () => { if (scroller.scrollTop > 8) away.current = true; if (near.current && away.current) revealNow.current(); };\n scroller.addEventListener('scroll', onScroll, { passive: true });\n return () => scroller.removeEventListener('scroll', onScroll);\n }, [automatic, scroller]);\n useEffect(() => {\n if (!automatic || !scroller || !sentinel || typeof IntersectionObserver === 'undefined' || history?.state.kind === 'loading' || history?.state.kind === 'error') return;\n const observer = new IntersectionObserver(entries => {\n near.current = entries.at(-1)?.isIntersecting ?? near.current;\n if (near.current && (scroller.scrollHeight <= scroller.clientHeight || away.current)) reveal();\n }, { root: scroller, rootMargin: '240px 0px 0px' });\n observer.observe(sentinel);\n return () => { observer.disconnect(); near.current = false; };\n }, [automatic, scroller, sentinel, reveal, history?.state]);\n const revealTo = (key: string) => { const index = rows.findIndex(row => row.key === key); if (index >= 0) setLimit(value => Math.max(value, rows.length - index)); };\n return { stick, hidden, reveal, revealTo, sentinelRef: setSentinel, loaded, visible: <T,>(items: readonly T[]): readonly T[] => hidden ? items.slice(hidden) : items, reset: () => { anchor.current = undefined; setLimit(page); } };\n}\n",
124
+ "content": "'use client';\n\nimport { useCallback, useMemo, useRef } 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 { PAGE_FIRST, PAGE_MORE, useTranscriptWindow } from '@hachej/boring-ui-kit/chat-react';\nimport type { ChatPaging } from '@hachej/boring-ui-kit/chat-react';\nimport type { ChatHistoryState } from '@hachej/boring-ui-kit/native-chat';\nimport type { ChatController } from '@hachej/boring-ui-kit/native-chat';\nimport { useMessageScroller, useMessageScrollerScrollable } from '@/components/ui/message-scroller';\nimport { Button } from '@/components/ui/button';\nimport type { ComposerFeedback, ComposerProps } from './composer';\nimport type { AttachmentsConfig, EffortConfig, MentionsConfig, ModelConfig, SlashConfig } from './config';\nimport type { PasteToFile } from '@hachej/boring-ui-kit/chat-text';\nimport type { CommandMentions } from './config';\nimport type { ChatCards, ChatTextPart, RowContext } from './message';\nimport type { QueuedMessage } from './queue';\nimport type { AnswerOutcome, ChatArtifactsConfig } from './config';\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 /** `natural` shows only messages, replies and question, approval and artifact cards, with one \"Preparing…\" status while the agent works: no tool steps, reasoning, file discovery or raw error text. Omit it and nothing changes. */\n readonly presentation?: 'natural';\n /** Show a retained voice message's audio player. Default false: transcript only; uploaded audio and stored tokens are unchanged. */\n readonly voiceReplay?: boolean;\n readonly actions?: PiChatActions;\n readonly renderEntry?: (entry: EntryRecord) => ChatCard | undefined;\n /** Omit complete assistant lines from display, copy and actions. Live trailing fragments wait for a newline or settlement. Not transport redaction. */\n readonly hideLine?: (line: string) => boolean;\n /** Initial number of displayed rows (default 60). An explicit limit uses Show earlier, not automatic paging; nothing is deleted. */\n readonly displayLimit?: number;\n /** Automatic paging: rows shown first (default 60) and rows added each time the reader reaches the top (default 40). Ignored with `displayLimit`. */\n readonly paging?: ChatPaging;\n /** Explicitly enable messageActions for paged history too; other historical controls remain inert. */\n readonly historicalMessageActions?: boolean;\n /** Host-rendered unread indicator, keyed by the reply. The host owns seen state and its persistence. */\n readonly unread?: (reply: ReplyRef) => ReactNode;\n /** Message inside the single native response-error notice. Null/undefined keeps the default; native status and metadata stay unchanged. */\n readonly replyError?: (reply: ReplyRef) => ReactNode;\n /** Card for any tool call; the catch-all after `toolRenderers`. */\n readonly renderTool?: (call: ToolCall, result: ToolResultMessage | undefined) => ChatCard | undefined;\n /** Cards for tool calls, keyed by tool name (same contract as `renderTool`). An entry that returns undefined falls back to `renderTool`. */\n readonly toolRenderers?: Readonly<Record<string, (call: ToolCall, result: ToolResultMessage | undefined) => ChatCard | undefined>> | undefined;\n /** Draws an assistant text part. Default: plain text (`markdownText` of `pi-chat-markdown` draws Markdown). */\n readonly renderText?: ((part: ChatTextPart) => ReactNode) | undefined;\n /**\n * The question, approval and sub-agent cards (`pi-chat-question`, `pi-chat-approval`, `pi-chat-subagent`; `withChatPlugins` adds them all).\n * Without a question or approval card the chat shows that it waits for the person's answer, with no answer UI; without the sub-agent card a\n * sub-agent call is an ordinary tool step.\n */\n readonly cards?: ChatCards | 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 /** Optional pills at the left of the composer's controls row. */\n readonly composerChips?: ComposerProps['chips'];\n /** Contextual host content above the input, for example a removable quote. */\n readonly composerHeader?: ReactNode;\n /** Host-owned content participates in send readiness without native image attachments. */\n readonly composerHasContent?: boolean;\n /** Retain files for the host's send operation instead of uploading immediately. */\n readonly onPickFiles?: (files: readonly File[]) => void;\n /** `/` menu of host commands and skills. Omit it and `/` is just text. */\n readonly slash?: SlashConfig;\n /** Show successful native write/edit paths as file cards under each reply. Off by default: only hosts with workspace file tools should opt in. */\n readonly fileChanges?: boolean;\n /** Opens a file from an upload or write/edit card. Falls back to mentions.open. */\n readonly onOpenFile?: (path: string) => void;\n /** Pastes above these limits become a file through `attachments` (on by default, 2000 characters or 40 lines). Needs `attachments`. */\n readonly pasteToFile?: PasteToFile;\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 /**\n * Artifact cards: tool results that carry a descriptor become a card that opens the artifact in the host's panel. The card and its recogniser\n * come from `pi-artifacts` (`withChatPlugins` adds them); without them, or without this prop, no artifact is offered.\n */\n readonly artifacts?: ChatArtifactsConfig;\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\n// Compatibility type export for one release.\nexport type { FilesHandler } from '@hachej/boring-ui-kit/chat-react';\nimport { useChatSession as useHeadlessChatSession } from '@hachej/boring-ui-kit/chat-react';\nimport type { FilesHandler } from '@hachej/boring-ui-kit/chat-react';\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: ChatController;\n /** The controller the host currently passes; a surface that outlives its controller stops acting on the old one. */\n readonly activeController: { readonly current: ChatController };\n readonly mode: Mode;\n readonly fileAccept: string;\n readonly onFiles?: FilesHandler | undefined;\n /** The phone camera for an `onFiles` chat (`attachments.Camera` is used with `attachments`). */\n readonly camera?: AttachmentsConfig['Camera'];\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 annotate toggle: when notes are pending (`count` > 0), Send attaches them to the message first. */\n readonly feedback?: ComposerFeedback | undefined;\n}\n\n/** Presentation adapter; all session state and controller protocols live in the kit. */\nexport function useChatSession(options: ChatSessionOptions) {\n const { controller, activeController, mode, presentation, voiceReplay, actions, renderEntry, hideLine, historicalMessageActions, unread, replyError, renderTool, toolRenderers, renderText, cards, groupTool, commandMentions, onOpenImage, onCopy, onComposerKeyDown, onFiles, fileAccept,\n slash, mentions, attachments, model, effort, artifacts, messageActions, replyFooter, afterSend, rowExtras, feedback, onOpenFile, fileChanges, composerChips, composerHeader, composerHasContent, onPickFiles, pasteToFile } = options;\n const { labels } = useChatText();\n const textarea = useRef<HTMLTextAreaElement | null>(null);\n const offered = artifacts?.recognise && artifacts.Card ? artifacts : undefined;\n const sessionArtifacts = useMemo(() => offered?.recognise ? { recognise: offered.recognise, detect: offered.detect, open: offered.open } : undefined, [offered]);\n const session = useHeadlessChatSession<ReactNode>({ controller, activeController, mode, presentation, actions, renderEntry, hideLine, renderTool, toolRenderers,\n groupTool, subagent: cards?.subagent, onOpenImage, onFiles, mentions, slash, attachments, model, effort,\n artifacts: sessionArtifacts,\n afterSend, feedback, onOpenFile, onPickFiles, commandMentions, labels, onFocus: () => textarea.current?.focus() });\n const { state, developer, natural, connected, working, sendBlocked, act } = session;\n const rowContext = useMemo<RowContext>(() => ({\n developer, natural, voiceReplay, renderText, cards, groupTool, onOpenImage, onCopy, openFile: onOpenFile ?? mentions?.open, fileChanges,\n commandMentions: commandMentions ? { commands: commandMentions.commands, onActivate: session.activateMention } : undefined,\n answer: actions?.answer,\n artifacts: offered?.Card ? { open: offered.open, isOpen: offered.isOpen, kinds: offered.kinds, Card: offered.Card } : undefined,\n messageActions, historicalMessageActions, unread, replyError,\n replyFooter,\n pieces: slash?.skills?.length || mentions || attachments ? { kinds: mentions?.kinds, mentions: Boolean(mentions), uploads: Boolean(attachments), skills: (slash?.skills ?? []).map(skill => skill.name), openMention: mentions?.open, renderMention: mentions?.renderSent ?? mentions?.render, preview: mentions?.preview, audioUrl: mentions?.audioUrl } : undefined,\n ...rowExtras,\n // eslint-disable-next-line react-hooks/exhaustive-deps -- lists the fields rows read, not whole objects: activateMention changes every render and must not rebuild every row.\n }), [controller, developer, natural, voiceReplay, renderText, cards, groupTool, onOpenImage, onCopy, onOpenFile, fileChanges, commandMentions, actions?.answer, slash?.skills, mentions, mentions?.open, mentions?.render, mentions?.renderSent, mentions?.preview, mentions?.audioUrl, attachments, offered?.open, offered?.isOpen, offered?.kinds, offered?.Card, messageActions, historicalMessageActions, unread, replyError, replyFooter, rowExtras]);\n\n /** The model-and-effort pill and the note that reports a refused change. */\n const pickers = () => {\n const disabled = session.changing !== null || state.disposed || !connected;\n // The pill is drawn by the component the config carries (`pi-chat-pickers`); without one there is no pill.\n const Picker = model?.Picker ?? effort?.Picker;\n const barStart = (model || effort) && Picker ? <Picker model={model} effort={effort} currentModel={session.currentModel} currentEffort={session.currentEffort} disabled={disabled} busy={session.changing}\n onModel={next => void session.changeModel(next)}\n onEffort={next => void session.changeEffort(next)} /> : undefined;\n const barNote = session.changeError ? <Button variant=\"ghost\" size=\"sm\" role=\"alert\" data-testid=\"configure-error\" title={`${session.changeError} (${labels.dismissHint})`} onClick={session.dismissChangeError}\n className=\"min-w-0 max-w-[16rem]\"><span className=\"truncate\">{session.changeError}</span></Button> : undefined;\n return { barStart, barNote };\n };\n\n const camera = attachments ? attachments.Camera : options.camera;\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: session.send, onStop: () => act(controller.stop),\n hasFiles: Boolean(composerHasContent),\n uploading: session.uploading > 0, canAttach: Boolean(onPickFiles || onFiles || attachments), ...(camera ? { camera } : {}), fileAccept: attachments ? attachments.accept ?? '' : fileAccept, onPickFiles: (files: readonly File[]) => { void session.upload(files); },\n slash, onSlashError: session.report, mentions, mentionPaths: session.picked, onMentionPicked: session.pickMention,\n uploads: session.pending, onDismissUpload: session.dismissUpload,\n onPasteText: attachments ? session.pasteText : undefined, pasteToFile,\n quote: composerHeader,\n feedback, chips: composerChips,\n };\n\n return { ...session, textarea, rowContext, composer, pickers };\n}\n\nexport type ChatSession = ReturnType<typeof useChatSession>;\n\n// Compatibility exports for one release; MessageScroller remains the only scroll owner.\nexport { chunkKeys, useRowChunks, PAGE_FIRST, PAGE_MORE, CHUNK } from '@hachej/boring-ui-kit/chat-react';\nexport type { ChatPaging } from '@hachej/boring-ui-kit/chat-react';\n\n/** Thin presentation adapter to the host's shadcn MessageScroller. */\nexport function useTranscript(rows: readonly { readonly key: string }[], page = PAGE_FIRST, more = PAGE_MORE, history?: { readonly state: ChatHistoryState; readonly connected: boolean; readonly load: () => Promise<void> }, automatic = true) {\n const window = useTranscriptWindow(rows, page, more, history, automatic);\n const { scrollToEnd } = useMessageScroller();\n const scrollable = useMessageScrollerScrollable();\n const scrollToBottom = useCallback((behavior?: 'instant') => scrollToEnd({ behavior: behavior === 'instant' ? 'instant' : 'smooth' }), [scrollToEnd]);\n return { ...window, stick: { scrollRef: window.scrollRef, scrollToBottom, isAtBottom: !scrollable.end } };\n}\n",
153
125
  "type": "registry:component",
154
126
  "target": "components/pi-chat/session.tsx"
155
127
  },
@@ -167,31 +139,31 @@
167
139
  },
168
140
  {
169
141
  "path": "registry/pi-chat/tool.tsx",
170
- "content": "'use client';\n\nimport { useState } from 'react';\nimport type { ReactNode } from 'react';\nimport type { ToolCall, ToolResultMessage } from '@earendil-works/pi-ai';\nimport type { ToolStatus, ToolEntry as ViewToolEntry } from '@hachej/boring-ui-kit/chat-view';\nimport { WrenchIcon } from 'lucide-react';\nimport { TraceCollapsible, TraceCollapsibleContent, TraceCollapsibleTrigger, TraceDescription, TraceIcon, TraceLine, TraceTitle } from '@/components/ui/trace';\nimport { Card, CardContent } from '@/components/ui/card';\nimport { Alert, AlertDescription } from '@/components/ui/alert';\nimport { Button } from '@/components/ui/button';\nimport { defaultChatLabels, useChatText } from './labels';\nimport type { ChatLabels } from './labels';\n\nexport type { ToolStatus } from '@hachej/boring-ui-kit/chat-view';\nexport type ToolEntry = ViewToolEntry<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\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/** One Trace step. Failures open by default; quiet successful steps have no disclosure. */\nexport function ToolCard({ entry, onOpenImage, details = true }: { readonly entry: ToolEntry; readonly details?: boolean; readonly onOpenImage?: (image: Extract<ToolResultMessage['content'][number], { type: 'image' }>) => void }) {\n const { labels } = useChatText();\n const [chosen, setChosen] = useState<boolean | undefined>();\n const { call, result, status } = entry;\n const open = details && (chosen ?? status === 'failed');\n const hint = preview(call.arguments);\n const line = <TraceLine {...(status === 'running' ? { status: 'running' } : status === 'failed' ? { status: 'error' } : {})}>\n <TraceIcon><WrenchIcon /></TraceIcon>\n <TraceTitle><span data-testid=\"tool-name\">{call.name}</span>{hint && ` · ${hint}`}</TraceTitle>\n <TraceDescription data-testid=\"tool-status\">{labels[STATUS_LABEL[status]]}</TraceDescription>\n </TraceLine>;\n return <TraceCollapsible data-testid=\"tool-card\" data-boring=\"tool-card\" data-status={status} data-tool={call.name} data-call-id={call.id} open={open} onOpenChange={setChosen}>\n {details ? <TraceCollapsibleTrigger className=\"min-h-8 max-sm:min-h-11 pointer-coarse:min-h-11\">{line}</TraceCollapsibleTrigger> : line}\n {details && <TraceCollapsibleContent><div data-testid=\"tool-details\" className=\"flex flex-col gap-3\">\n <Section title={labels.arguments}><Card><CardContent><pre className=\"m-0 max-h-60 overflow-auto whitespace-pre-wrap [overflow-wrap:anywhere]\">{JSON.stringify(call.arguments, null, 2)}</pre></CardContent></Card></Section>\n {result && <Section title={result.isError ? labels.error : labels.result}>\n <Alert variant={result.isError ? 'destructive' : 'default'} role={result.isError ? 'alert' : 'status'}><AlertDescription>\n {result.content.map((part, index) => part.type === 'text'\n ? <pre key={index} className=\"m-0 max-h-72 overflow-auto whitespace-pre-wrap [overflow-wrap:anywhere]\">{part.text}</pre>\n : <Button key={index} variant=\"outline\" size=\"sm\" className=\"max-sm:min-h-12! pointer-coarse:min-h-12!\" disabled={!onOpenImage} onClick={() => onOpenImage?.(part)}>{labels.openImageResult}</Button>)}\n {result.content.length === 0 && <span>{labels.emptyResult}</span>}\n </AlertDescription></Alert></Section>}\n </div></TraceCollapsibleContent>}\n </TraceCollapsible>;\n}\n\n",
142
+ "content": "'use client';\n\nimport { useState } from 'react';\nimport type { ReactNode } from 'react';\nimport type { ToolCall, ToolResultMessage } from '@earendil-works/pi-ai';\nimport type { ToolStatus, ToolEntry as ViewToolEntry } from '@hachej/boring-ui-kit/chat-view';\nimport { WrenchIcon } from 'lucide-react';\nimport { TraceCollapsible, TraceCollapsibleContent, TraceCollapsibleTrigger, TraceDescription, TraceIcon, TraceLine, TraceTitle } from '@/components/ui/trace';\nimport { Card, CardContent } from '@/components/ui/card';\nimport { Alert, AlertDescription } from '@/components/ui/alert';\nimport { Button } from '@/components/ui/button';\nimport { defaultChatLabels, useChatText } from './labels';\nimport type { ChatLabels } from './labels';\n\nexport type { ToolStatus } from '@hachej/boring-ui-kit/chat-view';\nexport type ToolEntry = ViewToolEntry<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\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/** One Trace step. Failures open by default; quiet successful steps have no disclosure. */\nexport function ToolCard({ entry, onOpenImage, details = true }: { readonly entry: ToolEntry; readonly details?: boolean; readonly onOpenImage?: (image: Extract<ToolResultMessage['content'][number], { type: 'image' }>) => void }) {\n const { labels } = useChatText();\n const [chosen, setChosen] = useState<boolean | undefined>();\n const { call, result, status } = entry;\n const open = details && (chosen ?? status === 'failed');\n const hint = preview(call.arguments);\n const line = <TraceLine {...(status === 'running' ? { status: 'running' } : status === 'failed' ? { status: 'error' } : {})}>\n <TraceIcon><WrenchIcon /></TraceIcon>\n <TraceTitle><span data-testid=\"tool-name\">{call.name}</span>{hint && ` · ${hint}`}</TraceTitle>\n <TraceDescription data-testid=\"tool-status\">{labels[STATUS_LABEL[status]]}</TraceDescription>\n </TraceLine>;\n return <TraceCollapsible data-testid=\"tool-card\" data-boring=\"tool-card\" data-status={status} data-tool={call.name} data-call-id={call.id} open={open} onOpenChange={setChosen}>\n {details ? <TraceCollapsibleTrigger className=\"min-h-8 max-md:min-h-11 pointer-coarse:min-h-11\">{line}</TraceCollapsibleTrigger> : line}\n {details && <TraceCollapsibleContent><div data-testid=\"tool-details\" className=\"flex flex-col gap-3\">\n <Section title={labels.arguments}><Card><CardContent><pre className=\"m-0 max-h-60 overflow-auto whitespace-pre-wrap [overflow-wrap:anywhere]\">{JSON.stringify(call.arguments, null, 2)}</pre></CardContent></Card></Section>\n {result && <Section title={result.isError ? labels.error : labels.result}>\n <Alert variant={result.isError ? 'destructive' : 'default'} role={result.isError ? 'alert' : 'status'}><AlertDescription>\n {result.content.map((part, index) => part.type === 'text'\n ? <pre key={index} className=\"m-0 max-h-72 overflow-auto whitespace-pre-wrap [overflow-wrap:anywhere]\">{part.text}</pre>\n : <Button key={index} variant=\"outline\" size=\"sm\" className=\"max-md:min-h-12! pointer-coarse:min-h-12!\" disabled={!onOpenImage} onClick={() => onOpenImage?.(part)}>{labels.openImageResult}</Button>)}\n {result.content.length === 0 && <span>{labels.emptyResult}</span>}\n </AlertDescription></Alert></Section>}\n </div></TraceCollapsibleContent>}\n </TraceCollapsible>;\n}\n\n",
171
143
  "type": "registry:component",
172
144
  "target": "components/pi-chat/tool.tsx"
173
145
  },
174
146
  {
175
147
  "path": "registry/pi-chat/use-remote-chat.ts",
176
- "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 type { ChatController } from '@hachej/boring-ui-kit/native-chat';\nimport { createRemoteChat } from '@hachej/boring-ui-kit/remote-chat';\nimport type { RemoteChat, RemoteChatOptions } from '@hachej/boring-ui-kit/remote-chat';\nimport type { PiChatActions } from './session';\n\n// ---- Placement: where the chat is shown, reported by the component that shows it and sent with each submit (see `useRemoteChat`).\n// `PiChat` reports `docked`, `AmbientChat` (also a docked chat floated by its divider) reports `floating`. Advisory for the model, never\n// authority. See docs/architecture/PAGE-TOOLS.md (PLACE-1..3).\nexport type ChatPlacement = 'docked' | 'floating';\n\n// Keyed by controller (a page can hold several chats; floating or docking keeps the controller, PLACE-3). Each mounted presenter has its own\n// registration, so unmounting one never clears another's; the latest surviving registration wins.\nconst placements = new WeakMap<ChatController, { readonly placement: ChatPlacement }[]>();\n\n/** Reports the placement of the chat showing `controller` while the caller is mounted. */\nexport function useChatPlacement(controller: ChatController, placement: ChatPlacement): void {\n useLayoutEffect(() => {\n const entry = { placement };\n const list = placements.get(controller) ?? [];\n placements.set(controller, [...list, entry]);\n return () => {\n const rest = (placements.get(controller) ?? []).filter(item => item !== entry);\n if (rest.length) placements.set(controller, rest); else placements.delete(controller);\n };\n }, [controller, placement]);\n}\n\nexport function readChatPlacement(controller: ChatController | undefined): ChatPlacement | undefined {\n return controller ? placements.get(controller)?.at(-1)?.placement : undefined;\n}\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, requestContext, transport, webSocket }: {\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 /**\n * The current screen context, read at each submit (for example `readAgentContext` of the app-shell item). The submit's `context` is this\n * value as it is (so a host reading `name` and `params` keeps working) plus `placement`: `docked` or `floating`, reported by the chat.\n */\n readonly requestContext?: () => Readonly<Record<string, unknown>> | undefined;\n /** `websocket`: one hibernation-friendly socket instead of the HTTP watch stream, falling back to HTTP (see `createRemoteChat`). Read when a conversation connects. */\n readonly transport?: RemoteChatOptions['transport'];\n readonly webSocket?: RemoteChatOptions['webSocket'];\n}): RemoteChatState {\n const url = conversationId === undefined ? undefined : String(endpoint(conversationId));\n const key = JSON.stringify([conversationId, url, identity?.runtimeId, identity?.scopeId, identity?.principalId, transport]);\n const binding = useMemo(() => ({ key, fetch, requestContext, webSocket }), [key]); // eslint-disable-line react-hooks/exhaustive-deps\n useLayoutEffect(() => { binding.fetch = fetch; binding.requestContext = requestContext; binding.webSocket = webSocket; }, [binding, fetch, requestContext, webSocket]);\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 const context = () => {\n const placement = readChatPlacement(controller), screen = binding.requestContext?.();\n return placement || screen ? { ...screen, ...(placement && { placement }) } : undefined;\n };\n setChat({ status: 'connecting', conversationId });\n void (async () => {\n while (!disposed) {\n try {\n remote = await createRemoteChat({ endpoint: url, fetch: request => binding.fetch(request), requestContext: context, ...(transport ? { transport } : {}), ...(binding.webSocket ? { webSocket: binding.webSocket } : {}) });\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",
148
+ "content": "// Compatibility exports for one release; transport/placement hooks live in the kit.\nexport { useChatPlacement, readChatPlacement, useRemoteChat } from '@hachej/boring-ui-kit/chat-react';\nexport type { ChatPlacement, RemoteChatState } from '@hachej/boring-ui-kit/chat-react';\n",
177
149
  "type": "registry:hook",
178
150
  "target": "components/pi-chat/use-remote-chat.ts"
179
151
  },
180
152
  {
181
153
  "path": "registry/pi-chat/use-chat-draft.ts",
182
- "content": "'use client';\n\nimport { useEffect, useRef } from 'react';\nimport type { ChatController } from '@hachej/boring-ui-kit/native-chat';\n\nconst PREFIX = 'pi-chat:draft:';\n\n/** The stored draft: a string, `null` when the key is missing, `undefined` when storage is unavailable (missing, blocked or throwing). */\nfunction read(storageKey: string): string | null | undefined {\n try {\n const storage = globalThis.localStorage;\n return storage ? storage.getItem(storageKey) : undefined;\n } catch { return undefined; }\n}\nfunction write(storageKey: string, text: string): void {\n try { if (text) globalThis.localStorage?.setItem(storageKey, text); else globalThis.localStorage?.removeItem(storageKey); } catch { /* the composer still holds the text */ }\n}\n\n/**\n * Keeps the composer's half-typed message (the controller's draft) per conversation in localStorage, so it survives a reload and shows in\n * every tab on the same conversation (the `storage` event). The draft is emptied when a message is sent, and a refused send puts the text back,\n * which is written again. Without `key` nothing happens. Storage that is missing or throws only means the draft is not kept.\n *\n * On mount the conversation's saved draft replaces the composer's text; text already in the composer and not yet saved is written at once.\n * On a change of `key` (same controller) the composer shows the new conversation's saved draft, or an empty one, so no text moves across.\n */\nexport function useChatDraft(controller: ChatController, key: string | undefined): void {\n // The key the hook last loaded; a different key on a later run is a conversation switch, not a first mount.\n const loaded = useRef<string | undefined>(undefined);\n useEffect(() => {\n if (key === undefined || controller.getSnapshot().disposed) return;\n const storageKey = PREFIX + key;\n const switched = loaded.current !== undefined && loaded.current !== key;\n loaded.current = key;\n const stored = read(storageKey);\n const current = controller.getSnapshot().draft.text;\n // The text last known to be in storage; a write happens only when the composer's text differs from it.\n let saved: string;\n if (stored) {\n if (stored !== current) controller.setText(stored);\n saved = stored;\n } else if (switched) {\n // The new conversation has no saved draft (or storage is unavailable): the old conversation's text must not stay.\n if (current) controller.setText('');\n saved = '';\n } else {\n saved = current;\n if (stored === null && current) write(storageKey, current);\n }\n const persist = () => {\n if (controller.getSnapshot().disposed) return;\n const text = controller.getSnapshot().draft.text;\n if (text === saved) return;\n saved = text;\n write(storageKey, text);\n };\n const unsubscribe = controller.subscribe(persist);\n // Another tab changed this conversation's draft (or cleared all storage: `key` is null). Adopting it does not write it back.\n // Unavailable storage is not a missing draft: the composer keeps its text.\n const onStorage = (event: StorageEvent) => {\n if (event.key !== null && event.key !== storageKey) return;\n if (controller.getSnapshot().disposed) return;\n const next = read(storageKey);\n if (next === undefined) return;\n const text = next ?? '';\n saved = text;\n if (text !== controller.getSnapshot().draft.text) controller.setText(text);\n };\n globalThis.addEventListener?.('storage', onStorage);\n return () => {\n unsubscribe();\n globalThis.removeEventListener?.('storage', onStorage);\n };\n }, [controller, key]);\n}\n",
154
+ "content": "'use client';\n\n// Compatibility for one release; draft persistence lives in the kit.\nexport { useChatDraft } from '@hachej/boring-ui-kit/chat-react';\n",
183
155
  "type": "registry:hook",
184
156
  "target": "components/pi-chat/use-chat-draft.ts"
185
157
  },
186
158
  {
187
159
  "path": "registry/pi-chat/labels.ts",
188
- "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, useRef } from 'react';\nimport type { ReactNode } from 'react';\nimport { ArrowDownIcon, ArrowUpIcon, CameraIcon, GitForkIcon, HistoryIcon, ListEndIcon, MessagesSquareIcon, PaperclipIcon, PlusIcon, RefreshCwIcon, SquareIcon } from 'lucide-react';\nimport type { BlockIcon } from '../button/actions';\nimport { withDefaults } from '../utils/utils';\n\n// An Intl.DateTimeFormat costs far more than formatting with one; every bubble's clock reuses the same few.\nconst formats = new Map<string, Intl.DateTimeFormat>();\nfunction intlFormat(locale: string, options: Intl.DateTimeFormatOptions): Intl.DateTimeFormat {\n const key = `${locale}|${JSON.stringify(options)}`;\n let found = formats.get(key);\n if (!found) { found = new Intl.DateTimeFormat(locale, options); formats.set(key, found); }\n return found;\n}\n/** « Tue 22 Oct, 14:02 ». */\nexport function formatTimestamp(at: string, locale: string) {\n const date = new Date(at);\n if (!Number.isFinite(date.getTime())) return at;\n return `${intlFormat(locale, { weekday: 'short', day: 'numeric', month: 'short' }).format(date)}, ${intlFormat(locale, { hour: '2-digit', minute: '2-digit' }).format(date)}`;\n}\n/** The time inside a bubble (« 14:02 », « 2:02 PM »). */\nexport function formatClock(at: string, locale: string) {\n const date = new Date(at);\n return Number.isFinite(date.getTime()) ? intlFormat(locale, { hour: 'numeric', minute: '2-digit' }).format(date) : '';\n}\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 artifacts: 'Artifacts',\n search: 'Search',\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 one status of `presentation=\"natural\"` while the agent works (any tool, retry or compaction), instead of the activity wording above. */\n preparing: 'Preparing…',\n /** In `presentation=\"natural\"`, replaces the controller's own reason when a send is blocked. */\n sendUnavailable: 'Sending is not available right now.',\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 takePhoto: 'Take a photo',\n cameraShoot: 'Take the photo',\n cameraClose: 'Close the camera',\n cameraUnavailable: 'The camera cannot open on this page.',\n cameraFallback: \"Use the phone's camera\",\n commands: 'Commands',\n annotate: 'Annotate',\n annotateHint: 'Annotate: click what you want to comment on (Esc to stop)',\n annotateNotes: (count: number) => `${count} ${count === 1 ? 'note' : 'notes'}`,\n annotateClear: 'Remove the notes',\n feedbackSent: (count: number) => `${count} ${count === 1 ? 'comment' : 'comments'} on the page`,\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 /** The type line of a file card in a sent message. */\n fileKind: { document: 'Document', image: 'Image', pdf: 'PDF', sheet: 'Spreadsheet', slides: 'Presentation', audio: 'Audio', file: 'File' },\n openFile: (name: string) => `Open ${name}`,\n fileChange: { created: 'Created', edited: 'Edited' },\n /** The name of a pasted text file: the words and the time it was pasted. */\n pastedFileName: (stamp: string) => `Pasted text ${stamp}`,\n restorePaste: 'Put the pasted text back in the message',\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 voiceHold: 'Hold to record, release to send',\n voiceRecording: 'Recording',\n voicePreparing: 'Preparing voice message…',\n voiceAudioOnly: 'Send audio only',\n voiceDiscard: 'Discard',\n voicePlay: 'Play voice message',\n voicePause: 'Pause voice message',\n voicePlayFailed: 'The audio could not be played. Try again.',\n voiceBlocked: 'Not sent. Review the chat notice before trying again.',\n voiceUnconfirmed: 'Message admission is unconfirmed. Use the chat notice to reconcile.',\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 /** The time inside a bubble in the `messaging` style (« 14:02 »), and its full date as the tooltip. */\n messageClock: (at: string) => formatClock(at, 'en'),\n messageTimestamp: (at: string) => formatTimestamp(at, 'en'),\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 loadEarlierMessages: 'Load earlier messages',\n earlierMessagesLoaded: (count: number) => `${count} earlier messages loaded`,\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: 'Start 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 imagePosition: (index: number, count: number) => `Image ${index} of ${count}`,\n previousImage: 'Previous image',\n nextImage: 'Next image',\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 /** A question of a form left blank, in the answer sent to the agent. */\n skipped: '(no 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 // Run card (a headless run: `runs/<id>`)\n run: 'Run',\n runStatus: (status: 'queued' | 'running' | 'completed' | 'failed'): string => ({ queued: 'Queued', running: 'Running', completed: 'Completed', failed: 'Failed' })[status],\n runElapsed: (time: string) => `Running for ${time}`,\n runDuration: (time: string) => `Took ${time}`,\n runRefresh: 'Refresh',\n runNotLoaded: 'The run could not be loaded.',\n // Sub-agent card (a `delegate` call)\n subagentStatus: (status: 'running' | 'done' | 'failed' | 'cancelled'): string => ({ running: 'Running', done: 'Done', failed: 'Failed', cancelled: 'Stopped' })[status],\n subagentTime: 'Time',\n subagentToolCalls: (count: number) => `${count} tool ${count === 1 ? 'call' : 'calls'}`,\n subagentTokens: (input: number, output: number) => `${input} tokens in, ${output} tokens out`,\n subagentConversation: (id: number) => `Open conversation ${id}`,\n // Artifact cards\n artifact: 'Artifact',\n artifactTypes: { markdown: 'Document', html: 'HTML page', svg: 'SVG image', code: 'Code', canvas: 'Canvas' },\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 camera: CameraIcon 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 const stableLabels = useShallowStable(labels), stableIcons = useShallowStable(icons);\n return useMemo(() => ({ labels: withDefaults(base.labels, stableLabels), icons: withDefaults(base.icons, stableIcons) }), [stableLabels, stableIcons, base]);\n}\n\nconst shallowEqual = (a: unknown, b: unknown): boolean => Object.is(a, b) || (!!a && !!b && typeof a === 'object' && typeof b === 'object' && Array.isArray(a) === Array.isArray(b)\n && Object.keys(a).length === Object.keys(b).length && Object.keys(a).every(key => Object.is((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key])));\n/** The previous value while the new one is equal key by key (functions by identity): inline `labels={{ title }}` keeps one text context. */\nexport function useShallowStable<T>(value: T): T {\n const previous = useRef(value);\n if (!shallowEqual(previous.current, value)) previous.current = value;\n return previous.current;\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",
160
+ "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, useRef } from 'react';\nimport type { ReactNode } from 'react';\nimport { ArrowDownIcon, ArrowUpIcon, CameraIcon, GitForkIcon, HistoryIcon, ListEndIcon, MessagesSquareIcon, PaperclipIcon, PlusIcon, RefreshCwIcon, SquareIcon } from 'lucide-react';\nimport type { BlockIcon } from '../button/actions';\nimport { withDefaults } from '../utils/utils';\n\n// An Intl.DateTimeFormat costs far more than formatting with one; every bubble's clock reuses the same few.\nconst formats = new Map<string, Intl.DateTimeFormat>();\nfunction intlFormat(locale: string, options: Intl.DateTimeFormatOptions): Intl.DateTimeFormat {\n const key = `${locale}|${JSON.stringify(options)}`;\n let found = formats.get(key);\n if (!found) { found = new Intl.DateTimeFormat(locale, options); formats.set(key, found); }\n return found;\n}\n/** « Tue 22 Oct, 14:02 ». */\nexport function formatTimestamp(at: string, locale: string) {\n const date = new Date(at);\n if (!Number.isFinite(date.getTime())) return at;\n return `${intlFormat(locale, { weekday: 'short', day: 'numeric', month: 'short' }).format(date)}, ${intlFormat(locale, { hour: '2-digit', minute: '2-digit' }).format(date)}`;\n}\n/** The time inside a bubble (« 14:02 », « 2:02 PM »). */\nexport function formatClock(at: string, locale: string) {\n const date = new Date(at);\n return Number.isFinite(date.getTime()) ? intlFormat(locale, { hour: 'numeric', minute: '2-digit' }).format(date) : '';\n}\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 artifacts: 'Artifacts',\n search: 'Search',\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 one status of `presentation=\"natural\"` while the agent works (any tool, retry or compaction), instead of the activity wording above. */\n preparing: 'Preparing…',\n /** In `presentation=\"natural\"`, replaces the controller's own reason when a send is blocked. */\n sendUnavailable: 'Sending is not available right now.',\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 takePhoto: 'Take a photo',\n cameraShoot: 'Take the photo',\n cameraClose: 'Close the camera',\n cameraUnavailable: 'The camera cannot open on this page.',\n cameraFallback: \"Use the phone's camera\",\n commands: 'Commands',\n annotate: 'Annotate',\n annotateHint: 'Annotate: click what you want to comment on (Esc to stop)',\n annotateNotes: (count: number) => `${count} ${count === 1 ? 'note' : 'notes'}`,\n annotateClear: 'Remove the notes',\n feedbackSent: (count: number) => `${count} ${count === 1 ? 'comment' : 'comments'} on the page`,\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 /** The type line of a file card in a sent message. */\n fileKind: { document: 'Document', image: 'Image', pdf: 'PDF', sheet: 'Spreadsheet', slides: 'Presentation', audio: 'Audio', file: 'File' },\n openFile: (name: string) => `Open ${name}`,\n fileChange: { created: 'Created', edited: 'Edited' },\n /** The name of a pasted text file: the words and the time it was pasted. */\n pastedFileName: (stamp: string) => `Pasted text ${stamp}`,\n restorePaste: 'Put the pasted text back in the message',\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 voiceHold: 'Hold to record, release to send',\n voicePauseRecording: 'Pause recording',\n voiceResumeRecording: 'Resume recording',\n voicePaused: 'Recording paused',\n voiceRecording: 'Recording',\n voicePreparing: 'Preparing voice message…',\n voiceAudioOnly: 'Send audio only',\n voiceDiscard: 'Discard',\n voicePlay: 'Play voice message',\n voicePause: 'Pause voice message',\n voicePlayFailed: 'The audio could not be played. Try again.',\n voiceBlocked: 'Not sent. Review the chat notice before trying again.',\n voiceUnconfirmed: 'Message admission is unconfirmed. Use the chat notice to reconcile.',\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 voiceTranscriptUnavailable: 'Voice message — transcription unavailable.',\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 /** The time inside a bubble in the `messaging` style (« 14:02 »), and its full date as the tooltip. */\n messageClock: (at: string) => formatClock(at, 'en'),\n messageTimestamp: (at: string) => formatTimestamp(at, 'en'),\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 loadEarlierMessages: 'Load earlier messages',\n earlierMessagesLoaded: (count: number) => `${count} earlier messages loaded`,\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: 'Start 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 imagePosition: (index: number, count: number) => `Image ${index} of ${count}`,\n previousImage: 'Previous image',\n nextImage: 'Next image',\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 /** A question of a form left blank, in the answer sent to the agent. */\n skipped: '(no 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 // Run card (a headless run: `runs/<id>`)\n run: 'Run',\n runStatus: (status: 'queued' | 'running' | 'completed' | 'failed'): string => ({ queued: 'Queued', running: 'Running', completed: 'Completed', failed: 'Failed' })[status],\n runElapsed: (time: string) => `Running for ${time}`,\n runDuration: (time: string) => `Took ${time}`,\n runRefresh: 'Refresh',\n runNotLoaded: 'The run could not be loaded.',\n // Sub-agent card (a `delegate` call)\n subagentStatus: (status: 'running' | 'done' | 'failed' | 'cancelled'): string => ({ running: 'Running', done: 'Done', failed: 'Failed', cancelled: 'Stopped' })[status],\n subagentTime: 'Time',\n subagentToolCalls: (count: number) => `${count} tool ${count === 1 ? 'call' : 'calls'}`,\n subagentTokens: (input: number, output: number) => `${input} tokens in, ${output} tokens out`,\n subagentConversation: (id: number) => `Open conversation ${id}`,\n // Artifact cards\n artifact: 'Artifact',\n artifactTypes: { markdown: 'Document', html: 'HTML page', svg: 'SVG image', code: 'Code', canvas: 'Canvas' },\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 camera: CameraIcon 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 const stableLabels = useShallowStable(labels), stableIcons = useShallowStable(icons);\n return useMemo(() => ({ labels: withDefaults(base.labels, stableLabels), icons: withDefaults(base.icons, stableIcons) }), [stableLabels, stableIcons, base]);\n}\n\nconst shallowEqual = (a: unknown, b: unknown): boolean => Object.is(a, b) || (!!a && !!b && typeof a === 'object' && typeof b === 'object' && Array.isArray(a) === Array.isArray(b)\n && Object.keys(a).length === Object.keys(b).length && Object.keys(a).every(key => Object.is((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key])));\n/** The previous value while the new one is equal key by key (functions by identity): inline `labels={{ title }}` keeps one text context. */\nexport function useShallowStable<T>(value: T): T {\n const previous = useRef(value);\n // eslint-disable-next-line react-hooks/refs -- a render-time identity cache: it only swaps in a value equal key by key, so any render reads the same result\n if (!shallowEqual(previous.current, value)) previous.current = value;\n // eslint-disable-next-line react-hooks/refs -- returns the cached identity (see above); never setState in render\n return previous.current;\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",
189
161
  "type": "registry:lib",
190
162
  "target": "components/pi-chat/labels.ts"
191
163
  },
192
164
  {
193
165
  "path": "registry/pi-chat/labels-fr.ts",
194
- "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 { formatClock, formatTimestamp } from './labels';\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 artifacts: 'Fichiers',\n search: 'Rechercher',\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 preparing: 'En préparation…',\n sendUnavailable: 'L’envoi n’est pas disponible pour le moment.',\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 takePhoto: 'Prendre une photo',\n cameraShoot: 'Prendre la photo',\n cameraClose: 'Fermer l’appareil photo',\n cameraUnavailable: 'L’appareil photo ne peut pas s’ouvrir sur cette page.',\n cameraFallback: 'Utiliser l’appareil photo du téléphone',\n // Voice input (the microphone button beside the composer)\n voiceRecord: 'Enregistrer un message',\n voiceHold: 'Maintenir pour enregistrer, relâcher pour envoyer',\n voiceRecording: 'Enregistrement',\n voicePreparing: 'Préparation du message vocal…',\n voiceAudioOnly: 'Envoyer l’audio seul',\n voiceDiscard: 'Abandonner',\n voicePlay: 'Lire',\n voicePause: 'Mettre en pause',\n voicePlayFailed: 'La lecture de l’audio a échoué. Réessayez.',\n voiceBlocked: 'Non envoyé. Vérifiez l’avis de la conversation avant de réessayer.',\n voiceUnconfirmed: 'L’envoi n’est pas confirmé. Vérifiez l’avis de la conversation.',\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 annotate: 'Annoter',\n annotateHint: 'Annoter : cliquez sur ce que vous voulez commenter (Échap pour arrêter)',\n annotateNotes: count => `${count} ${count === 1 ? 'note' : 'notes'}`,\n annotateClear: 'Retirer les notes',\n feedbackSent: count => `${count} ${count === 1 ? 'commentaire' : 'commentaires'} sur la page`,\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 fileKind: { document: 'Document', image: 'Image', pdf: 'PDF', sheet: 'Tableur', slides: 'Présentation', audio: 'Audio', file: 'Fichier' },\n openFile: name => `Ouvrir ${name}`,\n fileChange: { created: 'Créé', edited: 'Modifié' },\n pastedFileName: stamp => `Texte collé ${stamp}`,\n restorePaste: 'Remettre le texte collé dans le message',\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 messageClock: at => formatClock(at, 'fr'),\n messageTimestamp: at => formatTimestamp(at, 'fr'),\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 loadEarlierMessages: 'Charger les messages précédents',\n earlierMessagesLoaded: count => `${count} messages précédents chargés`,\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 imagePosition: (index, count) => `Image ${index} sur ${count}`,\n previousImage: 'Image précédente',\n nextImage: 'Image suivante',\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 run: 'Exécution',\n runStatus: status => ({ queued: 'En attente', running: 'En cours', completed: 'Terminée', failed: 'Échouée' })[status],\n runElapsed: time => `En cours depuis ${time}`,\n runDuration: time => `Durée : ${time}`,\n runRefresh: 'Actualiser',\n runNotLoaded: 'L’exécution n’a pas pu être chargée.',\n subagentStatus: status => ({ running: 'En cours', done: 'Terminé', failed: 'Échoué', cancelled: 'Arrêté' })[status],\n subagentTime: 'Durée',\n subagentToolCalls: count => `${count} ${count === 1 ? 'appel' : 'appels'} d’outil`,\n subagentTokens: (input, output) => `${input} jetons en entrée, ${output} jetons en sortie`,\n subagentConversation: id => `Ouvrir la conversation ${id}`,\n skipped: '(pas de 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 artifactTypes: { markdown: 'Document', html: 'Page HTML', svg: 'Image SVG', code: 'Code', canvas: 'Canevas' },\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",
166
+ "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 { formatClock, formatTimestamp } from './labels';\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 artifacts: 'Fichiers',\n search: 'Rechercher',\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 preparing: 'En préparation…',\n sendUnavailable: 'L’envoi n’est pas disponible pour le moment.',\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 takePhoto: 'Prendre une photo',\n cameraShoot: 'Prendre la photo',\n cameraClose: 'Fermer l’appareil photo',\n cameraUnavailable: 'L’appareil photo ne peut pas s’ouvrir sur cette page.',\n cameraFallback: 'Utiliser l’appareil photo du téléphone',\n // Voice input (the microphone button beside the composer)\n voiceRecord: 'Enregistrer un message',\n voiceHold: 'Maintenir pour enregistrer, relâcher pour envoyer',\n voicePauseRecording: 'Mettre l’enregistrement en pause',\n voiceResumeRecording: 'Reprendre l’enregistrement',\n voicePaused: 'Enregistrement en pause',\n voiceRecording: 'Enregistrement',\n voicePreparing: 'Préparation du message vocal…',\n voiceAudioOnly: 'Envoyer l’audio seul',\n voiceDiscard: 'Abandonner',\n voicePlay: 'Lire',\n voicePause: 'Mettre en pause',\n voicePlayFailed: 'La lecture de l’audio a échoué. Réessayez.',\n voiceBlocked: 'Non envoyé. Vérifiez l’avis de la conversation avant de réessayer.',\n voiceUnconfirmed: 'L’envoi n’est pas confirmé. Vérifiez l’avis de la conversation.',\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 voiceTranscriptUnavailable: 'Message vocal — transcription indisponible.',\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 annotate: 'Annoter',\n annotateHint: 'Annoter : cliquez sur ce que vous voulez commenter (Échap pour arrêter)',\n annotateNotes: count => `${count} ${count === 1 ? 'note' : 'notes'}`,\n annotateClear: 'Retirer les notes',\n feedbackSent: count => `${count} ${count === 1 ? 'commentaire' : 'commentaires'} sur la page`,\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 fileKind: { document: 'Document', image: 'Image', pdf: 'PDF', sheet: 'Tableur', slides: 'Présentation', audio: 'Audio', file: 'Fichier' },\n openFile: name => `Ouvrir ${name}`,\n fileChange: { created: 'Créé', edited: 'Modifié' },\n pastedFileName: stamp => `Texte collé ${stamp}`,\n restorePaste: 'Remettre le texte collé dans le message',\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 messageClock: at => formatClock(at, 'fr'),\n messageTimestamp: at => formatTimestamp(at, 'fr'),\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 loadEarlierMessages: 'Charger les messages précédents',\n earlierMessagesLoaded: count => `${count} messages précédents chargés`,\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 imagePosition: (index, count) => `Image ${index} sur ${count}`,\n previousImage: 'Image précédente',\n nextImage: 'Image suivante',\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 run: 'Exécution',\n runStatus: status => ({ queued: 'En attente', running: 'En cours', completed: 'Terminée', failed: 'Échouée' })[status],\n runElapsed: time => `En cours depuis ${time}`,\n runDuration: time => `Durée : ${time}`,\n runRefresh: 'Actualiser',\n runNotLoaded: 'L’exécution n’a pas pu être chargée.',\n subagentStatus: status => ({ running: 'En cours', done: 'Terminé', failed: 'Échoué', cancelled: 'Arrêté' })[status],\n subagentTime: 'Durée',\n subagentToolCalls: count => `${count} ${count === 1 ? 'appel' : 'appels'} d’outil`,\n subagentTokens: (input, output) => `${input} jetons en entrée, ${output} jetons en sortie`,\n subagentConversation: id => `Ouvrir la conversation ${id}`,\n skipped: '(pas de 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 artifactTypes: { markdown: 'Document', html: 'Page HTML', svg: 'Image SVG', code: 'Code', canvas: 'Canevas' },\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",
195
167
  "type": "registry:lib",
196
168
  "target": "components/pi-chat/labels-fr.ts"
197
169
  },
@@ -203,7 +175,7 @@
203
175
  },
204
176
  {
205
177
  "path": "registry/pi-chat/use-conversations.ts",
206
- "content": "import { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport type { ConversationItem, ConversationsConfig } from './config';\n\n/** One row as `createConversationsHandler` of `@hachej/boring-agent/conversations` returns it. */\ninterface ServedConversation {\n readonly id: number | string;\n readonly title: string | null;\n readonly lastMessage: string | null;\n readonly updatedAt: number;\n readonly archived: boolean;\n}\n\nconst item = (served: ServedConversation): ConversationItem => ({ id: String(served.id), title: served.title ?? undefined, updatedAt: served.updatedAt, lastMessage: served.lastMessage, archived: served.archived });\n\n/**\n * The sessions list over the host's conversations handler (`createConversationsHandler` of `@hachej/boring-agent/conversations`, mounted at\n * `endpoint`): the active list (polled every `pollMs` while mounted), server-side search with the Archived filter, New, rename, archive,\n * delete and fork. New and fork select the conversation they made through `onSelect`. `onChange` runs after every change the person made\n * (the host may reload what depends on the list). `fetch` is the host's authenticated fetch. Returns `undefined` until the first list arrives.\n */\nexport function useConversations({ endpoint, fetch, activeId, onSelect, onChange, pollMs = 4000 }: {\n /** Undefined: nothing is listed yet (for example while the host is still loading). */\n readonly endpoint: string | URL | undefined;\n readonly fetch: (request: Request) => Promise<Response>;\n readonly activeId: string | undefined;\n readonly onSelect: (id: string) => void;\n readonly onChange?: (() => void | Promise<void>) | undefined;\n readonly pollMs?: number;\n}): (ConversationsConfig & { readonly reload: () => Promise<void> }) | undefined {\n const [items, setItems] = useState<readonly ConversationItem[] | undefined>();\n const latest = useRef({ fetch, onSelect, onChange, activeId });\n latest.current = { fetch, onSelect, onChange, activeId };\n const base = endpoint === undefined ? undefined : String(endpoint);\n const call = useCallback(async (params: Record<string, string>, body?: unknown, signal?: AbortSignal) => {\n if (base === undefined) throw new Error('No conversations endpoint');\n const url = new URL(base, globalThis.location?.href);\n for (const [key, value] of Object.entries(params)) url.searchParams.set(key, value);\n const init: RequestInit = body === undefined ? { ...(signal ? { signal } : {}) } : { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body), ...(signal ? { signal } : {}) };\n const response = await latest.current.fetch(new Request(url, init));\n if (!response.ok) throw new Error(`Conversations: ${response.status}`);\n return await response.json() as { conversations?: readonly ServedConversation[]; conversationId?: number | string };\n }, [base]);\n const reload = useCallback(async () => { const result = await call({}); setItems((result.conversations ?? []).map(item)); }, [call]);\n // Another endpoint (another owner's list) starts empty; switching conversations only reloads.\n useEffect(() => { setItems(undefined); }, [base]);\n useEffect(() => {\n if (base === undefined) return;\n let off = false;\n const load = () => call({}).then(result => { if (!off) setItems((result.conversations ?? []).map(item)); }).catch(() => {});\n void load();\n const timer = setInterval(load, pollMs);\n return () => { off = true; clearInterval(timer); };\n }, [call, pollMs, activeId]); // eslint-disable-line react-hooks/exhaustive-deps\n return useMemo(() => {\n if (!items) return undefined;\n const changed = async () => { await reload().catch(() => {}); await latest.current.onChange?.(); };\n const op = (name: string, body: unknown) => call({ op: name }, body);\n return {\n items, activeId, reload,\n onSelect: (id: string) => latest.current.onSelect(id),\n onNew: () => { void op('create', {}).then(async result => { await changed(); if (result.conversationId !== undefined) latest.current.onSelect(String(result.conversationId)); }).catch(() => {}); },\n search: async (query: string, { archived }: { readonly archived: boolean }, signal: AbortSignal) =>\n ((await call({ ...(query ? { q: query } : {}), ...(archived ? { archived: '1' } : {}) }, undefined, signal)).conversations ?? []).map(item),\n rename: async (id: string, title: string) => { await op('rename', { conversationId: id, title }); await changed(); },\n archive: async (id: string, archived: boolean) => { await op('archive', { conversationId: id, archived }); await changed(); },\n remove: async (id: string) => { await op('delete', { conversationId: id }); await changed(); },\n fork: async (at: string) => {\n const from = latest.current.activeId;\n if (from === undefined) return;\n const { conversationId } = await op('fork', { conversationId: from, at });\n await changed();\n if (conversationId !== undefined) latest.current.onSelect(String(conversationId));\n },\n };\n }, [items, activeId, call, reload]);\n}\n",
178
+ "content": "// Compatibility export for one release; protocol/polling/actions live in the kit.\nexport { useConversations, useConversationsClient } from '@hachej/boring-ui-kit/chat-react';\n",
207
179
  "type": "registry:hook",
208
180
  "target": "components/pi-chat/use-conversations.ts"
209
181
  }
@@ -242,7 +214,7 @@
242
214
  }
243
215
  },
244
216
  "@layer utilities": {
245
- "@media (max-width: 640px), (pointer: coarse)": {
217
+ "@media (width < 768px), (pointer: coarse)": {
246
218
  ".pi-chat :is([data-slot=\"button\"], [data-slot=\"toggle\"], [class~=\"group/button\"], [class~=\"group/toggle\"])": {
247
219
  "min-height": "2.75rem",
248
220
  "min-width": "2.75rem"