@hachej/boring-ui-kit 0.4.41 → 0.4.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/package.json +2 -2
  2. package/r/agent-target.json +4 -4
  3. package/r/app-shell.json +18 -24
  4. package/r/board-viewer.json +6 -6
  5. package/r/button.json +1 -1
  6. package/r/dock.json +1 -1
  7. package/r/documents.json +13 -13
  8. package/r/feedback-preview.json +1 -1
  9. package/r/feedback.json +6 -6
  10. package/r/file-tree.json +4 -4
  11. package/r/highlights.json +3 -3
  12. package/r/html-viewer.json +3 -3
  13. package/r/looks-viewer.json +2 -2
  14. package/r/maquette-viewer.json +1 -1
  15. package/r/markdown-editor.json +3 -3
  16. package/r/mockup-viewer.json +1 -1
  17. package/r/pi-ambient.json +8 -8
  18. package/r/pi-app-kinds.json +10 -10
  19. package/r/pi-app.json +13 -13
  20. package/r/pi-artifacts.json +2 -2
  21. package/r/pi-chat-approval.json +2 -2
  22. package/r/pi-chat-attachments.json +1 -1
  23. package/r/pi-chat-markdown.json +2 -2
  24. package/r/pi-chat-mentions.json +1 -1
  25. package/r/pi-chat-pickers.json +1 -1
  26. package/r/pi-chat-plugins.json +11 -11
  27. package/r/pi-chat-question.json +1 -1
  28. package/r/pi-chat-slash.json +2 -2
  29. package/r/pi-chat-subagent.json +1 -1
  30. package/r/pi-chat-voice.json +3 -3
  31. package/r/pi-chat.json +5 -5
  32. package/r/pi-workspace.json +4 -4
  33. package/r/placed-agent.json +4 -4
  34. package/r/pm-panel.json +42 -28
  35. package/r/provider-setup.json +1 -1
  36. package/r/registry.json +206 -194
  37. package/r/requests-board.json +1 -1
  38. package/r/shared-chat.json +6 -6
  39. package/r/task-board.json +2 -2
  40. package/r/task-list-viewer.json +2 -2
  41. package/r/task-mentions.json +4 -4
  42. package/r/utils.json +6 -0
  43. package/r/version-history.json +2 -2
  44. package/r/viewer-code.json +2 -2
  45. package/r/viewer-frame.json +6 -6
  46. package/r/viewer-html.json +4 -4
  47. package/r/viewer-image.json +2 -2
  48. package/r/viewer-markdown.json +5 -5
  49. package/r/viewer-pdf.json +3 -3
  50. package/r/viewers.json +6 -6
  51. package/r/windows.json +1 -1
package/r/pi-app.json CHANGED
@@ -4,32 +4,32 @@
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 panel (versions, file viewer, auto-open of new artifacts) in the ArtifactWorkspace panel, a full-screen sheet on a phone; it draws files with the kinds the app passes in artifactKinds (defaultKinds of the pi-app-kinds item is the default list). layout=\"embedded\" drops the left column for one compact top bar (title, History, Library, New) that joins an app-shell screen header. 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.4.41",
8
- "@hachej/boring-files@^0.4.41",
7
+ "@hachej/boring-ui-kit@^0.4.42",
8
+ "@hachej/boring-files@^0.4.42",
9
9
  "react@^19.0.0",
10
10
  "react-dom@^19.0.0",
11
11
  "lucide-react@^1.51.0"
12
12
  ],
13
13
  "registryDependencies": [
14
- "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.41/r/pi-chat.json",
15
- "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.41/r/pi-chat-plugins.json",
16
- "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.41/r/pi-artifacts.json",
17
- "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.41/r/pi-workspace.json",
18
- "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.41/r/viewer-frame.json",
19
- "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.41/r/utils.json",
20
- "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.41/r/button.json",
21
- "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.41/r/file-tree.json"
14
+ "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.42/r/pi-chat.json",
15
+ "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.42/r/pi-chat-plugins.json",
16
+ "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.42/r/pi-artifacts.json",
17
+ "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.42/r/pi-workspace.json",
18
+ "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.42/r/viewer-frame.json",
19
+ "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.42/r/utils.json",
20
+ "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.42/r/button.json",
21
+ "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.42/r/file-tree.json"
22
22
  ],
