@nexface/chat 0.1.13-alpha.3 → 0.1.13-alpha.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/dist/assistant-attachments.js +60 -16
  2. package/dist/assistant-components.d.ts +3 -3
  3. package/dist/assistant-components.js +77 -28
  4. package/dist/assistant-runtime.d.ts +1 -1
  5. package/dist/assistant-runtime.js +100 -42
  6. package/dist/attachments.js +36 -14
  7. package/dist/client.js +312 -72
  8. package/dist/config.js +4 -4
  9. package/dist/default-chat.d.ts +1 -1
  10. package/dist/default-chat.js +2102 -727
  11. package/dist/errors.js +55 -17
  12. package/dist/page-confirmation.js +3 -3
  13. package/dist/protocol-messages.js +290 -65
  14. package/dist/protocol-response.js +38 -17
  15. package/dist/react.js +146 -49
  16. package/dist/shared/errors.d.ts +1 -1
  17. package/dist/shared/schema.js +45 -18
  18. package/dist/storage.js +130 -52
  19. package/dist/styles.css +99 -20
  20. package/dist/tool-result.js +7 -2
  21. package/dist/ui/attachment.aui.d.ts +1 -1
  22. package/dist/ui/attachment.aui.js +16 -19
  23. package/dist/ui/code-block.js +2 -2
  24. package/dist/ui/collapsible.js +2 -2
  25. package/dist/ui/composer-voice.js +3 -1
  26. package/dist/ui/dialog.d.ts +1 -1
  27. package/dist/ui/dialog.js +9 -3
  28. package/dist/ui/dropdown-menu.js +2 -2
  29. package/dist/ui/home-demo/composer.js +7 -3
  30. package/dist/ui/home-demo/greeting.d.ts +1 -1
  31. package/dist/ui/home-demo/greeting.js +1 -1
  32. package/dist/ui/home-demo/messages.d.ts +1 -1
  33. package/dist/ui/home-demo/messages.js +4 -4
  34. package/dist/ui/home-demo/suggestions.d.ts +1 -1
  35. package/dist/ui/home-demo/suggestions.js +5 -2
  36. package/dist/ui/home-demo/surfaces.js +3 -1
  37. package/dist/ui/home-demo/thread.d.ts +1 -1
  38. package/dist/ui/home-demo/thread.js +1 -1
  39. package/dist/ui/home-demo/trace-line.d.ts +1 -1
  40. package/dist/ui/home-demo/trace-line.js +2 -2
  41. package/dist/ui/home-demo/trace.d.ts +1 -1
  42. package/dist/ui/home-demo/trace.js +28 -8
  43. package/dist/ui/markdown-text.js +2 -2
  44. package/dist/ui/reasoning.aui.js +2 -2
  45. package/dist/ui/reasoning.d.ts +1 -1
  46. package/dist/ui/reasoning.js +6 -8
  47. package/dist/ui/surface.js +27 -7
  48. package/dist/ui/thread-list.aui.d.ts +2 -2
  49. package/dist/ui/thread-list.aui.js +18 -11
  50. package/dist/ui/tool-group.aui.js +2 -2
  51. package/dist/ui/tooltip-icon-button.js +1 -1
  52. package/dist/ui/use-attachment-src.js +1 -1
  53. package/dist/ui/use-copy-to-clipboard.d.ts +1 -1
  54. package/dist/ui/use-copy-to-clipboard.js +1 -1
  55. package/dist/ui/utils.js +9 -2
  56. package/dist/use-next-message.js +7 -3
  57. package/dist/voice/use-voice.js +35 -12
  58. package/package.json +3 -3
@@ -1,6 +1,6 @@
1
1
  import { ImageInputContentSchema, TextInputContentSchema } from "@ag-ui/core";
2
- import { attachmentContent, readAttachment, validateAttachment } from "./attachments.js";
3
- const errorText = (error) => error instanceof Error ? error.message : String(error);
2
+ import { attachmentContent, readAttachment, validateAttachment, } from "./attachments.js";
3
+ const errorText = (error) => (error instanceof Error ? error.message : String(error));
4
4
  const durablePreview = (preview) => preview?.startsWith("data:image/") ? preview : undefined;
5
5
  // Stop local waiting even when a service ignores cancellation; consume late rejections.
