@hachej/boring-ui-kit 0.2.2 → 0.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/r/pi-app.json CHANGED
@@ -4,42 +4,42 @@
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.2.2",
8
- "@hachej/boring-files@^0.2.2",
7
+ "@hachej/boring-ui-kit@^0.2.4",
8
+ "@hachej/boring-files@^0.2.4",
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
- "@boring-ui/pi-chat",
16
- "@boring-ui/pi-workspace",
17
- "@boring-ui/viewers",
18
- "@boring-ui/utils",
19
- "@boring-ui/button"
15
+ "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.2.4/r/pi-chat.json",
16
+ "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.2.4/r/pi-workspace.json",
17
+ "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.2.4/r/viewers.json",
18
+ "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.2.4/r/utils.json",
19
+ "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.2.4/r/button.json"
20
20
  ],
21
21
  "files": [
22
22
  {
23
23
  "path": "registry/pi-app/agent-workspace.tsx",
24
- "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 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 type { ArtifactDescriptor, ArtifactsConfig, ConversationsConfig, PiChatProps } from '../pi-chat/pi-chat';\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 { uploadRevisionAttachments } 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 './use-remote-chat';\nexport type { RemoteChatState } from './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\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. `center` (default): 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?: '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\nconst SESSIONS_WIDTH = 288;\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 = 'center', 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 libraryOpen = Boolean(revisionProvider) && !libraryInPane && 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 const options: ViewerOptions = useMemo(() => ({ client, identity, history, viewers, interactive, share }), [client, identityKey, history, viewers, interactive, share]); // 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 attachments = useMemo(() => fileTree ? {\n ...(uploadAccept !== undefined ? { accept: uploadAccept } : {}),\n upload: (files: File[], signal: AbortSignal) => {\n setAttachmentFailure(undefined);\n return uploadRevisionAttachments(fileTree, files, signal, (name, reason) => {\n if (fileTree.getSnapshot().lifecycle === 'active') setAttachmentFailure(current => ({ tree: fileTree,\n reasons: [...(current?.tree === fileTree ? current.reasons : []), `${name}: ${reason}`] }));\n }, { inlineImages, ...(maxBytes !== undefined ? { maxBytes, tooLarge } : {}) });\n },\n } : undefined, [fileTree, uploadAccept, inlineImages, maxBytes, tooLarge]);\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 /** 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 (!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 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 ...(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 {hasNavigation && (docked || (narrow && drawer)) && <SessionsPane conversations={conversations} drawer={narrow} onClose={() => setDrawer(false)} onChat={() => setCenterMode('chat')}\n agents={agents} view={paneView} onViewChange={changePaneView}\n {...(revisionProvider && !libraryInPane ? { library: { selected: libraryOpen, onSelect: openLibrary } } : {})}\n {...(libraryInPane ? { libraryContent: (onPicked: () => void) => fileTree\n ? <FileTreeView key={JSON.stringify([revisionProvider?.workspace, revisionProvider?.identity])} {...(locale ? { locale } : {})} {...viewOptions} controller={fileTree} historyKey={feed.seq} onOpen={path => { openFile(path); onPicked(); }} {...(isFile(opened) ? { selectedPath: opened.path } : {})} />\n : <p role=\"status\" className=\"m-0 p-3 text-sm text-muted-foreground\">{text.labels.loading}</p> } : {})} />}\n <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 ? 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\">{fileTree ? <FileTreeView key={JSON.stringify([revisionProvider?.workspace, revisionProvider?.identity])} {...(locale ? { locale } : {})} {...viewOptions} controller={fileTree} historyKey={feed.seq} onOpen={openFile} {...(isFile(opened) ? { selectedPath: opened.path } : {})} /> : <p role=\"status\">{treeOptions?.labels?.loading ?? text.labels.loading}</p>}</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>} />\n </div></ChatTextProvider></AppTextProvider>;\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",
24
+ "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 { uploadRevisionAttachments } 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 } : 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 attachments = useMemo(() => fileTree ? {\n ...(uploadAccept !== undefined ? { accept: uploadAccept } : {}),\n upload: (files: File[], signal: AbortSignal) => {\n setAttachmentFailure(undefined);\n return uploadRevisionAttachments(fileTree, files, signal, (name, reason) => {\n if (fileTree.getSnapshot().lifecycle === 'active') setAttachmentFailure(current => ({ tree: fileTree,\n reasons: [...(current?.tree === fileTree ? current.reasons : []), `${name}: ${reason}`] }));\n }, { inlineImages, ...(maxBytes !== undefined ? { maxBytes, tooLarge } : {}) });\n },\n } : undefined, [fileTree, uploadAccept, inlineImages, maxBytes, tooLarge]);\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
25
  "type": "registry:component",
26
26
  "target": "components/pi-app/agent-workspace.tsx"
27
27
  },
28
28
  {
29
29
  "path": "registry/pi-app/sessions.tsx",
30
- "content": "'use client';\n\nimport { useEffect } from 'react';\nimport type { ReactNode } from 'react';\nimport { Button } from '../button/button';\nimport { useAppText } from './app-labels';\nimport { ConversationList } from '../pi-chat/pi-chat';\nimport type { ConversationsConfig } from '../pi-chat/pi-chat';\nimport { cn } from '../utils/utils';\n\n/** One agent the person can talk to; the pane shows a switcher when there are two or more. */\nexport interface WorkspaceAgent { readonly id: string; readonly label: string; readonly description?: string | undefined }\n/** The page's agents and the chosen one. The host scopes `conversations` and the controller to `activeId`. */\nexport interface WorkspaceAgents { readonly items: readonly WorkspaceAgent[]; readonly activeId: string; readonly onSelect: (id: string) => void }\nexport type SessionsView = 'conversations' | 'library';\n\n/**\n * The sessions pane: a title with New, then the searchable conversation list of `pi-chat` (`ConversationList`: search, Archived filter,\n * rename, archive, delete). Docked at the left on a wide screen; a drawer over the page with a backdrop on a narrow one, closed by\n * Escape, the backdrop, the close button or choosing a conversation. `library` adds Chat and Library links (the Library opens in the\n * center); `libraryContent` instead shows the library in the pane, as a tab beside the conversations or alone without them. With two\n * or more `agents`, a switcher at the top chooses whose conversations are listed.\n */\nexport function SessionsPane({ conversations, title: givenTitle, drawer, onClose, library, onChat, libraryContent, view = 'conversations', onViewChange, agents }: {\n readonly conversations?: ConversationsConfig | undefined;\n readonly library?: { readonly selected: boolean; readonly onSelect: () => void } | undefined;\n readonly onChat?: (() => void) | undefined;\n /** The library shown in the pane; invoke onPicked after opening a file to close a mobile drawer. */\n readonly libraryContent?: ((onPicked: () => void) => ReactNode) | undefined;\n /** Which tab is shown when the pane has both conversations and `libraryContent`. */\n readonly view?: SessionsView | undefined;\n readonly onViewChange?: ((view: SessionsView) => void) | undefined;\n readonly agents?: WorkspaceAgents | undefined;\n readonly title?: string;\n /** Rendered as a drawer (narrow screens). */\n readonly drawer: boolean;\n /** Closes the drawer; absent when docked. */\n readonly onClose?: (() => void) | undefined;\n}) {\n const { labels, icons } = useAppText();\n const title = givenTitle ?? (conversations || !libraryContent ? labels.sessionsTitle : labels.library);\n useEffect(() => {\n if (!drawer || !onClose) return;\n const escape = (event: KeyboardEvent) => { if (event.key === 'Escape' && !event.defaultPrevented) onClose(); };\n document.addEventListener('keydown', escape);\n return () => document.removeEventListener('keydown', escape);\n }, [drawer, onClose]);\n const picked = () => { onChat?.(); if (drawer) onClose?.(); };\n const tabs = Boolean(libraryContent && conversations);\n const shown: SessionsView = !conversations && libraryContent ? 'library' : tabs ? view : 'conversations';\n const switcher = agents && agents.items.length > 1;\n const close = drawer && onClose && <Button size=\"icon-sm\" variant=\"ghost\" aria-label={library || libraryContent ? labels.closeNavigation : labels.closeSessions} title={labels.close} data-testid=\"sessions-close\" onClick={onClose}><icons.closeSessions className=\"size-4\" aria-hidden=\"true\" /></Button>;\n return <>\n {drawer && <button type=\"button\" tabIndex={-1} aria-hidden=\"true\" data-testid=\"sessions-backdrop\" onClick={onClose} className=\"fixed inset-0 z-40 cursor-default bg-black/40\" />}\n <aside data-testid=\"conversations\" data-drawer={drawer ? 'true' : 'false'} aria-label={title} {...(drawer ? { role: 'dialog', 'aria-modal': true } : {})}\n className={cn('pi-chat flex min-h-0 flex-col bg-background text-foreground', drawer\n ? 'fixed inset-y-0 left-0 z-50 w-[min(20rem,85vw)] border-r border-border shadow-xl pt-[env(safe-area-inset-top)] pb-[env(safe-area-inset-bottom)]'\n : 'w-72 shrink-0 border-r border-border')}>\n {switcher && <div className=\"flex shrink-0 items-center gap-2 border-b border-border px-3 py-2\">\n <label className=\"flex min-w-0 flex-1 items-center gap-2 text-xs text-muted-foreground\">\n <span className=\"shrink-0\">{labels.agent}</span>\n <select data-testid=\"agent-select\" value={agents.activeId} onChange={event => agents.onSelect(event.target.value)}\n className=\"h-8 min-w-0 flex-1 cursor-pointer truncate rounded-md border border-border bg-background px-2 text-sm font-medium text-foreground\">\n {agents.items.map(agent => <option key={agent.id} value={agent.id} title={agent.description}>{agent.label}</option>)}\n </select>\n </label>\n {close}\n </div>}\n <header className=\"flex shrink-0 items-center gap-2 border-b border-border px-3 py-2\">\n {tabs\n ? <div role=\"tablist\" aria-label={title} className=\"flex min-w-0 flex-1 items-center gap-0.5 rounded-lg bg-muted p-0.5\">\n {(['conversations', 'library'] as const).map(tab => <button key={tab} type=\"button\" role=\"tab\" data-testid={`sessions-tab-${tab}`} aria-selected={shown === tab} onClick={() => onViewChange?.(tab)}\n className={cn('h-7 min-w-0 flex-1 cursor-pointer truncate rounded-md px-2 text-[13px] font-medium', shown === tab ? 'bg-background text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground')}>\n {tab === 'library' ? labels.library : title}\n </button>)}\n </div>\n : <h2 className=\"m-0 min-w-0 flex-1 truncate text-sm font-semibold tracking-tight\">{title}</h2>}\n {conversations?.onNew && shown === 'conversations' && (tabs\n ? <Button size=\"icon-sm\" variant=\"outline\" data-testid=\"conversation-new\" aria-label={labels.newChat} title={labels.newChat} onClick={() => { conversations.onNew?.(); picked(); }}><icons.newChat className=\"size-3.5\" aria-hidden=\"true\" /></Button>\n : <Button size=\"sm\" variant=\"outline\" data-testid=\"conversation-new\" onClick={() => { conversations.onNew?.(); picked(); }}><icons.newChat className=\"size-3.5\" aria-hidden=\"true\" />{labels.newChat}</Button>)}\n {!switcher && close}\n </header>\n {library && <nav aria-label={labels.workspaceNavigation} className=\"flex shrink-0 flex-col gap-1 border-b border-border p-2\">\n <Button variant=\"ghost\" data-testid=\"workspace-chat-link\" aria-current={!library.selected ? 'page' : undefined} className=\"justify-start\" onClick={picked}><icons.chat className=\"size-4\" aria-hidden=\"true\" />{labels.chat}</Button>\n <Button variant=\"ghost\" data-testid=\"workspace-library\" aria-current={library.selected ? 'page' : undefined} className=\"justify-start\" onClick={() => { library.onSelect(); if (drawer) onClose?.(); }}><icons.library className=\"size-4\" aria-hidden=\"true\" />{labels.library}</Button>\n </nav>}\n {shown === 'library' && libraryContent\n ? <div {...(tabs ? { role: 'tabpanel' } : {})} data-testid=\"sessions-library\" className=\"flex min-h-0 flex-1 flex-col overflow-auto\">{libraryContent(() => { if (drawer) onClose?.(); })}</div>\n : conversations && <ConversationList conversations={conversations} onPicked={picked} />}\n </aside>\n </>;\n}\n\n/** The chat header's button that shows or hides the sessions pane (opens the drawer on a narrow screen). */\nexport function SessionsToggle({ open, drawer, onToggle, navigation = false }: { readonly open: boolean; readonly drawer: boolean; readonly onToggle: () => void; readonly navigation?: boolean }) {\n const { labels, icons } = useAppText();\n const label = navigation ? drawer ? labels.openNavigation : open ? labels.hideNavigation : labels.showNavigation\n : drawer ? labels.openSessions : open ? labels.hideSessions : labels.showSessions;\n return <Button size=\"icon-sm\" variant=\"ghost\" data-testid=\"sessions-toggle\" aria-label={label} title={label} aria-expanded={open} onClick={onToggle} className=\"-ml-1 shrink-0 text-muted-foreground\">\n <icons.sessionsToggle className=\"size-4\" aria-hidden=\"true\" />\n </Button>;\n}\n",
30
+ "content": "'use client';\n\nimport { useEffect } from 'react';\nimport type { ReactNode } from 'react';\nimport { Button } from '../button/button';\nimport { useAppText } from './app-labels';\nimport { ConversationList } from '../pi-chat/pi-chat';\nimport type { ConversationsConfig } from '../pi-chat/pi-chat';\nimport { cn } from '../utils/utils';\n\n/** One agent the person can talk to; the pane shows a switcher when there are two or more. */\nexport interface WorkspaceAgent { readonly id: string; readonly label: string; readonly description?: string | undefined }\n/** The page's agents and the chosen one. The host scopes `conversations` and the controller to `activeId`. */\nexport interface WorkspaceAgents { readonly items: readonly WorkspaceAgent[]; readonly activeId: string; readonly onSelect: (id: string) => void }\nexport type SessionsView = 'conversations' | 'library';\n\n/**\n * The sessions pane: a title with New, then the searchable conversation list of `pi-chat` (`ConversationList`: search, Archived filter,\n * rename, archive, delete). Docked at the left on a wide screen; a drawer over the page with a backdrop on a narrow one, closed by\n * Escape, the backdrop, the close button or choosing a conversation. `library` adds Chat and Library links (the Library opens in the\n * center); `libraryContent` instead shows the library in the pane, as a tab beside the conversations or alone without them. With two\n * or more `agents`, a switcher at the top chooses whose conversations are listed.\n */\nexport function SessionsPane({ conversations, title: givenTitle, drawer, onClose, library, onChat, libraryContent, view = 'conversations', onViewChange, agents }: {\n readonly conversations?: ConversationsConfig | undefined;\n /** `side`: the Library is a column beside the viewer, so the button toggles it (`aria-pressed`) and the chat stays current. */\n readonly library?: { readonly selected: boolean; readonly onSelect: () => void; readonly side?: boolean } | undefined;\n readonly onChat?: (() => void) | undefined;\n /** The library shown in the pane; invoke onPicked after opening a file to close a mobile drawer. */\n readonly libraryContent?: ((onPicked: () => void) => ReactNode) | undefined;\n /** Which tab is shown when the pane has both conversations and `libraryContent`. */\n readonly view?: SessionsView | undefined;\n readonly onViewChange?: ((view: SessionsView) => void) | undefined;\n readonly agents?: WorkspaceAgents | undefined;\n readonly title?: string;\n /** Rendered as a drawer (narrow screens). */\n readonly drawer: boolean;\n /** Closes the drawer; absent when docked. */\n readonly onClose?: (() => void) | undefined;\n}) {\n const { labels, icons } = useAppText();\n const title = givenTitle ?? (conversations || !libraryContent ? labels.sessionsTitle : labels.library);\n useEffect(() => {\n if (!drawer || !onClose) return;\n const escape = (event: KeyboardEvent) => { if (event.key === 'Escape' && !event.defaultPrevented) onClose(); };\n document.addEventListener('keydown', escape);\n return () => document.removeEventListener('keydown', escape);\n }, [drawer, onClose]);\n const picked = () => { onChat?.(); if (drawer) onClose?.(); };\n const tabs = Boolean(libraryContent && conversations);\n const shown: SessionsView = !conversations && libraryContent ? 'library' : tabs ? view : 'conversations';\n const switcher = agents && agents.items.length > 1;\n const close = drawer && onClose && <Button size=\"icon-sm\" variant=\"ghost\" aria-label={library || libraryContent ? labels.closeNavigation : labels.closeSessions} title={labels.close} data-testid=\"sessions-close\" onClick={onClose}><icons.closeSessions className=\"size-4\" aria-hidden=\"true\" /></Button>;\n return <>\n {drawer && <button type=\"button\" tabIndex={-1} aria-hidden=\"true\" data-testid=\"sessions-backdrop\" onClick={onClose} className=\"fixed inset-0 z-40 cursor-default bg-black/40\" />}\n <aside data-testid=\"conversations\" data-drawer={drawer ? 'true' : 'false'} aria-label={title} {...(drawer ? { role: 'dialog', 'aria-modal': true } : {})}\n className={cn('pi-chat flex min-h-0 flex-col bg-background text-foreground', drawer\n ? 'fixed inset-y-0 left-0 z-50 w-[min(20rem,85vw)] border-r border-border shadow-xl pt-[env(safe-area-inset-top)] pb-[env(safe-area-inset-bottom)]'\n : 'w-72 shrink-0 border-r border-border')}>\n {switcher && <div className=\"flex shrink-0 items-center gap-2 border-b border-border px-3 py-2\">\n <label className=\"flex min-w-0 flex-1 items-center gap-2 text-xs text-muted-foreground\">\n <span className=\"shrink-0\">{labels.agent}</span>\n <select data-testid=\"agent-select\" value={agents.activeId} onChange={event => agents.onSelect(event.target.value)}\n className=\"h-8 min-w-0 flex-1 cursor-pointer truncate rounded-md border border-border bg-background px-2 text-sm font-medium text-foreground\">\n {agents.items.map(agent => <option key={agent.id} value={agent.id} title={agent.description}>{agent.label}</option>)}\n </select>\n </label>\n {close}\n </div>}\n <header className=\"flex shrink-0 items-center gap-2 border-b border-border px-3 py-2\">\n {tabs\n ? <div role=\"tablist\" aria-label={title} className=\"flex min-w-0 flex-1 items-center gap-0.5 rounded-lg bg-muted p-0.5\">\n {(['conversations', 'library'] as const).map(tab => <button key={tab} type=\"button\" role=\"tab\" data-testid={`sessions-tab-${tab}`} aria-selected={shown === tab} onClick={() => onViewChange?.(tab)}\n className={cn('h-7 min-w-0 flex-1 cursor-pointer truncate rounded-md px-2 text-[13px] font-medium', shown === tab ? 'bg-background text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground')}>\n {tab === 'library' ? labels.library : title}\n </button>)}\n </div>\n : <h2 className=\"m-0 min-w-0 flex-1 truncate text-sm font-semibold tracking-tight\">{title}</h2>}\n {conversations?.onNew && shown === 'conversations' && (tabs\n ? <Button size=\"icon-sm\" variant=\"outline\" data-testid=\"conversation-new\" aria-label={labels.newChat} title={labels.newChat} onClick={() => { conversations.onNew?.(); picked(); }}><icons.newChat className=\"size-3.5\" aria-hidden=\"true\" /></Button>\n : <Button size=\"sm\" variant=\"outline\" data-testid=\"conversation-new\" onClick={() => { conversations.onNew?.(); picked(); }}><icons.newChat className=\"size-3.5\" aria-hidden=\"true\" />{labels.newChat}</Button>)}\n {!switcher && close}\n </header>\n {library && <nav aria-label={labels.workspaceNavigation} className=\"flex shrink-0 flex-col gap-1 border-b border-border p-2\">\n <Button variant=\"ghost\" data-testid=\"workspace-chat-link\" aria-current={library.side || !library.selected ? 'page' : undefined} className=\"justify-start\" onClick={picked}><icons.chat className=\"size-4\" aria-hidden=\"true\" />{labels.chat}</Button>\n <Button variant=\"ghost\" data-testid=\"workspace-library\" {...(library.side ? { 'aria-pressed': library.selected } : { 'aria-current': library.selected ? 'page' : undefined })} className=\"justify-start\" onClick={() => { library.onSelect(); if (drawer) onClose?.(); }}><icons.library className=\"size-4\" aria-hidden=\"true\" />{labels.library}</Button>\n </nav>}\n {shown === 'library' && libraryContent\n ? <div {...(tabs ? { role: 'tabpanel' } : {})} data-testid=\"sessions-library\" className=\"flex min-h-0 flex-1 flex-col overflow-auto\">{libraryContent(() => { if (drawer) onClose?.(); })}</div>\n : conversations && <ConversationList conversations={conversations} onPicked={picked} />}\n </aside>\n </>;\n}\n\n/** The chat header's button that shows or hides the sessions pane (opens the drawer on a narrow screen). */\nexport function SessionsToggle({ open, drawer, onToggle, navigation = false }: { readonly open: boolean; readonly drawer: boolean; readonly onToggle: () => void; readonly navigation?: boolean }) {\n const { labels, icons } = useAppText();\n const label = navigation ? drawer ? labels.openNavigation : open ? labels.hideNavigation : labels.showNavigation\n : drawer ? labels.openSessions : open ? labels.hideSessions : labels.showSessions;\n return <Button size=\"icon-sm\" variant=\"ghost\" data-testid=\"sessions-toggle\" aria-label={label} title={label} aria-expanded={open} onClick={onToggle} className=\"-ml-1 shrink-0 text-muted-foreground\">\n <icons.sessionsToggle className=\"size-4\" aria-hidden=\"true\" />\n </Button>;\n}\n",
31
31
  "type": "registry:component",
32
32
  "target": "components/pi-app/sessions.tsx"
33
33
  },
34
34
  {
35
35
  "path": "registry/pi-app/artifact-panel.tsx",
36
- "content": "'use client';\n\n// The artifact panel: the standard viewer bar (title, type, version switcher, Refresh, Share, copy, download, close) over the viewer for\n// the artifact's type. It follows the latest saved revision while nothing is unsaved (\"Latest\") or pins one older version, read-only. It\n// lists the versions the host's workspace provider retains for the file (`history`) and reads through the host's resource client. It never\n// executes artifact content (HTML runs only in the viewers' sandboxed preview when the host passes `interactive`).\nimport { useEffect, useMemo, useState, useSyncExternalStore } from 'react';\nimport type { ReactNode } from 'react';\nimport { CodeXmlIcon, EyeIcon } from 'lucide-react';\nimport { randomUUID } from '@hachej/boring-files/platform';\nimport type { ResourceClient, ResourceSnapshot } from '@hachej/boring-files';\nimport type { ResourceIdentity } from '@hachej/boring-files/remote';\nimport { createMarkdownController } from '@hachej/boring-ui-kit/markdown';\nimport type { MarkdownController } from '@hachej/boring-ui-kit/markdown';\nimport { createHtmlController } from '@hachej/boring-ui-kit/html';\nimport type { HtmlController } from '@hachej/boring-ui-kit/html';\nimport type { NativeChatController } from '@hachej/boring-ui-kit/native-chat';\nimport { artifactKey, collectArtifacts } from '../pi-chat/pi-chat';\nimport type { ArtifactDescriptor, ArtifactTarget, ArtifactsConfig } from '../pi-chat/pi-chat';\nimport { CodeBlock } from '../pi-chat/code-block';\nimport { typeLabel } from '../pi-chat/artifact';\nimport { HtmlPane } from '../viewers/html-pane';\nimport { MarkdownPane } from '../viewers/markdown-pane';\nimport { ViewerFrame, ViewerToggle } from '../viewers/viewer-frame';\nimport type { ViewerFrameProps, ViewerShare } from '../viewers/viewer-frame';\nimport { ViewerVersions } from '../viewers/menu';\nimport type { InteractiveHtml } from '../viewers/interactive-html';\nimport { downloadFile } from '../viewers/download';\nimport { copyText } from '../utils/utils';\nimport { savedLabel, useSaved } from './use-saved';\nimport { useAppText } from './app-labels';\n\nconst NOOP = () => () => {};\nconst POLL_MS = 1500;\nconst EXTENSION = /\\.([A-Za-z0-9]{1,8})$/;\n\n/** One retained revision of a file with its save time (`files.saves(path)` of `@hachej/boring-files/workspace`). */\nexport interface SavedRevision { readonly revision: string; readonly savedAt: number }\n\n/** What a host viewer for an artifact type or file kind the block does not render itself (for example a tldraw canvas) receives. */\nexport interface CustomViewerProps {\n readonly target: ArtifactTarget;\n readonly title: string;\n /** A pinned revision, read-only; absent: follow the latest. */\n readonly revision?: string | undefined;\n /** Pass these on to the `ViewerFrame` around it: test ids, the version switcher or back button, Close, the share target. */\n readonly frame: Pick<ViewerFrameProps, 'testId' | 'titleTestId' | 'controls' | 'onClose' | 'target'>;\n}\n/** Host viewers by artifact type or file kind (`canvas`, or any other). They take precedence over the built-in ones. */\nexport type CustomViewers = Readonly<Record<string, (props: CustomViewerProps) => ReactNode>>;\n\n/** Everything a viewer in the panel reads through: one resource client, the version history, host viewers and policy. */\nexport interface ViewerOptions {\n readonly client: ResourceClient;\n readonly identity: ResourceIdentity;\n readonly history?: ((path: string) => Promise<readonly SavedRevision[]>) | undefined;\n readonly viewers?: CustomViewers | undefined;\n /** The host's opt-in to running HTML pages in the sandboxed preview. */\n readonly interactive?: InteractiveHtml | undefined;\n readonly share?: ViewerShare | undefined;\n}\n\n/** Every artifact version the conversation's tool results produced (the version switcher's source), oldest first. */\nexport function useArtifactVersions(controller: NativeChatController | undefined, detect?: ArtifactsConfig['detect']): ArtifactDescriptor[] {\n const view = useSyncExternalStore(controller ? controller.subscribe : NOOP, () => controller?.getSnapshot().view, () => undefined);\n return useMemo(() => collectArtifacts(view, detect), [view, detect]);\n}\n\n/** How many messages the person has sent in the conversation: it changes when a new turn starts. */\nexport function useTurn(controller: NativeChatController | undefined): number {\n const view = useSyncExternalStore(controller ? controller.subscribe : NOOP, () => controller?.getSnapshot().view, () => undefined);\n return useMemo(() => (view?.entries ?? []).reduce((count, entry) => count + (entry.model ?? []).filter(message => message.role === 'user').length, 0), [view]);\n}\n\n/** The revisions the workspace provider retains for a file with their save times, newest first; followed while the panel is open. */\nfunction useHistory(history: ViewerOptions['history'], path: string): readonly SavedRevision[] {\n const [revisions, setRevisions] = useState<readonly SavedRevision[]>([]);\n useEffect(() => {\n if (!history) return;\n let cancelled = false;\n const key = (saves: readonly SavedRevision[]) => saves.map(save => `${save.revision}@${save.savedAt}`).join();\n const load = () => history(path).then(saves => { if (!cancelled) setRevisions(current => key(current) === key(saves) ? current : saves); }).catch(() => {});\n void load();\n const timer = setInterval(load, POLL_MS);\n return () => { cancelled = true; clearInterval(timer); };\n }, [history, path]);\n return revisions;\n}\n\ninterface VersionMenu {\n readonly items: readonly { readonly id: string; readonly label: string; readonly latest: boolean }[];\n readonly current: string;\n /** Position counted from the oldest retained revision: only a test hook. */\n readonly number: number | undefined;\n readonly savedAt: number | undefined;\n}\n\n/** The version menu, newest first: each retained revision is named by when it was saved, and the newest is \"Latest\". The pin is the revision. */\nfunction versionMenu(artifact: ArtifactDescriptor, follow: boolean, revisions: readonly SavedRevision[], earlier: string): VersionMenu {\n const at = follow ? 0 : revisions.findIndex(save => save.revision === artifact.revision);\n const shown = at < 0 ? undefined : revisions[at];\n return { items: revisions.map((save, index) => ({ id: index === 0 ? 'latest' : save.revision, label: savedLabel(save.savedAt, Date.now(), earlier), latest: index === 0 })),\n current: follow ? 'latest' : artifact.revision, number: shown ? revisions.length - at : undefined, savedAt: shown?.savedAt };\n}\n\nfunction SvgView({ text, title, frame }: { readonly text: string; readonly title: string; readonly frame: ViewerFrameProps }) {\n const { labels } = useAppText();\n const [mode, setMode] = useState<'preview' | 'source'>('preview');\n // An SVG is shown only as an image from a blob URL: it never becomes markup in this page, so its scripts cannot run.\n const url = useMemo(() => URL.createObjectURL(new Blob([text], { type: 'image/svg+xml' })), [text]);\n useEffect(() => () => URL.revokeObjectURL(url), [url]);\n return <ViewerFrame {...frame} controls={<>\n <ViewerToggle label={labels.view} value={mode} onChange={setMode} options={[\n { id: 'preview', label: labels.preview, text: labels.preview, icon: <EyeIcon className=\"size-4\" aria-hidden=\"true\" />, testId: 'artifact-mode' },\n { id: 'source', label: labels.source, text: labels.source, icon: <CodeXmlIcon className=\"size-4\" aria-hidden=\"true\" />, testId: 'artifact-mode' }]} />\n {frame.controls}</>}>\n {mode === 'preview'\n ? <div className=\"boring-viewer-checker flex min-h-0 flex-1 items-center justify-center overflow-auto bg-white p-6\"><img data-testid=\"artifact-svg\" src={url} alt={title} className=\"max-h-full max-w-full\" /></div>\n : <div className=\"min-h-0 flex-1 overflow-auto p-3\"><CodeBlock code={text} language=\"svg\" /></div>}\n </ViewerFrame>;\n}\n\ntype DocumentController = MarkdownController | HtmlController;\n\n/** One artifact version's frame and body. Mounted per resource and revision, so switching version starts clean. */\nfunction Version({ artifact, pinned, menu, options, onSelect, onClose }: {\n readonly artifact: ArtifactDescriptor; readonly pinned: boolean; readonly menu: VersionMenu; readonly options: ViewerOptions;\n readonly onSelect: (value: string) => void; readonly onClose: () => void;\n}) {\n const { type } = artifact;\n const { client, identity } = options;\n const { labels } = useAppText();\n const path = artifact.target.resource.path;\n const custom = options.viewers?.[type];\n const create = useMemo(() => {\n const base = (snapshot: ResourceSnapshot) => ({ identity, client, instanceId: randomUUID(), epoch: 'workspace', source: { kind: 'saved' as const, snapshot } });\n if (custom) return undefined;\n if (type === 'markdown') return (snapshot: ResourceSnapshot): DocumentController => createMarkdownController({ ...base(snapshot), readOnly: pinned });\n if (type === 'html') return (snapshot: ResourceSnapshot): DocumentController => createHtmlController({ ...base(snapshot), readOnly: true });\n return undefined;\n }, [type, pinned, client, identity, custom]);\n const saved = useSaved<DocumentController>({ client, target: artifact.target, revision: pinned ? artifact.revision : undefined, create });\n const controller = saved.controller;\n // The text to copy and download is the buffer when a viewer holds one, so the person's unsaved edits are included.\n const text = useSyncExternalStore(controller ? controller.subscribe : NOOP, () => controller ? controller.getSnapshot().text : saved.text, () => saved.text);\n const extension = EXTENSION.exec(path)?.[1] ?? 'txt';\n const revision = saved.kind === 'open' ? saved.snapshot.ref.revision : pinned ? artifact.revision : undefined;\n // The history menu: newest first, the newest marked \"Latest\" (choosing it follows the latest), the one on display checked.\n const versions = menu.items.length > 1 ? <ViewerVersions testId=\"artifact-versions\" current={menu.current} onSelect={onSelect} versions={menu.items} /> : undefined;\n const target = { artifact: artifactKey(artifact), version: pinned ? artifact.revision : 'latest' };\n const frame = {\n title: artifact.title, testId: 'artifact', titleTestId: 'artifact-panel-title', controls: versions, onClose, target, ...(revision === undefined ? {} : { revision }), ...(options.share ? { onShare: options.share } : {}),\n subtitle: <>\n <span data-testid=\"artifact-panel-type\">{typeLabel(artifact)}</span>\n <span aria-hidden=\"true\">·</span>\n <span data-testid=\"artifact-panel-version\">{pinned ? (menu.savedAt !== undefined ? labels.savedAt(savedLabel(menu.savedAt, Date.now(), labels.earlierVersion)) : labels.olderVersion) : menu.savedAt ? labels.latestSavedAt(savedLabel(menu.savedAt, Date.now(), labels.earlierVersion)) : labels.latest}</span>\n </>,\n ...(pinned ? { status: { label: labels.readOnly, kind: 'read-only' as const } } : {}),\n };\n const filename = `${artifact.title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') || 'artifact'}.${extension}`;\n const body = (children: ReactNode) => <div data-testid=\"artifact-body\" data-state={saved.kind} className=\"flex h-full min-h-0 flex-1 flex-col overflow-hidden\">{children}</div>;\n if (custom) return body(custom({ target: artifact.target, title: artifact.title, ...(pinned ? { revision: artifact.revision } : {}), frame: { testId: 'artifact', titleTestId: 'artifact-panel-title', controls: versions, onClose, target } }));\n // Until the version is open the bar offers no Share: the pane that shows it brings its own frame, so this one is replaced (remounted)\n // when it opens, and a Share pressed just then would copy the link with its \"Link copied\" notice lost with the old frame.\n if (saved.kind !== 'open') {\n const { onShare: _, ...waiting } = frame;\n return body(<ViewerFrame {...waiting}><p className=\"m-0 p-4 text-sm text-muted-foreground\" role=\"status\">{saved.kind === 'loading' ? labels.loading : saved.kind === 'invalid' ? labels.artifactNotText : labels.versionUnavailable}</p></ViewerFrame>);\n }\n const document = (children: ReactNode) => <div data-testid=\"document\" data-revision={saved.snapshot.ref.revision} className=\"h-full min-h-0\">{children}</div>;\n if (type === 'markdown' && controller) return body(document(<MarkdownPane controller={controller as MarkdownController} initialMode=\"rich\" {...frame} />));\n if (type === 'html' && controller) return body(document(<HtmlPane controller={controller as HtmlController} {...(options.interactive ? { interactive: options.interactive } : {})} {...frame} />));\n const actions = { onCopy: () => copyText(text ?? ''), onDownload: () => downloadFile(filename, text ?? '', `${artifact.mediaType};charset=utf-8`) };\n if (type === 'svg') return body(<SvgView text={saved.text} title={artifact.title} frame={{ ...frame, ...actions }} />);\n if (type === 'canvas') return body(<ViewerFrame {...frame}><p className=\"m-0 p-4 text-sm text-muted-foreground\" role=\"status\">{labels.noCanvasViewer}</p></ViewerFrame>);\n return body(<ViewerFrame {...frame} {...actions}><div className=\"min-h-0 flex-1 overflow-auto p-3\"><CodeBlock code={saved.text} language={artifact.language ?? 'text'} /></div></ViewerFrame>);\n}\n\n/**\n * One artifact in the panel. `active.follow` shows the latest saved revision under the newest known title (`versions`: every version of\n * this file the conversation presented or saved, newest first); otherwise the one revision in `active.descriptor` is pinned and read-only.\n * `onSelect` receives `latest` or a revision from the version menu.\n */\nexport function ArtifactPanel({ active, versions, options, onSelect, onClose }: {\n readonly active: { readonly descriptor: ArtifactDescriptor; readonly follow: boolean };\n readonly versions: readonly ArtifactDescriptor[];\n readonly options: ViewerOptions;\n readonly onSelect: (value: string) => void;\n readonly onClose: () => void;\n}) {\n const { follow } = active;\n const artifact = follow ? versions[0] ?? active.descriptor : active.descriptor;\n const path = artifact.target.resource.path;\n const revisions = useHistory(options.history, path);\n const { labels } = useAppText();\n const menu = versionMenu(artifact, follow, revisions, labels.earlierVersion);\n return <div data-testid=\"artifact-panel\" data-artifact-id={artifactKey(artifact)} data-artifact-type={artifact.type} data-follow={follow ? 'true' : 'false'} data-artifact-position={menu.number} data-artifact-revision={follow ? undefined : artifact.revision}\n className=\"pi-chat flex h-full min-h-0 flex-col\">\n <Version key={`${path}@${follow ? 'latest' : artifact.revision}`} artifact={artifact} pinned={!follow} menu={menu} options={options} onSelect={onSelect} onClose={onClose} />\n </div>;\n}\n",
36
+ "content": "'use client';\n\n// The artifact panel: the standard viewer bar (title, type, version switcher, Refresh, Share, copy, download, close) over the viewer for\n// the artifact's type. It follows the latest saved revision while nothing is unsaved (\"Latest\") or pins one older version, read-only. It\n// lists the versions the host's workspace provider retains for the file (`history`) and reads through the host's resource client. It never\n// executes artifact content (HTML runs only in the viewers' sandboxed preview when the host passes `interactive`).\nimport { useEffect, useMemo, useState, useSyncExternalStore } from 'react';\nimport type { ReactNode } from 'react';\nimport { CodeXmlIcon, EyeIcon } from 'lucide-react';\nimport { randomUUID } from '@hachej/boring-files/platform';\nimport type { ResourceClient, ResourceSnapshot } from '@hachej/boring-files';\nimport type { ResourceIdentity } from '@hachej/boring-files/remote';\nimport { createMarkdownController } from '@hachej/boring-ui-kit/markdown';\nimport type { MarkdownController } from '@hachej/boring-ui-kit/markdown';\nimport { createHtmlController } from '@hachej/boring-ui-kit/html';\nimport type { HtmlController } from '@hachej/boring-ui-kit/html';\nimport type { NativeChatController } from '@hachej/boring-ui-kit/native-chat';\nimport { artifactKey, collectArtifacts } from '../pi-chat/pi-chat';\nimport type { ArtifactDescriptor, ArtifactTarget, ArtifactsConfig } from '../pi-chat/pi-chat';\nimport { CodeBlock } from '../pi-chat/code-block';\nimport { typeLabel } from '../pi-chat/artifact';\nimport { HtmlPane } from '../viewers/html-pane';\nimport { MarkdownPane } from '../viewers/markdown-pane';\nimport { ViewerFrame, ViewerToggle } from '../viewers/viewer-frame';\nimport type { ViewerFrameProps, ViewerShare } from '../viewers/viewer-frame';\nimport { ViewerVersions } from '../viewers/menu';\nimport type { InteractiveHtml } from '../viewers/interactive-html';\nimport { downloadFile } from '../viewers/download';\nimport { copyText } from '../utils/utils';\nimport { savedLabel, useSaved } from './use-saved';\nimport { useAppText } from './app-labels';\n\nconst NOOP = () => () => {};\nconst POLL_MS = 1500;\nconst EXTENSION = /\\.([A-Za-z0-9]{1,8})$/;\n\n/** One retained revision of a file with its save time (`files.saves(path)` of `@hachej/boring-files/workspace`). */\nexport interface SavedRevision { readonly revision: string; readonly savedAt: number }\n\n/** What a host viewer for an artifact type or file kind the block does not render itself (for example a tldraw canvas) receives. */\nexport interface CustomViewerProps {\n readonly target: ArtifactTarget;\n readonly title: string;\n /** A pinned revision, read-only; absent: follow the latest. */\n readonly revision?: string | undefined;\n /** Pass these on to the `ViewerFrame` around it: test ids, the version switcher or back button, Close, the share target. */\n readonly frame: Pick<ViewerFrameProps, 'testId' | 'titleTestId' | 'controls' | 'onClose' | 'target'>;\n}\n/** Host viewers by artifact type or file kind (`canvas`, or any other). They take precedence over the built-in ones. */\nexport type CustomViewers = Readonly<Record<string, (props: CustomViewerProps) => ReactNode>>;\n\n/** Everything a viewer in the panel reads through: one resource client, the version history, host viewers and policy. */\nexport interface ViewerOptions {\n readonly client: ResourceClient;\n readonly identity: ResourceIdentity;\n readonly history?: ((path: string) => Promise<readonly SavedRevision[]>) | undefined;\n readonly viewers?: CustomViewers | undefined;\n /** The host's opt-in to running HTML pages in the sandboxed preview. */\n readonly interactive?: InteractiveHtml | undefined;\n readonly share?: ViewerShare | undefined;\n /** Told each revision a built-in viewer has mounted and shows (after it loads, never before): the page's acknowledgement of `present`. */\n readonly onShown?: ((shown: { readonly path: string; readonly revision: string; readonly hidden?: true }) => void) | undefined;\n}\n\n/** Reports `revision` of `path` once the viewer showing it has mounted (an effect, so never before the panel really shows it), and `hidden` when it stops. */\nexport function useReportShown(onShown: ViewerOptions['onShown'], path: string, revision: string | undefined): void {\n useEffect(() => {\n if (revision === undefined || !onShown) return undefined;\n onShown({ path, revision });\n return () => onShown({ path, revision, hidden: true });\n }, [onShown, path, revision]);\n}\n\n/** Every artifact version the conversation's tool results produced (the version switcher's source), oldest first. */\nexport function useArtifactVersions(controller: NativeChatController | undefined, detect?: ArtifactsConfig['detect']): ArtifactDescriptor[] {\n const view = useSyncExternalStore(controller ? controller.subscribe : NOOP, () => controller?.getSnapshot().view, () => undefined);\n return useMemo(() => collectArtifacts(view, detect), [view, detect]);\n}\n\n/** How many messages the person has sent in the conversation: it changes when a new turn starts. */\nexport function useTurn(controller: NativeChatController | undefined): number {\n const view = useSyncExternalStore(controller ? controller.subscribe : NOOP, () => controller?.getSnapshot().view, () => undefined);\n return useMemo(() => (view?.entries ?? []).reduce((count, entry) => count + (entry.model ?? []).filter(message => message.role === 'user').length, 0), [view]);\n}\n\n/** The revisions the workspace provider retains for a file with their save times, newest first; followed while the panel is open. */\nfunction useHistory(history: ViewerOptions['history'], path: string): readonly SavedRevision[] {\n const [revisions, setRevisions] = useState<readonly SavedRevision[]>([]);\n useEffect(() => {\n if (!history) return;\n let cancelled = false;\n const key = (saves: readonly SavedRevision[]) => saves.map(save => `${save.revision}@${save.savedAt}`).join();\n const load = () => history(path).then(saves => { if (!cancelled) setRevisions(current => key(current) === key(saves) ? current : saves); }).catch(() => {});\n void load();\n const timer = setInterval(load, POLL_MS);\n return () => { cancelled = true; clearInterval(timer); };\n }, [history, path]);\n return revisions;\n}\n\ninterface VersionMenu {\n readonly items: readonly { readonly id: string; readonly label: string; readonly latest: boolean }[];\n readonly current: string;\n /** Position counted from the oldest retained revision: only a test hook. */\n readonly number: number | undefined;\n readonly savedAt: number | undefined;\n}\n\n/** The version menu, newest first: each retained revision is named by when it was saved, and the newest is \"Latest\". The pin is the revision. */\nfunction versionMenu(artifact: ArtifactDescriptor, follow: boolean, revisions: readonly SavedRevision[], earlier: string): VersionMenu {\n const at = follow ? 0 : revisions.findIndex(save => save.revision === artifact.revision);\n const shown = at < 0 ? undefined : revisions[at];\n return { items: revisions.map((save, index) => ({ id: index === 0 ? 'latest' : save.revision, label: savedLabel(save.savedAt, Date.now(), earlier), latest: index === 0 })),\n current: follow ? 'latest' : artifact.revision, number: shown ? revisions.length - at : undefined, savedAt: shown?.savedAt };\n}\n\nfunction SvgView({ text, title, frame }: { readonly text: string; readonly title: string; readonly frame: ViewerFrameProps }) {\n const { labels } = useAppText();\n const [mode, setMode] = useState<'preview' | 'source'>('preview');\n // An SVG is shown only as an image from a blob URL: it never becomes markup in this page, so its scripts cannot run.\n const url = useMemo(() => URL.createObjectURL(new Blob([text], { type: 'image/svg+xml' })), [text]);\n useEffect(() => () => URL.revokeObjectURL(url), [url]);\n return <ViewerFrame {...frame} controls={<>\n <ViewerToggle label={labels.view} value={mode} onChange={setMode} options={[\n { id: 'preview', label: labels.preview, text: labels.preview, icon: <EyeIcon className=\"size-4\" aria-hidden=\"true\" />, testId: 'artifact-mode' },\n { id: 'source', label: labels.source, text: labels.source, icon: <CodeXmlIcon className=\"size-4\" aria-hidden=\"true\" />, testId: 'artifact-mode' }]} />\n {frame.controls}</>}>\n {mode === 'preview'\n ? <div className=\"boring-viewer-checker flex min-h-0 flex-1 items-center justify-center overflow-auto bg-white p-6\"><img data-testid=\"artifact-svg\" src={url} alt={title} className=\"max-h-full max-w-full\" /></div>\n : <div className=\"min-h-0 flex-1 overflow-auto p-3\"><CodeBlock code={text} language=\"svg\" /></div>}\n </ViewerFrame>;\n}\n\ntype DocumentController = MarkdownController | HtmlController;\n\n/** One artifact version's frame and body. Mounted per resource and revision, so switching version starts clean. */\nfunction Version({ artifact, pinned, menu, options, onSelect, onClose }: {\n readonly artifact: ArtifactDescriptor; readonly pinned: boolean; readonly menu: VersionMenu; readonly options: ViewerOptions;\n readonly onSelect: (value: string) => void; readonly onClose: () => void;\n}) {\n const { type } = artifact;\n const { client, identity } = options;\n const { labels } = useAppText();\n const path = artifact.target.resource.path;\n const custom = options.viewers?.[type];\n const create = useMemo(() => {\n const base = (snapshot: ResourceSnapshot) => ({ identity, client, instanceId: randomUUID(), epoch: 'workspace', source: { kind: 'saved' as const, snapshot } });\n if (custom) return undefined;\n if (type === 'markdown') return (snapshot: ResourceSnapshot): DocumentController => createMarkdownController({ ...base(snapshot), readOnly: pinned });\n if (type === 'html') return (snapshot: ResourceSnapshot): DocumentController => createHtmlController({ ...base(snapshot), readOnly: true });\n return undefined;\n }, [type, pinned, client, identity, custom]);\n const saved = useSaved<DocumentController>({ client, target: artifact.target, revision: pinned ? artifact.revision : undefined, create });\n const controller = saved.controller;\n // The text to copy and download is the buffer when a viewer holds one, so the person's unsaved edits are included.\n const text = useSyncExternalStore(controller ? controller.subscribe : NOOP, () => controller ? controller.getSnapshot().text : saved.text, () => saved.text);\n const extension = EXTENSION.exec(path)?.[1] ?? 'txt';\n const revision = saved.kind === 'open' ? saved.snapshot.ref.revision : pinned ? artifact.revision : undefined;\n // A host viewer and the canvas (which shows only a \"no viewer\" note) never report a mount: a presented file in them stays unconfirmed.\n useReportShown(options.onShown, path, !custom && type !== 'canvas' && saved.kind === 'open' ? saved.snapshot.ref.revision : undefined);\n // The history menu: newest first, the newest marked \"Latest\" (choosing it follows the latest), the one on display checked.\n const versions = menu.items.length > 1 ? <ViewerVersions testId=\"artifact-versions\" current={menu.current} onSelect={onSelect} versions={menu.items} /> : undefined;\n const target = { artifact: artifactKey(artifact), version: pinned ? artifact.revision : 'latest' };\n const frame = {\n title: artifact.title, testId: 'artifact', titleTestId: 'artifact-panel-title', controls: versions, onClose, target, ...(revision === undefined ? {} : { revision }), ...(options.share ? { onShare: options.share } : {}),\n subtitle: <>\n <span data-testid=\"artifact-panel-type\">{typeLabel(artifact)}</span>\n <span aria-hidden=\"true\">·</span>\n <span data-testid=\"artifact-panel-version\">{pinned ? (menu.savedAt !== undefined ? labels.savedAt(savedLabel(menu.savedAt, Date.now(), labels.earlierVersion)) : labels.olderVersion) : menu.savedAt ? labels.latestSavedAt(savedLabel(menu.savedAt, Date.now(), labels.earlierVersion)) : labels.latest}</span>\n </>,\n ...(pinned ? { status: { label: labels.readOnly, kind: 'read-only' as const } } : {}),\n };\n const filename = `${artifact.title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') || 'artifact'}.${extension}`;\n const body = (children: ReactNode) => <div data-testid=\"artifact-body\" data-state={saved.kind} className=\"flex h-full min-h-0 flex-1 flex-col overflow-hidden\">{children}</div>;\n if (custom) return body(custom({ target: artifact.target, title: artifact.title, ...(pinned ? { revision: artifact.revision } : {}), frame: { testId: 'artifact', titleTestId: 'artifact-panel-title', controls: versions, onClose, target } }));\n // Until the version is open the bar offers no Share: the pane that shows it brings its own frame, so this one is replaced (remounted)\n // when it opens, and a Share pressed just then would copy the link with its \"Link copied\" notice lost with the old frame.\n if (saved.kind !== 'open') {\n const { onShare: _, ...waiting } = frame;\n return body(<ViewerFrame {...waiting}><p className=\"m-0 p-4 text-sm text-muted-foreground\" role=\"status\">{saved.kind === 'loading' ? labels.loading : saved.kind === 'invalid' ? labels.artifactNotText : labels.versionUnavailable}</p></ViewerFrame>);\n }\n const document = (children: ReactNode) => <div data-testid=\"document\" data-revision={saved.snapshot.ref.revision} className=\"h-full min-h-0\">{children}</div>;\n if (type === 'markdown' && controller) return body(document(<MarkdownPane controller={controller as MarkdownController} initialMode=\"rich\" {...frame} />));\n if (type === 'html' && controller) return body(document(<HtmlPane controller={controller as HtmlController} {...(options.interactive ? { interactive: options.interactive } : {})} {...frame} />));\n const actions = { onCopy: () => copyText(text ?? ''), onDownload: () => downloadFile(filename, text ?? '', `${artifact.mediaType};charset=utf-8`) };\n if (type === 'svg') return body(<SvgView text={saved.text} title={artifact.title} frame={{ ...frame, ...actions }} />);\n if (type === 'canvas') return body(<ViewerFrame {...frame}><p className=\"m-0 p-4 text-sm text-muted-foreground\" role=\"status\">{labels.noCanvasViewer}</p></ViewerFrame>);\n return body(<ViewerFrame {...frame} {...actions}><div className=\"min-h-0 flex-1 overflow-auto p-3\"><CodeBlock code={saved.text} language={artifact.language ?? 'text'} /></div></ViewerFrame>);\n}\n\n/**\n * One artifact in the panel. `active.follow` shows the latest saved revision under the newest known title (`versions`: every version of\n * this file the conversation presented or saved, newest first); otherwise the one revision in `active.descriptor` is pinned and read-only.\n * `onSelect` receives `latest` or a revision from the version menu.\n */\nexport function ArtifactPanel({ active, versions, options, onSelect, onClose }: {\n readonly active: { readonly descriptor: ArtifactDescriptor; readonly follow: boolean };\n readonly versions: readonly ArtifactDescriptor[];\n readonly options: ViewerOptions;\n readonly onSelect: (value: string) => void;\n readonly onClose: () => void;\n}) {\n const { follow } = active;\n const artifact = follow ? versions[0] ?? active.descriptor : active.descriptor;\n const path = artifact.target.resource.path;\n const revisions = useHistory(options.history, path);\n const { labels } = useAppText();\n const menu = versionMenu(artifact, follow, revisions, labels.earlierVersion);\n return <div data-testid=\"artifact-panel\" data-artifact-id={artifactKey(artifact)} data-artifact-type={artifact.type} data-follow={follow ? 'true' : 'false'} data-artifact-position={menu.number} data-artifact-revision={follow ? undefined : artifact.revision}\n className=\"pi-chat flex h-full min-h-0 flex-col\">\n <Version key={`${path}@${follow ? 'latest' : artifact.revision}`} artifact={artifact} pinned={!follow} menu={menu} options={options} onSelect={onSelect} onClose={onClose} />\n </div>;\n}\n",
37
37
  "type": "registry:component",
38
38
  "target": "components/pi-app/artifact-panel.tsx"
39
39
  },
40
40
  {
41
41
  "path": "registry/pi-app/file-viewer.tsx",
42
- "content": "'use client';\n\n// Opens one workspace file in the viewer that suits its type, always in the standard viewer frame (viewers item): Markdown and HTML in\n// their editors (revisioned through the host's resource client, so saves go back to the file and an edit made behind the editor's back is\n// a conflict), images and PDFs read-only from the file's bytes, anything else as text. A host viewer (`viewers[kind]`) takes precedence.\nimport { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';\nimport type { ReactNode } from 'react';\nimport { randomUUID } from '@hachej/boring-files/platform';\nimport type { ResourceLocator, ResourceSnapshot } from '@hachej/boring-files';\nimport { createMarkdownController } from '@hachej/boring-ui-kit/markdown';\nimport type { MarkdownController } from '@hachej/boring-ui-kit/markdown';\nimport { createHtmlController } from '@hachej/boring-ui-kit/html';\nimport type { HtmlController } from '@hachej/boring-ui-kit/html';\nimport { HtmlPane } from '../viewers/html-pane';\nimport { ImagePane } from '../viewers/image-pane';\nimport { MarkdownPane } from '../viewers/markdown-pane';\nimport { PdfPane } from '../viewers/pdf-pane';\nimport { ViewerFrame } from '../viewers/viewer-frame';\nimport { downloadFile } from '../viewers/download';\nimport { formatBytes } from '../viewers/media';\nimport { copyText } from '../utils/utils';\nimport { mediaTypeOf, viewerKindOf } from '@hachej/boring-files/file-types';\nimport type { ViewerKind as FileKind } from '@hachej/boring-files/file-types';\nimport { KIND_LABEL, decodeText } from './file-kinds';\nimport type { ViewerOptions } from './artifact-panel';\nimport { useSaved } from './use-saved';\nimport { useAppText } from './app-labels';\n\nconst POLL_MS = 1500;\nconst nameOf = (path: string) => path.split('/').pop() || path;\n\ninterface Common {\n readonly path: string;\n readonly kind: FileKind;\n readonly locator: ResourceLocator;\n readonly options: ViewerOptions;\n readonly onClose: () => void;\n readonly back: ReactNode;\n readonly onUnsavedChange?: ((unsaved: boolean) => void) | undefined;\n}\n\nconst subtitleOf = (locator: ResourceLocator) => <span data-testid=\"file-path\" className=\"truncate\">{locator.resource.path}</span>;\n\n/** Markdown or HTML: a revisioned controller over the file. A new revision remounts the pane; it starts in the mode the person chose. */\nfunction FileDocument({ path, kind, locator, options, onClose, back, onUnsavedChange }: Common) {\n const { client, identity } = options;\n const create = useMemo(() => (snapshot: ResourceSnapshot): MarkdownController | HtmlController => (kind === 'markdown' ? createMarkdownController : createHtmlController)({\n identity, client, instanceId: randomUUID(), epoch: 'workspace', source: { kind: 'saved', snapshot } }), [kind, client, identity]);\n const saved = useSaved({ client, target: locator, create });\n useLayoutEffect(() => {\n const controller = saved.controller;\n if (!controller) return;\n const notify = () => {\n const snapshot = controller.getSnapshot();\n onUnsavedChange?.(snapshot.dirty || snapshot.save.kind === 'pending'\n || (snapshot.save.kind === 'settled' && snapshot.save.result.kind === 'unknown'));\n };\n notify();\n const unsubscribe = controller.subscribe(notify);\n return () => { unsubscribe(); onUnsavedChange?.(false); };\n }, [saved.controller, onUnsavedChange]);\n const { labels } = useAppText();\n const [mode, setMode] = useState<string>(kind === 'markdown' ? 'rich' : 'preview');\n const common = { title: nameOf(path), subtitle: subtitleOf(locator), target: { file: path }, onClose, titleTestId: 'file-title', controls: back, ...(options.share ? { onShare: options.share } : {}) };\n // Until the document is open the bar offers no Share, Copy or menu actions of its own: they would act on a document that is not shown.\n if (saved.kind !== 'open' || !saved.controller) {\n return <ViewerFrame title={common.title} subtitle={common.subtitle} onClose={onClose} controls={back}>\n <p role=\"status\" className=\"m-0 p-4 text-sm text-muted-foreground\">{saved.kind === 'loading' ? labels.loading : saved.kind === 'missing' ? labels.fileMissing : labels.fileNotText}</p>\n </ViewerFrame>;\n }\n const revision = saved.snapshot.ref.revision;\n // The preview selector the journeys use keeps working: the wrapper holds the document's text.\n return <div data-testid=\"file-preview\" className=\"h-full min-h-0\" data-revision={revision}>\n {kind === 'markdown'\n ? <MarkdownPane key={revision} controller={saved.controller as MarkdownController} revision={revision} initialMode={mode as 'rich'} onModeChange={setMode} {...common} />\n : <HtmlPane key={revision} controller={saved.controller as HtmlController} revision={revision} initialMode={mode as 'preview'} onModeChange={setMode} {...(options.interactive ? { interactive: options.interactive } : {})} {...common} />}\n </div>;\n}\n\ntype Loaded = { readonly kind: 'loading' | 'missing' } | { readonly kind: 'ready'; readonly bytes: Uint8Array; readonly revision: string; readonly text: string | undefined };\n\n/** Image, PDF and text files: read through the resource client, refreshed on demand (and followed while open, for text). */\nfunction FileBytes({ path, kind, locator, options, onClose, back }: Common) {\n const { labels } = useAppText();\n const targetKey = JSON.stringify(locator);\n const binding = useMemo(() => ({ client: options.client, locator, path }), [options.client, targetKey, path]); // eslint-disable-line react-hooks/exhaustive-deps\n const [stored, setStored] = useState<{ readonly binding: typeof binding; readonly value: Loaded }>();\n const file: Loaded = stored?.binding === binding ? stored.value : { kind: 'loading' };\n const running = useRef<AbortController | undefined>(undefined);\n const load = useCallback(async () => {\n running.current?.abort();\n const abort = new AbortController(); running.current = abort;\n try {\n const read = await binding.client.read({ target: binding.locator, revision: { kind: 'latest' } }, abort.signal);\n if (abort.signal.aborted || running.current !== abort) return;\n if (read.kind !== 'available') {\n setStored(current => current?.binding === binding && current.value.kind === 'ready' ? current : { binding, value: { kind: 'missing' } });\n return;\n }\n const { bytes, ref } = read.snapshot;\n setStored({ binding, value: { kind: 'ready', bytes, revision: ref.revision, text: decodeText(binding.path, bytes) } });\n } catch {\n if (!abort.signal.aborted && running.current === abort) setStored(current => current?.binding === binding && current.value.kind === 'ready' ? current : { binding, value: { kind: 'missing' } });\n }\n }, [binding]);\n useEffect(() => {\n void load();\n const timer = kind === 'text' ? setInterval(() => { void load(); }, POLL_MS) : undefined;\n return () => { running.current?.abort(); clearInterval(timer); };\n }, [load, kind]);\n const common = { subtitle: subtitleOf(locator), target: { file: path }, onClose, titleTestId: 'file-title', controls: back, ...(options.share ? { onShare: options.share } : {}) };\n // Until the file is read the bar offers no Share: the image and PDF panes bring their own frame, so this one is replaced (remounted)\n // when the bytes arrive, and a Share pressed just then would copy the link with its \"Link copied\" notice lost with the old frame.\n if (file.kind !== 'ready') {\n return <ViewerFrame title={nameOf(path)} subtitle={common.subtitle} onClose={onClose} titleTestId=\"file-title\" controls={back}>\n <p role=\"status\" className=\"m-0 p-4 text-sm text-muted-foreground\">{file.kind === 'loading' ? labels.loading : labels.fileMissing}</p>\n </ViewerFrame>;\n }\n if (kind === 'image') return <ImagePane name={nameOf(path)} mediaType={mediaTypeOf(path)} bytes={file.bytes} onRefresh={load} {...common} />;\n if (kind === 'pdf') return <PdfPane name={nameOf(path)} bytes={file.bytes} onRefresh={load} {...common} />;\n const { text } = file, size = file.bytes.byteLength;\n return <ViewerFrame title={nameOf(path)} {...common} subtitle={<>{subtitleOf(locator)}<span aria-hidden=\"true\">·</span><span>{formatBytes(size)}</span></>}\n onRefresh={load} {...(text === undefined ? {} : { onCopy: () => copyText(text), onDownload: () => downloadFile(nameOf(path), text, 'text/plain;charset=utf-8') })}>\n {text === undefined\n ? <p role=\"status\" className=\"m-0 p-4 text-sm text-muted-foreground\">{labels.binaryFile(formatBytes(size))}</p>\n : <div className=\"min-h-0 flex-1 overflow-auto p-3\"><pre data-testid=\"file-preview\" className=\"m-0 rounded-lg bg-muted p-3 font-mono text-[13px] leading-relaxed break-words whitespace-pre-wrap\">{text}</pre></div>}\n </ViewerFrame>;\n}\n\n/**\n * One file in the panel. `path` is the host's name for it (shown in the share target and `data-path`); `locator` is the resource the\n * client reads. Remount per file with a `key`. `onBack` adds a back button to the bar (for example to the host's file list).\n */\nexport function FileViewer({ path, locator, options, onClose, onBack, backLabel, onUnsavedChange }: {\n readonly path: string;\n readonly locator: ResourceLocator;\n readonly options: ViewerOptions;\n readonly onClose: () => void;\n readonly onBack?: (() => void) | undefined;\n readonly backLabel?: string | undefined;\n /** Built-in editable viewers report unsaved and unconfirmed changes for navigation guards. */\n readonly onUnsavedChange?: ((unsaved: boolean) => void) | undefined;\n}) {\n const kind = viewerKindOf(path);\n const { labels, icons } = useAppText();\n const back = onBack ? <button type=\"button\" data-testid=\"file-back\" onClick={onBack} className=\"inline-flex h-10 cursor-pointer items-center gap-1 rounded-lg border border-border bg-background px-2 text-sm md:h-8 md:text-xs\"><icons.back className=\"size-3.5\" aria-hidden=\"true\" />{backLabel ?? labels.back}</button> : undefined;\n const custom = options.viewers?.[kind];\n const common: Common = { path, kind, locator, options, onClose, back, onUnsavedChange };\n return <div data-testid=\"file-viewer\" data-kind={kind} data-path={path} aria-label={labels.fileViewer(KIND_LABEL[kind])} className=\"flex h-full min-h-0 flex-col overflow-hidden [&>*]:min-h-0 [&>*]:flex-1\">\n {custom ? custom({ target: locator, title: nameOf(path), frame: { titleTestId: 'file-title', onClose, target: { file: path }, controls: back } })\n : kind === 'markdown' || kind === 'html' ? <FileDocument {...common} />\n : kind === 'canvas' ? <ViewerFrame title={nameOf(path)} subtitle={subtitleOf(locator)} onClose={onClose} controls={back}><p role=\"status\" className=\"m-0 p-4 text-sm text-muted-foreground\">{labels.noCanvasViewer}</p></ViewerFrame>\n : <FileBytes {...common} />}\n </div>;\n}\n",
42
+ "content": "'use client';\n\n// Opens one workspace file in the viewer that suits its type, always in the standard viewer frame (viewers item): Markdown and HTML in\n// their editors (revisioned through the host's resource client, so saves go back to the file and an edit made behind the editor's back is\n// a conflict), images and PDFs read-only from the file's bytes, anything else as text. A host viewer (`viewers[kind]`) takes precedence.\nimport { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';\nimport type { ReactNode } from 'react';\nimport { randomUUID } from '@hachej/boring-files/platform';\nimport type { ResourceLocator, ResourceSnapshot } from '@hachej/boring-files';\nimport { createMarkdownController } from '@hachej/boring-ui-kit/markdown';\nimport type { MarkdownController } from '@hachej/boring-ui-kit/markdown';\nimport { createHtmlController } from '@hachej/boring-ui-kit/html';\nimport type { HtmlController } from '@hachej/boring-ui-kit/html';\nimport { HtmlPane } from '../viewers/html-pane';\nimport { ImagePane } from '../viewers/image-pane';\nimport { MarkdownPane } from '../viewers/markdown-pane';\nimport { PdfPane } from '../viewers/pdf-pane';\nimport { ViewerFrame } from '../viewers/viewer-frame';\nimport { downloadFile } from '../viewers/download';\nimport { formatBytes } from '../viewers/media';\nimport { copyText } from '../utils/utils';\nimport { mediaTypeOf, viewerKindOf } from '@hachej/boring-files/file-types';\nimport type { ViewerKind as FileKind } from '@hachej/boring-files/file-types';\nimport { KIND_LABEL, decodeText } from './file-kinds';\nimport { useReportShown } from './artifact-panel';\nimport type { ViewerOptions } from './artifact-panel';\nimport { useSaved } from './use-saved';\nimport { useAppText } from './app-labels';\n\nconst POLL_MS = 1500;\nconst nameOf = (path: string) => path.split('/').pop() || path;\n\ninterface Common {\n readonly path: string;\n readonly kind: FileKind;\n readonly locator: ResourceLocator;\n readonly options: ViewerOptions;\n readonly onClose: () => void;\n readonly back: ReactNode;\n readonly onUnsavedChange?: ((unsaved: boolean) => void) | undefined;\n}\n\nconst subtitleOf = (locator: ResourceLocator) => <span data-testid=\"file-path\" className=\"truncate\">{locator.resource.path}</span>;\n\n/** Markdown or HTML: a revisioned controller over the file. A new revision remounts the pane; it starts in the mode the person chose. */\nfunction FileDocument({ path, kind, locator, options, onClose, back, onUnsavedChange }: Common) {\n const { client, identity } = options;\n const create = useMemo(() => (snapshot: ResourceSnapshot): MarkdownController | HtmlController => (kind === 'markdown' ? createMarkdownController : createHtmlController)({\n identity, client, instanceId: randomUUID(), epoch: 'workspace', source: { kind: 'saved', snapshot } }), [kind, client, identity]);\n const saved = useSaved({ client, target: locator, create });\n useLayoutEffect(() => {\n const controller = saved.controller;\n if (!controller) return;\n const notify = () => {\n const snapshot = controller.getSnapshot();\n onUnsavedChange?.(snapshot.dirty || snapshot.save.kind === 'pending'\n || (snapshot.save.kind === 'settled' && snapshot.save.result.kind === 'unknown'));\n };\n notify();\n const unsubscribe = controller.subscribe(notify);\n return () => { unsubscribe(); onUnsavedChange?.(false); };\n }, [saved.controller, onUnsavedChange]);\n const { labels } = useAppText();\n const [mode, setMode] = useState<string>(kind === 'markdown' ? 'rich' : 'preview');\n useReportShown(options.onShown, path, saved.kind === 'open' && saved.controller ? saved.snapshot.ref.revision : undefined);\n const common = { title: nameOf(path), subtitle: subtitleOf(locator), target: { file: path }, onClose, titleTestId: 'file-title', controls: back, ...(options.share ? { onShare: options.share } : {}) };\n // Until the document is open the bar offers no Share, Copy or menu actions of its own: they would act on a document that is not shown.\n if (saved.kind !== 'open' || !saved.controller) {\n return <ViewerFrame title={common.title} subtitle={common.subtitle} onClose={onClose} controls={back}>\n <p role=\"status\" className=\"m-0 p-4 text-sm text-muted-foreground\">{saved.kind === 'loading' ? labels.loading : saved.kind === 'missing' ? labels.fileMissing : labels.fileNotText}</p>\n </ViewerFrame>;\n }\n const revision = saved.snapshot.ref.revision;\n // The preview selector the journeys use keeps working: the wrapper holds the document's text.\n return <div data-testid=\"file-preview\" className=\"h-full min-h-0\" data-revision={revision}>\n {kind === 'markdown'\n ? <MarkdownPane key={revision} controller={saved.controller as MarkdownController} revision={revision} initialMode={mode as 'rich'} onModeChange={setMode} {...common} />\n : <HtmlPane key={revision} controller={saved.controller as HtmlController} revision={revision} initialMode={mode as 'preview'} onModeChange={setMode} {...(options.interactive ? { interactive: options.interactive } : {})} {...common} />}\n </div>;\n}\n\ntype Loaded = { readonly kind: 'loading' | 'missing' } | { readonly kind: 'ready'; readonly bytes: Uint8Array; readonly revision: string; readonly text: string | undefined };\n\n/** Image, PDF and text files: read through the resource client, refreshed on demand (and followed while open, for text). */\nfunction FileBytes({ path, kind, locator, options, onClose, back }: Common) {\n const { labels } = useAppText();\n const targetKey = JSON.stringify(locator);\n const binding = useMemo(() => ({ client: options.client, locator, path }), [options.client, targetKey, path]); // eslint-disable-line react-hooks/exhaustive-deps\n const [stored, setStored] = useState<{ readonly binding: typeof binding; readonly value: Loaded }>();\n const file: Loaded = stored?.binding === binding ? stored.value : { kind: 'loading' };\n useReportShown(options.onShown, path, file.kind === 'ready' ? file.revision : undefined);\n const running = useRef<AbortController | undefined>(undefined);\n const load = useCallback(async () => {\n running.current?.abort();\n const abort = new AbortController(); running.current = abort;\n try {\n const read = await binding.client.read({ target: binding.locator, revision: { kind: 'latest' } }, abort.signal);\n if (abort.signal.aborted || running.current !== abort) return;\n if (read.kind !== 'available') {\n setStored(current => current?.binding === binding && current.value.kind === 'ready' ? current : { binding, value: { kind: 'missing' } });\n return;\n }\n const { bytes, ref } = read.snapshot;\n setStored({ binding, value: { kind: 'ready', bytes, revision: ref.revision, text: decodeText(binding.path, bytes) } });\n } catch {\n if (!abort.signal.aborted && running.current === abort) setStored(current => current?.binding === binding && current.value.kind === 'ready' ? current : { binding, value: { kind: 'missing' } });\n }\n }, [binding]);\n useEffect(() => {\n void load();\n const timer = kind === 'text' ? setInterval(() => { void load(); }, POLL_MS) : undefined;\n return () => { running.current?.abort(); clearInterval(timer); };\n }, [load, kind]);\n const common = { subtitle: subtitleOf(locator), target: { file: path }, onClose, titleTestId: 'file-title', controls: back, ...(options.share ? { onShare: options.share } : {}) };\n // Until the file is read the bar offers no Share: the image and PDF panes bring their own frame, so this one is replaced (remounted)\n // when the bytes arrive, and a Share pressed just then would copy the link with its \"Link copied\" notice lost with the old frame.\n if (file.kind !== 'ready') {\n return <ViewerFrame title={nameOf(path)} subtitle={common.subtitle} onClose={onClose} titleTestId=\"file-title\" controls={back}>\n <p role=\"status\" className=\"m-0 p-4 text-sm text-muted-foreground\">{file.kind === 'loading' ? labels.loading : labels.fileMissing}</p>\n </ViewerFrame>;\n }\n if (kind === 'image') return <ImagePane name={nameOf(path)} mediaType={mediaTypeOf(path)} bytes={file.bytes} onRefresh={load} {...common} />;\n if (kind === 'pdf') return <PdfPane name={nameOf(path)} bytes={file.bytes} onRefresh={load} {...common} />;\n const { text } = file, size = file.bytes.byteLength;\n return <ViewerFrame title={nameOf(path)} {...common} subtitle={<>{subtitleOf(locator)}<span aria-hidden=\"true\">·</span><span>{formatBytes(size)}</span></>}\n onRefresh={load} {...(text === undefined ? {} : { onCopy: () => copyText(text), onDownload: () => downloadFile(nameOf(path), text, 'text/plain;charset=utf-8') })}>\n {text === undefined\n ? <p role=\"status\" className=\"m-0 p-4 text-sm text-muted-foreground\">{labels.binaryFile(formatBytes(size))}</p>\n : <div className=\"min-h-0 flex-1 overflow-auto p-3\"><pre data-testid=\"file-preview\" className=\"m-0 rounded-lg bg-muted p-3 font-mono text-[13px] leading-relaxed break-words whitespace-pre-wrap\">{text}</pre></div>}\n </ViewerFrame>;\n}\n\n/**\n * One file in the panel. `path` is the host's name for it (shown in the share target and `data-path`); `locator` is the resource the\n * client reads. Remount per file with a `key`. `onBack` adds a back button to the bar (for example to the host's file list).\n */\nexport function FileViewer({ path, locator, options, onClose, onBack, backLabel, onUnsavedChange }: {\n readonly path: string;\n readonly locator: ResourceLocator;\n readonly options: ViewerOptions;\n readonly onClose: () => void;\n readonly onBack?: (() => void) | undefined;\n readonly backLabel?: string | undefined;\n /** Built-in editable viewers report unsaved and unconfirmed changes for navigation guards. */\n readonly onUnsavedChange?: ((unsaved: boolean) => void) | undefined;\n}) {\n const kind = viewerKindOf(path);\n const { labels, icons } = useAppText();\n const back = onBack ? <button type=\"button\" data-testid=\"file-back\" onClick={onBack} className=\"inline-flex h-10 cursor-pointer items-center gap-1 rounded-lg border border-border bg-background px-2 text-sm md:h-8 md:text-xs\"><icons.back className=\"size-3.5\" aria-hidden=\"true\" />{backLabel ?? labels.back}</button> : undefined;\n const custom = options.viewers?.[kind];\n const common: Common = { path, kind, locator, options, onClose, back, onUnsavedChange };\n return <div data-testid=\"file-viewer\" data-kind={kind} data-path={path} aria-label={labels.fileViewer(KIND_LABEL[kind])} className=\"flex h-full min-h-0 flex-col overflow-hidden [&>*]:min-h-0 [&>*]:flex-1\">\n {custom ? custom({ target: locator, title: nameOf(path), frame: { titleTestId: 'file-title', onClose, target: { file: path }, controls: back } })\n : kind === 'markdown' || kind === 'html' ? <FileDocument {...common} />\n : kind === 'canvas' ? <ViewerFrame title={nameOf(path)} subtitle={subtitleOf(locator)} onClose={onClose} controls={back}><p role=\"status\" className=\"m-0 p-4 text-sm text-muted-foreground\">{labels.noCanvasViewer}</p></ViewerFrame>\n : <FileBytes {...common} />}\n </div>;\n}\n",
43
43
  "type": "registry:component",
44
44
  "target": "components/pi-app/file-viewer.tsx"
45
45
  },
@@ -73,12 +73,6 @@
73
73
  "type": "registry:hook",
74
74
  "target": "components/pi-app/use-conversations.ts"
75
75
  },