23
23
  "files": [
24
24
  {
25
25
  "path": "registry/pi-app/agent-workspace.tsx",
26
- "content": "'use client';\n\nimport '@hachej/boring-ui-kit/file-tree.css';\n\nimport { Drawer, DrawerContent, DrawerTitle } from '@/components/ui/drawer';\nimport { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';\nimport type { ComponentProps, ReactNode } from 'react';\nimport type { ResourceClient, ResourceLocator } from '@hachej/boring-files';\nimport { createResourceClient } from '@hachej/boring-files/remote';\nimport { connectRevisionProvider } from '@hachej/boring-files/revision';\nimport { workspacePath } from '@hachej/boring-files/file-types';\nimport { checkBlobBase, parseBlobPointer, withBlobPointers } from '@hachej/boring-files/blob';\nimport type { BlobPointer } from '@hachej/boring-files/blob';\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 '../file-tree/file-tree';\nimport { frenchAppLabels } from './app-labels-fr';\nimport { chatTextFor } from '../pi-chat/locale';\nimport type { ChatLocale } from '../pi-chat/locale';\nimport type { FileTreeViewProps } from '../file-tree/file-tree';\nimport type { ResourceIdentity } from '@hachej/boring-files/remote';\nimport type { ChatController } from '@hachej/boring-ui-kit/native-chat';\nimport { useArtifactFollow } from '@hachej/boring-ui-kit/chat-react';\nimport { PiChat } from '../pi-chat/pi-chat';\nimport { withChatPlugins } from '../pi-chat-plugins/chat-plugins';\nimport { artifactKey, createTaskArtifact, parseTaskArtifact, taskSubjectKey } from '../pi-artifacts/artifact';\nimport type { ArtifactDescriptor, ArtifactHostViewApi, ArtifactsConfig } from '../pi-artifacts/artifact';\nimport type { 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 '../viewer-frame/viewer-frame';\nimport type { ViewerShare } from '../viewer-frame/viewer-frame';\nimport type { InteractiveHtml } from '../viewer-frame/interactive-html';\nimport { noKinds } from './viewer-kinds';\nimport type { PanelKind } from './viewer-kinds';\nimport { Button } from '@/components/ui/button';\nimport { Separator } from '@/components/ui/separator';\nimport { BlockActions } from '../button/actions';\nimport type { BlockAction } from '../button/actions';\nimport { ChatTextProvider, useMergedText } from '../pi-chat/labels';\nimport { cn, PHONE_BELOW, withDefaults } from '../utils/utils';\nimport { readFlag, writeFlag } from '../utils/persisted';\nimport { AppTextProvider, defaultAppIcons, defaultAppLabels } from './app-labels';\nimport type { AppIcons, AppLabels } from './app-labels';\nimport { ArtifactPanel } from './artifact-panel';\nimport type { CustomViewers, SavedRevision, ViewerOptions } from './artifact-panel';\nimport { FileViewer } from './file-viewer';\nimport { ImageViewer } from '../pi-chat/image-viewer';\nimport { thumbnail } from '../pi-chat/composer';\nimport { useRevisionAttachments } from './use-revision-attachments';\nimport { imageData } from './revision-files';\nimport { SessionsPane, SessionsToggle } from './sessions';\nimport { focusHistoryRow, historyColumnFits, useHistoryOpen } from './history-column';\nimport type { HistoryPlacement } from './history-column';\nimport type { SessionsView, WorkspaceAgents } from './sessions';\nimport { WorkspaceBar } from './workspace-bar';\nimport type { WorkspaceBarPanel } from './workspace-bar';\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 { HistoryColumn, HistoryColumnToggle, historyColumnFits, useHistoryColumn } from './history-column';\nexport type { HistoryPlacement } from './history-column';\nexport { WorkspaceBar } from './workspace-bar';\nexport type { WorkspaceBarPanel, WorkspaceBarProps } from './workspace-bar';\nexport { ConversationList, ConversationHistory } from '../pi-chat/history';\nexport { FileTree } from '../file-tree/file-tree';\nexport type { SessionsView, WorkspaceAgent, WorkspaceAgents } from './sessions';\nexport { useConversations } from '../pi-chat/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;\ntype ImageContent = Parameters<NonNullable<PiChatProps['onOpenImage']>>[0];\n\n/**\n * Large files (blob pointers): the workspace holds a small pointer file (`<name>.blob.json`, `@hachej/boring-files/blob`) for each\n * large file, and the host serves its bytes at `GET <blobBase><encodeURIComponent(id)>`. The Library lists a pointer under the file's\n * name, size and type, and the viewers show it from that URL (an image inline, a PDF in the PDF viewer, anything else as a download).\n */\nexport interface WorkspaceBlobs {\n /** Where the host serves blob bytes: a same-origin path starting with `/` (default `/_files/`). Anything else is refused (a `TypeError`). */\n readonly blobBase?: string | undefined;\n /**\n * The host's large-file upload, used by Library uploads above `uploads.maxBytes`: it stores the bytes and writes the pointer file\n * itself, then resolves with the pointer it wrote (checked with `parseBlobPointer`); the Library reloads its listing and writes\n * nothing. `onProgress` drives the row's progress bar, `signal` its cancel button; a refusal rejects with `{ error: { code, message } }`.\n * Without it a file above the cap is refused as today.\n */\n readonly uploadBlob?: ((file: File, options: { readonly signal: AbortSignal; readonly onProgress: (progress: { readonly loaded: number; readonly total: number }) => void }) => Promise<BlobPointer>) | undefined;\n}\n\n/**\n * Where the viewers read and write: the host's resource handler (`createResourceHandler` of `@hachej/boring-files/remote`) and its file history.\n * When the endpoint also answers the revision protocol's discovery (`createRevisionHandler` serves both), the page shows a read-only\n * Library of its files (open, and version history with `history`); a plain resource handler has no listing, so there is no Library.\n */\nexport interface WorkspaceResources extends WorkspaceBlobs {\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 * `default`: the sessions pane on the left, the chat in the center and the artifact panel on the right. `embedded`: for a page set\n * inside a host's screen (an app-shell screen, a hub page): no left column at any width, and one compact top bar with the\n * conversation title and History, Library and New as icon buttons (a popover on a wide workspace, a sheet on a phone) followed by\n * `controls`. Inside an app-shell screen the bar's buttons go into the shell's header, so the page has one row.\n */\n readonly layout?: 'default' | 'embedded' | undefined;\n /**\n * The side panel's width when it first opens, before the person drags the divider (then the dragged width is kept for the session):\n * pixels, or a fraction of the workspace's width when at most 1. Without it the panel leaves the chat 420px.\n */\n readonly panelWidth?: number | undefined;\n /** `embedded` only: the host's own panels in the bar, after History and Library (a popover on a wide workspace, a sheet on a phone). */\n readonly barPanels?: readonly WorkspaceBarPanel[] | undefined;\n /**\n * `embedded` only: a fixed leading title for the bar, normally the app's name. It stays whatever the conversation is called; the\n * conversation title then follows it as a muted second element (on a phone it is left to History). Without it the bar shows the\n * conversation title alone, as before.\n */\n readonly title?: string | undefined;\n /**\n * Where the Library of a `revisionProvider` opens. `panel` (default): the artifact column, or a bottom drawer on phones.\n * `side`: 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?: 'panel' | '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' | 'capabilities'> | 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: ChatController | 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 /** Place the sessions pieces in host navigation. Default: SessionsPane. False leaves navigation entirely to the host; conversations still powers chat Fork. */\n readonly sessions?: false | ((props: ComponentProps<typeof SessionsPane>) => ReactNode) | undefined;\n /**\n * `column` (default): the conversations are the pane's side column, open or closed as this viewer left it; while an open panel leaves\n * the chat too narrow beside it, the column steps aside and the chat's History opens the popover. `popover`: History is always the popover.\n */\n readonly history?: HistoryPlacement | undefined;\n /** Recognise artifacts in tool results that carry no descriptor (`ArtifactsConfig.detect`). */\n readonly detect?: ArtifactsConfig['detect'] | undefined;\n /**\n * Every artifact kind the chat's cards, the artifact panel and the file viewer resolve through, in order (the first match wins): an\n * `ArtifactKind` (match, label, icon, and a `renderer` or a lazily loaded `load`) or a document kind. The workspace knows no kind of its\n * own. The pi-app-kinds item's `defaultKinds({ locale, comments })` is the default list (maquette, diagram, mock-up, records, then\n * Markdown, HTML, SVG, CSV, image and PDF): pass it, put the app's own kinds before it (`[...mine, ...defaultKinds()]`) so they win, or\n * pass a list of your own. Build it once (`useMemo`): a new list re-resolves every open view.\n */\n readonly artifactKinds?: readonly PanelKind[] | 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 & ArtifactHostViewApi) => 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 layout keys (panel width and floating chat for the session; whether the sessions column is open, per viewer). */\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?: WorkspaceBlobs | undefined }\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 = 260, LIBRARY_WIDTH = 320, CHAT_MIN = 360, VIEWER_MIN = 360;\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({ layout = 'default', barPanels, panelWidth, title, controller, conversationId, chat = {}, labels, icons, panelActions, connecting, conversations, sessions, history: historyPlacement = 'column', resources, revisionProvider, libraryPlacement = 'panel', locale, fileTree: treeOptions, uploads, agents, detect, artifactKinds, viewers, interactive, share, opened: controlled,\n defaultOpened = null, onOpenedChange, onUnsavedChange, panels, autoOpen = true, fileBack, floatingChat, chatTop, controls, storageKey = 'boring.agent-workspace', sheetBelow = PHONE_BELOW, drawerBelow = PHONE_BELOW, floatBelow, className }: AgentWorkspaceProps) {\n const [own, setOwn] = useState<OpenedView | null>(defaultOpened);\n const [panelLibrary, setPanelLibrary] = useState(false);\n const opened = controlled !== undefined ? controlled : own;\n // eslint-disable-next-line react-hooks/refs -- latest-value ref assigned in render, read only by event handlers, effects and async callbacks\n const change = useRef(onOpenedChange); change.current = onOpenedChange;\n const isControlled = controlled !== undefined;\n const unsaved = useRef(false);\n // eslint-disable-next-line react-hooks/refs -- latest-value ref assigned in render, read only by event handlers, effects and async callbacks\n const currentView = useRef(opened); currentView.current = opened;\n // eslint-disable-next-line react-hooks/refs -- latest-value ref assigned in render, read only by event handlers, effects and async callbacks\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 const beforeLeave = useRef<(() => Promise<boolean>) | null>(null);\n const registerBeforeLeave = useCallback((flush: (() => Promise<boolean>) | null) => { beforeLeave.current = flush; }, []);\n const leaving = useRef(false);\n const guard = useCallback(async () => {\n if (leaving.current) return false;\n if (!unsaved.current) return true;\n const current = currentView.current;\n leaving.current = true;\n try {\n const saved = await beforeLeave.current?.();\n if (currentView.current !== current) return false;\n return saved === true || !unsaved.current || Boolean(globalThis.confirm?.('This file has unsaved or unconfirmed changes. Discard the local draft and leave this file?'));\n } finally { leaving.current = false; }\n }, []);\n const setOpened = useCallback(async (next: OpenedView | null): Promise<boolean> => {\n const current = currentView.current;\n if (isFile(current) && isFile(next) && current.path === next.path) { setPanelLibrary(false); return true; }\n if (!await guard()) return false;\n noteUnsaved(false);\n setPanelLibrary(false);\n if (!isControlled) setOwn(next); change.current?.(next);\n return true;\n }, [guard, isControlled, noteUnsaved]);\n const [fullscreen, setFullscreen] = useState(false);\n const [centerMode, setCenterMode] = useState<'chat' | 'library'>('chat');\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 openLibrary = useCallback(async () => {\n if (libraryPlacement === 'panel') {\n if (!await guard()) return;\n noteUnsaved(false); setPanelLibrary(value => !value);\n } else setCenterMode('library');\n setFullscreen(false);\n }, [guard, libraryPlacement, noteUnsaved]);\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 // With a revision provider, `resources` carries only the blob options; without one it is the resource handler too.\n const remote = revisionProvider ? undefined : resources as WorkspaceResources;\n // eslint-disable-next-line react-hooks/refs -- the host's latest fetch, read when a request goes out; clients built once keep calling the current one\n const fetcher = useRef(remote?.fetch); fetcher.current = remote?.fetch;\n const endpoint = remote ? String(remote.endpoint) : undefined;\n const historyEndpoint = remote?.history === undefined ? undefined : String(remote.history);\n const identity = revisionProvider?.identity ?? remote!.identity;\n const blobBase = checkBlobBase(resources?.blobBase);\n const hostUploadBlob = resources?.uploadBlob;\n const appLabels = text.labels;\n // The host's pointer is checked with the same validator the host uses; an invalid one is a refusal the Library shows.\n const uploadBlob = useMemo(() => hostUploadBlob && (async (file: File, options: Parameters<NonNullable<WorkspaceBlobs['uploadBlob']>>[1]) => {\n const pointer = parseBlobPointer(JSON.stringify(await hostUploadBlob(file, options) ?? null));\n if (pointer === undefined || 'kind' in pointer) throw { error: { code: 'invalid_pointer', message: appLabels.invalidBlobPointer(file.name) } };\n return pointer;\n }), [hostUploadBlob, appLabels]);\n const identityKey = JSON.stringify(identity);\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 // Resources only: a Library over the endpoint's own listing, when it answers the revision protocol's discovery for the same\n // person (`createRevisionHandler` serves the resource calls and the listing on one route). A plain resource handler refuses: no Library.\n const [listing, setListing] = useState<{ readonly key: string; readonly provider: RevisionProvider }>();\n const listingKey = revisionProvider || endpoint === undefined ? undefined : JSON.stringify([endpoint, identity]);\n useEffect(() => {\n if (listingKey === undefined) return;\n const abort = new AbortController();\n connectRevisionProvider({ endpoint: new URL(endpoint!, globalThis.location?.href), fetch: request => fetcher.current!(request), signal: abort.signal }).then(provider => {\n const { principalId, scopeId, initiatorId } = provider.identity;\n if (!abort.signal.aborted && principalId === identity.principalId && scopeId === identity.scopeId && initiatorId === identity.initiatorId) setListing({ key: listingKey, provider });\n }, () => { /* no listing on this endpoint */ });\n return () => abort.abort();\n }, [listingKey]); // eslint-disable-line react-hooks/exhaustive-deps\n // The Library's binding: the host's revision provider, or the listing above with the versions of `resources.history`.\n // eslint-disable-next-line react-hooks/refs -- the functions built here read refs only when a request, an event or an effect calls them, never during render\n const libraryProvider = useMemo(() => revisionProvider ?? (listing && listing.key === listingKey ? { ...listing.provider, history: history ?? listing.provider.history } : undefined),\n [revisionProvider, listing, listingKey, history]);\n // The viewers' client: the Library's binding when there is one (its calls carry the binding the revision protocol checks), else the plain resource client.\n // With `resources`, the binding is discovered after the first render on the same endpoint for the same person: it takes over the calls of\n // one stable client, so a viewer already open keeps its bytes and its editor instead of reloading when the binding arrives.\n const discovered = useRef(libraryProvider);\n // eslint-disable-next-line react-hooks/refs -- latest-value ref: a viewer may read through the client during its own render or layout effect, before this component's effects run\n discovered.current = libraryProvider;\n const client = useMemo((): ResourceClient => {\n if (revisionProvider) return revisionProvider;\n // eslint-disable-next-line react-hooks/refs -- the client's functions read refs only when a request calls them, never during render\n const plain = createResourceClient({ identity, endpoint: new URL(endpoint!, globalThis.location?.href), publication: true, reconciliation: true, fetch: request => fetcher.current!(request) });\n const current = (): ResourceClient => discovered.current ?? plain;\n return {\n read: (request, signal) => current().read(request, signal),\n publish: (request, signal) => current().publish!(request, signal),\n lookup: (operationId, signal) => current().lookup!(operationId, signal),\n rename: (request, signal) => current().rename!(request, signal),\n delete: (request, signal) => current().delete!(request, signal),\n };\n }, [revisionProvider, endpoint, identityKey]); // eslint-disable-line react-hooks/exhaustive-deps\n const [imagePreview, setImagePreview] = useState<{ readonly images: readonly ImageContent[]; readonly index: number; readonly controller: typeof controller; readonly client: typeof client; readonly conversationId: typeof conversationId }>();\n const openImage = useCallback((image: ImageContent, images: readonly ImageContent[] = [image]) => {\n const index = images.indexOf(image);\n if (index >= 0 && images.every(item => thumbnail(item.mimeType, item.data))) setImagePreview({ images: images.slice(), index, controller, client, conversationId });\n }, [controller, client, conversationId]);\n // eslint-disable-next-line react-hooks/refs -- the functions built here read refs only when a request, an event or an effect calls them, never during render\n const preview = imagePreview && !chat.onOpenImage && imagePreview.controller === controller && imagePreview.client === client && imagePreview.conversationId === conversationId ? imagePreview : undefined;\n // eslint-disable-next-line react-hooks/set-state-in-effect -- a new controller, client, conversation or host image handler drops the preview, once per change\n useEffect(() => { setImagePreview(undefined); }, [controller, client, conversationId, chat.onOpenImage]);\n const active = isArtifact(opened) && opened.conversation === conversationId ? opened : null;\n const follow = useArtifactFollow({ controller, conversationId, detect, active, autoOpen,\n onOpen: selection => { if (conversationId !== undefined) void setOpened({ kind: selection.descriptor.type === 'task' ? 'task' : 'artifact', conversation: conversationId, ...selection }); },\n unsaved: () => unsaved.current,\n narrow: () => globalThis.matchMedia?.(`(width < ${sheetBelow}px)`).matches === true,\n showing: path => showsPath(currentView.current, path),\n openPresent: path => { if (unsaved.current) return false; void setOpened({ kind: 'file', path }); return true; },\n openTask: subject => {\n if (unsaved.current || conversationId === undefined || !panels?.['task']) return false;\n void setOpened({ kind: 'task', conversation: conversationId, descriptor: createTaskArtifact(subject), follow: true });\n return true;\n },\n showingTask: subject => {\n const current = currentView.current;\n const descriptor = current?.kind === 'task' && current['conversation'] === conversationId ? parseTaskArtifact(current['descriptor']) : undefined;\n return descriptor !== undefined && taskSubjectKey(descriptor.subject) === taskSubjectKey(subject);\n },\n answer: chat.actions?.answer });\n const { onShown, onFailed } = follow;\n const kinds = artifactKinds ?? noKinds;\n const options: ViewerOptions = useMemo(() => ({ client, identity, history, viewers, kinds, interactive, share, onShown, onFailed, onUnsavedChange: noteUnsaved, onBeforeLeaveChange: registerBeforeLeave, blobBase }), [client, identityKey, history, viewers, kinds, interactive, share, onShown, onFailed, noteUnsaved, registerBeforeLeave, blobBase]); // eslint-disable-line react-hooks/exhaustive-deps\n const locate = revisionProvider?.locate ?? remote?.locate ?? defaultLocate;\n const readOnlyLibrary = !revisionProvider;\n const [fileBinding, setFileBinding] = useState<{ readonly provider: RevisionProvider; readonly tree: FileTreeController }>();\n useEffect(() => {\n if (!libraryProvider) return;\n // The Library reads its listings through `withBlobPointers`: each pointer file is resolved there, once, to the file it stands for.\n const tree = createFileTreeController({ revisionProvider: withBlobPointers(libraryProvider, blobBase) });\n // eslint-disable-next-line react-hooks/set-state-in-effect -- this effect owns the disposable tree (created and disposed here, StrictMode-safe); state only publishes it\n setFileBinding({ provider: libraryProvider, tree });\n void tree.refresh();\n return () => tree.dispose();\n }, [libraryProvider, blobBase]);\n // eslint-disable-next-line react-hooks/refs -- the functions built here read refs only when a request, an event or an effect calls them, never during render\n const libraryController = fileBinding?.provider === libraryProvider ? fileBinding?.tree : undefined;\n // Uploads and the upload notice belong to a revision provider only; the resources Library is read-only.\n const fileTree = revisionProvider ? libraryController : undefined;\n const embedded = layout === 'embedded';\n // Where the Library opens (`libraryPlacement`); embedded, it is the bar's Library button instead.\n // eslint-disable-next-line react-hooks/refs -- the functions built here read refs only when a request, an event or an effect calls them, never during render\n const placed = Boolean(libraryProvider) && !embedded;\n const libraryInPane = placed && libraryPlacement === 'pane';\n const librarySide = placed && libraryPlacement === 'side';\n const libraryOpen = placed && libraryPlacement === 'center' && centerMode === 'library';\n // The workspace's change feed: every file view below reloads when its seq moves (agent writes, saves, shell changes).\n const feed = useChangeFeed(libraryProvider);\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 (!libraryController || (Object.is(refreshedKey.current, refreshKey) && refreshedSeq.current === feed.seq)) return;\n refreshedKey.current = refreshKey;\n refreshedSeq.current = feed.seq;\n const { query, expanded } = libraryController.getSnapshot();\n if (query) void libraryController.search(query);\n else for (const directory of ['', ...expanded]) void libraryController.refresh(directory);\n }, [libraryController, refreshKey, feed.seq]);\n const openFile = useCallback((path: string) => { setOpened({ kind: 'file', path }); }, [setOpened]);\n // The file on show was renamed, moved or deleted from the Library: follow it to its new path, or close it (its old path is gone).\n const followFile = (from: string, to: string | null) => {\n const current = currentView.current;\n if (!isFile(current) || current.path !== from) return;\n const next = to === null ? null : { kind: 'file' as const, path: to };\n noteUnsaved(false);\n if (!isControlled) setOwn(next); change.current?.(next);\n };\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 // eslint-disable-next-line react-hooks/exhaustive-deps -- one mention cache per provider instance: revisionProvider is the cache's identity, not an input\n const mentionResults = useMemo(() => ({ seq: undefined as number | undefined, results: new Map<string, readonly FileEntry[]>() }), [revisionProvider]);\n // eslint-disable-next-line react-hooks/refs -- latest-value ref assigned in render, read only by event handlers, effects and async callbacks\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 // eslint-disable-next-line react-hooks/immutability -- the mention cache is this binding's own mutable holder, reset when the feed reports a change\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 // Thumbnails and voice playback read the original upload and MIME through the same provider as the file viewer.\n preview: async (path: string, signal: AbortSignal) => {\n const read = await revisionProvider.read({ target: revisionProvider.locate(path), revision: { kind: 'latest' } }, signal);\n return read.kind === 'available' ? { mimeType: read.snapshot.mediaType, data: imageData(read.snapshot.bytes) } : undefined;\n },\n } : undefined, [revisionProvider, openFile, mentionResults]);\n // The search function changes only with the binding; the feed's seq rides along as the picker's generation.\n // eslint-disable-next-line react-hooks/refs -- the functions built here read refs only when a request, an event or an effect calls them, never during render\n const mentionsForChat = useMemo(() => mentions && { ...mentions, generation: feed.seq }, [mentions, feed.seq]);\n const [attachmentFailure, setAttachmentFailure] = useState<{ readonly tree: FileTreeController; readonly reasons: readonly string[] }>();\n // Primitives only in the memo: a host's inline `labels` object would otherwise rebuild the chat's attachments on every render.\n const uploadAccept = uploads?.accept, inlineImages = uploads?.inlineImages === true, maxBytes = uploads?.maxBytes;\n const tooLarge = maxBytes !== undefined ? text.labels.attachmentTooLarge(sizeLabel(maxBytes)) : undefined;\n const revisionAttachments = useRevisionAttachments({ fileTree, accept: uploadAccept, inlineImages, maxBytes, tooLarge, onPreparationFailure: (name, reason) => {\n if (fileTree && fileTree.getSnapshot().lifecycle === 'active') setAttachmentFailure(current => ({ tree: fileTree,\n reasons: [...(current?.tree === fileTree ? current.reasons : []), `${name}: ${reason}`] }));\n } });\n const attachments = useMemo(() => revisionAttachments && { ...revisionAttachments, upload: (files: File[], signal: AbortSignal) => {\n setAttachmentFailure(undefined);\n return revisionAttachments.upload(files, signal);\n } }, [revisionAttachments]);\n\n // ---- Artifacts: cards open the panel; the agent's new ones open it too.\n const 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 || panelLibrary);\n // Record a close only after the host's unsaved-changes guard accepted it.\n const close = async () => { if (panelLibrary) { setPanelLibrary(false); return true; } if (!await setOpened(null)) return false; follow.recordClosed(); setFullscreen(false); return true; };\n const newestOf = (key: string) => follow.versions.filter((version): version is ArtifactDescriptor => version.type !== 'task' && artifactKey(version) === key);\n const artifacts: ArtifactsConfig = useMemo(() => ({\n open: follow.open, isOpen: follow.isOpen, ...(detect ? { detect } : {}), kinds,\n }), [follow.open, follow.isOpen, detect, kinds]);\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 [paneOpen, setPaneOpen] = useHistoryOpen(`${storageKey}.history-column`, true);\n const paneId = `${storageKey}-sessions`;\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 setPaneOpen(true);\n };\n // eslint-disable-next-line react-hooks/set-state-in-effect -- widening past the drawer breakpoint closes the drawer, once per change\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, onClose?: () => void) => libraryController\n ? <FileTreeView variant=\"list\" refresh={libraryPlacement !== 'panel'} title={text.labels.library} {...(onClose ? { onClose } : {})} key={JSON.stringify([libraryProvider?.workspace, libraryProvider?.identity])} {...(locale ? { locale } : {})} {...viewOptions}\n {...(readOnlyLibrary ? { upload: false, history: history !== undefined } : {})} {...(maxBytes !== undefined ? { maxBytes, ...(tooLarge ? { tooLarge } : {}) } : {})} {...(uploadBlob ? { uploadBlob } : {})} controller={libraryController} historyKey={feed.seq} onOpen={onOpen} onRenamed={(from, to) => followFile(from, to)} onDeleted={path => followFile(path, null)} {...(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 // `history=\"popover\"` keeps the conversations out of the pane. With an open panel the column steps aside unless column, panel and chat fit.\n const paneConversations = historyPlacement === 'column' ? conversations : undefined;\n const hasNavigation = !embedded && sessions !== false && Boolean(paneConversations || placed);\n const stepAside = Boolean(paneConversations) && hasNavigation && !narrow && panelOpen && !historyColumnFits(width, VIEWER_MIN);\n const docked = hasNavigation && width > 0 && !narrow && paneOpen && !stepAside;\n const popoverHistory = historyPlacement === 'popover' || stepAside;\n const toggle = hasNavigation && !docked && !drawer && !stepAside && <SessionsToggle navigation={placed} open={narrow ? drawer : paneOpen} drawer={narrow} controls={narrow ? undefined : paneId}\n onToggle={() => { if (narrow) setDrawer(value => !value); else { setPaneOpen(!paneOpen); if (!paneOpen) focusHistoryRow(paneId); } }} />;\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} variant=\"ghost\" size=\"icon-sm\" aria-hidden=\"true\" tabIndex={-1} className=\"invisible md:-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 hostControls = typeof controls === 'function' ? controls({ panelOpen }) : controls ?? chat.controls;\n const header = <>{conversations?.onNew && <Button variant=\"ghost\" size=\"icon-sm\" data-testid=\"workspace-new-chat\" aria-label={text.labels.newChat} title={text.labels.newChat} className=\"md:hidden\" onClick={conversations.onNew}><text.icons.newChat data-icon=\"inline-start\" aria-hidden=\"true\" /></Button>}{hostControls}</>;\n const conversationTitle = conversations?.items.find(item => item.id === conversationId)?.title;\n // pi-app ships every composer feature item: Markdown, the `/` menu, `@` mentions, the model pill, voice messages, the phone camera.\n // eslint-disable-next-line react-hooks/refs -- the functions built here read refs only when a request, an event or an effect calls them, never during render\n const chatProps: PiChatProps | undefined = controller && withChatPlugins({ ...(mentionsForChat ? { mentions: mentionsForChat } : {}), ...(attachments ? { attachments } : {}), ...(locale ? { locale } : {}), ...chat, controller, artifacts, onOpenFile: chat.onOpenFile ?? chat.mentions?.open ?? openFile, onOpenImage: chat.onOpenImage ?? openImage, ...(conversations ? { conversations, historyList: popoverHistory, showHistory: chat.showHistory ?? popoverHistory, conversationTitle, onRenameTitle: conversations.rename && conversationId ? (title: string) => conversations.rename!(conversationId, title) : undefined } : {}),\n headerStart: <>{toggle}{chat.headerStart}</>, ...(header === undefined ? {} : { controls: header }),\n // Embedded: the bar above replaces the chat's header (History, New and the host's controls are in it); conversations stay for Fork.\n ...(embedded ? { header: false, historyList: false, showHistory: false } : {}) });\n const bar = embedded && <WorkspaceBar title={title ?? conversationTitle ?? chatText.labels.title} {...(title && conversationTitle ? { subtitle: conversationTitle } : {})} conversations={conversations} narrow={narrow}\n library={libraryController ? onPicked => libraryTree(path => { openFile(path); onPicked(); }, onPicked) : undefined} panels={barPanels}\n controls={<><BlockActions actions={chat.headerActions} testId=\"chat-action\" menuLabel={chatText.labels.moreActions} />{hostControls}</>} />;\n const docked_chat = <div data-testid=\"workspace-center\" className=\"flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden\">\n {bar}\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 px-3 py-2 md:gap-3 md:px-4 md:py-2.5\">{toggleSpace}</div><Separator /></>}{connecting}</>}\n {toggle && <div ref={toggleRow} className=\"pointer-events-none absolute top-0 left-0 z-10 flex items-center px-3 md: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 ...(placed && libraryPlacement === 'panel' ? [{ id: 'library', label: text.labels.library, icon: text.icons.library, placement: 'menu' as const, onSelect: openLibrary }] : []),\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 const sessionProps: ComponentProps<typeof SessionsPane> = { id: paneId, conversations: paneConversations, drawer: narrow, onClose: () => setDrawer(false), onChat: () => setCenterMode('chat'), onCollapse: () => setPaneOpen(false), title: labels?.sessionsTitle,\n agents, view: paneView, onViewChange: changePaneView,\n ...(librarySide ? { library: { selected: sideOpen, onSelect: toggleSide, side: true } } : placed && !libraryInPane ? { library: { selected: libraryOpen || panelLibrary, onSelect: openLibrary } } : {}),\n ...(libraryInPane ? { libraryContent: (onPicked: () => void) => libraryTree(path => { openFile(path); onPicked(); }) } : {}),\n };\n return <AppTextProvider value={text}><ChatTextProvider value={chatText}><div ref={root} data-boring=\"agent-workspace\" data-layout={layout} data-sessions={!hasNavigation ? undefined : narrow ? (drawer ? 'drawer' : 'closed') : docked ? 'docked' : 'hidden'}\n className={cn('pi-chat 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 {/* eslint-disable-next-line react-hooks/refs -- the functions built here read refs only when a request, an event or an effect calls them, never during render */}\n {hasNavigation && (docked || (narrow && drawer)) && (sessions ? sessions(sessionProps) : <SessionsPane {...sessionProps} />)}\n <DockMain><ArtifactWorkspace open={panelOpen && !(panelLibrary && narrow)} onClose={close} panelLabel={text.labels.artifactPanel} labels={{ resize: text.labels.resizePanel, floatHint: text.labels.floatHint }} fullscreen={fullscreen} onFullscreenChange={setFullscreen} storageKey={`${storageKey}.panel-width`} {...(panelWidth === undefined ? {} : { defaultWidth: panelWidth })}\n sheetBelow={Math.max(CHAT_MIN + VIEWER_MIN, docked ? 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 || libraryPlacement === 'panel' ? null : <section data-testid=\"workspace-library-view\" aria-label={text.labels.library} className=\"flex min-h-0 flex-1 flex-col\">\n <div className=\"min-h-0 flex-1 overflow-auto\">{libraryTree(openFile, () => setCenterMode('chat'))}</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 {panelLibrary ? <section data-testid=\"workspace-library-side\" aria-label={text.labels.library} className=\"flex min-h-0 flex-1 flex-col\"><div className=\"min-h-0 flex-1 overflow-auto\">{libraryTree(openFile, () => setPanelLibrary(false))}</div></section> : 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])} onBeforeLeaveChange={registerBeforeLeave} 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, onShown, onFailed }) : 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 }} >\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 <div className=\"min-h-0 flex-1 overflow-auto\">{libraryTree(path => { void setOpened({ kind: 'file', path }).then(opened => { if (opened && narrow) setSideOpen(false); }); }, () => setSideOpen(false))}</div>\n </section>}\n </Dock>}\n </DockLayout>\n {preview && <ImageViewer images={preview.images} index={preview.index} labels={chatText.labels} testId=\"conversation-image\"\n onIndexChange={index => setImagePreview({ ...preview, index })} onClose={() => setImagePreview(undefined)} />}\n {/* eslint-disable-next-line react-hooks/refs -- the functions built here read refs only when a request, an event or an effect calls them, never during render */}\n {panelLibrary && narrow && <Drawer open showSwipeHandle onOpenChange={next => { if (!next) setPanelLibrary(false); }}><DrawerContent aria-label={text.labels.library} className=\"pi-chat min-h-[80dvh] max-h-[80dvh]\"><DrawerTitle className=\"sr-only\">{text.labels.library}</DrawerTitle><div data-testid=\"workspace-library-side\" className=\"min-h-0 flex-1 overflow-auto pb-[env(safe-area-inset-bottom)]\">{libraryTree(openFile, () => setPanelLibrary(false))}</div></DrawerContent></Drawer>}\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 variant=\"link\" 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 // eslint-disable-next-line react-hooks/refs -- the floating choice is held while the Library covers the chat; the layout effect above keeps it current\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 * A number that moves when the provider's files change (`RevisionProvider.changes`), coalesced over `settleMs` so a burst (a shell\n * writing many files) reloads once. `live` is false without a feed or after the feed was refused; views then keep their own refresh.\n * A hidden tab holds no feed: a browser allows few connections per host, and every tab of a share link holding a stream starves the\n * others (remote chat releases its stream the same way); `live` is false meanwhile. Shown again, it reconnects after the last event it\n * acted on (`since`; 0 when it had none, which the feed answers with a `resnapshot`), so a change made while hidden or while reconnecting\n * arrives on the new feed and moves the number then, after the feed is connected.\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 const shown = usePageShown();\n // The provider connected last, and the protocol seq of the last event the views reloaded for.\n const connected = useRef<{ readonly provider: RevisionProvider; seen: number | undefined } | undefined>(undefined);\n useEffect(() => {\n // eslint-disable-next-line react-hooks/set-state-in-effect -- the feed's state is reset for the new provider when this effect subscribes to it\n if (!provider?.changes) { setState({ provider, seq: undefined, live: false }); return; }\n if (!shown) { setState(current => current.provider === provider && current.live ? { ...current, live: false } : current); return; }\n const stop = new AbortController();\n let timer: ReturnType<typeof setTimeout> | undefined, latest: number | undefined;\n // A second connection to the same provider follows a hidden period: it resumes after the last event acted on. A first connection has nothing to catch up.\n const since = connected.current?.provider === provider ? connected.current.seen ?? 0 : undefined;\n const cursor = connected.current?.provider === provider ? connected.current : { provider, seen: undefined };\n connected.current = cursor;\n const move = () => { cursor.seen = latest; setState(current => ({ provider, seq: current.provider === provider ? (current.seq ?? 0) + 1 : 1, live: true })); };\n setState(current => ({ provider, seq: current.provider === provider ? current.seq : undefined, live: true }));\n void (async () => {\n try {\n for await (const event of provider.changes!({ ...(since === undefined ? {} : { since }), signal: stop.signal })) {\n latest = event.seq;\n // An event still settling when the feed closes is not acted on, so the next connection asks for it again.\n timer ??= setTimeout(() => { timer = undefined; if (!stop.signal.aborted) move(); }, 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(current => ({ provider, seq: current.provider === provider ? current.seq : undefined, live: false }));\n })();\n return () => { stop.abort(); clearTimeout(timer); };\n }, [provider, settleMs, shown]);\n return state.provider === provider ? state : { seq: undefined, live: false };\n}\n\n/** Whether the page is shown (`document.visibilityState`); true where there is no document. */\nfunction usePageShown(): boolean {\n const [shown, setShown] = useState(() => typeof document === 'undefined' || document.visibilityState !== 'hidden');\n useEffect(() => {\n if (typeof document === 'undefined') return;\n const update = () => setShown(document.visibilityState !== 'hidden');\n update();\n document.addEventListener('visibilitychange', update);\n return () => document.removeEventListener('visibilitychange', update);\n }, []);\n return shown;\n}\n",
26
+ "content": "'use client';\n\nimport '@hachej/boring-ui-kit/file-tree.css';\n\nimport { Drawer, DrawerContent, DrawerTitle } from '@/components/ui/drawer';\nimport { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';\nimport type { ComponentProps, ReactNode } from 'react';\nimport type { ResourceClient, ResourceLocator } from '@hachej/boring-files';\nimport { createResourceClient } from '@hachej/boring-files/remote';\nimport { connectRevisionProvider } from '@hachej/boring-files/revision';\nimport { workspacePath } from '@hachej/boring-files/file-types';\nimport { checkBlobBase, parseBlobPointer, withBlobPointers } from '@hachej/boring-files/blob';\nimport type { BlobPointer } from '@hachej/boring-files/blob';\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 '../file-tree/file-tree';\nimport { frenchAppLabels } from './app-labels-fr';\nimport { chatTextFor } from '../pi-chat/locale';\nimport type { ChatLocale } from '../pi-chat/locale';\nimport type { FileTreeViewProps } from '../file-tree/file-tree';\nimport type { ResourceIdentity } from '@hachej/boring-files/remote';\nimport type { ChatController } from '@hachej/boring-ui-kit/native-chat';\nimport { useArtifactFollow } from '@hachej/boring-ui-kit/chat-react';\nimport { PiChat } from '../pi-chat/pi-chat';\nimport { withChatPlugins } from '../pi-chat-plugins/chat-plugins';\nimport { artifactKey, createTaskArtifact, parseTaskArtifact, taskSubjectKey } from '../pi-artifacts/artifact';\nimport type { ArtifactDescriptor, ArtifactHostViewApi, ArtifactsConfig } from '../pi-artifacts/artifact';\nimport type { 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 '../viewer-frame/viewer-frame';\nimport type { ViewerShare } from '../viewer-frame/viewer-frame';\nimport type { InteractiveHtml } from '../viewer-frame/interactive-html';\nimport { noKinds } from './viewer-kinds';\nimport type { PanelKind } from './viewer-kinds';\nimport { Button } from '@/components/ui/button';\nimport { Separator } from '@/components/ui/separator';\nimport { BlockActions } from '../button/actions';\nimport type { BlockAction } from '../button/actions';\nimport { ChatTextProvider, useMergedText } from '../pi-chat/labels';\nimport { cn, PHONE_BELOW, withDefaults } from '../utils/utils';\nimport { readFlag, writeFlag } from '../utils/persisted';\nimport { AppTextProvider, defaultAppIcons, defaultAppLabels } from './app-labels';\nimport type { AppIcons, AppLabels } from './app-labels';\nimport { ArtifactPanel } from './artifact-panel';\nimport type { CustomViewers, SavedRevision, ViewerOptions } from './artifact-panel';\nimport { FileViewer } from './file-viewer';\nimport { ImageViewer } from '../pi-chat/image-viewer';\nimport { thumbnail } from '../pi-chat/composer';\nimport { useRevisionAttachments } from './use-revision-attachments';\nimport { imageData } from './revision-files';\nimport { SessionsPane, SessionsToggle } from './sessions';\nimport { focusHistoryRow, historyColumnFits, useHistoryOpen } from './history-column';\nimport type { HistoryPlacement } from './history-column';\nimport type { SessionsView, WorkspaceAgents } from './sessions';\nimport { WorkspaceBar } from './workspace-bar';\nimport type { WorkspaceBarPanel, WorkspaceBarProps } from './workspace-bar';\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 { HistoryColumn, HistoryColumnToggle, historyColumnFits, useHistoryColumn } from './history-column';\nexport type { HistoryPlacement } from './history-column';\nexport { WorkspaceBar } from './workspace-bar';\nexport type { WorkspaceBarPanel, WorkspaceBarProps } from './workspace-bar';\nexport { ConversationList, ConversationHistory } from '../pi-chat/history';\nexport { FileTree } from '../file-tree/file-tree';\nexport type { SessionsView, WorkspaceAgent, WorkspaceAgents } from './sessions';\nexport { useConversations } from '../pi-chat/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;\ntype ImageContent = Parameters<NonNullable<PiChatProps['onOpenImage']>>[0];\n\n/**\n * Large files (blob pointers): the workspace holds a small pointer file (`<name>.blob.json`, `@hachej/boring-files/blob`) for each\n * large file, and the host serves its bytes at `GET <blobBase><encodeURIComponent(id)>`. The Library lists a pointer under the file's\n * name, size and type, and the viewers show it from that URL (an image inline, a PDF in the PDF viewer, anything else as a download).\n */\nexport interface WorkspaceBlobs {\n /** Where the host serves blob bytes: a same-origin path starting with `/` (default `/_files/`). Anything else is refused (a `TypeError`). */\n readonly blobBase?: string | undefined;\n /**\n * The host's large-file upload, used by Library uploads above `uploads.maxBytes`: it stores the bytes and writes the pointer file\n * itself, then resolves with the pointer it wrote (checked with `parseBlobPointer`); the Library reloads its listing and writes\n * nothing. `onProgress` drives the row's progress bar, `signal` its cancel button; a refusal rejects with `{ error: { code, message } }`.\n * Without it a file above the cap is refused as today.\n */\n readonly uploadBlob?: ((file: File, options: { readonly signal: AbortSignal; readonly onProgress: (progress: { readonly loaded: number; readonly total: number }) => void }) => Promise<BlobPointer>) | undefined;\n}\n\n/**\n * Where the viewers read and write: the host's resource handler (`createResourceHandler` of `@hachej/boring-files/remote`) and its file history.\n * When the endpoint also answers the revision protocol's discovery (`createRevisionHandler` serves both), the page shows a read-only\n * Library of its files (open, and version history with `history`); a plain resource handler has no listing, so there is no Library.\n */\nexport interface WorkspaceResources extends WorkspaceBlobs {\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 * `default`: the sessions pane on the left, the chat in the center and the artifact panel on the right. `embedded`: for a page set\n * inside a host's screen (an app-shell screen, a hub page): no left column at any width, and one compact top bar with the\n * conversation title and History, Library and New as icon buttons (a popover on a wide workspace, a sheet on a phone) followed by\n * `controls`. Inside an app-shell screen the bar's buttons go into the shell's header, so the page has one row.\n */\n readonly layout?: 'default' | 'embedded' | undefined;\n /**\n * The side panel's width when it first opens, before the person drags the divider (then the dragged width is kept for the session):\n * pixels, or a fraction of the workspace's width when at most 1. Without it the panel leaves the chat 420px.\n */\n readonly panelWidth?: number | undefined;\n /** `embedded` only: the host's own panels in the bar, after History and Library (a popover on a wide workspace, a sheet on a phone). */\n readonly barPanels?: readonly WorkspaceBarPanel[] | undefined;\n /** Embedded bar arrangement; defaults keep the standard History, Library, host panels and New order. */\n readonly barOptions?: Pick<WorkspaceBarProps, 'panelsFirst'> | undefined;\n /**\n * `embedded` only: a fixed leading title for the bar, normally the app's name. It stays whatever the conversation is called; the\n * conversation title then follows it as a muted second element (on a phone it is left to History). Without it the bar shows the\n * conversation title alone, as before.\n */\n readonly title?: string | undefined;\n /**\n * Where the Library of a `revisionProvider` opens. `panel` (default): the artifact column, or a bottom drawer on phones.\n * `side`: 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?: 'panel' | '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' | 'capabilities'> | 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: ChatController | 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 /** Place the sessions pieces in host navigation. Default: SessionsPane. False leaves navigation entirely to the host; conversations still powers chat Fork. */\n readonly sessions?: false | ((props: ComponentProps<typeof SessionsPane>) => ReactNode) | undefined;\n /**\n * `column` (default): the conversations are the pane's side column, open or closed as this viewer left it; while an open panel leaves\n * the chat too narrow beside it, the column steps aside and the chat's History opens the popover. `popover`: History is always the popover.\n */\n readonly history?: HistoryPlacement | undefined;\n /** Recognise artifacts in tool results that carry no descriptor (`ArtifactsConfig.detect`). */\n readonly detect?: ArtifactsConfig['detect'] | undefined;\n /**\n * Every artifact kind the chat's cards, the artifact panel and the file viewer resolve through, in order (the first match wins): an\n * `ArtifactKind` (match, label, icon, and a `renderer` or a lazily loaded `load`) or a document kind. The workspace knows no kind of its\n * own. The pi-app-kinds item's `defaultKinds({ locale, comments })` is the default list (maquette, diagram, mock-up, records, then\n * Markdown, HTML, SVG, CSV, image and PDF): pass it, put the app's own kinds before it (`[...mine, ...defaultKinds()]`) so they win, or\n * pass a list of your own. Build it once (`useMemo`): a new list re-resolves every open view.\n */\n readonly artifactKinds?: readonly PanelKind[] | 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 & ArtifactHostViewApi) => ReactNode>> | undefined;\n /** Open the panel on each artifact (or new version) the agent makes, unless the person closed it during this turn. Not while the workspace is narrow enough for its sheet. 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 layout keys (panel width and floating chat for the session; whether the sessions column is open, per viewer). */\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?: WorkspaceBlobs | undefined }\n | { readonly resources: WorkspaceResources; readonly revisionProvider?: never }\n | { readonly resources?: undefined; readonly revisionProvider?: undefined }\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 = 260, LIBRARY_WIDTH = 320, CHAT_MIN = 360, VIEWER_MIN = 360;\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({ layout = 'default', barPanels, barOptions, panelWidth, title, controller, conversationId, chat = {}, labels, icons, panelActions, connecting, conversations, sessions, history: historyPlacement = 'column', resources, revisionProvider, libraryPlacement = 'panel', locale, fileTree: treeOptions, uploads, agents, detect, artifactKinds, viewers, interactive, share, opened: controlled,\n defaultOpened = null, onOpenedChange, onUnsavedChange, panels, autoOpen = true, fileBack, floatingChat, chatTop, controls, storageKey = 'boring.agent-workspace', sheetBelow = PHONE_BELOW, drawerBelow = PHONE_BELOW, floatBelow, className }: AgentWorkspaceProps) {\n const [own, setOwn] = useState<OpenedView | null>(defaultOpened);\n const [panelLibrary, setPanelLibrary] = useState(false);\n const opened = controlled !== undefined ? controlled : own;\n // eslint-disable-next-line react-hooks/refs -- latest-value ref assigned in render, read only by event handlers, effects and async callbacks\n const change = useRef(onOpenedChange); change.current = onOpenedChange;\n const isControlled = controlled !== undefined;\n const unsaved = useRef(false);\n // eslint-disable-next-line react-hooks/refs -- latest-value ref assigned in render, read only by event handlers, effects and async callbacks\n const currentView = useRef(opened); currentView.current = opened;\n // eslint-disable-next-line react-hooks/refs -- latest-value ref assigned in render, read only by event handlers, effects and async callbacks\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 const beforeLeave = useRef<(() => Promise<boolean>) | null>(null);\n const registerBeforeLeave = useCallback((flush: (() => Promise<boolean>) | null) => { beforeLeave.current = flush; }, []);\n const leaving = useRef(false);\n const guard = useCallback(async () => {\n if (leaving.current) return false;\n if (!unsaved.current) return true;\n const current = currentView.current;\n leaving.current = true;\n try {\n const saved = await beforeLeave.current?.();\n if (currentView.current !== current) return false;\n return saved === true || !unsaved.current || Boolean(globalThis.confirm?.('This file has unsaved or unconfirmed changes. Discard the local draft and leave this file?'));\n } finally { leaving.current = false; }\n }, []);\n const setOpened = useCallback(async (next: OpenedView | null): Promise<boolean> => {\n const current = currentView.current;\n if (isFile(current) && isFile(next) && current.path === next.path) { setPanelLibrary(false); return true; }\n if (!await guard()) return false;\n noteUnsaved(false);\n setPanelLibrary(false);\n if (!isControlled) setOwn(next); change.current?.(next);\n return true;\n }, [guard, isControlled, noteUnsaved]);\n const [fullscreen, setFullscreen] = useState(false);\n const [centerMode, setCenterMode] = useState<'chat' | 'library'>('chat');\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 openLibrary = useCallback(async () => {\n if (libraryPlacement === 'panel') {\n if (!await guard()) return;\n noteUnsaved(false); setPanelLibrary(value => !value);\n } else setCenterMode('library');\n setFullscreen(false);\n }, [guard, libraryPlacement, noteUnsaved]);\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 // With a revision provider, `resources` carries only the blob options; without one it is the resource handler too.\n const remote = revisionProvider ? undefined : resources as WorkspaceResources | undefined;\n // eslint-disable-next-line react-hooks/refs -- the host's latest fetch, read when a request goes out; clients built once keep calling the current one\n const fetcher = useRef(remote?.fetch); fetcher.current = remote?.fetch;\n const endpoint = remote ? String(remote.endpoint) : undefined;\n const historyEndpoint = remote?.history === undefined ? undefined : String(remote.history);\n const identity = revisionProvider?.identity ?? remote?.identity;\n const blobBase = checkBlobBase(resources?.blobBase);\n const hostUploadBlob = resources?.uploadBlob;\n const appLabels = text.labels;\n // The host's pointer is checked with the same validator the host uses; an invalid one is a refusal the Library shows.\n const uploadBlob = useMemo(() => hostUploadBlob && (async (file: File, options: Parameters<NonNullable<WorkspaceBlobs['uploadBlob']>>[1]) => {\n const pointer = parseBlobPointer(JSON.stringify(await hostUploadBlob(file, options) ?? null));\n if (pointer === undefined || 'kind' in pointer) throw { error: { code: 'invalid_pointer', message: appLabels.invalidBlobPointer(file.name) } };\n return pointer;\n }), [hostUploadBlob, appLabels]);\n const identityKey = JSON.stringify(identity);\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 // Resources only: a Library over the endpoint's own listing, when it answers the revision protocol's discovery for the same\n // person (`createRevisionHandler` serves the resource calls and the listing on one route). A plain resource handler refuses: no Library.\n const [listing, setListing] = useState<{ readonly key: string; readonly provider: RevisionProvider }>();\n const listingKey = revisionProvider || endpoint === undefined ? undefined : JSON.stringify([endpoint, identity]);\n useEffect(() => {\n if (listingKey === undefined) return;\n const abort = new AbortController();\n connectRevisionProvider({ endpoint: new URL(endpoint!, globalThis.location?.href), fetch: request => fetcher.current!(request), signal: abort.signal }).then(provider => {\n const { principalId, scopeId, initiatorId } = provider.identity;\n if (!abort.signal.aborted && principalId === identity?.principalId && scopeId === identity.scopeId && initiatorId === identity.initiatorId) setListing({ key: listingKey, provider });\n }, () => { /* no listing on this endpoint */ });\n return () => abort.abort();\n }, [listingKey]); // eslint-disable-line react-hooks/exhaustive-deps\n // The Library's binding: the host's revision provider, or the listing above with the versions of `resources.history`.\n // eslint-disable-next-line react-hooks/refs -- the functions built here read refs only when a request, an event or an effect calls them, never during render\n const libraryProvider = useMemo(() => revisionProvider ?? (listing && listing.key === listingKey ? { ...listing.provider, history: history ?? listing.provider.history } : undefined),\n [revisionProvider, listing, listingKey, history]);\n // The viewers' client: the Library's binding when there is one (its calls carry the binding the revision protocol checks), else the plain resource client.\n // With `resources`, the binding is discovered after the first render on the same endpoint for the same person: it takes over the calls of\n // one stable client, so a viewer already open keeps its bytes and its editor instead of reloading when the binding arrives.\n const discovered = useRef(libraryProvider);\n // eslint-disable-next-line react-hooks/refs -- latest-value ref: a viewer may read through the client during its own render or layout effect, before this component's effects run\n discovered.current = libraryProvider;\n const client = useMemo((): ResourceClient | undefined => {\n if (revisionProvider) return revisionProvider;\n if (endpoint === undefined || identity === undefined) return undefined;\n // eslint-disable-next-line react-hooks/refs -- the client's functions read refs only when a request calls them, never during render\n const plain = createResourceClient({ identity, endpoint: new URL(endpoint!, globalThis.location?.href), publication: true, reconciliation: true, fetch: request => fetcher.current!(request) });\n const current = (): ResourceClient => discovered.current ?? plain;\n return {\n read: (request, signal) => current().read(request, signal),\n publish: (request, signal) => current().publish!(request, signal),\n lookup: (operationId, signal) => current().lookup!(operationId, signal),\n rename: (request, signal) => current().rename!(request, signal),\n delete: (request, signal) => current().delete!(request, signal),\n };\n }, [revisionProvider, endpoint, identityKey]); // eslint-disable-line react-hooks/exhaustive-deps\n const [imagePreview, setImagePreview] = useState<{ readonly images: readonly ImageContent[]; readonly index: number; readonly controller: typeof controller; readonly client: typeof client; readonly conversationId: typeof conversationId }>();\n const openImage = useCallback((image: ImageContent, images: readonly ImageContent[] = [image]) => {\n const index = images.indexOf(image);\n if (index >= 0 && images.every(item => thumbnail(item.mimeType, item.data))) setImagePreview({ images: images.slice(), index, controller, client, conversationId });\n }, [controller, client, conversationId]);\n // eslint-disable-next-line react-hooks/refs -- the functions built here read refs only when a request, an event or an effect calls them, never during render\n const preview = imagePreview && !chat.onOpenImage && imagePreview.controller === controller && imagePreview.client === client && imagePreview.conversationId === conversationId ? imagePreview : undefined;\n // eslint-disable-next-line react-hooks/set-state-in-effect -- a new controller, client, conversation or host image handler drops the preview, once per change\n useEffect(() => { setImagePreview(undefined); }, [controller, client, conversationId, chat.onOpenImage]);\n const active = isArtifact(opened) && opened.conversation === conversationId ? opened : null;\n const follow = useArtifactFollow({ controller, conversationId, detect, active, autoOpen: autoOpen && (revisionProvider !== undefined || endpoint !== undefined),\n onOpen: selection => { if (conversationId !== undefined) void setOpened({ kind: selection.descriptor.type === 'task' ? 'task' : 'artifact', conversation: conversationId, ...selection }); },\n unsaved: () => unsaved.current,\n narrow: () => {\n const workspace = root.current?.querySelector<HTMLElement>('[data-boring=artifact-workspace]');\n return workspace !== undefined && workspace !== null && workspace.getBoundingClientRect().width < artifactSheetBelow;\n },\n showing: path => showsPath(currentView.current, path),\n openPresent: path => { if (unsaved.current) return false; void setOpened({ kind: 'file', path }); return true; },\n openTask: subject => {\n if (unsaved.current || conversationId === undefined || !panels?.['task']) return false;\n void setOpened({ kind: 'task', conversation: conversationId, descriptor: createTaskArtifact(subject), follow: true });\n return true;\n },\n showingTask: subject => {\n const current = currentView.current;\n const descriptor = current?.kind === 'task' && current['conversation'] === conversationId ? parseTaskArtifact(current['descriptor']) : undefined;\n return descriptor !== undefined && taskSubjectKey(descriptor.subject) === taskSubjectKey(subject);\n },\n answer: chat.actions?.answer });\n const { onShown, onFailed } = follow;\n const kinds = artifactKinds ?? noKinds;\n const hasResources = revisionProvider !== undefined || endpoint !== undefined;\n const options: ViewerOptions | undefined = useMemo(() => hasResources ? ({ client: client!, identity: identity!, history, viewers, kinds, interactive, share, onShown, onFailed, onUnsavedChange: noteUnsaved, onBeforeLeaveChange: registerBeforeLeave, blobBase }) : undefined, [hasResources, client, identityKey, history, viewers, kinds, interactive, share, onShown, onFailed, noteUnsaved, registerBeforeLeave, blobBase]); // eslint-disable-line react-hooks/exhaustive-deps\n const locate = revisionProvider?.locate ?? remote?.locate ?? defaultLocate;\n const readOnlyLibrary = !revisionProvider;\n const [fileBinding, setFileBinding] = useState<{ readonly provider: RevisionProvider; readonly tree: FileTreeController }>();\n useEffect(() => {\n if (!libraryProvider) return;\n // The Library reads its listings through `withBlobPointers`: each pointer file is resolved there, once, to the file it stands for.\n const tree = createFileTreeController({ revisionProvider: withBlobPointers(libraryProvider, blobBase) });\n // eslint-disable-next-line react-hooks/set-state-in-effect -- this effect owns the disposable tree (created and disposed here, StrictMode-safe); state only publishes it\n setFileBinding({ provider: libraryProvider, tree });\n void tree.refresh();\n return () => tree.dispose();\n }, [libraryProvider, blobBase]);\n // eslint-disable-next-line react-hooks/refs -- the functions built here read refs only when a request, an event or an effect calls them, never during render\n const libraryController = fileBinding?.provider === libraryProvider ? fileBinding?.tree : undefined;\n // Uploads and the upload notice belong to a revision provider only; the resources Library is read-only.\n const fileTree = revisionProvider ? libraryController : undefined;\n const embedded = layout === 'embedded';\n // Where the Library opens (`libraryPlacement`); embedded, it is the bar's Library button instead.\n // eslint-disable-next-line react-hooks/refs -- the functions built here read refs only when a request, an event or an effect calls them, never during render\n const placed = Boolean(libraryProvider) && !embedded;\n const libraryInPane = placed && libraryPlacement === 'pane';\n const librarySide = placed && libraryPlacement === 'side';\n const libraryOpen = placed && libraryPlacement === 'center' && centerMode === 'library';\n // The workspace's change feed: every file view below reloads when its seq moves (agent writes, saves, shell changes).\n const feed = useChangeFeed(libraryProvider);\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 (!libraryController || (Object.is(refreshedKey.current, refreshKey) && refreshedSeq.current === feed.seq)) return;\n refreshedKey.current = refreshKey;\n refreshedSeq.current = feed.seq;\n const { query, expanded } = libraryController.getSnapshot();\n if (query) void libraryController.search(query);\n else for (const directory of ['', ...expanded]) void libraryController.refresh(directory);\n }, [libraryController, refreshKey, feed.seq]);\n const openFile = useCallback((path: string) => { setOpened({ kind: 'file', path }); }, [setOpened]);\n // The file on show was renamed, moved or deleted from the Library: follow it to its new path, or close it (its old path is gone).\n const followFile = (from: string, to: string | null) => {\n const current = currentView.current;\n if (!isFile(current) || current.path !== from) return;\n const next = to === null ? null : { kind: 'file' as const, path: to };\n noteUnsaved(false);\n if (!isControlled) setOwn(next); change.current?.(next);\n };\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 // eslint-disable-next-line react-hooks/exhaustive-deps -- one mention cache per provider instance: revisionProvider is the cache's identity, not an input\n const mentionResults = useMemo(() => ({ seq: undefined as number | undefined, results: new Map<string, readonly FileEntry[]>() }), [revisionProvider]);\n // eslint-disable-next-line react-hooks/refs -- latest-value ref assigned in render, read only by event handlers, effects and async callbacks\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 // eslint-disable-next-line react-hooks/immutability -- the mention cache is this binding's own mutable holder, reset when the feed reports a change\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 // Thumbnails and voice playback read the original upload and MIME through the same provider as the file viewer.\n preview: async (path: string, signal: AbortSignal) => {\n const read = await revisionProvider.read({ target: revisionProvider.locate(path), revision: { kind: 'latest' } }, signal);\n return read.kind === 'available' ? { mimeType: read.snapshot.mediaType, data: imageData(read.snapshot.bytes) } : undefined;\n },\n } : undefined, [revisionProvider, openFile, mentionResults]);\n // The search function changes only with the binding; the feed's seq rides along as the picker's generation.\n // eslint-disable-next-line react-hooks/refs -- the functions built here read refs only when a request, an event or an effect calls them, never during render\n const mentionsForChat = useMemo(() => mentions && { ...mentions, generation: feed.seq }, [mentions, feed.seq]);\n const [attachmentFailure, setAttachmentFailure] = useState<{ readonly tree: FileTreeController; readonly reasons: readonly string[] }>();\n // Primitives only in the memo: a host's inline `labels` object would otherwise rebuild the chat's attachments on every render.\n const uploadAccept = uploads?.accept, inlineImages = uploads?.inlineImages === true, maxBytes = uploads?.maxBytes;\n const tooLarge = maxBytes !== undefined ? text.labels.attachmentTooLarge(sizeLabel(maxBytes)) : undefined;\n const revisionAttachments = useRevisionAttachments({ fileTree, accept: uploadAccept, inlineImages, maxBytes, tooLarge, onPreparationFailure: (name, reason) => {\n if (fileTree && fileTree.getSnapshot().lifecycle === 'active') setAttachmentFailure(current => ({ tree: fileTree,\n reasons: [...(current?.tree === fileTree ? current.reasons : []), `${name}: ${reason}`] }));\n } });\n const attachments = useMemo(() => revisionAttachments && { ...revisionAttachments, upload: (files: File[], signal: AbortSignal) => {\n setAttachmentFailure(undefined);\n return revisionAttachments.upload(files, signal);\n } }, [revisionAttachments]);\n\n // ---- Artifacts: cards open the panel; the agent's new ones open it too.\n const 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 || panelLibrary);\n // Record a close only after the host's unsaved-changes guard accepted it.\n const close = async () => { if (panelLibrary) { setPanelLibrary(false); return true; } if (!await setOpened(null)) return false; follow.recordClosed(); setFullscreen(false); return true; };\n const newestOf = (key: string) => follow.versions.filter((version): version is ArtifactDescriptor => version.type !== 'task' && artifactKey(version) === key);\n const artifacts: ArtifactsConfig = useMemo(() => ({\n open: follow.open, isOpen: follow.isOpen, ...(detect ? { detect } : {}), kinds,\n }), [follow.open, follow.isOpen, detect, kinds]);\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 [paneOpen, setPaneOpen] = useHistoryOpen(`${storageKey}.history-column`, true);\n const paneId = `${storageKey}-sessions`;\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 setPaneOpen(true);\n };\n // eslint-disable-next-line react-hooks/set-state-in-effect -- widening past the drawer breakpoint closes the drawer, once per change\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, onClose?: () => void) => libraryController\n ? <FileTreeView variant=\"list\" refresh={libraryPlacement !== 'panel'} title={text.labels.library} {...(onClose ? { onClose } : {})} key={JSON.stringify([libraryProvider?.workspace, libraryProvider?.identity])} {...(locale ? { locale } : {})} {...viewOptions}\n {...(readOnlyLibrary ? { upload: false, history: history !== undefined } : {})} {...(maxBytes !== undefined ? { maxBytes, ...(tooLarge ? { tooLarge } : {}) } : {})} {...(uploadBlob ? { uploadBlob } : {})} controller={libraryController} historyKey={feed.seq} onOpen={onOpen} onRenamed={(from, to) => followFile(from, to)} onDeleted={path => followFile(path, null)} {...(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 // `history=\"popover\"` keeps the conversations out of the pane. With an open panel the column steps aside unless column, panel and chat fit.\n const paneConversations = historyPlacement === 'column' ? conversations : undefined;\n const hasNavigation = !embedded && sessions !== false && Boolean(paneConversations || placed);\n const stepAside = Boolean(paneConversations) && hasNavigation && !narrow && panelOpen && !historyColumnFits(width, VIEWER_MIN);\n const docked = hasNavigation && width > 0 && !narrow && paneOpen && !stepAside;\n const artifactSheetBelow = Math.max(CHAT_MIN + VIEWER_MIN, docked ? sheetBelow - SESSIONS_WIDTH : sheetBelow);\n const popoverHistory = historyPlacement === 'popover' || stepAside;\n const toggle = hasNavigation && !docked && !drawer && !stepAside && <SessionsToggle navigation={placed} open={narrow ? drawer : paneOpen} drawer={narrow} controls={narrow ? undefined : paneId}\n onToggle={() => { if (narrow) setDrawer(value => !value); else { setPaneOpen(!paneOpen); if (!paneOpen) focusHistoryRow(paneId); } }} />;\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} variant=\"ghost\" size=\"icon-sm\" aria-hidden=\"true\" tabIndex={-1} className=\"invisible md:-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 hostControls = typeof controls === 'function' ? controls({ panelOpen }) : controls ?? chat.controls;\n const header = <>{conversations?.onNew && <Button variant=\"ghost\" size=\"icon-sm\" data-testid=\"workspace-new-chat\" aria-label={text.labels.newChat} title={text.labels.newChat} className=\"md:hidden\" onClick={conversations.onNew}><text.icons.newChat data-icon=\"inline-start\" aria-hidden=\"true\" /></Button>}{hostControls}</>;\n const conversationTitle = conversations?.items.find(item => item.id === conversationId)?.title;\n // pi-app ships every composer feature item: Markdown, the `/` menu, `@` mentions, the model pill, voice messages, the phone camera.\n // eslint-disable-next-line react-hooks/refs -- the functions built here read refs only when a request, an event or an effect calls them, never during render\n const chatProps: PiChatProps | undefined = controller && withChatPlugins({ ...(mentionsForChat ? { mentions: mentionsForChat } : {}), ...(attachments ? { attachments } : {}), ...(locale ? { locale } : {}), ...chat, controller, artifacts, onOpenFile: chat.onOpenFile ?? chat.mentions?.open ?? openFile, onOpenImage: chat.onOpenImage ?? openImage, ...(conversations ? { conversations, historyList: popoverHistory, showHistory: chat.showHistory ?? popoverHistory, conversationTitle, onRenameTitle: conversations.rename && conversationId ? (title: string) => conversations.rename!(conversationId, title) : undefined } : {}),\n headerStart: <>{toggle}{chat.headerStart}</>, ...(header === undefined ? {} : { controls: header }),\n // Embedded: the bar above replaces the chat's header (History, New and the host's controls are in it); conversations stay for Fork.\n ...(embedded ? { header: false, historyList: false, showHistory: false } : {}) });\n const bar = embedded && <WorkspaceBar title={title ?? conversationTitle ?? chatText.labels.title} {...(title && conversationTitle ? { subtitle: conversationTitle } : {})} conversations={conversations} narrow={narrow}\n library={libraryController ? onPicked => libraryTree(path => { openFile(path); onPicked(); }, onPicked) : undefined} panels={barPanels} {...barOptions}\n controls={<><BlockActions actions={chat.headerActions} testId=\"chat-action\" menuLabel={chatText.labels.moreActions} />{hostControls}</>} />;\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 px-3 py-2 md:gap-3 md:px-4 md:py-2.5\">{toggleSpace}</div><Separator /></>}{connecting}</>}\n {toggle && <div ref={toggleRow} className=\"pointer-events-none absolute top-0 left-0 z-10 flex items-center px-3 md: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 ...(placed && libraryPlacement === 'panel' ? [{ id: 'library', label: text.labels.library, icon: text.icons.library, placement: 'menu' as const, onSelect: openLibrary }] : []),\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 const sessionProps: ComponentProps<typeof SessionsPane> = { id: paneId, conversations: paneConversations, drawer: narrow, onClose: () => setDrawer(false), onChat: () => setCenterMode('chat'), onCollapse: () => setPaneOpen(false), title: labels?.sessionsTitle,\n agents, view: paneView, onViewChange: changePaneView,\n ...(librarySide ? { library: { selected: sideOpen, onSelect: toggleSide, side: true } } : placed && !libraryInPane ? { library: { selected: libraryOpen || panelLibrary, onSelect: openLibrary } } : {}),\n ...(libraryInPane ? { libraryContent: (onPicked: () => void) => libraryTree(path => { openFile(path); onPicked(); }) } : {}),\n };\n return <AppTextProvider value={text}><ChatTextProvider value={chatText}><div ref={root} data-boring=\"agent-workspace\" data-layout={layout} data-sessions={!hasNavigation ? undefined : narrow ? (drawer ? 'drawer' : 'closed') : docked ? 'docked' : 'hidden'}\n className={cn('pi-chat relative flex h-full min-h-0 min-w-0 flex-1 overflow-hidden', embedded && 'flex-col', className)}>\n {/* Above the viewer as well as the chat: what opens in an embedded workspace stays inside its window. */}\n {bar}\n <DockLayout storageKey={`${storageKey}.dock`} minMain={SESSIONS_WIDTH + 480}>\n {/* eslint-disable-next-line react-hooks/refs -- the functions built here read refs only when a request, an event or an effect calls them, never during render */}\n {hasNavigation && (docked || (narrow && drawer)) && (sessions ? sessions(sessionProps) : <SessionsPane {...sessionProps} />)}\n <DockMain><ArtifactWorkspace open={panelOpen && !(panelLibrary && narrow)} onClose={close} panelLabel={text.labels.artifactPanel} labels={{ resize: text.labels.resizePanel, floatHint: text.labels.floatHint }} fullscreen={fullscreen} onFullscreenChange={setFullscreen} storageKey={`${storageKey}.panel-width`} {...(panelWidth === undefined ? {} : { defaultWidth: panelWidth })}\n sheetBelow={artifactSheetBelow} {...(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 || libraryPlacement === 'panel' ? null : <section data-testid=\"workspace-library-view\" aria-label={text.labels.library} className=\"flex min-h-0 flex-1 flex-col\">\n <div className=\"min-h-0 flex-1 overflow-auto\">{libraryTree(openFile, () => setCenterMode('chat'))}</div>\n </section>} />}\n panel={win => <ViewerWindowProvider value={{ fullscreen: win.fullscreen, onFullscreenChange: win.onFullscreenChange, actions: actionsFor(win.floatChat),\n labels: win.sheet ? { ...text.labels, close: text.labels.backToChat } : text.labels,\n icons: win.sheet ? { ...text.icons, close: text.icons.back } : 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 {panelLibrary ? <section data-testid=\"workspace-library-side\" aria-label={text.labels.library} className=\"flex min-h-0 flex-1 flex-col\"><div className=\"min-h-0 flex-1 overflow-auto\">{libraryTree(openFile, () => setPanelLibrary(false))}</div></section> : active && options\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 && options ? <FileViewer key={JSON.stringify([revisionProvider?.workspace, identity, file.path])} onBeforeLeaveChange={registerBeforeLeave} 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, onShown, onFailed }) : 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 }} >\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 <div className=\"min-h-0 flex-1 overflow-auto\">{libraryTree(path => { void setOpened({ kind: 'file', path }).then(opened => { if (opened && narrow) setSideOpen(false); }); }, () => setSideOpen(false))}</div>\n </section>}\n </Dock>}\n </DockLayout>\n {preview && <ImageViewer images={preview.images} index={preview.index} labels={chatText.labels} testId=\"conversation-image\"\n onIndexChange={index => setImagePreview({ ...preview, index })} onClose={() => setImagePreview(undefined)} />}\n {/* eslint-disable-next-line react-hooks/refs -- the functions built here read refs only when a request, an event or an effect calls them, never during render */}\n {panelLibrary && narrow && <Drawer open showSwipeHandle onOpenChange={next => { if (!next) setPanelLibrary(false); }}><DrawerContent aria-label={text.labels.library} className=\"pi-chat min-h-[80dvh] max-h-[80dvh]\"><DrawerTitle className=\"sr-only\">{text.labels.library}</DrawerTitle><div data-testid=\"workspace-library-side\" className=\"min-h-0 flex-1 overflow-auto pb-[env(safe-area-inset-bottom)]\">{libraryTree(openFile, () => setPanelLibrary(false))}</div></DrawerContent></Drawer>}\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 variant=\"link\" 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 // eslint-disable-next-line react-hooks/refs -- the floating choice is held while the Library covers the chat; the layout effect above keeps it current\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 * A number that moves when the provider's files change (`RevisionProvider.changes`), coalesced over `settleMs` so a burst (a shell\n * writing many files) reloads once. `live` is false without a feed or after the feed was refused; views then keep their own refresh.\n * A hidden tab holds no feed: a browser allows few connections per host, and every tab of a share link holding a stream starves the\n * others (remote chat releases its stream the same way); `live` is false meanwhile. Shown again, it reconnects after the last event it\n * acted on (`since`; 0 when it had none, which the feed answers with a `resnapshot`), so a change made while hidden or while reconnecting\n * arrives on the new feed and moves the number then, after the feed is connected.\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 const shown = usePageShown();\n // The provider connected last, and the protocol seq of the last event the views reloaded for.\n const connected = useRef<{ readonly provider: RevisionProvider; seen: number | undefined } | undefined>(undefined);\n useEffect(() => {\n // eslint-disable-next-line react-hooks/set-state-in-effect -- the feed's state is reset for the new provider when this effect subscribes to it\n if (!provider?.changes) { setState({ provider, seq: undefined, live: false }); return; }\n if (!shown) { setState(current => current.provider === provider && current.live ? { ...current, live: false } : current); return; }\n const stop = new AbortController();\n let timer: ReturnType<typeof setTimeout> | undefined, latest: number | undefined;\n // A second connection to the same provider follows a hidden period: it resumes after the last event acted on. A first connection has nothing to catch up.\n const since = connected.current?.provider === provider ? connected.current.seen ?? 0 : undefined;\n const cursor = connected.current?.provider === provider ? connected.current : { provider, seen: undefined };\n connected.current = cursor;\n const move = () => { cursor.seen = latest; setState(current => ({ provider, seq: current.provider === provider ? (current.seq ?? 0) + 1 : 1, live: true })); };\n setState(current => ({ provider, seq: current.provider === provider ? current.seq : undefined, live: true }));\n void (async () => {\n try {\n for await (const event of provider.changes!({ ...(since === undefined ? {} : { since }), signal: stop.signal })) {\n latest = event.seq;\n // An event still settling when the feed closes is not acted on, so the next connection asks for it again.\n timer ??= setTimeout(() => { timer = undefined; if (!stop.signal.aborted) move(); }, 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(current => ({ provider, seq: current.provider === provider ? current.seq : undefined, live: false }));\n })();\n return () => { stop.abort(); clearTimeout(timer); };\n }, [provider, settleMs, shown]);\n return state.provider === provider ? state : { seq: undefined, live: false };\n}\n\n/** Whether the page is shown (`document.visibilityState`); true where there is no document. */\nfunction usePageShown(): boolean {\n const [shown, setShown] = useState(() => typeof document === 'undefined' || document.visibilityState !== 'hidden');\n useEffect(() => {\n if (typeof document === 'undefined') return;\n const update = () => setShown(document.visibilityState !== 'hidden');\n update();\n document.addEventListener('visibilitychange', update);\n return () => document.removeEventListener('visibilitychange', update);\n }, []);\n return shown;\n}\n",
27
27
  "type": "registry:component",
28
28
  "target": "components/pi-app/agent-workspace.tsx"
29
29
  },
30
30
  {
31
31
  "path": "registry/pi-app/sessions.tsx",
32
- "content": "'use client';\n\nimport type { ReactNode } from 'react';\nimport { Button } from '@/components/ui/button';\nimport { Drawer, DrawerContent, DrawerTitle } from '@/components/ui/drawer';\nimport { DropdownMenu, DropdownMenuContent, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';\nimport { ScrollArea } from '@/components/ui/scroll-area';\nimport { ChevronsUpDownIcon, MenuIcon } from 'lucide-react';\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\nexport interface WorkspaceAgent { readonly id: string; readonly label: string; readonly description?: string | undefined }\nexport interface WorkspaceAgents { readonly items: readonly WorkspaceAgent[]; readonly activeId: string; readonly onSelect: (id: string) => void }\nexport type SessionsView = 'conversations' | 'library';\n\n/** The same navigation in a desktop column and a focus-trapped, swipe-dismissable phone drawer. */\nexport function SessionsPane({ id, conversations, title: givenTitle, drawer, onClose, onCollapse, library, onChat, libraryContent, view = 'conversations', onViewChange, agents }: {\n /** The pane's element id (the toggle's `aria-controls`). */\n readonly id?: string | undefined;\n readonly conversations?: ConversationsConfig | undefined;\n readonly library?: { readonly selected: boolean; readonly onSelect: () => void; readonly side?: boolean } | undefined;\n readonly onChat?: (() => void) | undefined;\n readonly libraryContent?: ((onPicked: () => void) => ReactNode) | undefined;\n readonly view?: SessionsView | undefined;\n readonly onViewChange?: ((view: SessionsView) => void) | undefined;\n readonly agents?: WorkspaceAgents | undefined;\n readonly title?: string;\n readonly drawer: boolean;\n readonly onClose?: (() => void) | undefined;\n readonly onCollapse?: (() => void) | undefined;\n}) {\n const { labels, icons } = useAppText();\n const title = givenTitle ?? (conversations || !libraryContent ? labels.sessionsTitle : labels.library);\n const picked = () => { onChat?.(); if (drawer) onClose?.(); };\n const tabs = Boolean(libraryContent && conversations);\n const shown = !conversations && libraryContent ? 'library' : tabs ? view : 'conversations';\n const navigation = library && <Button variant=\"ghost\" data-testid=\"workspace-library\" aria-pressed={library.selected} className=\"mx-2 justify-start\" onClick={() => { library.onSelect(); if (drawer) onClose?.(); }}><icons.library aria-hidden=\"true\" />{labels.library}</Button>;\n const pane = <aside id={id} data-testid=\"conversations\" data-drawer={drawer ? 'true' : 'false'} aria-label={title}\n className={cn('pi-chat flex min-h-0 flex-1 flex-col bg-muted/30 text-foreground', drawer ? 'pt-[env(safe-area-inset-top)] pb-[env(safe-area-inset-bottom)]' : 'w-[260px] shrink-0 flex-none')}>\n <header className=\"flex h-13 shrink-0 items-center gap-2 px-4\">\n {agents && agents.items.length > 1 ? <DropdownMenu>\n <DropdownMenuTrigger render={<Button variant=\"ghost\" aria-label={labels.agent} data-testid=\"agent-select\" className=\"min-w-0 flex-1 justify-between\" />}>\n <span className=\"truncate\">{(agents.items.find(agent => agent.id === agents.activeId) ?? agents.items[0])?.label}</span><ChevronsUpDownIcon data-icon=\"inline-end\" aria-hidden=\"true\" />\n </DropdownMenuTrigger>\n <DropdownMenuContent align=\"start\" aria-label={labels.agent}>\n <DropdownMenuRadioGroup value={agents.activeId} onValueChange={agents.onSelect}>\n {agents.items.map(agent => <DropdownMenuRadioItem key={agent.id} value={agent.id} title={agent.description} data-testid={`agent-option-${agent.id}`}>{agent.label}</DropdownMenuRadioItem>)}\n </DropdownMenuRadioGroup>\n </DropdownMenuContent>\n </DropdownMenu> : <h2 className=\"m-0 min-w-0 flex-1 truncate text-sm font-semibold tracking-tight\">{agents?.items[0]?.label ?? title}</h2>}\n {(drawer ? onClose : onCollapse) && <SessionsToggle open drawer={drawer} navigation={Boolean(library || libraryContent)} onToggle={(drawer ? onClose : onCollapse)!} />}\n </header>\n {conversations?.onNew && <Button variant=\"ghost\" data-testid=\"conversation-new\" className=\"mx-2 mb-1 justify-start\" onClick={() => { conversations.onNew?.(); picked(); }}><icons.newChat data-icon=\"inline-start\" aria-hidden=\"true\" />{labels.newChat}</Button>}\n {tabs && <div role=\"tablist\" aria-label={title} className=\"mx-2 flex gap-1\">{(['conversations', 'library'] as const).map(tab => <Button key={tab} role=\"tab\" variant=\"ghost\" aria-selected={shown === tab} data-testid={`sessions-tab-${tab}`} onClick={() => onViewChange?.(tab)}>{tab === 'library' ? labels.library : title}</Button>)}</div>}\n {shown === 'library' && libraryContent ? <ScrollArea data-testid=\"sessions-library\" className=\"min-h-0 flex-1\">{libraryContent(() => { if (drawer) onClose?.(); })}</ScrollArea>\n : conversations ? <ConversationList conversations={conversations} onPicked={picked} navigation={navigation} /> : navigation}\n </aside>;\n if (!drawer) return pane;\n return <Drawer open onOpenChange={next => { if (!next) onClose?.(); }} swipeDirection=\"left\">\n <DrawerContent aria-label={title}>\n <DrawerTitle className=\"sr-only\">{title}</DrawerTitle>{pane}\n </DrawerContent>\n </Drawer>;\n}\n\nexport function SessionsToggle({ open, drawer, onToggle, navigation = false, controls }: { readonly open: boolean; readonly drawer: boolean; readonly onToggle: () => void; readonly navigation?: boolean; readonly controls?: string | undefined }) {\n const { labels, icons } = useAppText();\n const label = navigation ? drawer ? open ? labels.closeNavigation : labels.openNavigation : open ? labels.hideNavigation : labels.showNavigation\n : drawer ? open ? labels.closeSessions : 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} aria-controls={controls} onClick={onToggle} className=\"shrink-0\">\n {drawer && !open ? <MenuIcon data-icon=\"inline-start\" aria-hidden=\"true\" /> : <icons.sessionsToggle data-icon=\"inline-start\" aria-hidden=\"true\" />}\n </Button>;\n}\n",
32
+ "content": "'use client';\n\nimport type { ReactNode } from 'react';\nimport { Button } from '@/components/ui/button';\nimport { Drawer, DrawerContent, DrawerTitle } from '@/components/ui/drawer';\nimport { DropdownMenu, DropdownMenuContent, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';\nimport { ScrollArea } from '@/components/ui/scroll-area';\nimport { ChevronsUpDownIcon, MenuIcon } from 'lucide-react';\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\nexport interface WorkspaceAgent { readonly id: string; readonly label: string; readonly description?: string | undefined }\nexport interface WorkspaceAgents { readonly items: readonly WorkspaceAgent[]; readonly activeId: string; readonly onSelect: (id: string) => void }\nexport type SessionsView = 'conversations' | 'library';\n\n/** The same navigation in a desktop column and a focus-trapped, swipe-dismissable phone drawer. */\nexport function SessionsPane({ id, conversations, title: givenTitle, drawer, onClose, onCollapse, library, onChat, libraryContent, view = 'conversations', onViewChange, agents }: {\n /** The pane's element id (the toggle's `aria-controls`). */\n readonly id?: string | undefined;\n readonly conversations?: ConversationsConfig | undefined;\n readonly library?: { readonly selected: boolean; readonly onSelect: () => void; readonly side?: boolean } | undefined;\n readonly onChat?: (() => void) | undefined;\n readonly libraryContent?: ((onPicked: () => void) => ReactNode) | undefined;\n readonly view?: SessionsView | undefined;\n readonly onViewChange?: ((view: SessionsView) => void) | undefined;\n readonly agents?: WorkspaceAgents | undefined;\n readonly title?: string | undefined;\n readonly drawer: boolean;\n readonly onClose?: (() => void) | undefined;\n readonly onCollapse?: (() => void) | undefined;\n}) {\n const { labels, icons } = useAppText();\n const title = givenTitle ?? (conversations || !libraryContent ? labels.sessionsTitle : labels.library);\n const picked = () => { onChat?.(); if (drawer) onClose?.(); };\n const tabs = Boolean(libraryContent && conversations);\n const shown = !conversations && libraryContent ? 'library' : tabs ? view : 'conversations';\n const navigation = library && <Button variant=\"ghost\" data-testid=\"workspace-library\" aria-pressed={library.selected} className=\"mx-2 justify-start\" onClick={() => { library.onSelect(); if (drawer) onClose?.(); }}><icons.library aria-hidden=\"true\" />{labels.library}</Button>;\n const pane = <aside id={id} data-testid=\"conversations\" data-drawer={drawer ? 'true' : 'false'} aria-label={title}\n className={cn('pi-chat flex min-h-0 flex-1 flex-col bg-muted/30 text-foreground', drawer ? 'pt-[env(safe-area-inset-top)] pb-[env(safe-area-inset-bottom)]' : 'w-[260px] shrink-0 flex-none')}>\n <header className=\"flex h-13 shrink-0 items-center gap-2 px-4\">\n {agents && agents.items.length > 1 ? <DropdownMenu>\n <DropdownMenuTrigger render={<Button variant=\"ghost\" aria-label={labels.agent} data-testid=\"agent-select\" className=\"min-w-0 flex-1 justify-between\" />}>\n <span className=\"truncate\">{(agents.items.find(agent => agent.id === agents.activeId) ?? agents.items[0])?.label}</span><ChevronsUpDownIcon data-icon=\"inline-end\" aria-hidden=\"true\" />\n </DropdownMenuTrigger>\n <DropdownMenuContent align=\"start\" aria-label={labels.agent}>\n <DropdownMenuRadioGroup value={agents.activeId} onValueChange={agents.onSelect}>\n {agents.items.map(agent => <DropdownMenuRadioItem key={agent.id} value={agent.id} title={agent.description} data-testid={`agent-option-${agent.id}`}>{agent.label}</DropdownMenuRadioItem>)}\n </DropdownMenuRadioGroup>\n </DropdownMenuContent>\n </DropdownMenu> : <h2 className=\"m-0 min-w-0 flex-1 truncate text-sm font-semibold tracking-tight\">{agents?.items[0]?.label ?? title}</h2>}\n {(drawer ? onClose : onCollapse) && <SessionsToggle open drawer={drawer} navigation={Boolean(library || libraryContent)} onToggle={(drawer ? onClose : onCollapse)!} />}\n </header>\n {conversations?.onNew && <Button variant=\"ghost\" data-testid=\"conversation-new\" className=\"mx-2 mb-1 justify-start\" onClick={() => { conversations.onNew?.(); picked(); }}><icons.newChat data-icon=\"inline-start\" aria-hidden=\"true\" />{labels.newChat}</Button>}\n {tabs && <div role=\"tablist\" aria-label={title} className=\"mx-2 flex gap-1\">{(['conversations', 'library'] as const).map(tab => <Button key={tab} role=\"tab\" variant=\"ghost\" aria-selected={shown === tab} data-testid={`sessions-tab-${tab}`} onClick={() => onViewChange?.(tab)}>{tab === 'library' ? labels.library : title}</Button>)}</div>}\n {shown === 'library' && libraryContent ? <ScrollArea data-testid=\"sessions-library\" className=\"min-h-0 flex-1\">{libraryContent(() => { if (drawer) onClose?.(); })}</ScrollArea>\n : conversations ? <ConversationList conversations={conversations} onPicked={picked} navigation={navigation} /> : navigation}\n </aside>;\n if (!drawer) return pane;\n return <Drawer open onOpenChange={next => { if (!next) onClose?.(); }} swipeDirection=\"left\">\n <DrawerContent aria-label={title}>\n <DrawerTitle className=\"sr-only\">{title}</DrawerTitle>{pane}\n </DrawerContent>\n </Drawer>;\n}\n\nexport function SessionsToggle({ open, drawer, onToggle, navigation = false, controls }: { readonly open: boolean; readonly drawer: boolean; readonly onToggle: () => void; readonly navigation?: boolean; readonly controls?: string | undefined }) {\n const { labels, icons } = useAppText();\n const label = navigation ? drawer ? open ? labels.closeNavigation : labels.openNavigation : open ? labels.hideNavigation : labels.showNavigation\n : drawer ? open ? labels.closeSessions : 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} aria-controls={controls} onClick={onToggle} className=\"shrink-0\">\n {drawer && !open ? <MenuIcon data-icon=\"inline-start\" aria-hidden=\"true\" /> : <icons.sessionsToggle data-icon=\"inline-start\" aria-hidden=\"true\" />}\n </Button>;\n}\n",
33
33
  "type": "registry:component",
34
34
  "target": "components/pi-app/sessions.tsx"
35
35
  },
@@ -41,7 +41,7 @@
41
41
  },
