@nexface/chat 0.1.6 → 0.1.8-alpha.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.
@@ -1,3 +1,4 @@
1
+ import type { UIMessagePart } from "./messages.js";
1
2
  import type { AssistantBinding } from "./assistant-runtime.js";
2
3
  import type { ChatProps } from "./types.js";
3
4
  export declare function AttachmentTile({ binding, savedPreview }: {
@@ -12,10 +13,7 @@ export declare function AssistantComposer({ binding, options, placeholder, busy,
12
13
  cancelling: boolean;
13
14
  cancel(): void;
14
15
  }): import("react").JSX.Element;
15
- export declare function AssistantParts({ showDetails, errors }: {
16
+ export declare function AssistantParts({ showDetails, tools }: {
16
17
  showDetails: boolean;
17
- errors: readonly {
18
- id: string;
19
- message: string;
20
- }[];
18
+ tools?: readonly UIMessagePart[];
21
19
  }): import("react").JSX.Element;
@@ -1,6 +1,6 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
2
  import { AttachmentUI } from "./ui/attachment.aui.js";
3
- import { useRef } from "react";
3
+ import { useEffect, useRef, useState } from "react";
4
4
  import { MarkdownText } from "./ui/markdown-text.js";
5
5
  import { Composer } from "./ui/home-demo/composer.js";
6
6
  import { cn } from "./ui/utils.js";
@@ -33,22 +33,34 @@ export function AssistantComposer({ binding, options, placeholder, busy, cancell
33
33
  } } }, actions: _jsxs(_Fragment, { children: [options !== false ? _jsxs(_Fragment, { children: [_jsx("input", { ref: input, type: "file", multiple: true, disabled: sending, accept: options?.accept ?? attachmentAccept, hidden: true, onChange: (event) => { addFiles(Array.from(event.target.files ?? [])); event.target.value = ""; } }), _jsx("button", { type: "button", className: cn("text-muted-foreground hover:text-foreground rounded-control grid size-7 shrink-0 place-items-center transition-colors"), "aria-label": "\u6DFB\u52A0\u9644\u4EF6", disabled: sending, onClick: () => input.current?.click(), children: _jsx(PlusIcon, { className: cn("size-4") }) })] }) : _jsx("span", {}), _jsx("div", { className: cn("flex shrink-0 items-center gap-1"), children: showCancel ? _jsx("button", { type: "button", "aria-label": "\u53D6\u6D88\u4EFB\u52A1", className: cn("bg-primary text-primary-foreground rounded-control grid size-7 place-items-center"), disabled: cancelling, onClick: cancel, children: _jsx(SquareIcon, { className: cn("size-3 fill-current") }) }) :
34
34
  _jsx(ComposerPrimitive.Send, { asChild: true, disabled: sending, children: _jsx("button", { type: "button", onClick: (event) => { event.preventDefault(); void binding.send(); }, "aria-label": "\u53D1\u9001\u4EFB\u52A1", className: cn("bg-primary text-primary-foreground rounded-control grid size-7 place-items-center transition-opacity disabled:opacity-40"), children: _jsx(ArrowUpIcon, { className: cn("size-4") }) }) }) })] }), children: [_jsx("div", { className: cn("aui-composer-attachments flex w-full flex-row items-center gap-2 overflow-x-auto empty:hidden"), children: _jsx(ComposerPrimitive.Attachments, { children: () => _jsx(AttachmentTile, { binding: binding }) }) }), sending ? _jsx("small", { role: "status", children: "\u6B63\u5728\u5904\u7406\u9644\u4EF6\u2026" }) : null] });
35
35
  }
36
+ function ToolGroup({ tools, running, count, children }) {
37
+ const errors = tools.flatMap((tool) => tool.type === "tool" && tool.error ? [tool.error] : []);
38
+ const errorIds = JSON.stringify(errors.map((error) => error.id));
39
+ const hasErrors = errors.length > 0;
40
+ const [open, setOpen] = useState(hasErrors);
41
+ useEffect(() => {
42
+ if (errorIds !== "[]")
43
+ setOpen(true);
44
+ }, [errorIds]);
45
+ const unknown = hasErrors && errors.every((error) => error.scope === "tool" && error.execution === "unknown");
46
+ return _jsxs(ToolGroupRoot, { variant: "ghost", className: cn("my-1"), open: open, onOpenChange: setOpen, children: [_jsx(DisclosureTrigger, { live: running && !hasErrors, label: hasErrors ? unknown ? "Result unknown" : "Failed" : running ? "running" : "ran", detail: `${count} tools` }), _jsx(ToolGroupContent, { className: cn(disclosureContentClass), children: children })] });
47
+ }
36
48
  const groupAssistantParts = groupPartByType({ reasoning: ["group-chainOfThought", "group-reasoning"], source: ["group-chainOfThought", "group-source"], "tool-call": ["group-chainOfThought", "group-tool"], "standalone-tool-call": [] });
