@surfaces-ui/chat 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/NOTICE CHANGED
@@ -2,3 +2,53 @@ Surfaces UI
2
2
  Copyright 2026 Josh Schoen
3
3
 
4
4
  This product is licensed under the Apache License, Version 2.0 (see LICENSE).
5
+
6
+ --------------------------------------------------------------------------------
7
+
8
+ @surfaces-ui/icons includes drawings from Lucide (https://lucide.dev), taken
9
+ from lucide-static 1.84.0. Other packages include some of them by depending on
10
+ it or by bundling it. They are used under this license:
11
+
12
+ ISC License
13
+
14
+ Copyright (c) 2026 Lucide Icons and Contributors
15
+
16
+ Permission to use, copy, modify, and/or distribute this software for any
17
+ purpose with or without fee is hereby granted, provided that the above
18
+ copyright notice and this permission notice appear in all copies.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
21
+ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
22
+ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
23
+ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
24
+ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
25
+ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
26
+ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
27
+
28
+ ---
29
+
30
+ The following Lucide icons are derived from the Feather project:
31
+
32
+ airplay, alert-circle, alert-octagon, alert-triangle, aperture, arrow-down-circle, arrow-down-left, arrow-down-right, arrow-down, arrow-left-circle, arrow-left, arrow-right-circle, arrow-right, arrow-up-circle, arrow-up-left, arrow-up-right, arrow-up, at-sign, calendar, cast, check, chevron-down, chevron-left, chevron-right, chevron-up, chevrons-down, chevrons-left, chevrons-right, chevrons-up, circle, clipboard, clock, code, columns, command, compass, corner-down-left, corner-down-right, corner-left-down, corner-left-up, corner-right-down, corner-right-up, corner-up-left, corner-up-right, crosshair, database, divide-circle, divide-square, dollar-sign, download, external-link, feather, frown, hash, headphones, help-circle, info, italic, key, layout, life-buoy, link-2, link, loader, lock, log-in, log-out, maximize, meh, minimize, minimize-2, minus-circle, minus-square, minus, monitor, moon, more-horizontal, more-vertical, move, music, navigation-2, navigation, octagon, pause-circle, percent, plus-circle, plus-square, plus, power, radio, rss, search, server, share, shopping-bag, sidebar, smartphone, smile, square, table-2, tablet, target, terminal, trash-2, trash, triangle, tv, type, upload, x-circle, x-octagon, x-square, x, zoom-in, zoom-out
33
+
34
+ The MIT License (MIT) (for the icons listed above)
35
+
36
+ Copyright (c) 2013-present Cole Bemis
37
+
38
+ Permission is hereby granted, free of charge, to any person obtaining a copy
39
+ of this software and associated documentation files (the "Software"), to deal
40
+ in the Software without restriction, including without limitation the rights
41
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
42
+ copies of the Software, and to permit persons to whom the Software is
43
+ furnished to do so, subject to the following conditions:
44
+
45
+ The above copyright notice and this permission notice shall be included in all
46
+ copies or substantial portions of the Software.
47
+
48
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
49
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
50
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
51
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
52
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
53
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
54
+ SOFTWARE.
package/dist/Chat.d.ts CHANGED
@@ -5,7 +5,7 @@ import { type Catalog, type SurfaceAction } from "@surfaces-ui/spec";
5
5
  import { type ComponentRenderer, type SurfaceNote } from "@surfaces-ui/spec/react";
6
6
  import { type Ref } from "react";
7
7
  import { type AttachResult, type ComposerHandle, type ComposerProps } from "./ChatComposer.js";
8
- import type { ChatActions, ChatActor, ChatStep, ChatThread, ChatUsage } from "./thread.js";
8
+ import type { ChatActions, ChatActor, ChatMessage, ChatStep, ChatThread, ChatUsage } from "./thread.js";
9
9
  import type { ChatProvider } from "./selectors.js";
10
10
  import { type ChatSettings, type UseChat, type UseChatOptions } from "./useChat.js";
11
11
  export interface ToolStepsProps {
@@ -50,6 +50,8 @@ export interface MessageListProps {
50
50
  */
51
51
  resolveImage?: ImageResolver;
52
52
  }
53
+ /** What an agent is doing while its reply is on its way, in words, from the reply's parts so far. */
54
+ export declare function workingWords(message: ChatMessage): string;
53
55
  /**
54
56
  * The conversation so far. Replies can hold text, tool steps, approvals and
55
57
  * components the agent drew. The list follows new content while the reader
@@ -62,9 +64,14 @@ export interface SuggestionsProps {
62
64
  }
63
65
  /** Things the person might say next, one press each. */
64
66
  export declare function Suggestions({ items, onPick }: SuggestionsProps): import("react").JSX.Element | null;
65
- /** How full the agent's context is, and what the conversation has cost when known. */
66
- export declare function UsageGauge({ usage }: {
67
+ /**
68
+ * How full the agent's context is, and what the conversation has cost when
69
+ * known. With `empty`, those words are shown while the context is not known;
70
+ * without it nothing is.
71
+ */
72
+ export declare function UsageGauge({ usage, empty }: {
67
73
  usage: ChatUsage | undefined;
74
+ empty?: string;
68
75
  }): import("react").JSX.Element | null;
69
76
  export interface ChatProps {
70
77
  /** Any agent runtime behind the AgentBackend interface. */
package/dist/Chat.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { ImageResolverProvider, Markdown, addDataRefs, dataRefLabel, hasDataRefs, readDataRefs, safeImageAddress, sameDataRef } from "@surfaces-ui/components";
2
+ import { ImageResolverProvider, Markdown, addDataRefs, dataRefLabel, hasDataRefs, readDataRefs, safeImageAddress, sameDataRef, WorkingLine } from "@surfaces-ui/components";
3
3
  import { analyticsCatalog } from "@surfaces-ui/spec";
4
4
  import { SurfaceView, lazyAnalyticsRenderers } from "@surfaces-ui/spec/react";
5
5
  import { useEffect, useId, useRef, useState } from "react";
@@ -43,6 +43,23 @@ function AttachedChips({ attachments }) {
43
43
  return (_jsxs("li", { className: "sf-chat-reference", "data-kind": "attachment", "data-thumbnail": picture ? true : undefined, children: [picture ? _jsx("img", { className: "sf-chat-thumbnail", src: picture, alt: "", loading: "lazy", decoding: "async" }) : null, _jsx("span", { children: one.name })] }, one.id ?? one.name));
44
44
  }) }));
45
45
  }
46
+ /** What an agent is doing while its reply is on its way, in words, from the reply's parts so far. */
47
+ export function workingWords(message) {
48
+ const last = message.parts.at(-1);
49
+ if (!last)
50
+ return "Waiting for the agent to start…";
51
+ if (last.kind === "steps") {
52
+ const running = last.steps.findLast((s) => s.status === "running");
53
+ if (running)
54
+ return running.title ? /[.…]$/.test(running.title) ? running.title : `${running.title}…` : "Running a step…";
55
+ return last.steps.at(-1)?.status === "failed" ? "A step failed. Working out what to do instead…" : "Deciding what to do with what it found…";
56
+ }
57
+ if (last.kind === "text")
58
+ return "Writing its answer…";
59
+ if (last.kind === "surface")
60
+ return "Drawing…";
61
+ return "Working…";
62
+ }
46
63
  function MessageView({ message, thread, catalog, renderers, onAction, onAnswer, onReport, onProblem, onContext, onPartAction }) {
47
64
  if (message.role === "user") {
48
65
  return (_jsxs("article", { className: "sf-chat-message", "data-role": "user", children: [_jsx("span", { className: "sf-a2-visually-hidden", children: "You said:" }), _jsx("p", { children: message.parts.map((p) => (p.kind === "text" ? p.text : "")).join("") }), message.parts.map((p, i) => p.kind === "references" ? (_jsx("ul", { className: "sf-chat-references", "aria-label": "Attached", children: p.references.map((ref) => (_jsx("li", { className: "sf-chat-reference", "data-kind": ref.kind, children: dataRefLabel(ref) }, `${ref.sourceId}/${dataRefLabel(ref)}`))) }, i)) : p.kind === "attachments" ? (_jsx(AttachedChips, { attachments: p.attachments }, i)) : null)] }));
@@ -73,7 +90,7 @@ function MessageView({ message, thread, catalog, renderers, onAction, onAnswer,
73
90
  default:
74
91
  return (_jsx("p", { className: "sf-chat-error", role: "alert", children: part.code === "CANCELLED" ? "Stopped." : part.message }, index));
75
92
  }
76
- }), message.streaming && message.parts.length === 0 && _jsx("p", { className: "sf-chat-thinking", children: "Working\u2026" }), !message.streaming && message.generatedBy && _jsxs("p", { className: "sf-chat-by", children: ["Answered by ", message.generatedBy] })] }));
93
+ }), message.streaming && _jsx(WorkingLine, { className: "sf-chat-thinking", label: message.progress || workingWords(message), seed: String(message.id), announce: false }), !message.streaming && message.generatedBy && _jsxs("p", { className: "sf-chat-by", children: ["Answered by ", message.generatedBy] })] }));
77
94
  }