42
42
  {
43
43
  "path": "registry/pi-app/workspace-bar.tsx",
44
- "content": "'use client';\n\n// The compact top bar of `AgentWorkspace layout=\"embedded\"`: the conversation title, then History, Library, the host's own panels and New\n// as icon buttons (each panel opens a popover on a wide workspace and a bottom sheet on a phone) and the host's controls. Inside an app-shell\n// screen the controls go into the shell's header instead (`useScreenHeaderSlot`), so the page keeps one row. Host concern: Pi has no layout.\nimport { useState } from 'react';\nimport type { ReactElement, ReactNode } from 'react';\nimport { createPortal } from 'react-dom';\nimport { XIcon } from 'lucide-react';\nimport { Button } from '@/components/ui/button';\nimport { Drawer, DrawerContent, DrawerTitle } from '@/components/ui/drawer';\nimport { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';\nimport { Separator } from '@/components/ui/separator';\nimport { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';\nimport { ConversationList } from '../pi-chat/history';\nimport type { ConversationsConfig } from '../pi-chat/config';\nimport type { BlockIcon } from '../button/actions';\nimport { useScreenHeaderSlot } from '../utils/screen-header-slot';\nimport { cn } from '../utils/utils';\nimport { useAppText } from './app-labels';\n\n/** 44px on a phone (`narrow`), the bar's 32px otherwise. */\nconst iconSize = (narrow: boolean) => cn(narrow && 'size-11');\n\n/** A hover and focus tooltip on a wide workspace; a phone has no hover, and focus coming back from a sheet must not raise one. */\nfunction Hinted({ label, trigger, narrow }: { readonly label: string; readonly trigger: ReactElement; readonly narrow: boolean }) {\n if (narrow) return trigger;\n return <Tooltip><TooltipTrigger render={trigger} /><TooltipContent>{label}</TooltipContent></Tooltip>;\n}\n\n/** One icon button that opens `children`: an anchored popover on a wide workspace, a bottom sheet on a phone. */\nfunction BarPanel({ id, label, icon: Icon, narrow, open, onOpenChange, children }: {\n readonly id: string;\n readonly label: string;\n readonly icon: BlockIcon;\n readonly narrow: boolean;\n readonly open: boolean;\n readonly onOpenChange: (open: boolean) => void;\n readonly children: ReactNode;\n}) {\n const button = <Button variant=\"ghost\" size=\"icon\" data-testid={`workspace-bar-${id}`} aria-label={label} className={iconSize(narrow)}><Icon aria-hidden=\"true\" /></Button>;\n if (narrow) return <>\n <Button variant=\"ghost\" size=\"icon\" data-testid={`workspace-bar-${id}`} aria-label={label} aria-haspopup=\"dialog\" aria-expanded={open} className={iconSize(narrow)} onClick={() => onOpenChange(true)}><Icon aria-hidden=\"true\" /></Button>\n <Drawer open={open} onOpenChange={onOpenChange} showSwipeHandle>\n <DrawerContent data-testid={`workspace-${id}`} aria-label={label} className=\"pi-chat min-h-[50dvh] max-h-[85dvh]\">\n <DrawerTitle className=\"sr-only\">{label}</DrawerTitle>\n <div className=\"flex min-h-0 flex-1 flex-col pb-[env(safe-area-inset-bottom)]\">{children}</div>\n </DrawerContent>\n </Drawer>\n </>;\n return <Popover open={open} onOpenChange={onOpenChange}>\n <Hinted label={label} narrow={false} trigger={<PopoverTrigger render={button} />} />\n <PopoverContent data-testid={`workspace-${id}`} aria-label={label} align=\"end\" className=\"pi-chat w-[23rem] max-w-[calc(100vw-1rem)] max-h-[min(34rem,70dvh)]\">{children}</PopoverContent>\n </Popover>;\n}\n\n/** A host panel in the bar, beside History and Library: an icon button that opens `content` (`close` closes the popover or sheet). */\nexport interface WorkspaceBarPanel {\n readonly id: string;\n readonly label: string;\n readonly icon: BlockIcon;\n readonly content: (close: () => void) => ReactNode;\n}\n\nexport interface WorkspaceBarProps {\n readonly title: string;\n /** Muted after a fixed `title`: the conversation's title. Hidden on a phone, where History names the conversations. */\n readonly subtitle?: string | undefined;\n readonly conversations: ConversationsConfig | undefined;\n /** The Library's list (`onPicked` closes the popover or sheet), or undefined without a Library. */\n readonly library: ((onPicked: () => void) => ReactNode) | undefined;\n /** The host's own panels, after Library and before New (test ids `workspace-bar-<id>` and `workspace-<id>`). */\n readonly panels?: readonly WorkspaceBarPanel[] | undefined;\n /** A phone-sized workspace: sheets instead of popovers, 44px buttons. */\n readonly narrow: boolean;\n /** The host's own controls, after New. */\n readonly controls?: ReactNode;\n}\n\n/** The bar, or only its controls in the app shell's header when the page sits in a shell screen (then nothing renders here). */\nexport function WorkspaceBar({ title, subtitle, conversations, library, panels, narrow, controls }: WorkspaceBarProps) {\n const { labels, icons } = useAppText();\n const slot = useScreenHeaderSlot();\n const [shown, setShown] = useState<string | null>(null);\n const toggle = (which: string) => (open: boolean) => setShown(open ? which : current => current === which ? null : current);\n const close = () => setShown(null);\n const tools = <div data-testid=\"workspace-bar-tools\" className=\"flex shrink-0 items-center gap-0.5\">\n {conversations && <BarPanel id=\"history\" label={labels.history} icon={icons.history} narrow={narrow} open={shown === 'history'} onOpenChange={toggle('history')}>\n <header className=\"flex shrink-0 items-center gap-2 pl-1\">\n <h3 className=\"m-0 min-w-0 flex-1 truncate text-sm font-semibold\">{labels.history}</h3>\n <Button variant=\"ghost\" size=\"icon-sm\" aria-label={labels.close} title={labels.close} className={iconSize(narrow)} onClick={close}><XIcon aria-hidden=\"true\" /></Button>\n </header>\n <Separator />\n <div className=\"flex min-h-0 flex-1 flex-col\"><ConversationList conversations={conversations} onPicked={close} /></div>\n </BarPanel>}\n {library && <BarPanel id=\"library\" label={labels.library} icon={icons.library} narrow={narrow} open={shown === 'library'} onOpenChange={toggle('library')}>\n <div className=\"min-h-0 flex-1 overflow-auto\">{library(close)}</div>\n </BarPanel>}\n {panels?.map(panel => <BarPanel key={panel.id} id={panel.id} label={panel.label} icon={panel.icon} narrow={narrow} open={shown === panel.id} onOpenChange={toggle(panel.id)}>\n {panel.content(close)}\n </BarPanel>)}\n {conversations?.onNew && <Hinted label={labels.newChat} narrow={narrow} trigger={<Button variant=\"ghost\" size=\"icon\" data-testid=\"workspace-bar-new\" aria-label={labels.newChat} className={iconSize(narrow)} onClick={() => conversations.onNew?.()}><icons.newChat aria-hidden=\"true\" /></Button>} />}\n {controls}\n </div>;\n if (slot) return createPortal(tools, slot);\n return <header data-testid=\"workspace-bar\" className=\"flex h-13 shrink-0 items-center gap-1 pr-2 pl-4 max-md:h-14 max-md:pl-3\">\n <div className=\"flex min-w-0 flex-1 items-baseline gap-2\">\n <h2 data-testid=\"workspace-bar-title\" className={cn('m-0 min-w-0 truncate text-sm font-medium tracking-tight', subtitle === undefined && 'flex-1')}>{title}</h2>\n {subtitle !== undefined && <span data-testid=\"workspace-bar-conversation\" className=\"min-w-0 flex-1 truncate text-sm text-muted-foreground max-md:hidden\">{subtitle}</span>}\n </div>\n {tools}\n </header>;\n}\n",
44
+ "content": "'use client';\n\n// The compact top bar of `AgentWorkspace layout=\"embedded\"`: the conversation title, then History, Library, the host's own panels and New\n// as icon buttons (each panel opens a popover on a wide workspace and a bottom sheet on a phone) and the host's controls. Inside an app-shell\n// screen the controls go into the shell's header instead (`useScreenHeaderSlot`), so the page keeps one row. Host concern: Pi has no layout.\nimport { useState } from 'react';\nimport type { ReactElement, ReactNode } from 'react';\nimport { createPortal } from 'react-dom';\nimport { CircleIcon, XIcon } from 'lucide-react';\nimport { Button } from '@/components/ui/button';\nimport { Drawer, DrawerContent, DrawerTitle } from '@/components/ui/drawer';\nimport { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';\nimport { Separator } from '@/components/ui/separator';\nimport { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';\nimport { ConversationList } from '../pi-chat/history';\nimport type { ConversationsConfig } from '../pi-chat/config';\nimport type { BlockIcon } from '../button/actions';\nimport { useScreenHeaderSlot } from '../utils/screen-header-slot';\nimport { cn } from '../utils/utils';\nimport { useAppText } from './app-labels';\n\n/** 44px on a phone (`narrow`), the bar's 32px otherwise. */\nconst iconSize = (narrow: boolean) => cn(narrow && 'size-11');\n\n/** A hover and focus tooltip on a wide workspace; a phone has no hover, and focus coming back from a sheet must not raise one. */\nfunction Hinted({ label, trigger, narrow }: { readonly label: string; readonly trigger: ReactElement; readonly narrow: boolean }) {\n if (narrow) return trigger;\n return <Tooltip><TooltipTrigger render={trigger} /><TooltipContent>{label}</TooltipContent></Tooltip>;\n}\n\n/** One icon button that opens `children`: an anchored popover on a wide workspace, a bottom sheet on a phone. */\nfunction BarPanel({ id, label, icon: Icon, dot, narrow, open, onOpenChange, children }: {\n readonly id: string;\n readonly label: string;\n readonly icon: BlockIcon;\n readonly dot?: boolean | undefined;\n readonly narrow: boolean;\n readonly open: boolean;\n readonly onOpenChange: (open: boolean) => void;\n readonly children: ReactNode;\n}) {\n const content = <><Icon aria-hidden=\"true\" />{dot && <CircleIcon data-testid={`workspace-bar-${id}-dot`} aria-hidden=\"true\" className=\"absolute top-1 right-1 size-2 fill-primary stroke-none\" />}</>;\n const button = <Button variant=\"ghost\" size=\"icon\" data-testid={`workspace-bar-${id}`} aria-label={label} data-unread={dot || undefined} className={cn('relative', iconSize(narrow))}>{content}</Button>;\n if (narrow) return <>\n <Button variant=\"ghost\" size=\"icon\" data-testid={`workspace-bar-${id}`} aria-label={label} data-unread={dot || undefined} aria-haspopup=\"dialog\" aria-expanded={open} className={cn('relative', iconSize(narrow))} onClick={() => onOpenChange(true)}>{content}</Button>\n <Drawer open={open} onOpenChange={onOpenChange} showSwipeHandle>\n <DrawerContent data-testid={`workspace-${id}`} aria-label={label} className=\"pi-chat min-h-[50dvh] max-h-[85dvh]\">\n <DrawerTitle className=\"sr-only\">{label}</DrawerTitle>\n <div className=\"flex min-h-0 flex-1 flex-col pb-[env(safe-area-inset-bottom)]\">{children}</div>\n </DrawerContent>\n </Drawer>\n </>;\n return <Popover open={open} onOpenChange={onOpenChange}>\n <Hinted label={label} narrow={false} trigger={<PopoverTrigger render={button} />} />\n <PopoverContent data-testid={`workspace-${id}`} aria-label={label} align=\"end\" className=\"pi-chat w-[23rem] max-w-[calc(100vw-1rem)] max-h-[min(34rem,70dvh)]\">{children}</PopoverContent>\n </Popover>;\n}\n\n/** A host panel in the bar, beside History and Library: an icon button that opens `content` (`close` closes the popover or sheet). */\nexport interface WorkspaceBarPanel {\n readonly id: string;\n readonly label: string;\n readonly icon: BlockIcon;\n /** Host-owned unread indicator; opening the panel calls `onOpen`. */\n readonly dot?: boolean | undefined;\n readonly onOpen?: (() => void) | undefined;\n /** Local panel state only, including switches to another panel; not a durable acknowledgement. */\n readonly onOpenChange?: ((open: boolean) => void) | undefined;\n readonly content: (close: () => void) => ReactNode;\n}\n\nexport interface WorkspaceBarProps {\n readonly title: string;\n /** Muted after a fixed `title`: the conversation's title. Hidden on a phone, where History names the conversations. */\n readonly subtitle?: string | undefined;\n readonly conversations: ConversationsConfig | undefined;\n /** The Library's list (`onPicked` closes the popover or sheet), or undefined without a Library. */\n readonly library: ((onPicked: () => void) => ReactNode) | undefined;\n /** The host's own panels, after Library and before New (test ids `workspace-bar-<id>` and `workspace-<id>`). */\n readonly panels?: readonly WorkspaceBarPanel[] | undefined;\n /** Put host panels before History and Library. Default false. */\n readonly panelsFirst?: boolean | undefined;\n /** A phone-sized workspace: sheets instead of popovers, 44px buttons. */\n readonly narrow: boolean;\n /** The host's own controls, after New. */\n readonly controls?: ReactNode;\n}\n\n/** The bar, or only its controls in the app shell's header when the page sits in a shell screen (then nothing renders here). */\nexport function WorkspaceBar({ title, subtitle, conversations, library, panels, panelsFirst = false, narrow, controls }: WorkspaceBarProps) {\n const { labels, icons } = useAppText();\n const slot = useScreenHeaderSlot();\n const [shown, setShown] = useState<string | null>(null);\n const change = (next: string | null) => {\n if (next === shown) return;\n panels?.find(panel => panel.id === shown)?.onOpenChange?.(false);\n panels?.find(panel => panel.id === next)?.onOpenChange?.(true);\n setShown(next);\n };\n const toggle = (which: string) => (open: boolean) => change(open ? which : shown === which ? null : shown);\n const close = () => change(null);\n const hostPanels = panels?.map(panel => <BarPanel key={panel.id} id={panel.id} label={panel.label} icon={panel.icon} dot={panel.dot} narrow={narrow} open={shown === panel.id} onOpenChange={open => { toggle(panel.id)(open); if (open) panel.onOpen?.(); }}>\n {panel.content(close)}\n </BarPanel>);\n const tools = <div data-testid=\"workspace-bar-tools\" className=\"flex shrink-0 items-center gap-0.5\">\n {panelsFirst && hostPanels}\n {conversations && <BarPanel id=\"history\" label={labels.history} icon={icons.history} narrow={narrow} open={shown === 'history'} onOpenChange={toggle('history')}>\n <header className=\"flex shrink-0 items-center gap-2 pl-1\">\n <h3 className=\"m-0 min-w-0 flex-1 truncate text-sm font-semibold\">{labels.history}</h3>\n <Button variant=\"ghost\" size=\"icon-sm\" aria-label={labels.close} title={labels.close} className={iconSize(narrow)} onClick={close}><XIcon aria-hidden=\"true\" /></Button>\n </header>\n <Separator />\n <div className=\"flex min-h-0 flex-1 flex-col\"><ConversationList conversations={conversations} onPicked={close} /></div>\n </BarPanel>}\n {library && <BarPanel id=\"library\" label={labels.library} icon={icons.library} narrow={narrow} open={shown === 'library'} onOpenChange={toggle('library')}>\n <div className=\"min-h-0 flex-1 overflow-auto\">{library(close)}</div>\n </BarPanel>}\n {!panelsFirst && hostPanels}\n {conversations?.onNew && <Hinted label={labels.newChat} narrow={narrow} trigger={<Button variant=\"ghost\" size=\"icon\" data-testid=\"workspace-bar-new\" aria-label={labels.newChat} className={iconSize(narrow)} onClick={() => conversations.onNew?.()}><icons.newChat aria-hidden=\"true\" /></Button>} />}\n {controls}\n </div>;\n if (slot) return createPortal(tools, slot);\n return <>\n <header data-testid=\"workspace-bar\" className=\"flex h-13 shrink-0 items-center gap-1 pr-2 pl-4 max-md:h-14 max-md:pl-3\">\n <div className=\"flex min-w-0 flex-1 items-baseline gap-2\">\n <h2 data-testid=\"workspace-bar-title\" className={cn('m-0 min-w-0 truncate text-sm font-medium tracking-tight', subtitle === undefined && 'flex-1')}>{title}</h2>\n {subtitle !== undefined && <span data-testid=\"workspace-bar-conversation\" className=\"min-w-0 flex-1 truncate text-sm text-muted-foreground max-md:hidden\">{subtitle}</span>}\n </div>\n {tools}\n </header>\n <Separator className=\"h-px w-full\" />\n </>;\n}\n",
45
45
  "type": "registry:component",
46
46
  "target": "components/pi-app/workspace-bar.tsx"
47
47
  },
