@nexface/chat 0.1.14 → 0.1.15-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. package/dist/assistant-attachments.js +17 -60
  2. package/dist/assistant-attachments.js.map +1 -0
  3. package/dist/assistant-components.d.ts +3 -3
  4. package/dist/assistant-components.js +29 -77
  5. package/dist/assistant-components.js.map +1 -0
  6. package/dist/assistant-runtime.d.ts +1 -1
  7. package/dist/assistant-runtime.js +43 -100
  8. package/dist/assistant-runtime.js.map +1 -0
  9. package/dist/attachments.js +15 -36
  10. package/dist/attachments.js.map +1 -0
  11. package/dist/client.js +73 -312
  12. package/dist/client.js.map +1 -0
  13. package/dist/config.js +5 -4
  14. package/dist/config.js.map +1 -0
  15. package/dist/default-chat.d.ts +1 -1
  16. package/dist/default-chat.js +728 -2102
  17. package/dist/default-chat.js.map +7 -0
  18. package/dist/errors.js +18 -55
  19. package/dist/errors.js.map +1 -0
  20. package/dist/index.js +1 -0
  21. package/dist/index.js.map +1 -0
  22. package/dist/messages.js +1 -0
  23. package/dist/messages.js.map +1 -0
  24. package/dist/page-confirmation.js +4 -3
  25. package/dist/page-confirmation.js.map +1 -0
  26. package/dist/protocol-messages.js +66 -290
  27. package/dist/protocol-messages.js.map +1 -0
  28. package/dist/protocol-response.js +18 -38
  29. package/dist/protocol-response.js.map +1 -0
  30. package/dist/react.js +50 -146
  31. package/dist/react.js.map +1 -0
  32. package/dist/shared/errors.d.ts +1 -1
  33. package/dist/shared/errors.js +1 -0
  34. package/dist/shared/errors.js.map +1 -0
  35. package/dist/shared/runtime-controller.d.ts +0 -1
  36. package/dist/shared/runtime-controller.js +1 -0
  37. package/dist/shared/runtime-controller.js.map +1 -0
  38. package/dist/shared/runtime-execution.js +1 -0
  39. package/dist/shared/runtime-execution.js.map +1 -0
  40. package/dist/shared/schema.js +19 -45
  41. package/dist/shared/schema.js.map +1 -0
  42. package/dist/storage.js +53 -130
  43. package/dist/storage.js.map +1 -0
  44. package/dist/styles.css +20 -99
  45. package/dist/tool-result.js +3 -7
  46. package/dist/tool-result.js.map +1 -0
  47. package/dist/types.js +1 -0
  48. package/dist/types.js.map +1 -0
  49. package/dist/ui/attachment.aui.d.ts +1 -1
  50. package/dist/ui/attachment.aui.js +20 -16
  51. package/dist/ui/attachment.aui.js.map +1 -0
  52. package/dist/ui/avatar.js +1 -0
  53. package/dist/ui/avatar.js.map +1 -0
  54. package/dist/ui/button.js +1 -0
  55. package/dist/ui/button.js.map +1 -0
  56. package/dist/ui/code-block.js +3 -2
  57. package/dist/ui/code-block.js.map +1 -0
  58. package/dist/ui/collapsible.js +3 -2
  59. package/dist/ui/collapsible.js.map +1 -0
  60. package/dist/ui/composer-voice.js +2 -3
  61. package/dist/ui/composer-voice.js.map +1 -0
  62. package/dist/ui/dialog.d.ts +1 -1
  63. package/dist/ui/dialog.js +4 -9
  64. package/dist/ui/dialog.js.map +1 -0
  65. package/dist/ui/dropdown-menu.js +3 -2
  66. package/dist/ui/dropdown-menu.js.map +1 -0
  67. package/dist/ui/home-demo/action-bar.js +1 -0
  68. package/dist/ui/home-demo/action-bar.js.map +1 -0
  69. package/dist/ui/home-demo/composer.js +4 -7
  70. package/dist/ui/home-demo/composer.js.map +1 -0
  71. package/dist/ui/home-demo/greeting.d.ts +1 -1
  72. package/dist/ui/home-demo/greeting.js +2 -1
  73. package/dist/ui/home-demo/greeting.js.map +1 -0
  74. package/dist/ui/home-demo/messages.d.ts +1 -1
  75. package/dist/ui/home-demo/messages.js +5 -4
  76. package/dist/ui/home-demo/messages.js.map +1 -0
  77. package/dist/ui/home-demo/styles.js +1 -0
  78. package/dist/ui/home-demo/styles.js.map +1 -0
  79. package/dist/ui/home-demo/suggestions.d.ts +1 -1
  80. package/dist/ui/home-demo/suggestions.js +3 -5
  81. package/dist/ui/home-demo/suggestions.js.map +1 -0
  82. package/dist/ui/home-demo/surfaces.js +2 -3
  83. package/dist/ui/home-demo/surfaces.js.map +1 -0
  84. package/dist/ui/home-demo/thread.d.ts +1 -1
  85. package/dist/ui/home-demo/thread.js +2 -1
  86. package/dist/ui/home-demo/thread.js.map +1 -0
  87. package/dist/ui/home-demo/trace-line.d.ts +1 -1
  88. package/dist/ui/home-demo/trace-line.js +3 -2
  89. package/dist/ui/home-demo/trace-line.js.map +1 -0
  90. package/dist/ui/home-demo/trace.d.ts +1 -1
  91. package/dist/ui/home-demo/trace.js +9 -28
  92. package/dist/ui/home-demo/trace.js.map +1 -0
  93. package/dist/ui/home-demo/type.js +1 -0
  94. package/dist/ui/home-demo/type.js.map +1 -0
  95. package/dist/ui/input.js +1 -0
  96. package/dist/ui/input.js.map +1 -0
  97. package/dist/ui/markdown-text.js +3 -2
  98. package/dist/ui/markdown-text.js.map +1 -0
  99. package/dist/ui/reasoning.aui.js +3 -2
  100. package/dist/ui/reasoning.aui.js.map +1 -0
  101. package/dist/ui/reasoning.d.ts +1 -1
  102. package/dist/ui/reasoning.js +9 -6
  103. package/dist/ui/reasoning.js.map +1 -0
  104. package/dist/ui/surface.js +8 -27
  105. package/dist/ui/surface.js.map +1 -0
  106. package/dist/ui/thread-list.aui.d.ts +2 -2
  107. package/dist/ui/thread-list.aui.js +12 -18
  108. package/dist/ui/thread-list.aui.js.map +1 -0
  109. package/dist/ui/tool-group.aui.js +3 -2
  110. package/dist/ui/tool-group.aui.js.map +1 -0
  111. package/dist/ui/tooltip-icon-button.js +2 -1
  112. package/dist/ui/tooltip-icon-button.js.map +1 -0
  113. package/dist/ui/tooltip.js +1 -0
  114. package/dist/ui/tooltip.js.map +1 -0
  115. package/dist/ui/use-attachment-src.js +2 -1
  116. package/dist/ui/use-attachment-src.js.map +1 -0
  117. package/dist/ui/use-copy-to-clipboard.d.ts +1 -1
  118. package/dist/ui/use-copy-to-clipboard.js +2 -1
  119. package/dist/ui/use-copy-to-clipboard.js.map +1 -0
  120. package/dist/ui/utils.js +3 -9
  121. package/dist/ui/utils.js.map +1 -0
  122. package/dist/use-next-message.js +4 -7
  123. package/dist/use-next-message.js.map +1 -0
  124. package/dist/voice/types.js +1 -0
  125. package/dist/voice/types.js.map +1 -0
  126. package/dist/voice/use-voice.js +13 -35
  127. package/dist/voice/use-voice.js.map +1 -0
  128. package/package.json +4 -8