78
95
  /**
79
96
  * The conversation so far. Replies can hold text, tool steps, approvals and
@@ -101,10 +118,14 @@ export function Suggestions({ items, onPick }) {
101
118
  return null;
102
119
  return (_jsx("div", { className: "sf-chat-suggestions", role: "group", "aria-label": "Suggestions", children: items.map((item) => (_jsx("button", { type: "button", className: "sf-button", onClick: () => onPick(item), children: item }, item))) }));
103
120
  }
104
- /** How full the agent's context is, and what the conversation has cost when known. */
105
- export function UsageGauge({ usage }) {
121
+ /**
122
+ * How full the agent's context is, and what the conversation has cost when
123
+ * known. With `empty`, those words are shown while the context is not known;
124
+ * without it nothing is.
125
+ */
126
+ export function UsageGauge({ usage, empty }) {
106
127
  if (!usage || usage.contextLimit <= 0)
107
- return null;
128
+ return empty ? _jsx("p", { className: "sf-chat-usage", children: empty }) : null;
108
129
  const share = Math.min(1, usage.contextTokens / usage.contextLimit);
109
130
  return (_jsxs("p", { className: "sf-chat-usage", children: [_jsx("meter", { min: 0, max: 1, high: 0.8, value: share, "aria-label": "Context used" }), _jsxs("span", { children: [Math.round(share * 100), "% of context used", usage.costUsd !== undefined ? ` · $${usage.costUsd.toFixed(2)}` : ""] })] }));
110
131
  }
package/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AAK,SAAS,CAAC,CAAC,CAAC,6CAA6C,CAAC,CAAC,CAAC,KAAK,CAAC,WAAW,GAAI,EAClM,KAAC,UAAU,IAAC,KAAK,EAAE,MAAM,CAAC,KAAK,GAAI,IAC3B,CACX,CAAC;AACJ,CAAC","sourcesContent":["import type { AgentBackend } from \"@surfaces-ui/agent\";\nimport type { AgentInfo } from \"@surfaces-ui/proto\";\nimport { type DataRef, type ImageResolver, ImageResolverProvider, Markdown, addDataRefs, dataRefLabel, hasDataRefs, readDataRefs, safeImageAddress, sameDataRef } from \"@surfaces-ui/components\";\nimport { type Catalog, type SurfaceAction, analyticsCatalog } from \"@surfaces-ui/spec\";\nimport { type ComponentRenderer, type SurfaceNote, SurfaceView, lazyAnalyticsRenderers } from \"@surfaces-ui/spec/react\";\nimport { type DragEvent, type FormEvent, type KeyboardEvent, type Ref, useEffect, useId, useRef, useState } from \"react\";\nimport { ApprovalCard } from \"./Approval.js\";\nimport { type AttachResult, Composer, type ComposerHandle, type ComposerProps } from \"./ChatComposer.js\";\nimport type { ChatActions, ChatActor, ChatAttachment, ChatButton, ChatMessage, ChatStep, ChatThread, ChatUsage } from \"./thread.js\";\nimport type { ChatProvider } from \"./selectors.js\";\nimport { type ChatSettings, type UseChat, type UseChatOptions, useChat } from \"./useChat.js\";\n\nconst count = new Intl.NumberFormat(\"en-US\");\nconst STEP_MARK: Record<ChatStep[\"status\"], string> = { running: \"…\", done: \"✓\", failed: \"!\" };\nconst STEP_WORD: Record<ChatStep[\"status\"], string> = { running: \"running\", done: \"done\", failed: \"failed\" };\n\nexport interface ToolStepsProps {\n steps: ChatStep[];\n}\n\n/** The work an agent did for a reply, such as tool calls. Each step opens to show its detail. */\nexport function ToolSteps({ steps }: ToolStepsProps) {\n return (\n <ul className=\"sf-chat-steps\" aria-label=\"Steps\">\n {steps.map((step) => (\n <li key={step.id} data-status={step.status}>\n <details>\n <summary>\n <span className=\"sf-chat-step-mark\" aria-hidden=\"true\">\n {STEP_MARK[step.status]}\n </span>\n <span className=\"sf-chat-step-title\">{step.title || step.tool}</span>\n <span className=\"sf-chat-step-meta\">\n {STEP_WORD[step.status]}\n {step.durationMs > 0 ? ` · ${count.format(step.durationMs)} ms` : \"\"}\n </span>\n </summary>\n {step.tool && <p className=\"sf-chat-step-tool\">Tool: {step.tool}</p>}\n {step.detail && <pre tabIndex={0}>{step.detail}</pre>}\n </details>\n </li>\n ))}\n </ul>\n );\n}\n\nexport interface ActionsCardProps {\n actions: ChatActions;\n /** A press: the button's id, and the choice it belongs to when it is in one. Never called for a disabled button. */\n onPress(buttonId: string, choiceId?: string): void;\n}\n\nfunction ActionButtons({ buttons, label, onPress }: { buttons: ChatButton[]; label?: string; onPress(id: string): void }) {\n const uid = useId();\n if (buttons.length === 0) return null;\n return (\n <div className=\"sf-chat-actions-row\" role={label ? \"group\" : undefined} aria-label={label}>\n {buttons.map((button, i) => {\n const why = button.reason ? `${uid}-${i}` : undefined;\n return (\n <span key={button.id} className=\"sf-chat-actions-button\">\n <button\n type=\"button\"\n className=\"sf-button\"\n data-variant={button.variant}\n // Not `disabled`: a disabled button cannot be reached by keyboard, and then neither can its reason.\n aria-disabled={button.disabled || undefined}\n aria-label={button.ariaLabel}\n aria-describedby={why}\n title={button.reason}\n onClick={() => {\n if (!button.disabled) onPress(button.id);\n }}\n >\n {button.label}\n </button>\n {why && (\n <span id={why} className=\"sf-a2-visually-hidden\">\n {button.reason}\n </span>\n )}\n </span>\n );\n })}\n </div>\n );\n}\n\n/**\n * What a person can do about a reply, under it: a row of buttons, or several\n * alternatives one row each with buttons for the whole set after them. The\n * host decides what a press does and, once it is handled, replaces the\n * buttons with what became of it (`outcome`).\n */\nexport function ActionsCard({ actions, onPress }: ActionsCardProps) {\n const choices = actions.choices ?? [];\n return (\n <div className=\"sf-chat-actions\" role=\"group\" aria-label={actions.title || \"Actions\"} data-handled={actions.outcome !== undefined || undefined}>\n {actions.title && <p className=\"sf-chat-actions-title\">{actions.title}</p>}\n {actions.detail && <p className=\"sf-chat-actions-detail\">{actions.detail}</p>}\n {actions.outcome !== undefined ? (\n <p className=\"sf-chat-actions-outcome\" role=\"status\">\n {actions.outcome}\n </p>\n ) : (\n <>\n {choices.length > 0 && (\n <ul className=\"sf-chat-actions-choices\" aria-label=\"Choices\">\n {choices.map((choice) => (\n <li key={choice.id}>\n <p className=\"sf-chat-actions-choice\">\n <span className=\"sf-chat-actions-title\">{choice.title}</span>\n {choice.detail && <span className=\"sf-chat-actions-detail\"> · {choice.detail}</span>}\n </p>\n <ActionButtons buttons={choice.buttons} label={choice.title} onPress={(id) => onPress(id, choice.id)} />\n </li>\n ))}\n </ul>\n )}\n <ActionButtons buttons={actions.buttons ?? []} label={choices.length > 0 ? \"All choices\" : undefined} onPress={(id) => onPress(id)} />\n </>\n )}\n </div>\n );\n}\n\nexport interface MessageListProps {\n thread: ChatThread;\n catalog: Catalog;\n renderers: Record<string, ComponentRenderer>;\n onAction(action: SurfaceAction): void;\n onAnswer: UseChat[\"answer\"];\n /** Where each drawn surface stands and what went wrong with it, kept for the agent's next turn (`useChat`'s `report` and `problem`). */\n onReport?: UseChat[\"report\"];\n onProblem?: UseChat[\"problem\"];\n /** Told what a person does in a drawn component as they do it, with where. For a host that keeps its own context for an agent. */\n onContext?(note: SurfaceNote & { surfaceId: string; componentId: string }): void;\n /** A press on a button in an actions part (`ChatActions`): the part's id, the button's id, and its choice's id when it is in one. */\n onPartAction?(partId: string, actionId: string, choiceId?: string): void;\n /** Shown when the thread is empty. */\n empty?: string;\n /**\n * How an image an agent named is drawn, in its replies' Markdown and in any `Image` it draws: turns the name or address\n * it wrote into the address to load, or nothing (the description is shown). Without it, or a resolver given above\n * (`ImageResolverProvider`), no image an agent wrote is loaded. Not used for a person's own attachments (`ChatAttachment.preview`).\n */\n resolveImage?: ImageResolver;\n}\n\n/** Pictures and files a person attached to their message, as chips with a thumbnail where there is one. */\nfunction AttachedChips({ attachments }: { attachments: ChatAttachment[] }) {\n return (\n <ul className=\"sf-chat-references sf-chat-attachments\" aria-label=\"Attached files\">\n {attachments.map((one) => {\n // The preview is the host's own (a blob it made from the file), never an address a model wrote.\n const picture = one.mediaType.startsWith(\"image/\") ? safeImageAddress(one.preview) : undefined;\n return (\n <li key={one.id ?? one.name} className=\"sf-chat-reference\" data-kind=\"attachment\" data-thumbnail={picture ? true : undefined}>\n {picture ? <img className=\"sf-chat-thumbnail\" src={picture} alt=\"\" loading=\"lazy\" decoding=\"async\" /> : null}\n <span>{one.name}</span>\n </li>\n );\n })}\n </ul>\n );\n}\n\nfunction MessageView({ message, thread, catalog, renderers, onAction, onAnswer, onReport, onProblem, onContext, onPartAction }: MessageListProps & { message: ChatMessage }) {\n if (message.role === \"user\") {\n return (\n <article className=\"sf-chat-message\" data-role=\"user\">\n <span className=\"sf-a2-visually-hidden\">You said:</span>\n <p>{message.parts.map((p) => (p.kind === \"text\" ? p.text : \"\")).join(\"\")}</p>\n {message.parts.map((p, i) =>\n p.kind === \"references\" ? (\n // biome-ignore lint/suspicious/noArrayIndexKey: a message's parts do not move.\n <ul key={i} className=\"sf-chat-references\" aria-label=\"Attached\">\n {p.references.map((ref) => (\n <li key={`${ref.sourceId}/${dataRefLabel(ref)}`} className=\"sf-chat-reference\" data-kind={ref.kind}>\n {dataRefLabel(ref)}\n </li>\n ))}\n </ul>\n ) : p.kind === \"attachments\" ? (\n // biome-ignore lint/suspicious/noArrayIndexKey: a message's parts do not move.\n <AttachedChips key={i} attachments={p.attachments} />\n ) : null,\n )}\n </article>\n );\n }\n return (\n <article className=\"sf-chat-message\" data-role=\"assistant\" aria-busy={message.streaming}>\n <span className=\"sf-a2-visually-hidden\">The agent replied:</span>\n {message.parts.map((part, index) => {\n switch (part.kind) {\n case \"text\":\n return <Markdown key={index} text={part.text} />;\n case \"steps\":\n return <ToolSteps key={index} steps={part.steps} />;\n case \"surface\": {\n const surface = thread.surfaces[part.surfaceId];\n // Agent-drawn components are checked against the catalog before they are drawn.\n const key = part.surfaceId;\n return surface ? (\n <SurfaceView\n key={index}\n surface={surface}\n catalog={catalog}\n renderers={renderers}\n onAction={onAction}\n onDataChange={(data) => onReport?.(key, { data })}\n onControlsChange={(componentId, controls) => onReport?.(key, { componentId, controls })}\n onContext={(componentId, note) => {\n onReport?.(key, { componentId, note });\n onContext?.({ ...note, surfaceId: key, componentId });\n }}\n onProblem={(problem) => onProblem?.(key, problem)}\n className=\"sf-chat-surface\"\n />\n ) : null;\n }\n case \"approval\":\n return <ApprovalCard key={index} approval={part.approval} onAnswer={onAnswer} />;\n case \"actions\":\n return <ActionsCard key={index} actions={part.actions} onPress={(actionId, choiceId) => onPartAction?.(part.actions.id, actionId, choiceId)} />;\n case \"references\":\n case \"attachments\":\n // Attachments belong to what a person sent; a reply has none.\n return null;\n default:\n return (\n <p key={index} className=\"sf-chat-error\" role=\"alert\">\n {part.code === \"CANCELLED\" ? \"Stopped.\" : part.message}\n </p>\n );\n }\n })}\n {message.streaming && message.parts.length === 0 && <p className=\"sf-chat-thinking\">Working…</p>}\n {!message.streaming && message.generatedBy && <p className=\"sf-chat-by\">Answered by {message.generatedBy}</p>}\n </article>\n );\n}\n\n/**\n * The conversation so far. Replies can hold text, tool steps, approvals and\n * components the agent drew. The list follows new content while the reader\n * is at the bottom and stays put when they have scrolled up.\n */\nexport function MessageList(props: MessageListProps) {\n const { thread } = props;\n const list = useRef<HTMLDivElement>(null);\n const pinned = useRef(true);\n useEffect(() => {\n const element = list.current;\n if (element && pinned.current) element.scrollTop = element.scrollHeight;\n }, [thread]);\n const list_ = (\n <div\n ref={list}\n className=\"sf-chat-list\"\n role=\"log\"\n aria-label=\"Conversation\"\n aria-live=\"polite\"\n tabIndex={0}\n onScroll={(event) => {\n const element = event.currentTarget;\n pinned.current = element.scrollHeight - element.scrollTop - element.clientHeight < 48;\n }}\n >\n {thread.messages.length === 0 && props.empty && <div className=\"sf-chat-empty\">{props.empty}</div>}\n {thread.messages.map((message) => (\n <MessageView key={message.id} {...props} message={message} />\n ))}\n </div>\n );\n return props.resolveImage ? <ImageResolverProvider resolve={props.resolveImage}>{list_}</ImageResolverProvider> : list_;\n}\n\nexport interface SuggestionsProps {\n items: string[];\n onPick(text: string): void;\n}\n\n/** Things the person might say next, one press each. */\nexport function Suggestions({ items, onPick }: SuggestionsProps) {\n if (items.length === 0) return null;\n return (\n <div className=\"sf-chat-suggestions\" role=\"group\" aria-label=\"Suggestions\">\n {items.map((item) => (\n <button key={item} type=\"button\" className=\"sf-button\" onClick={() => onPick(item)}>\n {item}\n </button>\n ))}\n </div>\n );\n}\n\n/** How full the agent's context is, and what the conversation has cost when known. */\nexport function UsageGauge({ usage }: { usage: ChatUsage | undefined }) {\n if (!usage || usage.contextLimit <= 0) return null;\n const share = Math.min(1, usage.contextTokens / usage.contextLimit);\n return (\n <p className=\"sf-chat-usage\">\n <meter min={0} max={1} high={0.8} value={share} aria-label=\"Context used\" />\n <span>\n {Math.round(share * 100)}% of context used\n {usage.costUsd !== undefined ? ` · $${usage.costUsd.toFixed(2)}` : \"\"}\n </span>\n </p>\n );\n}\n\nexport interface ChatProps {\n /** Any agent runtime behind the AgentBackend interface. */\n agent: AgentBackend;\n /** The catalog agent-drawn components are checked against. Defaults to the analytics catalog. */\n catalog?: Catalog;\n renderers?: Record<string, ComponentRenderer>;\n agentId?: string;\n /** Limit the agent to the data in this saved context pack. */\n contextPackId?: string;\n /** Who is using the chat, from the host's sign-in; recorded on approval answers and surface events. */\n user?: ChatActor;\n /** Where to keep the conversation across reloads (`browserStorage()` from `@surfaces-ui/state`, or your own). */\n storage?: UseChatOptions[\"storage\"];\n storageKey?: string;\n /** Tables and columns attached to the message being written, when the host holds them (see `Composer`). */\n references?: DataRef[];\n onReferencesChange?(references: DataRef[]): void;\n /** The thread to open with: a saved or written conversation. Read once. */\n initialThread?: ChatThread;\n /** Told the thread after every change, so a host can save it or build from what was drawn. */\n onThreadChange?(thread: ChatThread): void;\n /**\n * Told what a person does in a drawn component as they do it (a view\n * added, a field changed, a filter set). The chat already keeps these and\n * gives them to the agent with its next turn; this is for a host that\n * wants them too.\n */\n onContext?: MessageListProps[\"onContext\"];\n /** Offered before the first message. */\n starters?: string[];\n placeholder?: string;\n /** How an image an agent named is drawn; see `MessageListProps.resolveImage`. */\n resolveImage?: ImageResolver;\n /** Turns files a person drops, pastes or picks into data or attachments; see `ComposerProps.attachFiles`. Without it there is no upload. */\n attachFiles?(files: File[]): Promise<AttachResult[]>;\n /** What the file picker offers; see `ComposerProps.accept`. */\n accept?: string;\n /** Widens the drop target beyond the composer; see `ComposerProps.dropTarget`. */\n dropTarget?: ComposerProps[\"dropTarget\"];\n /** Hands files in from outside; see `ComposerProps.handleRef`. */\n composerRef?: Ref<ComposerHandle>;\n /** The agent, model, skills and connectors a person chose, sent with each turn; with `onSettingsChange` the composer offers them. */\n settings?: ChatSettings;\n onSettingsChange?(settings: ChatSettings): void;\n /** What the agent offers (`DescribeAgents`), for the composer's menus. */\n agents?: AgentInfo[];\n /** Where models run, when the host can reach several: the Model menu groups models by provider. */\n providers?: ChatProvider[];\n onManageProviders?(): void;\n /** Shown when the thread is empty. */\n empty?: string;\n /** Height of the whole chat. A number is px. Defaults to 640. */\n height?: number | string;\n className?: string;\n}\n\n/**\n * A complete chat: the conversation, suggestions and the composer. Agent\n * replies stream in as Markdown, with tool steps, approvals and any catalog\n * component (charts, tables, pivots, model diagrams, decision cards) drawn\n * inline. Data components need a DataSourceProvider above the chat.\n */\nexport function Chat(props: ChatProps) {\n const catalog = props.catalog ?? analyticsCatalog;\n const renderers = props.renderers ?? lazyAnalyticsRenderers;\n const chat = useChat(props.agent, { catalog, agentId: props.agentId, contextPackId: props.contextPackId, user: props.user, storage: props.storage, storageKey: props.storageKey, initial: props.initialThread, settings: props.settings });\n const { thread } = chat;\n // Told on a change of thread only: a host passing a new function each render must not be told again (and set state in a loop).\n const onThreadChange = useRef(props.onThreadChange);\n onThreadChange.current = props.onThreadChange;\n useEffect(() => onThreadChange.current?.(thread), [thread]);\n const suggestions = thread.messages.length === 0 ? (props.starters ?? []) : thread.status === \"idle\" ? thread.suggestions : [];\n return (\n <section className={[\"sf-chat\", props.className].filter(Boolean).join(\" \")} style={{ height: props.height ?? 640 }} aria-label=\"Chat\">\n <MessageList thread={thread} catalog={catalog} renderers={renderers} onAction={chat.act} onAnswer={chat.answer} onReport={chat.report} onProblem={chat.problem} onContext={props.onContext} empty={props.empty} resolveImage={props.resolveImage} />\n <Suggestions items={suggestions} onPick={(text) => chat.send(text)} />\n <Composer\n agents={props.agents}\n settings={props.settings}\n onSettingsChange={props.onSettingsChange}\n providers={props.providers}\n onManageProviders={props.onManageProviders}\n references={props.references}\n onReferencesChange={props.onReferencesChange}\n attachFiles={props.attachFiles}\n accept={props.accept}\n dropTarget={props.dropTarget}\n handleRef={props.composerRef}\n onSend={chat.send} onStop={chat.stop} streaming={thread.status === \"streaming\"} placeholder={thread.status === \"waiting\" ? \"Answer above, or type to say something else\" : props.placeholder} />\n <UsageGauge usage={thread.usage} />\n </section>\n );\n}\n"]}
1
+ {"version":3,"file":"Chat.js","sourceRoot":"","sources":["../src/Chat.tsx"],"names":[],"mappings":";AAEA,OAAO,EAAoC,qBAAqB,EAAE,QAAQ,EAAE,WAAW,EAAE,YAAY,EAAE,WAAW,EAAE,YAAY,EAAE,gBAAgB,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AAC9M,OAAO,EAAoC,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AACvF,OAAO,EAA4C,WAAW,EAAE,sBAAsB,EAAE,MAAM,yBAAyB,CAAC;AACxH,OAAO,EAAgE,SAAS,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AACzH,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAC7C,OAAO,EAAqB,QAAQ,EAA2C,MAAM,mBAAmB,CAAC;AAGzG,OAAO,EAAwD,OAAO,EAAE,MAAM,cAAc,CAAC;AAE7F,MAAM,KAAK,GAAG,IAAI,IA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QAAQ,EACxB,gBAAgB,EAAE,KAAK,CAAC,gBAAgB,EACxC,SAAS,EAAE,KAAK,CAAC,SAAS,EAC1B,iBAAiB,EAAE,KAAK,CAAC,iBAAiB,EAC1C,UAAU,EAAE,KAAK,CAAC,UAAU,EAC5B,kBAAkB,EAAE,KAAK,CAAC,kBAAkB,EAC5C,WAAW,EAAE,KAAK,CAAC,WAAW,EAC9B,MAAM,EAAE,KAAK,CAAC,MAAM,EACpB,UAAU,EAAE,KAAK,CAAC,UAAU,EAC5B,SAAS,EAAE,KAAK,CAAC,WAAW,EAC5B,MAAM,EAAE,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,IAAI,EAAE,SAAS,EAAE,MAAM,CAAC,MAAM,KAAK,WAAW,EAAE,WAAW,EAAE,MAAM,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,6CAA6C,CAAC,CAAC,CAAC,KAAK,CAAC,WAAW,GAAI,EAClM,KAAC,UAAU,IAAC,KAAK,EAAE,MAAM,CAAC,KAAK,GAAI,IAC3B,CACX,CAAC;AACJ,CAAC","sourcesContent":["import type { AgentBackend } from \"@surfaces-ui/agent\";\nimport type { AgentInfo } from \"@surfaces-ui/proto\";\nimport { type DataRef, type ImageResolver, ImageResolverProvider, Markdown, addDataRefs, dataRefLabel, hasDataRefs, readDataRefs, safeImageAddress, sameDataRef, WorkingLine } from \"@surfaces-ui/components\";\nimport { type Catalog, type SurfaceAction, analyticsCatalog } from \"@surfaces-ui/spec\";\nimport { type ComponentRenderer, type SurfaceNote, SurfaceView, lazyAnalyticsRenderers } from \"@surfaces-ui/spec/react\";\nimport { type DragEvent, type FormEvent, type KeyboardEvent, type Ref, useEffect, useId, useRef, useState } from \"react\";\nimport { ApprovalCard } from \"./Approval.js\";\nimport { type AttachResult, Composer, type ComposerHandle, type ComposerProps } from \"./ChatComposer.js\";\nimport type { ChatActions, ChatActor, ChatAttachment, ChatButton, ChatMessage, ChatStep, ChatThread, ChatUsage } from \"./thread.js\";\nimport type { ChatProvider } from \"./selectors.js\";\nimport { type ChatSettings, type UseChat, type UseChatOptions, useChat } from \"./useChat.js\";\n\nconst count = new Intl.NumberFormat(\"en-US\");\nconst STEP_MARK: Record<ChatStep[\"status\"], string> = { running: \"…\", done: \"✓\", failed: \"!\" };\nconst STEP_WORD: Record<ChatStep[\"status\"], string> = { running: \"running\", done: \"done\", failed: \"failed\" };\n\nexport interface ToolStepsProps {\n steps: ChatStep[];\n}\n\n/** The work an agent did for a reply, such as tool calls. Each step opens to show its detail. */\nexport function ToolSteps({ steps }: ToolStepsProps) {\n return (\n <ul className=\"sf-chat-steps\" aria-label=\"Steps\">\n {steps.map((step) => (\n <li key={step.id} data-status={step.status}>\n <details>\n <summary>\n <span className=\"sf-chat-step-mark\" aria-hidden=\"true\">\n {STEP_MARK[step.status]}\n </span>\n <span className=\"sf-chat-step-title\">{step.title || step.tool}</span>\n <span className=\"sf-chat-step-meta\">\n {STEP_WORD[step.status]}\n {step.durationMs > 0 ? ` · ${count.format(step.durationMs)} ms` : \"\"}\n </span>\n </summary>\n {step.tool && <p className=\"sf-chat-step-tool\">Tool: {step.tool}</p>}\n {step.detail && <pre tabIndex={0}>{step.detail}</pre>}\n </details>\n </li>\n ))}\n </ul>\n );\n}\n\nexport interface ActionsCardProps {\n actions: ChatActions;\n /** A press: the button's id, and the choice it belongs to when it is in one. Never called for a disabled button. */\n onPress(buttonId: string, choiceId?: string): void;\n}\n\nfunction ActionButtons({ buttons, label, onPress }: { buttons: ChatButton[]; label?: string; onPress(id: string): void }) {\n const uid = useId();\n if (buttons.length === 0) return null;\n return (\n <div className=\"sf-chat-actions-row\" role={label ? \"group\" : undefined} aria-label={label}>\n {buttons.map((button, i) => {\n const why = button.reason ? `${uid}-${i}` : undefined;\n return (\n <span key={button.id} className=\"sf-chat-actions-button\">\n <button\n type=\"button\"\n className=\"sf-button\"\n data-variant={button.variant}\n // Not `disabled`: a disabled button cannot be reached by keyboard, and then neither can its reason.\n aria-disabled={button.disabled || undefined}\n aria-label={button.ariaLabel}\n aria-describedby={why}\n title={button.reason}\n onClick={() => {\n if (!button.disabled) onPress(button.id);\n }}\n >\n {button.label}\n </button>\n {why && (\n <span id={why} className=\"sf-a2-visually-hidden\">\n {button.reason}\n </span>\n )}\n </span>\n );\n })}\n </div>\n );\n}\n\n/**\n * What a person can do about a reply, under it: a row of buttons, or several\n * alternatives one row each with buttons for the whole set after them. The\n * host decides what a press does and, once it is handled, replaces the\n * buttons with what became of it (`outcome`).\n */\nexport function ActionsCard({ actions, onPress }: ActionsCardProps) {\n const choices = actions.choices ?? [];\n return (\n <div className=\"sf-chat-actions\" role=\"group\" aria-label={actions.title || \"Actions\"} data-handled={actions.outcome !== undefined || undefined}>\n {actions.title && <p className=\"sf-chat-actions-title\">{actions.title}</p>}\n {actions.detail && <p className=\"sf-chat-actions-detail\">{actions.detail}</p>}\n {actions.outcome !== undefined ? (\n <p className=\"sf-chat-actions-outcome\" role=\"status\">\n {actions.outcome}\n </p>\n ) : (\n <>\n {choices.length > 0 && (\n <ul className=\"sf-chat-actions-choices\" aria-label=\"Choices\">\n {choices.map((choice) => (\n <li key={choice.id}>\n <p className=\"sf-chat-actions-choice\">\n <span className=\"sf-chat-actions-title\">{choice.title}</span>\n {choice.detail && <span className=\"sf-chat-actions-detail\"> · {choice.detail}</span>}\n </p>\n <ActionButtons buttons={choice.buttons} label={choice.title} onPress={(id) => onPress(id, choice.id)} />\n </li>\n ))}\n </ul>\n )}\n <ActionButtons buttons={actions.buttons ?? []} label={choices.length > 0 ? \"All choices\" : undefined} onPress={(id) => onPress(id)} />\n </>\n )}\n </div>\n );\n}\n\nexport interface MessageListProps {\n thread: ChatThread;\n catalog: Catalog;\n renderers: Record<string, ComponentRenderer>;\n onAction(action: SurfaceAction): void;\n onAnswer: UseChat[\"answer\"];\n /** Where each drawn surface stands and what went wrong with it, kept for the agent's next turn (`useChat`'s `report` and `problem`). */\n onReport?: UseChat[\"report\"];\n onProblem?: UseChat[\"problem\"];\n /** Told what a person does in a drawn component as they do it, with where. For a host that keeps its own context for an agent. */\n onContext?(note: SurfaceNote & { surfaceId: string; componentId: string }): void;\n /** A press on a button in an actions part (`ChatActions`): the part's id, the button's id, and its choice's id when it is in one. */\n onPartAction?(partId: string, actionId: string, choiceId?: string): void;\n /** Shown when the thread is empty. */\n empty?: string;\n /**\n * How an image an agent named is drawn, in its replies' Markdown and in any `Image` it draws: turns the name or address\n * it wrote into the address to load, or nothing (the description is shown). Without it, or a resolver given above\n * (`ImageResolverProvider`), no image an agent wrote is loaded. Not used for a person's own attachments (`ChatAttachment.preview`).\n */\n resolveImage?: ImageResolver;\n}\n\n/** Pictures and files a person attached to their message, as chips with a thumbnail where there is one. */\nfunction AttachedChips({ attachments }: { attachments: ChatAttachment[] }) {\n return (\n <ul className=\"sf-chat-references sf-chat-attachments\" aria-label=\"Attached files\">\n {attachments.map((one) => {\n // The preview is the host's own (a blob it made from the file), never an address a model wrote.\n const picture = one.mediaType.startsWith(\"image/\") ? safeImageAddress(one.preview) : undefined;\n return (\n <li key={one.id ?? one.name} className=\"sf-chat-reference\" data-kind=\"attachment\" data-thumbnail={picture ? true : undefined}>\n {picture ? <img className=\"sf-chat-thumbnail\" src={picture} alt=\"\" loading=\"lazy\" decoding=\"async\" /> : null}\n <span>{one.name}</span>\n </li>\n );\n })}\n </ul>\n );\n}\n\n/** What an agent is doing while its reply is on its way, in words, from the reply's parts so far. */\nexport function workingWords(message: ChatMessage): string {\n const last = message.parts.at(-1);\n if (!last) return \"Waiting for the agent to start…\";\n if (last.kind === \"steps\") {\n const running = last.steps.findLast((s) => s.status === \"running\");\n if (running) return running.title ? /[.…]$/.test(running.title) ? running.title : `${running.title}…` : \"Running a step…\";\n return last.steps.at(-1)?.status === \"failed\" ? \"A step failed. Working out what to do instead…\" : \"Deciding what to do with what it found…\";\n }\n if (last.kind === \"text\") return \"Writing its answer…\";\n if (last.kind === \"surface\") return \"Drawing…\";\n return \"Working…\";\n}\n\nfunction MessageView({ message, thread, catalog, renderers, onAction, onAnswer, onReport, onProblem, onContext, onPartAction }: MessageListProps & { message: ChatMessage }) {\n if (message.role === \"user\") {\n return (\n <article className=\"sf-chat-message\" data-role=\"user\">\n <span className=\"sf-a2-visually-hidden\">You said:</span>\n <p>{message.parts.map((p) => (p.kind === \"text\" ? p.text : \"\")).join(\"\")}</p>\n {message.parts.map((p, i) =>\n p.kind === \"references\" ? (\n // biome-ignore lint/suspicious/noArrayIndexKey: a message's parts do not move.\n <ul key={i} className=\"sf-chat-references\" aria-label=\"Attached\">\n {p.references.map((ref) => (\n <li key={`${ref.sourceId}/${dataRefLabel(ref)}`} className=\"sf-chat-reference\" data-kind={ref.kind}>\n {dataRefLabel(ref)}\n </li>\n ))}\n </ul>\n ) : p.kind === \"attachments\" ? (\n // biome-ignore lint/suspicious/noArrayIndexKey: a message's parts do not move.\n <AttachedChips key={i} attachments={p.attachments} />\n ) : null,\n )}\n </article>\n );\n }\n return (\n <article className=\"sf-chat-message\" data-role=\"assistant\" aria-busy={message.streaming}>\n <span className=\"sf-a2-visually-hidden\">The agent replied:</span>\n {message.parts.map((part, index) => {\n switch (part.kind) {\n case \"text\":\n return <Markdown key={index} text={part.text} />;\n case \"steps\":\n return <ToolSteps key={index} steps={part.steps} />;\n case \"surface\": {\n const surface = thread.surfaces[part.surfaceId];\n // Agent-drawn components are checked against the catalog before they are drawn.\n const key = part.surfaceId;\n return surface ? (\n <SurfaceView\n key={index}\n surface={surface}\n catalog={catalog}\n renderers={renderers}\n onAction={onAction}\n onDataChange={(data) => onReport?.(key, { data })}\n onControlsChange={(componentId, controls) => onReport?.(key, { componentId, controls })}\n onContext={(componentId, note) => {\n onReport?.(key, { componentId, note });\n onContext?.({ ...note, surfaceId: key, componentId });\n }}\n onProblem={(problem) => onProblem?.(key, problem)}\n className=\"sf-chat-surface\"\n />\n ) : null;\n }\n case \"approval\":\n return <ApprovalCard key={index} approval={part.approval} onAnswer={onAnswer} />;\n case \"actions\":\n return <ActionsCard key={index} actions={part.actions} onPress={(actionId, choiceId) => onPartAction?.(part.actions.id, actionId, choiceId)} />;\n case \"references\":\n case \"attachments\":\n // Attachments belong to what a person sent; a reply has none.\n return null;\n default:\n return (\n <p key={index} className=\"sf-chat-error\" role=\"alert\">\n {part.code === \"CANCELLED\" ? \"Stopped.\" : part.message}\n </p>\n );\n }\n })}\n {message.streaming && <WorkingLine className=\"sf-chat-thinking\" label={message.progress || workingWords(message)} seed={String(message.id)} announce={false} />}\n {!message.streaming && message.generatedBy && <p className=\"sf-chat-by\">Answered by {message.generatedBy}</p>}\n </article>\n );\n}\n\n/**\n * The conversation so far. Replies can hold text, tool steps, approvals and\n * components the agent drew. The list follows new content while the reader\n * is at the bottom and stays put when they have scrolled up.\n */\nexport function MessageList(props: MessageListProps) {\n const { thread } = props;\n const list = useRef<HTMLDivElement>(null);\n const pinned = useRef(true);\n useEffect(() => {\n const element = list.current;\n if (element && pinned.current) element.scrollTop = element.scrollHeight;\n }, [thread]);\n const list_ = (\n <div\n ref={list}\n className=\"sf-chat-list\"\n role=\"log\"\n aria-label=\"Conversation\"\n aria-live=\"polite\"\n tabIndex={0}\n onScroll={(event) => {\n const element = event.currentTarget;\n pinned.current = element.scrollHeight - element.scrollTop - element.clientHeight < 48;\n }}\n >\n {thread.messages.length === 0 && props.empty && <div className=\"sf-chat-empty\">{props.empty}</div>}\n {thread.messages.map((message) => (\n <MessageView key={message.id} {...props} message={message} />\n ))}\n </div>\n );\n return props.resolveImage ? <ImageResolverProvider resolve={props.resolveImage}>{list_}</ImageResolverProvider> : list_;\n}\n\nexport interface SuggestionsProps {\n items: string[];\n onPick(text: string): void;\n}\n\n/** Things the person might say next, one press each. */\nexport function Suggestions({ items, onPick }: SuggestionsProps) {\n if (items.length === 0) return null;\n return (\n <div className=\"sf-chat-suggestions\" role=\"group\" aria-label=\"Suggestions\">\n {items.map((item) => (\n <button key={item} type=\"button\" className=\"sf-button\" onClick={() => onPick(item)}>\n {item}\n </button>\n ))}\n </div>\n );\n}\n\n/**\n * How full the agent's context is, and what the conversation has cost when\n * known. With `empty`, those words are shown while the context is not known;\n * without it nothing is.\n */\nexport function UsageGauge({ usage, empty }: { usage: ChatUsage | undefined; empty?: string }) {\n if (!usage || usage.contextLimit <= 0) return empty ? <p className=\"sf-chat-usage\">{empty}</p> : null;\n const share = Math.min(1, usage.contextTokens / usage.contextLimit);\n return (\n <p className=\"sf-chat-usage\">\n <meter min={0} max={1} high={0.8} value={share} aria-label=\"Context used\" />\n <span>\n {Math.round(share * 100)}% of context used\n {usage.costUsd !== undefined ? ` · $${usage.costUsd.toFixed(2)}` : \"\"}\n </span>\n </p>\n );\n}\n\nexport interface ChatProps {\n /** Any agent runtime behind the AgentBackend interface. */\n agent: AgentBackend;\n /** The catalog agent-drawn components are checked against. Defaults to the analytics catalog. */\n catalog?: Catalog;\n renderers?: Record<string, ComponentRenderer>;\n agentId?: string;\n /** Limit the agent to the data in this saved context pack. */\n contextPackId?: string;\n /** Who is using the chat, from the host's sign-in; recorded on approval answers and surface events. */\n user?: ChatActor;\n /** Where to keep the conversation across reloads (`browserStorage()` from `@surfaces-ui/state`, or your own). */\n storage?: UseChatOptions[\"storage\"];\n storageKey?: string;\n /** Tables and columns attached to the message being written, when the host holds them (see `Composer`). */\n references?: DataRef[];\n onReferencesChange?(references: DataRef[]): void;\n /** The thread to open with: a saved or written conversation. Read once. */\n initialThread?: ChatThread;\n /** Told the thread after every change, so a host can save it or build from what was drawn. */\n onThreadChange?(thread: ChatThread): void;\n /**\n * Told what a person does in a drawn component as they do it (a view\n * added, a field changed, a filter set). The chat already keeps these and\n * gives them to the agent with its next turn; this is for a host that\n * wants them too.\n */\n onContext?: MessageListProps[\"onContext\"];\n /** Offered before the first message. */\n starters?: string[];\n placeholder?: string;\n /** How an image an agent named is drawn; see `MessageListProps.resolveImage`. */\n resolveImage?: ImageResolver;\n /** Turns files a person drops, pastes or picks into data or attachments; see `ComposerProps.attachFiles`. Without it there is no upload. */\n attachFiles?(files: File[]): Promise<AttachResult[]>;\n /** What the file picker offers; see `ComposerProps.accept`. */\n accept?: string;\n /** Widens the drop target beyond the composer; see `ComposerProps.dropTarget`. */\n dropTarget?: ComposerProps[\"dropTarget\"];\n /** Hands files in from outside; see `ComposerProps.handleRef`. */\n composerRef?: Ref<ComposerHandle>;\n /** The agent, model, skills and connectors a person chose, sent with each turn; with `onSettingsChange` the composer offers them. */\n settings?: ChatSettings;\n onSettingsChange?(settings: ChatSettings): void;\n /** What the agent offers (`DescribeAgents`), for the composer's menus. */\n agents?: AgentInfo[];\n /** Where models run, when the host can reach several: the Model menu groups models by provider. */\n providers?: ChatProvider[];\n onManageProviders?(): void;\n /** Shown when the thread is empty. */\n empty?: string;\n /** Height of the whole chat. A number is px. Defaults to 640. */\n height?: number | string;\n className?: string;\n}\n\n/**\n * A complete chat: the conversation, suggestions and the composer. Agent\n * replies stream in as Markdown, with tool steps, approvals and any catalog\n * component (charts, tables, pivots, model diagrams, decision cards) drawn\n * inline. Data components need a DataSourceProvider above the chat.\n */\nexport function Chat(props: ChatProps) {\n const catalog = props.catalog ?? analyticsCatalog;\n const renderers = props.renderers ?? lazyAnalyticsRenderers;\n const chat = useChat(props.agent, { catalog, agentId: props.agentId, contextPackId: props.contextPackId, user: props.user, storage: props.storage, storageKey: props.storageKey, initial: props.initialThread, settings: props.settings });\n const { thread } = chat;\n // Told on a change of thread only: a host passing a new function each render must not be told again (and set state in a loop).\n const onThreadChange = useRef(props.onThreadChange);\n onThreadChange.current = props.onThreadChange;\n useEffect(() => onThreadChange.current?.(thread), [thread]);\n const suggestions = thread.messages.length === 0 ? (props.starters ?? []) : thread.status === \"idle\" ? thread.suggestions : [];\n return (\n <section className={[\"sf-chat\", props.className].filter(Boolean).join(\" \")} style={{ height: props.height ?? 640 }} aria-label=\"Chat\">\n <MessageList thread={thread} catalog={catalog} renderers={renderers} onAction={chat.act} onAnswer={chat.answer} onReport={chat.report} onProblem={chat.problem} onContext={props.onContext} empty={props.empty} resolveImage={props.resolveImage} />\n <Suggestions items={suggestions} onPick={(text) => chat.send(text)} />\n <Composer\n agents={props.agents}\n settings={props.settings}\n onSettingsChange={props.onSettingsChange}\n providers={props.providers}\n onManageProviders={props.onManageProviders}\n references={props.references}\n onReferencesChange={props.onReferencesChange}\n attachFiles={props.attachFiles}\n accept={props.accept}\n dropTarget={props.dropTarget}\n handleRef={props.composerRef}\n onSend={chat.send} onStop={chat.stop} streaming={thread.status === \"streaming\"} placeholder={thread.status === \"waiting\" ? \"Answer above, or type to say something else\" : props.placeholder} />\n <UsageGauge usage={thread.usage} />\n </section>\n );\n}\n"]}
@@ -37,7 +37,10 @@ export function usePageStudio(agent, initial, catalog = analyticsCatalog) {
37
37
  const controller = useRef(undefined);
38
38
  const session = useRef("");
39
39
  const local = useRef({ controls: {}, activity: [] });
40
+ /** What was left out of the page since the agent was last told: an icon whose name does not exist. */
41
+ const problems = useRef([]);
40
42
  useEffect(() => {
43
+ problems.current = [];
41
44
  setChanges([]);
42
45
  session.current = "";
43
46
  local.current = { controls: {}, activity: [] };
@@ -65,7 +68,9 @@ export function usePageStudio(agent, initial, catalog = analyticsCatalog) {
65
68
  },
66
69
  ];
67
70
  local.current.activity = [];
68
- for await (const event of agent.send({ sessionId: session.current, input: { case: "text", value: studioPrompt(before, text) }, surfaces }, { signal: current.signal })) {
71
+ const surfaceErrors = problems.current;
72
+ problems.current = [];
73
+ for await (const event of agent.send({ sessionId: session.current, input: { case: "text", value: studioPrompt(before, text) }, surfaces, surfaceErrors }, { signal: current.signal })) {
69
74
  const part = event.event;
70
75
  if (part.case === "text")
71
76
  change.summary += part.value.delta;
@@ -79,9 +84,11 @@ export function usePageStudio(agent, initial, catalog = analyticsCatalog) {
79
84
  }
80
85
  }
81
86
  const edits = editsFromMessages(before, messages);
82
- const result = editPage(before, edits, catalog);
87
+ const result = editPage(before, edits, catalog, { leaveOut: true });
83
88
  change.applied = edits.length - result.rejected.length;
84
- change.rejected = result.rejected.map((r) => r.reason);
89
+ change.rejected = [...result.rejected, ...result.leftOut].map((r) => r.reason);
90
+ // Told with the next instruction, as a chat tells an agent of what it drew.
91
+ problems.current = result.leftOut.map(({ edit, reason }) => ({ surfaceId: before.id, code: "VALIDATION_FAILED", path: "id" in edit ? `/${edit.id}` : "component" in edit ? `/${edit.component.id}` : "/", message: `Left out: ${reason}` }));
85
92
  if (change.applied > 0)
86
93
  store.set(result.page);
87
94
  }
@@ -1 +1 @@
1
- {"version":3,"file":"PageStudio.js","sourceRoot":"","sources":["../src/PageStudio.tsx"],"names":[],"mappings":";AAEA,OAAO,EAAwD,gBAAgB,EAAE,QAAQ,EAAE,iBAAiB,EAAE,WAAW,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC9K,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,aAAa,EAA4C,WAAW,EAAE,sBAAsB,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AAC9K,OAAO,EAAc,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAC7D,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAChE,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAIjD,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAiB1E;;;GAGG;AACH,MAAM,UAAU,YAAY,CAAC,IAAkB,EAAE,WAAmB;IAClE,OAAO;QACL,gBAAgB,WAAW,EAAE;QAC7B,EAAE;QACF,oBAAoB,IAAI,CAAC,EAAE,8DAA8D,IAAI,CAAC,EAAE,IAAI;QACpG,uGAAuG;QACvG,uCAAuC;QACvC,EAAE;QACF,eAAe,IAAI,CAAC,KAAK,EAAE;QAC3B,eAAe;QACf,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,UAAU,CAAC;KAChC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACf,CAAC;AA6BD;;;;;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CAAC,IAAI,EAAE,OAAO,EAAE,GAAG,EAAE,CAAC,KAAK,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,YAC1H,OAAO,IADG,OAAO,CAEX,CACV,CAAC,GACE,CACP,EACD,cAAI,SAAS,EAAC,eAAe,gBAAY,SAAS,eAAW,QAAQ,aAClE,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,KAAK,EAAE,EAAE,CAAC,CACrC,6BAA6B,MAAM,CAAC,KAAK,IAAI,MAAM,CAAC,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,SAAS,aAChF,YAAG,SAAS,EAAC,uBAAuB,YAAE,MAAM,CAAC,WAAW,GAAK,EAC5D,CAAC,MAAM,CAAC,QAAQ,IAAI,sBAAI,MAAM,CAAC,KAAK,IAAI,CAAC,MAAM,CAAC,OAAO,IAAI,CAAC,MAAM,CAAC,OAAO,GAAG,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,sBAAsB,CAAC,CAAC,GAAK,EAC3H,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAC/B,aAAgB,SAAS,EAAC,oBAAoB,8BAC9B,MAAM,KADd,MAAM,CAEV,CACL,CAAC,EACD,MAAM,CAAC,WAAW,IAAI,YAAG,SAAS,EAAC,YAAY,YAAE,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,eAAe,MAAM,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,MAAM,MAAM,CAAC,WAAW,EAAE,GAAK,KARlI,KAAK,CAST,CACN,CAAC,EACD,MAAM,CAAC,IAAI,IAAI,aAAI,SAAS,EAAC,kBAAkB,8BAAc,IAC3D,IACC,IACJ,CACP,CAAC;AACJ,CAAC","sourcesContent":["import type { JsonObject } from \"@bufbuild/protobuf\";\nimport type { AgentBackend } from \"@surfaces-ui/agent\";\nimport { type Catalog, type PageDocument, type SurfaceMessage, analyticsCatalog, editPage, editsFromMessages, pageSurface, removeComponentMessages } from \"@surfaces-ui/spec\";\nimport { ArrangeGhost, ArrangeHelp, ArrangeToggle, type ComponentRenderer, type SurfaceNote, SurfaceView, lazyAnalyticsRenderers, useArrange } from \"@surfaces-ui/spec/react\";\nimport { type Store, createStore } from \"@surfaces-ui/state\";\nimport { useHistory, useStore } from \"@surfaces-ui/state/react\";\nimport { ChatComposer } from \"./ChatComposer.js\";\nimport type { ChatProvider } from \"./selectors.js\";\nimport type { ChatActor } from \"./thread.js\";\nimport type { ChatSettings } from \"./useChat.js\";\nimport { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\n\n/** What happened when one instruction was applied. */\nexport interface StudioChange {\n instruction: string;\n /** The agent's own words about what it did. */\n summary: string;\n /** The model or agent that made the change, or the person who arranged the page by hand. Always shown. */\n generatedBy: string;\n /** True when a person made the change by hand (arranging), not an agent. */\n byPerson?: boolean;\n applied: number;\n /** Changes the catalog refused, and why. */\n rejected: string[];\n error?: string;\n}\n\n/**\n * The text sent to the agent for one instruction: what the person asked, how\n * to answer, and the page as it is now.\n */\nexport function studioPrompt(page: PageDocument, instruction: string): string {\n return [\n `Instruction: ${instruction}`,\n \"\",\n `Change the page \"${page.id}\" by sending A2UI updateComponents messages for surfaceId \"${page.id}\".`,\n \"Send only the components you add or change. To remove one, send its container without it in children.\",\n \"Say in one sentence what you changed.\",\n \"\",\n `Page title: ${page.title}`,\n \"Current page:\",\n JSON.stringify(page.components),\n ].join(\"\\n\");\n}\n\nexport interface UsePageStudio {\n page: PageDocument;\n /** The store holding the page, for persistence or URL sync from `@surfaces-ui/state`. */\n store: Store<PageDocument>;\n changes: StudioChange[];\n busy: boolean;\n /** Sends an instruction to the agent and applies the edits it returns. */\n instruct(instruction: string): Promise<void>;\n /**\n * Applies a change a person made by hand, such as arranging, as A2UI\n * messages: one undo step, a line in the log by them, and a note the agent\n * reads with the next instruction.\n */\n arrange(messages: SurfaceMessage[], title: string, by?: string): void;\n stop(): void;\n undo(): void;\n redo(): void;\n canUndo: boolean;\n canRedo: boolean;\n /**\n * Records where the drawn page stands: what a person typed, or one\n * component's controls in catalog prop form. Sent with every instruction\n * (`SendRequest.surfaces`), so the agent edits the page as the person sees it.\n */\n report(state: { data?: unknown; componentId?: string; controls?: Record<string, unknown>; note?: SurfaceNote }): void;\n}\n\n/**\n * Lets an agent configure a page from plain-language instructions. The\n * agent answers with A2UI messages; they are turned into edits, each edit is\n * checked against the catalog, and only valid ones change the page. Every\n * instruction is one undo step.\n */\nexport function usePageStudio(agent: AgentBackend, initial: PageDocument, catalog: Catalog = analyticsCatalog): UsePageStudio {\n const store = useMemo(() => createStore(initial), [initial]);\n const page = useStore(store);\n const history = useHistory(store);\n const [changes, setChanges] = useState<StudioChange[]>([]);\n const [busy, setBusy] = useState(false);\n const controller = useRef<AbortController | undefined>(undefined);\n const session = useRef(\"\");\n const local = useRef<{ data?: unknown; controls: Record<string, Record<string, unknown>>; activity: { componentId: string; kind: string; summary: string; subject?: Record<string, unknown>; at: string }[] }>({ controls: {}, activity: [] });\n\n useEffect(() => {\n setChanges([]);\n session.current = \"\";\n local.current = { controls: {}, activity: [] };\n return () => controller.current?.abort();\n }, [store]);\n\n const instruct = useCallback(\n async (instruction: string) => {\n const text = instruction.trim();\n if (!text) return;\n controller.current?.abort();\n const current = new AbortController();\n controller.current = current;\n setBusy(true);\n const before = store.get();\n const messages: SurfaceMessage[] = [];\n const change: StudioChange = { instruction: text, summary: \"\", generatedBy: \"\", applied: 0, rejected: [] };\n try {\n const surfaces = [\n {\n surfaceId: before.id,\n dataModel: toJson(local.current.data ?? before.data ?? {}),\n controls: Object.fromEntries(Object.entries(local.current.controls).map(([id, c]) => [id, toJson(c)])),\n // What the person did on the page since the last instruction, told once.\n activity: local.current.activity.map((a) => ({ componentId: a.componentId, kind: a.kind, summary: a.summary, at: a.at, ...(a.subject ? { subject: toJson(a.subject) } : {}) })),\n },\n ];\n local.current.activity = [];\n for await (const event of agent.send({ sessionId: session.current, input: { case: \"text\", value: studioPrompt(before, text) }, surfaces }, { signal: current.signal })) {\n const part = event.event;\n if (part.case === \"text\") change.summary += part.value.delta;\n else if (part.case === \"surface\") messages.push(part.value as unknown as SurfaceMessage);\n else if (part.case === \"error\") change.error = part.value.message;\n else if (part.case === \"done\") {\n change.generatedBy = part.value.generatedBy;\n session.current = part.value.sessionId || session.current;\n }\n }\n const edits = editsFromMessages(before, messages);\n const result = editPage(before, edits, catalog);\n change.applied = edits.length - result.rejected.length;\n change.rejected = result.rejected.map((r) => r.reason);\n if (change.applied > 0) store.set(result.page);\n } catch (error) {\n change.error = error instanceof Error ? error.message : String(error);\n } finally {\n if (!current.signal.aborted) setChanges((previous) => [...previous, { ...change, summary: change.summary.trim() }]);\n if (controller.current === current) {\n controller.current = undefined;\n setBusy(false);\n }\n }\n },\n [agent, catalog, store],\n );\n const stop = useCallback(() => {\n controller.current?.abort();\n controller.current = undefined;\n setBusy(false);\n }, []);\n\n const arrange = useCallback<UsePageStudio[\"arrange\"]>(\n (messages, title, by = \"you\") => {\n const before = store.get();\n const edits = editsFromMessages(before, messages);\n const result = editPage(before, edits, catalog);\n const applied = edits.length - result.rejected.length;\n if (applied > 0) store.set(result.page);\n setChanges((previous) => [...previous, { instruction: title, summary: \"\", generatedBy: by, byPerson: true, applied, rejected: result.rejected.map((r) => r.reason) }]);\n if (applied === 0) return;\n // What changed, as the props that now say where things are: the same form an agent arranges with.\n const changed = edits.flatMap((edit) => (edit.op === \"set\" ? [edit.component] : []));\n const subject = Object.fromEntries(changed.map(({ id, children, widths, sizes, wrap, gap, padding, height, minHeight }) => [id, Object.fromEntries(Object.entries({ children, widths, sizes, wrap, gap, padding, height, minHeight }).filter(([, v]) => v !== undefined))]));\n local.current.activity = [...local.current.activity, { componentId: changed[0]?.id ?? \"root\", kind: \"layout.changed\", summary: `${title}.`, subject, at: new Date().toISOString() }].slice(-40);\n },\n [catalog, store],\n );\n\n const report = useCallback<UsePageStudio[\"report\"]>((state) => {\n if (state.data !== undefined) local.current.data = state.data;\n if (state.componentId && state.controls) local.current.controls[state.componentId] = state.controls;\n if (state.componentId && state.note) local.current.activity = [...local.current.activity, { componentId: state.componentId, ...state.note, at: new Date().toISOString() }].slice(-40);\n }, []);\n\n return { page, store, changes, busy, instruct, arrange, stop, undo: history.undo, redo: history.redo, canUndo: history.canUndo(), canRedo: history.canRedo(), report };\n}\n\nconst toJson = (value: unknown): JsonObject => {\n const plain = JSON.parse(JSON.stringify(value ?? {}, (_, v) => (typeof v === \"bigint\" ? String(v) : v))) as unknown;\n return plain && typeof plain === \"object\" && !Array.isArray(plain) ? (plain as JsonObject) : {};\n};\n\nexport interface PageStudioProps {\n agent: AgentBackend;\n /** The page to start from. A different document starts again. */\n page: PageDocument;\n catalog?: Catalog;\n renderers?: Record<string, ComponentRenderer>;\n /** Instructions offered as one-press examples. */\n starters?: string[];\n /** Called after each change with the page as it is now. */\n onChange?(page: PageDocument): void;\n /** Where models run, when the host can reach several: the box's Model menu groups models by provider. */\n providers?: ChatProvider[];\n settings?: ChatSettings;\n onSettingsChange?(settings: ChatSettings): void;\n onManageProviders?(): void;\n /**\n * Lets a person arrange the page by hand: move components, put two side by\n * side, and drag heights and widths. Off unless given. Each change is one\n * undo step, shows in the log by `user`, and is told to the agent.\n */\n arrange?: boolean;\n /**\n * With `arrange`: keeps the width handles between a Grid's or Row's columns,\n * and the height handle under a component with a height of its own (a chart or\n * a table, say) or one whose height is set, while nobody\n * is arranging. Each drag is one undo step, the same as in Arrange.\n */\n resizeWhileViewing?: boolean;\n /** Who is arranging, for the log. */\n user?: ChatActor;\n className?: string;\n}\n\n/**\n * A page with an instruction box beside it. A person says what they want\n * (\"add a chart of revenue by month\", \"remove the table\") and the agent\n * changes the page. Changes are listed with who made them, anything the\n * catalog refused, and can be undone.\n */\nexport function PageStudio(props: PageStudioProps) {\n const catalog = props.catalog ?? analyticsCatalog;\n const studio = usePageStudio(props.agent, props.page, catalog);\n const onChange = useRef(props.onChange);\n onChange.current = props.onChange;\n useEffect(() => onChange.current?.(studio.page), [studio.page]);\n const surface = useMemo(() => pageSurface(studio.page), [studio.page]);\n const by = props.user?.name ?? \"you\";\n const [arrangeStatus, setArrangeStatus] = useState<{ text: string; error?: boolean }>();\n const arrange = useArrange({\n surface,\n catalog,\n apply: (messages, title) => studio.arrange(messages, title, by),\n say: setArrangeStatus,\n remove: (id) => {\n const result = removeComponentMessages(surface, id);\n if (\"error\" in result) setArrangeStatus({ text: result.error, error: true });\n else studio.arrange(result.messages, `Removed \"${id}\"`, by);\n },\n resizeWhileViewing: props.resizeWhileViewing === true,\n });\n const frame = props.arrange === true ? arrange.surfaceFrame : undefined;\n\n return (\n <div className={[\"sf-studio\", props.className].filter(Boolean).join(\" \")}>\n <section className=\"sf-studio-page\" aria-label={studio.page.title} aria-busy={studio.busy}>\n <h3 className=\"sf-studio-title\">{studio.page.title}</h3>\n {studio.page.description && <p className=\"sf-object-muted\">{studio.page.description}</p>}\n {props.arrange && <ArrangeHelp arrange={arrange} status={arrangeStatus} />}\n <div {...(props.arrange ? arrange.region : {})}>\n <SurfaceView\n surface={props.arrange ? arrange.shown(surface) : surface}\n catalog={catalog}\n renderers={props.renderers ?? lazyAnalyticsRenderers}\n onDataChange={(data) => studio.report({ data })}\n onControlsChange={(componentId, controls) => studio.report({ componentId, controls })}\n onContext={(componentId, note) => studio.report({ componentId, note })}\n {...(frame ? { frame } : {})}\n />\n </div>\n {props.arrange && <ArrangeGhost arrange={arrange} />}\n </section>\n\n <aside className=\"sf-studio-side\" aria-label=\"Change this page\">\n <div className=\"sf-studio-form\">\n <ChatComposer\n label=\"Describe a change\"\n placeholder=\"Add a line chart of revenue by month\"\n onSend={(text) => void studio.instruct(text)}\n onStop={studio.stop}\n streaming={studio.busy}\n agents={[]}\n providers={props.providers}\n settings={props.settings}\n onSettingsChange={props.onSettingsChange}\n onManageProviders={props.onManageProviders}\n />\n <div className=\"sf-object-buttons\">\n <button type=\"button\" className=\"sf-button\" disabled={!studio.canUndo || studio.busy} onClick={studio.undo}>\n Undo\n </button>\n <button type=\"button\" className=\"sf-button\" disabled={!studio.canRedo || studio.busy} onClick={studio.redo}>\n Redo\n </button>\n {props.arrange && <ArrangeToggle arrange={arrange} />}\n </div>\n </div>\n {props.starters && props.starters.length > 0 && (\n <div className=\"sf-chat-suggestions\" role=\"group\" aria-label=\"Examples\">\n {props.starters.map((starter) => (\n <button key={starter} type=\"button\" className=\"sf-button\" disabled={studio.busy} onClick={() => void studio.instruct(starter)}>\n {starter}\n </button>\n ))}\n </div>\n )}\n <ol className=\"sf-studio-log\" aria-label=\"Changes\" aria-live=\"polite\">\n {studio.changes.map((change, index) => (\n <li key={index} data-failed={change.error || change.applied === 0 ? \"\" : undefined}>\n <p className=\"sf-studio-instruction\">{change.instruction}</p>\n {!change.byPerson && <p>{change.error ?? (change.summary || (change.applied > 0 ? \"Changed.\" : \"Nothing was changed.\"))}</p>}\n {change.rejected.map((reason) => (\n <p key={reason} className=\"sf-studio-rejected\">\n Not applied: {reason}\n </p>\n ))}\n {change.generatedBy && <p className=\"sf-chat-by\">{change.byPerson ? `Arranged by ${change.generatedBy}` : `By ${change.generatedBy}`}</p>}\n </li>\n ))}\n {studio.busy && <li className=\"sf-chat-thinking\">Working…</li>}\n </ol>\n </aside>\n </div>\n );\n}\n"]}
1
+ {"version":3,"file":"PageStudio.js","sourceRoot":"","sources":["../src/PageStudio.tsx"],"names":[],"mappings":";AAEA,OAAO,EAAwD,gBAAgB,EAAE,QAAQ,EAAE,iBAAiB,EAAE,WAAW,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC9K,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,aAAa,EAA4C,WAAW,EAAE,sBAAsB,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AAC9K,OAAO,EAAc,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAC7D,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,0BAA0B,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sonObject } from \"@bufbuild/protobuf\";\nimport type { AgentBackend, SendInit } from \"@surfaces-ui/agent\";\nimport { type Catalog, type PageDocument, type SurfaceMessage, analyticsCatalog, editPage, editsFromMessages, pageSurface, removeComponentMessages } from \"@surfaces-ui/spec\";\nimport { ArrangeGhost, ArrangeHelp, ArrangeToggle, type ComponentRenderer, type SurfaceNote, SurfaceView, lazyAnalyticsRenderers, useArrange } from \"@surfaces-ui/spec/react\";\nimport { type Store, createStore } from \"@surfaces-ui/state\";\nimport { useHistory, useStore } from \"@surfaces-ui/state/react\";\nimport { ChatComposer } from \"./ChatComposer.js\";\nimport type { ChatProvider } from \"./selectors.js\";\nimport type { ChatActor } from \"./thread.js\";\nimport type { ChatSettings } from \"./useChat.js\";\nimport { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\n\n/** What happened when one instruction was applied. */\nexport interface StudioChange {\n instruction: string;\n /** The agent's own words about what it did. */\n summary: string;\n /** The model or agent that made the change, or the person who arranged the page by hand. Always shown. */\n generatedBy: string;\n /** True when a person made the change by hand (arranging), not an agent. */\n byPerson?: boolean;\n applied: number;\n /** Changes the catalog refused, and why. */\n rejected: string[];\n error?: string;\n}\n\n/**\n * The text sent to the agent for one instruction: what the person asked, how\n * to answer, and the page as it is now.\n */\nexport function studioPrompt(page: PageDocument, instruction: string): string {\n return [\n `Instruction: ${instruction}`,\n \"\",\n `Change the page \"${page.id}\" by sending A2UI updateComponents messages for surfaceId \"${page.id}\".`,\n \"Send only the components you add or change. To remove one, send its container without it in children.\",\n \"Say in one sentence what you changed.\",\n \"\",\n `Page title: ${page.title}`,\n \"Current page:\",\n JSON.stringify(page.components),\n ].join(\"\\n\");\n}\n\nexport interface UsePageStudio {\n page: PageDocument;\n /** The store holding the page, for persistence or URL sync from `@surfaces-ui/state`. */\n store: Store<PageDocument>;\n changes: StudioChange[];\n busy: boolean;\n /** Sends an instruction to the agent and applies the edits it returns. */\n instruct(instruction: string): Promise<void>;\n /**\n * Applies a change a person made by hand, such as arranging, as A2UI\n * messages: one undo step, a line in the log by them, and a note the agent\n * reads with the next instruction.\n */\n arrange(messages: SurfaceMessage[], title: string, by?: string): void;\n stop(): void;\n undo(): void;\n redo(): void;\n canUndo: boolean;\n canRedo: boolean;\n /**\n * Records where the drawn page stands: what a person typed, or one\n * component's controls in catalog prop form. Sent with every instruction\n * (`SendRequest.surfaces`), so the agent edits the page as the person sees it.\n */\n report(state: { data?: unknown; componentId?: string; controls?: Record<string, unknown>; note?: SurfaceNote }): void;\n}\n\n/**\n * Lets an agent configure a page from plain-language instructions. The\n * agent answers with A2UI messages; they are turned into edits, each edit is\n * checked against the catalog, and only valid ones change the page. Every\n * instruction is one undo step.\n */\nexport function usePageStudio(agent: AgentBackend, initial: PageDocument, catalog: Catalog = analyticsCatalog): UsePageStudio {\n const store = useMemo(() => createStore(initial), [initial]);\n const page = useStore(store);\n const history = useHistory(store);\n const [changes, setChanges] = useState<StudioChange[]>([]);\n const [busy, setBusy] = useState(false);\n const controller = useRef<AbortController | undefined>(undefined);\n const session = useRef(\"\");\n const local = useRef<{ data?: unknown; controls: Record<string, Record<string, unknown>>; activity: { componentId: string; kind: string; summary: string; subject?: Record<string, unknown>; at: string }[] }>({ controls: {}, activity: [] });\n\n /** What was left out of the page since the agent was last told: an icon whose name does not exist. */\n const problems = useRef<NonNullable<SendInit[\"surfaceErrors\"]>>([]);\n\n useEffect(() => {\n problems.current = [];\n setChanges([]);\n session.current = \"\";\n local.current = { controls: {}, activity: [] };\n return () => controller.current?.abort();\n }, [store]);\n\n const instruct = useCallback(\n async (instruction: string) => {\n const text = instruction.trim();\n if (!text) return;\n controller.current?.abort();\n const current = new AbortController();\n controller.current = current;\n setBusy(true);\n const before = store.get();\n const messages: SurfaceMessage[] = [];\n const change: StudioChange = { instruction: text, summary: \"\", generatedBy: \"\", applied: 0, rejected: [] };\n try {\n const surfaces = [\n {\n surfaceId: before.id,\n dataModel: toJson(local.current.data ?? before.data ?? {}),\n controls: Object.fromEntries(Object.entries(local.current.controls).map(([id, c]) => [id, toJson(c)])),\n // What the person did on the page since the last instruction, told once.\n activity: local.current.activity.map((a) => ({ componentId: a.componentId, kind: a.kind, summary: a.summary, at: a.at, ...(a.subject ? { subject: toJson(a.subject) } : {}) })),\n },\n ];\n local.current.activity = [];\n const surfaceErrors = problems.current;\n problems.current = [];\n for await (const event of agent.send({ sessionId: session.current, input: { case: \"text\", value: studioPrompt(before, text) }, surfaces, surfaceErrors }, { signal: current.signal })) {\n const part = event.event;\n if (part.case === \"text\") change.summary += part.value.delta;\n else if (part.case === \"surface\") messages.push(part.value as unknown as SurfaceMessage);\n else if (part.case === \"error\") change.error = part.value.message;\n else if (part.case === \"done\") {\n change.generatedBy = part.value.generatedBy;\n session.current = part.value.sessionId || session.current;\n }\n }\n const edits = editsFromMessages(before, messages);\n const result = editPage(before, edits, catalog, { leaveOut: true });\n change.applied = edits.length - result.rejected.length;\n change.rejected = [...result.rejected, ...result.leftOut].map((r) => r.reason);\n // Told with the next instruction, as a chat tells an agent of what it drew.\n problems.current = result.leftOut.map(({ edit, reason }) => ({ surfaceId: before.id, code: \"VALIDATION_FAILED\", path: \"id\" in edit ? `/${edit.id}` : \"component\" in edit ? `/${edit.component.id}` : \"/\", message: `Left out: ${reason}` }));\n if (change.applied > 0) store.set(result.page);\n } catch (error) {\n change.error = error instanceof Error ? error.message : String(error);\n } finally {\n if (!current.signal.aborted) setChanges((previous) => [...previous, { ...change, summary: change.summary.trim() }]);\n if (controller.current === current) {\n controller.current = undefined;\n setBusy(false);\n }\n }\n },\n [agent, catalog, store],\n );\n const stop = useCallback(() => {\n controller.current?.abort();\n controller.current = undefined;\n setBusy(false);\n }, []);\n\n const arrange = useCallback<UsePageStudio[\"arrange\"]>(\n (messages, title, by = \"you\") => {\n const before = store.get();\n const edits = editsFromMessages(before, messages);\n const result = editPage(before, edits, catalog);\n const applied = edits.length - result.rejected.length;\n if (applied > 0) store.set(result.page);\n setChanges((previous) => [...previous, { instruction: title, summary: \"\", generatedBy: by, byPerson: true, applied, rejected: result.rejected.map((r) => r.reason) }]);\n if (applied === 0) return;\n // What changed, as the props that now say where things are: the same form an agent arranges with.\n const changed = edits.flatMap((edit) => (edit.op === \"set\" ? [edit.component] : []));\n const subject = Object.fromEntries(changed.map(({ id, children, widths, sizes, wrap, gap, padding, height, minHeight }) => [id, Object.fromEntries(Object.entries({ children, widths, sizes, wrap, gap, padding, height, minHeight }).filter(([, v]) => v !== undefined))]));\n local.current.activity = [...local.current.activity, { componentId: changed[0]?.id ?? \"root\", kind: \"layout.changed\", summary: `${title}.`, subject, at: new Date().toISOString() }].slice(-40);\n },\n [catalog, store],\n );\n\n const report = useCallback<UsePageStudio[\"report\"]>((state) => {\n if (state.data !== undefined) local.current.data = state.data;\n if (state.componentId && state.controls) local.current.controls[state.componentId] = state.controls;\n if (state.componentId && state.note) local.current.activity = [...local.current.activity, { componentId: state.componentId, ...state.note, at: new Date().toISOString() }].slice(-40);\n }, []);\n\n return { page, store, changes, busy, instruct, arrange, stop, undo: history.undo, redo: history.redo, canUndo: history.canUndo(), canRedo: history.canRedo(), report };\n}\n\nconst toJson = (value: unknown): JsonObject => {\n const plain = JSON.parse(JSON.stringify(value ?? {}, (_, v) => (typeof v === \"bigint\" ? String(v) : v))) as unknown;\n return plain && typeof plain === \"object\" && !Array.isArray(plain) ? (plain as JsonObject) : {};\n};\n\nexport interface PageStudioProps {\n agent: AgentBackend;\n /** The page to start from. A different document starts again. */\n page: PageDocument;\n catalog?: Catalog;\n renderers?: Record<string, ComponentRenderer>;\n /** Instructions offered as one-press examples. */\n starters?: string[];\n /** Called after each change with the page as it is now. */\n onChange?(page: PageDocument): void;\n /** Where models run, when the host can reach several: the box's Model menu groups models by provider. */\n providers?: ChatProvider[];\n settings?: ChatSettings;\n onSettingsChange?(settings: ChatSettings): void;\n onManageProviders?(): void;\n /**\n * Lets a person arrange the page by hand: move components, put two side by\n * side, and drag heights and widths. Off unless given. Each change is one\n * undo step, shows in the log by `user`, and is told to the agent.\n */\n arrange?: boolean;\n /**\n * With `arrange`: keeps the width handles between a Grid's or Row's columns,\n * and the height handle under a component with a height of its own (a chart or\n * a table, say) or one whose height is set, while nobody\n * is arranging. Each drag is one undo step, the same as in Arrange.\n */\n resizeWhileViewing?: boolean;\n /** Who is arranging, for the log. */\n user?: ChatActor;\n className?: string;\n}\n\n/**\n * A page with an instruction box beside it. A person says what they want\n * (\"add a chart of revenue by month\", \"remove the table\") and the agent\n * changes the page. Changes are listed with who made them, anything the\n * catalog refused, and can be undone.\n */\nexport function PageStudio(props: PageStudioProps) {\n const catalog = props.catalog ?? analyticsCatalog;\n const studio = usePageStudio(props.agent, props.page, catalog);\n const onChange = useRef(props.onChange);\n onChange.current = props.onChange;\n useEffect(() => onChange.current?.(studio.page), [studio.page]);\n const surface = useMemo(() => pageSurface(studio.page), [studio.page]);\n const by = props.user?.name ?? \"you\";\n const [arrangeStatus, setArrangeStatus] = useState<{ text: string; error?: boolean }>();\n const arrange = useArrange({\n surface,\n catalog,\n apply: (messages, title) => studio.arrange(messages, title, by),\n say: setArrangeStatus,\n remove: (id) => {\n const result = removeComponentMessages(surface, id);\n if (\"error\" in result) setArrangeStatus({ text: result.error, error: true });\n else studio.arrange(result.messages, `Removed \"${id}\"`, by);\n },\n resizeWhileViewing: props.resizeWhileViewing === true,\n });\n const frame = props.arrange === true ? arrange.surfaceFrame : undefined;\n\n return (\n <div className={[\"sf-studio\", props.className].filter(Boolean).join(\" \")}>\n <section className=\"sf-studio-page\" aria-label={studio.page.title} aria-busy={studio.busy}>\n <h3 className=\"sf-studio-title\">{studio.page.title}</h3>\n {studio.page.description && <p className=\"sf-object-muted\">{studio.page.description}</p>}\n {props.arrange && <ArrangeHelp arrange={arrange} status={arrangeStatus} />}\n <div {...(props.arrange ? arrange.region : {})}>\n <SurfaceView\n surface={props.arrange ? arrange.shown(surface) : surface}\n catalog={catalog}\n renderers={props.renderers ?? lazyAnalyticsRenderers}\n onDataChange={(data) => studio.report({ data })}\n onControlsChange={(componentId, controls) => studio.report({ componentId, controls })}\n onContext={(componentId, note) => studio.report({ componentId, note })}\n {...(frame ? { frame } : {})}\n />\n </div>\n {props.arrange && <ArrangeGhost arrange={arrange} />}\n </section>\n\n <aside className=\"sf-studio-side\" aria-label=\"Change this page\">\n <div className=\"sf-studio-form\">\n <ChatComposer\n label=\"Describe a change\"\n placeholder=\"Add a line chart of revenue by month\"\n onSend={(text) => void studio.instruct(text)}\n onStop={studio.stop}\n streaming={studio.busy}\n agents={[]}\n providers={props.providers}\n settings={props.settings}\n onSettingsChange={props.onSettingsChange}\n onManageProviders={props.onManageProviders}\n />\n <div className=\"sf-object-buttons\">\n <button type=\"button\" className=\"sf-button\" disabled={!studio.canUndo || studio.busy} onClick={studio.undo}>\n Undo\n </button>\n <button type=\"button\" className=\"sf-button\" disabled={!studio.canRedo || studio.busy} onClick={studio.redo}>\n Redo\n </button>\n {props.arrange && <ArrangeToggle arrange={arrange} />}\n </div>\n </div>\n {props.starters && props.starters.length > 0 && (\n <div className=\"sf-chat-suggestions\" role=\"group\" aria-label=\"Examples\">\n {props.starters.map((starter) => (\n <button key={starter} type=\"button\" className=\"sf-button\" disabled={studio.busy} onClick={() => void studio.instruct(starter)}>\n {starter}\n </button>\n ))}\n </div>\n )}\n <ol className=\"sf-studio-log\" aria-label=\"Changes\" aria-live=\"polite\">\n {studio.changes.map((change, index) => (\n <li key={index} data-failed={change.error || change.applied === 0 ? \"\" : undefined}>\n <p className=\"sf-studio-instruction\">{change.instruction}</p>\n {!change.byPerson && <p>{change.error ?? (change.summary || (change.applied > 0 ? \"Changed.\" : \"Nothing was changed.\"))}</p>}\n {change.rejected.map((reason) => (\n <p key={reason} className=\"sf-studio-rejected\">\n Not applied: {reason}\n </p>\n ))}\n {change.generatedBy && <p className=\"sf-chat-by\">{change.byPerson ? `Arranged by ${change.generatedBy}` : `By ${change.generatedBy}`}</p>}\n </li>\n ))}\n {studio.busy && <li className=\"sf-chat-thinking\">Working…</li>}\n </ol>\n </aside>\n </div>\n );\n}\n"]}
package/dist/icons.d.ts CHANGED
@@ -1,6 +1,7 @@
1
+ import { type IconDrawing } from "@surfaces-ui/icons";
1
2
  /** Small outline icons for the chat's controls, drawn in the text colour at the text's size. */
2
3
  declare const PATHS: {
3
- readonly plus: "M12 5v14 M5 12h14";
4
+ readonly plus: IconDrawing;
4
5
  readonly send: "M12 19V5 M6 11l6-6 6 6";
5
6
  readonly stop: "M7 7h10v10H7z";
6
7
  readonly mic: "M12 4a3 3 0 0 0-3 3v5a3 3 0 0 0 6 0V7a3 3 0 0 0-3-3z M6 11a6 6 0 0 0 12 0 M12 17v3";
@@ -16,7 +17,7 @@ declare const PATHS: {
16
17
  readonly model: "M12 3l8 4.5v9L12 21l-8-4.5v-9z M12 12l8-4.5 M12 12v9 M12 12L4 7.5";
17
18
  readonly sessions: "M4 6h16 M4 12h16 M4 18h10";
18
19
  readonly chat: "M4 5h16v11H10l-5 4v-4H4z";
19
- readonly close: "M6 6l12 12 M18 6L6 18";
20
+ readonly close: IconDrawing;
20
21
  readonly check: "M5 12l5 5 9-10";
21
22
  readonly pin: "M9 4h6l-1 6 3 3H7l3-3z M12 13v7";
22
23
  readonly search: "M11 5a6 6 0 1 0 0 12 6 6 0 0 0 0-12z M20 20l-4.5-4.5";
package/dist/icons.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { addIcon, closeIcon, Icon, iconFrame } from "@surfaces-ui/icons";
2
3
  /** Small outline icons for the chat's controls, drawn in the text colour at the text's size. */
3
4
  const PATHS = {
4
- plus: "M12 5v14 M5 12h14",
5
+ plus: addIcon,
5
6
  send: "M12 19V5 M6 11l6-6 6 6",
6
7
  stop: "M7 7h10v10H7z",
7
8
  mic: "M12 4a3 3 0 0 0-3 3v5a3 3 0 0 0 6 0V7a3 3 0 0 0-3-3z M6 11a6 6 0 0 0 12 0 M12 17v3",
@@ -17,7 +18,7 @@ const PATHS = {
17
18
  model: "M12 3l8 4.5v9L12 21l-8-4.5v-9z M12 12l8-4.5 M12 12v9 M12 12L4 7.5",
18
19
  sessions: "M4 6h16 M4 12h16 M4 18h10",
19
20
  chat: "M4 5h16v11H10l-5 4v-4H4z",
20
- close: "M6 6l12 12 M18 6L6 18",
21
+ close: closeIcon,
21
22
  check: "M5 12l5 5 9-10",
22
23
  pin: "M9 4h6l-1 6 3 3H7l3-3z M12 13v7",
23
24
  search: "M11 5a6 6 0 1 0 0 12 6 6 0 0 0 0-12z M20 20l-4.5-4.5",
@@ -29,6 +30,9 @@ const PATHS = {
29
30
  /** Every name ChatIcon draws. */
30
31
  export const CHAT_ICONS = Object.keys(PATHS);
31
32
  export function ChatIcon({ name }) {
32
- return (_jsx("svg", { className: "sf-chat-icon", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "1.7", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", focusable: "false", children: _jsx("path", { d: PATHS[name] }) }));
33
+ const drawing = PATHS[name];
34
+ if (typeof drawing !== "string")
35
+ return _jsx(Icon, { icon: drawing, className: "sf-chat-icon", width: undefined, height: undefined });
36
+ return (_jsx("svg", { className: "sf-chat-icon", ...iconFrame, "aria-hidden": "true", children: _jsx("path", { d: drawing }) }));
33
37
  }
34
38
  //# sourceMappingURL=icons.js.map
package/dist/icons.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"icons.js","sourceRoot":"","sources":["../src/icons.tsx"],"names":[],"mappings":";AAAA,gGAAgG;AAChG,MAAM,KAAK,GAAG;IACZ,IAAI,EAAE,mBAAmB;IACzB,IAAI,EAAE,wBAAwB;IAC9B,IAAI,EAAE,eAAe;IACrB,GAAG,EAAE,oFAAoF;IACzF,IAAI,EAAE,2CAA2C;IACjD,OAAO,EAAE,eAAe;IACxB,IAAI,EAAE,eAAe;IACrB,IAAI,EAAE,gBAAgB;IACtB,IAAI,EAAE,yHAAyH;IAC/H,IAAI,EAAE,4BAA4B;IAClC,KAAK,EAAE,gEAAgE;IACvE,IAAI,EAAE,mDAAmD;IACzD,KAAK,EAAE,4CAA4C;IACnD,KAAK,EAAE,mEAAmE;IAC1E,QAAQ,EAAE,2BAA2B;IACrC,IAAI,EAAE,0BAA0B;IAChC,KAAK,EAAE,uBAAuB;IAC9B,KAAK,EAAE,gBAAgB;IACvB,GAAG,EAAE,iCAAiC;IACtC,MAAM,EAAE,sDAAsD;IAC9D,kFAAkF;IAClF,IAAI,EAAE,mJAAmJ;IACzJ,IAAI,EAAE,0DAA0D;IAChE,KAAK,EAAE,yEAAyE;CACxE,CAAC;AAGX,iCAAiC;AACjC,MAAM,CAAC,MAAM,UAAU,GAAG,MAAM,CAAC,IAAI,CAAC,KAAK,CAAmB,CAAC;AAE/D,MAAM,UAAU,QAAQ,CAAC,EAAE,IAAI,EAA0B;IACvD,OAAO,CACL,cAAK,SAAS,EAAC,cAAc,EAAC,OAAO,EAAC,WAAW,EAAC,IAAI,EAAC,MAAM,EAAC,MAAM,EAAC,cAAc,EAAC,WAAW,EAAC,KAAK,EAAC,aAAa,EAAC,OAAO,EAAC,cAAc,EAAC,OAAO,iBAAa,MAAM,EAAC,SAAS,EAAC,OAAO,YACrL,eAAM,CAAC,EAAE,KAAK,CAAC,IAAI,CAAC,GAAI,GACpB,CACP,CAAC;AACJ,CAAC","sourcesContent":["/** Small outline icons for the chat's controls, drawn in the text colour at the text's size. */\nconst PATHS = {\n plus: \"M12 5v14 M5 12h14\",\n send: \"M12 19V5 M6 11l6-6 6 6\",\n stop: \"M7 7h10v10H7z\",\n mic: \"M12 4a3 3 0 0 0-3 3v5a3 3 0 0 0 6 0V7a3 3 0 0 0-3-3z M6 11a6 6 0 0 0 12 0 M12 17v3\",\n talk: \"M4 12h2 M8 8v8 M12 5v14 M16 8v8 M20 12h-2\",\n chevron: \"M7 10l5 5 5-5\",\n next: \"M10 7l5 5-5 5\",\n back: \"M14 7l-5 5 5 5\",\n data: \"M5 6c0-1.7 3.1-3 7-3s7 1.3 7 3-3.1 3-7 3-7-1.3-7-3z M5 6v12c0 1.7 3.1 3 7 3s7-1.3 7-3V6 M5 12c0 1.7 3.1 3 7 3s7-1.3 7-3\",\n file: \"M6 3h8l4 4v14H6z M14 3v4h4\",\n skill: \"M5 5h9a3 3 0 0 1 3 3v12H8a3 3 0 0 1-3-3z M5 17a3 3 0 0 1 3-3h9\",\n plug: \"M9 3v5 M15 3v5 M7 8h10v3a5 5 0 0 1-10 0z M12 16v5\",\n agent: \"M4 7h9M17 7h3M4 17h3M11 17h9M15 5v4M9 15v4\",\n model: \"M12 3l8 4.5v9L12 21l-8-4.5v-9z M12 12l8-4.5 M12 12v9 M12 12L4 7.5\",\n sessions: \"M4 6h16 M4 12h16 M4 18h10\",\n chat: \"M4 5h16v11H10l-5 4v-4H4z\",\n close: \"M6 6l12 12 M18 6L6 18\",\n check: \"M5 12l5 5 9-10\",\n pin: \"M9 4h6l-1 6 3 3H7l3-3z M12 13v7\",\n search: \"M11 5a6 6 0 1 0 0 12 6 6 0 0 0 0-12z M20 20l-4.5-4.5\",\n // Three dots across, for an overflow menu: the drawing ItemControls' \"more\" uses.\n more: \"M4.8 12a1.2 1.2 0 1 0 2.4 0a1.2 1.2 0 1 0-2.4 0 M10.8 12a1.2 1.2 0 1 0 2.4 0a1.2 1.2 0 1 0-2.4 0 M16.8 12a1.2 1.2 0 1 0 2.4 0a1.2 1.2 0 1 0-2.4 0\",\n bell: \"M18 16v-5a6 6 0 0 0-12 0v5l-2 2h16z M10 21a2 2 0 0 0 4 0\",\n about: \"M12 4a8 8 0 1 0 0 16 8 8 0 0 0 0-16z M12 9a3 3 0 1 0 0 6 3 3 0 0 0 0-6z\",\n} as const;\n\nexport type ChatIconName = keyof typeof PATHS;\n/** Every name ChatIcon draws. */\nexport const CHAT_ICONS = Object.keys(PATHS) as ChatIconName[];\n\nexport function ChatIcon({ name }: { name: ChatIconName }) {\n return (\n <svg className=\"sf-chat-icon\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.7\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\" focusable=\"false\">\n <path d={PATHS[name]} />\n </svg>\n );\n}\n"]}
1
+ {"version":3,"file":"icons.js","sourceRoot":"","sources":["../src/icons.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAE,OAAO,EAAE,SAAS,EAAE,IAAI,EAAoB,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAE3F,gGAAgG;AAChG,MAAM,KAAK,GAAG;IACZ,IAAI,EAAE,OAAO;IACb,IAAI,EAAE,wBAAwB;IAC9B,IAAI,EAAE,eAAe;IACrB,GAAG,EAAE,oFAAoF;IACzF,IAAI,EAAE,2CAA2C;IACjD,OAAO,EAAE,eAAe;IACxB,IAAI,EAAE,eAAe;IACrB,IAAI,EAAE,gBAAgB;IACtB,IAAI,EAAE,yHAAyH;IAC/H,IAAI,EAAE,4BAA4B;IAClC,KAAK,EAAE,gEAAgE;IACvE,IAAI,EAAE,mDAAmD;IACzD,KAAK,EAAE,4CAA4C;IACnD,KAAK,EAAE,mEAAmE;IAC1E,QAAQ,EAAE,2BAA2B;IACrC,IAAI,EAAE,0BAA0B;IAChC,KAAK,EAAE,SAAS;IAChB,KAAK,EAAE,gBAAgB;IACvB,GAAG,EAAE,iCAAiC;IACtC,MAAM,EAAE,sDAAsD;IAC9D,kFAAkF;IAClF,IAAI,EAAE,mJAAmJ;IACzJ,IAAI,EAAE,0DAA0D;IAChE,KAAK,EAAE,yEAAyE;CACzB,CAAC;AAG1D,iCAAiC;AACjC,MAAM,CAAC,MAAM,UAAU,GAAG,MAAM,CAAC,IAAI,CAAC,KAAK,CAAmB,CAAC;AAE/D,MAAM,UAAU,QAAQ,CAAC,EAAE,IAAI,EAA0B;IACvD,MAAM,OAAO,GAAyB,KAAK,CAAC,IAAI,CAAC,CAAC;IAClD,IAAI,OAAO,OAAO,KAAK,QAAQ;QAAE,OAAO,KAAC,IAAI,IAAC,IAAI,EAAE,OAAO,EAAE,SAAS,EAAC,cAAc,EAAC,KAAK,EAAE,SAAS,EAAE,MAAM,EAAE,SAAS,GAAI,CAAC;IAC9H,OAAO,CACL,cAAK,SAAS,EAAC,cAAc,KAAK,SAAS,iBAAc,MAAM,YAC7D,eAAM,CAAC,EAAE,OAAO,GAAI,GAChB,CACP,CAAC;AACJ,CAAC","sourcesContent":["import { addIcon, closeIcon, Icon, type IconDrawing, iconFrame } from \"@surfaces-ui/icons\";\n\n/** Small outline icons for the chat's controls, drawn in the text colour at the text's size. */\nconst PATHS = {\n plus: addIcon,\n send: \"M12 19V5 M6 11l6-6 6 6\",\n stop: \"M7 7h10v10H7z\",\n mic: \"M12 4a3 3 0 0 0-3 3v5a3 3 0 0 0 6 0V7a3 3 0 0 0-3-3z M6 11a6 6 0 0 0 12 0 M12 17v3\",\n talk: \"M4 12h2 M8 8v8 M12 5v14 M16 8v8 M20 12h-2\",\n chevron: \"M7 10l5 5 5-5\",\n next: \"M10 7l5 5-5 5\",\n back: \"M14 7l-5 5 5 5\",\n data: \"M5 6c0-1.7 3.1-3 7-3s7 1.3 7 3-3.1 3-7 3-7-1.3-7-3z M5 6v12c0 1.7 3.1 3 7 3s7-1.3 7-3V6 M5 12c0 1.7 3.1 3 7 3s7-1.3 7-3\",\n file: \"M6 3h8l4 4v14H6z M14 3v4h4\",\n skill: \"M5 5h9a3 3 0 0 1 3 3v12H8a3 3 0 0 1-3-3z M5 17a3 3 0 0 1 3-3h9\",\n plug: \"M9 3v5 M15 3v5 M7 8h10v3a5 5 0 0 1-10 0z M12 16v5\",\n agent: \"M4 7h9M17 7h3M4 17h3M11 17h9M15 5v4M9 15v4\",\n model: \"M12 3l8 4.5v9L12 21l-8-4.5v-9z M12 12l8-4.5 M12 12v9 M12 12L4 7.5\",\n sessions: \"M4 6h16 M4 12h16 M4 18h10\",\n chat: \"M4 5h16v11H10l-5 4v-4H4z\",\n close: closeIcon,\n check: \"M5 12l5 5 9-10\",\n pin: \"M9 4h6l-1 6 3 3H7l3-3z M12 13v7\",\n search: \"M11 5a6 6 0 1 0 0 12 6 6 0 0 0 0-12z M20 20l-4.5-4.5\",\n // Three dots across, for an overflow menu: the drawing ItemControls' \"more\" uses.\n more: \"M4.8 12a1.2 1.2 0 1 0 2.4 0a1.2 1.2 0 1 0-2.4 0 M10.8 12a1.2 1.2 0 1 0 2.4 0a1.2 1.2 0 1 0-2.4 0 M16.8 12a1.2 1.2 0 1 0 2.4 0a1.2 1.2 0 1 0-2.4 0\",\n bell: \"M18 16v-5a6 6 0 0 0-12 0v5l-2 2h16z M10 21a2 2 0 0 0 4 0\",\n about: \"M12 4a8 8 0 1 0 0 16 8 8 0 0 0 0-16z M12 9a3 3 0 1 0 0 6 3 3 0 0 0 0-6z\",\n} as const satisfies Record<string, string | IconDrawing>;\n\nexport type ChatIconName = keyof typeof PATHS;\n/** Every name ChatIcon draws. */\nexport const CHAT_ICONS = Object.keys(PATHS) as ChatIconName[];\n\nexport function ChatIcon({ name }: { name: ChatIconName }) {\n const drawing: string | IconDrawing = PATHS[name];\n if (typeof drawing !== \"string\") return <Icon icon={drawing} className=\"sf-chat-icon\" width={undefined} height={undefined} />;\n return (\n <svg className=\"sf-chat-icon\" {...iconFrame} aria-hidden=\"true\">\n <path d={drawing} />\n </svg>\n );\n}\n"]}
package/dist/thread.d.ts CHANGED
@@ -160,6 +160,8 @@ export interface ChatMessage {
160
160
  /** The model or agent that answered. Always shown. */
161
161
  generatedBy: string;
162
162
  streaming: boolean;
163
+ /** What the agent is doing, in words, while the reply is on its way. Without it, the chat says so from the reply's own parts. */
164
+ progress?: string;
163
165
  }
164
166
  export interface ChatUsage {
165
167
  inputTokens: number;
@@ -1 +1 @@
1
- {"version":3,"file":"thread.js","sourceRoot":"","sources":["../src/thread.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,YAAY,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAC5E,OAAO,EAAoD,YAAY,EAAE,gBAAgB,EAAE,cAAc,EAAE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W,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC,EAAe,EAAE,CAAC,OAAO,CAAC,KAAK,QAAQ,CAAC,CAAC,CAAC,CAAC,EAAE;KACzH,CAAC;AACJ,CAAC","sourcesContent":["import type { AgentEvent } from \"@surfaces-ui/agent\";\nimport type { JsonObject } from \"@bufbuild/protobuf\";\nimport { ApprovalKind, ApprovalRisk, StepStatus } from \"@surfaces-ui/proto\";\nimport { type Catalog, type SurfaceMessage, type Surfaces, applyMessage, isComponentIssue, upgradeMessage, upgradeSurface } from \"@surfaces-ui/spec\";\nimport type { DataRef } from \"@surfaces-ui/components\";\n\nexport interface ChatStep {\n id: string;\n title: string;\n status: \"running\" | \"done\" | \"failed\";\n tool: string;\n /** More to show when opened: the SQL run, an error message. */\n detail: string;\n durationMs: number;\n}\n\nexport interface ChatApproval {\n id: string;\n kind: \"permission\" | \"choice\" | \"input\";\n title: string;\n detail: string;\n /** SQL the agent wants to run, when that is what needs approval. */\n sql: string;\n options: string[];\n /** What exactly is being approved, shown as JSON. */\n subject?: JsonObject;\n /** \"sha256:…\" of `{ sql, subject }`; the card refuses to offer approval when it does not match. */\n digest: string;\n /** ISO time after which it cannot be approved. Empty for no limit. */\n expiresAt: string;\n risk: \"low\" | \"high\" | \"irreversible\" | \"\";\n /** The person may change the SQL or subject before approving. */\n editable: boolean;\n reasonRequired: boolean;\n /** Different people who must allow it. */\n approvalsRequired: number;\n /** Decisions already made, when several people must decide. */\n approvals: ChatDecision[];\n /** What the request was based on, for the person to see. */\n basis: string;\n /** Set once the person has answered. */\n answer?: ChatApprovalAnswer;\n}\n\n/** Who decided, as the host identified them. */\nexport interface ChatActor {\n id: string;\n name: string;\n}\n\nexport interface ChatDecision {\n by?: ChatActor;\n /** ISO time. */\n at: string;\n allow: boolean;\n reason: string;\n}\n\nexport interface ChatApprovalAnswer extends ChatDecision {\n /** The chosen option or typed answer. */\n text: string;\n /** \"sha256:…\" of what was approved, edits included. */\n digest: string;\n editedSql?: string;\n editedSubject?: JsonObject;\n}\n\n/** One button in an actions part. What a press does is the host's to decide. */\nexport interface ChatButton {\n /** Reaches the host with the press; need only be unique within its row. */\n id: string;\n label: string;\n /** \"primary\" for the one thing most people will do; \"danger\" for what cannot be taken back. */\n variant?: \"primary\" | \"danger\";\n /** Shown but cannot be pressed. It stays reachable by keyboard so its reason can be read. */\n disabled?: boolean;\n /** Why it cannot be pressed (or, when it can, what it does). Its tooltip, and read with it. */\n reason?: string;\n /** A fuller name when the label alone is ambiguous: \"Apply “Bold” from the chat\". */\n ariaLabel?: string;\n}\n\n/** One of several alternatives in an actions part, with buttons of its own. */\nexport interface ChatChoice {\n id: string;\n title: string;\n detail?: string;\n buttons: ChatButton[];\n}\n\n/**\n * What a person can do about a reply, drawn under it: one set of buttons\n * (\"Show on the page\", \"Discard\", \"Apply\"), or several alternatives one row\n * each with buttons for the whole set after them (\"Discard all\"). Presses go\n * to `MessageList`'s `onPartAction`. Once handled, the host sets `outcome`,\n * which replaces every button.\n */\nexport interface ChatActions {\n id: string;\n title?: string;\n detail?: string;\n /** Alternatives to choose between, one row each. */\n choices?: ChatChoice[];\n /** Buttons for the whole set, after any choices. */\n buttons?: ChatButton[];\n /** What became of it (\"Applied.\", \"Discarded.\"). Replaces the buttons. */\n outcome?: string;\n}\n\n/**\n * Something a person attached to a message that is not a table or a file of data: a picture, usually. The host\n * keeps the bytes; the thread keeps this description, which is what the message list shows.\n */\nexport interface ChatAttachment {\n /** Tells it apart, and lets the host find what it kept. Default: the name. */\n id?: string;\n /** The file's name, shown under or beside the thumbnail. */\n name: string;\n /** Its media type, such as \"image/png\". A thumbnail is drawn only for an `image/*` type. */\n mediaType: string;\n /** Its size in bytes, when known. */\n size?: number;\n /**\n * An address a small picture of it can be drawn from (a `blob:` URL the host made, a raster `data:image/` URL, an\n * http(s) or same-origin address). It comes from the host, never from a model: nothing an agent wrote is put here, and\n * an address that is not one of those kinds is ignored. A blob URL does not outlive the page, so a thread kept\n * across reloads shows the name alone until the host supplies a preview again.\n */\n preview?: string;\n}\n\n/** One piece of a reply, in the order it arrived. */\nexport type ChatPart =\n | { kind: \"text\"; text: string }\n /** Tables and columns a person attached to their message, by name. */\n | { kind: \"references\"; references: DataRef[] }\n /** Pictures and other files a person attached to their message that are not data (`ChatAttachment`). */\n | { kind: \"attachments\"; attachments: ChatAttachment[] }\n | { kind: \"steps\"; steps: ChatStep[] }\n /** A component the agent drew. `surfaceId` is the key into `ChatThread.surfaces`. */\n | { kind: \"surface\"; surfaceId: string }\n | { kind: \"approval\"; approval: ChatApproval }\n /** Buttons the host offers under a reply. Added by the host, never by an agent's events. */\n | { kind: \"actions\"; actions: ChatActions }\n | { kind: \"error\"; code: string; message: string };\n\nexport interface ChatMessage {\n id: number;\n role: \"user\" | \"assistant\";\n parts: ChatPart[];\n /** The model or agent that answered. Always shown. */\n generatedBy: string;\n streaming: boolean;\n}\n\nexport interface ChatUsage {\n inputTokens: number;\n outputTokens: number;\n contextTokens: number;\n contextLimit: number;\n costUsd?: number;\n}\n\nexport interface ChatThread {\n messages: ChatMessage[];\n /** Agent-drawn surfaces, keyed by message and the agent's own surface ID. */\n surfaces: Surfaces;\n /** \"waiting\" means the agent paused for the person's answer. */\n status: \"idle\" | \"streaming\" | \"waiting\";\n sessionId: string;\n usage?: ChatUsage;\n /** Things the person might say next. */\n suggestions: string[];\n}\n\nexport type ChatAction =\n | { type: \"user\"; text: string; references?: DataRef[]; attachments?: ChatAttachment[] }\n /** A turn has started; the reply is added to the latest assistant message when `resume` is set. */\n | { type: \"begin\"; resume?: boolean }\n | { type: \"event\"; event: AgentEvent }\n | { type: \"answered\"; id: string; answer: ChatApprovalAnswer }\n | { type: \"end\" }\n | { type: \"reset\" }\n /** Replaces the thread with one loaded from storage (checked with `parseThread` first). */\n | { type: \"restore\"; thread: ChatThread };\n\nexport const emptyThread: ChatThread = { messages: [], surfaces: {}, status: \"idle\", sessionId: \"\", suggestions: [] };\n\nconst STEP_STATUS: Partial<Record<StepStatus, ChatStep[\"status\"]>> = {\n [StepStatus.RUNNING]: \"running\",\n [StepStatus.DONE]: \"done\",\n [StepStatus.FAILED]: \"failed\",\n};\nconst APPROVAL_KIND: Partial<Record<ApprovalKind, ChatApproval[\"kind\"]>> = {\n [ApprovalKind.PERMISSION]: \"permission\",\n [ApprovalKind.CHOICE]: \"choice\",\n [ApprovalKind.INPUT]: \"input\",\n};\n\nconst APPROVAL_RISK: Partial<Record<ApprovalRisk, ChatApproval[\"risk\"]>> = {\n [ApprovalRisk.LOW]: \"low\",\n [ApprovalRisk.HIGH]: \"high\",\n [ApprovalRisk.IRREVERSIBLE]: \"irreversible\",\n};\n\nconst SCOPE = \":\";\n/** The key a message's surface is stored under, so two replies can both use \"main\". */\nexport const surfaceKey = (messageId: number, surfaceId: string) => `m${messageId}${SCOPE}${surfaceId}`;\n/** The agent's own ID for a stored surface, to send back with an action. */\nexport const agentSurfaceId = (key: string) => key.slice(key.indexOf(SCOPE) + 1);\n\nfunction updateLast(thread: ChatThread, change: (message: ChatMessage) => ChatMessage): ChatThread {\n const index = thread.messages.findLastIndex((m) => m.role === \"assistant\");\n if (index < 0) return thread;\n return { ...thread, messages: thread.messages.map((m, i) => (i === index ? change(m) : m)) };\n}\n\nfunction withPart(message: ChatMessage, part: ChatPart): ChatMessage {\n return { ...message, parts: [...message.parts, part] };\n}\n\nfunction applySurface(thread: ChatThread, raw: unknown, catalog: Catalog): ChatThread {\n const message = thread.messages.findLast((m) => m.role === \"assistant\");\n if (!message) return thread;\n const fail = (text: string) => updateLast(thread, (m) => withPart(m, { kind: \"error\", code: \"INVALID_SURFACE\", message: text }));\n // A malformed envelope is refused; a malformed component is applied and reported where it is drawn.\n const fatal = catalog.validateMessage(raw).filter((issue) => !isComponentIssue(issue));\n if (fatal.length > 0) return fail(`The agent sent a view this page cannot draw: ${fatal[0]!.path} ${fatal[0]!.message}`);\n // What is kept is in the current version, whichever the agent wrote.\n const record = upgradeMessage(raw) as Record<string, { surfaceId: string }>;\n const kind = ([\"createSurface\", \"updateComponents\", \"updateDataModel\", \"deleteSurface\"] as const).find((k) => record[k]);\n if (!kind) return thread;\n const key = surfaceKey(message.id, record[kind]!.surfaceId);\n const scoped = { ...record, [kind]: { ...record[kind], surfaceId: key } } as unknown as SurfaceMessage;\n try {\n const surfaces = applyMessage(thread.surfaces, scoped);\n const shown = message.parts.some((p) => p.kind === \"surface\" && p.surfaceId === key);\n const next = { ...thread, surfaces };\n return kind === \"createSurface\" && !shown ? updateLast(next, (m) => withPart(m, { kind: \"surface\", surfaceId: key })) : next;\n } catch (error) {\n return fail(error instanceof Error ? error.message : String(error));\n }\n}\n\n/**\n * Folds user input and agent events into a thread. Pure: the same actions\n * always give the same thread, so a conversation can be replayed in tests.\n */\nexport function reduceThread(thread: ChatThread, action: ChatAction, catalog: Catalog): ChatThread {\n const nextId = (thread.messages.at(-1)?.id ?? 0) + 1;\n switch (action.type) {\n case \"reset\":\n return emptyThread;\n case \"restore\":\n return action.thread;\n case \"user\":\n return {\n ...thread,\n suggestions: [],\n messages: [\n ...thread.messages,\n { id: nextId, role: \"user\", parts: [\n { kind: \"text\", text: action.text },\n ...(action.references?.length ? [{ kind: \"references\" as const, references: action.references }] : []),\n ...(action.attachments?.length ? [{ kind: \"attachments\" as const, attachments: action.attachments }] : []),\n ], generatedBy: \"\", streaming: false },\n ],\n };\n case \"begin\": {\n const last = thread.messages.at(-1);\n if (action.resume && last?.role === \"assistant\") {\n return { ...updateLast(thread, (m) => ({ ...m, streaming: true })), status: \"streaming\", suggestions: [] };\n }\n return {\n ...thread,\n status: \"streaming\",\n suggestions: [],\n messages: [...thread.messages, { id: nextId, role: \"assistant\", parts: [], generatedBy: \"\", streaming: true }],\n };\n }\n case \"answered\":\n return {\n ...thread,\n messages: thread.messages.map((m) => ({\n ...m,\n parts: m.parts.map((p) =>\n p.kind === \"approval\" && p.approval.id === action.id ? { ...p, approval: { ...p.approval, answer: action.answer } } : p,\n ),\n })),\n };\n case \"end\": {\n const waiting = thread.messages.at(-1)?.parts.some((p) => p.kind === \"approval\" && !p.approval.answer) ?? false;\n return { ...updateLast(thread, (m) => ({ ...m, streaming: false })), status: waiting ? \"waiting\" : \"idle\" };\n }\n case \"event\": {\n const event = action.event.event;\n switch (event.case) {\n case \"text\":\n return updateLast(thread, (m) => {\n const last = m.parts.at(-1);\n if (last?.kind === \"text\") return { ...m, parts: [...m.parts.slice(0, -1), { kind: \"text\", text: last.text + event.value.delta }] };\n return withPart(m, { kind: \"text\", text: event.value.delta });\n });\n case \"step\": {\n const step: ChatStep = {\n id: event.value.id,\n title: event.value.title,\n status: STEP_STATUS[event.value.status] ?? \"running\",\n tool: event.value.tool,\n detail: event.value.detail,\n durationMs: Number(event.value.durationMs),\n };\n return updateLast(thread, (m) => {\n // An event for a step already shown updates it in place.\n if (m.parts.some((p) => p.kind === \"steps\" && p.steps.some((s) => s.id === step.id))) {\n return {\n ...m,\n parts: m.parts.map((p) =>\n p.kind === \"steps\" ? { ...p, steps: p.steps.map((s) => (s.id === step.id ? { ...s, ...step, title: step.title || s.title, detail: step.detail || s.detail } : s)) } : p,\n ),\n };\n }\n const last = m.parts.at(-1);\n if (last?.kind === \"steps\") return { ...m, parts: [...m.parts.slice(0, -1), { kind: \"steps\", steps: [...last.steps, step] }] };\n return withPart(m, { kind: \"steps\", steps: [step] });\n });\n }\n case \"surface\":\n return applySurface(thread, event.value, catalog);\n case \"approval\": {\n const approval: ChatApproval = {\n id: event.value.id,\n kind: APPROVAL_KIND[event.value.kind] ?? \"permission\",\n title: event.value.title,\n detail: event.value.detail,\n sql: event.value.sql,\n options: event.value.options,\n ...(event.value.subject ? { subject: event.value.subject } : {}),\n digest: event.value.digest,\n expiresAt: event.value.expiresAt,\n risk: APPROVAL_RISK[event.value.risk] ?? \"\",\n editable: event.value.editable,\n reasonRequired: event.value.reasonRequired,\n approvalsRequired: Math.max(1, event.value.approvalsRequired),\n approvals: event.value.approvals.map((r) => ({\n ...(r.decidedBy ? { by: { id: r.decidedBy.id, name: r.decidedBy.name } } : {}),\n at: r.decidedAt,\n allow: r.allow,\n reason: r.reason,\n })),\n basis: event.value.basis,\n };\n return updateLast(thread, (m) => withPart(m, { kind: \"approval\", approval }));\n }\n case \"usage\":\n return {\n ...thread,\n usage: {\n inputTokens: Number(event.value.inputTokens),\n outputTokens: Number(event.value.outputTokens),\n contextTokens: Number(event.value.contextTokens),\n contextLimit: Number(event.value.contextLimit),\n costUsd: event.value.costUsd,\n },\n };\n case \"suggestions\":\n return { ...thread, suggestions: event.value.items };\n case \"error\":\n return updateLast(thread, (m) => withPart(m, { kind: \"error\", code: event.value.code, message: event.value.message }));\n case \"done\":\n return { ...updateLast(thread, (m) => ({ ...m, generatedBy: event.value.generatedBy || m.generatedBy })), sessionId: event.value.sessionId || thread.sessionId };\n default:\n return thread;\n }\n }\n }\n}\n\nconst PART_KINDS = new Set([\"text\", \"references\", \"attachments\", \"steps\", \"surface\", \"approval\", \"actions\", \"error\"]);\nconst isRecord = (value: unknown): value is Record<string, unknown> => !!value && typeof value === \"object\" && !Array.isArray(value);\n\n/**\n * Checks a thread loaded from storage before it is used, since anyone with\n * access to the storage can edit it. Returns undefined for anything that is\n * not a thread. A reply that was still streaming when the page closed is\n * marked as cut off; an approval nobody answered is still waiting. Surfaces\n * are checked against the catalog again when they are drawn.\n */\nexport function parseThread(input: unknown): ChatThread | undefined {\n if (!isRecord(input) || !Array.isArray(input.messages) || !isRecord(input.surfaces)) return undefined;\n const messages: ChatMessage[] = [];\n for (const raw of input.messages) {\n if (!isRecord(raw) || typeof raw.id !== \"number\" || (raw.role !== \"user\" && raw.role !== \"assistant\") || !Array.isArray(raw.parts)) return undefined;\n if (!raw.parts.every((p) => isRecord(p) && PART_KINDS.has(p.kind as string))) return undefined;\n const parts = raw.parts as ChatPart[];\n const cut = raw.streaming === true;\n messages.push({\n id: raw.id,\n role: raw.role,\n parts: cut ? [...parts, { kind: \"error\", code: \"INTERRUPTED\", message: \"This reply was cut off when the page closed.\" }] : parts,\n generatedBy: typeof raw.generatedBy === \"string\" ? raw.generatedBy : \"\",\n streaming: false,\n });\n }\n const waiting = messages.at(-1)?.parts.some((p) => p.kind === \"approval\" && !p.approval.answer) ?? false;\n return {\n messages,\n // A thread kept before the move to A2UI v1.0 holds surfaces written for v0.9.\n surfaces: Object.fromEntries(Object.entries(input.surfaces as ChatThread[\"surfaces\"]).map(([key, surface]) => [key, isRecord(surface) && isRecord(surface.components) ? upgradeSurface(surface) : surface])),\n status: waiting ? \"waiting\" : \"idle\",\n sessionId: typeof input.sessionId === \"string\" ? input.sessionId : \"\",\n ...(isRecord(input.usage) ? { usage: input.usage as unknown as ChatUsage } : {}),\n suggestions: Array.isArray(input.suggestions) ? input.suggestions.filter((s): s is string => typeof s === \"string\") : [],\n };\n}\n"]}
1
+ {"version":3,"file":"thread.js","sourceRoot":"","sources":["../src/thread.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,YAAY,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAC5E,OAAO,EAAoD,YAAY,EAAE,gBAAgB,EAAE,cAAc,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAyLrJ,MAAM,CAAC,MAAM,WAAW,GAAe,EAAE,QAAQ,EAAE,EAAE,EAAE,QAAQ,EAAE,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,EAAE,EAAE,WAAW,EAAE,EAAE,EAAE,CAAC;AAEtH,MAAM,WAAW,GAAoD;IACnE,CAAC,UAAU,CAAC,OAAO,CAAC,EAAE,SAAS;IAC/B,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,MAAM;IACzB,CAAC,UAAU,CAAC,MAAM,CAAC,EAAE,QAAQ;CAC9B,CAAC;AACF,MAAM,aAAa,GAAwD;IACzE,CAAC,YAAY,CAAC,UAAU,CAAC,EAAE,YAAY;IACvC,CAAC,YAAY,CAAC,MAAM,CAAC,EAAE,QAAQ;IA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AE,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,QAAkC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,OAAO,CAAC,EAAE,EAAE,CAAC,CAAC,GAAG,EAAE,QAAQ,CAAC,OAAO,CAAC,IAAI,QAAQ,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC;QAC5M,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,MAAM;QACpC,SAAS,EAAE,OAAO,KAAK,CAAC,SAAS,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE;QACrE,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,KAAK,CAAC,KAA6B,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAChF,WAAW,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC,EAAe,EAAE,CAAC,OAAO,CAAC,KAAK,QAAQ,CAAC,CAAC,CAAC,CAAC,EAAE;KACzH,CAAC;AACJ,CAAC","sourcesContent":["import type { AgentEvent } from \"@surfaces-ui/agent\";\nimport type { JsonObject } from \"@bufbuild/protobuf\";\nimport { ApprovalKind, ApprovalRisk, StepStatus } from \"@surfaces-ui/proto\";\nimport { type Catalog, type SurfaceMessage, type Surfaces, applyMessage, isComponentIssue, upgradeMessage, upgradeSurface } from \"@surfaces-ui/spec\";\nimport type { DataRef } from \"@surfaces-ui/components\";\n\nexport interface ChatStep {\n id: string;\n title: string;\n status: \"running\" | \"done\" | \"failed\";\n tool: string;\n /** More to show when opened: the SQL run, an error message. */\n detail: string;\n durationMs: number;\n}\n\nexport interface ChatApproval {\n id: string;\n kind: \"permission\" | \"choice\" | \"input\";\n title: string;\n detail: string;\n /** SQL the agent wants to run, when that is what needs approval. */\n sql: string;\n options: string[];\n /** What exactly is being approved, shown as JSON. */\n subject?: JsonObject;\n /** \"sha256:…\" of `{ sql, subject }`; the card refuses to offer approval when it does not match. */\n digest: string;\n /** ISO time after which it cannot be approved. Empty for no limit. */\n expiresAt: string;\n risk: \"low\" | \"high\" | \"irreversible\" | \"\";\n /** The person may change the SQL or subject before approving. */\n editable: boolean;\n reasonRequired: boolean;\n /** Different people who must allow it. */\n approvalsRequired: number;\n /** Decisions already made, when several people must decide. */\n approvals: ChatDecision[];\n /** What the request was based on, for the person to see. */\n basis: string;\n /** Set once the person has answered. */\n answer?: ChatApprovalAnswer;\n}\n\n/** Who decided, as the host identified them. */\nexport interface ChatActor {\n id: string;\n name: string;\n}\n\nexport interface ChatDecision {\n by?: ChatActor;\n /** ISO time. */\n at: string;\n allow: boolean;\n reason: string;\n}\n\nexport interface ChatApprovalAnswer extends ChatDecision {\n /** The chosen option or typed answer. */\n text: string;\n /** \"sha256:…\" of what was approved, edits included. */\n digest: string;\n editedSql?: string;\n editedSubject?: JsonObject;\n}\n\n/** One button in an actions part. What a press does is the host's to decide. */\nexport interface ChatButton {\n /** Reaches the host with the press; need only be unique within its row. */\n id: string;\n label: string;\n /** \"primary\" for the one thing most people will do; \"danger\" for what cannot be taken back. */\n variant?: \"primary\" | \"danger\";\n /** Shown but cannot be pressed. It stays reachable by keyboard so its reason can be read. */\n disabled?: boolean;\n /** Why it cannot be pressed (or, when it can, what it does). Its tooltip, and read with it. */\n reason?: string;\n /** A fuller name when the label alone is ambiguous: \"Apply “Bold” from the chat\". */\n ariaLabel?: string;\n}\n\n/** One of several alternatives in an actions part, with buttons of its own. */\nexport interface ChatChoice {\n id: string;\n title: string;\n detail?: string;\n buttons: ChatButton[];\n}\n\n/**\n * What a person can do about a reply, drawn under it: one set of buttons\n * (\"Show on the page\", \"Discard\", \"Apply\"), or several alternatives one row\n * each with buttons for the whole set after them (\"Discard all\"). Presses go\n * to `MessageList`'s `onPartAction`. Once handled, the host sets `outcome`,\n * which replaces every button.\n */\nexport interface ChatActions {\n id: string;\n title?: string;\n detail?: string;\n /** Alternatives to choose between, one row each. */\n choices?: ChatChoice[];\n /** Buttons for the whole set, after any choices. */\n buttons?: ChatButton[];\n /** What became of it (\"Applied.\", \"Discarded.\"). Replaces the buttons. */\n outcome?: string;\n}\n\n/**\n * Something a person attached to a message that is not a table or a file of data: a picture, usually. The host\n * keeps the bytes; the thread keeps this description, which is what the message list shows.\n */\nexport interface ChatAttachment {\n /** Tells it apart, and lets the host find what it kept. Default: the name. */\n id?: string;\n /** The file's name, shown under or beside the thumbnail. */\n name: string;\n /** Its media type, such as \"image/png\". A thumbnail is drawn only for an `image/*` type. */\n mediaType: string;\n /** Its size in bytes, when known. */\n size?: number;\n /**\n * An address a small picture of it can be drawn from (a `blob:` URL the host made, a raster `data:image/` URL, an\n * http(s) or same-origin address). It comes from the host, never from a model: nothing an agent wrote is put here, and\n * an address that is not one of those kinds is ignored. A blob URL does not outlive the page, so a thread kept\n * across reloads shows the name alone until the host supplies a preview again.\n */\n preview?: string;\n}\n\n/** One piece of a reply, in the order it arrived. */\nexport type ChatPart =\n | { kind: \"text\"; text: string }\n /** Tables and columns a person attached to their message, by name. */\n | { kind: \"references\"; references: DataRef[] }\n /** Pictures and other files a person attached to their message that are not data (`ChatAttachment`). */\n | { kind: \"attachments\"; attachments: ChatAttachment[] }\n | { kind: \"steps\"; steps: ChatStep[] }\n /** A component the agent drew. `surfaceId` is the key into `ChatThread.surfaces`. */\n | { kind: \"surface\"; surfaceId: string }\n | { kind: \"approval\"; approval: ChatApproval }\n /** Buttons the host offers under a reply. Added by the host, never by an agent's events. */\n | { kind: \"actions\"; actions: ChatActions }\n | { kind: \"error\"; code: string; message: string };\n\nexport interface ChatMessage {\n id: number;\n role: \"user\" | \"assistant\";\n parts: ChatPart[];\n /** The model or agent that answered. Always shown. */\n generatedBy: string;\n streaming: boolean;\n /** What the agent is doing, in words, while the reply is on its way. Without it, the chat says so from the reply's own parts. */\n progress?: string;\n}\n\nexport interface ChatUsage {\n inputTokens: number;\n outputTokens: number;\n contextTokens: number;\n contextLimit: number;\n costUsd?: number;\n}\n\nexport interface ChatThread {\n messages: ChatMessage[];\n /** Agent-drawn surfaces, keyed by message and the agent's own surface ID. */\n surfaces: Surfaces;\n /** \"waiting\" means the agent paused for the person's answer. */\n status: \"idle\" | \"streaming\" | \"waiting\";\n sessionId: string;\n usage?: ChatUsage;\n /** Things the person might say next. */\n suggestions: string[];\n}\n\nexport type ChatAction =\n | { type: \"user\"; text: string; references?: DataRef[]; attachments?: ChatAttachment[] }\n /** A turn has started; the reply is added to the latest assistant message when `resume` is set. */\n | { type: \"begin\"; resume?: boolean }\n | { type: \"event\"; event: AgentEvent }\n | { type: \"answered\"; id: string; answer: ChatApprovalAnswer }\n | { type: \"end\" }\n | { type: \"reset\" }\n /** Replaces the thread with one loaded from storage (checked with `parseThread` first). */\n | { type: \"restore\"; thread: ChatThread };\n\nexport const emptyThread: ChatThread = { messages: [], surfaces: {}, status: \"idle\", sessionId: \"\", suggestions: [] };\n\nconst STEP_STATUS: Partial<Record<StepStatus, ChatStep[\"status\"]>> = {\n [StepStatus.RUNNING]: \"running\",\n [StepStatus.DONE]: \"done\",\n [StepStatus.FAILED]: \"failed\",\n};\nconst APPROVAL_KIND: Partial<Record<ApprovalKind, ChatApproval[\"kind\"]>> = {\n [ApprovalKind.PERMISSION]: \"permission\",\n [ApprovalKind.CHOICE]: \"choice\",\n [ApprovalKind.INPUT]: \"input\",\n};\n\nconst APPROVAL_RISK: Partial<Record<ApprovalRisk, ChatApproval[\"risk\"]>> = {\n [ApprovalRisk.LOW]: \"low\",\n [ApprovalRisk.HIGH]: \"high\",\n [ApprovalRisk.IRREVERSIBLE]: \"irreversible\",\n};\n\nconst SCOPE = \":\";\n/** The key a message's surface is stored under, so two replies can both use \"main\". */\nexport const surfaceKey = (messageId: number, surfaceId: string) => `m${messageId}${SCOPE}${surfaceId}`;\n/** The agent's own ID for a stored surface, to send back with an action. */\nexport const agentSurfaceId = (key: string) => key.slice(key.indexOf(SCOPE) + 1);\n\nfunction updateLast(thread: ChatThread, change: (message: ChatMessage) => ChatMessage): ChatThread {\n const index = thread.messages.findLastIndex((m) => m.role === \"assistant\");\n if (index < 0) return thread;\n return { ...thread, messages: thread.messages.map((m, i) => (i === index ? change(m) : m)) };\n}\n\nfunction withPart(message: ChatMessage, part: ChatPart): ChatMessage {\n return { ...message, parts: [...message.parts, part] };\n}\n\nfunction applySurface(thread: ChatThread, raw: unknown, catalog: Catalog): ChatThread {\n const message = thread.messages.findLast((m) => m.role === \"assistant\");\n if (!message) return thread;\n const fail = (text: string) => updateLast(thread, (m) => withPart(m, { kind: \"error\", code: \"INVALID_SURFACE\", message: text }));\n // A malformed envelope is refused; a malformed component is applied and reported where it is drawn.\n const fatal = catalog.validateMessage(raw).filter((issue) => !isComponentIssue(issue));\n if (fatal.length > 0) return fail(`The agent sent a view this page cannot draw: ${fatal[0]!.path} ${fatal[0]!.message}`);\n // What is kept is in the current version, whichever the agent wrote.\n const record = upgradeMessage(raw) as Record<string, { surfaceId: string }>;\n const kind = ([\"createSurface\", \"updateComponents\", \"updateDataModel\", \"deleteSurface\"] as const).find((k) => record[k]);\n if (!kind) return thread;\n const key = surfaceKey(message.id, record[kind]!.surfaceId);\n const scoped = { ...record, [kind]: { ...record[kind], surfaceId: key } } as unknown as SurfaceMessage;\n try {\n const surfaces = applyMessage(thread.surfaces, scoped);\n const shown = message.parts.some((p) => p.kind === \"surface\" && p.surfaceId === key);\n const next = { ...thread, surfaces };\n return kind === \"createSurface\" && !shown ? updateLast(next, (m) => withPart(m, { kind: \"surface\", surfaceId: key })) : next;\n } catch (error) {\n return fail(error instanceof Error ? error.message : String(error));\n }\n}\n\n/**\n * Folds user input and agent events into a thread. Pure: the same actions\n * always give the same thread, so a conversation can be replayed in tests.\n */\nexport function reduceThread(thread: ChatThread, action: ChatAction, catalog: Catalog): ChatThread {\n const nextId = (thread.messages.at(-1)?.id ?? 0) + 1;\n switch (action.type) {\n case \"reset\":\n return emptyThread;\n case \"restore\":\n return action.thread;\n case \"user\":\n return {\n ...thread,\n suggestions: [],\n messages: [\n ...thread.messages,\n { id: nextId, role: \"user\", parts: [\n { kind: \"text\", text: action.text },\n ...(action.references?.length ? [{ kind: \"references\" as const, references: action.references }] : []),\n ...(action.attachments?.length ? [{ kind: \"attachments\" as const, attachments: action.attachments }] : []),\n ], generatedBy: \"\", streaming: false },\n ],\n };\n case \"begin\": {\n const last = thread.messages.at(-1);\n if (action.resume && last?.role === \"assistant\") {\n return { ...updateLast(thread, (m) => ({ ...m, streaming: true })), status: \"streaming\", suggestions: [] };\n }\n return {\n ...thread,\n status: \"streaming\",\n suggestions: [],\n messages: [...thread.messages, { id: nextId, role: \"assistant\", parts: [], generatedBy: \"\", streaming: true }],\n };\n }\n case \"answered\":\n return {\n ...thread,\n messages: thread.messages.map((m) => ({\n ...m,\n parts: m.parts.map((p) =>\n p.kind === \"approval\" && p.approval.id === action.id ? { ...p, approval: { ...p.approval, answer: action.answer } } : p,\n ),\n })),\n };\n case \"end\": {\n const waiting = thread.messages.at(-1)?.parts.some((p) => p.kind === \"approval\" && !p.approval.answer) ?? false;\n return { ...updateLast(thread, (m) => ({ ...m, streaming: false })), status: waiting ? \"waiting\" : \"idle\" };\n }\n case \"event\": {\n const event = action.event.event;\n switch (event.case) {\n case \"text\":\n return updateLast(thread, (m) => {\n const last = m.parts.at(-1);\n if (last?.kind === \"text\") return { ...m, parts: [...m.parts.slice(0, -1), { kind: \"text\", text: last.text + event.value.delta }] };\n return withPart(m, { kind: \"text\", text: event.value.delta });\n });\n case \"step\": {\n const step: ChatStep = {\n id: event.value.id,\n title: event.value.title,\n status: STEP_STATUS[event.value.status] ?? \"running\",\n tool: event.value.tool,\n detail: event.value.detail,\n durationMs: Number(event.value.durationMs),\n };\n return updateLast(thread, (m) => {\n // An event for a step already shown updates it in place.\n if (m.parts.some((p) => p.kind === \"steps\" && p.steps.some((s) => s.id === step.id))) {\n return {\n ...m,\n parts: m.parts.map((p) =>\n p.kind === \"steps\" ? { ...p, steps: p.steps.map((s) => (s.id === step.id ? { ...s, ...step, title: step.title || s.title, detail: step.detail || s.detail } : s)) } : p,\n ),\n };\n }\n const last = m.parts.at(-1);\n if (last?.kind === \"steps\") return { ...m, parts: [...m.parts.slice(0, -1), { kind: \"steps\", steps: [...last.steps, step] }] };\n return withPart(m, { kind: \"steps\", steps: [step] });\n });\n }\n case \"surface\":\n return applySurface(thread, event.value, catalog);\n case \"approval\": {\n const approval: ChatApproval = {\n id: event.value.id,\n kind: APPROVAL_KIND[event.value.kind] ?? \"permission\",\n title: event.value.title,\n detail: event.value.detail,\n sql: event.value.sql,\n options: event.value.options,\n ...(event.value.subject ? { subject: event.value.subject } : {}),\n digest: event.value.digest,\n expiresAt: event.value.expiresAt,\n risk: APPROVAL_RISK[event.value.risk] ?? \"\",\n editable: event.value.editable,\n reasonRequired: event.value.reasonRequired,\n approvalsRequired: Math.max(1, event.value.approvalsRequired),\n approvals: event.value.approvals.map((r) => ({\n ...(r.decidedBy ? { by: { id: r.decidedBy.id, name: r.decidedBy.name } } : {}),\n at: r.decidedAt,\n allow: r.allow,\n reason: r.reason,\n })),\n basis: event.value.basis,\n };\n return updateLast(thread, (m) => withPart(m, { kind: \"approval\", approval }));\n }\n case \"usage\":\n return {\n ...thread,\n usage: {\n inputTokens: Number(event.value.inputTokens),\n outputTokens: Number(event.value.outputTokens),\n contextTokens: Number(event.value.contextTokens),\n contextLimit: Number(event.value.contextLimit),\n costUsd: event.value.costUsd,\n },\n };\n case \"suggestions\":\n return { ...thread, suggestions: event.value.items };\n case \"error\":\n return updateLast(thread, (m) => withPart(m, { kind: \"error\", code: event.value.code, message: event.value.message }));\n case \"done\":\n return { ...updateLast(thread, (m) => ({ ...m, generatedBy: event.value.generatedBy || m.generatedBy })), sessionId: event.value.sessionId || thread.sessionId };\n default:\n return thread;\n }\n }\n }\n}\n\nconst PART_KINDS = new Set([\"text\", \"references\", \"attachments\", \"steps\", \"surface\", \"approval\", \"actions\", \"error\"]);\nconst isRecord = (value: unknown): value is Record<string, unknown> => !!value && typeof value === \"object\" && !Array.isArray(value);\n\n/**\n * Checks a thread loaded from storage before it is used, since anyone with\n * access to the storage can edit it. Returns undefined for anything that is\n * not a thread. A reply that was still streaming when the page closed is\n * marked as cut off; an approval nobody answered is still waiting. Surfaces\n * are checked against the catalog again when they are drawn.\n */\nexport function parseThread(input: unknown): ChatThread | undefined {\n if (!isRecord(input) || !Array.isArray(input.messages) || !isRecord(input.surfaces)) return undefined;\n const messages: ChatMessage[] = [];\n for (const raw of input.messages) {\n if (!isRecord(raw) || typeof raw.id !== \"number\" || (raw.role !== \"user\" && raw.role !== \"assistant\") || !Array.isArray(raw.parts)) return undefined;\n if (!raw.parts.every((p) => isRecord(p) && PART_KINDS.has(p.kind as string))) return undefined;\n const parts = raw.parts as ChatPart[];\n const cut = raw.streaming === true;\n messages.push({\n id: raw.id,\n role: raw.role,\n parts: cut ? [...parts, { kind: \"error\", code: \"INTERRUPTED\", message: \"This reply was cut off when the page closed.\" }] : parts,\n generatedBy: typeof raw.generatedBy === \"string\" ? raw.generatedBy : \"\",\n streaming: false,\n });\n }\n const waiting = messages.at(-1)?.parts.some((p) => p.kind === \"approval\" && !p.approval.answer) ?? false;\n return {\n messages,\n // A thread kept before the move to A2UI v1.0 holds surfaces written for v0.9.\n surfaces: Object.fromEntries(Object.entries(input.surfaces as ChatThread[\"surfaces\"]).map(([key, surface]) => [key, isRecord(surface) && isRecord(surface.components) ? upgradeSurface(surface) : surface])),\n status: waiting ? \"waiting\" : \"idle\",\n sessionId: typeof input.sessionId === \"string\" ? input.sessionId : \"\",\n ...(isRecord(input.usage) ? { usage: input.usage as unknown as ChatUsage } : {}),\n suggestions: Array.isArray(input.suggestions) ? input.suggestions.filter((s): s is string => typeof s === \"string\") : [],\n };\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@surfaces-ui/chat",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "Chat thread components for Surfaces UI: streaming replies, tool steps, approvals and inline agent-drawn components",
5
5
  "keywords": [
6
6
  "surfaces-ui",
@@ -46,12 +46,13 @@
46
46
  },
47
47
  "dependencies": {
48
48
  "@bufbuild/protobuf": "^2.17.0",
49
- "@surfaces-ui/agent": "0.6.0",
50
- "@surfaces-ui/components": "0.6.0",
51
- "@surfaces-ui/proto": "0.6.0",
52
- "@surfaces-ui/spec": "0.6.0",
53
- "@surfaces-ui/state": "0.6.0",
54
- "@surfaces-ui/trace": "0.6.0"
49
+ "@surfaces-ui/agent": "0.7.0",
50
+ "@surfaces-ui/components": "0.7.0",
51
+ "@surfaces-ui/proto": "0.7.0",
52
+ "@surfaces-ui/spec": "0.7.0",
53
+ "@surfaces-ui/icons": "0.7.0",
54
+ "@surfaces-ui/state": "0.7.0",
55
+ "@surfaces-ui/trace": "0.7.0"
55
56
  },
56
57
  "devDependencies": {
57
58
  "@codemirror/view": "^6.43.15",
@@ -61,7 +62,7 @@
61
62
  "jsdom": "^31.0.0",
62
63
  "react": "^19.3.1",
63
64
  "react-dom": "^19.3.1",
64
- "@surfaces-ui/data": "0.6.0"
65
+ "@surfaces-ui/data": "0.7.0"
65
66
  },
66
67
  "publishConfig": {
67
68
  "access": "public",