@nexface/chat 0.1.1-alpha.1 → 0.1.1-alpha.10
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/THIRD_PARTY_LICENSES.txt +44 -0
- package/dist/assistant-attachments.d.ts +31 -0
- package/dist/assistant-attachments.js +158 -0
- package/dist/assistant-attachments.js.map +1 -0
- package/dist/assistant-components.d.ts +19 -0
- package/dist/assistant-components.js +39 -0
- package/dist/assistant-components.js.map +1 -0
- package/dist/assistant-runtime.d.ts +24 -0
- package/dist/assistant-runtime.js +104 -0
- package/dist/assistant-runtime.js.map +1 -0
- package/dist/attachments.d.ts +3 -1
- package/dist/attachments.js +13 -0
- package/dist/attachments.js.map +1 -1
- package/dist/client.d.ts +89 -0
- package/dist/client.js +620 -0
- package/dist/client.js.map +1 -0
- package/dist/config.d.ts +1 -1
- package/dist/config.js.map +1 -1
- package/dist/default-chat.d.ts +2 -1
- package/dist/default-chat.js +85 -115
- package/dist/default-chat.js.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/messages.d.ts +27 -0
- package/dist/messages.js +121 -0
- package/dist/messages.js.map +1 -0
- package/dist/page-confirmation.d.ts +2 -1
- package/dist/page-confirmation.js.map +1 -1
- package/dist/protocol-messages.d.ts +9 -0
- package/dist/protocol-messages.js +249 -0
- package/dist/protocol-messages.js.map +1 -0
- package/dist/protocol-response.d.ts +32 -0
- package/dist/protocol-response.js +62 -0
- package/dist/protocol-response.js.map +1 -0
- package/dist/react.d.ts +29 -41
- package/dist/react.js +225 -662
- package/dist/react.js.map +1 -1
- package/dist/storage.d.ts +19 -0
- package/dist/storage.js +111 -0
- package/dist/storage.js.map +1 -0
- package/dist/styles.css +2337 -95
- package/dist/tool-result.d.ts +1 -0
- package/dist/tool-result.js +12 -0
- package/dist/tool-result.js.map +1 -0
- package/dist/types.d.ts +40 -1
- package/dist/types.js.map +1 -1
- package/dist/ui/attachment.aui.d.ts +7 -0
- package/dist/ui/attachment.aui.js +93 -0
- package/dist/ui/attachment.aui.js.map +1 -0
- package/dist/ui/avatar.d.ts +11 -0
- package/dist/ui/avatar.js +24 -0
- package/dist/ui/avatar.js.map +1 -0
- package/dist/ui/button.d.ts +13 -0
- package/dist/ui/button.js +38 -0
- package/dist/ui/button.js.map +1 -0
- package/dist/ui/dialog.d.ts +17 -0
- package/dist/ui/dialog.js +43 -0
- package/dist/ui/dialog.js.map +1 -0
- package/dist/ui/dropdown-menu.d.ts +25 -0
- package/dist/ui/dropdown-menu.js +60 -0
- package/dist/ui/dropdown-menu.js.map +1 -0
- package/dist/ui/input.d.ts +3 -0
- package/dist/ui/input.js +9 -0
- package/dist/ui/input.js.map +1 -0
- package/dist/ui/markdown-text.d.ts +7 -0
- package/dist/ui/markdown-text.js +73 -0
- package/dist/ui/markdown-text.js.map +1 -0
- package/dist/ui/skeleton.d.ts +2 -0
- package/dist/ui/skeleton.js +8 -0
- package/dist/ui/skeleton.js.map +1 -0
- package/dist/ui/surface.d.ts +4 -0
- package/dist/ui/surface.js +53 -0
- package/dist/ui/surface.js.map +1 -0
- package/dist/ui/thread-list.aui.d.ts +9 -0
- package/dist/ui/thread-list.aui.js +19 -0
- package/dist/ui/thread-list.aui.js.map +1 -0
- package/dist/ui/thread.aui.d.ts +29 -0
- package/dist/ui/thread.aui.js +25 -0
- package/dist/ui/thread.aui.js.map +1 -0
- package/dist/ui/tooltip-icon-button.d.ts +7 -0
- package/dist/ui/tooltip-icon-button.js +12 -0
- package/dist/ui/tooltip-icon-button.js.map +1 -0
- package/dist/ui/tooltip.d.ts +7 -0
- package/dist/ui/tooltip.js +23 -0
- package/dist/ui/tooltip.js.map +1 -0
- package/dist/ui/use-attachment-src.d.ts +1 -0
- package/dist/ui/use-attachment-src.js +28 -0
- package/dist/ui/use-attachment-src.js.map +1 -0
- package/dist/ui/use-copy-to-clipboard.d.ts +7 -0
- package/dist/ui/use-copy-to-clipboard.js +16 -0
- package/dist/ui/use-copy-to-clipboard.js.map +1 -0
- package/dist/ui/utils.d.ts +2 -0
- package/dist/ui/utils.js +8 -0
- package/dist/ui/utils.js.map +1 -0
- package/package.json +25 -12
- package/dist/operation-surface.d.ts +0 -7
- package/dist/operation-surface.js +0 -79
- package/dist/operation-surface.js.map +0 -1
- package/dist/operation-types.d.ts +0 -17
- package/dist/operation-types.js +0 -2
- package/dist/operation-types.js.map +0 -1
- package/dist/operation-view.d.ts +0 -13
- package/dist/operation-view.js +0 -367
- package/dist/operation-view.js.map +0 -1
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 AgentbaseAI Inc.
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
MIT License
|
|
25
|
+
|
|
26
|
+
Copyright (c) 2023 shadcn
|
|
27
|
+
|
|
28
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
29
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
30
|
+
in the Software without restriction, including without limitation the rights
|
|
31
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
32
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
33
|
+
furnished to do so, subject to the following conditions:
|
|
34
|
+
|
|
35
|
+
The above copyright notice and this permission notice shall be included in all
|
|
36
|
+
copies or substantial portions of the Software.
|
|
37
|
+
|
|
38
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
39
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
40
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
41
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
42
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
43
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
44
|
+
SOFTWARE.
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { AttachmentAdapter, PendingAttachment, CompleteAttachment } from "@assistant-ui/react";
|
|
2
|
+
import { type Attachment } from "./attachments.js";
|
|
3
|
+
import type { ChatAttachmentOptions } from "./types.js";
|
|
4
|
+
export declare function toAssistantAttachment(attachment: Attachment): CompleteAttachment;
|
|
5
|
+
export declare class AssistantAttachments implements AttachmentAdapter {
|
|
6
|
+
private changed;
|
|
7
|
+
private notice;
|
|
8
|
+
readonly accept = "*";
|
|
9
|
+
private entries;
|
|
10
|
+
private disposed;
|
|
11
|
+
options: false | ChatAttachmentOptions;
|
|
12
|
+
constructor(changed: () => void, notice: (message: string) => void);
|
|
13
|
+
get blocked(): boolean;
|
|
14
|
+
get processing(): boolean;
|
|
15
|
+
get sending(): boolean;
|
|
16
|
+
preview(id: string): string | undefined;
|
|
17
|
+
add({ file }: {
|
|
18
|
+
file: File;
|
|
19
|
+
}): AsyncGenerator<PendingAttachment, void>;
|
|
20
|
+
send(attachment: {
|
|
21
|
+
id: string;
|
|
22
|
+
}): Promise<CompleteAttachment>;
|
|
23
|
+
remove(attachment: {
|
|
24
|
+
id: string;
|
|
25
|
+
}): Promise<void>;
|
|
26
|
+
take(attachments: readonly CompleteAttachment[]): Attachment[];
|
|
27
|
+
commit(attachments: readonly CompleteAttachment[]): void;
|
|
28
|
+
dispose(): void;
|
|
29
|
+
private live;
|
|
30
|
+
private assertLive;
|
|
31
|
+
}
|
|
@@ -0,0 +1,158 @@
|
|
|
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);
|
|
4
|
+
const durablePreview = (preview) => preview?.startsWith("data:image/") ? preview : undefined;
|
|
5
|
+
// Stop local waiting even when a service ignores cancellation; consume late rejections.
|
|
6
|
+
function abortable(signal, task) {
|
|
7
|
+
return new Promise((resolve, reject) => {
|
|
8
|
+
const abort = () => reject(new DOMException("附件处理已取消。", "AbortError"));
|
|
9
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
10
|
+
void task.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
|
|
11
|
+
if (signal.aborted)
|
|
12
|
+
abort();
|
|
13
|
+
});
|
|
14
|
+
}
|
|
15
|
+
export function toAssistantAttachment(attachment) {
|
|
16
|
+
const content = attachmentContent(attachment).map((part) => {
|
|
17
|
+
if (part.type === "text")
|
|
18
|
+
return part;
|
|
19
|
+
return { type: "image", image: part.source.type === "data" ? `data:${part.source.mimeType};base64,${part.source.value}` : part.source.value };
|
|
20
|
+
});
|
|
21
|
+
return { id: attachment.id, name: attachment.name, type: attachment.preview ? "image" : "document", content, status: { type: "complete" } };
|
|
22
|
+
}
|
|
23
|
+
// Only this bridge knows assistant-ui's attachment state and lifecycle types.
|
|
24
|
+
export class AssistantAttachments {
|
|
25
|
+
changed;
|
|
26
|
+
notice;
|
|
27
|
+
accept = "*";
|
|
28
|
+
entries = new Map();
|
|
29
|
+
disposed = false;
|
|
30
|
+
options = {};
|
|
31
|
+
constructor(changed, notice) {
|
|
32
|
+
this.changed = changed;
|
|
33
|
+
this.notice = notice;
|
|
34
|
+
}
|
|
35
|
+
get blocked() { return [...this.entries.values()].some((entry) => entry.adding || Boolean(entry.error)); }
|
|
36
|
+
get processing() { return [...this.entries.values()].some((entry) => entry.adding || entry.sending); }
|
|
37
|
+
get sending() { return [...this.entries.values()].some((entry) => entry.sending); }
|
|
38
|
+
preview(id) { return this.entries.get(id)?.preview; }
|
|
39
|
+
async *add({ file }) {
|
|
40
|
+
if (this.disposed || this.options === false)
|
|
41
|
+
throw new Error("附件已禁用。");
|
|
42
|
+
const options = this.options;
|
|
43
|
+
const maxCount = options.maxCount ?? 3;
|
|
44
|
+
if (!Number.isInteger(maxCount) || maxCount <= 0)
|
|
45
|
+
throw new Error("附件数量限制必须是正整数。");
|
|
46
|
+
if (this.entries.size >= maxCount)
|
|
47
|
+
throw new Error("附件数量超出限制。");
|
|
48
|
+
const entry = { id: crypto.randomUUID(), file, controller: new AbortController(), adapter: options.adapter, adding: true, sending: false };
|
|
49
|
+
this.entries.set(entry.id, entry);
|
|
50
|
+
this.changed();
|
|
51
|
+
const base = { id: entry.id, file, name: file.name, contentType: file.type, type: file.type.startsWith("image/") ? "image" : "document" };
|
|
52
|
+
yield { ...base, status: { type: "running", reason: "uploading", progress: 0 } };
|
|
53
|
+
try {
|
|
54
|
+
if (entry.adapter) {
|
|
55
|
+
validateAttachment(file, options);
|
|
56
|
+
const result = await abortable(entry.controller.signal, entry.adapter.add({ id: entry.id, file, signal: entry.controller.signal }));
|
|
57
|
+
this.assertLive(entry);
|
|
58
|
+
entry.data = result.data;
|
|
59
|
+
entry.preview = result.preview;
|
|
60
|
+
}
|
|
61
|
+
else {
|
|
62
|
+
entry.local = await abortable(entry.controller.signal, readAttachment(file, options));
|
|
63
|
+
this.assertLive(entry);
|
|
64
|
+
entry.preview = entry.local.preview;
|
|
65
|
+
}
|
|
66
|
+
yield { ...base, status: { type: "requires-action", reason: "composer-send" } };
|
|
67
|
+
}
|
|
68
|
+
catch (error) {
|
|
69
|
+
if (!this.live(entry))
|
|
70
|
+
return;
|
|
71
|
+
entry.error = errorText(error);
|
|
72
|
+
yield { ...base, status: { type: "incomplete", reason: "error", message: entry.error } };
|
|
73
|
+
}
|
|
74
|
+
finally {
|
|
75
|
+
entry.adding = false;
|
|
76
|
+
if (!this.disposed)
|
|
77
|
+
this.changed();
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
async send(attachment) {
|
|
81
|
+
const entry = this.entries.get(attachment.id);
|
|
82
|
+
if (!entry)
|
|
83
|
+
throw new Error("附件已移除。");
|
|
84
|
+
this.assertLive(entry);
|
|
85
|
+
if (entry.adding || entry.error)
|
|
86
|
+
throw new Error(entry.error ?? "附件尚未准备完成。");
|
|
87
|
+
entry.sending = true;
|
|
88
|
+
this.changed();
|
|
89
|
+
try {
|
|
90
|
+
let content;
|
|
91
|
+
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 }));
|
|
93
|
+
this.assertLive(entry);
|
|
94
|
+
if (!Array.isArray(result.content) || !result.content.length)
|
|
95
|
+
throw new Error("附件处理必须返回文本或内联图片。");
|
|
96
|
+
content = result.content.map((part) => {
|
|
97
|
+
if (part.type === "text")
|
|
98
|
+
return TextInputContentSchema.parse(part);
|
|
99
|
+
const image = ImageInputContentSchema.parse(part);
|
|
100
|
+
if (image.source.type !== "data")
|
|
101
|
+
throw new Error("附件仅支持内联图片,不支持图片 URL。");
|
|
102
|
+
return image;
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
else
|
|
106
|
+
content = attachmentContent(entry.local);
|
|
107
|
+
this.assertLive(entry);
|
|
108
|
+
const preview = durablePreview(entry.preview);
|
|
109
|
+
entry.result = { id: entry.id, name: entry.file.name, content, ...(preview ? { preview } : {}) };
|
|
110
|
+
return toAssistantAttachment(entry.result);
|
|
111
|
+
}
|
|
112
|
+
catch (error) {
|
|
113
|
+
if (this.live(entry))
|
|
114
|
+
this.notice(errorText(error));
|
|
115
|
+
throw error;
|
|
116
|
+
}
|
|
117
|
+
finally {
|
|
118
|
+
entry.sending = false;
|
|
119
|
+
if (!this.disposed)
|
|
120
|
+
this.changed();
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
// Removal is local-first. Cleanup failures must not resurrect the chip.
|
|
124
|
+
async remove(attachment) {
|
|
125
|
+
const entry = this.entries.get(attachment.id);
|
|
126
|
+
if (!entry)
|
|
127
|
+
return;
|
|
128
|
+
this.entries.delete(entry.id);
|
|
129
|
+
entry.controller.abort();
|
|
130
|
+
if (!this.disposed)
|
|
131
|
+
this.changed();
|
|
132
|
+
void Promise.resolve().then(() => entry.adapter?.remove?.({ id: entry.id, file: entry.file, data: entry.data }))
|
|
133
|
+
.catch((error) => { if (!this.disposed)
|
|
134
|
+
this.notice(`附件清理失败:${errorText(error)}`); });
|
|
135
|
+
}
|
|
136
|
+
take(attachments) {
|
|
137
|
+
return attachments.map((attachment) => {
|
|
138
|
+
const entry = this.entries.get(attachment.id);
|
|
139
|
+
if (!entry?.result)
|
|
140
|
+
throw new Error("附件尚未准备完成。");
|
|
141
|
+
return entry.result;
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
commit(attachments) {
|
|
145
|
+
for (const attachment of attachments)
|
|
146
|
+
this.entries.delete(attachment.id);
|
|
147
|
+
this.changed();
|
|
148
|
+
}
|
|
149
|
+
dispose() {
|
|
150
|
+
this.disposed = true;
|
|
151
|
+
for (const id of this.entries.keys())
|
|
152
|
+
void this.remove({ id });
|
|
153
|
+
}
|
|
154
|
+
live(entry) { return !this.disposed && !entry.controller.signal.aborted && this.entries.get(entry.id) === entry; }
|
|
155
|
+
assertLive(entry) { if (!this.live(entry))
|
|
156
|
+
throw new DOMException("附件处理已取消。", "AbortError"); }
|
|
157
|
+
}
|
|
158
|
+
//# sourceMappingURL=assistant-attachments.js.map
|
|
@@ -0,0 +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,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,IA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zH,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"]}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { MarkdownText } from "./ui/markdown-text.js";
|
|
2
|
+
export { MarkdownText };
|
|
3
|
+
import { type ToolCallMessagePartComponent } from "@assistant-ui/react";
|
|
4
|
+
import type { AssistantBinding } from "./assistant-runtime.js";
|
|
5
|
+
import type { ChatProps } from "./types.js";
|
|
6
|
+
export declare const ToolDetail: ToolCallMessagePartComponent;
|
|
7
|
+
export declare const HiddenTool: ToolCallMessagePartComponent;
|
|
8
|
+
export declare function AttachmentTile({ binding, savedPreview }: {
|
|
9
|
+
binding?: AssistantBinding;
|
|
10
|
+
savedPreview?: string | undefined;
|
|
11
|
+
}): import("react").JSX.Element;
|
|
12
|
+
export declare function AssistantComposer({ binding, options, placeholder, busy, cancelling, cancel }: {
|
|
13
|
+
binding: AssistantBinding;
|
|
14
|
+
options: ChatProps["attachments"];
|
|
15
|
+
placeholder: string;
|
|
16
|
+
busy: boolean;
|
|
17
|
+
cancelling: boolean;
|
|
18
|
+
cancel(): void;
|
|
19
|
+
}): import("react").JSX.Element;
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
|
|
2
|
+
import { AttachmentUI } from "./ui/attachment.aui.js";
|
|
3
|
+
import { useRef } from "react";
|
|
4
|
+
import { MarkdownText } from "./ui/markdown-text.js";
|
|
5
|
+
export { MarkdownText };
|
|
6
|
+
import { Composer, composerInputClass } from "./ui/thread.aui.js";
|
|
7
|
+
import { Button } from "./ui/button.js";
|
|
8
|
+
import { TooltipIconButton } from "./ui/tooltip-icon-button.js";
|
|
9
|
+
import { cn } from "./ui/utils.js";
|
|
10
|
+
import { AttachmentPrimitive, ComposerPrimitive, useAuiState } from "@assistant-ui/react";
|
|
11
|
+
import { PaperPlaneTiltIcon } from "@phosphor-icons/react/PaperPlaneTilt";
|
|
12
|
+
import { PaperclipIcon } from "@phosphor-icons/react/Paperclip";
|
|
13
|
+
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
|
+
export function AttachmentTile({ binding, savedPreview }) {
|
|
17
|
+
const attachment = useAuiState((s) => s.attachment);
|
|
18
|
+
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: "nexface-chat__attachment-status", children: [_jsx(AttachmentPrimitive.Name, {}), binding && attachment.status.type === "requires-action" ? _jsx("small", { children: "\u5DF2\u5C31\u7EEA" }) : null, attachment.status.type === "running" ? _jsx("small", { children: "\u6B63\u5728\u5904\u7406\u2026" }) : null, attachment.status.type === "incomplete" ? _jsx("small", { role: "alert", children: attachment.status.message ?? "附件处理失败" }) : null] }) });
|
|
20
|
+
}
|
|
21
|
+
export function AssistantComposer({ binding, options, placeholder, busy, cancelling, cancel }) {
|
|
22
|
+
const input = useRef(null);
|
|
23
|
+
const sending = binding.sending;
|
|
24
|
+
const addFiles = (files) => {
|
|
25
|
+
for (const file of files)
|
|
26
|
+
void binding.runtime.thread.composer.addAttachment(file).catch((error) => binding.setNotice(error instanceof Error ? error.message : String(error)));
|
|
27
|
+
};
|
|
28
|
+
return _jsxs(Composer, { onSubmit: (event) => { event.preventDefault(); void binding.send(); }, onDragOver: (event) => { if (options !== false)
|
|
29
|
+
event.preventDefault(); }, onDrop: (event) => { if (options !== false && !sending) {
|
|
30
|
+
event.preventDefault();
|
|
31
|
+
addFiles(Array.from(event.dataTransfer.files));
|
|
32
|
+
} }, 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)
|
|
33
|
+
event.preventDefault();
|
|
34
|
+
else if (event.key === "Enter" && !event.shiftKey && !event.nativeEvent.isComposing) {
|
|
35
|
+
event.preventDefault();
|
|
36
|
+
void binding.send();
|
|
37
|
+
} } }), 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(TooltipIconButton, { tooltip: "\u6DFB\u52A0\u9644\u4EF6", type: "button", className: cn("aui-composer-add-attachment text-muted-foreground hover:text-foreground size-7 rounded-full"), "aria-label": "\u6DFB\u52A0\u9644\u4EF6", disabled: sending, onClick: () => input.current?.click(), children: _jsx(PaperclipIcon, {}) })] }) : _jsx("span", {}), _jsxs("div", { className: cn("flex items-center gap-1.5"), children: [busy ? _jsx(Button, { type: "button", "aria-label": "\u53D6\u6D88\u4EFB\u52A1", className: cn("aui-composer-cancel size-7 rounded-full"), size: "icon", disabled: cancelling, onClick: cancel, children: _jsx("span", { className: "nexface-chat__stop" }) }) : null, _jsx(ComposerPrimitive.Send, { asChild: true, disabled: sending, children: _jsx(TooltipIconButton, { tooltip: "\u53D1\u9001\u4EFB\u52A1", variant: "default", onClick: (event) => { event.preventDefault(); void binding.send(); }, "aria-label": "\u53D1\u9001\u4EFB\u52A1", className: cn("aui-composer-send size-7 rounded-full"), children: _jsx(PaperPlaneTiltIcon, { weight: "fill" }) }) })] })] }), 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] });
|
|
38
|
+
}
|
|
39
|
+
//# sourceMappingURL=assistant-components.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"assistant-components.js","sourceRoot":"","sources":["../src/assistant-components.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AACtD,OAAO,EAAE,MAAM,EAAE,MAAM,OAAO,CAAC;AAC/B,OAAO,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AACrD,OAAO,EAAE,YAAY,EAAE,CAAC;AACxB,OAAO,EAAE,QAAQ,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AAClE,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AACxC,OAAO,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAChE,OAAO,EAAE,EAAE,EAAE,MAAM,eAAe,CAAC;AACnC,OAAO,EAAE,mBAAmB,EAAE,iBAAiB,EAAE,WAAW,EAAqC,MAAM,qBAAqB,CAAC;AAC7H,OAAO,EAAE,kBAAkB,EAAE,MAAM,sCAAsC,CAAC;AAC1E,OAAO,EAAE,aAAa,EAAE,MAAM,iCAAiC,CAAC;AAEhE,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAGpD,MAAM,CAAC,MAAM,UAAU,GAAiC,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC,mBAAS,SAAS,EAAC,oBAAoB,gBAAa,OAAO,IAAI,SAAS,aAC3K,2DAAc,yDAA0B,IAAU,EA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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 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 {busy ? <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> : null}\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"]}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { type ReactNode } from "react";
|
|
2
|
+
import { type AssistantRuntime, type ThreadMessageLike } from "@assistant-ui/react";
|
|
3
|
+
import { AssistantAttachments } from "./assistant-attachments.js";
|
|
4
|
+
import { type useChat, type UIMessage } from "./react.js";
|
|
5
|
+
import type { ChatProps } from "./types.js";
|
|
6
|
+
type ChatState = ReturnType<typeof useChat>;
|
|
7
|
+
export type AssistantBinding = {
|
|
8
|
+
runtime: AssistantRuntime;
|
|
9
|
+
attachments: AssistantAttachments;
|
|
10
|
+
notice: string;
|
|
11
|
+
setNotice(message: string): void;
|
|
12
|
+
sending: boolean;
|
|
13
|
+
send(): Promise<void>;
|
|
14
|
+
};
|
|
15
|
+
export declare function convertMessage(message: UIMessage): ThreadMessageLike;
|
|
16
|
+
export declare function SessionRuntime({ id, chat, options, blocked, active, children }: {
|
|
17
|
+
id: string;
|
|
18
|
+
chat: ChatState;
|
|
19
|
+
options: ChatProps["attachments"];
|
|
20
|
+
blocked: boolean;
|
|
21
|
+
active: boolean;
|
|
22
|
+
children(binding: AssistantBinding): ReactNode;
|
|
23
|
+
}): import("react").JSX.Element;
|
|
24
|
+
export {};
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
+
import { useEffect, useLayoutEffect, useReducer, useRef, useState } from "react";
|
|
3
|
+
import { AssistantRuntimeProvider, MessageNotSentError, useExternalStoreRuntime } from "@assistant-ui/react";
|
|
4
|
+
import { AssistantAttachments, toAssistantAttachment } from "./assistant-attachments.js";
|
|
5
|
+
import { assertChatSendable } from "./react.js";
|
|
6
|
+
export function convertMessage(message) {
|
|
7
|
+
const content = message.parts.map((part) => part.type === "text" ? part : {
|
|
8
|
+
type: "tool-call", toolCallId: part.toolCallId, toolName: part.name,
|
|
9
|
+
args: {},
|
|
10
|
+
argsText: part.arguments, result: part.result, isError: part.isError,
|
|
11
|
+
});
|
|
12
|
+
if (message.role === "user")
|
|
13
|
+
return { id: message.id, role: "user", content, attachments: message.attachments?.map(toAssistantAttachment) };
|
|
14
|
+
return { id: message.id, role: "assistant", content, status: message.state === "running"
|
|
15
|
+
? { type: "running" } : message.state === "error" ? { type: "incomplete", reason: "error" } : { type: "complete", reason: "stop" } };
|
|
16
|
+
}
|
|
17
|
+
// Keep one composer per visited Session: switching the external-store thread id
|
|
18
|
+
// would invalidate pending attachment work and discard that Session's draft.
|
|
19
|
+
export function SessionRuntime({ id, chat, options, blocked, active, children }) {
|
|
20
|
+
const latest = useRef(chat);
|
|
21
|
+
useLayoutEffect(() => { latest.current = chat; });
|
|
22
|
+
const messages = useRef([]);
|
|
23
|
+
if (chat.activeSessionId === id)
|
|
24
|
+
messages.current = chat.messages;
|
|
25
|
+
const [, refresh] = useReducer((n) => n + 1, 0);
|
|
26
|
+
const [notice, setNotice] = useState("");
|
|
27
|
+
const [sending, setSending] = useState(false);
|
|
28
|
+
const sendLock = useRef(false);
|
|
29
|
+
const [attachments] = useState(() => new AssistantAttachments(refresh, setNotice));
|
|
30
|
+
attachments.options = options ?? {};
|
|
31
|
+
const alive = useRef(false);
|
|
32
|
+
useEffect(() => {
|
|
33
|
+
alive.current = true;
|
|
34
|
+
return () => {
|
|
35
|
+
alive.current = false;
|
|
36
|
+
queueMicrotask(() => { if (!alive.current)
|
|
37
|
+
attachments.dispose(); });
|
|
38
|
+
};
|
|
39
|
+
}, [attachments]);
|
|
40
|
+
const runtime = useExternalStoreRuntime({
|
|
41
|
+
messages: messages.current,
|
|
42
|
+
convertMessage,
|
|
43
|
+
isRunning: active && chat.status !== "idle" && chat.status !== "error" && chat.status !== "waiting",
|
|
44
|
+
isSendDisabled: !active || blocked || attachments.blocked,
|
|
45
|
+
onNew: async (message) => {
|
|
46
|
+
if (!alive.current || latest.current.activeSessionId !== id)
|
|
47
|
+
throw new MessageNotSentError("会话已切换,请返回原会话重新发送。");
|
|
48
|
+
const files = attachments.take(message.attachments ?? []);
|
|
49
|
+
const text = message.content.flatMap((part) => part.type === "text" ? [part.text] : []).join("");
|
|
50
|
+
attachments.commit(message.attachments ?? []);
|
|
51
|
+
setNotice("");
|
|
52
|
+
await latest.current.sendMessage(text, files);
|
|
53
|
+
},
|
|
54
|
+
onCancel: async () => { latest.current.cancel(); },
|
|
55
|
+
adapters: {
|
|
56
|
+
attachments: options === false ? undefined : attachments,
|
|
57
|
+
threadList: {
|
|
58
|
+
threadId: id,
|
|
59
|
+
threads: chat.sessions.map((session) => ({ id: session.id, title: session.title, status: "regular" })),
|
|
60
|
+
onSwitchToNewThread: () => { latest.current.createSession(); },
|
|
61
|
+
onSwitchToThread: (next) => latest.current.switchSession(next),
|
|
62
|
+
onRename: (target, title) => latest.current.renameSession(target, title),
|
|
63
|
+
onDelete: (target) => latest.current.deleteSession(target),
|
|
64
|
+
},
|
|
65
|
+
},
|
|
66
|
+
});
|
|
67
|
+
const send = async () => {
|
|
68
|
+
const draft = runtime.thread.composer.getState();
|
|
69
|
+
if (!active || blocked || attachments.blocked || sendLock.current || draft.isEmpty)
|
|
70
|
+
return;
|
|
71
|
+
sendLock.current = true;
|
|
72
|
+
setSending(true);
|
|
73
|
+
setNotice("");
|
|
74
|
+
try {
|
|
75
|
+
// Prepare before dispatch: the upstream void send API cannot report upload
|
|
76
|
+
// rejections to its caller. Keep the draft intact until every file settles.
|
|
77
|
+
const results = await Promise.allSettled(draft.attachments.map((attachment) => attachments.send(attachment)));
|
|
78
|
+
const failed = results.find((result) => result.status === "rejected");
|
|
79
|
+
if (failed?.status === "rejected")
|
|
80
|
+
throw failed.reason;
|
|
81
|
+
if (!alive.current)
|
|
82
|
+
return;
|
|
83
|
+
if (latest.current.activeSessionId !== id)
|
|
84
|
+
throw new Error("会话已切换,请返回原会话重新发送。");
|
|
85
|
+
assertChatSendable(latest.current, id);
|
|
86
|
+
const completed = results.flatMap((result) => result.status === "fulfilled" ? [result.value] : []);
|
|
87
|
+
const files = attachments.take(completed);
|
|
88
|
+
attachments.commit(completed);
|
|
89
|
+
runtime.thread.composer.reset();
|
|
90
|
+
void latest.current.sendMessage(draft.text, files).catch(() => undefined);
|
|
91
|
+
}
|
|
92
|
+
catch (error) {
|
|
93
|
+
if (alive.current && !(error instanceof DOMException && error.name === "AbortError"))
|
|
94
|
+
setNotice(error instanceof Error ? error.message : String(error));
|
|
95
|
+
}
|
|
96
|
+
finally {
|
|
97
|
+
sendLock.current = false;
|
|
98
|
+
if (alive.current)
|
|
99
|
+
setSending(false);
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
return _jsx(AssistantRuntimeProvider, { runtime: runtime, children: active ? children({ runtime, attachments, notice, setNotice, sending, send }) : null });
|
|
103
|
+
}
|
|
104
|
+
//# sourceMappingURL=assistant-runtime.js.map
|
|
@@ -0,0 +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,EAAE,oBAAoB,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AACzF,OAAO,EAAE,kBAAkB,EAAgC,MAAM,YAAY,CAAC;AAM9E,MAAM,UAAU,cAAc,C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AO;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"]}
|
package/dist/attachments.d.ts
CHANGED
|
@@ -3,8 +3,10 @@ import type { ChatAttachmentOptions } from "./types.js";
|
|
|
3
3
|
export interface Attachment {
|
|
4
4
|
id: string;
|
|
5
5
|
name: string;
|
|
6
|
-
content: AgentInputContent;
|
|
6
|
+
content: AgentInputContent | AgentInputContent[];
|
|
7
7
|
preview?: string;
|
|
8
8
|
}
|
|
9
9
|
export declare const attachmentAccept = ".txt,.md,.csv,.json,.png,.jpg,.jpeg,.webp";
|
|
10
|
+
export declare const attachmentContent: (attachment: Attachment) => AgentInputContent[];
|
|
11
|
+
export declare function validateAttachment(file: File, options: ChatAttachmentOptions): void;
|
|
10
12
|
export declare function readAttachment(file: File, options: ChatAttachmentOptions): Promise<Attachment>;
|
package/dist/attachments.js
CHANGED
|
@@ -3,6 +3,19 @@ const types = {
|
|
|
3
3
|
png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", webp: "image/webp",
|
|
4
4
|
};
|
|
5
5
|
export const attachmentAccept = ".txt,.md,.csv,.json,.png,.jpg,.jpeg,.webp";
|
|
6
|
+
export const attachmentContent = (attachment) => Array.isArray(attachment.content) ? attachment.content : [attachment.content];
|
|
7
|
+
export function validateAttachment(file, options) {
|
|
8
|
+
if (options.maxSizeBytes !== undefined && (!Number.isFinite(options.maxSizeBytes) || options.maxSizeBytes <= 0))
|
|
9
|
+
throw new Error("附件大小限制必须是正数。");
|
|
10
|
+
if (file.size > (options.maxSizeBytes ?? 5 * 1024 * 1024))
|
|
11
|
+
throw new Error(`文件过大:${file.name}`);
|
|
12
|
+
const extension = file.name.split(".").at(-1)?.toLowerCase() ?? "";
|
|
13
|
+
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))))
|
|
17
|
+
throw new Error(`不接受此文件:${file.name}`);
|
|
18
|
+
}
|
|
6
19
|
export async function readAttachment(file, options) {
|
|
7
20
|
if (options.maxSizeBytes !== undefined && (!Number.isFinite(options.maxSizeBytes) || options.maxSizeBytes <= 0))
|
|
8
21
|
throw new Error("附件大小限制必须是正数。");
|
package/dist/attachments.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"attachments.js","sourceRoot":"","sources":["../src/attachments.ts"],"names":[],"mappings":"AAUA,MAAM,KAAK,GAA2B;IACpC,GAAG,EAAE,YAAY,EAAE,EAAE,EAAE,eAAe,EAAE,GAAG,EAAE,UAAU,EAAE,IAAI,EAAE,kBAAkB;IACjF,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,YAAY,EAAE,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE,YAAY;CAC5E,CAAC;AACF,MAAM,CAAC,MAAM,gBAAgB,GAAG,2CAA2C,CAAC;AAE5E,MAAM,CAAC,KAAK,UAAU,cAAc,CAAC,IAAU,EAAE,OAA8B;IAC7E,IAAI,OAAO,CAAC,YAAY,KAAK,SAAS,IAAI,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,YAAY,C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EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,OAAO,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,IAAI,CAAC,IAAI,KAAK,KAAK,EAAE,EAAE,EAAE,CAAC;IAC/F,CAAC;IACD,MAAM,OAAO,GAAG,MAAM,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IACvC,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE;YAC9C,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,EAAE,QAAQ,EAAE,IAAI,EAAE;SACxG,EAAE,CAAC;AACN,CAAC;AAED,SAAS,IAAI,CAAC,IAAU,EAAE,KAAc;IACtC,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACrC,MAAM,MAAM,GAAG,IAAI,UAAU,EAAE,CAAC;QAChC,MAAM,CAAC,MAAM,GAAG,GAAG,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC;QACrD,MAAM,CAAC,OAAO,GAAG,GAAG,EAAE,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,UAAU,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;QAChE,IAAI,KAAK;YAAE,MAAM,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;;YACjC,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;IAC/B,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { AgentInputContent } from \"@nexface/agent\";\nimport type { ChatAttachmentOptions } from \"./types.js\";\n\nexport interface Attachment {\n id: string;\n name: string;\n content: AgentInputContent | AgentInputContent[];\n preview?: string;\n}\n\nconst types: Record<string, string> = {\n txt: \"text/plain\", md: \"text/markdown\", csv: \"text/csv\", json: \"application/json\",\n png: \"image/png\", jpg: \"image/jpeg\", jpeg: \"image/jpeg\", webp: \"image/webp\",\n};\nexport const attachmentAccept = \".txt,.md,.csv,.json,.png,.jpg,.jpeg,.webp\";\n\nexport const attachmentContent = (attachment: Attachment): AgentInputContent[] =>\n Array.isArray(attachment.content) ? attachment.content : [attachment.content];\n\nexport function validateAttachment(file: File, options: ChatAttachmentOptions): void {\n if (options.maxSizeBytes !== undefined && (!Number.isFinite(options.maxSizeBytes) || options.maxSizeBytes <= 0)) throw new Error(\"附件大小限制必须是正数。\");\n if (file.size > (options.maxSizeBytes ?? 5 * 1024 * 1024)) throw new Error(`文件过大:${file.name}`);\n const extension = file.name.split(\".\").at(-1)?.toLowerCase() ?? \"\";\n const mime = file.type || types[extension] || \"\";\n const accepted = (options.accept ?? attachmentAccept).split(\",\").map((part) => part.trim().toLowerCase());\n if (!accepted.some((part) => part === \"*\" || part === `.${extension}` || part === mime\n || part.endsWith(\"/*\") && mime.startsWith(part.slice(0, -1)))) throw new Error(`不接受此文件:${file.name}`);\n}\n\nexport async function readAttachment(file: File, options: ChatAttachmentOptions): Promise<Attachment> {\n if (options.maxSizeBytes !== undefined && (!Number.isFinite(options.maxSizeBytes) || options.maxSizeBytes <= 0)) throw new Error(\"附件大小限制必须是正数。\");\n const extension = file.name.split(\".\").at(-1)?.toLowerCase() ?? \"\";\n const mime = types[extension];\n if (!mime || (file.type && file.type !== mime && !(extension === \"md\" && file.type === \"text/plain\"))) {\n throw new Error(`不支持文件类型:${file.name}`);\n }\n const accepted = (options.accept ?? attachmentAccept).split(\",\").map((part) => part.trim().toLowerCase());\n if (!accepted.some((part) => part === `.${extension}` || part === mime\n || part.endsWith(\"/*\") && mime.startsWith(part.slice(0, -1)))) {\n throw new Error(`不接受此文件:${file.name}`);\n }\n if (file.size > (options.maxSizeBytes ?? 5 * 1024 * 1024)) throw new Error(`文件过大:${file.name}`);\n const id = globalThis.crypto.randomUUID();\n if (!mime.startsWith(\"image/\")) {\n const value = await read(file, false);\n return { id, name: file.name, content: { type: \"text\", text: `附件 ${file.name}\\n${value}` } };\n }\n const preview = await read(file, true);\n return { id, name: file.name, preview, content: {\n type: \"image\", source: { type: \"data\", value: preview.slice(preview.indexOf(\",\") + 1), mimeType: mime },\n } };\n}\n\nfunction read(file: File, image: boolean): Promise<string> {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onload = () => resolve(String(reader.result));\n reader.onerror = () => reject(new Error(`无法读取文件:${file.name}`));\n if (image) reader.readAsDataURL(file);\n else reader.readAsText(file);\n });\n}\n"]}
|