@nexface/chat 0.1.3 → 0.1.4-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.
- package/dist/assistant-attachments.js +6 -2
- package/dist/assistant-attachments.js.map +1 -1
- package/dist/assistant-components.d.ts +7 -3
- package/dist/assistant-components.js +30 -16
- package/dist/assistant-components.js.map +1 -1
- package/dist/assistant-runtime.d.ts +3 -1
- package/dist/assistant-runtime.js +45 -4
- package/dist/assistant-runtime.js.map +1 -1
- package/dist/default-chat.js +47 -63
- package/dist/default-chat.js.map +1 -1
- package/dist/fonts/JetBrainsMono-OFL.txt +93 -0
- package/dist/fonts/PublicSans-OFL.txt +93 -0
- package/dist/fonts/jetbrains-mono.ttf +0 -0
- package/dist/fonts/public-sans.ttf +0 -0
- package/dist/messages.d.ts +3 -0
- package/dist/messages.js.map +1 -1
- package/dist/protocol-messages.js +39 -8
- package/dist/protocol-messages.js.map +1 -1
- package/dist/storage.js +2 -2
- package/dist/storage.js.map +1 -1
- package/dist/styles.css +1167 -325
- package/dist/ui/button.js +1 -1
- package/dist/ui/button.js.map +1 -1
- package/dist/ui/code-block.d.ts +22 -0
- package/dist/ui/code-block.js +49 -0
- package/dist/ui/code-block.js.map +1 -0
- package/dist/ui/collapsible.d.ts +5 -0
- package/dist/ui/collapsible.js +15 -0
- package/dist/ui/collapsible.js.map +1 -0
- package/dist/ui/dropdown-menu.js +4 -3
- package/dist/ui/dropdown-menu.js.map +1 -1
- package/dist/ui/home-demo/action-bar.d.ts +2 -0
- package/dist/ui/home-demo/action-bar.js +10 -0
- package/dist/ui/home-demo/action-bar.js.map +1 -0
- package/dist/ui/home-demo/composer.d.ts +11 -0
- package/dist/ui/home-demo/composer.js +12 -0
- package/dist/ui/home-demo/composer.js.map +1 -0
- package/dist/ui/home-demo/greeting.d.ts +5 -0
- package/dist/ui/home-demo/greeting.js +8 -0
- package/dist/ui/home-demo/greeting.js.map +1 -0
- package/dist/ui/home-demo/messages.d.ts +9 -0
- package/dist/ui/home-demo/messages.js +15 -0
- package/dist/ui/home-demo/messages.js.map +1 -0
- package/dist/ui/home-demo/styles.d.ts +3 -0
- package/dist/ui/home-demo/styles.js +4 -0
- package/dist/ui/home-demo/styles.js.map +1 -0
- package/dist/ui/home-demo/suggestions.d.ts +13 -0
- package/dist/ui/home-demo/suggestions.js +21 -0
- package/dist/ui/home-demo/suggestions.js.map +1 -0
- package/dist/ui/home-demo/surfaces.d.ts +4 -0
- package/dist/ui/home-demo/surfaces.js +4 -0
- package/dist/ui/home-demo/surfaces.js.map +1 -0
- package/dist/ui/home-demo/thread.d.ts +13 -0
- package/dist/ui/home-demo/thread.js +12 -0
- package/dist/ui/home-demo/thread.js.map +1 -0
- package/dist/ui/home-demo/trace-line.d.ts +19 -0
- package/dist/ui/home-demo/trace-line.js +38 -0
- package/dist/ui/home-demo/trace-line.js.map +1 -0
- package/dist/ui/home-demo/trace.d.ts +11 -0
- package/dist/ui/home-demo/trace.js +20 -0
- package/dist/ui/home-demo/trace.js.map +1 -0
- package/dist/ui/home-demo/type.d.ts +5 -0
- package/dist/ui/home-demo/type.js +6 -0
- package/dist/ui/home-demo/type.js.map +1 -0
- package/dist/ui/input.js +2 -2
- package/dist/ui/input.js.map +1 -1
- package/dist/ui/markdown-text.js +32 -12
- package/dist/ui/markdown-text.js.map +1 -1
- package/dist/ui/reasoning.aui.d.ts +21 -0
- package/dist/ui/reasoning.aui.js +56 -0
- package/dist/ui/reasoning.aui.js.map +1 -0
- package/dist/ui/reasoning.d.ts +34 -0
- package/dist/ui/reasoning.js +112 -0
- package/dist/ui/reasoning.js.map +1 -0
- package/dist/ui/thread-list.aui.d.ts +7 -4
- package/dist/ui/thread-list.aui.js +53 -5
- package/dist/ui/thread-list.aui.js.map +1 -1
- package/dist/ui/tool-group.aui.d.ts +34 -0
- package/dist/ui/tool-group.aui.js +60 -0
- package/dist/ui/tool-group.aui.js.map +1 -0
- package/package.json +4 -4
- package/dist/ui/thread.aui.d.ts +0 -29
- package/dist/ui/thread.aui.js +0 -26
- package/dist/ui/thread.aui.js.map +0 -1
|
@@ -41,10 +41,14 @@ export class AssistantAttachments {
|
|
|
41
41
|
throw new Error("附件已禁用。");
|
|
42
42
|
const options = this.options;
|
|
43
43
|
const maxCount = options.maxCount ?? 3;
|
|
44
|
-
if (!Number.isInteger(maxCount) || maxCount <= 0)
|
|
44
|
+
if (!Number.isInteger(maxCount) || maxCount <= 0) {
|
|
45
|
+
this.notice("附件数量限制必须是正整数。");
|
|
45
46
|
throw new Error("附件数量限制必须是正整数。");
|
|
46
|
-
|
|
47
|
+
}
|
|
48
|
+
if (this.entries.size >= maxCount) {
|
|
49
|
+
this.notice("附件数量超出限制。");
|
|
47
50
|
throw new Error("附件数量超出限制。");
|
|
51
|
+
}
|
|
48
52
|
const entry = { id: crypto.randomUUID(), file, controller: new AbortController(), adapter: options.adapter, adding: true, sending: false };
|
|
49
53
|
this.entries.set(entry.id, entry);
|
|
50
54
|
this.changed();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"assistant-attachments.js","sourceRoot":"","sources":["../src/assistant-attachments.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAC9E,OAAO,EAAE,iBAAiB,EAAE,cAAc,EAAE,kBAAkB,EAAmB,MAAM,kBAAkB,CAAC;AAgB1G,MAAM,SAAS,GAAG,CAAC,KAAc,EAAE,EAAE,CAAC,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAC7F,MAAM,cAAc,GAAG,CAAC,OAAgB,EAAE,EAAE,CAAC,OAAO,EAAE,UAAU,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC;AAEtG,wFAAwF;AACxF,SAAS,SAAS,CAAI,MAAmB,EAAE,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AC,IAAI,EAAE;YAAE,KAAK,IAAI,CAAC,MAAM,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;IACjE,CAAC;IACO,IAAI,CAAC,KAAY,IAAI,OAAO,CAAC,IAAI,CAAC,QAAQ,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,MAAM,CAAC,OAAO,IAAI,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC,KAAK,KAAK,CAAC,CAAC,CAAC;IACzH,UAAU,CAAC,KAAY,IAAI,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC;QAAE,MAAM,IAAI,YAAY,CAAC,UAAU,EAAE,YAAY,CAAC,CAAC,CAAC,CAAC;CAC9G","sourcesContent":["import type { AgentInputContent } from \"@nexface/agent\";\nimport type { AttachmentAdapter, PendingAttachment, CompleteAttachment } from \"@assistant-ui/react\";\nimport { ImageInputContentSchema, TextInputContentSchema } from \"@ag-ui/core\";\nimport { attachmentContent, readAttachment, validateAttachment, type Attachment } from \"./attachments.js\";\nimport type { ChatAttachmentOptions } from \"./types.js\";\n\ntype Entry = {\n id: string;\n file: File;\n controller: AbortController;\n adapter: ChatAttachmentOptions[\"adapter\"];\n data?: unknown;\n preview?: string | undefined;\n local?: Attachment;\n result?: Attachment;\n adding: boolean;\n sending: boolean;\n error?: string;\n};\nconst errorText = (error: unknown) => error instanceof Error ? error.message : String(error);\nconst durablePreview = (preview?: string) => preview?.startsWith(\"data:image/\") ? preview : undefined;\n\n// Stop local waiting even when a service ignores cancellation; consume late rejections.\nfunction abortable<T>(signal: AbortSignal, task: Promise<T>): Promise<T> {\n return new Promise((resolve, reject) => {\n const abort = () => reject(new DOMException(\"附件处理已取消。\", \"AbortError\"));\n signal.addEventListener(\"abort\", abort, { once: true });\n void task.then(resolve, reject).finally(() => signal.removeEventListener(\"abort\", abort));\n if (signal.aborted) abort();\n });\n}\n\nexport function toAssistantAttachment(attachment: Attachment): CompleteAttachment {\n const content: CompleteAttachment[\"content\"] = attachmentContent(attachment).map((part) => {\n if (part.type === \"text\") return part;\n return { type: \"image\", image: part.source.type === \"data\" ? `data:${part.source.mimeType};base64,${part.source.value}` : part.source.value };\n });\n return { id: attachment.id, name: attachment.name, type: attachment.preview ? \"image\" : \"document\", content, status: { type: \"complete\" } };\n}\n\n// Only this bridge knows assistant-ui's attachment state and lifecycle types.\nexport class AssistantAttachments implements AttachmentAdapter {\n readonly accept = \"*\";\n private entries = new Map<string, Entry>();\n private disposed = false;\n options: false | ChatAttachmentOptions = {};\n constructor(private changed: () => void, private notice: (message: string) => void) {}\n get blocked() { return [...this.entries.values()].some((entry) => entry.adding || Boolean(entry.error)); }\n get processing() { return [...this.entries.values()].some((entry) => entry.adding || entry.sending); }\n get sending() { return [...this.entries.values()].some((entry) => entry.sending); }\n preview(id: string) { return this.entries.get(id)?.preview; }\n\n async *add({ file }: { file: File }): AsyncGenerator<PendingAttachment, void> {\n if (this.disposed || this.options === false) throw new Error(\"附件已禁用。\");\n const options = this.options;\n const maxCount = options.maxCount ?? 3;\n if (!Number.isInteger(maxCount) || maxCount <= 0) throw new Error(\"附件数量限制必须是正整数。\");\n if (this.entries.size >= maxCount) throw new Error(\"附件数量超出限制。\");\n const entry: Entry = { id: crypto.randomUUID(), file, controller: new AbortController(), adapter: options.adapter, adding: true, sending: false };\n this.entries.set(entry.id, entry);\n this.changed();\n const base = { id: entry.id, file, name: file.name, contentType: file.type, type: file.type.startsWith(\"image/\") ? \"image\" : \"document\" };\n yield { ...base, status: { type: \"running\", reason: \"uploading\", progress: 0 } };\n try {\n if (entry.adapter) {\n validateAttachment(file, options);\n const result = await abortable(entry.controller.signal, entry.adapter.add({ id: entry.id, file, signal: entry.controller.signal }));\n this.assertLive(entry);\n entry.data = result.data;\n entry.preview = result.preview;\n } else {\n entry.local = await abortable(entry.controller.signal, readAttachment(file, options));\n this.assertLive(entry);\n entry.preview = entry.local.preview;\n }\n yield { ...base, status: { type: \"requires-action\", reason: \"composer-send\" } };\n } catch (error) {\n if (!this.live(entry)) return;\n entry.error = errorText(error);\n yield { ...base, status: { type: \"incomplete\", reason: \"error\", message: entry.error } };\n } finally {\n entry.adding = false;\n if (!this.disposed) this.changed();\n }\n }\n\n async send(attachment: { id: string }): Promise<CompleteAttachment> {\n const entry = this.entries.get(attachment.id);\n if (!entry) throw new Error(\"附件已移除。\");\n this.assertLive(entry);\n if (entry.adding || entry.error) throw new Error(entry.error ?? \"附件尚未准备完成。\");\n entry.sending = true;\n this.changed();\n try {\n let content: AgentInputContent[];\n if (entry.adapter) {\n const result = await abortable(entry.controller.signal, entry.adapter.send({ id: entry.id, file: entry.file, data: entry.data, signal: entry.controller.signal }));\n this.assertLive(entry);\n if (!Array.isArray(result.content) || !result.content.length) throw new Error(\"附件处理必须返回文本或内联图片。\");\n content = result.content.map((part) => {\n if (part.type === \"text\") return TextInputContentSchema.parse(part);\n const image = ImageInputContentSchema.parse(part);\n if (image.source.type !== \"data\") throw new Error(\"附件仅支持内联图片,不支持图片 URL。\");\n return image;\n });\n } else content = attachmentContent(entry.local!);\n this.assertLive(entry);\n const preview = durablePreview(entry.preview);\n entry.result = { id: entry.id, name: entry.file.name, content, ...(preview ? { preview } : {}) };\n return toAssistantAttachment(entry.result);\n } catch (error) {\n if (this.live(entry)) this.notice(errorText(error));\n throw error;\n } finally {\n entry.sending = false;\n if (!this.disposed) this.changed();\n }\n }\n\n // Removal is local-first. Cleanup failures must not resurrect the chip.\n async remove(attachment: { id: string }): Promise<void> {\n const entry = this.entries.get(attachment.id);\n if (!entry) return;\n this.entries.delete(entry.id);\n entry.controller.abort();\n if (!this.disposed) this.changed();\n void Promise.resolve().then(() => entry.adapter?.remove?.({ id: entry.id, file: entry.file, data: entry.data }))\n .catch((error) => { if (!this.disposed) this.notice(`附件清理失败:${errorText(error)}`); });\n }\n\n take(attachments: readonly CompleteAttachment[]): Attachment[] {\n return attachments.map((attachment) => {\n const entry = this.entries.get(attachment.id);\n if (!entry?.result) throw new Error(\"附件尚未准备完成。\");\n return entry.result;\n });\n }\n commit(attachments: readonly CompleteAttachment[]) {\n for (const attachment of attachments) this.entries.delete(attachment.id);\n this.changed();\n }\n dispose() {\n this.disposed = true;\n for (const id of this.entries.keys()) void this.remove({ id });\n }\n private live(entry: Entry) { return !this.disposed && !entry.controller.signal.aborted && this.entries.get(entry.id) === entry; }\n private assertLive(entry: Entry) { if (!this.live(entry)) throw new DOMException(\"附件处理已取消。\", \"AbortError\"); }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"assistant-attachments.js","sourceRoot":"","sources":["../src/assistant-attachments.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAC9E,OAAO,EAAE,iBAAiB,EAAE,cAAc,EAAE,kBAAkB,EAAmB,MAAM,kBAAkB,CAAC;AAgB1G,MAAM,SAAS,GAAG,CAAC,KAAc,EAAE,EAAE,CAAC,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAC7F,MAAM,cAAc,GAAG,CAAC,OAAgB,EAAE,EAAE,CAAC,OAAO,EAAE,UAAU,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC;AAEtG,wFAAwF;AACxF,SAAS,SAAS,CAAI,MAAmB,EAAE,IAAgB;IACzD,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACrC,MAAM,KAAK,GAAG,GAAG,EAAE,CAAC,MAAM,CAAC,IAAI,YAAY,CAAC,UAAU,EAAE,YAAY,CAAC,CAAC,CAAC;QACvE,MAAM,CAAC,gBAAgB,CAAC,OAAO,EAAE,KAAK,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;QACxD,KAAK,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,MAAM,CAAC,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CAAC,OAAO,IAAI,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC,KAAK,KAAK,CAAC,CAAC,CAAC;IACzH,UAAU,CAAC,KAAY,IAAI,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC;QAAE,MAAM,IAAI,YAAY,CAAC,UAAU,EAAE,YAAY,CAAC,CAAC,CAAC,CAAC;CAC9G","sourcesContent":["import type { AgentInputContent } from \"@nexface/agent\";\nimport type { AttachmentAdapter, PendingAttachment, CompleteAttachment } from \"@assistant-ui/react\";\nimport { ImageInputContentSchema, TextInputContentSchema } from \"@ag-ui/core\";\nimport { attachmentContent, readAttachment, validateAttachment, type Attachment } from \"./attachments.js\";\nimport type { ChatAttachmentOptions } from \"./types.js\";\n\ntype Entry = {\n id: string;\n file: File;\n controller: AbortController;\n adapter: ChatAttachmentOptions[\"adapter\"];\n data?: unknown;\n preview?: string | undefined;\n local?: Attachment;\n result?: Attachment;\n adding: boolean;\n sending: boolean;\n error?: string;\n};\nconst errorText = (error: unknown) => error instanceof Error ? error.message : String(error);\nconst durablePreview = (preview?: string) => preview?.startsWith(\"data:image/\") ? preview : undefined;\n\n// Stop local waiting even when a service ignores cancellation; consume late rejections.\nfunction abortable<T>(signal: AbortSignal, task: Promise<T>): Promise<T> {\n return new Promise((resolve, reject) => {\n const abort = () => reject(new DOMException(\"附件处理已取消。\", \"AbortError\"));\n signal.addEventListener(\"abort\", abort, { once: true });\n void task.then(resolve, reject).finally(() => signal.removeEventListener(\"abort\", abort));\n if (signal.aborted) abort();\n });\n}\n\nexport function toAssistantAttachment(attachment: Attachment): CompleteAttachment {\n const content: CompleteAttachment[\"content\"] = attachmentContent(attachment).map((part) => {\n if (part.type === \"text\") return part;\n return { type: \"image\", image: part.source.type === \"data\" ? `data:${part.source.mimeType};base64,${part.source.value}` : part.source.value };\n });\n return { id: attachment.id, name: attachment.name, type: attachment.preview ? \"image\" : \"document\", content, status: { type: \"complete\" } };\n}\n\n// Only this bridge knows assistant-ui's attachment state and lifecycle types.\nexport class AssistantAttachments implements AttachmentAdapter {\n readonly accept = \"*\";\n private entries = new Map<string, Entry>();\n private disposed = false;\n options: false | ChatAttachmentOptions = {};\n constructor(private changed: () => void, private notice: (message: string) => void) {}\n get blocked() { return [...this.entries.values()].some((entry) => entry.adding || Boolean(entry.error)); }\n get processing() { return [...this.entries.values()].some((entry) => entry.adding || entry.sending); }\n get sending() { return [...this.entries.values()].some((entry) => entry.sending); }\n preview(id: string) { return this.entries.get(id)?.preview; }\n\n async *add({ file }: { file: File }): AsyncGenerator<PendingAttachment, void> {\n if (this.disposed || this.options === false) throw new Error(\"附件已禁用。\");\n const options = this.options;\n const maxCount = options.maxCount ?? 3;\n if (!Number.isInteger(maxCount) || maxCount <= 0) {\n this.notice(\"附件数量限制必须是正整数。\");\n throw new Error(\"附件数量限制必须是正整数。\");\n }\n if (this.entries.size >= maxCount) {\n this.notice(\"附件数量超出限制。\");\n throw new Error(\"附件数量超出限制。\");\n }\n const entry: Entry = { id: crypto.randomUUID(), file, controller: new AbortController(), adapter: options.adapter, adding: true, sending: false };\n this.entries.set(entry.id, entry);\n this.changed();\n const base = { id: entry.id, file, name: file.name, contentType: file.type, type: file.type.startsWith(\"image/\") ? \"image\" : \"document\" };\n yield { ...base, status: { type: \"running\", reason: \"uploading\", progress: 0 } };\n try {\n if (entry.adapter) {\n validateAttachment(file, options);\n const result = await abortable(entry.controller.signal, entry.adapter.add({ id: entry.id, file, signal: entry.controller.signal }));\n this.assertLive(entry);\n entry.data = result.data;\n entry.preview = result.preview;\n } else {\n entry.local = await abortable(entry.controller.signal, readAttachment(file, options));\n this.assertLive(entry);\n entry.preview = entry.local.preview;\n }\n yield { ...base, status: { type: \"requires-action\", reason: \"composer-send\" } };\n } catch (error) {\n if (!this.live(entry)) return;\n entry.error = errorText(error);\n yield { ...base, status: { type: \"incomplete\", reason: \"error\", message: entry.error } };\n } finally {\n entry.adding = false;\n if (!this.disposed) this.changed();\n }\n }\n\n async send(attachment: { id: string }): Promise<CompleteAttachment> {\n const entry = this.entries.get(attachment.id);\n if (!entry) throw new Error(\"附件已移除。\");\n this.assertLive(entry);\n if (entry.adding || entry.error) throw new Error(entry.error ?? \"附件尚未准备完成。\");\n entry.sending = true;\n this.changed();\n try {\n let content: AgentInputContent[];\n if (entry.adapter) {\n const result = await abortable(entry.controller.signal, entry.adapter.send({ id: entry.id, file: entry.file, data: entry.data, signal: entry.controller.signal }));\n this.assertLive(entry);\n if (!Array.isArray(result.content) || !result.content.length) throw new Error(\"附件处理必须返回文本或内联图片。\");\n content = result.content.map((part) => {\n if (part.type === \"text\") return TextInputContentSchema.parse(part);\n const image = ImageInputContentSchema.parse(part);\n if (image.source.type !== \"data\") throw new Error(\"附件仅支持内联图片,不支持图片 URL。\");\n return image;\n });\n } else content = attachmentContent(entry.local!);\n this.assertLive(entry);\n const preview = durablePreview(entry.preview);\n entry.result = { id: entry.id, name: entry.file.name, content, ...(preview ? { preview } : {}) };\n return toAssistantAttachment(entry.result);\n } catch (error) {\n if (this.live(entry)) this.notice(errorText(error));\n throw error;\n } finally {\n entry.sending = false;\n if (!this.disposed) this.changed();\n }\n }\n\n // Removal is local-first. Cleanup failures must not resurrect the chip.\n async remove(attachment: { id: string }): Promise<void> {\n const entry = this.entries.get(attachment.id);\n if (!entry) return;\n this.entries.delete(entry.id);\n entry.controller.abort();\n if (!this.disposed) this.changed();\n void Promise.resolve().then(() => entry.adapter?.remove?.({ id: entry.id, file: entry.file, data: entry.data }))\n .catch((error) => { if (!this.disposed) this.notice(`附件清理失败:${errorText(error)}`); });\n }\n\n take(attachments: readonly CompleteAttachment[]): Attachment[] {\n return attachments.map((attachment) => {\n const entry = this.entries.get(attachment.id);\n if (!entry?.result) throw new Error(\"附件尚未准备完成。\");\n return entry.result;\n });\n }\n commit(attachments: readonly CompleteAttachment[]) {\n for (const attachment of attachments) this.entries.delete(attachment.id);\n this.changed();\n }\n dispose() {\n this.disposed = true;\n for (const id of this.entries.keys()) void this.remove({ id });\n }\n private live(entry: Entry) { return !this.disposed && !entry.controller.signal.aborted && this.entries.get(entry.id) === entry; }\n private assertLive(entry: Entry) { if (!this.live(entry)) throw new DOMException(\"附件处理已取消。\", \"AbortError\"); }\n}\n"]}
|
|
@@ -1,10 +1,7 @@
|
|
|
1
1
|
import { MarkdownText } from "./ui/markdown-text.js";
|
|
2
2
|
export { MarkdownText };
|
|
3
|
-
import { type ToolCallMessagePartComponent } from "@assistant-ui/react";
|
|
4
3
|
import type { AssistantBinding } from "./assistant-runtime.js";
|
|
5
4
|
import type { ChatProps } from "./types.js";
|
|
6
|
-
export declare const ToolDetail: ToolCallMessagePartComponent;
|
|
7
|
-
export declare const HiddenTool: ToolCallMessagePartComponent;
|
|
8
5
|
export declare function AttachmentTile({ binding, savedPreview }: {
|
|
9
6
|
binding?: AssistantBinding;
|
|
10
7
|
savedPreview?: string | undefined;
|
|
@@ -17,3 +14,10 @@ export declare function AssistantComposer({ binding, options, placeholder, busy,
|
|
|
17
14
|
cancelling: boolean;
|
|
18
15
|
cancel(): void;
|
|
19
16
|
}): import("react").JSX.Element;
|
|
17
|
+
export declare function AssistantParts({ showDetails, errors }: {
|
|
18
|
+
showDetails: boolean;
|
|
19
|
+
errors: readonly {
|
|
20
|
+
id: string;
|
|
21
|
+
message: string;
|
|
22
|
+
}[];
|
|
23
|
+
}): import("react").JSX.Element;
|
|
@@ -3,20 +3,19 @@ import { AttachmentUI } from "./ui/attachment.aui.js";
|
|
|
3
3
|
import { useRef } from "react";
|
|
4
4
|
import { MarkdownText } from "./ui/markdown-text.js";
|
|
5
5
|
export { MarkdownText };
|
|
6
|
-
import { Composer
|
|
7
|
-
import { Button } from "./ui/button.js";
|
|
8
|
-
import { TooltipIconButton } from "./ui/tooltip-icon-button.js";
|
|
6
|
+
import { Composer } from "./ui/home-demo/composer.js";
|
|
9
7
|
import { cn } from "./ui/utils.js";
|
|
10
|
-
import { AttachmentPrimitive, ComposerPrimitive, useAuiState } from "@assistant-ui/react";
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
8
|
+
import { AttachmentPrimitive, ComposerPrimitive, useAuiState, MessagePrimitive, groupPartByType } from "@assistant-ui/react";
|
|
9
|
+
import { ArrowUpIcon, PlusIcon, SquareIcon } from "lucide-react";
|
|
10
|
+
import { ToolGroupRoot, ToolGroupContent } from "./ui/tool-group.aui.js";
|
|
11
|
+
import { DisclosureTrigger, ToolCall, disclosureContentClass } from "./ui/home-demo/trace.js";
|
|
12
|
+
import { Reasoning, ReasoningRoot, ReasoningContent, ReasoningText } from "./ui/reasoning.aui.js";
|
|
13
|
+
import { TraceLine } from "./ui/home-demo/trace-line.js";
|
|
13
14
|
import { attachmentAccept } from "./attachments.js";
|
|
14
|
-
export const ToolDetail = ({ toolName, argsText, result, isError }) => _jsxs("details", { className: "nexface-chat__tool", "data-error": isError || undefined, children: [_jsxs("summary", { children: ["\u64CD\u4F5C\u8BB0\u5F55 ", _jsx("span", { "aria-hidden": true, children: "\u203A" })] }), _jsx("strong", { children: toolName }), _jsx("small", { children: result === undefined ? "等待执行结果" : isError ? "未完成" : "已完成" }), _jsxs("div", { children: [_jsx("b", { children: "Input" }), _jsx("pre", { children: argsText })] }), result !== undefined ? _jsxs("div", { children: [_jsx("b", { children: isError ? "Error" : "Output" }), _jsx("pre", { children: typeof result === "string" ? result : JSON.stringify(result) })] }) : null] });
|
|
15
|
-
export const HiddenTool = () => null;
|
|
16
15
|
export function AttachmentTile({ binding, savedPreview }) {
|
|
17
16
|
const attachment = useAuiState((s) => s.attachment);
|
|
18
17
|
const preview = binding?.attachments.preview(attachment.id) ?? savedPreview ?? attachment.content?.find((part) => part.type === "image")?.image;
|
|
19
|
-
return _jsx(AttachmentUI, { preview: preview, children: _jsxs("div", { className: "
|
|
18
|
+
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
19
|
}
|
|
21
20
|
export function AssistantComposer({ binding, options, placeholder, busy, cancelling, cancel }) {
|
|
22
21
|
const input = useRef(null);
|
|
@@ -26,16 +25,31 @@ export function AssistantComposer({ binding, options, placeholder, busy, cancell
|
|
|
26
25
|
for (const file of files)
|
|
27
26
|
void binding.runtime.thread.composer.addAttachment(file).catch((error) => binding.setNotice(error instanceof Error ? error.message : String(error)));
|
|
28
27
|
};
|
|
29
|
-
return _jsxs(Composer, { onSubmit: (event) => { event.preventDefault(); void binding.send(); },
|
|
30
|
-
|
|
31
|
-
event.preventDefault();
|
|
32
|
-
addFiles(Array.from(event.dataTransfer.files));
|
|
33
|
-
} }, input: _jsx(ComposerPrimitive.Input, { className: cn(composerInputClass), "aria-label": "\u8F93\u5165 Agent \u4EFB\u52A1", placeholder: placeholder, disabled: sending, rows: 1, minRows: 2, maxRows: 7, cancelOnEscape: false, onKeyDown: (event) => { if (event.keyCode === 229)
|
|
28
|
+
return _jsxs(Composer, { onSubmit: (event) => { event.preventDefault(); void binding.send(); }, inputProps: { "aria-label": "输入 Agent 任务", placeholder, disabled: sending, cancelOnEscape: false,
|
|
29
|
+
onKeyDown: (event) => { if (event.keyCode === 229)
|
|
34
30
|
event.preventDefault();
|
|
35
31
|
else if (event.key === "Enter" && !event.shiftKey && !event.nativeEvent.isComposing) {
|
|
36
32
|
event.preventDefault();
|
|
37
33
|
void binding.send();
|
|
38
|
-
} } }
|
|
39
|
-
_jsx(ComposerPrimitive.Send, { asChild: true, disabled: sending, children: _jsx(
|
|
34
|
+
} } }, 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") }) }) :
|
|
35
|
+
_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] });
|
|
36
|
+
}
|
|
37
|
+
const groupAssistantParts = groupPartByType({ reasoning: ["group-chainOfThought", "group-reasoning"], source: ["group-chainOfThought", "group-source"], "tool-call": ["group-chainOfThought", "group-tool"], "standalone-tool-call": [] });
|
|
38
|
+
export function AssistantParts({ showDetails, errors }) {
|
|
39
|
+
return _jsxs(_Fragment, { children: [_jsx(MessagePrimitive.GroupedParts, { groupBy: groupAssistantParts, children: ({ part, children }) => {
|
|
40
|
+
switch (part.type) {
|
|
41
|
+
case "group-chainOfThought": return _jsx("div", { children: children });
|
|
42
|
+
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 })] });
|
|
43
|
+
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 }) })] });
|
|
44
|
+
case "reasoning": return _jsx(Reasoning, { ...part });
|
|
45
|
+
case "group-source":
|
|
46
|
+
case "source": return null;
|
|
47
|
+
case "data": return part.dataRendererUI;
|
|
48
|
+
case "text": return part.text === "" && part.status?.type === "running" ? _jsx(TraceLine, { live: true, label: "thinking" }) : _jsx(MarkdownText, {});
|
|
49
|
+
case "tool-call": return part.toolUI ?? _jsx(ToolCall, { ...part, showDetails: showDetails });
|
|
50
|
+
case "indicator": return _jsx(TraceLine, { live: true, label: "thinking" });
|
|
51
|
+
default: return null;
|
|
52
|
+
}
|
|
53
|
+
} }), 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))] });
|
|
40
54
|
}
|
|
41
55
|
//# 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,O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EAAE,CAAC,2BAA2B,CAAC,YAC5C,UAAU,CAAC,CAAC,CAAC,KAAC,MAAM,IAAC,IAAI,EAAC,QAAQ,gBAAY,0BAAM,EAAC,SAAS,EAAE,EAAE,CAAC,yCAAyC,CAAC,EAAE,IAAI,EAAC,MAAM,EAAC,QAAQ,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,YAAE,eAAM,SAAS,EAAC,oBAAoB,GAAG,GAAS,CAAC,CAAC;wBACrN,KAAC,iBAAiB,CAAC,IAAI,IAAC,OAAO,QAAC,QAAQ,EAAE,OAAO,YAAE,KAAC,iBAAiB,IAAC,OAAO,EAAC,0BAAM,EAAC,OAAO,EAAC,SAAS,EAAC,OAAO,EAAE,CAAC,KAAK,EAAE,EAAE,GAAG,KAAK,CAAC,cAAc,EAAE,CAAC,CAAC,KAAK,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,gBAAa,0BAAM,EAAC,SAAS,EAAE,EAAE,CAAC,uCAAuC,CAAC,YAAE,KAAC,kBAAkB,IAAC,MAAM,EAAC,MAAM,GAAG,GAAoB,GAAyB,GACpU,IACL,aACH,cAAK,SAAS,EAAE,EAAE,CAAC,+FAA+F,CAAC,YAAE,KAAC,iBAAiB,CAAC,WAAW,cAAE,GAAG,EAAE,CAAC,KAAC,cAAc,IAAC,OAAO,EAAE,OAAO,GAAI,GAAiC,GAAM,EACrO,OAAO,CAAC,CAAC,CAAC,gBAAO,IAAI,EAAC,QAAQ,2DAAgB,CAAC,CAAC,CAAC,IAAI,IAC7C,CAAC;AACd,CAAC","sourcesContent":["import { AttachmentUI } from \"./ui/attachment.aui.js\";\nimport { useRef } from \"react\";\nimport { MarkdownText } from \"./ui/markdown-text.js\";\nexport { MarkdownText };\nimport { Composer, composerInputClass } from \"./ui/thread.aui.js\";\nimport { Button } from \"./ui/button.js\";\nimport { TooltipIconButton } from \"./ui/tooltip-icon-button.js\";\nimport { cn } from \"./ui/utils.js\";\nimport { AttachmentPrimitive, ComposerPrimitive, useAuiState, type ToolCallMessagePartComponent } from \"@assistant-ui/react\";\nimport { PaperPlaneTiltIcon } from \"@phosphor-icons/react/PaperPlaneTilt\";\nimport { PaperclipIcon } from \"@phosphor-icons/react/Paperclip\";\nimport type { AssistantBinding } from \"./assistant-runtime.js\";\nimport { attachmentAccept } from \"./attachments.js\";\nimport type { ChatProps } from \"./types.js\";\n\nexport const ToolDetail: ToolCallMessagePartComponent = ({ toolName, argsText, result, isError }) => <details className=\"nexface-chat__tool\" data-error={isError || undefined}>\n <summary>操作记录 <span aria-hidden>›</span></summary><strong>{toolName}</strong>\n <small>{result === undefined ? \"等待执行结果\" : isError ? \"未完成\" : \"已完成\"}</small>\n <div><b>Input</b><pre>{argsText}</pre></div>\n {result !== undefined ? <div><b>{isError ? \"Error\" : \"Output\"}</b><pre>{typeof result === \"string\" ? result : JSON.stringify(result)}</pre></div> : null}\n</details>;\nexport const HiddenTool: ToolCallMessagePartComponent = () => null;\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=\"nexface-chat__attachment-status\"><AttachmentPrimitive.Name />\n {binding && attachment.status.type === \"requires-action\" ? <small>已就绪</small> : null}\n {attachment.status.type === \"running\" ? <small>正在处理…</small> : null}\n {attachment.status.type === \"incomplete\" ? <small 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 onDragOver={(event) => { if (options !== false) event.preventDefault(); }}\n onDrop={(event) => { if (options !== false && !sending) { event.preventDefault(); addFiles(Array.from(event.dataTransfer.files)); } }}\n input={<ComposerPrimitive.Input className={cn(composerInputClass)} aria-label=\"输入 Agent 任务\" placeholder={placeholder} disabled={sending} rows={1} minRows={2} maxRows={7} 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 <TooltipIconButton tooltip=\"添加附件\" type=\"button\" className={cn(\"aui-composer-add-attachment text-muted-foreground hover:text-foreground size-7 rounded-full\")} aria-label=\"添加附件\" disabled={sending} onClick={() => input.current?.click()}><PaperclipIcon /></TooltipIconButton></> : <span />}\n <div className={cn(\"flex items-center gap-1.5\")}>\n {showCancel ? <Button type=\"button\" aria-label=\"取消任务\" className={cn(\"aui-composer-cancel size-7 rounded-full\")} size=\"icon\" disabled={cancelling} onClick={cancel}><span className=\"nexface-chat__stop\" /></Button> :\n <ComposerPrimitive.Send asChild disabled={sending}><TooltipIconButton tooltip=\"发送任务\" variant=\"default\" onClick={(event) => { event.preventDefault(); void binding.send(); }} aria-label=\"发送任务\" className={cn(\"aui-composer-send size-7 rounded-full\")}><PaperPlaneTiltIcon weight=\"fill\" /></TooltipIconButton></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"]}
|
|
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,YAAY,EAAE,CAAC;AACxB,OAAO,EAAE,QAAQ,EAAE,MAAM,4BAA4B,CAAC;AAGtD,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,QAAQ,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AACjE,OAAO,EAAE,aAAa,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AACzE,OAAO,EAAE,iBAAiB,EAAE,QAAQ,EAAE,sBAAsB,EAAE,MAAM,yBAAyB,CAAC;AAC9F,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAClG,OAAO,EAAE,SAAS,EAAE,MAAM,8BAA8B,CAAC;AAEzD,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAGpD,MAAM,UAAU,cAAc,CAAC,EAAE,OAAO,EAAE,YAAY,EAAqE;IACzH,MAAM,UAAU,GAAG,WAAW,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC;IACpD,MAAM,OAAO,GAAG,OAAO,EAAE,WAAW,CAAC,OAAO,CAAC,UAAU,CAAC,EAAE,CAAC,IAAI,YA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AC;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\";\nexport { MarkdownText };\nimport { Composer } from \"./ui/home-demo/composer.js\";\n\n\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>{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"]}
|
|
@@ -13,12 +13,14 @@ export type AssistantBinding = {
|
|
|
13
13
|
send(): Promise<void>;
|
|
14
14
|
};
|
|
15
15
|
export declare function convertMessage(message: UIMessage): ThreadMessageLike;
|
|
16
|
-
export declare function
|
|
16
|
+
export declare function projectMessages(messages: readonly UIMessage[]): UIMessage[];
|
|
17
|
+
export declare function SessionRuntime({ id, chat, options, blocked, active, onEdit, children }: {
|
|
17
18
|
id: string;
|
|
18
19
|
chat: ChatState;
|
|
19
20
|
options: ChatProps["attachments"];
|
|
20
21
|
blocked: boolean;
|
|
21
22
|
active: boolean;
|
|
23
|
+
onEdit?(sourceId: string, text: string): Promise<void>;
|
|
22
24
|
children(binding: AssistantBinding): ReactNode;
|
|
23
25
|
}): import("react").JSX.Element;
|
|
24
26
|
export {};
|
|
@@ -3,10 +3,19 @@ import { useEffect, useLayoutEffect, useReducer, useRef, useState } from "react"
|
|
|
3
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
|
+
function parseToolArgs(text) {
|
|
7
|
+
try {
|
|
8
|
+
const value = JSON.parse(text);
|
|
9
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
10
|
+
}
|
|
11
|
+
catch {
|
|
12
|
+
return {};
|
|
13
|
+
}
|
|
14
|
+
}
|
|
6
15
|
export function convertMessage(message) {
|
|
7
|
-
const content = message.parts.map((part) => part.type
|
|
16
|
+
const content = message.parts.map((part) => part.type !== "tool" ? part : {
|
|
8
17
|
type: "tool-call", toolCallId: part.toolCallId, toolName: part.name,
|
|
9
|
-
args:
|
|
18
|
+
args: parseToolArgs(part.arguments),
|
|
10
19
|
argsText: part.arguments, result: part.result, isError: part.isError,
|
|
11
20
|
});
|
|
12
21
|
if (message.role === "user")
|
|
@@ -14,9 +23,22 @@ export function convertMessage(message) {
|
|
|
14
23
|
return { id: message.id, role: "assistant", content, status: message.state === "running"
|
|
15
24
|
? { type: "running" } : message.state === "error" ? { type: "incomplete", reason: "error" } : { type: "complete", reason: "stop" } };
|
|
16
25
|
}
|
|
26
|
+
// Project each user turn to one assistant row without changing persisted messages.
|
|
27
|
+
export function projectMessages(messages) {
|
|
28
|
+
const projected = [];
|
|
29
|
+
for (const message of messages) {
|
|
30
|
+
const previous = projected.at(-1);
|
|
31
|
+
if (message.role === "assistant" && previous?.role === "assistant") {
|
|
32
|
+
projected[projected.length - 1] = { ...previous, parts: [...previous.parts, ...message.parts], ...(message.state ? { state: message.state } : {}) };
|
|
33
|
+
}
|
|
34
|
+
else
|
|
35
|
+
projected.push(message);
|
|
36
|
+
}
|
|
37
|
+
return projected;
|
|
38
|
+
}
|
|
17
39
|
// Keep one composer per visited Session: switching the external-store thread id
|
|
18
40
|
// would invalidate pending attachment work and discard that Session's draft.
|
|
19
|
-
export function SessionRuntime({ id, chat, options, blocked, active, children }) {
|
|
41
|
+
export function SessionRuntime({ id, chat, options, blocked, active, onEdit, children }) {
|
|
20
42
|
const latest = useRef(chat);
|
|
21
43
|
useLayoutEffect(() => { latest.current = chat; });
|
|
22
44
|
const messages = useRef([]);
|
|
@@ -38,7 +60,7 @@ export function SessionRuntime({ id, chat, options, blocked, active, children })
|
|
|
38
60
|
};
|
|
39
61
|
}, [attachments]);
|
|
40
62
|
const runtime = useExternalStoreRuntime({
|
|
41
|
-
messages: messages.current,
|
|
63
|
+
messages: projectMessages(messages.current),
|
|
42
64
|
convertMessage,
|
|
43
65
|
isRunning: active && chat.status !== "idle" && chat.status !== "error" && chat.status !== "waiting",
|
|
44
66
|
isSendDisabled: !active || blocked || attachments.blocked,
|
|
@@ -51,6 +73,25 @@ export function SessionRuntime({ id, chat, options, blocked, active, children })
|
|
|
51
73
|
setNotice("");
|
|
52
74
|
await latest.current.sendMessage(text, files);
|
|
53
75
|
},
|
|
76
|
+
onEdit: onEdit ? async (message) => {
|
|
77
|
+
if (!message.sourceId)
|
|
78
|
+
throw new Error("未找到要编辑的消息。");
|
|
79
|
+
const text = message.content.flatMap((part) => part.type === "text" ? [part.text] : []).join("");
|
|
80
|
+
try {
|
|
81
|
+
await onEdit(message.sourceId, text);
|
|
82
|
+
}
|
|
83
|
+
catch {
|
|
84
|
+
const sourceId = message.sourceId;
|
|
85
|
+
queueMicrotask(() => {
|
|
86
|
+
if (!alive.current || latest.current.activeSessionId !== id)
|
|
87
|
+
return;
|
|
88
|
+
const composer = runtime.thread.getMessageById(sourceId).composer;
|
|
89
|
+
if (!composer.getState().isEditing)
|
|
90
|
+
composer.beginEdit();
|
|
91
|
+
composer.setText(text);
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
} : undefined,
|
|
54
95
|
onCancel: async () => { latest.current.cancel(); },
|
|
55
96
|
adapters: {
|
|
56
97
|
attachments: options === false ? undefined : attachments,
|
|
@@ -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,EAAiD,MAAM,qBAAqB,CAAC;AAC5J,OAAO,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C,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 } 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\nexport function convertMessage(message: UIMessage): ThreadMessageLike {\n const content = message.parts.map((part): Exclude<ThreadMessageLike[\"content\"], string>[number] => part.type === \"text\" ? part : {\n type: \"tool-call\", toolCallId: part.toolCallId, toolName: part.name,\n args: {},\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// 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, children }: {\n id: string; chat: ChatState; options: ChatProps[\"attachments\"]; blocked: boolean; active: boolean;\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: 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 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,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AAE,CAAC,CAAC;YACnG,MAAM,KAAK,GAAG,WAAW,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;YAC1C,WAAW,CAAC,MAAM,CAAC,SAAS,CAAC,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.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"]}
|