37
- export function AssistantParts({ showDetails, errors }) {
38
- return _jsxs(_Fragment, { children: [_jsx(MessagePrimitive.GroupedParts, { groupBy: groupAssistantParts, children: ({ part, children }) => {
39
- switch (part.type) {
40
- case "group-chainOfThought": return _jsx("div", { className: cn("mb-3"), children: children });
41
- case "group-tool": return part.indices.length === 1 ? _jsx(_Fragment, { children: children }) : _jsxs(ToolGroupRoot, { variant: "ghost", className: cn("my-1"), children: [_jsx(DisclosureTrigger, { live: part.status.type === "running", label: part.status.type === "running" ? "running" : "ran", detail: `${part.indices.length} tools` }), _jsx(ToolGroupContent, { className: cn(disclosureContentClass), children: children })] });
42
- case "group-reasoning": return _jsxs(ReasoningRoot, { variant: "ghost", streaming: part.status.type === "running", className: cn("my-1 mb-3"), children: [_jsx(DisclosureTrigger, { live: part.status.type === "running", label: part.status.type === "running" ? "thinking" : "reasoning" }), _jsx(ReasoningContent, { "aria-busy": part.status.type === "running", className: cn(disclosureContentClass), children: _jsx(ReasoningText, { className: cn("ps-0"), children: children }) })] });
43
- case "reasoning": return _jsx(Reasoning, { ...part });
44
- case "group-source":
45
- case "source": return null;
46
- case "data": return part.dataRendererUI;
47
- case "text": return part.text === "" && part.status?.type === "running" ? _jsx(TraceLine, { live: true, label: "thinking" }) : _jsx(MarkdownText, {});
48
- case "tool-call": return part.toolUI ?? _jsx(ToolCall, { ...part, showDetails: showDetails });
49
- case "indicator": return _jsx(TraceLine, { live: true, label: "thinking" });
50
- default: return null;
51
- }
52
- } }), errors.map((error) => _jsx("p", { role: "alert", className: cn("mt-2 border-l-2 pl-3 text-[13px] border-destructive/60 text-destructive"), children: error.message }, error.id))] });
49
+ export function AssistantParts({ showDetails, tools = [] }) {
50
+ return _jsx(_Fragment, { children: _jsx(MessagePrimitive.GroupedParts, { groupBy: groupAssistantParts, children: ({ part, children }) => {
51
+ switch (part.type) {
52
+ case "group-chainOfThought": return _jsx("div", { className: cn("mb-3"), children: children });
53
+ case "group-tool": return part.indices.length === 1 ? _jsx(_Fragment, { children: children }) : _jsx(ToolGroup, { tools: tools.filter((_, index) => part.indices.includes(index)), running: part.status.type === "running", count: part.indices.length, children: children });
54
+ case "group-reasoning": return _jsxs(ReasoningRoot, { variant: "ghost", streaming: part.status.type === "running", className: cn("my-1 mb-3"), children: [_jsx(DisclosureTrigger, { live: part.status.type === "running", label: part.status.type === "running" ? "thinking" : "reasoning" }), _jsx(ReasoningContent, { "aria-busy": part.status.type === "running", className: cn(disclosureContentClass), children: _jsx(ReasoningText, { className: cn("ps-0"), children: children }) })] });
55
+ case "reasoning": return _jsx(Reasoning, { ...part });
56
+ case "group-source":
57
+ case "source": return null;
58
+ case "data": return part.dataRendererUI;
59
+ case "text": return part.text === "" && part.status?.type === "running" ? _jsx(TraceLine, { live: true, label: "thinking" }) : _jsx(MarkdownText, {});
60
+ case "tool-call": return part.toolUI ?? _jsx(ToolCall, { ...part, showDetails: showDetails, presentation: tools.find((tool) => tool.type === "tool" && tool.toolCallId === part.toolCallId) });
61
+ case "indicator": return _jsx(TraceLine, { live: true, label: "thinking" });
62
+ default: return null;
63
+ }
64
+ } }) });
53
65
  }
54
66
  //# sourceMappingURL=assistant-components.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"assistant-components.js","sourceRoot":"","sources":["../src/assistant-components.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AACtD,OAAO,EAAE,MAAM,EAAE,MAAM,OAAO,CAAC;AAC/B,OAAO,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AACrD,OAAO,EAAE,QAAQ,EAAE,MAAM,4BAA4B,CAAC;AACtD,OAAO,EAAE,EAAE,EAAE,MAAM,eAAe,CAAC;AACnC,OAAO,EAAE,mBAAmB,EAAE,iBAAiB,EAAE,WAAW,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAC7H,OAAO,EAAE,WAAW,EAAE,QA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AAsB,CAAC,YAAE,KAAC,aAAa,IAAC,SAAS,EAAE,EAAE,CAAC,MAAM,CAAC,YAAG,QAAQ,GAAiB,GAAmB,IACzK,CAAC;wBACjB,KAAK,WAAW,CAAC,CAAC,OAAO,KAAC,SAAS,OAAK,IAAI,GAAI,CAAC;wBACjD,KAAK,cAAc,CAAC;wBACpB,KAAK,QAAQ,CAAC,CAAC,OAAO,IAAI,CAAC;wBAC3B,KAAK,MAAM,CAAC,CAAC,OAAO,IAAI,CAAC,cAAc,CAAC;wBACxC,KAAK,MAAM,CAAC,CAAC,OAAO,IAAI,CAAC,IAAI,KAAK,EAAE,IAAI,IAAI,CAAC,MAAM,EAAE,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,KAAC,SAAS,IAAC,IAAI,QAAC,KAAK,EAAC,UAAU,GAAG,CAAC,CAAC,CAAC,KAAC,YAAY,KAAG,CAAC;wBACjI,KAAK,WAAW,CAAC,CAAC,OAAO,IAAI,CAAC,MAAM,IAAI,KAAC,QAAQ,OAAK,IAAI,EAAE,WAAW,EAAE,WAAW,GAAI,CAAC;wBACzF,KAAK,WAAW,CAAC,CAAC,OAAO,KAAC,SAAS,IAAC,IAAI,QAAC,KAAK,EAAC,UAAU,GAAG,CAAC;wBAC7D,OAAO,CAAC,CAAC,OAAO,IAAI,CAAC;oBACvB,CAAC;gBACH,CAAC,GAAiC,EAAC,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,YAAkB,IAAI,EAAC,OAAO,EAAC,SAAS,EAAE,EAAE,CAAC,yEAAyE,CAAC,YAAG,KAAK,CAAC,OAAO,IAA/H,KAAK,CAAC,EAAE,CAA4H,CAAC,IAAI,CAAC;AAC7M,CAAC","sourcesContent":["import { AttachmentUI } from \"./ui/attachment.aui.js\";\nimport { useRef } from \"react\";\nimport { MarkdownText } from \"./ui/markdown-text.js\";\nimport { Composer } from \"./ui/home-demo/composer.js\";\nimport { cn } from \"./ui/utils.js\";\nimport { AttachmentPrimitive, ComposerPrimitive, useAuiState, MessagePrimitive, groupPartByType } from \"@assistant-ui/react\";\nimport { ArrowUpIcon, PlusIcon, SquareIcon } from \"lucide-react\";\nimport { ToolGroupRoot, ToolGroupContent } from \"./ui/tool-group.aui.js\";\nimport { DisclosureTrigger, ToolCall, disclosureContentClass } from \"./ui/home-demo/trace.js\";\nimport { Reasoning, ReasoningRoot, ReasoningContent, ReasoningText } from \"./ui/reasoning.aui.js\";\nimport { TraceLine } from \"./ui/home-demo/trace-line.js\";\nimport type { AssistantBinding } from \"./assistant-runtime.js\";\nimport { attachmentAccept } from \"./attachments.js\";\nimport type { ChatProps } from \"./types.js\";\n\nexport function AttachmentTile({ binding, savedPreview }: { binding?: AssistantBinding; savedPreview?: string | undefined }) {\n const attachment = useAuiState((s) => s.attachment);\n const preview = binding?.attachments.preview(attachment.id) ?? savedPreview ?? attachment.content?.find((part) => part.type === \"image\")?.image;\n return <AttachmentUI preview={preview}>\n <div className={cn(\"flex max-w-40 flex-col text-xs wrap-anywhere\")}><AttachmentPrimitive.Name />\n {binding && attachment.status.type === \"requires-action\" ? <small className={cn(\"text-muted-foreground\")}>已就绪</small> : null}\n {attachment.status.type === \"running\" ? <small className={cn(\"text-muted-foreground\")}>正在处理…</small> : null}\n {attachment.status.type === \"incomplete\" ? <small className={cn(\"text-destructive\")} role=\"alert\">{attachment.status.message ?? \"附件处理失败\"}</small> : null}\n </div>\n </AttachmentUI>;\n}\n\nexport function AssistantComposer({ binding, options, placeholder, busy, cancelling, cancel }: {\n binding: AssistantBinding; options: ChatProps[\"attachments\"]; placeholder: string;\n busy: boolean; cancelling: boolean; cancel(): void;\n}) {\n const input = useRef<HTMLInputElement>(null);\n const sending = binding.sending;\n const showCancel = useAuiState((state) => busy && (state.thread.isRunning || state.composer.isEmpty));\n const addFiles = (files: File[]) => {\n for (const file of files) void binding.runtime.thread.composer.addAttachment(file).catch((error: unknown) => binding.setNotice(error instanceof Error ? error.message : String(error)));\n };\n return <Composer onSubmit={(event) => { event.preventDefault(); void binding.send(); }}\n inputProps={{ \"aria-label\": \"输入 Agent 任务\", placeholder, disabled: sending, cancelOnEscape: false,\n onKeyDown: (event) => { if (event.keyCode === 229) event.preventDefault(); else if (event.key === \"Enter\" && !event.shiftKey && !event.nativeEvent.isComposing) { event.preventDefault(); void binding.send(); } } }}\n actions={<>\n {options !== false ? <><input ref={input} type=\"file\" multiple disabled={sending} accept={options?.accept ?? attachmentAccept} hidden\n onChange={(event) => { addFiles(Array.from(event.target.files ?? [])); event.target.value = \"\"; }} />\n <button type=\"button\" className={cn(\"text-muted-foreground hover:text-foreground rounded-control grid size-7 shrink-0 place-items-center transition-colors\")} aria-label=\"添加附件\" disabled={sending} onClick={() => input.current?.click()}><PlusIcon className={cn(\"size-4\")} /></button></> : <span />}\n <div className={cn(\"flex shrink-0 items-center gap-1\")}>\n {showCancel ? <button type=\"button\" aria-label=\"取消任务\" className={cn(\"bg-primary text-primary-foreground rounded-control grid size-7 place-items-center\")} disabled={cancelling} onClick={cancel}><SquareIcon className={cn(\"size-3 fill-current\")} /></button> :\n <ComposerPrimitive.Send asChild disabled={sending}><button type=\"button\" onClick={(event) => { event.preventDefault(); void binding.send(); }} aria-label=\"发送任务\" className={cn(\"bg-primary text-primary-foreground rounded-control grid size-7 place-items-center transition-opacity disabled:opacity-40\")}><ArrowUpIcon className={cn(\"size-4\")} /></button></ComposerPrimitive.Send>}\n </div>\n </>}>\n <div className={cn(\"aui-composer-attachments flex w-full flex-row items-center gap-2 overflow-x-auto empty:hidden\")}><ComposerPrimitive.Attachments>{() => <AttachmentTile binding={binding} />}</ComposerPrimitive.Attachments></div>\n {sending ? <small role=\"status\">正在处理附件…</small> : null}\n </Composer>;\n}\n\nconst groupAssistantParts = groupPartByType({ reasoning: [\"group-chainOfThought\", \"group-reasoning\"], source: [\"group-chainOfThought\", \"group-source\"], \"tool-call\": [\"group-chainOfThought\", \"group-tool\"], \"standalone-tool-call\": [] });\nexport function AssistantParts({ showDetails, errors }: { showDetails: boolean; errors: readonly { id: string; message: string }[] }) {\n return <><MessagePrimitive.GroupedParts groupBy={groupAssistantParts}>{({ part, children }) => {\n switch (part.type) {\n case \"group-chainOfThought\": return <div className={cn(\"mb-3\")}>{children}</div>;\n case \"group-tool\": return part.indices.length === 1 ? <>{children}</> : <ToolGroupRoot variant=\"ghost\" className={cn(\"my-1\")}>\n <DisclosureTrigger live={part.status.type === \"running\"} label={part.status.type === \"running\" ? \"running\" : \"ran\"} detail={`${part.indices.length} tools`} />\n <ToolGroupContent className={cn(disclosureContentClass)}>{children}</ToolGroupContent>\n </ToolGroupRoot>;\n case \"group-reasoning\": return <ReasoningRoot variant=\"ghost\" streaming={part.status.type === \"running\"} className={cn(\"my-1 mb-3\")}>\n <DisclosureTrigger live={part.status.type === \"running\"} label={part.status.type === \"running\" ? \"thinking\" : \"reasoning\"} />\n <ReasoningContent aria-busy={part.status.type === \"running\"} className={cn(disclosureContentClass)}><ReasoningText className={cn(\"ps-0\")}>{children}</ReasoningText></ReasoningContent>\n </ReasoningRoot>;\n case \"reasoning\": return <Reasoning {...part} />;\n case \"group-source\":\n case \"source\": return null;\n case \"data\": return part.dataRendererUI;\n case \"text\": return part.text === \"\" && part.status?.type === \"running\" ? <TraceLine live label=\"thinking\" /> : <MarkdownText />;\n case \"tool-call\": return part.toolUI ?? <ToolCall {...part} showDetails={showDetails} />;\n case \"indicator\": return <TraceLine live label=\"thinking\" />;\n default: return null;\n }\n }}</MessagePrimitive.GroupedParts>{errors.map((error) => <p key={error.id} role=\"alert\" className={cn(\"mt-2 border-l-2 pl-3 text-[13px] border-destructive/60 text-destructive\")}>{error.message}</p>)}</>;\n}\n"]}
1
+ {"version":3,"file":"assistant-components.js","sourceRoot":"","sources":["../src/assistant-components.tsx"],"names":[],"mappings":";AACA,OAAO,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AACtD,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAkB,MAAM,OAAO,CAAC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QAAC,KAAK,EAAC,UAAU,GAAG,CAAC;oBAC7D,OAAO,CAAC,CAAC,OAAO,IAAI,CAAC;gBACvB,CAAC;YACH,CAAC,GAAiC,GAAG,CAAC;AACxC,CAAC","sourcesContent":["import type { UIMessagePart } from \"./messages.js\";\nimport { AttachmentUI } from \"./ui/attachment.aui.js\";\nimport { useEffect, useRef, useState, type ReactNode } from \"react\";\nimport { MarkdownText } from \"./ui/markdown-text.js\";\nimport { Composer } from \"./ui/home-demo/composer.js\";\nimport { cn } from \"./ui/utils.js\";\nimport { AttachmentPrimitive, ComposerPrimitive, useAuiState, MessagePrimitive, groupPartByType } from \"@assistant-ui/react\";\nimport { ArrowUpIcon, PlusIcon, SquareIcon } from \"lucide-react\";\nimport { ToolGroupRoot, ToolGroupContent } from \"./ui/tool-group.aui.js\";\nimport { DisclosureTrigger, ToolCall, disclosureContentClass } from \"./ui/home-demo/trace.js\";\nimport { Reasoning, ReasoningRoot, ReasoningContent, ReasoningText } from \"./ui/reasoning.aui.js\";\nimport { TraceLine } from \"./ui/home-demo/trace-line.js\";\nimport type { AssistantBinding } from \"./assistant-runtime.js\";\nimport { attachmentAccept } from \"./attachments.js\";\nimport type { ChatProps } from \"./types.js\";\n\nexport function AttachmentTile({ binding, savedPreview }: { binding?: AssistantBinding; savedPreview?: string | undefined }) {\n const attachment = useAuiState((s) => s.attachment);\n const preview = binding?.attachments.preview(attachment.id) ?? savedPreview ?? attachment.content?.find((part) => part.type === \"image\")?.image;\n return <AttachmentUI preview={preview}>\n <div className={cn(\"flex max-w-40 flex-col text-xs wrap-anywhere\")}><AttachmentPrimitive.Name />\n {binding && attachment.status.type === \"requires-action\" ? <small className={cn(\"text-muted-foreground\")}>已就绪</small> : null}\n {attachment.status.type === \"running\" ? <small className={cn(\"text-muted-foreground\")}>正在处理…</small> : null}\n {attachment.status.type === \"incomplete\" ? <small className={cn(\"text-destructive\")} role=\"alert\">{attachment.status.message ?? \"附件处理失败\"}</small> : null}\n </div>\n </AttachmentUI>;\n}\n\nexport function AssistantComposer({ binding, options, placeholder, busy, cancelling, cancel }: {\n binding: AssistantBinding; options: ChatProps[\"attachments\"]; placeholder: string;\n busy: boolean; cancelling: boolean; cancel(): void;\n}) {\n const input = useRef<HTMLInputElement>(null);\n const sending = binding.sending;\n const showCancel = useAuiState((state) => busy && (state.thread.isRunning || state.composer.isEmpty));\n const addFiles = (files: File[]) => {\n for (const file of files) void binding.runtime.thread.composer.addAttachment(file).catch((error: unknown) => binding.setNotice(error instanceof Error ? error.message : String(error)));\n };\n return <Composer onSubmit={(event) => { event.preventDefault(); void binding.send(); }}\n inputProps={{ \"aria-label\": \"输入 Agent 任务\", placeholder, disabled: sending, cancelOnEscape: false,\n onKeyDown: (event) => { if (event.keyCode === 229) event.preventDefault(); else if (event.key === \"Enter\" && !event.shiftKey && !event.nativeEvent.isComposing) { event.preventDefault(); void binding.send(); } } }}\n actions={<>\n {options !== false ? <><input ref={input} type=\"file\" multiple disabled={sending} accept={options?.accept ?? attachmentAccept} hidden\n onChange={(event) => { addFiles(Array.from(event.target.files ?? [])); event.target.value = \"\"; }} />\n <button type=\"button\" className={cn(\"text-muted-foreground hover:text-foreground rounded-control grid size-7 shrink-0 place-items-center transition-colors\")} aria-label=\"添加附件\" disabled={sending} onClick={() => input.current?.click()}><PlusIcon className={cn(\"size-4\")} /></button></> : <span />}\n <div className={cn(\"flex shrink-0 items-center gap-1\")}>\n {showCancel ? <button type=\"button\" aria-label=\"取消任务\" className={cn(\"bg-primary text-primary-foreground rounded-control grid size-7 place-items-center\")} disabled={cancelling} onClick={cancel}><SquareIcon className={cn(\"size-3 fill-current\")} /></button> :\n <ComposerPrimitive.Send asChild disabled={sending}><button type=\"button\" onClick={(event) => { event.preventDefault(); void binding.send(); }} aria-label=\"发送任务\" className={cn(\"bg-primary text-primary-foreground rounded-control grid size-7 place-items-center transition-opacity disabled:opacity-40\")}><ArrowUpIcon className={cn(\"size-4\")} /></button></ComposerPrimitive.Send>}\n </div>\n </>}>\n <div className={cn(\"aui-composer-attachments flex w-full flex-row items-center gap-2 overflow-x-auto empty:hidden\")}><ComposerPrimitive.Attachments>{() => <AttachmentTile binding={binding} />}</ComposerPrimitive.Attachments></div>\n {sending ? <small role=\"status\">正在处理附件…</small> : null}\n </Composer>;\n}\n\nfunction ToolGroup({ tools, running, count, children }: {\n tools: readonly UIMessagePart[]; running: boolean; count: number; children: ReactNode;\n}) {\n const errors = tools.flatMap((tool) => tool.type === \"tool\" && tool.error ? [tool.error] : []);\n const errorIds = JSON.stringify(errors.map((error) => error.id));\n const hasErrors = errors.length > 0;\n const [open, setOpen] = useState(hasErrors);\n useEffect(() => {\n if (errorIds !== \"[]\") setOpen(true);\n }, [errorIds]);\n const unknown = hasErrors && errors.every((error) => error.scope === \"tool\" && error.execution === \"unknown\");\n return <ToolGroupRoot variant=\"ghost\" className={cn(\"my-1\")} open={open} onOpenChange={setOpen}>\n <DisclosureTrigger live={running && !hasErrors} label={hasErrors ? unknown ? \"Result unknown\" : \"Failed\" : running ? \"running\" : \"ran\"} detail={`${count} tools`} />\n <ToolGroupContent className={cn(disclosureContentClass)}>{children}</ToolGroupContent>\n </ToolGroupRoot>;\n}\n\nconst groupAssistantParts = groupPartByType({ reasoning: [\"group-chainOfThought\", \"group-reasoning\"], source: [\"group-chainOfThought\", \"group-source\"], \"tool-call\": [\"group-chainOfThought\", \"group-tool\"], \"standalone-tool-call\": [] });\nexport function AssistantParts({ showDetails, tools = [] }: { showDetails: boolean; tools?: readonly UIMessagePart[] }) {\n return <><MessagePrimitive.GroupedParts groupBy={groupAssistantParts}>{({ part, children }) => {\n switch (part.type) {\n case \"group-chainOfThought\": return <div className={cn(\"mb-3\")}>{children}</div>;\n case \"group-tool\": return part.indices.length === 1 ? <>{children}</> : <ToolGroup\n tools={tools.filter((_, index) => part.indices.includes(index))} running={part.status.type === \"running\"} count={part.indices.length}>\n {children}\n </ToolGroup>;\n case \"group-reasoning\": return <ReasoningRoot variant=\"ghost\" streaming={part.status.type === \"running\"} className={cn(\"my-1 mb-3\")}>\n <DisclosureTrigger live={part.status.type === \"running\"} label={part.status.type === \"running\" ? \"thinking\" : \"reasoning\"} />\n <ReasoningContent aria-busy={part.status.type === \"running\"} className={cn(disclosureContentClass)}><ReasoningText className={cn(\"ps-0\")}>{children}</ReasoningText></ReasoningContent>\n </ReasoningRoot>;\n case \"reasoning\": return <Reasoning {...part} />;\n case \"group-source\":\n case \"source\": return null;\n case \"data\": return part.dataRendererUI;\n case \"text\": return part.text === \"\" && part.status?.type === \"running\" ? <TraceLine live label=\"thinking\" /> : <MarkdownText />;\n case \"tool-call\": return part.toolUI ?? <ToolCall {...part} showDetails={showDetails} presentation={tools.find((tool) => tool.type === \"tool\" && tool.toolCallId === part.toolCallId)} />;\n case \"indicator\": return <TraceLine live label=\"thinking\" />;\n default: return null;\n }\n }}</MessagePrimitive.GroupedParts></>;\n}\n"]}
@@ -20,8 +20,10 @@ export function convertMessage(message) {
20
20
  });
