@hachej/boring-ui-kit 0.3.1 → 0.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +2 -2
- package/r/app-shell.json +16 -10
- package/r/button.json +1 -1
- package/r/dock.json +1 -1
- package/r/documents.json +56 -0
- package/r/feedback-preview.json +1 -1
- package/r/feedback.json +5 -5
- package/r/file-tree.json +3 -3
- package/r/html-viewer.json +2 -2
- package/r/markdown-editor.json +2 -2
- package/r/pi-ambient.json +7 -7
- package/r/pi-app.json +10 -10
- package/r/pi-chat.json +11 -11
- package/r/pi-workspace.json +4 -4
- package/r/provider-setup.json +2 -2
- package/r/registry.json +109 -54
- package/r/task-list-viewer.json +2 -2
- package/r/viewers.json +5 -5
package/r/pi-ambient.json
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
"title": "Pi ambient agent",
|
|
5
5
|
"description": "AmbientChat, a compact floating agent bar that grows into a chat window over an existing page, and AgentNotifications, toasts for finished, failed and waiting tasks (with the one guarded browser Notification helper). A block over the pi-chat item; its in-window artifact panel uses the pi-workspace layout.",
|
|
6
6
|
"dependencies": [
|
|
7
|
-
"@hachej/boring-ui-kit@^0.3.
|
|
7
|
+
"@hachej/boring-ui-kit@^0.3.2",
|
|
8
8
|
"react@^19.0.0",
|
|
9
9
|
"react-dom@^19.0.0",
|
|
10
10
|
"@earendil-works/pi-durable@~1.2.0",
|
|
@@ -12,16 +12,16 @@
|
|
|
12
12
|
"lucide-react@^1.51.0"
|
|
13
13
|
],
|
|
14
14
|
"registryDependencies": [
|
|
15
|
-
"https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.3.
|
|
16
|
-
"https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.3.
|
|
17
|
-
"https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.3.
|
|
18
|
-
"https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.3.
|
|
19
|
-
"https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.3.
|
|
15
|
+
"https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.3.2/r/theme.json",
|
|
16
|
+
"https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.3.2/r/pi-chat.json",
|
|
17
|
+
"https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.3.2/r/pi-workspace.json",
|
|
18
|
+
"https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.3.2/r/utils.json",
|
|
19
|
+
"https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.3.2/r/button.json"
|
|
20
20
|
],
|
|
21
21
|
"files": [
|
|
22
22
|
{
|
|
23
23
|
"path": "registry/pi-ambient/ambient.tsx",
|
|
24
|
-
"content": "'use client';\n\nimport { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';\nimport type { KeyboardEvent, PointerEvent, ReactNode } from 'react';\nimport type { EntryRecord } from '@earendil-works/pi-durable';\nimport type { ImageContent, ToolCall, ToolResultMessage } from '@earendil-works/pi-ai';\nimport type { NativeChatController } from '@hachej/boring-ui-kit/native-chat';\nimport { BellIcon, ChevronDownIcon, ExternalLinkIcon, GripVerticalIcon, Loader2Icon, MinusIcon, PanelLeftIcon, ThumbsDownIcon, ThumbsUpIcon } from 'lucide-react';\nimport { Button } from '../button/button';\nimport { BlockActions } from '../button/actions';\nimport type { BlockAction, BlockIcon } from '../button/actions';\nimport { CopyButton } from '../pi-chat/code-block';\nimport { Composer } from '../pi-chat/composer';\nimport type { ComposerFeedback } from '../pi-chat/composer';\nimport type { AttachmentsConfig, ConversationsConfig, EffortConfig, MentionsConfig, ModelConfig, SlashConfig } from '../pi-chat/config';\nimport { notifyPermission, requestNotifyPermission } from './browser-notify';\nimport type { NotifyPermission } from './browser-notify';\nimport { ConversationHistory } from '../pi-chat/history';\nimport type { CommandMentions } from '../pi-chat/markdown';\nimport { RowView } from '../pi-chat/message';\nimport type { RowContext } from '../pi-chat/message';\nimport { ChatNotices, Notice } from '../pi-chat/notice';\nimport { AgentNotifications, KindIcon, createNotificationStore, defaultNotificationLabels, finishNotice, pendingQuestion, useNotifications } from './notifications';\nimport type { AgentNotification, NotificationLabels, NotificationStore } from './notifications';\nimport { ChatTextProvider, defaultChatIcons, defaultChatLabels, useMergedText } from '../pi-chat/labels';\nimport type { ChatIcons, ChatLabels } from '../pi-chat/labels';\nimport { MessageQueue } from '../pi-chat/queue';\nimport { artifactKey, collectArtifacts } from '../pi-chat/artifact';\nimport type { ArtifactDescriptor, ArtifactsConfig } from '../pi-chat/artifact';\nimport type { ChatCard, Mode } from '../pi-chat/rows';\nimport { useChatSession, useTranscript } from '../pi-chat/session';\nimport type { ChatFeatureProps, ChatSession } from '../pi-chat/session';\nimport { ArtifactWorkspace } from '../pi-workspace/workspace';\nimport type { WorkspacePanelApi } from '../pi-workspace/workspace';\nimport { cn } from '../utils/utils';\n\nexport { AgentNotifications, createNotificationStore, defaultNotificationLabels, summaryOf, useNotifications, watchConversation } from './notifications';\nexport type { AgentNotification, AgentNotificationsProps, NewNotification, NotificationKind, NotificationLabels, NotificationStore } from './notifications';\n\nconst elapsedText = (seconds: number) => seconds < 60 ? `${seconds}s` : `${Math.floor(seconds / 60)}m ${String(seconds % 60).padStart(2, '0')}s`;\n\n/** The floating window's own words, over the chat's (`defaultChatLabels`) and the toasts' (`defaultNotificationLabels`). */\nexport const defaultAmbientLabels = {\n ...defaultChatLabels,\n ...defaultNotificationLabels,\n /** Shown while the conversation has no title of its own (the active item of `conversations` provides one). */\n title: 'Agent',\n /** The input's placeholder while idle. */\n placeholder: 'Do anything',\n /** The input's placeholder while the agent works. */\n working: (seconds: number) => `Working for ${elapsedText(seconds)}`,\n region: (title: string) => `Agent: ${title}`,\n openAgent: (title: string, unread: boolean) => `Open agent: ${title}${unread ? ' (new activity)' : ''}`,\n openChat: (title: string) => `Open chat: ${title}`,\n minimize: 'Minimise',\n switchConversation: 'Switch conversation',\n statusWorking: 'Working',\n enableNotifications: 'Notify me when the page is in the background',\n dock: 'Dock chat',\n dockHint: 'Dock chat beside the panel',\n move: 'Move the agent window (arrow keys, Home resets)',\n moveHint: 'Drag to move',\n goodResponse: 'Good response',\n badResponse: 'Bad response',\n openFull: 'Open in full chat',\n empty: 'Ask the agent to do something.',\n loadFailedShort: 'Could not load the conversation.',\n disconnectedShort: 'Disconnected.',\n artifactPanel: 'Artifact panel',\n};\nexport type AmbientLabels = ChatLabels & NotificationLabels & typeof defaultAmbientLabels;\n\n/** The floating window's icons, over the chat's. */\nexport const defaultAmbientIcons = {\n ...defaultChatIcons,\n minimize: MinusIcon as BlockIcon,\n dock: PanelLeftIcon as BlockIcon,\n grip: GripVerticalIcon as BlockIcon,\n switchConversation: ChevronDownIcon as BlockIcon,\n notify: BellIcon as BlockIcon,\n openFull: ExternalLinkIcon as BlockIcon,\n goodResponse: ThumbsUpIcon as BlockIcon,\n badResponse: ThumbsDownIcon as BlockIcon,\n};\nexport type AmbientIcons = ChatIcons & typeof defaultAmbientIcons;\nconst AMBIENT_TEXT = { labels: defaultAmbientLabels as AmbientLabels, icons: defaultAmbientIcons as AmbientIcons };\n\n/** `bar` is the compact bar, `expanded` the same window grown into a chat, `minimized` a small pill. */\nexport type AmbientState = 'bar' | 'expanded' | 'minimized';\n\n/** What the artifact panel inside the window gets besides the full-screen and close controls: the versions of the open artifact and how to switch. */\nexport interface AmbientArtifactPanelApi extends WorkspacePanelApi {\n /** Every known version of the open artifact in this conversation, newest first. */\n readonly versions: readonly ArtifactDescriptor[];\n /** True while the panel follows the newest version; false when one older version is pinned. */\n readonly follow: boolean;\n /** `'latest'` follows the newest version; a descriptor from `versions` pins that one. */\n readonly select: (version: ArtifactDescriptor | 'latest') => void;\n}\n\nexport interface AmbientChatProps extends ChatFeatureProps {\n readonly controller: NativeChatController;\n /**\n * Every word the window shows, over `defaultAmbientLabels` (the chat's labels, the toasts' and its own): `title` while the conversation has\n * none of its own, `placeholder` while idle, `working(seconds)` while the agent works.\n */\n readonly labels?: Partial<AmbientLabels> | undefined;\n /** The window's icons (minimise, dock, grip, …) and the chat's, over `defaultAmbientIcons`. */\n readonly icons?: Partial<AmbientIcons> | undefined;\n /** The agent's avatar before the title in the bar. */\n readonly avatar?: ReactNode;\n /** Host actions in the bar, before Dock: `header` ones as buttons, `menu` ones in a \"…\" menu. Test ids `ambient-action-<id>`, the menu `ambient-action-more`. */\n readonly headerActions?: readonly BlockAction[] | undefined;\n /** `contrast` is a dark window on any page: the root carries `.dark`, so it shows the host's own dark tokens; `surface` follows the host's theme. */\n readonly variant?: 'contrast' | 'surface';\n /** Controlled window state; otherwise `defaultState` starts it and the window keeps it. */\n readonly state?: AmbientState;\n readonly defaultState?: AmbientState;\n readonly onStateChange?: (state: AmbientState) => void;\n /** Where the bar was dragged is remembered under this key. */\n readonly storageKey?: string;\n /** `session` (default) remembers the position for this browser tab's session; `local` keeps it in `localStorage` across sessions. */\n readonly storage?: 'session' | 'local';\n /** Host controls in the composer row, between the effort picker and Send (for example a voice button the host guards itself). Absent: nothing is shown. */\n readonly tools?: ReactNode;\n /** Hand the conversation to a full `PiChat` or `ArtifactWorkspace`. Adds an \"Open in full chat\" action to replies. */\n readonly onOpenFull?: (conversationId: string) => void;\n /** Adds thumbs up and down to replies. `value` is `null` when the person takes the rating back. */\n readonly onFeedback?: (reply: { readonly key: string; readonly text: string }, value: 'up' | 'down' | null) => void;\n /** Toasts for finished, failed and waiting tasks. Pass a store to feed it for background conversations too; `false` turns them off. */\n readonly notifications?: NotificationStore | false;\n readonly autoDismissMs?: number;\n readonly maxToasts?: number;\n /** System notifications while the page is hidden. A bell in the header asks for permission when the person chooses to; nothing is asked on load. */\n readonly systemNotifications?: boolean;\n /**\n * The viewer shown inside the window when an artifact card is opened: the window widens into chat on the left and this panel on the right\n * (`ArtifactWorkspace`: draggable divider, full screen, a full-screen sheet on a phone). Build it from the viewer registry (`ViewerFrame`, ...),\n * wrapped in `ViewerWindowProvider` with `api.fullscreen` / `api.onFullscreenChange` so its bar shows the full screen button.\n */\n readonly artifactPanel?: (artifact: ArtifactDescriptor, api: AmbientArtifactPanelApi) => ReactNode;\n /** `window` (default when `artifactPanel` is given) opens artifacts inside the window; `host` calls `artifacts.open` instead, for hosts that show them in their own viewer. */\n readonly artifactTarget?: 'window' | 'host';\n /** The title's ⌄ opens this list to switch conversations or tasks. */\n readonly conversations?: ConversationsConfig;\n /** Adds a \"Dock chat\" action to the header, for a host that floats this window out of a docked chat (`ArtifactWorkspace` with `floatBelow`). It shares the controller with the docked `PiChat`, so nothing is lost. */\n readonly onDock?: () => void;\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 readonly className?: string;\n}\n\ninterface Position { readonly right: number; readonly bottom: number }\nconst MARGIN = 8, DEFAULT_POSITION: Position = { right: 16, bottom: 16 };\n\nfunction storageFor(persist: 'session' | 'local'): Storage | undefined { try { return persist === 'local' ? globalThis.localStorage : globalThis.sessionStorage; } catch { return undefined; } }\nfunction readPosition(key: string, persist: 'session' | 'local'): Position | undefined {\n try {\n const value: unknown = JSON.parse(storageFor(persist)?.getItem(key) ?? 'null');\n const { right, bottom } = (value ?? {}) as { right?: unknown; bottom?: unknown };\n return typeof right === 'number' && typeof bottom === 'number' && Number.isFinite(right) && Number.isFinite(bottom) ? { right, bottom } : undefined;\n } catch { return undefined; }\n}\nfunction writePosition(key: string, persist: 'session' | 'local', position: Position) {\n try { storageFor(persist)?.setItem(key, JSON.stringify(position)); } catch { /* the position is a convenience */ }\n}\nconst clamp = (position: Position, size: { w: number; h: number }, viewport: { w: number; h: number }): Position => ({\n right: Math.round(Math.min(Math.max(MARGIN, position.right), Math.max(MARGIN, viewport.w - size.w - MARGIN))),\n bottom: Math.round(Math.min(Math.max(MARGIN, position.bottom), Math.max(MARGIN, viewport.h - size.h - MARGIN))),\n});\n\n// The layout viewport that fixed positioning uses (without scrollbars), not the window's outer size.\nconst viewportSize = () => { const root = globalThis.document?.documentElement; return { w: root?.clientWidth || globalThis.innerWidth || 1024, h: root?.clientHeight || globalThis.innerHeight || 768 }; };\nfunction usePhone(): boolean {\n const query = '(max-width: 639px)';\n const [phone, setPhone] = useState(() => globalThis.matchMedia?.(query).matches === true);\n useEffect(() => {\n const list = globalThis.matchMedia?.(query);\n if (!list) return;\n const update = () => setPhone(list.matches);\n update();\n list.addEventListener('change', update);\n return () => list.removeEventListener('change', update);\n }, []);\n return phone;\n}\n\n/** Whole seconds since `active` became true; 0 while inactive. */\nfunction useElapsed(active: boolean): number {\n const [seconds, setSeconds] = useState(0);\n useEffect(() => {\n if (!active) { setSeconds(0); return; }\n const started = Date.now();\n setSeconds(0);\n const timer = setInterval(() => setSeconds(Math.floor((Date.now() - started) / 1000)), 1000);\n return () => clearInterval(timer);\n }, [active]);\n return seconds;\n}\n\n/** Pushes a toast when a run finishes or fails and when a question starts waiting; takes it back when the question is answered or a new run starts. */\nfunction useRunFeed({ enabled, store, conversationId, title, session, suppress, onOutcome, waiting }: {\n readonly enabled: boolean; readonly store: NotificationStore; readonly conversationId: string; readonly title: string; readonly session: ChatSession; readonly waiting: string;\n readonly suppress: () => boolean; readonly onOutcome: (outcome: 'done' | 'error' | null) => void;\n}) {\n const { working, waitingForAnswer, rows, connected } = session;\n const before = useRef({ working, waiting: waitingForAnswer });\n const latest = useRef({ rows, title, suppress, onOutcome, connected, waiting });\n latest.current = { rows, title, suppress, onOutcome, connected, waiting };\n useEffect(() => {\n const was = before.current;\n before.current = { working, waiting: waitingForAnswer };\n const now = latest.current;\n if (working && !was.working) { now.onOutcome(null); store.dismiss(`${conversationId}:done`); }\n if (!enabled) return;\n if (waitingForAnswer && !was.waiting && !now.suppress()) store.push({ id: `${conversationId}:input`, kind: 'input', title: now.title, summary: pendingQuestion(now.rows) ?? now.waiting, conversationId });\n if (!waitingForAnswer && was.waiting) store.dismiss(`${conversationId}:input`);\n if (was.working && !working && now.connected) {\n const finished = finishNotice(now.rows);\n if (!finished) return;\n now.onOutcome(finished.kind);\n if (!now.suppress()) store.push({ id: `${conversationId}:done`, kind: finished.kind, title: now.title, summary: finished.summary, conversationId });\n }\n }, [working, waitingForAnswer, enabled, store, conversationId]);\n}\n\n/** A compact floating agent bar over an existing page; it grows into a chat window in place. Borrows a concrete native controller like `PiChat`. */\nexport function AmbientChat(props: AmbientChatProps) {\n const active = useRef(props.controller); active.current = props.controller;\n const [mount, setMount] = useState({ controller: props.controller, sequence: 0 });\n if (mount.controller !== props.controller) setMount({ controller: props.controller, sequence: mount.sequence + 1 });\n // The window state and the toasts belong to the bar, not to one conversation: they survive switching conversations.\n const [local, setLocal] = useState<AmbientState>(props.defaultState ?? 'bar');\n const internalStore = useMemo(createNotificationStore, []);\n const text = useMergedText<AmbientLabels, AmbientIcons>(props.labels, props.icons, AMBIENT_TEXT);\n return <ChatTextProvider value={text}><AmbientSession key={mount.sequence} {...props} labels={text.labels} icons={text.icons} activeController={active} windowState={props.state ?? local} store={props.notifications || internalStore}\n onWindowState={next => { if (props.state === undefined) setLocal(next); props.onStateChange?.(next); }} /></ChatTextProvider>;\n}\n\nconst iconButton = 'inline-flex size-8 shrink-0 cursor-pointer items-center justify-center rounded-lg text-muted-foreground outline-none transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/60 max-sm:size-11 pointer-coarse:size-11 motion-reduce:transition-none';\n\ntype SessionProps = Omit<AmbientChatProps, 'labels' | 'icons'> & { readonly labels: AmbientLabels; readonly icons: AmbientIcons; readonly activeController: { readonly current: NativeChatController }; readonly windowState: AmbientState; readonly store: NotificationStore; readonly onWindowState: (state: AmbientState) => void };\n\nfunction AmbientSession({ controller, labels, icons, avatar, headerActions, messageActions, variant = 'contrast', mode = 'expert', actions,\n windowState, onWindowState, store, storageKey = 'boring.ambient.position', storage = 'session', tools, onOpenFull, onFeedback, notifications, autoDismissMs, maxToasts, systemNotifications = false,\n renderEntry, renderTool, groupTool, commandMentions, onOpenImage, onCopy, onComposerKeyDown, fileAccept = 'image/*', slash, mentions, attachments, model, effort, replyFooter, artifacts: hostArtifacts, artifactPanel, artifactTarget, conversations, onDock, feedback: composerFeedback, className,\n activeController }: SessionProps) {\n const { title } = labels;\n const stateRef = useRef(windowState); stateRef.current = windowState;\n // The artifact open inside the window, and whether it follows the newest version. It belongs to the expanded window: leaving that state closes it.\n const [opened, setOpened] = useState<{ readonly descriptor: ArtifactDescriptor; readonly follow: boolean } | null>(null);\n const [fullscreen, setFullscreen] = useState(false);\n const setWindowState = (next: AmbientState) => {\n if (next !== 'expanded') { setOpened(null); setFullscreen(false); }\n if (next !== stateRef.current) onWindowState(next);\n };\n const expanded = windowState === 'expanded', minimized = windowState === 'minimized';\n const phone = usePhone();\n const root = useRef<HTMLDivElement>(null), titleButton = useRef<HTMLButtonElement>(null), pill = useRef<HTMLButtonElement>(null);\n const [picking, setPicking] = useState(false);\n const [feedback, setFeedback] = useState<Readonly<Record<string, 'up' | 'down'>>>({});\n const [outcome, setOutcome] = useState<'done' | 'error' | null>(null);\n const [permission, setPermission] = useState<NotifyPermission>('unsupported');\n useEffect(() => { setPermission(notifyPermission()); }, []);\n useEffect(() => { if (!outcome) return; const timer = setTimeout(() => setOutcome(null), 8000); return () => clearTimeout(timer); }, [outcome]);\n\n // Replies get copy, optional feedback and the time; the host may hand the conversation to its full chat.\n const conversationRef = useRef('');\n const replyActions = useMemo<NonNullable<RowContext['replyActions']>>(() => (reply, host) => <div data-testid=\"reply-actions\" className=\"mt-2 -ml-2 flex items-center gap-0.5 text-muted-foreground\">\n <CopyButton text={reply.text} label={labels.copyResponse} iconOnly {...(onCopy ? { onCopy } : {})} className=\"size-8 p-0 text-muted-foreground max-sm:size-11\" />\n {onFeedback && <>\n {(['up', 'down'] as const).map(value => <button key={value} type=\"button\" data-testid={`feedback-${value}`} aria-pressed={feedback[reply.key] === value} aria-label={value === 'up' ? labels.goodResponse : labels.badResponse}\n title={value === 'up' ? labels.goodResponse : labels.badResponse}\n onClick={() => { const next = feedback[reply.key] === value ? null : value; setFeedback(current => { const { [reply.key]: _removed, ...rest } = current; return next ? { ...rest, [reply.key]: next } : rest; }); onFeedback({ key: reply.key, text: reply.text }, next); }}\n className={cn(iconButton, 'aria-pressed:text-foreground')}>{value === 'up' ? <icons.goodResponse className=\"size-3.5\" aria-hidden=\"true\" /> : <icons.badResponse className=\"size-3.5\" aria-hidden=\"true\" />}</button>)}\n </>}\n {onOpenFull && <button type=\"button\" data-testid=\"open-full\" aria-label={labels.openFull} title={labels.openFull} onClick={() => onOpenFull(conversationRef.current)} className={iconButton}><icons.openFull className=\"size-3.5\" aria-hidden=\"true\" /></button>}\n {host}\n {reply.timestamp !== undefined && <time dateTime={new Date(reply.timestamp).toISOString()} data-testid=\"reply-time\" className=\"ml-1.5 text-xs tabular-nums\">{new Date(reply.timestamp).toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit' })}</time>}\n </div>, [onCopy, onFeedback, onOpenFull, feedback, labels, icons]);\n const scrollToBottom = useRef<() => void>(() => {});\n const rowExtras = useMemo(() => ({ replyActions }), [replyActions]);\n const inWindow = Boolean(artifactPanel) && artifactTarget !== 'host';\n const detect = hostArtifacts?.detect;\n const versionsRef = useRef<readonly ArtifactDescriptor[]>([]);\n const artifacts = useMemo<ArtifactsConfig | undefined>(() => !inWindow ? hostArtifacts : {\n open: descriptor => { const newest = versionsRef.current.filter(version => artifactKey(version) === artifactKey(descriptor)).reduce((top, version) => Math.max(top, version.ordinal ?? 0), 0); setOpened({ descriptor, follow: (descriptor.ordinal ?? 0) >= newest }); },\n isOpen: descriptor => opened !== null && artifactKey(opened.descriptor) === artifactKey(descriptor) && (opened.follow ? (descriptor.ordinal ?? 0) >= (versionsRef.current.find(version => artifactKey(version) === artifactKey(descriptor))?.ordinal ?? 0) : descriptor.revision === opened.descriptor.revision),\n ...(detect ? { detect } : {}),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [inWindow, hostArtifacts, opened, detect]);\n const session = useChatSession({ controller, activeController, mode, actions, renderEntry, renderTool, groupTool, commandMentions, onOpenImage, onCopy, onComposerKeyDown, fileAccept,\n slash, mentions, attachments, model, effort, artifacts, messageActions, replyFooter, afterSend: () => scrollToBottom.current(), rowExtras, feedback: composerFeedback });\n const { state, derived, rows, queued, queueActions, working, waitingForAnswer, error, act, textarea, rowContext, composer, empty, loading } = session;\n const transcript = useTranscript(rows);\n const versions = useMemo(() => inWindow ? collectArtifacts(state.view, detect).sort((a, b) => (b.ordinal ?? 0) - (a.ordinal ?? 0)) : [], [inWindow, state.view, detect]);\n versionsRef.current = versions;\n const known = opened ? versions.filter(version => artifactKey(version) === artifactKey(opened.descriptor)) : [];\n const shownArtifact = opened ? (opened.follow ? known[0] ?? opened.descriptor : opened.descriptor) : undefined;\n const { stick, hidden } = transcript;\n scrollToBottom.current = () => { void stick.scrollToBottom('instant'); };\n const { barStart, barNote } = session.pickers();\n\n const conversationId = String(conversations?.activeId ?? state.conversationId);\n conversationRef.current = conversationId;\n const activeItem = conversations?.items.find(item => item.id === conversations.activeId);\n const shownTitle = activeItem?.title?.trim() || title;\n const toasts = useNotifications(store);\n useRunFeed({ enabled: notifications !== false, store, conversationId, title: shownTitle, session, onOutcome: setOutcome, waiting: labels.waitingForAnswer,\n suppress: () => stateRef.current === 'expanded' && globalThis.document?.visibilityState !== 'hidden' });\n const unread = !expanded && toasts.length > 0;\n const seconds = useElapsed(working);\n\n // Position: offsets from the bottom right corner, remembered for the session, clamped to the viewport at render so a smaller window restores them.\n const [position, setPosition] = useState<Position>(() => readPosition(storageKey, storage) ?? DEFAULT_POSITION);\n const [viewport, setViewport] = useState(viewportSize);\n const [size, setSize] = useState({ w: 0, h: 0 });\n useEffect(() => {\n const onResize = () => setViewport(viewportSize());\n globalThis.addEventListener('resize', onResize);\n return () => globalThis.removeEventListener('resize', onResize);\n }, []);\n useEffect(() => {\n const element = root.current;\n if (!element || typeof ResizeObserver === 'undefined') return;\n const observer = new ResizeObserver(() => setSize({ w: element.offsetWidth, h: element.offsetHeight }));\n observer.observe(element);\n setSize({ w: element.offsetWidth, h: element.offsetHeight });\n return () => observer.disconnect();\n }, [minimized, expanded]);\n // The size and the viewport also follow every render, so the clamp below never works from a stale measurement (the title or status icon can change the pill's width; a scrollbar can appear without a resize event).\n useLayoutEffect(() => {\n const element = root.current;\n const fresh = viewportSize();\n setViewport(current => current.w === fresh.w && current.h === fresh.h ? current : fresh);\n if (element) setSize(current => current.w === element.offsetWidth && current.h === element.offsetHeight ? current : { w: element.offsetWidth, h: element.offsetHeight });\n });\n const placed = clamp(position, size, viewport);\n // Moves and the release are followed on the window, so a drag keeps working when the pointer leaves the handle (and when pointer capture is unavailable).\n // `threshold` is how far the pointer must travel before it is a drag: a click on the pill (threshold > 0) still restores it.\n const dragged = useRef(false);\n const beginDrag = (event: PointerEvent<HTMLElement>, threshold: number) => {\n if (phone || event.button !== 0) return;\n dragged.current = false;\n const origin = { pointer: event.pointerId, x: event.clientX, y: event.clientY, start: placed };\n let last = origin.start, moving = threshold === 0;\n const move = (next: globalThis.PointerEvent) => {\n if (next.pointerId !== origin.pointer) return;\n if (!moving) { if (Math.hypot(next.clientX - origin.x, next.clientY - origin.y) < threshold) return; moving = true; dragged.current = true; }\n last = clamp({ right: origin.start.right - (next.clientX - origin.x), bottom: origin.start.bottom - (next.clientY - origin.y) }, size, viewport);\n setPosition(last);\n };\n const end = (next: globalThis.PointerEvent) => {\n if (next.pointerId !== origin.pointer) return;\n globalThis.removeEventListener('pointermove', move); globalThis.removeEventListener('pointerup', end); globalThis.removeEventListener('pointercancel', end);\n if (moving) writePosition(storageKey, storage, last);\n };\n globalThis.addEventListener('pointermove', move); globalThis.addEventListener('pointerup', end); globalThis.addEventListener('pointercancel', end);\n };\n const onGripDown = (event: PointerEvent<HTMLButtonElement>) => { event.preventDefault(); beginDrag(event, 0); };\n // Arrow keys move the window (Shift for big steps); Home puts it back in the default corner.\n const onGripKey = (event: KeyboardEvent<HTMLElement>) => {\n if (phone) return;\n const step = event.shiftKey ? 64 : 16;\n const delta = event.key === 'ArrowLeft' ? { right: step, bottom: 0 } : event.key === 'ArrowRight' ? { right: -step, bottom: 0 } : event.key === 'ArrowUp' ? { right: 0, bottom: step } : event.key === 'ArrowDown' ? { right: 0, bottom: -step } : undefined;\n if (!delta && event.key !== 'Home') return;\n event.preventDefault();\n const next = delta ? clamp({ right: placed.right + delta.right, bottom: placed.bottom + delta.bottom }, size, viewport) : clamp(DEFAULT_POSITION, size, viewport);\n setPosition(next); writePosition(storageKey, storage, next);\n };\n const grip = (className?: string) => <button type=\"button\" data-testid=\"ambient-grip\" aria-label={labels.move} title={labels.moveHint} onPointerDown={onGripDown} onKeyDown={onGripKey}\n className={cn(iconButton, 'cursor-grab touch-none active:cursor-grabbing', className)}><icons.grip className=\"size-4\" aria-hidden=\"true\" /></button>;\n\n const expand = () => { setOutcome(null); store.dismissConversation(conversationId); setWindowState('expanded'); };\n useEffect(() => {\n if (expanded && !globalThis.matchMedia?.('(pointer: coarse)').matches) textarea.current?.focus();\n }, [expanded, textarea]);\n // The title is disabled while the window is open, so focus goes back to it once the bar is showing again.\n const refocusTitle = useRef(false);\n useEffect(() => { if (!expanded && refocusTitle.current) { refocusTitle.current = false; titleButton.current?.focus(); } }, [expanded]);\n const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {\n if (event.key !== 'Escape' || event.defaultPrevented || !expanded || picking) return;\n event.preventDefault();\n // Escape steps back: full screen, then the artifact, then the window.\n if (fullscreen) return setFullscreen(false);\n if (opened) return setOpened(null);\n refocusTitle.current = true;\n setWindowState('bar');\n };\n const onActivate = useCallback((item: AgentNotification) => {\n if (item.conversationId !== undefined && item.conversationId !== conversationId) conversations?.onSelect(item.conversationId);\n expand();\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [conversationId, conversations]);\n\n const connectionKind = state.connection.kind;\n const status = waitingForAnswer ? 'input' : working ? 'working' : outcome;\n const label = waitingForAnswer ? labels.waitingForAnswer : labels.working(seconds);\n const panelOpen = expanded && shownArtifact !== undefined && artifactPanel !== undefined;\n const surface = cn('relative flex flex-col border border-border bg-background text-foreground shadow-lg', phone && expanded ? 'h-dvh rounded-none border-0 pt-[env(safe-area-inset-top)]' : 'rounded-3xl',\n !phone && expanded && (panelOpen ? 'h-full overflow-hidden' : 'max-h-[70dvh]'));\n // With an artifact open the window widens (most of the viewport, at most 72rem) and takes a fixed height so the panel fills it.\n const rootClass = cn('pi-chat pi-ambient fixed z-50', variant === 'contrast' && 'dark scheme-dark', phone ? (expanded ? 'inset-0' : 'inset-x-2 bottom-[max(0.5rem,env(safe-area-inset-bottom))]')\n : cn('transition-[width] motion-reduce:transition-none', minimized ? 'w-auto' : panelOpen ? 'h-[min(46rem,calc(100dvh-1rem))] w-[min(72rem,calc(100vw-1rem))]' : expanded ? 'w-[min(35rem,calc(100vw-1rem))]' : 'w-[min(26rem,calc(100vw-1rem))]'), className);\n const rootStyle = phone ? undefined : { right: placed.right, bottom: placed.bottom };\n\n if (minimized) return <div ref={root} data-boring=\"ambient-chat\" data-state=\"minimized\" data-variant={variant} className={cn(rootClass, phone && 'flex justify-end')} style={rootStyle} onKeyDown={onKeyDown}>\n {notifications !== false && <AgentNotifications store={store} variant={variant} placement=\"inline\" systemNotifications={systemNotifications} onActivate={onActivate} labels={labels}\n {...(autoDismissMs !== undefined ? { autoDismissMs } : {})} {...(maxToasts !== undefined ? { max: maxToasts } : {})} className=\"absolute right-0 bottom-full mb-3 w-[min(26rem,calc(100vw-1rem))]\" />}\n <div data-testid=\"ambient-pill-box\" onPointerDown={event => beginDrag(event, 4)} onKeyDown={onGripKey} onClickCapture={event => { if (dragged.current) { dragged.current = false; event.stopPropagation(); event.preventDefault(); } }}\n className={cn('relative flex h-11 max-w-[min(20rem,calc(100vw-1rem))] items-center rounded-full border border-border bg-background text-foreground shadow-lg transition-colors hover:bg-popover motion-reduce:transition-none', !phone && 'cursor-grab touch-none select-none active:cursor-grabbing')}>\n {!phone && grip('ml-1.5 size-8 rounded-lg')}\n <button ref={pill} type=\"button\" data-testid=\"ambient-pill\" onClick={() => setWindowState('bar')} aria-label={labels.openAgent(shownTitle, unread)}\n className={cn('relative flex h-full min-w-0 cursor-pointer items-center gap-2.5 rounded-full pr-4 text-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring/70', phone ? 'pl-3.5' : 'pl-1.5')}>\n {status === 'working' ? <Loader2Icon className=\"size-4 shrink-0 animate-spin text-muted-foreground motion-reduce:animate-none\" aria-hidden=\"true\" />\n : status ? <KindIcon kind={status === 'input' ? 'input' : status} className=\"size-4\" /> : null}\n <span className=\"min-w-0 truncate text-sm\">{shownTitle}</span>\n {unread && <span data-testid=\"ambient-unread\" aria-hidden=\"true\" className=\"absolute top-1.5 right-2 size-2.5 rounded-full border-2 border-background bg-primary\" />}\n </button>\n </div>\n </div>;\n\n const visibleRows = transcript.visible(rows);\n return <div ref={root} data-boring=\"ambient-chat\" data-state={windowState} data-variant={variant} data-phone={phone ? 'true' : undefined} role=\"region\" aria-label={labels.region(shownTitle)}\n className={rootClass} style={rootStyle} onKeyDown={onKeyDown}>\n {notifications !== false && !(phone && expanded) && <AgentNotifications store={store} variant={variant} placement=\"inline\" systemNotifications={systemNotifications} onActivate={onActivate} labels={labels}\n {...(autoDismissMs !== undefined ? { autoDismissMs } : {})} {...(maxToasts !== undefined ? { max: maxToasts } : {})} className=\"absolute right-0 bottom-full mb-3 w-full\" />}\n {picking && conversations && <ConversationHistory conversations={conversations} placement={expanded ? 'below' : 'above'} onClose={() => setPicking(false)} />}\n <div data-testid=\"ambient-surface\" className={surface}>\n <ArtifactWorkspace open={panelOpen} onClose={() => { setOpened(null); setFullscreen(false); }} fullscreen={fullscreen} onFullscreenChange={setFullscreen} storageKey=\"boring.ambient.panel-width\" panelLabel={labels.artifactPanel}\n defaultWidth={600} minPanel={320} minChat={300} sheetBelow={720}\n panel={api => shownArtifact && artifactPanel ? artifactPanel(shownArtifact, { ...api, versions: known, follow: opened?.follow ?? true,\n select: version => setOpened(current => current ? (version === 'latest' ? { descriptor: known[0] ?? current.descriptor, follow: true } : { descriptor: version, follow: false }) : current) }) : null}\n chat={<section className=\"flex min-h-0 min-w-0 flex-1 flex-col\">\n <header data-testid=\"ambient-header\" className={cn('flex h-12 shrink-0 items-center gap-0.5 px-2 max-sm:h-14', !expanded && 'border-b border-border')}>\n <button type=\"button\" data-testid=\"ambient-minimize\" aria-label={labels.minimize} title={labels.minimize} onClick={() => { setPicking(false); setWindowState(expanded ? 'bar' : 'minimized'); }} className={iconButton}><icons.minimize className=\"size-4\" aria-hidden=\"true\" /></button>\n <span data-testid=\"ambient-status\" data-status={status ?? 'idle'} role=\"img\" aria-label={status === 'working' ? labels.statusWorking : status === 'input' ? labels.needsInput : status === 'done' ? labels.finished : status === 'error' ? labels.failedRun : undefined}\n aria-hidden={status ? undefined : 'true'} className={cn('flex shrink-0 items-center justify-center', status ? 'mx-1.5 w-5' : 'w-1.5')}>\n {status === 'working' ? <Loader2Icon className=\"size-4 animate-spin text-muted-foreground motion-reduce:animate-none\" aria-hidden=\"true\" /> : status ? <KindIcon kind={status === 'input' ? 'input' : status} className=\"size-[1.125rem]\" /> : null}\n </span>\n {avatar && <span data-testid=\"ambient-avatar\" className=\"flex size-6 shrink-0 items-center justify-center overflow-hidden rounded-full [&>img]:size-full [&>img]:object-cover [&>svg]:size-4\">{avatar}</span>}\n <button ref={titleButton} type=\"button\" data-testid=\"ambient-title\" onClick={expand} disabled={expanded} aria-label={expanded ? shownTitle : labels.openChat(shownTitle)}\n className=\"min-w-0 max-w-full cursor-pointer truncate rounded-md px-1 py-1 text-left font-(family-name:--chat-display) text-sm text-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring/60 disabled:cursor-default max-sm:py-2.5\">{shownTitle}</button>\n {conversations && <button type=\"button\" data-testid=\"ambient-switch\" aria-label={labels.switchConversation} aria-haspopup=\"dialog\" aria-expanded={picking} title={labels.switchConversation} onClick={() => setPicking(open => !open)}\n className={cn(iconButton, 'size-7 max-sm:size-11')}><icons.switchConversation className=\"size-3.5\" aria-hidden=\"true\" /></button>}\n {expanded ? <span className=\"flex-1\" /> : <button type=\"button\" tabIndex={-1} aria-hidden=\"true\" data-testid=\"ambient-header-fill\" onClick={expand} className=\"h-full min-w-2 flex-1 cursor-pointer\" />}\n {systemNotifications && permission === 'default' && <button type=\"button\" data-testid=\"ambient-enable-notifications\" aria-label={labels.enableNotifications} title={labels.enableNotifications}\n onClick={() => { void requestNotifyPermission().then(setPermission); }} className={iconButton}><icons.notify className=\"size-4\" aria-hidden=\"true\" /></button>}\n <BlockActions actions={headerActions} testId=\"ambient-action\" menuLabel={labels.moreActions} className=\"[&_button]:max-sm:size-11 [&_button]:pointer-coarse:size-11\" />\n {onDock && !phone && <button type=\"button\" data-testid=\"ambient-dock\" aria-label={labels.dock} title={labels.dockHint} onClick={() => { setPicking(false); onDock(); }} className={iconButton}><icons.dock className=\"size-4\" aria-hidden=\"true\" /></button>}\n {!phone && grip()}\n </header>\n\n {expanded && <div className=\"flex min-h-0 flex-1 flex-col\">\n {(connectionKind === 'error' || connectionKind === 'closed') && <div className=\"px-4 pb-2\"><Notice tone={connectionKind === 'error' ? 'error' : 'info'} testid=\"connection-notice\">\n <span className=\"flex-1\">{connectionKind === 'error' ? labels.loadFailed : labels.disconnected}</span>\n {!state.disposed && <Button size=\"sm\" variant=\"outline\" onClick={() => act(controller.connect)}><icons.reconnect className=\"size-3.5\" aria-hidden=\"true\" />{labels.reconnect}</Button>}</Notice></div>}\n {derived.pinned.length > 0 && <aside aria-label={labels.requiredActions} className=\"shrink-0 space-y-2 px-4 pb-2\">{derived.pinned.map(card => <div key={card.key}>{card.content}</div>)}</aside>}\n <div className=\"relative flex min-h-0 flex-1 flex-col\">\n <div ref={stick.scrollRef} data-testid=\"transcript-scroll\" className=\"min-h-0 flex-1 overflow-x-hidden overflow-y-auto overscroll-contain\">\n <div ref={stick.contentRef} role=\"log\" aria-label={labels.messages} aria-live=\"polite\" data-testid=\"transcript\" className=\"flex min-h-28 flex-col gap-5 px-4 pt-1 pb-5\">\n {hidden > 0 && <div className=\"flex justify-center\"><Button size=\"sm\" variant=\"outline\" data-testid=\"show-earlier\" className=\"text-muted-foreground\" onClick={transcript.reveal}>{labels.showEarlier}</Button></div>}\n {visibleRows.map(row => <RowView key={row.key} row={row} context={rowContext} />)}\n {loading && <p role=\"status\" data-testid=\"loading\" className=\"m-0 flex items-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 {empty && !loading && <p data-testid=\"ambient-empty\" className=\"m-0 py-6 text-center text-sm text-muted-foreground\">{labels.empty}</p>}\n </div>\n </div>\n {!stick.isAtBottom && <Button variant=\"outline\" size=\"icon\" data-testid=\"jump-latest\" aria-label={labels.jumpToLatest} title={labels.jumpToLatest} onClick={() => { transcript.reset(); void stick.scrollToBottom(); }}\n className=\"absolute bottom-2 left-1/2 -translate-x-1/2 bg-background/95 shadow-md backdrop-blur\"><icons.jumpToLatest className=\"size-4\" aria-hidden=\"true\" /></Button>}\n </div>\n </div>}\n\n <div className={cn('shrink-0', expanded && 'border-t border-border', phone && 'pb-[env(safe-area-inset-bottom)]')}>\n <div className=\"space-y-2 px-3 empty:hidden [&:has(*)]:pt-2\">\n <ChatNotices state={state} error={error} onReconcile={() => act(controller.reconcile)} onRetry={() => act(controller.retrySameRequest)} />\n {!expanded && (connectionKind === 'error' || connectionKind === 'closed') && <Notice tone=\"info\" testid=\"connection-notice\">\n <span className=\"flex-1\">{connectionKind === 'error' ? labels.loadFailedShort : labels.disconnectedShort}</span>\n {!state.disposed && <Button size=\"sm\" variant=\"outline\" onClick={() => act(controller.connect)}>{labels.reconnect}</Button>}</Notice>}\n </div>\n <MessageQueue items={queued} sending={state.outbox} withdraw={actions?.withdraw} actions={queueActions} />\n <Composer {...composer} layout=\"inline\" placeholder={working || waitingForAnswer ? label : labels.placeholder} barStart={barStart} barNote={barNote} barEnd={tools} />\n </div>\n </section>} />\n </div>\n </div>;\n}\n",
|
|
24
|
+
"content": "'use client';\n\nimport { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';\nimport type { KeyboardEvent, PointerEvent, ReactNode } from 'react';\nimport type { EntryRecord } from '@earendil-works/pi-durable';\nimport type { ImageContent, ToolCall, ToolResultMessage } from '@earendil-works/pi-ai';\nimport type { NativeChatController } from '@hachej/boring-ui-kit/native-chat';\nimport { BellIcon, ChevronDownIcon, ExternalLinkIcon, GripVerticalIcon, Loader2Icon, MinusIcon, PanelLeftIcon, ThumbsDownIcon, ThumbsUpIcon } from 'lucide-react';\nimport { Button } from '../button/button';\nimport { BlockActions } from '../button/actions';\nimport type { BlockAction, BlockIcon } from '../button/actions';\nimport { CopyButton } from '../pi-chat/code-block';\nimport { Composer } from '../pi-chat/composer';\nimport type { ComposerFeedback } from '../pi-chat/composer';\nimport type { AttachmentsConfig, ConversationsConfig, EffortConfig, MentionsConfig, ModelConfig, SlashConfig } from '../pi-chat/config';\nimport { notifyPermission, requestNotifyPermission } from './browser-notify';\nimport type { NotifyPermission } from './browser-notify';\nimport { ConversationHistory } from '../pi-chat/history';\nimport type { CommandMentions } from '../pi-chat/markdown';\nimport { RowView } from '../pi-chat/message';\nimport type { RowContext } from '../pi-chat/message';\nimport { ChatNotices, Notice } from '../pi-chat/notice';\nimport { AgentNotifications, KindIcon, createNotificationStore, defaultNotificationLabels, finishNotice, pendingQuestion, useNotifications } from './notifications';\nimport type { AgentNotification, NotificationLabels, NotificationStore } from './notifications';\nimport { ChatTextProvider, defaultChatIcons, defaultChatLabels, useMergedText } from '../pi-chat/labels';\nimport type { ChatIcons, ChatLabels } from '../pi-chat/labels';\nimport { MessageQueue } from '../pi-chat/queue';\nimport { artifactKey, collectArtifacts } from '../pi-chat/artifact';\nimport type { ArtifactDescriptor, ArtifactsConfig } from '../pi-chat/artifact';\nimport type { ChatCard, Mode } from '../pi-chat/rows';\nimport { useChatSession, useTranscript } from '../pi-chat/session';\nimport type { ChatFeatureProps, ChatSession } from '../pi-chat/session';\nimport { ArtifactWorkspace } from '../pi-workspace/workspace';\nimport type { WorkspacePanelApi } from '../pi-workspace/workspace';\nimport { cn } from '../utils/utils';\n\nexport { AgentNotifications, createNotificationStore, defaultNotificationLabels, summaryOf, useNotifications, watchConversation } from './notifications';\nexport type { AgentNotification, AgentNotificationsProps, NewNotification, NotificationKind, NotificationLabels, NotificationStore } from './notifications';\n\nconst elapsedText = (seconds: number) => seconds < 60 ? `${seconds}s` : `${Math.floor(seconds / 60)}m ${String(seconds % 60).padStart(2, '0')}s`;\n\n/** The floating window's own words, over the chat's (`defaultChatLabels`) and the toasts' (`defaultNotificationLabels`). */\nexport const defaultAmbientLabels = {\n ...defaultChatLabels,\n ...defaultNotificationLabels,\n /** Shown while the conversation has no title of its own (the active item of `conversations` provides one). */\n title: 'Agent',\n /** The input's placeholder while idle. */\n placeholder: 'Do anything',\n /** The input's placeholder while the agent works. */\n working: (seconds: number) => `Working for ${elapsedText(seconds)}`,\n region: (title: string) => `Agent: ${title}`,\n openAgent: (title: string, unread: boolean) => `Open agent: ${title}${unread ? ' (new activity)' : ''}`,\n openChat: (title: string) => `Open chat: ${title}`,\n minimize: 'Minimise',\n switchConversation: 'Switch conversation',\n statusWorking: 'Working',\n enableNotifications: 'Notify me when the page is in the background',\n dock: 'Dock chat',\n dockHint: 'Dock chat beside the panel',\n move: 'Move the agent window (arrow keys, Home resets)',\n moveHint: 'Drag to move',\n goodResponse: 'Good response',\n badResponse: 'Bad response',\n openFull: 'Open in full chat',\n empty: 'Ask the agent to do something.',\n loadFailedShort: 'Could not load the conversation.',\n disconnectedShort: 'Disconnected.',\n artifactPanel: 'Artifact panel',\n};\nexport type AmbientLabels = ChatLabels & NotificationLabels & typeof defaultAmbientLabels;\n\n/** The floating window's icons, over the chat's. */\nexport const defaultAmbientIcons = {\n ...defaultChatIcons,\n minimize: MinusIcon as BlockIcon,\n dock: PanelLeftIcon as BlockIcon,\n grip: GripVerticalIcon as BlockIcon,\n switchConversation: ChevronDownIcon as BlockIcon,\n notify: BellIcon as BlockIcon,\n openFull: ExternalLinkIcon as BlockIcon,\n goodResponse: ThumbsUpIcon as BlockIcon,\n badResponse: ThumbsDownIcon as BlockIcon,\n};\nexport type AmbientIcons = ChatIcons & typeof defaultAmbientIcons;\nconst AMBIENT_TEXT = { labels: defaultAmbientLabels as AmbientLabels, icons: defaultAmbientIcons as AmbientIcons };\n\n/** `bar` is the compact bar, `expanded` the same window grown into a chat, `minimized` a small pill. */\nexport type AmbientState = 'bar' | 'expanded' | 'minimized';\n\n/** What the artifact panel inside the window gets besides the full-screen and close controls: the versions of the open artifact and how to switch. */\nexport interface AmbientArtifactPanelApi extends WorkspacePanelApi {\n /** Every known version of the open artifact in this conversation, newest first. */\n readonly versions: readonly ArtifactDescriptor[];\n /** True while the panel follows the newest version; false when one older version is pinned. */\n readonly follow: boolean;\n /** `'latest'` follows the newest version; a descriptor from `versions` pins that one. */\n readonly select: (version: ArtifactDescriptor | 'latest') => void;\n}\n\nexport interface AmbientChatProps extends ChatFeatureProps {\n readonly controller: NativeChatController;\n /**\n * Every word the window shows, over `defaultAmbientLabels` (the chat's labels, the toasts' and its own): `title` while the conversation has\n * none of its own, `placeholder` while idle, `working(seconds)` while the agent works.\n */\n readonly labels?: Partial<AmbientLabels> | undefined;\n /** The window's icons (minimise, dock, grip, …) and the chat's, over `defaultAmbientIcons`. */\n readonly icons?: Partial<AmbientIcons> | undefined;\n /** The agent's avatar before the title in the bar. */\n readonly avatar?: ReactNode;\n /** Host actions in the bar, before Dock: `header` ones as buttons, `menu` ones in a \"…\" menu. Test ids `ambient-action-<id>`, the menu `ambient-action-more`. */\n readonly headerActions?: readonly BlockAction[] | undefined;\n /** `contrast` is a dark window on any page: the root carries `.dark`, so it shows the host's own dark tokens; `surface` follows the host's theme. */\n readonly variant?: 'contrast' | 'surface';\n /** Controlled window state; otherwise `defaultState` starts it and the window keeps it. */\n readonly state?: AmbientState;\n readonly defaultState?: AmbientState;\n readonly onStateChange?: (state: AmbientState) => void;\n /** Where the bar was dragged is remembered under this key. */\n readonly storageKey?: string;\n /** `session` (default) remembers the position for this browser tab's session; `local` keeps it in `localStorage` across sessions. */\n readonly storage?: 'session' | 'local';\n /** Host controls in the composer row, between the effort picker and Send (for example a voice button the host guards itself). Absent: nothing is shown. */\n readonly tools?: ReactNode;\n /** Hand the conversation to a full `PiChat` or `ArtifactWorkspace`. Adds an \"Open in full chat\" action to replies. */\n readonly onOpenFull?: (conversationId: string) => void;\n /** Adds thumbs up and down to replies. `value` is `null` when the person takes the rating back. */\n readonly onFeedback?: (reply: { readonly key: string; readonly text: string }, value: 'up' | 'down' | null) => void;\n /** Toasts for finished, failed and waiting tasks. Pass a store to feed it for background conversations too; `false` turns them off. */\n readonly notifications?: NotificationStore | false;\n readonly autoDismissMs?: number;\n readonly maxToasts?: number;\n /** System notifications while the page is hidden. A bell in the header asks for permission when the person chooses to; nothing is asked on load. */\n readonly systemNotifications?: boolean;\n /**\n * The viewer shown inside the window when an artifact card is opened: the window widens into chat on the left and this panel on the right\n * (`ArtifactWorkspace`: draggable divider, full screen, a full-screen sheet on a phone). Build it from the viewer registry (`ViewerFrame`, ...),\n * wrapped in `ViewerWindowProvider` with `api.fullscreen` / `api.onFullscreenChange` so its bar shows the full screen button.\n */\n readonly artifactPanel?: (artifact: ArtifactDescriptor, api: AmbientArtifactPanelApi) => ReactNode;\n /** `window` (default when `artifactPanel` is given) opens artifacts inside the window; `host` calls `artifacts.open` instead, for hosts that show them in their own viewer. */\n readonly artifactTarget?: 'window' | 'host';\n /** The title's ⌄ opens this list to switch conversations or tasks. */\n readonly conversations?: ConversationsConfig;\n /** Adds a \"Dock chat\" action to the header, for a host that floats this window out of a docked chat (`ArtifactWorkspace` with `floatBelow`). It shares the controller with the docked `PiChat`, so nothing is lost. */\n readonly onDock?: () => void;\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 readonly className?: string;\n}\n\ninterface Position { readonly right: number; readonly bottom: number }\nconst MARGIN = 8, DEFAULT_POSITION: Position = { right: 16, bottom: 16 };\n\nfunction storageFor(persist: 'session' | 'local'): Storage | undefined { try { return persist === 'local' ? globalThis.localStorage : globalThis.sessionStorage; } catch { return undefined; } }\nfunction readPosition(key: string, persist: 'session' | 'local'): Position | undefined {\n try {\n const value: unknown = JSON.parse(storageFor(persist)?.getItem(key) ?? 'null');\n const { right, bottom } = (value ?? {}) as { right?: unknown; bottom?: unknown };\n return typeof right === 'number' && typeof bottom === 'number' && Number.isFinite(right) && Number.isFinite(bottom) ? { right, bottom } : undefined;\n } catch { return undefined; }\n}\nfunction writePosition(key: string, persist: 'session' | 'local', position: Position) {\n try { storageFor(persist)?.setItem(key, JSON.stringify(position)); } catch { /* the position is a convenience */ }\n}\nconst clamp = (position: Position, size: { w: number; h: number }, viewport: { w: number; h: number }): Position => ({\n right: Math.round(Math.min(Math.max(MARGIN, position.right), Math.max(MARGIN, viewport.w - size.w - MARGIN))),\n bottom: Math.round(Math.min(Math.max(MARGIN, position.bottom), Math.max(MARGIN, viewport.h - size.h - MARGIN))),\n});\n\n// The layout viewport that fixed positioning uses (without scrollbars), not the window's outer size.\nconst viewportSize = () => { const root = globalThis.document?.documentElement; return { w: root?.clientWidth || globalThis.innerWidth || 1024, h: root?.clientHeight || globalThis.innerHeight || 768 }; };\nfunction usePhone(): boolean {\n const query = '(max-width: 639px)';\n const [phone, setPhone] = useState(() => globalThis.matchMedia?.(query).matches === true);\n useEffect(() => {\n const list = globalThis.matchMedia?.(query);\n if (!list) return;\n const update = () => setPhone(list.matches);\n update();\n list.addEventListener('change', update);\n return () => list.removeEventListener('change', update);\n }, []);\n return phone;\n}\n\n/** Whole seconds since `active` became true; 0 while inactive. */\nfunction useElapsed(active: boolean): number {\n const [seconds, setSeconds] = useState(0);\n useEffect(() => {\n if (!active) { setSeconds(0); return; }\n const started = Date.now();\n setSeconds(0);\n const timer = setInterval(() => setSeconds(Math.floor((Date.now() - started) / 1000)), 1000);\n return () => clearInterval(timer);\n }, [active]);\n return seconds;\n}\n\n/** Pushes a toast when a run finishes or fails and when a question starts waiting; takes it back when the question is answered or a new run starts. */\nfunction useRunFeed({ enabled, store, conversationId, title, session, suppress, onOutcome, waiting }: {\n readonly enabled: boolean; readonly store: NotificationStore; readonly conversationId: string; readonly title: string; readonly session: ChatSession; readonly waiting: string;\n readonly suppress: () => boolean; readonly onOutcome: (outcome: 'done' | 'error' | null) => void;\n}) {\n const { working, waitingForAnswer, rows, connected } = session;\n const before = useRef({ working, waiting: waitingForAnswer });\n const latest = useRef({ rows, title, suppress, onOutcome, connected, waiting });\n latest.current = { rows, title, suppress, onOutcome, connected, waiting };\n useEffect(() => {\n const was = before.current;\n before.current = { working, waiting: waitingForAnswer };\n const now = latest.current;\n if (working && !was.working) { now.onOutcome(null); store.dismiss(`${conversationId}:done`); }\n if (!enabled) return;\n if (waitingForAnswer && !was.waiting && !now.suppress()) store.push({ id: `${conversationId}:input`, kind: 'input', title: now.title, summary: pendingQuestion(now.rows) ?? now.waiting, conversationId });\n if (!waitingForAnswer && was.waiting) store.dismiss(`${conversationId}:input`);\n if (was.working && !working && now.connected) {\n const finished = finishNotice(now.rows);\n if (!finished) return;\n now.onOutcome(finished.kind);\n if (!now.suppress()) store.push({ id: `${conversationId}:done`, kind: finished.kind, title: now.title, summary: finished.summary, conversationId });\n }\n }, [working, waitingForAnswer, enabled, store, conversationId]);\n}\n\n/** A compact floating agent bar over an existing page; it grows into a chat window in place. Borrows a concrete native controller like `PiChat`. */\nexport function AmbientChat(props: AmbientChatProps) {\n const active = useRef(props.controller); active.current = props.controller;\n const [mount, setMount] = useState({ controller: props.controller, sequence: 0 });\n if (mount.controller !== props.controller) setMount({ controller: props.controller, sequence: mount.sequence + 1 });\n // The window state and the toasts belong to the bar, not to one conversation: they survive switching conversations.\n const [local, setLocal] = useState<AmbientState>(props.defaultState ?? 'bar');\n const internalStore = useMemo(createNotificationStore, []);\n const text = useMergedText<AmbientLabels, AmbientIcons>(props.labels, props.icons, AMBIENT_TEXT);\n return <ChatTextProvider value={text}><AmbientSession key={mount.sequence} {...props} labels={text.labels} icons={text.icons} activeController={active} windowState={props.state ?? local} store={props.notifications || internalStore}\n onWindowState={next => { if (props.state === undefined) setLocal(next); props.onStateChange?.(next); }} /></ChatTextProvider>;\n}\n\nconst iconButton = 'inline-flex size-8 shrink-0 cursor-pointer items-center justify-center rounded-lg text-muted-foreground outline-none transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/60 max-sm:size-11 pointer-coarse:size-11 motion-reduce:transition-none';\n\ntype SessionProps = Omit<AmbientChatProps, 'labels' | 'icons'> & { readonly labels: AmbientLabels; readonly icons: AmbientIcons; readonly activeController: { readonly current: NativeChatController }; readonly windowState: AmbientState; readonly store: NotificationStore; readonly onWindowState: (state: AmbientState) => void };\n\nfunction AmbientSession({ controller, labels, icons, avatar, headerActions, messageActions, variant = 'contrast', mode = 'expert', actions,\n windowState, onWindowState, store, storageKey = 'boring.ambient.position', storage = 'session', tools, onOpenFull, onFeedback, notifications, autoDismissMs, maxToasts, systemNotifications = false,\n renderEntry, renderTool, groupTool, commandMentions, onOpenImage, onCopy, onComposerKeyDown, fileAccept = 'image/*', slash, mentions, attachments, onOpenFile, pasteToFile, model, effort, replyFooter, artifacts: hostArtifacts, artifactPanel, artifactTarget, conversations, onDock, feedback: composerFeedback, className,\n activeController }: SessionProps) {\n const { title } = labels;\n const stateRef = useRef(windowState); stateRef.current = windowState;\n // The artifact open inside the window, and whether it follows the newest version. It belongs to the expanded window: leaving that state closes it.\n const [opened, setOpened] = useState<{ readonly descriptor: ArtifactDescriptor; readonly follow: boolean } | null>(null);\n const [fullscreen, setFullscreen] = useState(false);\n const setWindowState = (next: AmbientState) => {\n if (next !== 'expanded') { setOpened(null); setFullscreen(false); }\n if (next !== stateRef.current) onWindowState(next);\n };\n const expanded = windowState === 'expanded', minimized = windowState === 'minimized';\n const phone = usePhone();\n const root = useRef<HTMLDivElement>(null), titleButton = useRef<HTMLButtonElement>(null), pill = useRef<HTMLButtonElement>(null);\n const [picking, setPicking] = useState(false);\n const [feedback, setFeedback] = useState<Readonly<Record<string, 'up' | 'down'>>>({});\n const [outcome, setOutcome] = useState<'done' | 'error' | null>(null);\n const [permission, setPermission] = useState<NotifyPermission>('unsupported');\n useEffect(() => { setPermission(notifyPermission()); }, []);\n useEffect(() => { if (!outcome) return; const timer = setTimeout(() => setOutcome(null), 8000); return () => clearTimeout(timer); }, [outcome]);\n\n // Replies get copy, optional feedback and the time; the host may hand the conversation to its full chat.\n const conversationRef = useRef('');\n const replyActions = useMemo<NonNullable<RowContext['replyActions']>>(() => (reply, host) => <div data-testid=\"reply-actions\" className=\"mt-2 -ml-2 flex items-center gap-0.5 text-muted-foreground\">\n <CopyButton text={reply.text} label={labels.copyResponse} iconOnly {...(onCopy ? { onCopy } : {})} className=\"size-8 p-0 text-muted-foreground max-sm:size-11\" />\n {onFeedback && <>\n {(['up', 'down'] as const).map(value => <button key={value} type=\"button\" data-testid={`feedback-${value}`} aria-pressed={feedback[reply.key] === value} aria-label={value === 'up' ? labels.goodResponse : labels.badResponse}\n title={value === 'up' ? labels.goodResponse : labels.badResponse}\n onClick={() => { const next = feedback[reply.key] === value ? null : value; setFeedback(current => { const { [reply.key]: _removed, ...rest } = current; return next ? { ...rest, [reply.key]: next } : rest; }); onFeedback({ key: reply.key, text: reply.text }, next); }}\n className={cn(iconButton, 'aria-pressed:text-foreground')}>{value === 'up' ? <icons.goodResponse className=\"size-3.5\" aria-hidden=\"true\" /> : <icons.badResponse className=\"size-3.5\" aria-hidden=\"true\" />}</button>)}\n </>}\n {onOpenFull && <button type=\"button\" data-testid=\"open-full\" aria-label={labels.openFull} title={labels.openFull} onClick={() => onOpenFull(conversationRef.current)} className={iconButton}><icons.openFull className=\"size-3.5\" aria-hidden=\"true\" /></button>}\n {host}\n {reply.timestamp !== undefined && <time dateTime={new Date(reply.timestamp).toISOString()} data-testid=\"reply-time\" className=\"ml-1.5 text-xs tabular-nums\">{new Date(reply.timestamp).toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit' })}</time>}\n </div>, [onCopy, onFeedback, onOpenFull, feedback, labels, icons]);\n const scrollToBottom = useRef<() => void>(() => {});\n const rowExtras = useMemo(() => ({ replyActions }), [replyActions]);\n const inWindow = Boolean(artifactPanel) && artifactTarget !== 'host';\n const detect = hostArtifacts?.detect;\n const versionsRef = useRef<readonly ArtifactDescriptor[]>([]);\n const artifacts = useMemo<ArtifactsConfig | undefined>(() => !inWindow ? hostArtifacts : {\n open: descriptor => { const newest = versionsRef.current.filter(version => artifactKey(version) === artifactKey(descriptor)).reduce((top, version) => Math.max(top, version.ordinal ?? 0), 0); setOpened({ descriptor, follow: (descriptor.ordinal ?? 0) >= newest }); },\n isOpen: descriptor => opened !== null && artifactKey(opened.descriptor) === artifactKey(descriptor) && (opened.follow ? (descriptor.ordinal ?? 0) >= (versionsRef.current.find(version => artifactKey(version) === artifactKey(descriptor))?.ordinal ?? 0) : descriptor.revision === opened.descriptor.revision),\n ...(detect ? { detect } : {}),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [inWindow, hostArtifacts, opened, detect]);\n const session = useChatSession({ controller, activeController, mode, actions, renderEntry, renderTool, groupTool, commandMentions, onOpenImage, onCopy, onComposerKeyDown, fileAccept,\n slash, mentions, attachments, model, effort, artifacts, messageActions, replyFooter, afterSend: () => scrollToBottom.current(), rowExtras, feedback: composerFeedback, onOpenFile, pasteToFile });\n const { state, derived, rows, queued, queueActions, working, waitingForAnswer, error, act, textarea, rowContext, composer, empty, loading } = session;\n const transcript = useTranscript(rows);\n const versions = useMemo(() => inWindow ? collectArtifacts(state.view, detect).sort((a, b) => (b.ordinal ?? 0) - (a.ordinal ?? 0)) : [], [inWindow, state.view, detect]);\n versionsRef.current = versions;\n const known = opened ? versions.filter(version => artifactKey(version) === artifactKey(opened.descriptor)) : [];\n const shownArtifact = opened ? (opened.follow ? known[0] ?? opened.descriptor : opened.descriptor) : undefined;\n const { stick, hidden } = transcript;\n scrollToBottom.current = () => { void stick.scrollToBottom('instant'); };\n const { barStart, barNote } = session.pickers();\n\n const conversationId = String(conversations?.activeId ?? state.conversationId);\n conversationRef.current = conversationId;\n const activeItem = conversations?.items.find(item => item.id === conversations.activeId);\n const shownTitle = activeItem?.title?.trim() || title;\n const toasts = useNotifications(store);\n useRunFeed({ enabled: notifications !== false, store, conversationId, title: shownTitle, session, onOutcome: setOutcome, waiting: labels.waitingForAnswer,\n suppress: () => stateRef.current === 'expanded' && globalThis.document?.visibilityState !== 'hidden' });\n const unread = !expanded && toasts.length > 0;\n const seconds = useElapsed(working);\n\n // Position: offsets from the bottom right corner, remembered for the session, clamped to the viewport at render so a smaller window restores them.\n const [position, setPosition] = useState<Position>(() => readPosition(storageKey, storage) ?? DEFAULT_POSITION);\n const [viewport, setViewport] = useState(viewportSize);\n const [size, setSize] = useState({ w: 0, h: 0 });\n useEffect(() => {\n const onResize = () => setViewport(viewportSize());\n globalThis.addEventListener('resize', onResize);\n return () => globalThis.removeEventListener('resize', onResize);\n }, []);\n useEffect(() => {\n const element = root.current;\n if (!element || typeof ResizeObserver === 'undefined') return;\n const observer = new ResizeObserver(() => setSize({ w: element.offsetWidth, h: element.offsetHeight }));\n observer.observe(element);\n setSize({ w: element.offsetWidth, h: element.offsetHeight });\n return () => observer.disconnect();\n }, [minimized, expanded]);\n // The size and the viewport also follow every render, so the clamp below never works from a stale measurement (the title or status icon can change the pill's width; a scrollbar can appear without a resize event).\n useLayoutEffect(() => {\n const element = root.current;\n const fresh = viewportSize();\n setViewport(current => current.w === fresh.w && current.h === fresh.h ? current : fresh);\n if (element) setSize(current => current.w === element.offsetWidth && current.h === element.offsetHeight ? current : { w: element.offsetWidth, h: element.offsetHeight });\n });\n const placed = clamp(position, size, viewport);\n // Moves and the release are followed on the window, so a drag keeps working when the pointer leaves the handle (and when pointer capture is unavailable).\n // `threshold` is how far the pointer must travel before it is a drag: a click on the pill (threshold > 0) still restores it.\n const dragged = useRef(false);\n const beginDrag = (event: PointerEvent<HTMLElement>, threshold: number) => {\n if (phone || event.button !== 0) return;\n dragged.current = false;\n const origin = { pointer: event.pointerId, x: event.clientX, y: event.clientY, start: placed };\n let last = origin.start, moving = threshold === 0;\n const move = (next: globalThis.PointerEvent) => {\n if (next.pointerId !== origin.pointer) return;\n if (!moving) { if (Math.hypot(next.clientX - origin.x, next.clientY - origin.y) < threshold) return; moving = true; dragged.current = true; }\n last = clamp({ right: origin.start.right - (next.clientX - origin.x), bottom: origin.start.bottom - (next.clientY - origin.y) }, size, viewport);\n setPosition(last);\n };\n const end = (next: globalThis.PointerEvent) => {\n if (next.pointerId !== origin.pointer) return;\n globalThis.removeEventListener('pointermove', move); globalThis.removeEventListener('pointerup', end); globalThis.removeEventListener('pointercancel', end);\n if (moving) writePosition(storageKey, storage, last);\n };\n globalThis.addEventListener('pointermove', move); globalThis.addEventListener('pointerup', end); globalThis.addEventListener('pointercancel', end);\n };\n const onGripDown = (event: PointerEvent<HTMLButtonElement>) => { event.preventDefault(); beginDrag(event, 0); };\n // Arrow keys move the window (Shift for big steps); Home puts it back in the default corner.\n const onGripKey = (event: KeyboardEvent<HTMLElement>) => {\n if (phone) return;\n const step = event.shiftKey ? 64 : 16;\n const delta = event.key === 'ArrowLeft' ? { right: step, bottom: 0 } : event.key === 'ArrowRight' ? { right: -step, bottom: 0 } : event.key === 'ArrowUp' ? { right: 0, bottom: step } : event.key === 'ArrowDown' ? { right: 0, bottom: -step } : undefined;\n if (!delta && event.key !== 'Home') return;\n event.preventDefault();\n const next = delta ? clamp({ right: placed.right + delta.right, bottom: placed.bottom + delta.bottom }, size, viewport) : clamp(DEFAULT_POSITION, size, viewport);\n setPosition(next); writePosition(storageKey, storage, next);\n };\n const grip = (className?: string) => <button type=\"button\" data-testid=\"ambient-grip\" aria-label={labels.move} title={labels.moveHint} onPointerDown={onGripDown} onKeyDown={onGripKey}\n className={cn(iconButton, 'cursor-grab touch-none active:cursor-grabbing', className)}><icons.grip className=\"size-4\" aria-hidden=\"true\" /></button>;\n\n const expand = () => { setOutcome(null); store.dismissConversation(conversationId); setWindowState('expanded'); };\n useEffect(() => {\n if (expanded && !globalThis.matchMedia?.('(pointer: coarse)').matches) textarea.current?.focus();\n }, [expanded, textarea]);\n // The title is disabled while the window is open, so focus goes back to it once the bar is showing again.\n const refocusTitle = useRef(false);\n useEffect(() => { if (!expanded && refocusTitle.current) { refocusTitle.current = false; titleButton.current?.focus(); } }, [expanded]);\n const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {\n if (event.key !== 'Escape' || event.defaultPrevented || !expanded || picking) return;\n event.preventDefault();\n // Escape steps back: full screen, then the artifact, then the window.\n if (fullscreen) return setFullscreen(false);\n if (opened) return setOpened(null);\n refocusTitle.current = true;\n setWindowState('bar');\n };\n const onActivate = useCallback((item: AgentNotification) => {\n if (item.conversationId !== undefined && item.conversationId !== conversationId) conversations?.onSelect(item.conversationId);\n expand();\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [conversationId, conversations]);\n\n const connectionKind = state.connection.kind;\n const status = waitingForAnswer ? 'input' : working ? 'working' : outcome;\n const label = waitingForAnswer ? labels.waitingForAnswer : labels.working(seconds);\n const panelOpen = expanded && shownArtifact !== undefined && artifactPanel !== undefined;\n const surface = cn('relative flex flex-col border border-border bg-background text-foreground shadow-lg', phone && expanded ? 'h-dvh rounded-none border-0 pt-[env(safe-area-inset-top)]' : 'rounded-3xl',\n !phone && expanded && (panelOpen ? 'h-full overflow-hidden' : 'max-h-[70dvh]'));\n // With an artifact open the window widens (most of the viewport, at most 72rem) and takes a fixed height so the panel fills it.\n const rootClass = cn('pi-chat pi-ambient fixed z-50', variant === 'contrast' && 'dark scheme-dark', phone ? (expanded ? 'inset-0' : 'inset-x-2 bottom-[max(0.5rem,env(safe-area-inset-bottom))]')\n : cn('transition-[width] motion-reduce:transition-none', minimized ? 'w-auto' : panelOpen ? 'h-[min(46rem,calc(100dvh-1rem))] w-[min(72rem,calc(100vw-1rem))]' : expanded ? 'w-[min(35rem,calc(100vw-1rem))]' : 'w-[min(26rem,calc(100vw-1rem))]'), className);\n const rootStyle = phone ? undefined : { right: placed.right, bottom: placed.bottom };\n\n if (minimized) return <div ref={root} data-boring=\"ambient-chat\" data-state=\"minimized\" data-variant={variant} className={cn(rootClass, phone && 'flex justify-end')} style={rootStyle} onKeyDown={onKeyDown}>\n {notifications !== false && <AgentNotifications store={store} variant={variant} placement=\"inline\" systemNotifications={systemNotifications} onActivate={onActivate} labels={labels}\n {...(autoDismissMs !== undefined ? { autoDismissMs } : {})} {...(maxToasts !== undefined ? { max: maxToasts } : {})} className=\"absolute right-0 bottom-full mb-3 w-[min(26rem,calc(100vw-1rem))]\" />}\n <div data-testid=\"ambient-pill-box\" onPointerDown={event => beginDrag(event, 4)} onKeyDown={onGripKey} onClickCapture={event => { if (dragged.current) { dragged.current = false; event.stopPropagation(); event.preventDefault(); } }}\n className={cn('relative flex h-11 max-w-[min(20rem,calc(100vw-1rem))] items-center rounded-full border border-border bg-background text-foreground shadow-lg transition-colors hover:bg-popover motion-reduce:transition-none', !phone && 'cursor-grab touch-none select-none active:cursor-grabbing')}>\n {!phone && grip('ml-1.5 size-8 rounded-lg')}\n <button ref={pill} type=\"button\" data-testid=\"ambient-pill\" onClick={() => setWindowState('bar')} aria-label={labels.openAgent(shownTitle, unread)}\n className={cn('relative flex h-full min-w-0 cursor-pointer items-center gap-2.5 rounded-full pr-4 text-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring/70', phone ? 'pl-3.5' : 'pl-1.5')}>\n {status === 'working' ? <Loader2Icon className=\"size-4 shrink-0 animate-spin text-muted-foreground motion-reduce:animate-none\" aria-hidden=\"true\" />\n : status ? <KindIcon kind={status === 'input' ? 'input' : status} className=\"size-4\" /> : null}\n <span className=\"min-w-0 truncate text-sm\">{shownTitle}</span>\n {unread && <span data-testid=\"ambient-unread\" aria-hidden=\"true\" className=\"absolute top-1.5 right-2 size-2.5 rounded-full border-2 border-background bg-primary\" />}\n </button>\n </div>\n </div>;\n\n const visibleRows = transcript.visible(rows);\n return <div ref={root} data-boring=\"ambient-chat\" data-state={windowState} data-variant={variant} data-phone={phone ? 'true' : undefined} role=\"region\" aria-label={labels.region(shownTitle)}\n className={rootClass} style={rootStyle} onKeyDown={onKeyDown}>\n {notifications !== false && !(phone && expanded) && <AgentNotifications store={store} variant={variant} placement=\"inline\" systemNotifications={systemNotifications} onActivate={onActivate} labels={labels}\n {...(autoDismissMs !== undefined ? { autoDismissMs } : {})} {...(maxToasts !== undefined ? { max: maxToasts } : {})} className=\"absolute right-0 bottom-full mb-3 w-full\" />}\n {picking && conversations && <ConversationHistory conversations={conversations} placement={expanded ? 'below' : 'above'} onClose={() => setPicking(false)} />}\n <div data-testid=\"ambient-surface\" className={surface}>\n <ArtifactWorkspace open={panelOpen} onClose={() => { setOpened(null); setFullscreen(false); }} fullscreen={fullscreen} onFullscreenChange={setFullscreen} storageKey=\"boring.ambient.panel-width\" panelLabel={labels.artifactPanel}\n defaultWidth={600} minPanel={320} minChat={300} sheetBelow={720}\n panel={api => shownArtifact && artifactPanel ? artifactPanel(shownArtifact, { ...api, versions: known, follow: opened?.follow ?? true,\n select: version => setOpened(current => current ? (version === 'latest' ? { descriptor: known[0] ?? current.descriptor, follow: true } : { descriptor: version, follow: false }) : current) }) : null}\n chat={<section className=\"flex min-h-0 min-w-0 flex-1 flex-col\">\n <header data-testid=\"ambient-header\" className={cn('flex h-12 shrink-0 items-center gap-0.5 px-2 max-sm:h-14', !expanded && 'border-b border-border')}>\n <button type=\"button\" data-testid=\"ambient-minimize\" aria-label={labels.minimize} title={labels.minimize} onClick={() => { setPicking(false); setWindowState(expanded ? 'bar' : 'minimized'); }} className={iconButton}><icons.minimize className=\"size-4\" aria-hidden=\"true\" /></button>\n <span data-testid=\"ambient-status\" data-status={status ?? 'idle'} role=\"img\" aria-label={status === 'working' ? labels.statusWorking : status === 'input' ? labels.needsInput : status === 'done' ? labels.finished : status === 'error' ? labels.failedRun : undefined}\n aria-hidden={status ? undefined : 'true'} className={cn('flex shrink-0 items-center justify-center', status ? 'mx-1.5 w-5' : 'w-1.5')}>\n {status === 'working' ? <Loader2Icon className=\"size-4 animate-spin text-muted-foreground motion-reduce:animate-none\" aria-hidden=\"true\" /> : status ? <KindIcon kind={status === 'input' ? 'input' : status} className=\"size-[1.125rem]\" /> : null}\n </span>\n {avatar && <span data-testid=\"ambient-avatar\" className=\"flex size-6 shrink-0 items-center justify-center overflow-hidden rounded-full [&>img]:size-full [&>img]:object-cover [&>svg]:size-4\">{avatar}</span>}\n <button ref={titleButton} type=\"button\" data-testid=\"ambient-title\" onClick={expand} disabled={expanded} aria-label={expanded ? shownTitle : labels.openChat(shownTitle)}\n className=\"min-w-0 max-w-full cursor-pointer truncate rounded-md px-1 py-1 text-left font-(family-name:--chat-display) text-sm text-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring/60 disabled:cursor-default max-sm:py-2.5\">{shownTitle}</button>\n {conversations && <button type=\"button\" data-testid=\"ambient-switch\" aria-label={labels.switchConversation} aria-haspopup=\"dialog\" aria-expanded={picking} title={labels.switchConversation} onClick={() => setPicking(open => !open)}\n className={cn(iconButton, 'size-7 max-sm:size-11')}><icons.switchConversation className=\"size-3.5\" aria-hidden=\"true\" /></button>}\n {expanded ? <span className=\"flex-1\" /> : <button type=\"button\" tabIndex={-1} aria-hidden=\"true\" data-testid=\"ambient-header-fill\" onClick={expand} className=\"h-full min-w-2 flex-1 cursor-pointer\" />}\n {systemNotifications && permission === 'default' && <button type=\"button\" data-testid=\"ambient-enable-notifications\" aria-label={labels.enableNotifications} title={labels.enableNotifications}\n onClick={() => { void requestNotifyPermission().then(setPermission); }} className={iconButton}><icons.notify className=\"size-4\" aria-hidden=\"true\" /></button>}\n <BlockActions actions={headerActions} testId=\"ambient-action\" menuLabel={labels.moreActions} className=\"[&_button]:max-sm:size-11 [&_button]:pointer-coarse:size-11\" />\n {onDock && !phone && <button type=\"button\" data-testid=\"ambient-dock\" aria-label={labels.dock} title={labels.dockHint} onClick={() => { setPicking(false); onDock(); }} className={iconButton}><icons.dock className=\"size-4\" aria-hidden=\"true\" /></button>}\n {!phone && grip()}\n </header>\n\n {expanded && <div className=\"flex min-h-0 flex-1 flex-col\">\n {(connectionKind === 'error' || connectionKind === 'closed') && <div className=\"px-4 pb-2\"><Notice tone={connectionKind === 'error' ? 'error' : 'info'} testid=\"connection-notice\">\n <span className=\"flex-1\">{connectionKind === 'error' ? labels.loadFailed : labels.disconnected}</span>\n {!state.disposed && <Button size=\"sm\" variant=\"outline\" onClick={() => act(controller.connect)}><icons.reconnect className=\"size-3.5\" aria-hidden=\"true\" />{labels.reconnect}</Button>}</Notice></div>}\n {derived.pinned.length > 0 && <aside aria-label={labels.requiredActions} className=\"shrink-0 space-y-2 px-4 pb-2\">{derived.pinned.map(card => <div key={card.key}>{card.content}</div>)}</aside>}\n <div className=\"relative flex min-h-0 flex-1 flex-col\">\n <div ref={stick.scrollRef} data-testid=\"transcript-scroll\" className=\"min-h-0 flex-1 overflow-x-hidden overflow-y-auto overscroll-contain\">\n <div ref={stick.contentRef} role=\"log\" aria-label={labels.messages} aria-live=\"polite\" data-testid=\"transcript\" className=\"flex min-h-28 flex-col gap-5 px-4 pt-1 pb-5\">\n {hidden > 0 && <div className=\"flex justify-center\"><Button size=\"sm\" variant=\"outline\" data-testid=\"show-earlier\" className=\"text-muted-foreground\" onClick={transcript.reveal}>{labels.showEarlier}</Button></div>}\n {visibleRows.map(row => <RowView key={row.key} row={row} context={rowContext} />)}\n {loading && <p role=\"status\" data-testid=\"loading\" className=\"m-0 flex items-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 {empty && !loading && <p data-testid=\"ambient-empty\" className=\"m-0 py-6 text-center text-sm text-muted-foreground\">{labels.empty}</p>}\n </div>\n </div>\n {!stick.isAtBottom && <Button variant=\"outline\" size=\"icon\" data-testid=\"jump-latest\" aria-label={labels.jumpToLatest} title={labels.jumpToLatest} onClick={() => { transcript.reset(); void stick.scrollToBottom(); }}\n className=\"absolute bottom-2 left-1/2 -translate-x-1/2 bg-background/95 shadow-md backdrop-blur\"><icons.jumpToLatest className=\"size-4\" aria-hidden=\"true\" /></Button>}\n </div>\n </div>}\n\n <div className={cn('shrink-0', expanded && 'border-t border-border', phone && 'pb-[env(safe-area-inset-bottom)]')}>\n <div className=\"space-y-2 px-3 empty:hidden [&:has(*)]:pt-2\">\n <ChatNotices state={state} error={error} onReconcile={() => act(controller.reconcile)} onRetry={() => act(controller.retrySameRequest)} />\n {!expanded && (connectionKind === 'error' || connectionKind === 'closed') && <Notice tone=\"info\" testid=\"connection-notice\">\n <span className=\"flex-1\">{connectionKind === 'error' ? labels.loadFailedShort : labels.disconnectedShort}</span>\n {!state.disposed && <Button size=\"sm\" variant=\"outline\" onClick={() => act(controller.connect)}>{labels.reconnect}</Button>}</Notice>}\n </div>\n <MessageQueue items={queued} sending={state.outbox} withdraw={actions?.withdraw} actions={queueActions} />\n <Composer {...composer} layout=\"inline\" placeholder={working || waitingForAnswer ? label : labels.placeholder} barStart={barStart} barNote={barNote} barEnd={tools} />\n </div>\n </section>} />\n </div>\n </div>;\n}\n",
|
|
25
25
|
"type": "registry:component",
|
|
26
26
|
"target": "components/pi-ambient/ambient.tsx"
|
|
27
27
|
},
|
package/r/pi-app.json
CHANGED
|
@@ -4,25 +4,25 @@
|
|
|
4
4
|
"title": "Pi agent app",
|
|
5
5
|
"description": "AgentWorkspace: a whole agent page in one component. Left: the sessions pane (search, New, rename, archive, delete; collapsible, a drawer on a narrow screen). Center: PiChat. Right: the artifact viewers (artifact panel with versions, file viewer, auto-open of new artifacts) in the ArtifactWorkspace panel, a full-screen sheet on a phone. Props are data and callbacks; hooks for the conversations handler (useConversations), the chat transport (useRemoteChat) and saved resources (useSaved).",
|
|
6
6
|
"dependencies": [
|
|
7
|
-
"@hachej/boring-ui-kit@^0.3.
|
|
8
|
-
"@hachej/boring-files@^0.3.
|
|
7
|
+
"@hachej/boring-ui-kit@^0.3.2",
|
|
8
|
+
"@hachej/boring-files@^0.3.2",
|
|
9
9
|
"react@^19.0.0",
|
|
10
10
|
"react-dom@^19.0.0",
|
|
11
11
|
"lucide-react@^1.51.0",
|
|
12
12
|
"radix-ui@^1.8.0"
|
|
13
13
|
],
|
|
14
14
|
"registryDependencies": [
|
|
15
|
-
"https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.3.
|
|
16
|
-
"https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.3.
|
|
17
|
-
"https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.3.
|
|
18
|
-
"https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.3.
|
|
19
|
-
"https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.3.
|
|
20
|
-
"https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.3.
|
|
15
|
+
"https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.3.2/r/theme.json",
|
|
16
|
+
"https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.3.2/r/pi-chat.json",
|
|
17
|
+
"https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.3.2/r/pi-workspace.json",
|
|
18
|
+
"https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.3.2/r/viewers.json",
|
|
19
|
+
"https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.3.2/r/utils.json",
|
|
20
|
+
"https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.3.2/r/button.json"
|
|
21
21
|
],
|
|
22
22
|
"files": [
|
|
23
23
|
{
|
|
24
24
|
"path": "registry/pi-app/agent-workspace.tsx",
|
|
25
|
-
"content": "'use client';\n\nimport '@hachej/boring-ui-kit/file-tree.css';\n\nimport { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';\nimport type { ReactNode } from 'react';\nimport type { ResourceLocator } from '@hachej/boring-files';\nimport { createResourceClient } from '@hachej/boring-files/remote';\nimport { workspacePath } from '@hachej/boring-files/file-types';\nimport type { FileEntry, RevisionProvider } from '@hachej/boring-files/revision';\nimport { createFileTreeController } from '@hachej/boring-ui-kit/file-tree';\nimport { randomUUID } from '@hachej/boring-files/platform';\nimport type { FileTreeController } from '@hachej/boring-ui-kit/file-tree';\nimport { FileTreeView } from '@hachej/boring-ui-kit/file-tree-view';\nimport { frenchAppLabels } from './app-labels-fr';\nimport { chatTextFor } from '../pi-chat/locale';\nimport type { ChatLocale } from '../pi-chat/locale';\nimport type { FileTreeViewProps } from '@hachej/boring-ui-kit/file-tree-view';\nimport type { ResourceIdentity } from '@hachej/boring-files/remote';\nimport type { NativeChatController } from '@hachej/boring-ui-kit/native-chat';\nimport { PiChat, artifactKey } from '../pi-chat/pi-chat';\nimport { createPresentAcks, pendingPresents } from '../pi-chat/artifact';\nimport type { PresentAcks } from '../pi-chat/artifact';\nimport type { ArtifactDescriptor, ArtifactsConfig, ConversationsConfig, PiChatProps } from '../pi-chat/pi-chat';\nimport { Dock, DockLayout, DockMain } from '../pi-workspace/dock';\nimport { ArtifactWorkspace } from '../pi-workspace/workspace';\nimport type { WorkspacePanelApi } from '../pi-workspace/workspace';\nimport { ViewerWindowProvider } from '../viewers/viewer-frame';\nimport type { ViewerShare } from '../viewers/viewer-frame';\nimport type { InteractiveHtml } from '../viewers/interactive-html';\nimport { Button } from '../button/button';\nimport type { BlockAction } from '../button/actions';\nimport { ChatTextProvider, useMergedText } from '../pi-chat/labels';\nimport { cn, withDefaults } from '../utils/utils';\nimport { AppTextProvider, defaultAppIcons, defaultAppLabels } from './app-labels';\nimport type { AppIcons, AppLabels } from './app-labels';\nimport { ArtifactPanel, useArtifactVersions, useTurn } from './artifact-panel';\nimport type { CustomViewers, SavedRevision, ViewerOptions } from './artifact-panel';\nimport { FileViewer } from './file-viewer';\nimport { useRevisionAttachments } from './use-revision-attachments';\nimport { SessionsPane, SessionsToggle } from './sessions';\nimport type { SessionsView, WorkspaceAgents } from './sessions';\n\nexport { ArtifactPanel, useArtifactVersions, useTurn } from './artifact-panel';\nexport type { CustomViewerProps, CustomViewers, SavedRevision, ViewerOptions } from './artifact-panel';\nexport { FileViewer } from './file-viewer';\nexport { SessionsPane, SessionsToggle } from './sessions';\nexport type { SessionsView, WorkspaceAgent, WorkspaceAgents } from './sessions';\nexport { useConversations } from './use-conversations';\nexport { useRemoteChat } from '../pi-chat/use-remote-chat';\nexport type { RemoteChatState } from '../pi-chat/use-remote-chat';\nexport { savedLabel, useSaved } from './use-saved';\nexport { viewerKindOf as kindOf, mediaTypeOf } from '@hachej/boring-files/file-types';\nexport { defaultAppIcons, defaultAppLabels } from './app-labels';\nexport { frenchAppLabels } from './app-labels-fr';\nexport type { AppIcons, AppLabels } from './app-labels';\nexport type { ViewerKind as FileKind } from '@hachej/boring-files/file-types';\n\n/** An artifact version in the panel: `follow` shows the latest saved revision, otherwise `descriptor.revision` is pinned and read-only. */\nexport interface ArtifactView { readonly kind: 'artifact'; readonly conversation: string; readonly descriptor: ArtifactDescriptor; readonly follow: boolean }\n/** A file in the panel, by the host's path (see `resources.locate`). */\nexport interface FileView { readonly kind: 'file'; readonly path: string }\n/** Anything else the host renders in the panel through `panels[kind]` (for example a file list or a tool view). */\nexport interface HostView { readonly kind: string; readonly [field: string]: unknown }\n/** What the right-hand panel shows, or `null` when it is closed. */\nexport type OpenedView = ArtifactView | FileView | HostView;\n\nconst isArtifact = (view: OpenedView | null): view is ArtifactView => view?.kind === 'artifact';\nconst isFile = (view: OpenedView | null): view is FileView => view?.kind === 'file';\n/** Whether the panel shows the file at `path` (a file view, or the artifact view of it). */\nconst showsPath = (view: OpenedView | null, path: string): boolean => isFile(view) ? view.path === path : isArtifact(view) ? view.descriptor.target.resource.path === path : false;\nconst subscribeNothing = () => () => {};\n\n/** Where the viewers read and write: the host's resource handler (`createResourceHandler` of `@hachej/boring-files/remote`) and its file history. */\nexport interface WorkspaceResources {\n /** The resource handler endpoint. */\n readonly endpoint: string | URL;\n /** The host's authenticated fetch, also used for `history`. */\n readonly fetch: (request: Request) => Promise<Response>;\n /** The person's identity as the resource handler authenticates it (comparison metadata, never a grant). */\n readonly identity: ResourceIdentity;\n /** Optional `GET <history>?path=<resource path>` returning `{ saves: [{ revision, savedAt }] }` newest first (`files.saves(path)`): the version menu. */\n readonly history?: string | URL | undefined;\n /** The resource of a file path in a `FileView`. Default: the published `workspace` provider at the path without a leading slash. */\n readonly locate?: ((path: string) => ResourceLocator) | undefined;\n}\n\ninterface AgentWorkspaceBaseProps {\n /**\n * Where the Library of a `revisionProvider` opens. `side` (default): a column to the right of the viewer (a `Dock`, resizable), opened\n * from the Library button in the viewer's top bar or in the left pane, alone at the right edge when no file is open; on a phone a\n * full-screen sheet that choosing a file closes. `center`: Chat and Library links in the left pane, the Library replacing\n * the chat in the center (the chat stays mounted). `pane`: the Library is a tab beside the conversations in the left pane, or the\n * whole pane on a single-session page without `conversations`; files open in the right panel as usual.\n */\n readonly libraryPlacement?: 'side' | 'center' | 'pane' | undefined;\n /** The page's language: `en` (default) or `fr`, for the chat, the panes, the viewers and the Library. `labels` and `chat.labels` override any word. */\n readonly locale?: ChatLocale | undefined;\n /**\n * The Library tree's options: its words (`labels`, over `defaultFileTreeLabels`), whether it offers Upload and History, and a\n * `refreshKey` that reloads it when it changes. Deprecated: with a `revisionProvider` that has a change feed (`connectRevisionProvider`)\n * the tree, the Library, the history panel and the @ search reload from the workspace's own change events; `refreshKey` remains\n * for a provider without one.\n */\n readonly fileTree?: Pick<FileTreeViewProps, 'labels' | 'upload' | 'history' | 'refreshKey'> | undefined;\n /**\n * How the chat's attachments are saved under `uploads/` (they exist only with a Library, `revisionProvider` or `resources`). Every file\n * is reference-only by default: the message carries its `@path` and the agent reads it with its file tools. See `WorkspaceUploads`.\n */\n readonly uploads?: WorkspaceUploads | undefined;\n /**\n * The page's agents. With two or more, a switcher at the top of the left pane chooses one; the host scopes `conversations` and the\n * controller to `activeId`. One agent (or none given) shows no switcher.\n */\n readonly agents?: WorkspaceAgents | undefined;\n /** The open conversation's controller (`useRemoteChat`); `undefined` while connecting, when `connecting` is shown instead. */\n readonly controller: NativeChatController | undefined;\n /** The open conversation: auto-opened artifacts and the artifact view belong to it. */\n readonly conversationId: string | undefined;\n /** Everything else `PiChat` takes (labels, icons, headerActions, messageActions, mode, actions, slash, mentions, attachments, model, effort, emptyState, ...). */\n readonly chat?: Omit<PiChatProps, 'controller' | 'artifacts' | 'conversations' | 'historyList'>;\n /**\n * The block's words (sessions pane, artifact panel, file viewer and the viewers' bars), over `defaultAppLabels`; for example\n * `{ sessionsTitle: 'Projects', newChat: 'Start' }`. The chat's own go in `chat.labels`.\n */\n readonly labels?: Partial<AppLabels> | undefined;\n /** The block's icons (sessions toggle, New, Float chat, the viewer bar's), over `defaultAppIcons`. The chat's go in `chat.icons`. */\n readonly icons?: Partial<AppIcons> | undefined;\n /**\n * Host actions on the artifact panel's bar (every viewer it shows), after the built-in Float chat: `header` ones as buttons beside Share,\n * `menu` ones in its \"…\" menu. A function receives what is open. Test ids `<viewer testId>-<id>` (`artifact-<id>` for an artifact).\n */\n readonly panelActions?: readonly BlockAction[] | ((view: OpenedView) => readonly BlockAction[]) | undefined;\n readonly connecting?: ReactNode;\n /** The sessions pane (`useConversations`). Omit it for a page without one. Replies keep their Fork button through `conversations.fork`. */\n readonly conversations?: ConversationsConfig | undefined;\n /** Recognise artifacts in tool results that carry no descriptor (`ArtifactsConfig.detect`). */\n readonly detect?: ArtifactsConfig['detect'] | undefined;\n /** Host viewers by artifact type or file kind, for example `{ canvas: props => <MyCanvas {...props} /> }`. */\n readonly viewers?: CustomViewers | undefined;\n /** Run HTML pages in the viewers' sandboxed preview, loading scripts only from these origins. Off without it. */\n readonly interactive?: InteractiveHtml | undefined;\n /** The viewer bar's Share action; it receives `target` `{ artifact, version }` or `{ file }`. */\n readonly share?: ViewerShare | undefined;\n /** Controlled panel content (with `onOpenedChange`); uncontrolled from `defaultOpened` otherwise. */\n readonly opened?: OpenedView | null | undefined;\n readonly defaultOpened?: OpenedView | null | undefined;\n readonly onOpenedChange?: ((next: OpenedView | null) => void) | undefined;\n /**\n * Whether the open file has unsaved or unconfirmed changes. The workspace asks before leaving such a file itself; a host that\n * switches the workspace or identity (a new `revisionProvider`) or changes a controlled `opened` should ask first too, since the\n * viewer of the previous file is replaced and its local draft discarded.\n */\n readonly onUnsavedChange?: ((unsaved: boolean) => void) | undefined;\n /** Renderers for host views, by `kind`. */\n readonly panels?: Readonly<Record<string, (view: HostView, panel: WorkspacePanelApi) => ReactNode>> | undefined;\n /** Open the panel on each artifact (or new version) the agent makes, unless the person closed it during this turn. Not on a phone. Default true. */\n readonly autoOpen?: boolean;\n /** A back button in a file's viewer bar (for example to the host's file list). */\n readonly fileBack?: { readonly label: string; readonly onBack: () => void } | undefined;\n /** With `floatBelow`: the floating chat over the same session (for example `AmbientChat` of `pi-ambient` with `onDock={dock}`). */\n readonly floatingChat?: ((props: PiChatProps, dock: () => void) => ReactNode) | undefined;\n /** Shown above the chat (notices). */\n readonly chatTop?: ReactNode;\n /** The chat header's controls; a function receives whether the panel is open. */\n readonly controls?: ReactNode | ((state: { readonly panelOpen: boolean }) => ReactNode);\n /** Prefix of the session-scoped layout keys (panel width, floating chat, collapsed sessions). */\n readonly storageKey?: string;\n /** Below this width of the workspace the artifact panel is a full-screen sheet. */\n readonly sheetBelow?: number;\n /** Below this width of the workspace the sessions pane is a drawer. */\n readonly drawerBelow?: number;\n readonly floatBelow?: number | undefined;\n readonly className?: string;\n}\n\n/** The chat's attachment rules. `inlineImages` (default false) also sends a png, jpeg, gif or webp as a native image in the message: every later turn then carries its base64, so it is off by default. `maxBytes` refuses a larger file before it is uploaded (no limit by default), and the chat shows why. `accept` is the file picker's `accept` (any file by default). */\nexport interface WorkspaceUploads {\n readonly inlineImages?: boolean | undefined;\n readonly maxBytes?: number | undefined;\n readonly accept?: string | undefined;\n}\n\n/** A byte count for a refusal message: `2.5 MB`, `300 KB`, or `12 bytes`. */\nconst sizeLabel = (bytes: number) => bytes >= 1_000_000 ? `${Number((bytes / 1_000_000).toFixed(1))} MB` : bytes >= 1_000 ? `${Math.round(bytes / 1_000)} KB` : `${bytes} bytes`;\n\nexport type AgentWorkspaceProps = AgentWorkspaceBaseProps & (\n | { readonly revisionProvider: RevisionProvider; readonly resources?: never }\n | { readonly resources: WorkspaceResources; readonly revisionProvider?: never }\n);\n\n// The Library column is docked only while the chat and the viewer (their `ArtifactWorkspace` minimums) keep their room beside it; otherwise it is Dock's sheet.\nconst SESSIONS_WIDTH = 288, LIBRARY_WIDTH = 320, CHAT_MIN = 340, VIEWER_MIN = 360;\nconst readFlag = (key: string): boolean => { try { return sessionStorage.getItem(key) === '1'; } catch { return false; } };\nconst writeFlag = (key: string, on: boolean) => { try { if (on) sessionStorage.setItem(key, '1'); else sessionStorage.removeItem(key); } catch { /* the layout is a convenience */ } };\nconst defaultLocate = (path: string): ResourceLocator => ({ resource: { providerId: 'workspace', path: workspacePath(path) }, view: { kind: 'published' } });\n\n/**\n * A complete agent page in one component: the sessions pane on the left (search, New, rename, archive, delete; collapsible, a drawer on\n * a narrow screen), the chat in the center (`PiChat`) and the artifact viewers on the right (`ArtifactWorkspace` with the artifact panel and\n * its versions, the file viewer and the host's own views). Agent artifacts open the panel as they appear. Every prop is data or a callback:\n * the host owns the routes, authentication, the controller and what is open (when controlled).\n */\nexport function AgentWorkspace({ controller, conversationId, chat = {}, labels, icons, panelActions, connecting, conversations, resources, revisionProvider, libraryPlacement = 'side', locale, fileTree: treeOptions, uploads, agents, detect, viewers, interactive, share, opened: controlled,\n defaultOpened = null, onOpenedChange, onUnsavedChange, panels, autoOpen = true, fileBack, floatingChat, chatTop, controls, storageKey = 'boring.agent-workspace', sheetBelow = 768, drawerBelow = 768, floatBelow, className }: AgentWorkspaceProps) {\n const [own, setOwn] = useState<OpenedView | null>(defaultOpened);\n const opened = controlled !== undefined ? controlled : own;\n const change = useRef(onOpenedChange); change.current = onOpenedChange;\n const isControlled = controlled !== undefined;\n const unsaved = useRef(false);\n const currentView = useRef(opened); currentView.current = opened;\n const unsavedChange = useRef(onUnsavedChange); unsavedChange.current = onUnsavedChange;\n const noteUnsaved = useCallback((value: boolean) => { if (unsaved.current !== value) { unsaved.current = value; unsavedChange.current?.(value); } }, []);\n /** Opens `next` and reports whether it did: leaving a file with unsaved changes asks first, and the person may stay. */\n const setOpened = useCallback((next: OpenedView | null): boolean => {\n const current = currentView.current;\n if (isFile(current) && isFile(next) && current.path === next.path) return true;\n if (unsaved.current && !globalThis.confirm?.('This file has unsaved or unconfirmed changes. Discard the local draft and leave this file?')) return false;\n noteUnsaved(false);\n if (!isControlled) setOwn(next); change.current?.(next);\n return true;\n }, [isControlled, noteUnsaved]);\n const [fullscreen, setFullscreen] = useState(false);\n const [centerMode, setCenterMode] = useState<'chat' | 'library'>('chat');\n const libraryInPane = Boolean(revisionProvider) && libraryPlacement === 'pane';\n const librarySide = Boolean(revisionProvider) && libraryPlacement === 'side';\n const [sideOpen, setSideOpenState] = useState(false);\n // The Library's real docked width, reported by its Dock: the room it needs beside the chat and the viewer.\n const [libraryWidth, setLibraryWidth] = useState(LIBRARY_WIDTH);\n // Opening the column leaves a full-screen viewer, whose overlay would otherwise cover it.\n const setSideOpen = useCallback((next: boolean) => { setSideOpenState(next); if (next) setFullscreen(false); }, []);\n const libraryOpen = Boolean(revisionProvider) && libraryPlacement === 'center' && centerMode === 'library';\n const openLibrary = useCallback(() => { setCenterMode('library'); setFullscreen(false); }, []);\n const text = useMemo(() => ({ labels: withDefaults(locale === 'fr' ? frenchAppLabels : defaultAppLabels, labels), icons: withDefaults(defaultAppIcons, icons) }), [labels, icons, locale]);\n // The sessions pane shows the chat's conversation list, so it reads the chat's labels too.\n const chatText = useMergedText(chat.labels, chat.icons, chatTextFor(locale));\n\n const fetcher = useRef(resources?.fetch); fetcher.current = resources?.fetch;\n const endpoint = resources ? String(resources.endpoint) : undefined;\n const historyEndpoint = resources?.history === undefined ? undefined : String(resources.history);\n const identity = revisionProvider?.identity ?? resources!.identity;\n const identityKey = JSON.stringify(identity);\n const client = useMemo(() => revisionProvider ?? createResourceClient({ identity, endpoint: new URL(endpoint!, globalThis.location?.href), publication: true, reconciliation: true,\n fetch: request => fetcher.current!(request) }), [revisionProvider, endpoint, identityKey]); // eslint-disable-line react-hooks/exhaustive-deps\n const history = useMemo(() => revisionProvider ? revisionProvider.history : historyEndpoint === undefined ? undefined : async (path: string): Promise<readonly SavedRevision[]> => {\n const url = new URL(historyEndpoint, globalThis.location?.href);\n url.searchParams.set('path', path);\n const response = await fetcher.current!(new Request(url));\n if (!response.ok) throw new Error(`History: ${response.status}`);\n return (await response.json() as { saves: readonly SavedRevision[] }).saves;\n }, [revisionProvider, historyEndpoint]);\n // ---- Presented files: the page confirms a `present` call only once its panel has mounted the revision (`onShown`, from the viewers).\n // The bookkeeping is `createPresentAcks` (pi-chat/artifact.ts); the answer goes through the chat's own `answer` (the transport's\n // `?op=answer`) and the server checks the path and revision.\n const answerPresent = useRef(chat.actions?.answer); answerPresent.current = chat.actions?.answer;\n const openForPresent = useRef<(path: string) => boolean>(() => false);\n const presentAcks = useRef<PresentAcks | undefined>(undefined);\n if (!presentAcks.current) presentAcks.current = createPresentAcks({ answer: (id, body) => answerPresent.current?.(id, body),\n open: path => openForPresent.current(path), instanceId: randomUUID() });\n const onShown = useCallback((view: { readonly path: string; readonly revision: string; readonly hidden?: true }) => {\n if (view.hidden) presentAcks.current?.hidden(view); else presentAcks.current?.shown(view);\n }, []);\n const options: ViewerOptions = useMemo(() => ({ client, identity, history, viewers, interactive, share, onShown }), [client, identityKey, history, viewers, interactive, share, onShown]); // eslint-disable-line react-hooks/exhaustive-deps\n const locate = revisionProvider?.locate ?? resources?.locate ?? defaultLocate;\n const [fileBinding, setFileBinding] = useState<{ readonly provider: RevisionProvider; readonly tree: FileTreeController }>();\n useEffect(() => {\n if (!revisionProvider) return;\n const tree = createFileTreeController({ revisionProvider });\n setFileBinding({ provider: revisionProvider, tree });\n void tree.refresh();\n return () => tree.dispose();\n }, [revisionProvider]);\n const fileTree = fileBinding?.provider === revisionProvider ? fileBinding?.tree : undefined;\n // The workspace's change feed: every file view below reloads when its seq moves (agent writes, saves, shell changes).\n const feed = useChangeFeed(revisionProvider);\n // The shared tree controller reloads, shown or not: the Library may be on its other tab when a file arrives, and mounting the tree\n // later must not show the listing from before. `fileTree.refreshKey` (deprecated) does the same for a provider without a feed.\n const { refreshKey, ...viewOptions } = treeOptions ?? {};\n const refreshedKey = useRef(refreshKey);\n const refreshedSeq = useRef(feed.seq);\n useEffect(() => {\n if (!fileTree || (Object.is(refreshedKey.current, refreshKey) && refreshedSeq.current === feed.seq)) return;\n refreshedKey.current = refreshKey;\n refreshedSeq.current = feed.seq;\n const { query, expanded } = fileTree.getSnapshot();\n if (query) void fileTree.search(query);\n else for (const directory of ['', ...expanded]) void fileTree.refresh(directory);\n }, [fileTree, refreshKey, feed.seq]);\n const openFile = useCallback((path: string) => { setOpened({ kind: 'file', path }); }, [setOpened]);\n // @ search: results are reused while the feed reports nothing new (typing back and forth), and dropped at the next change event.\n // One cache per provider instance (one workspace binding), so another binding never sees these results.\n const mentionResults = useMemo(() => ({ seq: undefined as number | undefined, results: new Map<string, readonly FileEntry[]>() }), [revisionProvider]);\n const feedState = useRef(feed); feedState.current = feed;\n const mentions = useMemo(() => revisionProvider ? {\n search: async (query: string, signal: AbortSignal) => {\n const { live, seq } = feedState.current;\n const cache = mentionResults;\n if (cache.seq !== seq || !live) { cache.seq = seq; cache.results = new Map(); }\n const known = live ? cache.results.get(query) : undefined;\n if (known) return known;\n const results = cache.results;\n const entries = (await revisionProvider.search({ query, limit: 8 }, signal)).entries;\n // Kept only when no change arrived meanwhile.\n if (live && cache.results === results && cache.seq === feedState.current.seq) results.set(query, entries);\n return entries;\n },\n open: openFile,\n } : undefined, [revisionProvider, openFile, mentionResults]);\n // The search function changes only with the binding; the feed's seq rides along as the picker's generation.\n const mentionsForChat = useMemo(() => mentions && { ...mentions, generation: feed.seq }, [mentions, feed.seq]);\n const [attachmentFailure, setAttachmentFailure] = useState<{ readonly tree: FileTreeController; readonly reasons: readonly string[] }>();\n // Primitives only in the memo: a host's inline `labels` object would otherwise rebuild the chat's attachments on every render.\n const uploadAccept = uploads?.accept, inlineImages = uploads?.inlineImages === true, maxBytes = uploads?.maxBytes;\n const tooLarge = maxBytes !== undefined ? text.labels.attachmentTooLarge(sizeLabel(maxBytes)) : undefined;\n const revisionAttachments = useRevisionAttachments({ fileTree, accept: uploadAccept, inlineImages, maxBytes, tooLarge, onPreparationFailure: (name, reason) => {\n if (fileTree && fileTree.getSnapshot().lifecycle === 'active') setAttachmentFailure(current => ({ tree: fileTree,\n reasons: [...(current?.tree === fileTree ? current.reasons : []), `${name}: ${reason}`] }));\n } });\n const attachments = useMemo(() => revisionAttachments && { ...revisionAttachments, upload: (files: File[], signal: AbortSignal) => {\n setAttachmentFailure(undefined);\n return revisionAttachments.upload(files, signal);\n } }, [revisionAttachments]);\n\n // ---- Artifacts: cards open the panel; the agent's new ones open it too.\n const versions = useArtifactVersions(controller, detect);\n const turn = useTurn(controller);\n const active = isArtifact(opened) && opened.conversation === conversationId ? opened : null;\n const file = isFile(opened) ? opened : null;\n const host = opened && !isArtifact(opened) && !isFile(opened) && panels?.[opened.kind] ? opened : null;\n const panelOpen = Boolean(active || file || host);\n const seen = useRef(new Map<string, Set<string>>());\n const closedInTurn = useRef(new Map<string, number>());\n // Kept editing after the unsaved-changes question: the panel stays as it was, and the next artifact may still open it.\n const close = () => { if (!setOpened(null)) return; if (conversationId !== undefined) closedInTurn.current.set(conversationId, turn); setFullscreen(false); };\n useEffect(() => {\n if (!controller || conversationId === undefined) return;\n const keys = versions.map(version => `${artifactKey(version)}:${version.revision}`);\n const known = seen.current.get(conversationId);\n // What the conversation already held when it loaded does not count.\n if (!known) { seen.current.set(conversationId, new Set(keys)); return; }\n const fresh = versions.filter(version => !known.has(`${artifactKey(version)}:${version.revision}`));\n for (const key of keys) known.add(key);\n if (unsaved.current || !autoOpen || !fresh.length || closedInTurn.current.get(conversationId) === turn || globalThis.matchMedia?.(`(max-width: ${sheetBelow - 1}px)`).matches) return;\n setOpened({ kind: 'artifact', conversation: conversationId, descriptor: fresh.at(-1)!, follow: true });\n }, [versions, controller, conversationId, turn]); // eslint-disable-line react-hooks/exhaustive-deps\n // A `present` call waiting for the page: decided by `createPresentAcks` (refused when the person closed the panel this turn, has unsaved\n // edits or is on a phone; otherwise its file is opened unless `autoOpen` is off, and the acknowledgement follows the mount).\n openForPresent.current = path => setOpened({ kind: 'file', path });\n const liveView = useSyncExternalStore(controller ? controller.subscribe : subscribeNothing, () => controller?.getSnapshot().view, () => undefined);\n const presentCalls = useMemo(() => pendingPresents(liveView), [liveView]);\n useEffect(() => {\n if (!answerPresent.current || conversationId === undefined) return;\n presentAcks.current?.consider(presentCalls, { closedThisTurn: closedInTurn.current.get(conversationId) === turn, unsaved: unsaved.current,\n narrow: globalThis.matchMedia?.(`(max-width: ${sheetBelow - 1}px)`).matches === true, autoOpen, showing: path => showsPath(currentView.current, path) });\n }, [presentCalls, conversationId, turn, autoOpen, sheetBelow]);\n /** The versions of one file that the conversation presented or saved, newest first. */\n const newestOf = (key: string) => versions.filter(version => artifactKey(version) === key).reverse();\n const artifacts: ArtifactsConfig = useMemo(() => ({\n open: descriptor => { if (conversationId !== undefined) setOpened({ kind: 'artifact', conversation: conversationId, descriptor, follow: descriptor.revision === newestOf(artifactKey(descriptor))[0]?.revision }); },\n isOpen: descriptor => Boolean(active && artifactKey(active.descriptor) === artifactKey(descriptor) && (active.follow ? descriptor.revision === newestOf(artifactKey(descriptor))[0]?.revision : descriptor.revision === active.descriptor.revision)),\n ...(detect ? { detect } : {}),\n }), [conversationId, active, versions, detect, setOpened]); // eslint-disable-line react-hooks/exhaustive-deps\n\n // ---- Sessions: docked on a wide workspace (collapsible, remembered for the session), a drawer on a narrow one.\n const root = useRef<HTMLDivElement>(null);\n const [width, setWidth] = useState(0);\n useLayoutEffect(() => {\n const element = root.current;\n if (!element) return;\n const measure = () => setWidth(element.getBoundingClientRect().width);\n measure();\n if (typeof ResizeObserver === 'undefined') return;\n const observer = new ResizeObserver(measure);\n observer.observe(element);\n return () => observer.disconnect();\n }, []);\n const narrow = width > 0 && width < drawerBelow;\n const [collapsed, setCollapsed] = useState(() => readFlag(`${storageKey}.sessions-hidden`));\n const [drawer, setDrawer] = useState(false);\n const [paneView, setPaneView] = useState<SessionsView>(() => readFlag(`${storageKey}.library`) ? 'library' : 'conversations');\n const changePaneView = useCallback((next: SessionsView) => { writeFlag(`${storageKey}.library`, next === 'library'); setPaneView(next); }, [storageKey]);\n // The upload notice's \"Open Library\": the center Library, or the pane's Library tab with the pane shown.\n const revealLibrary = () => {\n if (librarySide) { setSideOpen(true); return; }\n if (!libraryInPane) { openLibrary(); return; }\n changePaneView('library');\n if (narrow) setDrawer(true); else { writeFlag(`${storageKey}.sessions-hidden`, false); setCollapsed(false); }\n };\n useEffect(() => { if (!narrow) setDrawer(false); }, [narrow]);\n const toggleSide = useCallback(() => setSideOpen(!sideOpen), [setSideOpen, sideOpen]);\n // The Library tree, one view for the side column, the center and the pane; `onOpen` is what choosing a file does there.\n const libraryTree = (onOpen: (path: string) => void) => fileTree\n ? <FileTreeView key={JSON.stringify([revisionProvider?.workspace, revisionProvider?.identity])} {...(locale ? { locale } : {})} {...viewOptions} controller={fileTree} historyKey={feed.seq} onOpen={onOpen} {...(isFile(opened) ? { selectedPath: opened.path } : {})} />\n : <p role=\"status\" className=\"m-0 p-3 text-sm text-muted-foreground\">{treeOptions?.labels?.loading ?? text.labels.loading}</p>;\n const hasNavigation = Boolean(conversations || revisionProvider);\n const docked = hasNavigation && width > 0 && !narrow && !collapsed;\n const toggle = hasNavigation && <SessionsToggle navigation={Boolean(revisionProvider)} open={narrow ? drawer : !collapsed} drawer={narrow}\n onToggle={() => { if (narrow) setDrawer(value => !value); else setCollapsed(value => { writeFlag(`${storageKey}.sessions-hidden`, !value); return !value; }); }} />;\n\n // ---- The docked chat's header is replaced on every switch and connect (the `connecting` row, then a new `PiChat`). The toggle is not\n // part of it: it stays mounted in the shell, over an invisible space of its size in whichever header is showing, and follows that\n // header's height. A press that starts before the swap ends on the same button and still clicks (a button that leaves the document\n // between press and release loses the click, even when moved rather than recreated).\n const toggleRow = useRef<HTMLDivElement>(null);\n const followHeader = useRef<ResizeObserver | undefined>(undefined);\n const headerSlot = useCallback((space: HTMLElement | null) => {\n followHeader.current?.disconnect(); followHeader.current = undefined;\n const header = space?.parentElement;\n if (!header || typeof ResizeObserver === 'undefined') return;\n followHeader.current = new ResizeObserver(() => { if (toggleRow.current) toggleRow.current.style.height = `${header.clientHeight}px`; });\n followHeader.current.observe(header);\n }, []);\n const toggleSpace = toggle && <Button ref={headerSlot} size=\"icon-sm\" aria-hidden=\"true\" tabIndex={-1} className=\"invisible -ml-1\" />;\n\n // ---- The chat in the center: docked PiChat, or the host's floating surface over the same controller (with the toggle in its header).\n const header = typeof controls === 'function' ? controls({ panelOpen }) : controls ?? chat.controls;\n const chatProps: PiChatProps | undefined = controller && { ...(mentionsForChat ? { mentions: mentionsForChat } : {}), ...(attachments ? { attachments } : {}), ...(locale ? { locale } : {}), ...chat, controller, artifacts, ...(conversations ? { conversations, historyList: false } : {}),\n headerStart: <>{toggle}{chat.headerStart}</>, ...(header === undefined ? {} : { controls: header }) };\n const docked_chat = <div data-testid=\"workspace-center\" className=\"flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden\">\n {attachmentFailure?.tree === fileTree && attachmentFailure?.reasons.map((reason, index) => <p key={index} role=\"alert\" className=\"m-0 px-4 py-2 text-sm\">{reason}</p>)}\n {fileTree && <UploadNotice controller={fileTree} onOpen={revealLibrary} />}\n {chatTop}\n <div className=\"relative flex min-h-0 flex-1 flex-col\">\n {chatProps ? <PiChat key={conversationId} {...chatProps} headerStart={<>{toggleSpace}{chat.headerStart}</>} className={cn('min-h-0 flex-1', chat.className)} />\n // Same geometry as the PiChat header, so nothing moves when the chat arrives.\n : <>{toggle && <div className=\"flex shrink-0 items-center gap-2 border-b border-border px-3 py-2 sm:gap-3 sm:px-4 sm:py-2.5\">{toggleSpace}</div>}{connecting}</>}\n {toggle && <div ref={toggleRow} className=\"pointer-events-none absolute top-0 left-0 z-10 flex items-center px-3 sm:px-4 [&>*]:pointer-events-auto\">{toggle}</div>}\n </div>\n </div>;\n\n const kind = active ? 'artifact' : file ? 'file' : host?.kind;\n const shown = active ?? file ?? host;\n const actionsFor = (floatChat: (() => void) | undefined): readonly BlockAction[] => [\n ...(librarySide ? [{ id: 'library', label: text.labels.library, icon: text.icons.library, pressed: sideOpen, onSelect: toggleSide }] : []),\n ...(floatChat ? [{ id: 'float-chat', label: text.labels.floatChat, icon: text.icons.floatChat, placement: 'menu' as const, onSelect: floatChat }] : []),\n ...(shown ? typeof panelActions === 'function' ? panelActions(shown) : panelActions ?? [] : []),\n ];\n return <AppTextProvider value={text}><ChatTextProvider value={chatText}><div ref={root} data-boring=\"agent-workspace\" data-sessions={!hasNavigation ? undefined : narrow ? (drawer ? 'drawer' : 'closed') : docked ? 'docked' : 'hidden'}\n className={cn('relative flex h-full min-h-0 min-w-0 flex-1 overflow-hidden', className)}>\n <DockLayout storageKey={`${storageKey}.dock`} minMain={SESSIONS_WIDTH + 480}>\n {hasNavigation && (docked || (narrow && drawer)) && <SessionsPane conversations={conversations} drawer={narrow} onClose={() => setDrawer(false)} onChat={() => setCenterMode('chat')}\n agents={agents} view={paneView} onViewChange={changePaneView}\n {...(librarySide ? { library: { selected: sideOpen, onSelect: toggleSide, side: true } } : revisionProvider && !libraryInPane ? { library: { selected: libraryOpen, onSelect: openLibrary } } : {})}\n {...(libraryInPane ? { libraryContent: (onPicked: () => void) => libraryTree(path => { openFile(path); onPicked(); }) } : {})} />}\n <DockMain><ArtifactWorkspace open={panelOpen} onClose={close} panelLabel={text.labels.artifactPanel} labels={{ resize: text.labels.resizePanel, floatHint: text.labels.floatHint }} fullscreen={fullscreen} onFullscreenChange={setFullscreen} storageKey={`${storageKey}.panel-width`}\n sheetBelow={docked ? Math.max(0, sheetBelow - SESSIONS_WIDTH) : sheetBelow} {...(floatBelow === undefined || libraryOpen ? {} : { floatBelow })}\n chat={layout => <WorkspaceCenter libraryOpen={libraryOpen} floating={layout.floating} chat={docked_chat}\n floatingChat={floatingChat && chatProps ? floatingChat(chatProps, layout.dock) : undefined}\n // With the Library in the pane, the center holds only the chat (no second, hidden toggle or tree).\n library={libraryInPane || librarySide ? null : <section data-testid=\"workspace-library-view\" aria-label={text.labels.library} className=\"flex min-h-0 flex-1 flex-col\">\n <header className=\"flex shrink-0 items-center gap-2 border-b border-border px-3 py-2\">{toggle}<h2 className=\"m-0 flex-1 text-sm font-semibold\">{text.labels.library}</h2>\n <Button variant=\"ghost\" size=\"sm\" onClick={() => setCenterMode('chat')}>{text.labels.backToChat}</Button></header>\n <div className=\"min-h-0 flex-1 overflow-auto\">{libraryTree(openFile)}</div>\n </section>} />}\n panel={win => <ViewerWindowProvider value={{ fullscreen: win.fullscreen, onFullscreenChange: win.onFullscreenChange, actions: actionsFor(win.floatChat), labels: text.labels, icons: text.icons }}>\n <div data-testid=\"viewer-panel\" data-kind={kind} className=\"flex min-h-0 flex-1 flex-col overflow-hidden [&>*]:min-h-0 [&>*]:flex-1\">\n {active\n ? <ArtifactPanel key={artifactKey(active.descriptor)} active={active} versions={newestOf(artifactKey(active.descriptor))} options={options} onClose={win.close}\n onSelect={value => {\n const known = newestOf(artifactKey(active.descriptor));\n setOpened({ kind: 'artifact', conversation: active.conversation, follow: value === 'latest', descriptor: value === 'latest' ? (known[0] ?? active.descriptor) : { ...active.descriptor, revision: value } });\n }} />\n : file ? <FileViewer key={JSON.stringify([revisionProvider?.workspace, identity, file.path])} onUnsavedChange={noteUnsaved} path={file.path} locator={locate(file.path)} options={options} onClose={win.close} {...(fileBack ? { onBack: fileBack.onBack, backLabel: fileBack.label } : {})} />\n : host ? panels![host.kind]!(host, win) : null}\n </div></ViewerWindowProvider>} /></DockMain>\n {librarySide && <Dock id=\"library\" side=\"right\" open={sideOpen} onOpenChange={setSideOpen} defaultWidth={LIBRARY_WIDTH} minWidth={240} narrowBelow={Math.max(drawerBelow, (docked ? SESSIONS_WIDTH : 0) + (panelOpen ? VIEWER_MIN + CHAT_MIN : CHAT_MIN) + libraryWidth)} narrow=\"sheet\"\n labels={{ region: text.labels.library, resize: text.labels.resizePanel }} className=\"border-l border-border\">\n {api => <section data-testid=\"workspace-library-side\" aria-label={text.labels.library} className=\"flex min-h-0 flex-1 flex-col\">\n <WidthProbe width={api.width} onWidth={setLibraryWidth} />\n <header className=\"flex shrink-0 items-center gap-2 border-b border-border px-3 py-2\"><h2 className=\"m-0 min-w-0 flex-1 truncate text-sm font-semibold\">{text.labels.library}</h2>\n <Button size=\"icon-sm\" variant=\"ghost\" aria-label={text.labels.close} title={text.labels.close} data-testid=\"workspace-library-close\" onClick={() => setSideOpen(false)}><text.icons.closeSessions className=\"size-4\" aria-hidden=\"true\" /></Button></header>\n <div className=\"min-h-0 flex-1 overflow-auto\">{libraryTree(path => { if (setOpened({ kind: 'file', path }) && narrow) setSideOpen(false); })}</div>\n </section>}\n </Dock>}\n </DockLayout>\n </div></ChatTextProvider></AppTextProvider>;\n}\n\nfunction WidthProbe({ width, onWidth }: { readonly width: number; readonly onWidth: (width: number) => void }) {\n useLayoutEffect(() => { onWidth(width); }, [width, onWidth]);\n return null;\n}\n\nfunction UploadNotice({ controller, onOpen }: { readonly controller: FileTreeController; readonly onOpen: () => void }) {\n const state = useSyncExternalStore(controller.subscribe, controller.getSnapshot, controller.getSnapshot);\n const failures = state.uploads.filter(upload => upload.state.kind === 'settled' && upload.state.result.kind !== 'committed');\n return failures.length ? <p role=\"alert\" className=\"m-0 px-4 py-2 text-sm\">{failures.length} upload{failures.length === 1 ? '' : 's'} need attention. <button type=\"button\" className=\"underline\" onClick={onOpen}>Open Library</button> to review the results and check unconfirmed uploads.</p> : null;\n}\n\n/** Keep the selected chat surface mounted while Library temporarily uses its layout space. */\nfunction WorkspaceCenter({ libraryOpen, floating, chat, floatingChat, library }: {\n readonly libraryOpen: boolean;\n readonly floating: boolean;\n readonly chat: ReactNode;\n readonly floatingChat: ReactNode;\n readonly library: ReactNode;\n}) {\n const lastFloating = useRef(floating);\n useLayoutEffect(() => { if (!libraryOpen) lastFloating.current = floating; }, [libraryOpen, floating]);\n const showFloating = libraryOpen ? lastFloating.current : floating;\n return <div className=\"flex min-h-0 flex-1 flex-col\">\n <div data-testid=\"workspace-chat-surface\" hidden={libraryOpen} inert={libraryOpen} aria-hidden={libraryOpen || undefined} className={cn('min-h-0 flex-1 flex-col', libraryOpen ? 'hidden' : 'flex')}>\n {showFloating && floatingChat ? floatingChat : chat}\n </div>\n <div hidden={!libraryOpen} inert={!libraryOpen} aria-hidden={!libraryOpen || undefined} className={cn('min-h-0 flex-1 flex-col', libraryOpen ? 'flex' : 'hidden')}>{library}</div>\n </div>;\n}\n\n/**\n * The seq of the provider's latest change event (`RevisionProvider.changes`), coalesced over `settleMs` so a burst (a shell writing\n * many files) reloads once. `live` is false without a feed or after the feed was refused; views then keep their own refresh.\n */\nfunction useChangeFeed(provider: RevisionProvider | undefined, settleMs = 150): { readonly seq: number | undefined; readonly live: boolean } {\n const [state, setState] = useState<{ readonly provider: RevisionProvider | undefined; readonly seq: number | undefined; readonly live: boolean }>({ provider, seq: undefined, live: false });\n useEffect(() => {\n if (!provider?.changes) { setState({ provider, seq: undefined, live: false }); return; }\n const stop = new AbortController();\n let timer: ReturnType<typeof setTimeout> | undefined, latest: number | undefined;\n setState({ provider, seq: undefined, live: true });\n void (async () => {\n try {\n for await (const event of provider.changes!({ signal: stop.signal })) {\n latest = event.seq;\n timer ??= setTimeout(() => { timer = undefined; if (!stop.signal.aborted) setState({ provider, seq: latest, live: true }); }, settleMs);\n }\n } catch { /* refused: the views fall back to their own refresh */ }\n clearTimeout(timer);\n timer = undefined;\n if (!stop.signal.aborted) setState({ provider, seq: latest, live: false });\n })();\n return () => { stop.abort(); clearTimeout(timer); };\n }, [provider, settleMs]);\n return state.provider === provider ? state : { seq: undefined, live: false };\n}\n",
|
|
25
|
+
"content": "'use client';\n\nimport '@hachej/boring-ui-kit/file-tree.css';\n\nimport { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';\nimport type { ReactNode } from 'react';\nimport type { ResourceLocator } from '@hachej/boring-files';\nimport { createResourceClient } from '@hachej/boring-files/remote';\nimport { mediaTypeOf, workspacePath } from '@hachej/boring-files/file-types';\nimport type { FileEntry, RevisionProvider } from '@hachej/boring-files/revision';\nimport { createFileTreeController } from '@hachej/boring-ui-kit/file-tree';\nimport { randomUUID } from '@hachej/boring-files/platform';\nimport type { FileTreeController } from '@hachej/boring-ui-kit/file-tree';\nimport { FileTreeView } from '@hachej/boring-ui-kit/file-tree-view';\nimport { frenchAppLabels } from './app-labels-fr';\nimport { chatTextFor } from '../pi-chat/locale';\nimport type { ChatLocale } from '../pi-chat/locale';\nimport type { FileTreeViewProps } from '@hachej/boring-ui-kit/file-tree-view';\nimport type { ResourceIdentity } from '@hachej/boring-files/remote';\nimport type { NativeChatController } from '@hachej/boring-ui-kit/native-chat';\nimport { PiChat, artifactKey } from '../pi-chat/pi-chat';\nimport { createPresentAcks, pendingPresents } from '../pi-chat/artifact';\nimport type { PresentAcks } from '../pi-chat/artifact';\nimport type { ArtifactDescriptor, ArtifactsConfig, ConversationsConfig, PiChatProps } from '../pi-chat/pi-chat';\nimport { Dock, DockLayout, DockMain } from '../pi-workspace/dock';\nimport { ArtifactWorkspace } from '../pi-workspace/workspace';\nimport type { WorkspacePanelApi } from '../pi-workspace/workspace';\nimport { ViewerWindowProvider } from '../viewers/viewer-frame';\nimport type { ViewerShare } from '../viewers/viewer-frame';\nimport type { InteractiveHtml } from '../viewers/interactive-html';\nimport { Button } from '../button/button';\nimport type { BlockAction } from '../button/actions';\nimport { ChatTextProvider, useMergedText } from '../pi-chat/labels';\nimport { cn, withDefaults } from '../utils/utils';\nimport { AppTextProvider, defaultAppIcons, defaultAppLabels } from './app-labels';\nimport type { AppIcons, AppLabels } from './app-labels';\nimport { ArtifactPanel, useArtifactVersions, useTurn } from './artifact-panel';\nimport type { CustomViewers, SavedRevision, ViewerOptions } from './artifact-panel';\nimport { FileViewer } from './file-viewer';\nimport { useRevisionAttachments } from './use-revision-attachments';\nimport { imageData } from './revision-files';\nimport { SessionsPane, SessionsToggle } from './sessions';\nimport type { SessionsView, WorkspaceAgents } from './sessions';\n\nexport { ArtifactPanel, useArtifactVersions, useTurn } from './artifact-panel';\nexport type { CustomViewerProps, CustomViewers, SavedRevision, ViewerOptions } from './artifact-panel';\nexport { FileViewer } from './file-viewer';\nexport { SessionsPane, SessionsToggle } from './sessions';\nexport type { SessionsView, WorkspaceAgent, WorkspaceAgents } from './sessions';\nexport { useConversations } from './use-conversations';\nexport { useRemoteChat } from '../pi-chat/use-remote-chat';\nexport type { RemoteChatState } from '../pi-chat/use-remote-chat';\nexport { savedLabel, useSaved } from './use-saved';\nexport { viewerKindOf as kindOf, mediaTypeOf } from '@hachej/boring-files/file-types';\nexport { defaultAppIcons, defaultAppLabels } from './app-labels';\nexport { frenchAppLabels } from './app-labels-fr';\nexport type { AppIcons, AppLabels } from './app-labels';\nexport type { ViewerKind as FileKind } from '@hachej/boring-files/file-types';\n\n/** An artifact version in the panel: `follow` shows the latest saved revision, otherwise `descriptor.revision` is pinned and read-only. */\nexport interface ArtifactView { readonly kind: 'artifact'; readonly conversation: string; readonly descriptor: ArtifactDescriptor; readonly follow: boolean }\n/** A file in the panel, by the host's path (see `resources.locate`). */\nexport interface FileView { readonly kind: 'file'; readonly path: string }\n/** Anything else the host renders in the panel through `panels[kind]` (for example a file list or a tool view). */\nexport interface HostView { readonly kind: string; readonly [field: string]: unknown }\n/** What the right-hand panel shows, or `null` when it is closed. */\nexport type OpenedView = ArtifactView | FileView | HostView;\n\nconst isArtifact = (view: OpenedView | null): view is ArtifactView => view?.kind === 'artifact';\nconst isFile = (view: OpenedView | null): view is FileView => view?.kind === 'file';\n/** Whether the panel shows the file at `path` (a file view, or the artifact view of it). */\nconst showsPath = (view: OpenedView | null, path: string): boolean => isFile(view) ? view.path === path : isArtifact(view) ? view.descriptor.target.resource.path === path : false;\nconst subscribeNothing = () => () => {};\n\n/** Where the viewers read and write: the host's resource handler (`createResourceHandler` of `@hachej/boring-files/remote`) and its file history. */\nexport interface WorkspaceResources {\n /** The resource handler endpoint. */\n readonly endpoint: string | URL;\n /** The host's authenticated fetch, also used for `history`. */\n readonly fetch: (request: Request) => Promise<Response>;\n /** The person's identity as the resource handler authenticates it (comparison metadata, never a grant). */\n readonly identity: ResourceIdentity;\n /** Optional `GET <history>?path=<resource path>` returning `{ saves: [{ revision, savedAt }] }` newest first (`files.saves(path)`): the version menu. */\n readonly history?: string | URL | undefined;\n /** The resource of a file path in a `FileView`. Default: the published `workspace` provider at the path without a leading slash. */\n readonly locate?: ((path: string) => ResourceLocator) | undefined;\n}\n\ninterface AgentWorkspaceBaseProps {\n /**\n * Where the Library of a `revisionProvider` opens. `side` (default): a column to the right of the viewer (a `Dock`, resizable), opened\n * from the Library button in the viewer's top bar or in the left pane, alone at the right edge when no file is open; on a phone a\n * full-screen sheet that choosing a file closes. `center`: Chat and Library links in the left pane, the Library replacing\n * the chat in the center (the chat stays mounted). `pane`: the Library is a tab beside the conversations in the left pane, or the\n * whole pane on a single-session page without `conversations`; files open in the right panel as usual.\n */\n readonly libraryPlacement?: 'side' | 'center' | 'pane' | undefined;\n /** The page's language: `en` (default) or `fr`, for the chat, the panes, the viewers and the Library. `labels` and `chat.labels` override any word. */\n readonly locale?: ChatLocale | undefined;\n /**\n * The Library tree's options: its words (`labels`, over `defaultFileTreeLabels`), whether it offers Upload and History, and a\n * `refreshKey` that reloads it when it changes. Deprecated: with a `revisionProvider` that has a change feed (`connectRevisionProvider`)\n * the tree, the Library, the history panel and the @ search reload from the workspace's own change events; `refreshKey` remains\n * for a provider without one.\n */\n readonly fileTree?: Pick<FileTreeViewProps, 'labels' | 'upload' | 'history' | 'refreshKey'> | undefined;\n /**\n * How the chat's attachments are saved under `uploads/` (they exist only with a Library, `revisionProvider` or `resources`). Every file\n * is reference-only by default: the message carries its `@path` and the agent reads it with its file tools. See `WorkspaceUploads`.\n */\n readonly uploads?: WorkspaceUploads | undefined;\n /**\n * The page's agents. With two or more, a switcher at the top of the left pane chooses one; the host scopes `conversations` and the\n * controller to `activeId`. One agent (or none given) shows no switcher.\n */\n readonly agents?: WorkspaceAgents | undefined;\n /** The open conversation's controller (`useRemoteChat`); `undefined` while connecting, when `connecting` is shown instead. */\n readonly controller: NativeChatController | undefined;\n /** The open conversation: auto-opened artifacts and the artifact view belong to it. */\n readonly conversationId: string | undefined;\n /** Everything else `PiChat` takes (labels, icons, headerActions, messageActions, mode, actions, slash, mentions, attachments, model, effort, emptyState, ...). */\n readonly chat?: Omit<PiChatProps, 'controller' | 'artifacts' | 'conversations' | 'historyList'>;\n /**\n * The block's words (sessions pane, artifact panel, file viewer and the viewers' bars), over `defaultAppLabels`; for example\n * `{ sessionsTitle: 'Projects', newChat: 'Start' }`. The chat's own go in `chat.labels`.\n */\n readonly labels?: Partial<AppLabels> | undefined;\n /** The block's icons (sessions toggle, New, Float chat, the viewer bar's), over `defaultAppIcons`. The chat's go in `chat.icons`. */\n readonly icons?: Partial<AppIcons> | undefined;\n /**\n * Host actions on the artifact panel's bar (every viewer it shows), after the built-in Float chat: `header` ones as buttons beside Share,\n * `menu` ones in its \"…\" menu. A function receives what is open. Test ids `<viewer testId>-<id>` (`artifact-<id>` for an artifact).\n */\n readonly panelActions?: readonly BlockAction[] | ((view: OpenedView) => readonly BlockAction[]) | undefined;\n readonly connecting?: ReactNode;\n /** The sessions pane (`useConversations`). Omit it for a page without one. Replies keep their Fork button through `conversations.fork`. */\n readonly conversations?: ConversationsConfig | undefined;\n /** Recognise artifacts in tool results that carry no descriptor (`ArtifactsConfig.detect`). */\n readonly detect?: ArtifactsConfig['detect'] | undefined;\n /** Host viewers by artifact type or file kind, for example `{ canvas: props => <MyCanvas {...props} /> }`. */\n readonly viewers?: CustomViewers | undefined;\n /** Run HTML pages in the viewers' sandboxed preview, loading scripts only from these origins. Off without it. */\n readonly interactive?: InteractiveHtml | undefined;\n /** The viewer bar's Share action; it receives `target` `{ artifact, version }` or `{ file }`. */\n readonly share?: ViewerShare | undefined;\n /** Controlled panel content (with `onOpenedChange`); uncontrolled from `defaultOpened` otherwise. */\n readonly opened?: OpenedView | null | undefined;\n readonly defaultOpened?: OpenedView | null | undefined;\n readonly onOpenedChange?: ((next: OpenedView | null) => void) | undefined;\n /**\n * Whether the open file has unsaved or unconfirmed changes. The workspace asks before leaving such a file itself; a host that\n * switches the workspace or identity (a new `revisionProvider`) or changes a controlled `opened` should ask first too, since the\n * viewer of the previous file is replaced and its local draft discarded.\n */\n readonly onUnsavedChange?: ((unsaved: boolean) => void) | undefined;\n /** Renderers for host views, by `kind`. */\n readonly panels?: Readonly<Record<string, (view: HostView, panel: WorkspacePanelApi) => ReactNode>> | undefined;\n /** Open the panel on each artifact (or new version) the agent makes, unless the person closed it during this turn. Not on a phone. Default true. */\n readonly autoOpen?: boolean;\n /** A back button in a file's viewer bar (for example to the host's file list). */\n readonly fileBack?: { readonly label: string; readonly onBack: () => void } | undefined;\n /** With `floatBelow`: the floating chat over the same session (for example `AmbientChat` of `pi-ambient` with `onDock={dock}`). */\n readonly floatingChat?: ((props: PiChatProps, dock: () => void) => ReactNode) | undefined;\n /** Shown above the chat (notices). */\n readonly chatTop?: ReactNode;\n /** The chat header's controls; a function receives whether the panel is open. */\n readonly controls?: ReactNode | ((state: { readonly panelOpen: boolean }) => ReactNode);\n /** Prefix of the session-scoped layout keys (panel width, floating chat, collapsed sessions). */\n readonly storageKey?: string;\n /** Below this width of the workspace the artifact panel is a full-screen sheet. */\n readonly sheetBelow?: number;\n /** Below this width of the workspace the sessions pane is a drawer. */\n readonly drawerBelow?: number;\n readonly floatBelow?: number | undefined;\n readonly className?: string;\n}\n\n/** The chat's attachment rules. `inlineImages` (default false) also sends a png, jpeg, gif or webp as a native image in the message: every later turn then carries its base64, so it is off by default. `maxBytes` refuses a larger file before it is uploaded (no limit by default), and the chat shows why. `accept` is the file picker's `accept` (any file by default). */\nexport interface WorkspaceUploads {\n readonly inlineImages?: boolean | undefined;\n readonly maxBytes?: number | undefined;\n readonly accept?: string | undefined;\n}\n\n/** A byte count for a refusal message: `2.5 MB`, `300 KB`, or `12 bytes`. */\nconst sizeLabel = (bytes: number) => bytes >= 1_000_000 ? `${Number((bytes / 1_000_000).toFixed(1))} MB` : bytes >= 1_000 ? `${Math.round(bytes / 1_000)} KB` : `${bytes} bytes`;\n\nexport type AgentWorkspaceProps = AgentWorkspaceBaseProps & (\n | { readonly revisionProvider: RevisionProvider; readonly resources?: never }\n | { readonly resources: WorkspaceResources; readonly revisionProvider?: never }\n);\n\n// The Library column is docked only while the chat and the viewer (their `ArtifactWorkspace` minimums) keep their room beside it; otherwise it is Dock's sheet.\nconst SESSIONS_WIDTH = 288, LIBRARY_WIDTH = 320, CHAT_MIN = 340, VIEWER_MIN = 360;\nconst readFlag = (key: string): boolean => { try { return sessionStorage.getItem(key) === '1'; } catch { return false; } };\nconst writeFlag = (key: string, on: boolean) => { try { if (on) sessionStorage.setItem(key, '1'); else sessionStorage.removeItem(key); } catch { /* the layout is a convenience */ } };\nconst defaultLocate = (path: string): ResourceLocator => ({ resource: { providerId: 'workspace', path: workspacePath(path) }, view: { kind: 'published' } });\n\n/**\n * A complete agent page in one component: the sessions pane on the left (search, New, rename, archive, delete; collapsible, a drawer on\n * a narrow screen), the chat in the center (`PiChat`) and the artifact viewers on the right (`ArtifactWorkspace` with the artifact panel and\n * its versions, the file viewer and the host's own views). Agent artifacts open the panel as they appear. Every prop is data or a callback:\n * the host owns the routes, authentication, the controller and what is open (when controlled).\n */\nexport function AgentWorkspace({ controller, conversationId, chat = {}, labels, icons, panelActions, connecting, conversations, resources, revisionProvider, libraryPlacement = 'side', locale, fileTree: treeOptions, uploads, agents, detect, viewers, interactive, share, opened: controlled,\n defaultOpened = null, onOpenedChange, onUnsavedChange, panels, autoOpen = true, fileBack, floatingChat, chatTop, controls, storageKey = 'boring.agent-workspace', sheetBelow = 768, drawerBelow = 768, floatBelow, className }: AgentWorkspaceProps) {\n const [own, setOwn] = useState<OpenedView | null>(defaultOpened);\n const opened = controlled !== undefined ? controlled : own;\n const change = useRef(onOpenedChange); change.current = onOpenedChange;\n const isControlled = controlled !== undefined;\n const unsaved = useRef(false);\n const currentView = useRef(opened); currentView.current = opened;\n const unsavedChange = useRef(onUnsavedChange); unsavedChange.current = onUnsavedChange;\n const noteUnsaved = useCallback((value: boolean) => { if (unsaved.current !== value) { unsaved.current = value; unsavedChange.current?.(value); } }, []);\n /** Opens `next` and reports whether it did: leaving a file with unsaved changes asks first, and the person may stay. */\n const setOpened = useCallback((next: OpenedView | null): boolean => {\n const current = currentView.current;\n if (isFile(current) && isFile(next) && current.path === next.path) return true;\n if (unsaved.current && !globalThis.confirm?.('This file has unsaved or unconfirmed changes. Discard the local draft and leave this file?')) return false;\n noteUnsaved(false);\n if (!isControlled) setOwn(next); change.current?.(next);\n return true;\n }, [isControlled, noteUnsaved]);\n const [fullscreen, setFullscreen] = useState(false);\n const [centerMode, setCenterMode] = useState<'chat' | 'library'>('chat');\n const libraryInPane = Boolean(revisionProvider) && libraryPlacement === 'pane';\n const librarySide = Boolean(revisionProvider) && libraryPlacement === 'side';\n const [sideOpen, setSideOpenState] = useState(false);\n // The Library's real docked width, reported by its Dock: the room it needs beside the chat and the viewer.\n const [libraryWidth, setLibraryWidth] = useState(LIBRARY_WIDTH);\n // Opening the column leaves a full-screen viewer, whose overlay would otherwise cover it.\n const setSideOpen = useCallback((next: boolean) => { setSideOpenState(next); if (next) setFullscreen(false); }, []);\n const libraryOpen = Boolean(revisionProvider) && libraryPlacement === 'center' && centerMode === 'library';\n const openLibrary = useCallback(() => { setCenterMode('library'); setFullscreen(false); }, []);\n const text = useMemo(() => ({ labels: withDefaults(locale === 'fr' ? frenchAppLabels : defaultAppLabels, labels), icons: withDefaults(defaultAppIcons, icons) }), [labels, icons, locale]);\n // The sessions pane shows the chat's conversation list, so it reads the chat's labels too.\n const chatText = useMergedText(chat.labels, chat.icons, chatTextFor(locale));\n\n const fetcher = useRef(resources?.fetch); fetcher.current = resources?.fetch;\n const endpoint = resources ? String(resources.endpoint) : undefined;\n const historyEndpoint = resources?.history === undefined ? undefined : String(resources.history);\n const identity = revisionProvider?.identity ?? resources!.identity;\n const identityKey = JSON.stringify(identity);\n const client = useMemo(() => revisionProvider ?? createResourceClient({ identity, endpoint: new URL(endpoint!, globalThis.location?.href), publication: true, reconciliation: true,\n fetch: request => fetcher.current!(request) }), [revisionProvider, endpoint, identityKey]); // eslint-disable-line react-hooks/exhaustive-deps\n const history = useMemo(() => revisionProvider ? revisionProvider.history : historyEndpoint === undefined ? undefined : async (path: string): Promise<readonly SavedRevision[]> => {\n const url = new URL(historyEndpoint, globalThis.location?.href);\n url.searchParams.set('path', path);\n const response = await fetcher.current!(new Request(url));\n if (!response.ok) throw new Error(`History: ${response.status}`);\n return (await response.json() as { saves: readonly SavedRevision[] }).saves;\n }, [revisionProvider, historyEndpoint]);\n // ---- Presented files: the page confirms a `present` call only once its panel has mounted the revision (`onShown`, from the viewers).\n // The bookkeeping is `createPresentAcks` (pi-chat/artifact.ts); the answer goes through the chat's own `answer` (the transport's\n // `?op=answer`) and the server checks the path and revision.\n const answerPresent = useRef(chat.actions?.answer); answerPresent.current = chat.actions?.answer;\n const openForPresent = useRef<(path: string) => boolean>(() => false);\n const presentAcks = useRef<PresentAcks | undefined>(undefined);\n if (!presentAcks.current) presentAcks.current = createPresentAcks({ answer: (id, body) => answerPresent.current?.(id, body),\n open: path => openForPresent.current(path), instanceId: randomUUID() });\n const onShown = useCallback((view: { readonly path: string; readonly revision: string; readonly hidden?: true }) => {\n if (view.hidden) presentAcks.current?.hidden(view); else presentAcks.current?.shown(view);\n }, []);\n const options: ViewerOptions = useMemo(() => ({ client, identity, history, viewers, interactive, share, onShown }), [client, identityKey, history, viewers, interactive, share, onShown]); // eslint-disable-line react-hooks/exhaustive-deps\n const locate = revisionProvider?.locate ?? resources?.locate ?? defaultLocate;\n const [fileBinding, setFileBinding] = useState<{ readonly provider: RevisionProvider; readonly tree: FileTreeController }>();\n useEffect(() => {\n if (!revisionProvider) return;\n const tree = createFileTreeController({ revisionProvider });\n setFileBinding({ provider: revisionProvider, tree });\n void tree.refresh();\n return () => tree.dispose();\n }, [revisionProvider]);\n const fileTree = fileBinding?.provider === revisionProvider ? fileBinding?.tree : undefined;\n // The workspace's change feed: every file view below reloads when its seq moves (agent writes, saves, shell changes).\n const feed = useChangeFeed(revisionProvider);\n // The shared tree controller reloads, shown or not: the Library may be on its other tab when a file arrives, and mounting the tree\n // later must not show the listing from before. `fileTree.refreshKey` (deprecated) does the same for a provider without a feed.\n const { refreshKey, ...viewOptions } = treeOptions ?? {};\n const refreshedKey = useRef(refreshKey);\n const refreshedSeq = useRef(feed.seq);\n useEffect(() => {\n if (!fileTree || (Object.is(refreshedKey.current, refreshKey) && refreshedSeq.current === feed.seq)) return;\n refreshedKey.current = refreshKey;\n refreshedSeq.current = feed.seq;\n const { query, expanded } = fileTree.getSnapshot();\n if (query) void fileTree.search(query);\n else for (const directory of ['', ...expanded]) void fileTree.refresh(directory);\n }, [fileTree, refreshKey, feed.seq]);\n const openFile = useCallback((path: string) => { setOpened({ kind: 'file', path }); }, [setOpened]);\n // @ search: results are reused while the feed reports nothing new (typing back and forth), and dropped at the next change event.\n // One cache per provider instance (one workspace binding), so another binding never sees these results.\n const mentionResults = useMemo(() => ({ seq: undefined as number | undefined, results: new Map<string, readonly FileEntry[]>() }), [revisionProvider]);\n const feedState = useRef(feed); feedState.current = feed;\n const mentions = useMemo(() => revisionProvider ? {\n search: async (query: string, signal: AbortSignal) => {\n const { live, seq } = feedState.current;\n const cache = mentionResults;\n if (cache.seq !== seq || !live) { cache.seq = seq; cache.results = new Map(); }\n const known = live ? cache.results.get(query) : undefined;\n if (known) return known;\n const results = cache.results;\n const entries = (await revisionProvider.search({ query, limit: 8 }, signal)).entries;\n // Kept only when no change arrived meanwhile.\n if (live && cache.results === results && cache.seq === feedState.current.seq) results.set(query, entries);\n return entries;\n },\n open: openFile,\n // A card's thumbnail: the chat's image upload read through this provider, the same read the file viewer makes.\n preview: async (path: string, signal: AbortSignal) => {\n const read = await revisionProvider.read({ target: revisionProvider.locate(path), revision: { kind: 'latest' } }, signal);\n return read.kind === 'available' ? { mimeType: mediaTypeOf(path), data: imageData(read.snapshot.bytes) } : undefined;\n },\n } : undefined, [revisionProvider, openFile, mentionResults]);\n // The search function changes only with the binding; the feed's seq rides along as the picker's generation.\n const mentionsForChat = useMemo(() => mentions && { ...mentions, generation: feed.seq }, [mentions, feed.seq]);\n const [attachmentFailure, setAttachmentFailure] = useState<{ readonly tree: FileTreeController; readonly reasons: readonly string[] }>();\n // Primitives only in the memo: a host's inline `labels` object would otherwise rebuild the chat's attachments on every render.\n const uploadAccept = uploads?.accept, inlineImages = uploads?.inlineImages === true, maxBytes = uploads?.maxBytes;\n const tooLarge = maxBytes !== undefined ? text.labels.attachmentTooLarge(sizeLabel(maxBytes)) : undefined;\n const revisionAttachments = useRevisionAttachments({ fileTree, accept: uploadAccept, inlineImages, maxBytes, tooLarge, onPreparationFailure: (name, reason) => {\n if (fileTree && fileTree.getSnapshot().lifecycle === 'active') setAttachmentFailure(current => ({ tree: fileTree,\n reasons: [...(current?.tree === fileTree ? current.reasons : []), `${name}: ${reason}`] }));\n } });\n const attachments = useMemo(() => revisionAttachments && { ...revisionAttachments, upload: (files: File[], signal: AbortSignal) => {\n setAttachmentFailure(undefined);\n return revisionAttachments.upload(files, signal);\n } }, [revisionAttachments]);\n\n // ---- Artifacts: cards open the panel; the agent's new ones open it too.\n const versions = useArtifactVersions(controller, detect);\n const turn = useTurn(controller);\n const active = isArtifact(opened) && opened.conversation === conversationId ? opened : null;\n const file = isFile(opened) ? opened : null;\n const host = opened && !isArtifact(opened) && !isFile(opened) && panels?.[opened.kind] ? opened : null;\n const panelOpen = Boolean(active || file || host);\n const seen = useRef(new Map<string, Set<string>>());\n const closedInTurn = useRef(new Map<string, number>());\n // Kept editing after the unsaved-changes question: the panel stays as it was, and the next artifact may still open it.\n const close = () => { if (!setOpened(null)) return; if (conversationId !== undefined) closedInTurn.current.set(conversationId, turn); setFullscreen(false); };\n useEffect(() => {\n if (!controller || conversationId === undefined) return;\n const keys = versions.map(version => `${artifactKey(version)}:${version.revision}`);\n const known = seen.current.get(conversationId);\n // What the conversation already held when it loaded does not count.\n if (!known) { seen.current.set(conversationId, new Set(keys)); return; }\n const fresh = versions.filter(version => !known.has(`${artifactKey(version)}:${version.revision}`));\n for (const key of keys) known.add(key);\n if (unsaved.current || !autoOpen || !fresh.length || closedInTurn.current.get(conversationId) === turn || globalThis.matchMedia?.(`(max-width: ${sheetBelow - 1}px)`).matches) return;\n setOpened({ kind: 'artifact', conversation: conversationId, descriptor: fresh.at(-1)!, follow: true });\n }, [versions, controller, conversationId, turn]); // eslint-disable-line react-hooks/exhaustive-deps\n // A `present` call waiting for the page: decided by `createPresentAcks` (refused when the person closed the panel this turn, has unsaved\n // edits or is on a phone; otherwise its file is opened unless `autoOpen` is off, and the acknowledgement follows the mount).\n openForPresent.current = path => setOpened({ kind: 'file', path });\n const liveView = useSyncExternalStore(controller ? controller.subscribe : subscribeNothing, () => controller?.getSnapshot().view, () => undefined);\n const presentCalls = useMemo(() => pendingPresents(liveView), [liveView]);\n useEffect(() => {\n if (!answerPresent.current || conversationId === undefined) return;\n presentAcks.current?.consider(presentCalls, { closedThisTurn: closedInTurn.current.get(conversationId) === turn, unsaved: unsaved.current,\n narrow: globalThis.matchMedia?.(`(max-width: ${sheetBelow - 1}px)`).matches === true, autoOpen, showing: path => showsPath(currentView.current, path) });\n }, [presentCalls, conversationId, turn, autoOpen, sheetBelow]);\n /** The versions of one file that the conversation presented or saved, newest first. */\n const newestOf = (key: string) => versions.filter(version => artifactKey(version) === key).reverse();\n const artifacts: ArtifactsConfig = useMemo(() => ({\n open: descriptor => { if (conversationId !== undefined) setOpened({ kind: 'artifact', conversation: conversationId, descriptor, follow: descriptor.revision === newestOf(artifactKey(descriptor))[0]?.revision }); },\n isOpen: descriptor => Boolean(active && artifactKey(active.descriptor) === artifactKey(descriptor) && (active.follow ? descriptor.revision === newestOf(artifactKey(descriptor))[0]?.revision : descriptor.revision === active.descriptor.revision)),\n ...(detect ? { detect } : {}),\n }), [conversationId, active, versions, detect, setOpened]); // eslint-disable-line react-hooks/exhaustive-deps\n\n // ---- Sessions: docked on a wide workspace (collapsible, remembered for the session), a drawer on a narrow one.\n const root = useRef<HTMLDivElement>(null);\n const [width, setWidth] = useState(0);\n useLayoutEffect(() => {\n const element = root.current;\n if (!element) return;\n const measure = () => setWidth(element.getBoundingClientRect().width);\n measure();\n if (typeof ResizeObserver === 'undefined') return;\n const observer = new ResizeObserver(measure);\n observer.observe(element);\n return () => observer.disconnect();\n }, []);\n const narrow = width > 0 && width < drawerBelow;\n const [collapsed, setCollapsed] = useState(() => readFlag(`${storageKey}.sessions-hidden`));\n const [drawer, setDrawer] = useState(false);\n const [paneView, setPaneView] = useState<SessionsView>(() => readFlag(`${storageKey}.library`) ? 'library' : 'conversations');\n const changePaneView = useCallback((next: SessionsView) => { writeFlag(`${storageKey}.library`, next === 'library'); setPaneView(next); }, [storageKey]);\n // The upload notice's \"Open Library\": the center Library, or the pane's Library tab with the pane shown.\n const revealLibrary = () => {\n if (librarySide) { setSideOpen(true); return; }\n if (!libraryInPane) { openLibrary(); return; }\n changePaneView('library');\n if (narrow) setDrawer(true); else { writeFlag(`${storageKey}.sessions-hidden`, false); setCollapsed(false); }\n };\n useEffect(() => { if (!narrow) setDrawer(false); }, [narrow]);\n const toggleSide = useCallback(() => setSideOpen(!sideOpen), [setSideOpen, sideOpen]);\n // The Library tree, one view for the side column, the center and the pane; `onOpen` is what choosing a file does there.\n const libraryTree = (onOpen: (path: string) => void) => fileTree\n ? <FileTreeView key={JSON.stringify([revisionProvider?.workspace, revisionProvider?.identity])} {...(locale ? { locale } : {})} {...viewOptions} controller={fileTree} historyKey={feed.seq} onOpen={onOpen} {...(isFile(opened) ? { selectedPath: opened.path } : {})} />\n : <p role=\"status\" className=\"m-0 p-3 text-sm text-muted-foreground\">{treeOptions?.labels?.loading ?? text.labels.loading}</p>;\n const hasNavigation = Boolean(conversations || revisionProvider);\n const docked = hasNavigation && width > 0 && !narrow && !collapsed;\n const toggle = hasNavigation && <SessionsToggle navigation={Boolean(revisionProvider)} open={narrow ? drawer : !collapsed} drawer={narrow}\n onToggle={() => { if (narrow) setDrawer(value => !value); else setCollapsed(value => { writeFlag(`${storageKey}.sessions-hidden`, !value); return !value; }); }} />;\n\n // ---- The docked chat's header is replaced on every switch and connect (the `connecting` row, then a new `PiChat`). The toggle is not\n // part of it: it stays mounted in the shell, over an invisible space of its size in whichever header is showing, and follows that\n // header's height. A press that starts before the swap ends on the same button and still clicks (a button that leaves the document\n // between press and release loses the click, even when moved rather than recreated).\n const toggleRow = useRef<HTMLDivElement>(null);\n const followHeader = useRef<ResizeObserver | undefined>(undefined);\n const headerSlot = useCallback((space: HTMLElement | null) => {\n followHeader.current?.disconnect(); followHeader.current = undefined;\n const header = space?.parentElement;\n if (!header || typeof ResizeObserver === 'undefined') return;\n followHeader.current = new ResizeObserver(() => { if (toggleRow.current) toggleRow.current.style.height = `${header.clientHeight}px`; });\n followHeader.current.observe(header);\n }, []);\n const toggleSpace = toggle && <Button ref={headerSlot} size=\"icon-sm\" aria-hidden=\"true\" tabIndex={-1} className=\"invisible -ml-1\" />;\n\n // ---- The chat in the center: docked PiChat, or the host's floating surface over the same controller (with the toggle in its header).\n const header = typeof controls === 'function' ? controls({ panelOpen }) : controls ?? chat.controls;\n const chatProps: PiChatProps | undefined = controller && { ...(mentionsForChat ? { mentions: mentionsForChat } : {}), ...(attachments ? { attachments } : {}), ...(locale ? { locale } : {}), ...chat, controller, artifacts, ...(conversations ? { conversations, historyList: false } : {}),\n headerStart: <>{toggle}{chat.headerStart}</>, ...(header === undefined ? {} : { controls: header }) };\n const docked_chat = <div data-testid=\"workspace-center\" className=\"flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden\">\n {attachmentFailure?.tree === fileTree && attachmentFailure?.reasons.map((reason, index) => <p key={index} role=\"alert\" className=\"m-0 px-4 py-2 text-sm\">{reason}</p>)}\n {fileTree && <UploadNotice controller={fileTree} onOpen={revealLibrary} />}\n {chatTop}\n <div className=\"relative flex min-h-0 flex-1 flex-col\">\n {chatProps ? <PiChat key={conversationId} {...chatProps} headerStart={<>{toggleSpace}{chat.headerStart}</>} className={cn('min-h-0 flex-1', chat.className)} />\n // Same geometry as the PiChat header, so nothing moves when the chat arrives.\n : <>{toggle && <div className=\"flex shrink-0 items-center gap-2 border-b border-border px-3 py-2 sm:gap-3 sm:px-4 sm:py-2.5\">{toggleSpace}</div>}{connecting}</>}\n {toggle && <div ref={toggleRow} className=\"pointer-events-none absolute top-0 left-0 z-10 flex items-center px-3 sm:px-4 [&>*]:pointer-events-auto\">{toggle}</div>}\n </div>\n </div>;\n\n const kind = active ? 'artifact' : file ? 'file' : host?.kind;\n const shown = active ?? file ?? host;\n const actionsFor = (floatChat: (() => void) | undefined): readonly BlockAction[] => [\n ...(librarySide ? [{ id: 'library', label: text.labels.library, icon: text.icons.library, pressed: sideOpen, onSelect: toggleSide }] : []),\n ...(floatChat ? [{ id: 'float-chat', label: text.labels.floatChat, icon: text.icons.floatChat, placement: 'menu' as const, onSelect: floatChat }] : []),\n ...(shown ? typeof panelActions === 'function' ? panelActions(shown) : panelActions ?? [] : []),\n ];\n return <AppTextProvider value={text}><ChatTextProvider value={chatText}><div ref={root} data-boring=\"agent-workspace\" data-sessions={!hasNavigation ? undefined : narrow ? (drawer ? 'drawer' : 'closed') : docked ? 'docked' : 'hidden'}\n className={cn('relative flex h-full min-h-0 min-w-0 flex-1 overflow-hidden', className)}>\n <DockLayout storageKey={`${storageKey}.dock`} minMain={SESSIONS_WIDTH + 480}>\n {hasNavigation && (docked || (narrow && drawer)) && <SessionsPane conversations={conversations} drawer={narrow} onClose={() => setDrawer(false)} onChat={() => setCenterMode('chat')}\n agents={agents} view={paneView} onViewChange={changePaneView}\n {...(librarySide ? { library: { selected: sideOpen, onSelect: toggleSide, side: true } } : revisionProvider && !libraryInPane ? { library: { selected: libraryOpen, onSelect: openLibrary } } : {})}\n {...(libraryInPane ? { libraryContent: (onPicked: () => void) => libraryTree(path => { openFile(path); onPicked(); }) } : {})} />}\n <DockMain><ArtifactWorkspace open={panelOpen} onClose={close} panelLabel={text.labels.artifactPanel} labels={{ resize: text.labels.resizePanel, floatHint: text.labels.floatHint }} fullscreen={fullscreen} onFullscreenChange={setFullscreen} storageKey={`${storageKey}.panel-width`}\n sheetBelow={docked ? Math.max(0, sheetBelow - SESSIONS_WIDTH) : sheetBelow} {...(floatBelow === undefined || libraryOpen ? {} : { floatBelow })}\n chat={layout => <WorkspaceCenter libraryOpen={libraryOpen} floating={layout.floating} chat={docked_chat}\n floatingChat={floatingChat && chatProps ? floatingChat(chatProps, layout.dock) : undefined}\n // With the Library in the pane, the center holds only the chat (no second, hidden toggle or tree).\n library={libraryInPane || librarySide ? null : <section data-testid=\"workspace-library-view\" aria-label={text.labels.library} className=\"flex min-h-0 flex-1 flex-col\">\n <header className=\"flex shrink-0 items-center gap-2 border-b border-border px-3 py-2\">{toggle}<h2 className=\"m-0 flex-1 text-sm font-semibold\">{text.labels.library}</h2>\n <Button variant=\"ghost\" size=\"sm\" onClick={() => setCenterMode('chat')}>{text.labels.backToChat}</Button></header>\n <div className=\"min-h-0 flex-1 overflow-auto\">{libraryTree(openFile)}</div>\n </section>} />}\n panel={win => <ViewerWindowProvider value={{ fullscreen: win.fullscreen, onFullscreenChange: win.onFullscreenChange, actions: actionsFor(win.floatChat), labels: text.labels, icons: text.icons }}>\n <div data-testid=\"viewer-panel\" data-kind={kind} className=\"flex min-h-0 flex-1 flex-col overflow-hidden [&>*]:min-h-0 [&>*]:flex-1\">\n {active\n ? <ArtifactPanel key={artifactKey(active.descriptor)} active={active} versions={newestOf(artifactKey(active.descriptor))} options={options} onClose={win.close}\n onSelect={value => {\n const known = newestOf(artifactKey(active.descriptor));\n setOpened({ kind: 'artifact', conversation: active.conversation, follow: value === 'latest', descriptor: value === 'latest' ? (known[0] ?? active.descriptor) : { ...active.descriptor, revision: value } });\n }} />\n : file ? <FileViewer key={JSON.stringify([revisionProvider?.workspace, identity, file.path])} onUnsavedChange={noteUnsaved} path={file.path} locator={locate(file.path)} options={options} onClose={win.close} {...(fileBack ? { onBack: fileBack.onBack, backLabel: fileBack.label } : {})} />\n : host ? panels![host.kind]!(host, win) : null}\n </div></ViewerWindowProvider>} /></DockMain>\n {librarySide && <Dock id=\"library\" side=\"right\" open={sideOpen} onOpenChange={setSideOpen} defaultWidth={LIBRARY_WIDTH} minWidth={240} narrowBelow={Math.max(drawerBelow, (docked ? SESSIONS_WIDTH : 0) + (panelOpen ? VIEWER_MIN + CHAT_MIN : CHAT_MIN) + libraryWidth)} narrow=\"sheet\"\n labels={{ region: text.labels.library, resize: text.labels.resizePanel }} className=\"border-l border-border\">\n {api => <section data-testid=\"workspace-library-side\" aria-label={text.labels.library} className=\"flex min-h-0 flex-1 flex-col\">\n <WidthProbe width={api.width} onWidth={setLibraryWidth} />\n <header className=\"flex shrink-0 items-center gap-2 border-b border-border px-3 py-2\"><h2 className=\"m-0 min-w-0 flex-1 truncate text-sm font-semibold\">{text.labels.library}</h2>\n <Button size=\"icon-sm\" variant=\"ghost\" aria-label={text.labels.close} title={text.labels.close} data-testid=\"workspace-library-close\" onClick={() => setSideOpen(false)}><text.icons.closeSessions className=\"size-4\" aria-hidden=\"true\" /></Button></header>\n <div className=\"min-h-0 flex-1 overflow-auto\">{libraryTree(path => { if (setOpened({ kind: 'file', path }) && narrow) setSideOpen(false); })}</div>\n </section>}\n </Dock>}\n </DockLayout>\n </div></ChatTextProvider></AppTextProvider>;\n}\n\nfunction WidthProbe({ width, onWidth }: { readonly width: number; readonly onWidth: (width: number) => void }) {\n useLayoutEffect(() => { onWidth(width); }, [width, onWidth]);\n return null;\n}\n\nfunction UploadNotice({ controller, onOpen }: { readonly controller: FileTreeController; readonly onOpen: () => void }) {\n const state = useSyncExternalStore(controller.subscribe, controller.getSnapshot, controller.getSnapshot);\n const failures = state.uploads.filter(upload => upload.state.kind === 'settled' && upload.state.result.kind !== 'committed');\n return failures.length ? <p role=\"alert\" className=\"m-0 px-4 py-2 text-sm\">{failures.length} upload{failures.length === 1 ? '' : 's'} need attention. <button type=\"button\" className=\"underline\" onClick={onOpen}>Open Library</button> to review the results and check unconfirmed uploads.</p> : null;\n}\n\n/** Keep the selected chat surface mounted while Library temporarily uses its layout space. */\nfunction WorkspaceCenter({ libraryOpen, floating, chat, floatingChat, library }: {\n readonly libraryOpen: boolean;\n readonly floating: boolean;\n readonly chat: ReactNode;\n readonly floatingChat: ReactNode;\n readonly library: ReactNode;\n}) {\n const lastFloating = useRef(floating);\n useLayoutEffect(() => { if (!libraryOpen) lastFloating.current = floating; }, [libraryOpen, floating]);\n const showFloating = libraryOpen ? lastFloating.current : floating;\n return <div className=\"flex min-h-0 flex-1 flex-col\">\n <div data-testid=\"workspace-chat-surface\" hidden={libraryOpen} inert={libraryOpen} aria-hidden={libraryOpen || undefined} className={cn('min-h-0 flex-1 flex-col', libraryOpen ? 'hidden' : 'flex')}>\n {showFloating && floatingChat ? floatingChat : chat}\n </div>\n <div hidden={!libraryOpen} inert={!libraryOpen} aria-hidden={!libraryOpen || undefined} className={cn('min-h-0 flex-1 flex-col', libraryOpen ? 'flex' : 'hidden')}>{library}</div>\n </div>;\n}\n\n/**\n * The seq of the provider's latest change event (`RevisionProvider.changes`), coalesced over `settleMs` so a burst (a shell writing\n * many files) reloads once. `live` is false without a feed or after the feed was refused; views then keep their own refresh.\n */\nfunction useChangeFeed(provider: RevisionProvider | undefined, settleMs = 150): { readonly seq: number | undefined; readonly live: boolean } {\n const [state, setState] = useState<{ readonly provider: RevisionProvider | undefined; readonly seq: number | undefined; readonly live: boolean }>({ provider, seq: undefined, live: false });\n useEffect(() => {\n if (!provider?.changes) { setState({ provider, seq: undefined, live: false }); return; }\n const stop = new AbortController();\n let timer: ReturnType<typeof setTimeout> | undefined, latest: number | undefined;\n setState({ provider, seq: undefined, live: true });\n void (async () => {\n try {\n for await (const event of provider.changes!({ signal: stop.signal })) {\n latest = event.seq;\n timer ??= setTimeout(() => { timer = undefined; if (!stop.signal.aborted) setState({ provider, seq: latest, live: true }); }, settleMs);\n }\n } catch { /* refused: the views fall back to their own refresh */ }\n clearTimeout(timer);\n timer = undefined;\n if (!stop.signal.aborted) setState({ provider, seq: latest, live: false });\n })();\n return () => { stop.abort(); clearTimeout(timer); };\n }, [provider, settleMs]);\n return state.provider === provider ? state : { seq: undefined, live: false };\n}\n",
|
|
26
26
|
"type": "registry:component",
|
|
27
27
|
"target": "components/pi-app/agent-workspace.tsx"
|
|
28
28
|
},
|
|
@@ -82,7 +82,7 @@
|
|
|
82
82
|
},
|
|
83
83
|
{
|
|
84
84
|
"path": "registry/pi-app/revision-files.ts",
|
|
85
|
-
"content": "import { uploadPath } from '@hachej/boring-files/file-types';\nimport { randomUUID } from '@hachej/boring-files/platform';\nimport type { FileTreeController } from '@hachej/boring-ui-kit/file-tree';\nimport type { UploadResult } from '../pi-chat/config';\n\
|
|
85
|
+
"content": "import { uploadPath } from '@hachej/boring-files/file-types';\nimport { randomUUID } from '@hachej/boring-files/platform';\nimport type { FileTreeController } from '@hachej/boring-ui-kit/file-tree';\nimport type { UploadResult } from '../pi-chat/config';\n\nexport function imageData(bytes: Uint8Array): string {\n let binary = '';\n for (let offset = 0; offset < bytes.length; offset += 32768) binary += String.fromCharCode(...bytes.subarray(offset, offset + 32768));\n return btoa(binary);\n}\n\n/**\n * What a chat upload may do. `inlineImages` also sends a png, jpeg, gif or webp as a native image in the message (off by default: the\n * file is saved and the message carries only its `@path`, which the agent reads with a tool, so no base64 rides along in every later\n * turn). `maxBytes` refuses a larger file before it is read or uploaded, with `tooLarge` as the reason shown beside the other failures.\n * `accept` is the picker's MIME/extension list: a file of another type is refused too (a drop or a paste does not pass the picker).\n */\nexport interface AttachmentPolicy { readonly inlineImages?: boolean | undefined; readonly maxBytes?: number | undefined; readonly tooLarge?: string | undefined; readonly accept?: string | undefined }\n\n/** Whether a file passes a picker's `accept` list: `image/*`, an exact MIME type or an extension such as `.pdf`. An empty list accepts any file. */\nexport function acceptsFile(file: { readonly name: string; readonly type: string }, accept: string): boolean {\n const name = file.name.toLowerCase(), type = file.type.toLowerCase();\n const tokens = accept.split(',').map(token => token.trim().toLowerCase()).filter(Boolean);\n return tokens.length === 0 || tokens.some(token => token.startsWith('.') ? name.endsWith(token) : token.endsWith('/*') ? type.startsWith(token.slice(0, -1)) : type === token);\n}\n\n/**\n * Where a chat attachment is saved: its name with a short random suffix, so a second `image.png` (every pasted screenshot has that\n * name) or the same file attached again is a new file beside the first instead of a refused overwrite. The name has no whitespace,\n * because a chat mention ends at a space: each run of whitespace becomes `_`.\n */\nexport function attachmentPath(name: string): string {\n return uploadPath(name, randomUUID().slice(0, 8));\n}\n\n/** Successful files remain attached when another file is refused; every outcome remains visible in the shared file tree. */\nexport async function uploadRevisionAttachments(controller: FileTreeController, files: readonly File[], signal: AbortSignal, onPreparationFailure?: (name: string, reason: string) => void, policy: AttachmentPolicy = {}): Promise<readonly UploadResult[]> {\n const uploaded: UploadResult[] = [];\n let reason = 'No files were saved. Open Files to review the uploads.';\n for (const file of files) {\n if (signal.aborted) break;\n if (policy.maxBytes !== undefined && file.size > policy.maxBytes) { reason = policy.tooLarge ?? 'The file is too large to attach.'; onPreparationFailure?.(file.name, reason); continue; }\n if (policy.accept && !acceptsFile(file, policy.accept)) { reason = 'This file type is not accepted.'; onPreparationFailure?.(file.name, reason); continue; }\n try {\n const path = attachmentPath(file.name), bytes = new Uint8Array(await file.arrayBuffer());\n const upload = await controller.upload({ path, bytes, mediaType: file.type || 'application/octet-stream', signal });\n if (upload.state.kind === 'settled' && upload.state.result.kind === 'committed') {\n uploaded.push({ path, name: file.name, ...(policy.inlineImages && /^image\\/(png|jpeg|gif|webp)$/.test(file.type) ? { image: { data: imageData(bytes), mimeType: file.type } } : {}) });\n } else if (upload.state.kind === 'settled' && 'reason' in upload.state.result) reason = upload.state.result.reason;\n } catch (error) { reason = error instanceof Error ? error.message : 'Upload failed'; onPreparationFailure?.(file.name, reason); }\n }\n if (!uploaded.length) throw new Error(reason);\n return uploaded;\n}\n",
|
|
86
86
|
"type": "registry:lib",
|
|
87
87
|
"target": "components/pi-app/revision-files.ts"
|
|
88
88
|
},
|