76
- {
77
- "path": "registry/pi-app/use-remote-chat.ts",
78
- "content": "import { useEffect, useLayoutEffect, useMemo, useState } from 'react';\nimport { createNativeChatController } from '@hachej/boring-ui-kit/native-chat';\nimport type { ChatIdentity, NativeChatController } from '@hachej/boring-ui-kit/native-chat';\nimport { createRemoteChat } from '@hachej/boring-ui-kit/remote-chat';\nimport type { RemoteChat } from '@hachej/boring-ui-kit/remote-chat';\nimport type { PiChatActions } from '../pi-chat/pi-chat';\n\nexport type RemoteChatState =\n | { readonly status: 'connecting'; readonly conversationId: string | undefined }\n | { readonly status: 'offline'; readonly conversationId: string | undefined; readonly error: string }\n | { readonly status: 'ready'; readonly conversationId: string; readonly controller: NativeChatController; readonly actions: PiChatActions; readonly configure: RemoteChat['configure'] };\n\n/**\n * One native chat controller per selected conversation over the host's chat transport (`createChatTransportHandler` of\n * `@hachej/boring-agent/chat-transport`). `endpoint(id)` names the transport URL of a conversation; `fetch` is the host's authenticated fetch.\n * The remote chat reopens a dropped stream itself (the controller reads `reconnecting` meanwhile); it never means the task stopped.\n * A failed connect retries every second. The previous conversation's controller is never handed out: it is disposed on change.\n */\nexport function useRemoteChat({ conversationId, endpoint, fetch, identity }: {\n readonly conversationId: string | undefined;\n readonly endpoint: (conversationId: string) => string | URL;\n readonly fetch: (request: Request) => Promise<Response>;\n readonly identity: ChatIdentity | undefined;\n}): RemoteChatState {\n const url = conversationId === undefined ? undefined : String(endpoint(conversationId));\n const key = JSON.stringify([conversationId, url, identity?.runtimeId, identity?.scopeId, identity?.principalId]);\n const binding = useMemo(() => ({ key, fetch }), [key]); // eslint-disable-line react-hooks/exhaustive-deps\n useLayoutEffect(() => { binding.fetch = fetch; }, [binding, fetch]);\n const [stored, setStored] = useState<{ readonly binding: typeof binding; readonly chat: RemoteChatState }>();\n useEffect(() => {\n if (conversationId === undefined || !identity || url === undefined) return;\n const setChat = (chat: RemoteChatState) => setStored({ binding, chat });\n let disposed = false, controller: NativeChatController | undefined, remote: RemoteChat | undefined;\n setChat({ status: 'connecting', conversationId });\n void (async () => {\n while (!disposed) {\n try {\n remote = await createRemoteChat({ endpoint: url, fetch: request => binding.fetch(request) });\n if (disposed) return void remote.close();\n controller = createNativeChatController({ identity, ...remote });\n await controller.connect();\n if (disposed) return void controller.dispose();\n // Human-in-the-loop answers and queue withdrawal are optional on the transport: pass only what it offers.\n const actions: { answer?: RemoteChat['answer']; withdraw?: RemoteChat['withdraw'] } = {};\n if (typeof remote.answer === 'function') actions.answer = remote.answer;\n if (typeof remote.withdraw === 'function') actions.withdraw = remote.withdraw;\n setChat({ status: 'ready', controller, conversationId, actions, configure: remote.configure });\n return;\n } catch (error) {\n controller?.dispose(); controller = undefined; void remote?.close(); remote = undefined;\n if (disposed) return;\n setChat({ status: 'offline', conversationId, error: String((error as Error)?.message ?? error) });\n await new Promise(resolve => setTimeout(resolve, 1000));\n }\n }\n })();\n return () => { disposed = true; controller?.dispose(); void remote?.close(); };\n }, [binding]); // eslint-disable-line react-hooks/exhaustive-deps\n return identity && stored?.binding === binding ? stored.chat : { status: 'connecting', conversationId };\n}\n",
79
- "type": "registry:hook",
80
- "target": "components/pi-app/use-remote-chat.ts"
81
- },
82
76
  {
83
77
  "path": "registry/pi-app/app-labels.ts",
84
78
  "content": "/*\n * The words and icons of the pi-app block as plain data: its own (sessions pane, artifact panel, file viewer) and the viewers' it composes\n * (`defaultViewerLabels`). `AgentWorkspace` takes a partial `labels` and `icons`; the chat's go through `chat.labels` and `chat.icons`.\n */\nimport { createContext, createElement, useContext } from 'react';\nimport type { ReactNode } from 'react';\nimport { ArrowLeftIcon, LibraryIcon, MessageSquareIcon, PanelLeftIcon, PictureInPicture2Icon, PlusIcon, XIcon } from 'lucide-react';\nimport type { BlockIcon } from '../button/actions';\nimport { defaultViewerIcons, defaultViewerLabels } from '../viewers/viewer-window';\n\nexport const defaultAppLabels = {\n ...defaultViewerLabels,\n sessionsTitle: 'Chats',\n workspaceNavigation: 'Workspace navigation',\n openNavigation: 'Open navigation',\n closeNavigation: 'Close navigation',\n hideNavigation: 'Hide navigation',\n showNavigation: 'Show navigation',\n chat: 'Chat',\n library: 'Library',\n agent: 'Agent',\n backToChat: 'Back to chat',\n newChat: 'New',\n closeSessions: 'Close chats',\n openSessions: 'Open chats',\n hideSessions: 'Hide chats',\n showSessions: 'Show chats',\n floatChat: 'Float chat',\n floatHint: 'Release to float the chat',\n resizePanel: 'Resize artifact panel',\n artifactPanel: 'Artifact panel',\n back: 'Back',\n savedAt: (when: string) => `Saved ${when}`,\n latestSavedAt: (when: string) => `Latest, saved ${when}`,\n olderVersion: 'Older version',\n earlierVersion: 'Earlier version',\n artifactNotText: 'This artifact cannot be shown as text.',\n versionUnavailable: 'This version is not available.',\n noCanvasViewer: 'This host has no canvas viewer (pass one in `viewers.canvas`).',\n fileMissing: 'This file no longer exists.',\n attachmentTooLarge: (limit: string) => `Larger than ${limit}. Not saved.`,\n fileNotText: 'This file cannot be shown as text.',\n binaryFile: (size: string) => `This is a binary file (${size}); it cannot be shown as text.`,\n fileViewer: (kind: string) => `${kind} viewer`,\n newVersion: 'A new version is available.',\n};\nexport type AppLabels = typeof defaultAppLabels;\n\nexport const defaultAppIcons = {\n ...defaultViewerIcons,\n sessionsToggle: PanelLeftIcon as BlockIcon,\n library: LibraryIcon as BlockIcon,\n chat: MessageSquareIcon as BlockIcon,\n newChat: PlusIcon as BlockIcon,\n closeSessions: XIcon as BlockIcon,\n floatChat: PictureInPicture2Icon as BlockIcon,\n back: ArrowLeftIcon as BlockIcon,\n};\nexport type AppIcons = typeof defaultAppIcons;\n\nexport interface AppText { readonly labels: AppLabels; readonly icons: AppIcons }\nconst AppTextContext = createContext<AppText>({ labels: defaultAppLabels, icons: defaultAppIcons });\n/** The block's labels and icons (the defaults outside an `AgentWorkspace`). */\nexport const useAppText = (): AppText => useContext(AppTextContext);\nexport function AppTextProvider({ value, children }: { readonly value: AppText; readonly children: ReactNode }) {\n return createElement(AppTextContext.Provider, { value }, children);\n}\n",