21
21
  if (message.role === "user")
22
22
  return { id: message.id, role: "user", content, attachments: message.attachments?.map(toAssistantAttachment) };
23
- return { id: message.id, role: "assistant", content, status: message.state === "running"
24
- ? { type: "running" } : message.state === "error" ? { type: "incomplete", reason: "error" } : { type: "complete", reason: "stop" } };
23
+ return { id: message.id, role: "assistant", content, status: message.error
24
+ ? { type: "incomplete", reason: "error", error: message.error.userMessage }
25
+ : message.state === "cancelled" ? { type: "incomplete", reason: "cancelled" }
26
+ : message.state === "running" ? { type: "running" } : { type: "complete", reason: "stop" } };
25
27
  }
26
28
  // Project each user turn to one assistant row without changing persisted messages.
27
29
  export function projectMessages(messages) {
@@ -29,7 +31,7 @@ export function projectMessages(messages) {
29
31
  for (const message of messages) {
30
32
  const previous = projected.at(-1);
31
33
  if (message.role === "assistant" && previous?.role === "assistant") {
32
- projected[projected.length - 1] = { ...previous, parts: [...previous.parts, ...message.parts], ...(message.state ? { state: message.state } : {}) };
34
+ projected[projected.length - 1] = { ...previous, parts: [...previous.parts, ...message.parts], ...(message.state ? { state: message.state } : {}), ...(message.error ? { error: message.error } : {}) };
33
35
  }
34
36
  else
35
37
  projected.push(message);
@@ -1 +1 @@
1
- {"version":3,"file":"assistant-runtime.js","sourceRoot":"","sources":["../src/assistant-runtime.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAE,SAAS,EAAE,eAAe,EAAE,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAkB,MAAM,OAAO,CAAC;AACjG,OAAO,EAAE,wBAAwB,EAAE,mBAAmB,EAAE,uBAAuB,EAAgF,MAAM,qBAAqB,CAAC;AAC3L,OAAO,EAAE,oBAAoB,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AACzF,OAAO,EAAE,kBAAkB,EAAgC,MAAM,YAAY,CAAC;AAM9E,SAAS,aAAa,CAAC,IAAY;IACjC,IAAI,CAAC;QACH,MAAM,KAAK,GAAY,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QACxC,OAAO,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAyC,CAAC,CAAC,CAAC,EAAE,CAAC;IAC/H,CAAC;IAAC,MAAM,CAAC;QAAC,OAAO,EAAE,CAAC;IAAC,CAAC;AACxB,CAAC;AAED,MAAM,UAAU,cAAc,CAAC,OAAkB;IAC/C,MAAM,OAAO,GAAG,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAyD,EAAE,CAAC,IAAI,CAAC,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC;QAC/H,IAAI,EAAE,WAAW,EAAE,UAAU,EAAE,IAAI,CAAC,UAAU,EAAE,QAAQ,EAAE,IAAI,CAAC,IAAI;QACnE,IAAI,EAAE,aAAa,CAAC,IAAI,CAAC,SAAS,CAAC;QACnC,QAAQ,EAAE,IAAI,CAAC,SAAS,EAAE,M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CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;QAC1J,CAAC;gBAAS,CAAC;YACT,QAAQ,CAAC,OAAO,GAAG,KAAK,CAAC;YACzB,IAAI,KAAK,CAAC,OAAO;gBAAE,UAAU,CAAC,KAAK,CAAC,CAAC;QACvC,CAAC;IACH,CAAC,CAAC;IACF,OAAO,KAAC,wBAAwB,IAAC,OAAO,EAAE,OAAO,YAAG,MAAM,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,SAAS,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,GAA4B,CAAC;AACvK,CAAC","sourcesContent":["import { useEffect, useLayoutEffect, useReducer, useRef, useState, type ReactNode } from \"react\";\nimport { AssistantRuntimeProvider, MessageNotSentError, useExternalStoreRuntime, type AssistantRuntime, type ThreadMessageLike, type ToolCallMessagePartProps } from \"@assistant-ui/react\";\nimport { AssistantAttachments, toAssistantAttachment } from \"./assistant-attachments.js\";\nimport { assertChatSendable, type useChat, type UIMessage } from \"./react.js\";\nimport type { ChatProps } from \"./types.js\";\n\ntype ChatState = ReturnType<typeof useChat>;\nexport type AssistantBinding = { runtime: AssistantRuntime; attachments: AssistantAttachments; notice: string; setNotice(message: string): void; sending: boolean; send(): Promise<void> };\n\nfunction parseToolArgs(text: string): ToolCallMessagePartProps[\"args\"] {\n try {\n const value: unknown = JSON.parse(text);\n return value !== null && typeof value === \"object\" && !Array.isArray(value) ? value as ToolCallMessagePartProps[\"args\"] : {};\n } catch { return {}; }\n}\n\nexport function convertMessage(message: UIMessage): ThreadMessageLike {\n const content = message.parts.map((part): Exclude<ThreadMessageLike[\"content\"], string>[number] => part.type !== \"tool\" ? part : {\n type: \"tool-call\", toolCallId: part.toolCallId, toolName: part.name,\n args: parseToolArgs(part.arguments),\n argsText: part.arguments, result: part.result, isError: part.isError,\n });\n if (message.role === \"user\") return { id: message.id, role: \"user\", content, attachments: message.attachments?.map(toAssistantAttachment) };\n return { id: message.id, role: \"assistant\", content, status: message.state === \"running\"\n ? { type: \"running\" } : message.state === \"error\" ? { type: \"incomplete\", reason: \"error\" } : { type: \"complete\", reason: \"stop\" } };\n}\n\n// Project each user turn to one assistant row without changing persisted messages.\nexport function projectMessages(messages: readonly UIMessage[]): UIMessage[] {\n const projected: UIMessage[] = [];\n for (const message of messages) {\n const previous = projected.at(-1);\n if (message.role === \"assistant\" && previous?.role === \"assistant\") {\n projected[projected.length - 1] = { ...previous, parts: [...previous.parts, ...message.parts], ...(message.state ? { state: message.state } : {}) };\n } else projected.push(message);\n }\n return projected;\n}\n\n// Keep one composer per visited Session: switching the external-store thread id\n// would invalidate pending attachment work and discard that Session's draft.\nexport function SessionRuntime({ id, chat, options, blocked, active, onEdit, children }: {\n id: string; chat: ChatState; options: ChatProps[\"attachments\"]; blocked: boolean; active: boolean;\n onEdit?(sourceId: string, text: string): Promise<void>;\n children(binding: AssistantBinding): ReactNode;\n}) {\n const latest = useRef(chat);\n useLayoutEffect(() => { latest.current = chat; });\n const messages = useRef<readonly UIMessage[]>([]);\n if (chat.activeSessionId === id) messages.current = chat.messages;\n const [, refresh] = useReducer((n: number) => n + 1, 0);\n const [notice, setNotice] = useState(\"\");\n const [sending, setSending] = useState(false);\n const sendLock = useRef(false);\n const [attachments] = useState(() => new AssistantAttachments(refresh, setNotice));\n attachments.options = options ?? {};\n const alive = useRef(false);\n useEffect(() => {\n alive.current = true;\n return () => {\n alive.current = false;\n queueMicrotask(() => { if (!alive.current) attachments.dispose(); });\n };\n }, [attachments]);\n const runtime = useExternalStoreRuntime<UIMessage>({\n messages: projectMessages(messages.current),\n convertMessage,\n isRunning: active && chat.status !== \"idle\" && chat.status !== \"error\" && chat.status !== \"waiting\",\n isSendDisabled: !active || blocked || attachments.blocked,\n onNew: async (message) => {\n if (!alive.current || latest.current.activeSessionId !== id) throw new MessageNotSentError(\"会话已切换,请返回原会话重新发送。\");\n const files = attachments.take(message.attachments ?? []);\n const text = message.content.flatMap((part) => part.type === \"text\" ? [part.text] : []).join(\"\");\n attachments.commit(message.attachments ?? []);\n setNotice(\"\");\n await latest.current.sendMessage(text, files);\n },\n onEdit: onEdit ? async (message) => {\n if (!message.sourceId) throw new Error(\"未找到要编辑的消息。\");\n const text = message.content.flatMap((part) => part.type === \"text\" ? [part.text] : []).join(\"\");\n try {\n await onEdit(message.sourceId, text);\n } catch {\n const sourceId = message.sourceId;\n queueMicrotask(() => {\n if (!alive.current || latest.current.activeSessionId !== id) return;\n const composer = runtime.thread.getMessageById(sourceId).composer;\n if (!composer.getState().isEditing) composer.beginEdit();\n composer.setText(text);\n });\n }\n } : undefined,\n onCancel: async () => { latest.current.cancel(); },\n adapters: {\n attachments: options === false ? undefined : attachments,\n threadList: {\n threadId: id,\n threads: chat.sessions.map((session) => ({ id: session.id, title: session.title, status: \"regular\" as const })),\n onSwitchToNewThread: () => { latest.current.createSession(); },\n onSwitchToThread: (next) => latest.current.switchSession(next),\n onRename: (target, title) => latest.current.renameSession(target, title),\n onDelete: (target) => latest.current.deleteSession(target),\n },\n },\n });\n const send = async () => {\n const draft = runtime.thread.composer.getState();\n if (!active || blocked || attachments.blocked || sendLock.current || draft.isEmpty) return;\n sendLock.current = true;\n setSending(true);\n setNotice(\"\");\n try {\n // Prepare before dispatch: the upstream void send API cannot report upload\n // rejections to its caller. Keep the draft intact until every file settles.\n const results = await Promise.allSettled(draft.attachments.map((attachment) => attachments.send(attachment)));\n const failed = results.find((result) => result.status === \"rejected\");\n if (failed?.status === \"rejected\") throw failed.reason;\n if (!alive.current) return;\n if (latest.current.activeSessionId !== id) throw new Error(\"会话已切换,请返回原会话重新发送。\");\n assertChatSendable(latest.current, id);\n const completed = results.flatMap((result) => result.status === \"fulfilled\" ? [result.value] : []);\n const files = attachments.take(completed);\n attachments.commit(completed);\n runtime.thread.composer.reset();\n void latest.current.sendMessage(draft.text, files).catch(() => undefined);\n } catch (error) {\n if (alive.current && !(error instanceof DOMException && error.name === \"AbortError\")) setNotice(error instanceof Error ? error.message : String(error));\n } finally {\n sendLock.current = false;\n if (alive.current) setSending(false);\n }\n };\n return <AssistantRuntimeProvider runtime={runtime}>{active ? children({ runtime, attachments, notice, setNotice, sending, send }) : null}</AssistantRuntimeProvider>;\n}\n"]}
1
+ {"version":3,"file":"assistant-runtime.js","sourceRoot":"","sources":["../src/assistant-runtime.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAE,SAAS,EAAE,eAAe,EAAE,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAkB,MAAM,OAAO,CAAC;AACjG,OAAO,EAAE,wBAAwB,EAAE,mBAAmB,EAAE,uBAAuB,EAAgF,MAAM,qBAAqB,CAAC;AAC3L,OAAO,EAAE,oBAAoB,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AACzF,OAAO,EAAE,kBAAkB,EAAgC,MAAM,YAAY,CAAC;AAM9E,SAAS,aAAa,CAAC,IAAY;IACjC,IAAI,CAAC;QACH,MAAM,KAAK,GAAY,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QACxC,OAAO,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAyC,CAAC,CAAC,CAAC,EAAE,CAAC;IAC/H,CAAC;IAAC,MAAM,CAAC;QAAC,OAAO,EAAE,CAAC;IAAC,CAAC;AACxB,CAAC;AAED,MAAM,UAAU,cAAc,CAAC,OAAkB;IAC/C,MAAM,OAAO,GAAG,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAyD,EAAE,CAAC,IAAI,CAAC,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC;QAC/H,IAAI,EAAE,WAAW,EAAE,UAAU,EAAE,IAAI,CAAC,UAAU,EAAE,QAAQ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AAC,CAAC;YAC9B,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC;YAChC,KAAK,MAAM,CAAC,OAAO,CAAC,WAAW,CAAC,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;QAC5E,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,KAAK,CAAC,OAAO,IAAI,CAAC,CAAC,KAAK,YAAY,YAAY,IAAI,KAAK,CAAC,IAAI,KAAK,YAAY,CAAC;gBAAE,SAAS,CAAC,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;QAC1J,CAAC;gBAAS,CAAC;YACT,QAAQ,CAAC,OAAO,GAAG,KAAK,CAAC;YACzB,IAAI,KAAK,CAAC,OAAO;gBAAE,UAAU,CAAC,KAAK,CAAC,CAAC;QACvC,CAAC;IACH,CAAC,CAAC;IACF,OAAO,KAAC,wBAAwB,IAAC,OAAO,EAAE,OAAO,YAAG,MAAM,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,SAAS,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,GAA4B,CAAC;AACvK,CAAC","sourcesContent":["import { useEffect, useLayoutEffect, useReducer, useRef, useState, type ReactNode } from \"react\";\nimport { AssistantRuntimeProvider, MessageNotSentError, useExternalStoreRuntime, type AssistantRuntime, type ThreadMessageLike, type ToolCallMessagePartProps } from \"@assistant-ui/react\";\nimport { AssistantAttachments, toAssistantAttachment } from \"./assistant-attachments.js\";\nimport { assertChatSendable, type useChat, type UIMessage } from \"./react.js\";\nimport type { ChatProps } from \"./types.js\";\n\ntype ChatState = ReturnType<typeof useChat>;\nexport type AssistantBinding = { runtime: AssistantRuntime; attachments: AssistantAttachments; notice: string; setNotice(message: string): void; sending: boolean; send(): Promise<void> };\n\nfunction parseToolArgs(text: string): ToolCallMessagePartProps[\"args\"] {\n try {\n const value: unknown = JSON.parse(text);\n return value !== null && typeof value === \"object\" && !Array.isArray(value) ? value as ToolCallMessagePartProps[\"args\"] : {};\n } catch { return {}; }\n}\n\nexport function convertMessage(message: UIMessage): ThreadMessageLike {\n const content = message.parts.map((part): Exclude<ThreadMessageLike[\"content\"], string>[number] => part.type !== \"tool\" ? part : {\n type: \"tool-call\", toolCallId: part.toolCallId, toolName: part.name,\n args: parseToolArgs(part.arguments),\n argsText: part.arguments, result: part.result, isError: part.isError,\n });\n if (message.role === \"user\") return { id: message.id, role: \"user\", content, attachments: message.attachments?.map(toAssistantAttachment) };\n return { id: message.id, role: \"assistant\", content, status: message.error\n ? { type: \"incomplete\", reason: \"error\", error: message.error.userMessage }\n : message.state === \"cancelled\" ? { type: \"incomplete\", reason: \"cancelled\" }\n : message.state === \"running\" ? { type: \"running\" } : { type: \"complete\", reason: \"stop\" } };\n}\n\n// Project each user turn to one assistant row without changing persisted messages.\nexport function projectMessages(messages: readonly UIMessage[]): UIMessage[] {\n const projected: UIMessage[] = [];\n for (const message of messages) {\n const previous = projected.at(-1);\n if (message.role === \"assistant\" && previous?.role === \"assistant\") {\n projected[projected.length - 1] = { ...previous, parts: [...previous.parts, ...message.parts], ...(message.state ? { state: message.state } : {}), ...(message.error ? { error: message.error } : {}) };\n } else projected.push(message);\n }\n return projected;\n}\n\n// Keep one composer per visited Session: switching the external-store thread id\n// would invalidate pending attachment work and discard that Session's draft.\nexport function SessionRuntime({ id, chat, options, blocked, active, onEdit, children }: {\n id: string; chat: ChatState; options: ChatProps[\"attachments\"]; blocked: boolean; active: boolean;\n onEdit?(sourceId: string, text: string): Promise<void>;\n children(binding: AssistantBinding): ReactNode;\n}) {\n const latest = useRef(chat);\n useLayoutEffect(() => { latest.current = chat; });\n const messages = useRef<readonly UIMessage[]>([]);\n if (chat.activeSessionId === id) messages.current = chat.messages;\n const [, refresh] = useReducer((n: number) => n + 1, 0);\n const [notice, setNotice] = useState(\"\");\n const [sending, setSending] = useState(false);\n const sendLock = useRef(false);\n const [attachments] = useState(() => new AssistantAttachments(refresh, setNotice));\n attachments.options = options ?? {};\n const alive = useRef(false);\n useEffect(() => {\n alive.current = true;\n return () => {\n alive.current = false;\n queueMicrotask(() => { if (!alive.current) attachments.dispose(); });\n };\n }, [attachments]);\n const runtime = useExternalStoreRuntime<UIMessage>({\n messages: projectMessages(messages.current),\n convertMessage,\n isRunning: active && chat.status !== \"idle\" && chat.status !== \"error\" && chat.status !== \"waiting\",\n isSendDisabled: !active || blocked || attachments.blocked,\n onNew: async (message) => {\n if (!alive.current || latest.current.activeSessionId !== id) throw new MessageNotSentError(\"会话已切换,请返回原会话重新发送。\");\n const files = attachments.take(message.attachments ?? []);\n const text = message.content.flatMap((part) => part.type === \"text\" ? [part.text] : []).join(\"\");\n attachments.commit(message.attachments ?? []);\n setNotice(\"\");\n await latest.current.sendMessage(text, files);\n },\n onEdit: onEdit ? async (message) => {\n if (!message.sourceId) throw new Error(\"未找到要编辑的消息。\");\n const text = message.content.flatMap((part) => part.type === \"text\" ? [part.text] : []).join(\"\");\n try {\n await onEdit(message.sourceId, text);\n } catch {\n const sourceId = message.sourceId;\n queueMicrotask(() => {\n if (!alive.current || latest.current.activeSessionId !== id) return;\n const composer = runtime.thread.getMessageById(sourceId).composer;\n if (!composer.getState().isEditing) composer.beginEdit();\n composer.setText(text);\n });\n }\n } : undefined,\n onCancel: async () => { latest.current.cancel(); },\n adapters: {\n attachments: options === false ? undefined : attachments,\n threadList: {\n threadId: id,\n threads: chat.sessions.map((session) => ({ id: session.id, title: session.title, status: \"regular\" as const })),\n onSwitchToNewThread: () => { latest.current.createSession(); },\n onSwitchToThread: (next) => latest.current.switchSession(next),\n onRename: (target, title) => latest.current.renameSession(target, title),\n onDelete: (target) => latest.current.deleteSession(target),\n },\n },\n });\n const send = async () => {\n const draft = runtime.thread.composer.getState();\n if (!active || blocked || attachments.blocked || sendLock.current || draft.isEmpty) return;\n sendLock.current = true;\n setSending(true);\n setNotice(\"\");\n try {\n // Prepare before dispatch: the upstream void send API cannot report upload\n // rejections to its caller. Keep the draft intact until every file settles.\n const results = await Promise.allSettled(draft.attachments.map((attachment) => attachments.send(attachment)));\n const failed = results.find((result) => result.status === \"rejected\");\n if (failed?.status === \"rejected\") throw failed.reason;\n if (!alive.current) return;\n if (latest.current.activeSessionId !== id) throw new Error(\"会话已切换,请返回原会话重新发送。\");\n assertChatSendable(latest.current, id);\n const completed = results.flatMap((result) => result.status === \"fulfilled\" ? [result.value] : []);\n const files = attachments.take(completed);\n attachments.commit(completed);\n runtime.thread.composer.reset();\n void latest.current.sendMessage(draft.text, files).catch(() => undefined);\n } catch (error) {\n if (alive.current && !(error instanceof DOMException && error.name === \"AbortError\")) setNotice(error instanceof Error ? error.message : String(error));\n } finally {\n sendLock.current = false;\n if (alive.current) setSending(false);\n }\n };\n return <AssistantRuntimeProvider runtime={runtime}>{active ? children({ runtime, attachments, notice, setNotice, sending, send }) : null}</AssistantRuntimeProvider>;\n}\n"]}
package/dist/client.d.ts CHANGED
@@ -3,6 +3,7 @@ import type { ToolRuntime } from "@nexface/tools";
3
3
  import { type Message } from "@ag-ui/core";
4
4
  import { type ProtocolEvent } from "./protocol-messages.js";
5
5
  import { type NexfaceAgentConfig } from "./config.js";
6
+ import { type NexfaceErrorEvent } from "./errors.js";
6
7
  import { type UIMessage } from "./messages.js";
7
8
  export type { Message } from "@ag-ui/core";
8
9
  export type { ProtocolEvent } from "./protocol-messages.js";
@@ -14,6 +15,7 @@ export type RunHandler = (input: RunAgentInput, options: {
14
15
  }) => Promise<Response>;
15
16
  export type ChatClientOptions = {
16
17
  toolRuntime: ToolRuntime;
18
+ onError?: (event: NexfaceErrorEvent) => void;
17
19
  } & ({
18
20
  agent: NexfaceAgentConfig;
19
21
  run?: never;
@@ -60,6 +62,7 @@ declare class ChatClientImplementation implements ChatClient {
60
62
  getStatus: () => ChatClientStatus;
61
63
  getApproval: () => ToolApprovalInterruptDescriptor | undefined;
62
64
  getError: () => Error | undefined;
65
+ assertRecoveryAvailable(): void;
63
66
  subscribe: (listener: () => void) => (() => void);
64
67
  subscribeEvents: (listener: (event: ProtocolEvent) => void) => (() => void);
65
68
  get cancelling(): boolean;
package/dist/client.js CHANGED
@@ -3,8 +3,9 @@ import { decodeAgentResponse } from "./protocol-response.js";
3
3
  import { isToolRuntimeError } from "@nexface/tools";
4
4
  import { getInternalToolRuntime, validateAgentToolInput } from "@nexface/tools/internal";
5
5
  import { EventType, EventSchemas, RunAgentInputSchema, TextInputContentSchema, ImageInputContentSchema } from "@ag-ui/core";
6
- import { createMessageUpdater, restoreMessages, settleApproval } from "./protocol-messages.js";
6
+ import { createMessageUpdater, restoreMessages, settleApproval, projectMessages } from "./protocol-messages.js";
7
7
  import { resolveModelConfig } from "./config.js";
8
+ import { markErrorPresented, runError, toolError } from "./errors.js";
8
9
  const controllerSymbol = Symbol.for("@nexface/agent/chat-controller");
9
10
  const agentController = (agent) => agent[controllerSymbol];
10
11
  const id = () => globalThis.crypto.randomUUID();
@@ -65,6 +66,11 @@ class ChatClientImplementation {
65
66
  #hasPageHook = (_name) => false;
66
67
  #cancelled = false;
67
68
  #executingBrowserCall;
69
+ #runId;
70
+ #failureId = "";
71
+ #reported = new Set();
72
+ #toolCauses = new Map();
73
+ #runtimeCauses = new Map();
68
74
  constructor(options, model) {
69
75
  if (!options?.toolRuntime || Boolean(options.agent) === Boolean(options.run))
70
76
  throw new ClientError("INVALID_INPUT", "Provide exactly one agent config or run function and a ToolRuntime.");
@@ -78,6 +84,10 @@ class ChatClientImplementation {
78
84
  getStatus = () => this.#status;
79
85
  getApproval = () => this.#approval;
80
86
  getError = () => this.#error;
87
+ assertRecoveryAvailable() {
88
+ if (this.#recoveryUnavailable)
89
+ throw new ClientError("CHAT_RECOVERY_UNAVAILABLE", "This chat cannot continue. Check the action results, then start a new chat.");
90
+ }
81
91
  subscribe = (listener) => { this.#listeners.add(listener); return () => { this.#listeners.delete(listener); }; };
82
92
  subscribeEvents = (listener) => { this.#eventListeners.add(listener); return () => { this.#eventListeners.delete(listener); }; };
83
93
  #publish() {
@@ -130,10 +140,56 @@ class ChatClientImplementation {
130
140
  this.#model = model;
131
141
  this.#publish();
132
142
  }
143
+ #report(error, cause) {
144
+ if (this.#reported.has(error.id))
145
+ return;
146
+ this.#reported.add(error.id);
147
+ try {
148
+ const result = this.#options.onError?.({ cause, code: error.code, ...(error.scope === "tool" ? { toolCallId: error.toolCallId } : {}), sessionId: this.id, ...(this.#runId ? { runId: this.#runId } : {}) });
149
+ // Also contain rejected promises from async diagnostic callbacks.
150
+ void Promise.resolve(result).catch(() => undefined);
151
+ }
152
+ catch { /* Diagnostics must not affect task execution. */ }
153
+ }
133
154
  #event(event) {
155
+ if (event.type === EventType.RUN_STARTED)
156
+ this.#runId = event.runId;
157
+ if (event.type === EventType.TOOL_CALL_RESULT) {
158
+ const owner = [...this.#messages].reverse().find((message) => message.role === "assistant" && message.toolCalls?.some((call) => call.id === event.toolCallId));
159
+ const call = owner?.role === "assistant" ? owner.toolCalls?.find((call) => call.id === event.toolCallId) : undefined;
160
+ let name = call?.function.name;
161
+ if (name === "nxf_callAppTool")
162
+ try {
163
+ name = JSON.parse(call.function.arguments).name;
164
+ }
165
+ catch { /* Incomplete calls have no local diagnostic. */ }
166
+ const presentation = toolError(event.messageId, event.toolCallId, event.content, event.metadata?.nexface?.parentErrorId, false, name);
167
+ const localCause = presentation.toolState && name ? this.#runtimeCauses.get(name)?.shift() : undefined;
168
+ if (presentation.toolState === "cancelled" && localCause !== undefined) {
169
+ // Cancellation after execution began cannot prove that effects were undone.
170
+ event = { ...event, metadata: { ...event.metadata, nexface: { ...event.metadata?.nexface, executionUnknown: true, parentErrorId: this.#failureId } } };
171
+ }
172
+ if (presentation.error && !presentation.error.parentErrorId)
173
+ this.#report(presentation.error, this.#toolCauses.get(event.toolCallId) ?? localCause ?? presentation.cause);
174
+ this.#toolCauses.delete(event.toolCallId);
175
+ }
134
176
  if (event.type === EventType.RUN_STARTED || event.type === EventType.RUN_FINISHED)
135
177
  event = { ...event, threadId: this.id };
136
178
  this.#messages = this.#updateMessages(this.#messages, event);
179
+ if (event.type === EventType.MESSAGES_SNAPSHOT) {
180
+ const receipts = new Map(event.messages.filter((message) => message.role === "tool").map((message) => [message.id, message]));
181
+ for (const message of projectMessages(this.#messages))
182
+ for (const part of message.parts) {
183
+ if (part.type !== "tool" || !part.error || part.error.parentErrorId || this.#reported.has(part.error.id))
184
+ continue;
185
+ const receipt = receipts.get(part.error.id);
186
+ if (!receipt)
187
+ continue;
188
+ const diagnostic = toolError(receipt.id, part.toolCallId, receipt.content, undefined, false, part.name).cause ?? receipt.error;
189
+ this.#report(part.error, this.#toolCauses.get(part.toolCallId) ?? this.#runtimeCauses.get(part.name)?.shift() ?? diagnostic);
190
+ this.#toolCauses.delete(part.toolCallId);
191
+ }
192
+ }
137
193
  if (event.type === EventType.TOOL_CALL_RESULT) {
138
194
  this.#settled.get(event.toolCallId)?.();
139
195
  this.#settled.delete(event.toolCallId);
@@ -223,6 +279,13 @@ class ChatClientImplementation {
223
279
  this.#executingBrowserCall = undefined;
224
280
  this.#status = "running";
225
281
  this.#error = undefined;
282
+ this.#failureId = id();
283
+ this.#runId = undefined;
284
+ // Complete snapshots include older turns; they must not re-emit diagnostics.
285
+ this.#reported = new Set(projectMessages(this.#messages).flatMap((message) => [
286
+ ...(message.error ? [message.error.id] : []),
287
+ ...message.parts.flatMap((part) => part.type === "tool" && part.error ? [part.error.id] : []),
288
+ ]));
226
289
  this.#messages = [...this.#messages, { id: userId, role: "user", content: typeof content === "string" ? content : [...content], ...(userMessage ? { metadata: { nexface: { restoredParts: userMessage.parts, attachments: userMessage.attachments ?? [], revisionOf: userMessage.revisionOf } } } : {}) }];
227
290
  const runtime = getInternalToolRuntime(this.runtime);
228
291
  const operationId = runtime.getActivitySnapshot().operation?.id;
@@ -231,6 +294,13 @@ class ChatClientImplementation {
231
294
  if (operation && operation.id === operationId && operation.status === "cancelling" && !controller.signal.aborted)
232
295
  this.cancel();
233
296
  });
297
+ const unsubscribeExecution = this.runtime.on("toolexecution", (event) => {
298
+ if (event.status !== "error")
299
+ return;
300
+ const causes = this.#runtimeCauses.get(event.name) ?? [];
301
+ causes.push(event.error);
302
+ this.#runtimeCauses.set(event.name, causes);
303
+ });
234
304
  let succeeded = false;
235
305
  try {
236
306
  this.#publish();
@@ -250,14 +320,29 @@ class ChatClientImplementation {
250
320
  failure = failure.failure;
251
321
  const record = failure;
252
322
  this.#error = failure instanceof Error ? failure : Object.assign(new Error(typeof record?.message === "string" ? record.message : String(failure)), { name: typeof record?.name === "string" ? record.name : "Error", ...(typeof record?.code === "string" ? { code: record.code } : {}) });
253
- const text = controller.signal.aborted ? "任务已取消。" : this.#error.message;
254
- this.#messages = [
255
- ...this.#messages.map((message) => message.metadata?.nexface?.state === "running" ? { ...message, metadata: { ...message.metadata, nexface: { ...message.metadata.nexface, state: "error" } } } : message),
256
- { id: id(), role: "assistant", content: text, metadata: { nexface: { state: "error" } } },
257
- ];
258
- throw this.#error;
323
+ const cancelled = controller.signal.aborted;
324
+ const lastUser = this.#messages.reduce((last, message, index) => message.role === "user" ? index : last, -1);
325
+ const current = this.#messages.slice(lastUser + 1);
326
+ const unknownTools = projectMessages(current).some((message) => message.parts.some((part) => part.type === "tool" && part.toolState === "unknown"));
327
+ const error = cancelled ? undefined : runError(this.#failureId, failure, unknownTools);
328
+ this.#messages = this.#messages.map((message, index) => index > lastUser && message.metadata?.nexface?.state === "running"
329
+ ? { ...message, metadata: { ...message.metadata, nexface: { ...message.metadata.nexface, state: cancelled ? "cancelled" : "error" } } } : message);
330
+ // A display-only row carries the terminal state without inventing model text.
331
+ this.#messages.push({ id: id(), role: "assistant", content: "", metadata: { nexface: {
332
+ displayOnly: true, state: cancelled ? "cancelled" : "error", ...(error ? { error } : {}),
333
+ } } });
334
+ const rejection = this.#error;
335
+ markErrorPresented(rejection);
336
+ if (cancelled)
337
+ this.#error = undefined;
338
+ else if (error)
339
+ this.#report(error, failure);
340
+ throw rejection;
259
341
  }
260
342
  finally {
343
+ unsubscribeExecution();
344
+ this.#toolCauses.clear();
345
+ this.#runtimeCauses.clear();
261
346
  unsubscribe();
262
347
  this.#pending?.cleanup();
263
348
  this.#pending = undefined;
@@ -363,7 +448,9 @@ class ChatClientImplementation {
363
448
  const approval = this.#approval;
364
449
  if (!approval)
365
450
  return;
366
- this.#messages = settleApproval(this.#messages, approval, "TOOL_CONFIRMATION_INVALIDATED", message, "binding_changed");
451
+ const previousIds = new Set(this.#messages.map((item) => item.id));
452
+ this.#messages = settleApproval(this.#messages, approval, "TOOL_CONFIRMATION_INVALIDATED", message, "binding_changed")
453
+ .map((item) => previousIds.has(item.id) ? item : { ...item, metadata: { ...item.metadata, nexface: { ...item.metadata?.nexface, parentErrorId: this.#failureId } } });
367
454
  if (this.agent) {
368
455
  agentController(this.agent).settle(approval.id, { type: "invalidate", message, reason: "binding_changed" }, this.#messages);
369
456
  }
@@ -417,8 +504,9 @@ class ChatClientImplementation {
417
504
  const catalog = [...this.runtime.getTools()];
418
505
  const contexts = await this.runtime.getContexts({ signal });
419
506
  const runId = id();
507
+ this.#runId = runId;
420
508
  const input = {
421
- threadId: this.id, runId, messages: this.#messages, state: this.#state ?? null,
509
+ threadId: this.id, runId, messages: this.#messages.filter((message) => !message.metadata?.nexface?.displayOnly), state: this.#state ?? null,
422
510
  ...(resume ? { resume } : {}),
423
511
  tools: catalog.map(({ definition }) => ({ name: definition.name, description: definition.description, parameters: definition.inputSchema ?? { type: "object", properties: {} } })),
424
512
  context: contexts.map((context) => ({ description: context.description ?? context.name, value: JSON.stringify(context) })),
@@ -433,16 +521,13 @@ class ChatClientImplementation {
433
521
  const response = await abortable(this.#runHandler(input, { signal }), signal);
434
522
  if (!response.ok || !response.body)
435
523
  throw new ClientError("CHAT_REQUEST_FAILED", `Agent request failed (${response.status}).`);
524
+ let terminal;
436
525
  let terminalEvent;
437
526
  let messageSnapshot;
438
527
  let stateSnapshot;
439
528
  let started = false;
440
529
  for await (const event of readEvents(response, signal)) {
441
530
  if (event.type === EventType.RUN_ERROR) {
442
- if (started && messageSnapshot && stateSnapshot) {
443
- terminalEvent = event;
444
- break;
445
- }
446
531
  this.#event(event);
447
532
  throw new ClientError(event.code ?? "CHAT_RUN_ERROR", event.message);
448
533
  }
@@ -470,6 +555,7 @@ class ChatClientImplementation {
470
555
  if (event.type === EventType.RUN_FINISHED) {
471
556
  if (!started || !event.outcome || !messageSnapshot || !stateSnapshot)
472
557
  throw new ClientError("CHAT_STREAM_INCOMPLETE", "Agent terminal is missing its recovery snapshots or outcome.");
558
+ terminal = { ...event.result, outcome: event.outcome };
473
559
  terminalEvent = event;
474
560
  break;
475
561
  }
@@ -477,11 +563,11 @@ class ChatClientImplementation {
477
563
  throw new ClientError("CHAT_STREAM_INCOMPLETE", "Unexpected event between recovery snapshots and terminal.");
478
564
  this.#event(event);
479
565
  }
480
- if (!terminalEvent || !messageSnapshot || !stateSnapshot)
566
+ if (!terminal || !terminalEvent || !messageSnapshot || !stateSnapshot)
481
567
  throw new ClientError("CHAT_STREAM_INCOMPLETE", "Agent stream ended without complete recovery snapshots.");
482
568
  let decoded;
483
569
  try {
484
- decoded = decodeAgentResponse(messageSnapshot.messages, stateSnapshot.snapshot, terminalEvent, this.id);
570
+ decoded = decodeAgentResponse(messageSnapshot.messages, stateSnapshot.snapshot, terminalEvent);
485
571
  }
486
572
  catch (error) {
487
573
  throw new ClientError("CHAT_STREAM_INCOMPLETE", error instanceof Error ? error.message : "Invalid Agent recovery response.");
@@ -495,10 +581,6 @@ class ChatClientImplementation {
495
581
  this.#event(stateSnapshot);
496
582
  this.#event(terminalEvent);
497
583
  };
498
- if (decoded.type === "error") {
499
- commit();
500
- throw new ClientError(decoded.code, decoded.message);
501
- }
502
584
  if (decoded.type === "success") {
503
585
  commit();
504
586
  return decoded.result;
@@ -529,7 +611,7 @@ class ChatClientImplementation {
529
611
  if (receipts.some((item) => item.role === "tool" && item.toolCallId === call.id))
530
612
  continue;
531
613
  const unknown = inFlight || this.#executingBrowserCall === call.id;
532
- this.#event({ type: EventType.TOOL_CALL_RESULT, messageId: id(), role: "tool", toolCallId: call.id, content: JSON.stringify({ error: { code: unknown ? "EXECUTION_OUTCOME_UNKNOWN" : "TOOL_CANCELLED", message: unknown ? "The execution outcome is unknown; this call may have executed." : "Task ended before execution." } }) });
614
+ this.#event({ type: EventType.TOOL_CALL_RESULT, messageId: id(), role: "tool", toolCallId: call.id, metadata: { nexface: { parentErrorId: this.#failureId } }, content: JSON.stringify({ error: { code: unknown ? "EXECUTION_OUTCOME_UNKNOWN" : "TOOL_CANCELLED", message: unknown ? "The execution outcome is unknown; this call may have executed." : "Task ended before execution." } }) });
533
615
  }
534
616
  }
535
617
  throw error;
@@ -568,10 +650,8 @@ class ChatClientImplementation {
568
650
  signal.throwIfAborted();
569
651
  if (error instanceof ClientError && error.code === "TOOL_CONFIRMATION_INVALIDATED")
570
652
  throw error;
571
- const code = error instanceof ClientError || isToolRuntimeError(error) ? error.code : "TOOL_ERROR";
572
- // An executor error cannot establish that the outer tool was never executed.
573
- const executionError = code === "TOOL_CONFIRMATION_REJECTED" && this.#executingBrowserCall === action.toolCallId;
574
- return { toolCallId: action.toolCallId, error: { code: executionError ? "TOOL_ERROR" : code, message: error instanceof Error ? error.message : String(error) }, ...(confirmed ? { confirmed } : {}) };
653
+ this.#toolCauses.set(action.toolCallId, error);
654
+ return { toolCallId: action.toolCallId, error: { code: error instanceof ClientError || isToolRuntimeError(error) ? error.code : "TOOL_ERROR", message: error instanceof Error ? error.message : String(error) }, ...(confirmed ? { confirmed } : {}) };
575
655
  }
576
656
  finally {
577
657
  if (!signal.aborted)