@@ -4,14 +4,14 @@
4
4
  "title": "Pi artifacts",
5
5
  "description": "Artifact descriptors, kinds and the artifact card that opens generated content in the host's panel. Plug it in with `artifacts={{ ...artifactCards, open, isOpen, kinds }}`; without it pi-chat offers no artifact. pi-app and the viewers import their artifact kinds and types from it.",
6
6
  "dependencies": [
7
- "@hachej/boring-ui-kit@^0.4.41",
7
+ "@hachej/boring-ui-kit@^0.4.42",
8
8
  "react@^19.0.0",
9
9
  "lucide-react@^1.51.0",
10
10
  "@earendil-works/pi-ai@~1.4.0",
11
11
  "@earendil-works/pi-durable@~1.4.0"
12
12
  ],
13
13
  "registryDependencies": [
14
- "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.41/r/pi-chat.json"
14
+ "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.42/r/pi-chat.json"
15
15
  ],
16
16
  "files": [
17
17
  {
@@ -4,13 +4,13 @@
4
4
  "title": "Pi chat approval card",
5
5
  "description": "The Approve / Deny card for host tools wrapped with `requireApproval`. Plug it in with `cards={{ approval: ApprovalCard }}`; without it pi-chat shows a \"waiting for your answer\" notice with no answer UI.",
6
6
  "dependencies": [
7
- "@hachej/boring-ui-kit@^0.4.41",
7
+ "@hachej/boring-ui-kit@^0.4.42",
8
8
  "react@^19.0.0",
9
9
  "lucide-react@^1.51.0",
10
10
  "@earendil-works/pi-ai@~1.4.0"
11
11
  ],
12
12
  "registryDependencies": [
13
- "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.41/r/pi-chat.json"
13
+ "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.42/r/pi-chat.json"
14
14
  ],
15
15
  "files": [
16
16
  {
@@ -9,7 +9,7 @@
9
9
  "lucide-react@^1.51.0"
10
10
  ],
11
11
  "registryDependencies": [
12
- "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.41/r/pi-chat.json"
12
+ "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.42/r/pi-chat.json"
13
13
  ],
14
14
  "files": [
15
15
  {
@@ -4,13 +4,13 @@
4
4
  "title": "Pi chat Markdown",
5
5
  "description": "Markdown for the chat's assistant replies: safe token-by-token rendering (raw HTML shown as text, no images fetched, http(s) links only), code blocks, tables, task lists and /command buttons. Plug it in with `renderText={markdownText}`; without it pi-chat shows replies as plain text.",
6
6
  "dependencies": [
7
- "@hachej/boring-ui-kit@^0.4.41",
7
+ "@hachej/boring-ui-kit@^0.4.42",
8
8
  "react@^19.0.0",
9
9
  "marked@^17.0.6",
10
10
  "entities@^8.1.0"
11
11
  ],
12
12
  "registryDependencies": [
13
- "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.41/r/pi-chat.json"
13
+ "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.42/r/pi-chat.json"
14
14
  ],
15
15
  "files": [
16
16
  {
@@ -8,7 +8,7 @@
8
8
  "lucide-react@^1.51.0"
9
9
  ],
10
10
  "registryDependencies": [
11
- "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.41/r/pi-chat.json"
11
+ "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.42/r/pi-chat.json"
12
12
  ],
13
13
  "files": [
14
14
  {
@@ -8,7 +8,7 @@
8
8
  "lucide-react@^1.51.0"
9
9
  ],
10
10
  "registryDependencies": [
11
- "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.41/r/pi-chat.json"
11
+ "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.42/r/pi-chat.json"
12
12
  ],
13
13
  "files": [
14
14
  {
@@ -7,17 +7,17 @@
7
7
  "react@^19.0.0"
8
8
  ],
9
9
  "registryDependencies": [
10
- "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.41/r/pi-chat.json",
11
- "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.41/r/pi-chat-markdown.json",
12
- "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.41/r/pi-chat-slash.json",
13
- "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.41/r/pi-chat-mentions.json",
14
- "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.41/r/pi-chat-pickers.json",
15
- "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.41/r/pi-chat-voice.json",
16
- "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.41/r/pi-chat-attachments.json",
17
- "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.41/r/pi-chat-question.json",
18
- "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.41/r/pi-chat-approval.json",
19
- "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.41/r/pi-chat-subagent.json",
20
- "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.41/r/pi-artifacts.json"
10
+ "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.42/r/pi-chat.json",
11
+ "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.42/r/pi-chat-markdown.json",
12
+ "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.42/r/pi-chat-slash.json",
13
+ "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.42/r/pi-chat-mentions.json",
14
+ "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.42/r/pi-chat-pickers.json",
15
+ "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.42/r/pi-chat-voice.json",
16
+ "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.42/r/pi-chat-attachments.json",
17
+ "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.42/r/pi-chat-question.json",
18
+ "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.42/r/pi-chat-approval.json",
19
+ "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.42/r/pi-chat-subagent.json",
20
+ "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.42/r/pi-artifacts.json"
21
21
  ],
22
22
  "files": [
23
23
  {
@@ -9,7 +9,7 @@
9
9
  "@earendil-works/pi-ai@~1.4.0"
10
10
  ],
11
11
  "registryDependencies": [
12
- "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.41/r/pi-chat.json"
12
+ "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.42/r/pi-chat.json"
13
13
  ],
14
14
  "files": [
15
15
  {
@@ -4,12 +4,12 @@
4
4
  "title": "Pi chat slash menu",
5
5
  "description": "The composer's `/` menu of commands and skills (and the Commands entry of the + menu). Plug it in with `slash={{ ...config, Picker: SlashPicker }}`; without it pi-chat has no `/` menu.",
6
6
  "dependencies": [
7
- "@hachej/boring-ui-kit@^0.4.41",
7
+ "@hachej/boring-ui-kit@^0.4.42",
8
8
  "react@^19.0.0",
9
9
  "lucide-react@^1.51.0"
10
10
  ],
11
11
  "registryDependencies": [
12
- "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.41/r/pi-chat.json"
12
+ "https://cdn.jsdelivr.net/npm/@hachej/boring-ui-kit@0.4.42/r/pi-chat.json"
13
13
  ],
14
14
  "files": [
15
15
  {