6
6
  function abortable(signal, task) {
@@ -16,9 +16,20 @@ export function toAssistantAttachment(attachment) {
16
16
  const content = attachmentContent(attachment).map((part) => {
17
17
  if (part.type === "text")
18
18
  return part;
19
- return { type: "image", image: part.source.type === "data" ? `data:${part.source.mimeType};base64,${part.source.value}` : part.source.value };
19
+ return {
20
+ type: "image",
21
+ image: part.source.type === "data"
22
+ ? `data:${part.source.mimeType};base64,${part.source.value}`
23
+ : part.source.value,
24
+ };
20
25
  });
21
- return { id: attachment.id, name: attachment.name, type: attachment.preview ? "image" : "document", content, status: { type: "complete" } };
26
+ return {
27
+ id: attachment.id,
28
+ name: attachment.name,
29
+ type: attachment.preview ? "image" : "document",
30
+ content,
31
+ status: { type: "complete" },
32
+ };
22
33
  }
23
34
  // Only this bridge knows assistant-ui's attachment state and lifecycle types.
24
35
  export class AssistantAttachments {
@@ -32,8 +43,12 @@ export class AssistantAttachments {
32
43
  this.changed = changed;
33
44
  this.notice = notice;
34
45
  }
35
- get blocked() { return [...this.entries.values()].some((entry) => entry.adding || Boolean(entry.error)); }
36
- preview(id) { return this.entries.get(id)?.preview; }
46
+ get blocked() {
47
+ return [...this.entries.values()].some((entry) => entry.adding || Boolean(entry.error));
48
+ }
49
+ preview(id) {
50
+ return this.entries.get(id)?.preview;
51
+ }
37
52
  async *add({ file }) {
38
53
  if (this.disposed || this.options === false)
39
54
  throw new Error("附件已禁用。");
@@ -47,10 +62,22 @@ export class AssistantAttachments {
47
62
  this.notice("附件数量超出限制。");
48
63
  throw new Error("附件数量超出限制。");
49
64
  }
50
- const entry = { id: crypto.randomUUID(), file, controller: new AbortController(), adapter: options.adapter, adding: true };
65
+ const entry = {
66
+ id: crypto.randomUUID(),
67
+ file,
68
+ controller: new AbortController(),
69
+ adapter: options.adapter,
70
+ adding: true,
71
+ };
51
72
  this.entries.set(entry.id, entry);
52
73
  this.changed();
53
- const base = { id: entry.id, file, name: file.name, contentType: file.type, type: file.type.startsWith("image/") ? "image" : "document" };
74
+ const base = {
75
+ id: entry.id,
76
+ file,
77
+ name: file.name,
78
+ contentType: file.type,
79
+ type: file.type.startsWith("image/") ? "image" : "document",
80
+ };
54
81
  yield { ...base, status: { type: "running", reason: "uploading", progress: 0 } };
55
82
  try {
56
83
  if (entry.adapter) {
@@ -89,7 +116,12 @@ export class AssistantAttachments {
89
116
  try {
90
117
  let content;
91
118
  if (entry.adapter) {
92
- const result = await abortable(entry.controller.signal, entry.adapter.send({ id: entry.id, file: entry.file, data: entry.data, signal: entry.controller.signal }));
119
+ const result = await abortable(entry.controller.signal, entry.adapter.send({
120
+ id: entry.id,
121
+ file: entry.file,
122
+ data: entry.data,
123
+ signal: entry.controller.signal,
124
+ }));
93
125
  this.assertLive(entry);
94
126
  if (!Array.isArray(result.content) || !result.content.length)
95
127
  throw new Error("附件处理必须返回文本或内联图片。");
@@ -106,7 +138,12 @@ export class AssistantAttachments {
106
138
  content = attachmentContent(entry.local);
107
139
  this.assertLive(entry);
108
140
  const preview = durablePreview(entry.preview);
109
- entry.result = { id: entry.id, name: entry.file.name, content, ...(preview ? { preview } : {}) };
141
+ entry.result = {
142
+ id: entry.id,
143
+ name: entry.file.name,
144
+ content,
145
+ ...(preview ? { preview } : {}),
146
+ };
110
147
  return toAssistantAttachment(entry.result);
111
148
  }
112
149
  catch (error) {
@@ -124,9 +161,12 @@ export class AssistantAttachments {
124
161
  entry.controller.abort();
125
162
  if (!this.disposed)
126
163
  this.changed();
127
- void Promise.resolve().then(() => entry.adapter?.remove?.({ id: entry.id, file: entry.file, data: entry.data }))
128
- .catch((error) => { if (!this.disposed)
129
- this.notice(`附件清理失败:${errorText(error)}`); });
164
+ void Promise.resolve()
165
+ .then(() => entry.adapter?.remove?.({ id: entry.id, file: entry.file, data: entry.data }))
166
+ .catch((error) => {
167
+ if (!this.disposed)
168
+ this.notice(`附件清理失败:${errorText(error)}`);
169
+ });
130
170
  }
131
171
  take(attachments) {
132
172
  return attachments.map((attachment) => {
@@ -146,7 +186,11 @@ export class AssistantAttachments {
146
186
  for (const id of this.entries.keys())
147
187
  void this.remove({ id });
148
188
  }
149
- live(entry) { return !this.disposed && !entry.controller.signal.aborted && this.entries.get(entry.id) === entry; }
150
- assertLive(entry) { if (!this.live(entry))
151
- throw new DOMException("附件处理已取消。", "AbortError"); }
189
+ live(entry) {
190
+ return (!this.disposed && !entry.controller.signal.aborted && this.entries.get(entry.id) === entry);
191
+ }
192
+ assertLive(entry) {
193
+ if (!this.live(entry))
194
+ throw new DOMException("附件处理已取消。", "AbortError");
195
+ }
152
196
  }
@@ -1,11 +1,11 @@
1
1
  import type { UIMessagePart } from "./messages.js";
2
2
  import type { AssistantBinding } from "./assistant-runtime.js";
3
3
  import type { ChatProps } from "./types.js";
4
- export declare function AttachmentTile({ binding, savedPreview }: {
4
+ export declare function AttachmentTile({ binding, savedPreview, }: {
5
5
  binding?: AssistantBinding;
6
6
  savedPreview?: string | undefined;
7
7
  }): import("react").JSX.Element;
8
- export declare function AssistantComposer({ binding, options, placeholder, suggestion, busy, cancelling, cancel }: {
8
+ export declare function AssistantComposer({ binding, options, placeholder, suggestion, busy, cancelling, cancel, }: {
9
9
  binding: AssistantBinding;
10
10
  options: ChatProps["attachments"];
11
11
  placeholder: string;
@@ -14,7 +14,7 @@ export declare function AssistantComposer({ binding, options, placeholder, sugge
14
14
  cancelling: boolean;
15
15
  cancel(): void;
16
16
  }): import("react").JSX.Element;
17
- export declare function AssistantParts({ showDetails, tools }: {
17
+ export declare function AssistantParts({ showDetails, tools, }: {
18
18
  showDetails: boolean;
19
19
  tools?: readonly UIMessagePart[];
20
20
  }): import("react").JSX.Element;
@@ -5,7 +5,7 @@ import { MarkdownText } from "./ui/markdown-text.js";
5
5
  import { Composer } from "./ui/home-demo/composer.js";
6
6
  import { ComposerVoice } from "./ui/composer-voice.js";
7
7
  import { cn } from "./ui/utils.js";
8
- import { AuiIf, AttachmentPrimitive, ComposerPrimitive, useAuiState, MessagePrimitive, groupPartByType } from "@assistant-ui/react";
8
+ import { AuiIf, AttachmentPrimitive, ComposerPrimitive, useAuiState, MessagePrimitive, groupPartByType, } from "@assistant-ui/react";
9
9
  import { ArrowUpIcon, PlusIcon, SquareIcon, MicIcon, XIcon } from "lucide-react";
10
10
  import { TooltipIconButton } from "./ui/tooltip-icon-button.js";
11
11
  import { Button } from "./ui/button.js";
@@ -15,30 +15,52 @@ import { DisclosureTrigger, ToolCall, disclosureContentClass } from "./ui/home-d
15
15
  import { Reasoning, ReasoningRoot, ReasoningContent, ReasoningText } from "./ui/reasoning.aui.js";
16
16
  import { TraceLine } from "./ui/home-demo/trace-line.js";
17
17
  import { attachmentAccept } from "./attachments.js";
18
- export function AttachmentTile({ binding, savedPreview }) {
18
+ export function AttachmentTile({ binding, savedPreview, }) {
19
19
  const attachment = useAuiState((s) => s.attachment);
20
- const preview = binding?.attachments.preview(attachment.id) ?? savedPreview ?? attachment.content?.find((part) => part.type === "image")?.image;
21
- return _jsx(AttachmentUI, { preview: preview, children: _jsxs("div", { className: cn("flex max-w-40 flex-col text-xs wrap-anywhere"), children: [_jsx(AttachmentPrimitive.Name, {}), binding && attachment.status.type === "requires-action" ? _jsx("small", { className: cn("text-muted-foreground"), children: "\u5DF2\u5C31\u7EEA" }) : null, attachment.status.type === "running" ? _jsx("small", { className: cn("text-muted-foreground"), children: "\u6B63\u5728\u5904\u7406\u2026" }) : null, attachment.status.type === "incomplete" ? _jsx("small", { className: cn("text-destructive"), role: "alert", children: attachment.status.message ?? "附件处理失败" }) : null] }) });
20
+ const preview = binding?.attachments.preview(attachment.id) ??
21
+ savedPreview ??
22
+ attachment.content?.find((part) => part.type === "image")?.image;
23
+ return (_jsx(AttachmentUI, { preview: preview, children: _jsxs("div", { className: cn("flex max-w-40 flex-col text-xs wrap-anywhere"), children: [_jsx(AttachmentPrimitive.Name, {}), binding && attachment.status.type === "requires-action" ? (_jsx("small", { className: cn("text-muted-foreground"), children: "\u5DF2\u5C31\u7EEA" })) : null, attachment.status.type === "running" ? (_jsx("small", { className: cn("text-muted-foreground"), children: "\u6B63\u5728\u5904\u7406\u2026" })) : null, attachment.status.type === "incomplete" ? (_jsx("small", { className: cn("text-destructive"), role: "alert", children: attachment.status.message ?? "附件处理失败" })) : null] }) }));
22
24
  }
23
- export function AssistantComposer({ binding, options, placeholder, suggestion, busy, cancelling, cancel }) {
25
+ export function AssistantComposer({ binding, options, placeholder, suggestion, busy, cancelling, cancel, }) {
24
26
  const input = useRef(null);
25
27
  const sending = binding.sending;
26
28
  const voiceBusy = binding.voice.status !== "idle";
27
29
  const inputDisabled = sending || voiceBusy;
28
- const voiceDisabledReason = busy ? "任务执行中,暂不能录音" : sending ? "正在处理附件,暂不能录音" : undefined;
30
+ const voiceDisabledReason = busy
31
+ ? "任务执行中,暂不能录音"
32
+ : sending
33
+ ? "正在处理附件,暂不能录音"
34
+ : undefined;
29
35
  const empty = useAuiState((state) => state.composer.text.length === 0);
30
36
  const nextMessage = !busy && !inputDisabled && empty ? suggestion : undefined;
31
37
  const showCancel = useAuiState((state) => busy && (state.thread.isRunning || state.composer.isEmpty));
32
38
  const addFiles = (files) => {
33
39
  for (const file of files)
34
- void binding.runtime.thread.composer.addAttachment(file).catch((error) => binding.setNotice(error instanceof Error ? error.message : String(error)));
40
+ void binding.runtime.thread.composer
41
+ .addAttachment(file)
42
+ .catch((error) => binding.setNotice(error instanceof Error ? error.message : String(error)));
35
43
  };
36
- return _jsxs(Composer, { onSubmit: (event) => { event.preventDefault(); void binding.send(); }, inputProps: { "aria-label": "输入 Agent 任务", placeholder: nextMessage ?? placeholder, disabled: inputDisabled, cancelOnEscape: false,
44
+ return (_jsxs(Composer, { onSubmit: (event) => {
45
+ event.preventDefault();
46
+ void binding.send();
47
+ }, inputProps: {
48
+ "aria-label": "输入 Agent 任务",
49
+ placeholder: nextMessage ?? placeholder,
50
+ disabled: inputDisabled,
51
+ cancelOnEscape: false,
37
52
  addAttachmentOnPaste: !inputDisabled,
38
53
  onKeyDown: (event) => {
39
54
  if (event.keyCode === 229)
40
55
  event.preventDefault();
41
- else if ((event.key === "ArrowRight" || event.key === "Tab") && nextMessage && !event.nativeEvent.isComposing && !event.shiftKey && !event.ctrlKey && !event.altKey && !event.metaKey && !event.currentTarget.value) {
56
+ else if ((event.key === "ArrowRight" || event.key === "Tab") &&
57
+ nextMessage &&
58
+ !event.nativeEvent.isComposing &&
59
+ !event.shiftKey &&
60
+ !event.ctrlKey &&
61
+ !event.altKey &&
62
+ !event.metaKey &&
63
+ !event.currentTarget.value) {
42
64
  event.preventDefault();
43
65
  binding.runtime.thread.composer.setText(nextMessage);
44
66
  }
@@ -46,11 +68,23 @@ export function AssistantComposer({ binding, options, placeholder, suggestion, b
46
68
  event.preventDefault();
47
69
  void binding.send();
48
70
  }
49
- } }, actions: _jsxs(_Fragment, { children: [voiceBusy ? _jsx("span", { role: "status", className: cn("sr-only"), children: binding.voice.status === "starting" ? "正在准备语音输入,请确认麦克风已授权…" : binding.voice.status === "transcribing" ? "正在识别,请稍候…" : "正在录音" }) : null, voiceBusy ? _jsx(TooltipIconButton, { tooltip: "\u53D6\u6D88\u5F55\u97F3", "aria-label": "\u53D6\u6D88\u8BED\u97F3\u8F93\u5165", className: cn("size-7 shrink-0"), onClick: binding.voice.cancel, children: _jsx(XIcon, { className: cn("size-4") }) }) : options !== false ? _jsxs(_Fragment, { children: [_jsx("input", { ref: input, type: "file", multiple: true, disabled: inputDisabled, 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: inputDisabled, onClick: () => input.current?.click(), children: _jsx(PlusIcon, { className: cn("size-4") }) })] }) : _jsx("span", {}), voiceBusy ? _jsx(ComposerVoice, { recording: binding.voice.status === "recording" }) : null, _jsxs("div", { className: cn("flex shrink-0 items-center gap-1"), children: [_jsxs(AuiIf, { condition: (state) => state.thread.capabilities.dictation, children: [_jsx(AuiIf, { condition: (state) => state.composer.dictation == null, children: _jsx(TooltipProvider, { delayDuration: 0, children: _jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { asChild: true, children: _jsx("span", { className: cn("inline-flex"), tabIndex: voiceDisabledReason ? 0 : undefined, "aria-label": voiceDisabledReason, children: _jsx(ComposerPrimitive.Dictate, { asChild: true, disabled: busy || sending, children: _jsx(Button, { variant: "ghost", size: "icon", "aria-label": "\u5F00\u59CB\u8BED\u97F3\u8F93\u5165", "aria-description": voiceDisabledReason, className: cn("size-7 p-1"), children: _jsx(MicIcon, { className: cn("size-4") }) }) }) }) }), _jsx(TooltipContent, { children: voiceDisabledReason ?? "语音输入" })] }) }) }), _jsx(AuiIf, { condition: (state) => state.composer.dictation != null, children: _jsx(ComposerPrimitive.StopDictation, { asChild: true, disabled: binding.voice.status !== "recording", children: _jsx("button", { type: "button", "aria-label": "\u7ED3\u675F\u8BED\u97F3\u8F93\u5165", title: "\u7ED3\u675F\u5F55\u97F3", className: cn("text-destructive rounded-control grid size-7 place-items-center transition-colors disabled:opacity-50"), children: _jsx(SquareIcon, { className: cn("size-3 animate-pulse fill-current") }) }) }) })] }), 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") }) }) :
50
- _jsx(ComposerPrimitive.Send, { asChild: true, disabled: inputDisabled, 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", { ref: (element) => { element?.toggleAttribute("inert", inputDisabled); }, 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] });
71
+ },
72
+ }, actions: _jsxs(_Fragment, { children: [voiceBusy ? (_jsx("span", { role: "status", className: cn("sr-only"), children: binding.voice.status === "starting"
73
+ ? "正在准备语音输入,请确认麦克风已授权…"
74
+ : binding.voice.status === "transcribing"
75
+ ? "正在识别,请稍候…"
76
+ : "正在录音" })) : null, voiceBusy ? (_jsx(TooltipIconButton, { tooltip: "\u53D6\u6D88\u5F55\u97F3", "aria-label": "\u53D6\u6D88\u8BED\u97F3\u8F93\u5165", className: cn("size-7 shrink-0"), onClick: binding.voice.cancel, children: _jsx(XIcon, { className: cn("size-4") }) })) : options !== false ? (_jsxs(_Fragment, { children: [_jsx("input", { ref: input, type: "file", multiple: true, disabled: inputDisabled, accept: options?.accept ?? attachmentAccept, hidden: true, onChange: (event) => {
77
+ addFiles(Array.from(event.target.files ?? []));
78
+ event.target.value = "";
79
+ } }), _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: inputDisabled, onClick: () => input.current?.click(), children: _jsx(PlusIcon, { className: cn("size-4") }) })] })) : (_jsx("span", {})), voiceBusy ? _jsx(ComposerVoice, { recording: binding.voice.status === "recording" }) : null, _jsxs("div", { className: cn("flex shrink-0 items-center gap-1"), children: [_jsxs(AuiIf, { condition: (state) => state.thread.capabilities.dictation, children: [_jsx(AuiIf, { condition: (state) => state.composer.dictation == null, children: _jsx(TooltipProvider, { delayDuration: 0, children: _jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { asChild: true, children: _jsx("span", { className: cn("inline-flex"), tabIndex: voiceDisabledReason ? 0 : undefined, "aria-label": voiceDisabledReason, children: _jsx(ComposerPrimitive.Dictate, { asChild: true, disabled: busy || sending, children: _jsx(Button, { variant: "ghost", size: "icon", "aria-label": "\u5F00\u59CB\u8BED\u97F3\u8F93\u5165", "aria-description": voiceDisabledReason, className: cn("size-7 p-1"), children: _jsx(MicIcon, { className: cn("size-4") }) }) }) }) }), _jsx(TooltipContent, { children: voiceDisabledReason ?? "语音输入" })] }) }) }), _jsx(AuiIf, { condition: (state) => state.composer.dictation != null, children: _jsx(ComposerPrimitive.StopDictation, { asChild: true, disabled: binding.voice.status !== "recording", children: _jsx("button", { type: "button", "aria-label": "\u7ED3\u675F\u8BED\u97F3\u8F93\u5165", title: "\u7ED3\u675F\u5F55\u97F3", className: cn("text-destructive rounded-control grid size-7 place-items-center transition-colors disabled:opacity-50"), children: _jsx(SquareIcon, { className: cn("size-3 animate-pulse fill-current") }) }) }) })] }), 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") }) })) : (_jsx(ComposerPrimitive.Send, { asChild: true, disabled: inputDisabled, children: _jsx("button", { type: "button", onClick: (event) => {
80
+ event.preventDefault();
81
+ void binding.send();
82
+ }, "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", { ref: (element) => {
83
+ element?.toggleAttribute("inert", inputDisabled);
84
+ }, 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] }));
51
85
  }
52
- function ToolGroup({ tools, running, count, children }) {
53
- const errors = tools.flatMap((tool) => tool.type === "tool" && tool.error ? [tool.error] : []);
86
+ function ToolGroup({ tools, running, count, children, }) {
87
+ const errors = tools.flatMap((tool) => (tool.type === "tool" && tool.error ? [tool.error] : []));
54
88
  const errorIds = JSON.stringify(errors.map((error) => error.id));
55
89
  const hasErrors = errors.length > 0;
56
90
  const [open, setOpen] = useState(hasErrors);
@@ -59,24 +93,39 @@ function ToolGroup({ tools, running, count, children }) {
59
93
  setOpen(true);
60
94
  }, [errorIds]);
61
95
  const unknown = hasErrors && errors.every((error) => error.scope === "tool" && error.execution === "unknown");
62
- 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 })] });
96
+ 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 })] }));
63
97
  }
64
98
  const GroupedParts = MessagePrimitive.GroupedParts;
65
- const groupAssistantParts = groupPartByType({ reasoning: ["group-chainOfThought", "group-reasoning"], source: ["group-chainOfThought", "group-source"], "tool-call": ["group-chainOfThought", "group-tool"], "standalone-tool-call": [] });
66
- export function AssistantParts({ showDetails, tools = [] }) {
67
- return _jsx(_Fragment, { children: _jsx(GroupedParts, { groupBy: groupAssistantParts, children: ({ part, children }) => {
99
+ const groupAssistantParts = groupPartByType({
100
+ reasoning: ["group-chainOfThought", "group-reasoning"],
101
+ source: ["group-chainOfThought", "group-source"],
102
+ "tool-call": ["group-chainOfThought", "group-tool"],
103
+ "standalone-tool-call": [],
104
+ });
105
+ export function AssistantParts({ showDetails, tools = [], }) {
106
+ return (_jsx(_Fragment, { children: _jsx(GroupedParts, { groupBy: groupAssistantParts, children: ({ part, children }) => {
68
107
  switch (part.type) {
69
- case "group-chainOfThought": return _jsx("div", { className: cn("mb-3"), children: children });
70
- 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 });
71
- case "group-reasoning": return _jsxs(ReasoningRoot, { variant: "ghost", streaming: part.status.type === "running", className: cn("my-1"), 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 }) })] });
72
- case "reasoning": return _jsx(Reasoning, { ...part });
108
+ case "group-chainOfThought":
109
+ return _jsx("div", { className: cn("mb-3"), children: children });
110
+ case "group-tool":
111
+ 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 }));
112
+ case "group-reasoning":
113
+ return (_jsxs(ReasoningRoot, { variant: "ghost", streaming: part.status.type === "running", className: cn("my-1"), 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 }) })] }));
114
+ case "reasoning":
115
+ return _jsx(Reasoning, { ...part });
73
116
  case "group-source":
74
- case "source": return null;
75
- case "data": return part.dataRendererUI;
76
- case "text": return part.text === "" && part.status?.type === "running" ? _jsx(TraceLine, { live: true, label: "thinking" }) : _jsx(MarkdownText, {});
77
- case "tool-call": return part.toolUI ?? _jsx(ToolCall, { ...part, showDetails: showDetails, presentation: tools.find((tool) => tool.type === "tool" && tool.toolCallId === part.toolCallId) });
78
- case "indicator": return _jsx(TraceLine, { live: true, label: "thinking" });
79
- default: return null;
117
+ case "source":
118
+ return null;
119
+ case "data":
120
+ return part.dataRendererUI;
121
+ case "text":
122
+ return part.text === "" && part.status?.type === "running" ? (_jsx(TraceLine, { live: true, label: "thinking" })) : (_jsx(MarkdownText, {}));
123
+ case "tool-call":
124
+ return (part.toolUI ?? (_jsx(ToolCall, { ...part, showDetails: showDetails, presentation: tools.find((tool) => tool.type === "tool" && tool.toolCallId === part.toolCallId) })));
125
+ case "indicator":
126
+ return _jsx(TraceLine, { live: true, label: "thinking" });
127
+ default:
128
+ return null;
80
129
  }
81
- } }) });
130
+ } }) }));
82
131
  }
@@ -16,7 +16,7 @@ export type AssistantBinding = {
16
16
  };
17
17
  export declare function convertMessage(message: UIMessage): ThreadMessageLike;
18
18
  export declare function projectMessages(messages: readonly UIMessage[]): UIMessage[];
19
- export declare function SessionRuntime({ id, chat, options, dictation, open, blocked, active, onEdit, children }: {
19
+ export declare function SessionRuntime({ id, chat, options, dictation, open, blocked, active, onEdit, children, }: {
20
20
  id: string;
21
21
  chat: ChatState;
22
22
  options: ChatProps["attachments"];
@@ -1,30 +1,51 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
2
  import { useEffect, useLayoutEffect, useReducer, useRef, useState } from "react";
3
- import { AssistantRuntimeProvider, MessageNotSentError, useExternalStoreRuntime } from "@assistant-ui/react";
3
+ import { AssistantRuntimeProvider, MessageNotSentError, useExternalStoreRuntime, } from "@assistant-ui/react";
4
4
  import { AssistantAttachments, toAssistantAttachment } from "./assistant-attachments.js";
5
5
  import { assertChatSendable } from "./react.js";
6
6
  import { useVoiceInput } from "./voice/use-voice.js";
7
7
  function parseToolArgs(text) {
8
8
  try {
9
9
  const value = JSON.parse(text);
10
- return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
10
+ return value !== null && typeof value === "object" && !Array.isArray(value)
11
+ ? value
12
+ : {};
11
13
  }
12
14
  catch {
13
15
  return {};
14
16
  }
15
17
  }
16
18
  export function convertMessage(message) {
17
- const content = message.parts.map((part) => part.type !== "tool" ? part : {
18
- type: "tool-call", toolCallId: part.toolCallId, toolName: part.name,
19
- args: parseToolArgs(part.arguments),
20
- argsText: part.arguments, result: part.result, isError: part.isError,
21
- });
19
+ const content = message.parts.map((part) => part.type !== "tool"
20
+ ? part
21
+ : {
22
+ type: "tool-call",
23
+ toolCallId: part.toolCallId,
24
+ toolName: part.name,
25
+ args: parseToolArgs(part.arguments),
26
+ argsText: part.arguments,
27
+ result: part.result,
28
+ isError: part.isError,
29
+ });
22
30
  if (message.role === "user")
23
- return { id: message.id, role: "user", content, attachments: message.attachments?.map(toAssistantAttachment) };
24
- return { id: message.id, role: "assistant", content, status: message.error
31
+ return {
32
+ id: message.id,
33
+ role: "user",
34
+ content,
35
+ attachments: message.attachments?.map(toAssistantAttachment),
36
+ };
37
+ return {
38
+ id: message.id,
39
+ role: "assistant",
40
+ content,
41
+ status: message.error
25
42
  ? { type: "incomplete", reason: "error", error: message.error.userMessage }
26
- : message.state === "cancelled" ? { type: "incomplete", reason: "cancelled" }
27
- : message.state === "running" ? { type: "running" } : { type: "complete", reason: "stop" } };
43
+ : message.state === "cancelled"
44
+ ? { type: "incomplete", reason: "cancelled" }
45
+ : message.state === "running"
46
+ ? { type: "running" }
47
+ : { type: "complete", reason: "stop" },
48
+ };
28
49
  }
29
50
  // Project each user turn to one assistant row without changing persisted messages.
30
51
  export function projectMessages(messages) {
@@ -32,7 +53,12 @@ export function projectMessages(messages) {
32
53
  for (const message of messages) {
33
54
  const previous = projected.at(-1);
34
55
  if (message.role === "assistant" && previous?.role === "assistant") {
35
- projected[projected.length - 1] = { ...previous, parts: [...previous.parts, ...message.parts], ...(message.state ? { state: message.state } : {}), ...(message.error ? { error: message.error } : {}) };
56
+ projected[projected.length - 1] = {
57
+ ...previous,
58
+ parts: [...previous.parts, ...message.parts],
59
+ ...(message.state ? { state: message.state } : {}),
60
+ ...(message.error ? { error: message.error } : {}),
61
+ };
36
62
  }
37
63
  else
38
64
  projected.push(message);
@@ -41,9 +67,11 @@ export function projectMessages(messages) {
41
67
  }
42
68
  // Keep one composer per visited Session: switching the external-store thread id
43
69
  // would invalidate pending attachment work and discard that Session's draft.
44
- export function SessionRuntime({ id, chat, options, dictation, open = true, blocked, active, onEdit, children }) {
70
+ export function SessionRuntime({ id, chat, options, dictation, open = true, blocked, active, onEdit, children, }) {
45
71
  const latest = useRef(chat);
46
- useLayoutEffect(() => { latest.current = chat; });
72
+ useLayoutEffect(() => {
73
+ latest.current = chat;
74
+ });
47
75
  const messages = useRef([]);
48
76
  if (chat.activeSessionId === id)
49
77
  messages.current = chat.messages;
@@ -54,14 +82,23 @@ export function SessionRuntime({ id, chat, options, dictation, open = true, bloc
54
82
  const [attachments] = useState(() => new AssistantAttachments(refresh, setNotice));
55
83
  attachments.options = options ?? {};
56
84
  const alive = useRef(false);
57
- const voice = useVoiceInput({ dictation, active, open, blocked: blocked || sending || attachments.blocked,
58
- sessionId: id, composer: () => runtime.thread.composer, notice: setNotice });
85
+ const voice = useVoiceInput({
86
+ dictation,
87
+ active,
88
+ open,
89
+ blocked: blocked || sending || attachments.blocked,
90
+ sessionId: id,
91
+ composer: () => runtime.thread.composer,
92
+ notice: setNotice,
93
+ });
59
94
  useEffect(() => {
60
95
  alive.current = true;
61
96
  return () => {
62
97
  alive.current = false;
63
- queueMicrotask(() => { if (!alive.current)
64
- attachments.dispose(); });
98
+ queueMicrotask(() => {
99
+ if (!alive.current)
100
+ attachments.dispose();
101
+ });
65
102
  };
66
103
  }, [attachments]);
67
104
  const runtime = useExternalStoreRuntime({
@@ -73,38 +110,52 @@ export function SessionRuntime({ id, chat, options, dictation, open = true, bloc
73
110
  if (!alive.current || latest.current.activeSessionId !== id)
74
111
  throw new MessageNotSentError("会话已切换,请返回原会话重新发送。");
75
112
  const files = attachments.take(message.attachments ?? []);
76
- const text = message.content.flatMap((part) => part.type === "text" ? [part.text] : []).join("");
113
+ const text = message.content
114
+ .flatMap((part) => (part.type === "text" ? [part.text] : []))
115
+ .join("");
77
116
  attachments.commit(message.attachments ?? []);
78
117
  setNotice("");
79
118
  await latest.current.sendMessage(text, files);
80
119
  },
81
- onEdit: onEdit ? async (message) => {
82
- if (!message.sourceId)
83
- throw new Error("未找到要编辑的消息。");
84
- const text = message.content.flatMap((part) => part.type === "text" ? [part.text] : []).join("");
85
- try {
86
- await onEdit(message.sourceId, text);
87
- }
88
- catch {
89
- const sourceId = message.sourceId;
90
- queueMicrotask(() => {
91
- if (!alive.current || latest.current.activeSessionId !== id)
92
- return;
93
- const composer = runtime.thread.getMessageById(sourceId).composer;
94
- if (!composer.getState().isEditing)
95
- composer.beginEdit();
96
- composer.setText(text);
97
- });
120
+ onEdit: onEdit
121
+ ? async (message) => {
122
+ if (!message.sourceId)
123
+ throw new Error("未找到要编辑的消息。");
124
+ const text = message.content
125
+ .flatMap((part) => (part.type === "text" ? [part.text] : []))
126
+ .join("");
127
+ try {
128
+ await onEdit(message.sourceId, text);
129
+ }
130
+ catch {
131
+ const sourceId = message.sourceId;
132
+ queueMicrotask(() => {
133
+ if (!alive.current || latest.current.activeSessionId !== id)
134
+ return;
135
+ const composer = runtime.thread.getMessageById(sourceId).composer;
136
+ if (!composer.getState().isEditing)
137
+ composer.beginEdit();
138
+ composer.setText(text);
139
+ });
140
+ }
98
141
  }
99
- } : undefined,
100
- onCancel: async () => { latest.current.cancel(); },
142
+ : undefined,
143
+ onCancel: async () => {
144
+ latest.current.cancel();
145
+ },
101
146
  adapters: {
102
147
  dictation: voice.dictation,
103
148
  attachments: options === false ? undefined : attachments,
104
149
  threadList: {
105
150
  threadId: id,
106
- threads: chat.sessions.map((session) => ({ id: session.id, title: session.title, status: "regular" })),
107
- onSwitchToNewThread: () => { latest.current.createSession(); },
151
+ threads: chat.sessions.map((session) => ({
152
+ id: session.id,
153
+ title: session.title,
154
+ status: "regular",
155
+ })),
156
+ onSwitchToNewThread: () => {
157
+ latest.current.createSession();
158
+ },
108
159
  onSwitchToThread: (next) => latest.current.switchSession(next),
109
160
  onRename: (target, title) => latest.current.renameSession(target, title),
110
161
  onDelete: (target) => latest.current.deleteSession(target),
@@ -113,7 +164,12 @@ export function SessionRuntime({ id, chat, options, dictation, open = true, bloc
113
164
  });
114
165
  const send = async () => {
115
166
  const draft = runtime.thread.composer.getState();
116
- if (!active || blocked || attachments.blocked || sendLock.current || voice.state.status !== "idle" || draft.isEmpty)
167
+ if (!active ||
168
+ blocked ||
169
+ attachments.blocked ||
170
+ sendLock.current ||
171
+ voice.state.status !== "idle" ||
172
+ draft.isEmpty)
117
173
  return;
118
174
  sendLock.current = true;
119
175
  setSending(true);
@@ -146,5 +202,7 @@ export function SessionRuntime({ id, chat, options, dictation, open = true, bloc
146
202
  setSending(false);
147
203
  }
148
204
  };
149
- return _jsx(AssistantRuntimeProvider, { runtime: runtime, children: active ? children({ runtime, attachments, notice, setNotice, sending, voice: voice.state, send }) : null });
205
+ return (_jsx(AssistantRuntimeProvider, { runtime: runtime, children: active
206
+ ? children({ runtime, attachments, notice, setNotice, sending, voice: voice.state, send })
207
+ : null }));
150
208
  }
@@ -1,32 +1,48 @@
1
1
  const types = {
2
- txt: "text/plain", md: "text/markdown", csv: "text/csv", json: "application/json",
3
- png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", webp: "image/webp",
2
+ txt: "text/plain",
3
+ md: "text/markdown",
4
+ csv: "text/csv",
5
+ json: "application/json",
6
+ png: "image/png",
7
+ jpg: "image/jpeg",
8
+ jpeg: "image/jpeg",
9
+ webp: "image/webp",
4
10
  };
5
11
  export const attachmentAccept = ".txt,.md,.csv,.json,.png,.jpg,.jpeg,.webp";
6
12
  export const attachmentContent = (attachment) => Array.isArray(attachment.content) ? attachment.content : [attachment.content];
7
13
  export function validateAttachment(file, options) {
8
- if (options.maxSizeBytes !== undefined && (!Number.isFinite(options.maxSizeBytes) || options.maxSizeBytes <= 0))
14
+ if (options.maxSizeBytes !== undefined &&
15
+ (!Number.isFinite(options.maxSizeBytes) || options.maxSizeBytes <= 0))
9
16
  throw new Error("附件大小限制必须是正数。");
10
17
  if (file.size > (options.maxSizeBytes ?? 5 * 1024 * 1024))
11
18
  throw new Error(`文件过大:${file.name}`);
12
19
  const extension = file.name.split(".").at(-1)?.toLowerCase() ?? "";
13
20
  const mime = file.type || types[extension] || "";
14
- const accepted = (options.accept ?? attachmentAccept).split(",").map((part) => part.trim().toLowerCase());
15
- if (!accepted.some((part) => part === "*" || part === `.${extension}` || part === mime
16
- || part.endsWith("/*") && mime.startsWith(part.slice(0, -1))))
21
+ const accepted = (options.accept ?? attachmentAccept)
22
+ .split(",")
23
+ .map((part) => part.trim().toLowerCase());
24
+ if (!accepted.some((part) => part === "*" ||
25
+ part === `.${extension}` ||
26
+ part === mime ||
27
+ (part.endsWith("/*") && mime.startsWith(part.slice(0, -1)))))
17
28
  throw new Error(`不接受此文件:${file.name}`);
18
29
  }
19
30
  export async function readAttachment(file, options) {
20
- if (options.maxSizeBytes !== undefined && (!Number.isFinite(options.maxSizeBytes) || options.maxSizeBytes <= 0))
31
+ if (options.maxSizeBytes !== undefined &&
32
+ (!Number.isFinite(options.maxSizeBytes) || options.maxSizeBytes <= 0))
21
33
  throw new Error("附件大小限制必须是正数。");
22
34
  const extension = file.name.split(".").at(-1)?.toLowerCase() ?? "";
23
35
  const mime = types[extension];
24
- if (!mime || (file.type && file.type !== mime && !(extension === "md" && file.type === "text/plain"))) {
36
+ if (!mime ||
37
+ (file.type && file.type !== mime && !(extension === "md" && file.type === "text/plain"))) {
25
38
  throw new Error(`不支持文件类型:${file.name}`);
26
39
  }
27
- const accepted = (options.accept ?? attachmentAccept).split(",").map((part) => part.trim().toLowerCase());
28
- if (!accepted.some((part) => part === `.${extension}` || part === mime
29
- || part.endsWith("/*") && mime.startsWith(part.slice(0, -1)))) {
40
+ const accepted = (options.accept ?? attachmentAccept)
41
+ .split(",")
42
+ .map((part) => part.trim().toLowerCase());
43
+ if (!accepted.some((part) => part === `.${extension}` ||
44
+ part === mime ||
45
+ (part.endsWith("/*") && mime.startsWith(part.slice(0, -1))))) {
30
46
  throw new Error(`不接受此文件:${file.name}`);
31
47
  }
32
48
  if (file.size > (options.maxSizeBytes ?? 5 * 1024 * 1024))
@@ -37,9 +53,15 @@ export async function readAttachment(file, options) {
37
53
  return { id, name: file.name, content: { type: "text", text: `附件 ${file.name}\n${value}` } };
38
54
  }
39
55
  const preview = await read(file, true);
40
- return { id, name: file.name, preview, content: {
41
- type: "image", source: { type: "data", value: preview.slice(preview.indexOf(",") + 1), mimeType: mime },
42
- } };
56
+ return {
57
+ id,
58
+ name: file.name,
59
+ preview,
60
+ content: {
61
+ type: "image",
62
+ source: { type: "data", value: preview.slice(preview.indexOf(",") + 1), mimeType: mime },
63
+ },
64
+ };
43
65
  }
44
66
  function read(file, image) {
45
67
  return new Promise((resolve, reject) => {