@@ -1,51 +1,30 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
2
  import { useEffect, useLayoutEffect, useReducer, useRef, useState } from "react";
3
- import { AssistantRuntimeProvider, MessageNotSentError, useExternalStoreRuntime, } from "@assistant-ui/react";
3
+ import { AssistantRuntimeProvider, MessageNotSentError, useExternalStoreRuntime } from "@assistant-ui/react";
4
4
  import { AssistantAttachments, toAssistantAttachment } from "./assistant-attachments.js";
5
5
  import { assertChatSendable } from "./react.js";
6
6
  import { useVoiceInput } from "./voice/use-voice.js";
7
7
  function parseToolArgs(text) {
8
8
  try {
9
9
  const value = JSON.parse(text);
10
- return value !== null && typeof value === "object" && !Array.isArray(value)
11
- ? value
12
- : {};
10
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
13
11
  }
14
12
  catch {
15
13
  return {};
16
14
  }
17
15
  }
18
16
  export function convertMessage(message) {
19
- const content = message.parts.map((part) => part.type !== "tool"
20
- ? part
21
- : {
22
- type: "tool-call",
23
- toolCallId: part.toolCallId,
24
- toolName: part.name,
25
- args: parseToolArgs(part.arguments),
26
- argsText: part.arguments,
27
- result: part.result,
28
- isError: part.isError,
29
- });
17
+ const content = message.parts.map((part) => part.type !== "tool" ? part : {
18
+ type: "tool-call", toolCallId: part.toolCallId, toolName: part.name,
19
+ args: parseToolArgs(part.arguments),
20
+ argsText: part.arguments, result: part.result, isError: part.isError,
21
+ });
30
22
  if (message.role === "user")
31
- return {
32
- id: message.id,
33
- role: "user",
34
- content,
35
- attachments: message.attachments?.map(toAssistantAttachment),
36
- };
37
- return {
38
- id: message.id,
39
- role: "assistant",
40
- content,
41
- status: message.error
23
+ return { id: message.id, role: "user", content, attachments: message.attachments?.map(toAssistantAttachment) };
24
+ return { id: message.id, role: "assistant", content, status: message.error
42
25
  ? { type: "incomplete", reason: "error", error: message.error.userMessage }
43
- : message.state === "cancelled"
44
- ? { type: "incomplete", reason: "cancelled" }
45
- : message.state === "running"
46
- ? { type: "running" }
47
- : { type: "complete", reason: "stop" },
48
- };
26
+ : message.state === "cancelled" ? { type: "incomplete", reason: "cancelled" }
27
+ : message.state === "running" ? { type: "running" } : { type: "complete", reason: "stop" } };
49
28
  }
50
29
  // Project each user turn to one assistant row without changing persisted messages.
51
30
  export function projectMessages(messages) {
@@ -53,12 +32,7 @@ export function projectMessages(messages) {
53
32
  for (const message of messages) {
54
33
  const previous = projected.at(-1);
55
34
  if (message.role === "assistant" && previous?.role === "assistant") {
56
- projected[projected.length - 1] = {
57
- ...previous,
58
- parts: [...previous.parts, ...message.parts],
59
- ...(message.state ? { state: message.state } : {}),
60
- ...(message.error ? { error: message.error } : {}),
61
- };
35
+ projected[projected.length - 1] = { ...previous, parts: [...previous.parts, ...message.parts], ...(message.state ? { state: message.state } : {}), ...(message.error ? { error: message.error } : {}) };
62
36
  }
63
37
  else
64
38
  projected.push(message);
@@ -67,11 +41,9 @@ export function projectMessages(messages) {
67
41
  }
68
42
  // Keep one composer per visited Session: switching the external-store thread id
69
43
  // would invalidate pending attachment work and discard that Session's draft.
70
- export function SessionRuntime({ id, chat, options, dictation, open = true, blocked, active, onEdit, children, }) {
44
+ export function SessionRuntime({ id, chat, options, dictation, open = true, blocked, active, onEdit, children }) {
71
45
  const latest = useRef(chat);
72
- useLayoutEffect(() => {
73
- latest.current = chat;
74
- });
46
+ useLayoutEffect(() => { latest.current = chat; });
75
47
  const messages = useRef([]);
76
48
  if (chat.activeSessionId === id)
77
49
  messages.current = chat.messages;
@@ -82,23 +54,14 @@ export function SessionRuntime({ id, chat, options, dictation, open = true, bloc
82
54
  const [attachments] = useState(() => new AssistantAttachments(refresh, setNotice));
83
55
  attachments.options = options ?? {};
84
56
  const alive = useRef(false);
85
- const voice = useVoiceInput({
86
- dictation,
87
- active,
88
- open,
89
- blocked: blocked || sending || attachments.blocked,
90
- sessionId: id,
91
- composer: () => runtime.thread.composer,
92
- notice: setNotice,
93
- });
57
+ const voice = useVoiceInput({ dictation, active, open, blocked: blocked || sending || attachments.blocked,
58
+ sessionId: id, composer: () => runtime.thread.composer, notice: setNotice });
94
59
  useEffect(() => {
95
60
  alive.current = true;
96
61
  return () => {
97
62
  alive.current = false;
98
- queueMicrotask(() => {
99
- if (!alive.current)
100
- attachments.dispose();
101
- });
63
+ queueMicrotask(() => { if (!alive.current)
64
+ attachments.dispose(); });
102
65
  };
103
66
  }, [attachments]);
104
67
  const runtime = useExternalStoreRuntime({
@@ -110,52 +73,38 @@ export function SessionRuntime({ id, chat, options, dictation, open = true, bloc
110
73
  if (!alive.current || latest.current.activeSessionId !== id)
111
74
  throw new MessageNotSentError("会话已切换,请返回原会话重新发送。");
112
75
  const files = attachments.take(message.attachments ?? []);
113
- const text = message.content
114
- .flatMap((part) => (part.type === "text" ? [part.text] : []))
115
- .join("");
76
+ const text = message.content.flatMap((part) => part.type === "text" ? [part.text] : []).join("");
116
77
  attachments.commit(message.attachments ?? []);
117
78
  setNotice("");
118
79
  await latest.current.sendMessage(text, files);
119
80
  },
120
- onEdit: onEdit
121
- ? async (message) => {
122
- if (!message.sourceId)
123
- throw new Error("未找到要编辑的消息。");
124
- const text = message.content
125
- .flatMap((part) => (part.type === "text" ? [part.text] : []))
126
- .join("");
127
- try {
128
- await onEdit(message.sourceId, text);
129
- }
130
- catch {
131
- const sourceId = message.sourceId;
132
- queueMicrotask(() => {
133
- if (!alive.current || latest.current.activeSessionId !== id)
134
- return;
135
- const composer = runtime.thread.getMessageById(sourceId).composer;
136
- if (!composer.getState().isEditing)
137
- composer.beginEdit();
138
- composer.setText(text);
139
- });
140
- }
81
+ onEdit: onEdit ? async (message) => {
82
+ if (!message.sourceId)
83
+ throw new Error("未找到要编辑的消息。");
84
+ const text = message.content.flatMap((part) => part.type === "text" ? [part.text] : []).join("");
85
+ try {
86
+ await onEdit(message.sourceId, text);
141
87
  }
142
- : undefined,
143
- onCancel: async () => {
144
- latest.current.cancel();
145
- },
88
+ catch {
89
+ const sourceId = message.sourceId;
90
+ queueMicrotask(() => {
91
+ if (!alive.current || latest.current.activeSessionId !== id)
92
+ return;
93
+ const composer = runtime.thread.getMessageById(sourceId).composer;
94
+ if (!composer.getState().isEditing)
95
+ composer.beginEdit();
96
+ composer.setText(text);
97
+ });
98
+ }
99
+ } : undefined,
100
+ onCancel: async () => { latest.current.cancel(); },
146
101
  adapters: {
147
102
  dictation: voice.dictation,
148
103
  attachments: options === false ? undefined : attachments,
149
104
  threadList: {
150
105
  threadId: id,
151
- threads: chat.sessions.map((session) => ({
152
- id: session.id,
153
- title: session.title,
154
- status: "regular",
155
- })),
156
- onSwitchToNewThread: () => {
157
- latest.current.createSession();
158
- },
106
+ threads: chat.sessions.map((session) => ({ id: session.id, title: session.title, status: "regular" })),
107
+ onSwitchToNewThread: () => { latest.current.createSession(); },
159
108
  onSwitchToThread: (next) => latest.current.switchSession(next),
160
109
  onRename: (target, title) => latest.current.renameSession(target, title),
161
110
  onDelete: (target) => latest.current.deleteSession(target),
@@ -164,12 +113,7 @@ export function SessionRuntime({ id, chat, options, dictation, open = true, bloc
164
113
  });
165
114
  const send = async () => {
166
115
  const draft = runtime.thread.composer.getState();
167
- if (!active ||
168
- blocked ||
169
- attachments.blocked ||
170
- sendLock.current ||
171
- voice.state.status !== "idle" ||
172
- draft.isEmpty)
116
+ if (!active || blocked || attachments.blocked || sendLock.current || voice.state.status !== "idle" || draft.isEmpty)
173
117
  return;
174
118
  sendLock.current = true;
175
119
  setSending(true);
@@ -202,7 +146,6 @@ export function SessionRuntime({ id, chat, options, dictation, open = true, bloc
202
146
  setSending(false);
203
147
  }
204
148
  };
205
- return (_jsx(AssistantRuntimeProvider, { runtime: runtime, children: active
206
- ? children({ runtime, attachments, notice, setNotice, sending, voice: voice.state, send })
207
- : null }));
149
+ return _jsx(AssistantRuntimeProvider, { runtime: runtime, children: active ? children({ runtime, attachments, notice, setNotice, sending, voice: voice.state, send }) : null });
208
150
  }
151
+ //# 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,EAAgF,MAAM,qBAAqB,CAAC;AAC3L,OAAO,EAAE,oBAAoB,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AACzF,OAAO,EAAE,kBAAkB,EAAgC,MAAM,YAAY,CAAC;AAE9E,OAAO,EAAE,aAAa,EAA2B,MAAM,sBAAsB,CAAC;AAK9E,SAAS,aAAa,CAAC,IAAY;IACjC,IAAI,CAAC;QACH,MAAM,KAAK,GAAY,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QACxC,OAAO,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAyC,CAAC,CAAC,CAAC,EAAE,CAAC;IAC/H,CAAC;IAAC,MAAM,CAAC;QAAC,OAAO,EAAE,CAAC;IAAC,CAAC;AACxB,CAAC;AAED,MAAM,UAAU,cAAc,CAAC,OAAkB;IAC/C,MAAM,OAAO,GAAG,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAyD,EAAE,CAAC,IAAI,CAAC,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC;QAC/H,IAAI,EAAE,WAAW,EAAE,UAAU,EAAE,IAAI,CAAC,UAAU,EAAE,QAAQ,EAAE,IAAI,CAAC,IAAI;Q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EAAE,KAAK,CAAC,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,GAA4B,CAAC;AAC3L,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\";\nimport { useVoiceInput, type VoiceComposerState } from \"./voice/use-voice.js\";\n\ntype ChatState = ReturnType<typeof useChat>;\nexport type AssistantBinding = { runtime: AssistantRuntime; attachments: AssistantAttachments; notice: string; setNotice(message: string): void; sending: boolean; voice: VoiceComposerState; send(): Promise<void> };\n\nfunction parseToolArgs(text: string): ToolCallMessagePartProps[\"args\"] {\n try {\n const value: unknown = JSON.parse(text);\n return value !== null && typeof value === \"object\" && !Array.isArray(value) ? value as ToolCallMessagePartProps[\"args\"] : {};\n } catch { return {}; }\n}\n\nexport function convertMessage(message: UIMessage): ThreadMessageLike {\n const content = message.parts.map((part): Exclude<ThreadMessageLike[\"content\"], string>[number] => part.type !== \"tool\" ? part : {\n type: \"tool-call\", toolCallId: part.toolCallId, toolName: part.name,\n args: parseToolArgs(part.arguments),\n argsText: part.arguments, result: part.result, isError: part.isError,\n });\n if (message.role === \"user\") return { id: message.id, role: \"user\", content, attachments: message.attachments?.map(toAssistantAttachment) };\n return { id: message.id, role: \"assistant\", content, status: message.error\n ? { type: \"incomplete\", reason: \"error\", error: message.error.userMessage }\n : message.state === \"cancelled\" ? { type: \"incomplete\", reason: \"cancelled\" }\n : message.state === \"running\" ? { type: \"running\" } : { type: \"complete\", reason: \"stop\" } };\n}\n\n// Project each user turn to one assistant row without changing persisted messages.\nexport function projectMessages(messages: readonly UIMessage[]): UIMessage[] {\n const projected: UIMessage[] = [];\n for (const message of messages) {\n const previous = projected.at(-1);\n if (message.role === \"assistant\" && previous?.role === \"assistant\") {\n projected[projected.length - 1] = { ...previous, parts: [...previous.parts, ...message.parts], ...(message.state ? { state: message.state } : {}), ...(message.error ? { error: message.error } : {}) };\n } else projected.push(message);\n }\n return projected;\n}\n\n// Keep one composer per visited Session: switching the external-store thread id\n// would invalidate pending attachment work and discard that Session's draft.\nexport function SessionRuntime({ id, chat, options, dictation, open = true, blocked, active, onEdit, children }: {\n id: string; chat: ChatState; options: ChatProps[\"attachments\"]; blocked: boolean; active: boolean;\n dictation?: ChatProps[\"dictation\"]; open?: 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 const voice = useVoiceInput({ dictation, active, open, blocked: blocked || sending || attachments.blocked,\n sessionId: id, composer: () => runtime.thread.composer, notice: setNotice });\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 || voice.state.status !== \"idle\",\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 dictation: voice.dictation,\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 (): Promise<void> => {\n const draft = runtime.thread.composer.getState();\n if (!active || blocked || attachments.blocked || sendLock.current || voice.state.status !== \"idle\" || 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, voice: voice.state, send }) : null}</AssistantRuntimeProvider>;\n}\n"]}
@@ -1,48 +1,32 @@
1
1
  const types = {
2
- txt: "text/plain",
3
- md: "text/markdown",
4
- csv: "text/csv",
5
- json: "application/json",
6
- png: "image/png",
7
- jpg: "image/jpeg",
8
- jpeg: "image/jpeg",
9
- webp: "image/webp",
2
+ txt: "text/plain", md: "text/markdown", csv: "text/csv", json: "application/json",
3
+ png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", webp: "image/webp",
10
4
  };
11
5
  export const attachmentAccept = ".txt,.md,.csv,.json,.png,.jpg,.jpeg,.webp";
12
6
  export const attachmentContent = (attachment) => Array.isArray(attachment.content) ? attachment.content : [attachment.content];
13
7
  export function validateAttachment(file, options) {
14
- if (options.maxSizeBytes !== undefined &&
15
- (!Number.isFinite(options.maxSizeBytes) || options.maxSizeBytes <= 0))
8
+ if (options.maxSizeBytes !== undefined && (!Number.isFinite(options.maxSizeBytes) || options.maxSizeBytes <= 0))
16
9
  throw new Error("附件大小限制必须是正数。");
17
10
  if (file.size > (options.maxSizeBytes ?? 5 * 1024 * 1024))
18
11
  throw new Error(`文件过大:${file.name}`);
19
12
  const extension = file.name.split(".").at(-1)?.toLowerCase() ?? "";
20
13
  const mime = file.type || types[extension] || "";
21
- const accepted = (options.accept ?? attachmentAccept)
22
- .split(",")
23
- .map((part) => part.trim().toLowerCase());
24
- if (!accepted.some((part) => part === "*" ||
25
- part === `.${extension}` ||
26
- part === mime ||
27
- (part.endsWith("/*") && mime.startsWith(part.slice(0, -1)))))
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))))
28
17
  throw new Error(`不接受此文件:${file.name}`);
29
18
  }
30
19
  export async function readAttachment(file, options) {
31
- if (options.maxSizeBytes !== undefined &&
32
- (!Number.isFinite(options.maxSizeBytes) || options.maxSizeBytes <= 0))
20
+ if (options.maxSizeBytes !== undefined && (!Number.isFinite(options.maxSizeBytes) || options.maxSizeBytes <= 0))
33
21
  throw new Error("附件大小限制必须是正数。");
34
22
  const extension = file.name.split(".").at(-1)?.toLowerCase() ?? "";
35
23
  const mime = types[extension];
36
- if (!mime ||
37
- (file.type && file.type !== mime && !(extension === "md" && file.type === "text/plain"))) {
24
+ if (!mime || (file.type && file.type !== mime && !(extension === "md" && file.type === "text/plain"))) {
38
25
  throw new Error(`不支持文件类型:${file.name}`);
39
26
  }
40
- const accepted = (options.accept ?? attachmentAccept)
41
- .split(",")
42
- .map((part) => part.trim().toLowerCase());
43
- if (!accepted.some((part) => part === `.${extension}` ||
44
- part === mime ||
45
- (part.endsWith("/*") && mime.startsWith(part.slice(0, -1))))) {
27
+ const accepted = (options.accept ?? attachmentAccept).split(",").map((part) => part.trim().toLowerCase());
28
+ if (!accepted.some((part) => part === `.${extension}` || part === mime
29
+ || part.endsWith("/*") && mime.startsWith(part.slice(0, -1)))) {
46
30
  throw new Error(`不接受此文件:${file.name}`);
47
31
  }
48
32
  if (file.size > (options.maxSizeBytes ?? 5 * 1024 * 1024))
@@ -53,15 +37,9 @@ export async function readAttachment(file, options) {
53
37
  return { id, name: file.name, content: { type: "text", text: `附件 ${file.name}\n${value}` } };
54
38
  }
55
39
  const preview = await read(file, true);
56
- return {
57
- id,
58
- name: file.name,
59
- preview,
60
- content: {
61
- type: "image",
62
- source: { type: "data", value: preview.slice(preview.indexOf(",") + 1), mimeType: mime },
63
- },
64
- };
40
+ return { id, name: file.name, preview, content: {
41
+ type: "image", source: { type: "data", value: preview.slice(preview.indexOf(",") + 1), mimeType: mime },
42
+ } };
65
43
  }
66
44
  function read(file, image) {
67
45
  return new Promise((resolve, reject) => {
@@ -74,3 +52,4 @@ function read(file, image) {
74
52
  reader.readAsText(file);
75
53
  });
76
54
  }
55
+ //# sourceMappingURL=attachments.js.map
@@ -0,0 +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,MAAM,iBAAiB,GAAG,CAAC,UAAsB,EAAuB,EAAE,CAC/E,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;AAEhF,MAAM,UAAU,kBAAkB,CAAC,IAAU,EAAE,OAA8B;IAC3E,IAAI,OAAO,CAAC,YAAY,KAAK,SAAS,IAAI,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,YAAY,CAAC,IAAI,OAAO,CAAC,YAAY,IAAI,CAAC,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,cAAc,CAAC,CAAC;IACjJ,IAAI,IAAI,CAAC,IAAI,GAAG,CAAC,OAAO,CAAC,YAAY,IAAI,CAAC,GAAG,IAAI,GAAG,IAAI,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,QAAQ,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC;IAChG,MAAM,SAAS,GAAG,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,WAAW,E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,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"]}