@njuptlzf/agent-chat-web 0.0.0-stage → 0.2.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.
Files changed (82) hide show
  1. package/dist/AgentChat.d.ts +28 -0
  2. package/dist/AgentChat.js +355 -0
  3. package/dist/AgentChatApp.d.ts +31 -0
  4. package/dist/AgentChatApp.js +90 -0
  5. package/dist/DockPanel.d.ts +22 -0
  6. package/dist/DockPanel.js +22 -0
  7. package/dist/PersonasPage.d.ts +1 -0
  8. package/dist/PersonasPage.js +318 -0
  9. package/dist/adapter.d.ts +52 -0
  10. package/dist/adapter.js +242 -0
  11. package/dist/app-def-check.d.ts +50 -0
  12. package/dist/app-def-check.js +184 -0
  13. package/dist/app.d.ts +112 -0
  14. package/dist/app.js +174 -0
  15. package/dist/auth.d.ts +41 -0
  16. package/dist/auth.js +86 -0
  17. package/dist/dock.d.ts +52 -0
  18. package/dist/dock.js +132 -0
  19. package/dist/docs.d.ts +48 -0
  20. package/dist/docs.js +178 -0
  21. package/dist/index.d.ts +17 -0
  22. package/dist/index.js +8 -0
  23. package/dist/mount.d.ts +50 -0
  24. package/dist/mount.js +38 -0
  25. package/dist/qual.d.ts +21 -0
  26. package/dist/qual.js +53 -0
  27. package/dist/sse.d.ts +14 -0
  28. package/dist/sse.js +99 -0
  29. package/dist/styles.css +1478 -0
  30. package/dist/theme.d.ts +10 -0
  31. package/dist/theme.js +14 -0
  32. package/dist/ui/CodeCopyHeader.d.ts +7 -0
  33. package/dist/ui/CodeCopyHeader.js +22 -0
  34. package/dist/ui/ConfirmCard.d.ts +15 -0
  35. package/dist/ui/ConfirmCard.js +9 -0
  36. package/dist/ui/Lightbox.d.ts +6 -0
  37. package/dist/ui/Lightbox.js +31 -0
  38. package/dist/ui/QueueBar.d.ts +44 -0
  39. package/dist/ui/QueueBar.js +17 -0
  40. package/dist/ui/Splitter.d.ts +27 -0
  41. package/dist/ui/Splitter.js +61 -0
  42. package/dist/ui/ThemeToggle.d.ts +2 -0
  43. package/dist/ui/ThemeToggle.js +16 -0
  44. package/dist/ui/TierPicker.d.ts +14 -0
  45. package/dist/ui/TierPicker.js +54 -0
  46. package/dist/ui/UIPromptCard.d.ts +17 -0
  47. package/dist/ui/UIPromptCard.js +18 -0
  48. package/dist/ui/timefmt.d.ts +35 -0
  49. package/dist/ui/timefmt.js +110 -0
  50. package/dist/ui/useNarrow.d.ts +7 -0
  51. package/dist/ui/useNarrow.js +15 -0
  52. package/package.json +72 -6
  53. package/src/App.tsx +13 -0
  54. package/src/agent-chat/AgentChat.tsx +692 -0
  55. package/src/agent-chat/AgentChatApp.tsx +206 -0
  56. package/src/agent-chat/DockPanel.tsx +74 -0
  57. package/src/agent-chat/PersonasPage.tsx +678 -0
  58. package/src/agent-chat/adapter.ts +272 -0
  59. package/src/agent-chat/app-def-check.ts +215 -0
  60. package/src/agent-chat/app.tsx +327 -0
  61. package/src/agent-chat/auth.ts +83 -0
  62. package/src/agent-chat/dock.ts +162 -0
  63. package/src/agent-chat/docs.ts +179 -0
  64. package/src/agent-chat/index.ts +17 -0
  65. package/src/agent-chat/mount.tsx +123 -0
  66. package/src/agent-chat/qual.ts +55 -0
  67. package/src/agent-chat/sse.ts +104 -0
  68. package/src/agent-chat/theme.ts +23 -0
  69. package/src/agent-chat/ui/CodeCopyHeader.tsx +29 -0
  70. package/src/agent-chat/ui/ConfirmCard.tsx +32 -0
  71. package/src/agent-chat/ui/Lightbox.tsx +32 -0
  72. package/src/agent-chat/ui/QueueBar.tsx +70 -0
  73. package/src/agent-chat/ui/Splitter.tsx +81 -0
  74. package/src/agent-chat/ui/ThemeToggle.tsx +25 -0
  75. package/src/agent-chat/ui/TierPicker.tsx +112 -0
  76. package/src/agent-chat/ui/UIPromptCard.tsx +68 -0
  77. package/src/agent-chat/ui/timefmt.ts +110 -0
  78. package/src/agent-chat/ui/useNarrow.ts +20 -0
  79. package/src/fake-product/entry.tsx +54 -0
  80. package/src/main.tsx +8 -0
  81. package/src/styles.css +1478 -0
  82. package/README.md +0 -3
@@ -0,0 +1,692 @@
1
+ import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
2
+ import type { BrandingResponse, ChatCommand, ChatImage, ModelTier, TokenUsage } from "@njuptlzf/agent-chat-protocol";
3
+ import {
4
+ ActionBarPrimitive,
5
+ AuiIf,
6
+ AssistantRuntimeProvider,
7
+ ComposerPrimitive,
8
+ MessagePrimitive,
9
+ ThreadPrimitive,
10
+ useAui,
11
+ useAuiState,
12
+ useLocalRuntime,
13
+ useMessageTiming,
14
+ type FeedbackAdapter,
15
+ type FileMessagePartProps,
16
+ type ReasoningMessagePartProps,
17
+ type ThreadMessageLike,
18
+ type ToolCallMessagePartProps,
19
+ } from "@assistant-ui/react";
20
+ import { MarkdownTextPrimitive } from "@assistant-ui/react-markdown";
21
+ import { createChatAdapter, dataUrlToImage, markEdit, type UiNotifyEvent, type UiPromptEvent } from "./adapter.ts";
22
+ import { docKind, docPart, fileToDoc, MAX_DOCS, type DocEntry } from "./docs.ts";
23
+ import { auth } from "./auth.ts";
24
+ import { dockStore, subscribeChat } from "./dock.ts";
25
+ import { postDecision, postJson } from "./sse.ts";
26
+ import { ConfirmCard, type ConfirmRequest } from "./ui/ConfirmCard.tsx";
27
+ import CodeCopyHeader from "./ui/CodeCopyHeader.tsx";
28
+ import { Lightbox } from "./ui/Lightbox.tsx";
29
+ import { QueueBar, type QueuedMessage, type QueuedPart } from "./ui/QueueBar.tsx";
30
+ import { TierPicker } from "./ui/TierPicker.tsx";
31
+ import ThemeToggle from "./ui/ThemeToggle.tsx";
32
+ import { UIPromptCard } from "./ui/UIPromptCard.tsx";
33
+
34
+ export default function ChatApp({
35
+ branding,
36
+ sessionId,
37
+ initialMessages,
38
+ tier,
39
+ scope,
40
+ renderCard,
41
+ persona,
42
+ title,
43
+ policyNote,
44
+ welcome,
45
+ suggestions,
46
+ commands,
47
+ onRunEnd,
48
+ onTier,
49
+ }: {
50
+ branding: BrandingResponse;
51
+ sessionId?: string;
52
+ initialMessages?: readonly ThreadMessageLike[];
53
+ tier?: string;
54
+ scope?: string;
55
+ /** 产物卡渲染器:由产品 AppDef 注入,core 不认识 details 的形状。 */
56
+ renderCard?: (details: unknown) => ReactNode;
57
+ /**
58
+ * 人格:随每条消息发给服务端;undefined = 产品默认助手。
59
+ * **id 由产品 manifest 声明**,core 不认识具体名字(通用化),
60
+ * 所以这里是普通字符串,不是字面量联合类型。
61
+ */
62
+ persona?: string;
63
+ /** 对话区列头(2026-11-04):随人格换(声明人格→「人格 B」),缺省回落产品名。 */
64
+ title?: string;
65
+ /** 常驻提示条(如「由 AI 生成,仅供参考」)。只在人格需要说明时传。 */
66
+ policyNote?: string;
67
+ /** 空态文案/快捷问法覆盖(声明人格与默认助手问的不是一类事)。 */
68
+ welcome?: string;
69
+ suggestions?: string[];
70
+ commands: ChatCommand[];
71
+ onRunEnd: () => void;
72
+ onTier: (id: string) => void;
73
+ }) {
74
+ const [running, setRunning] = useState(false);
75
+ const [queue, setQueue] = useState<QueuedMessage[]>([]);
76
+ const [usage, setUsage] = useState<TokenUsage | null>(null);
77
+ const [confirms, setConfirms] = useState<ConfirmRequest[]>([]);
78
+ const [uiPrompts, setUiPrompts] = useState<UiPromptEvent[]>([]);
79
+ const [notices, setNotices] = useState<(UiNotifyEvent & { key: number })[]>([]);
80
+ // 工具中文名(SSE 首帧 tools_meta)——用户视角只显示这句,不显示声明名。
81
+ const [toolLabels, setToolLabels] = useState<Record<string, string>>({});
82
+ const noticeSeq = useRef(0);
83
+ const runningRef = useRef(false);
84
+ const queueRef = useRef<QueuedMessage[]>([]);
85
+ const sessionIdRef = useRef<string | undefined>(sessionId);
86
+ const tierRef = useRef(tier);
87
+ const scopeRef = useRef(scope);
88
+ queueRef.current = queue;
89
+ tierRef.current = tier;
90
+ scopeRef.current = scope;
91
+
92
+ const adapter = useMemo(
93
+ () =>
94
+ createChatAdapter({
95
+ getSessionId: () => sessionIdRef.current,
96
+ setSessionId: (id) => {
97
+ sessionIdRef.current = id;
98
+ },
99
+ getContext: () => {
100
+ // One-shot: a page-supplied context belongs to the message that
101
+ // carried it, never to the next thing typed into the box.
102
+ const ctx = contextRef.current;
103
+ contextRef.current = undefined;
104
+ return ctx;
105
+ },
106
+ getAuthToken: () => auth.token,
107
+ getTier: () => tierRef.current,
108
+ getScope: () => scopeRef.current,
109
+ getPersona: () => persona,
110
+ onRunEnd: ({ usage }) => {
111
+ setUsage(usage);
112
+ setConfirms([]);
113
+ setUiPrompts([]);
114
+ runningRef.current = false;
115
+ setRunning(false);
116
+ onRunEnd();
117
+ setTimeout(() => flushRef.current?.(), 0);
118
+ },
119
+ onToolConfirm: (info) => setConfirms((c) => [...c.filter((x) => x.toolCallId !== info.toolCallId), info]),
120
+ onToolSettled: (toolCallId) => setConfirms((c) => c.filter((x) => x.toolCallId !== toolCallId)),
121
+ onToolsMeta: (labels) => setToolLabels(labels),
122
+ onUiPrompt: (p) => setUiPrompts((xs) => [...xs.filter((x) => x.id !== p.id), p]),
123
+ onUiNotify: (n) => {
124
+ const key = ++noticeSeq.current;
125
+ setNotices((xs) => [...xs, { ...n, key }]);
126
+ setTimeout(() => setNotices((xs) => xs.filter((x) => x.key !== key)), 8000);
127
+ },
128
+ }),
129
+ [onRunEnd],
130
+ );
131
+ // A7: thumbs up/down. The official FeedbackAdapter hook gives us the rated
132
+ // message; the client message id is an opaque ref (the server's own messageId
133
+ // is a per-run counter, so it cannot anchor a stored answer).
134
+ const feedbackAdapter = useMemo<FeedbackAdapter>(
135
+ () => ({
136
+ submit: ({ message, type }) => {
137
+ const sid = sessionIdRef.current;
138
+ if (!sid) return;
139
+ void postJson("/api/feedback", { sessionId: sid, rating: type === "positive" ? "up" : "down", ref: message.id }, auth.token).catch(
140
+ () => {},
141
+ );
142
+ },
143
+ }),
144
+ [],
145
+ );
146
+
147
+ const runtime = useLocalRuntime(adapter, { initialMessages, adapters: { feedback: feedbackAdapter } });
148
+
149
+ const answerConfirm = useCallback((info: ConfirmRequest, allow: boolean) => {
150
+ setConfirms((c) => c.filter((x) => x.toolCallId !== info.toolCallId));
151
+ void postDecision({ sessionId: info.sessionId, toolCallId: info.toolCallId, allow }, auth.token);
152
+ }, []);
153
+
154
+ // Answer an extension dialog. The server pairs it back to the parked run by id;
155
+ // a lost POST is harmless (the prompt fails closed on its own timeout).
156
+ const answerUI = useCallback((prompt: UiPromptEvent, answer: { value?: string; confirmed?: boolean; cancelled?: true }) => {
157
+ setUiPrompts((xs) => xs.filter((x) => x.id !== prompt.id));
158
+ const sessionId = sessionIdRef.current;
159
+ if (!sessionId) return;
160
+ void postJson("/api/ui-response", { sessionId, id: prompt.id, ...answer }, auth.token).catch(() => {});
161
+ }, []);
162
+
163
+ const flush = useCallback(() => {
164
+ const [head, ...rest] = queueRef.current;
165
+ if (!head) return;
166
+ setQueue(rest);
167
+ runningRef.current = true;
168
+ setRunning(true);
169
+ runtime.thread.append({ role: "user", content: head });
170
+ }, [runtime]);
171
+ const flushRef = useRef(flush);
172
+ flushRef.current = flush;
173
+
174
+ const send = useCallback(
175
+ (raw: string, images: ChatImage[] = [], docs: DocEntry[] = []) => {
176
+ const text = raw.trim();
177
+ if (!text && images.length === 0 && docs.length === 0) return;
178
+ const content: QueuedPart[] = [
179
+ ...(text ? [{ type: "text" as const, text }] : []),
180
+ ...images.map((img) => ({ type: "image" as const, image: `data:${img.mimeType};base64,${img.data}` })),
181
+ // B4-A: converted documents ride file parts; the adapter re-reads them.
182
+ ...docs.map((d) => docPart(d)),
183
+ ];
184
+ if (runningRef.current) {
185
+ // E2: the whole message waits, images included — the queue stores parts,
186
+ // so a queued attachment is appended with the text that carried it.
187
+ setQueue((q) => [...q, content]);
188
+ return;
189
+ }
190
+ runningRef.current = true;
191
+ setRunning(true);
192
+ runtime.thread.append({ role: "user", content });
193
+ },
194
+ [runtime],
195
+ );
196
+
197
+ // Host-injected prompts: the dock's sendToChat() hands work to whichever chat
198
+ // is mounted, with the caller's page context attached to that one message.
199
+ const contextRef = useRef<Record<string, unknown> | undefined>(undefined);
200
+ useEffect(
201
+ () =>
202
+ subscribeChat((task) => {
203
+ contextRef.current = task.context;
204
+ send(task.text);
205
+ }),
206
+ [send],
207
+ );
208
+
209
+ // 坞(Dock)要知道有没有对话在跑:业务页跳转前据此提示。
210
+ useEffect(() => {
211
+ dockStore.setRunning(running);
212
+ }, [running]);
213
+
214
+ // steer: bump one queued item to the front and stop the current run to make room now
215
+ const steer = (i: number) => {
216
+ setQueue((q) => {
217
+ const item = q[i];
218
+ return item ? [item, ...q.filter((_, j) => j !== i)] : q;
219
+ });
220
+ runtime.thread.cancelRun();
221
+ };
222
+ const drop = (i: number) => setQueue((q) => q.filter((_, j) => j !== i));
223
+
224
+ return (
225
+ <AssistantRuntimeProvider runtime={runtime}>
226
+ <div className="chat">
227
+ <header className="chatbar">
228
+ {branding.logo ? <img className="logo" src={branding.logo} alt="" /> : null}
229
+ <h1>{title ?? branding.title}</h1>
230
+ <ThemeToggle />
231
+ </header>
232
+ {policyNote && (
233
+ <p className="policy-bar" role="note">
234
+ <span className="policy-dot" aria-hidden="true">i</span>
235
+ <span>{policyNote}</span>
236
+ </p>
237
+ )}
238
+ <ThreadPrimitive.Root className="thread">
239
+ <div className="thread-wrap">
240
+ <ThreadPrimitive.Viewport className="viewport">
241
+ <ThreadPrimitive.Empty>
242
+ <div className="welcome">
243
+ <p>{welcome ?? branding.welcome ?? "有什么可以帮你?"}</p>
244
+ {(suggestions ?? branding.suggestions ?? []).map((s) => (
245
+ <button key={s} className="chip" onClick={() => send(s)}>
246
+ {s}
247
+ </button>
248
+ ))}
249
+ </div>
250
+ </ThreadPrimitive.Empty>
251
+ {/* components is compared field-by-field (isComponentsSame), so this
252
+ literal is fine; UserEditComposer is required or Edit renders the
253
+ plain bubble with no input. */}
254
+ <ToolLabels.Provider value={toolLabels}>
255
+ <CardRenderer.Provider value={renderCard ?? (() => null)}>
256
+ <ThreadPrimitive.Messages components={{ UserMessage, UserEditComposer, AssistantMessage }} />
257
+ </CardRenderer.Provider>
258
+ </ToolLabels.Provider>
259
+ {/* Official gate (AuiIf; ThreadPrimitive.If is its deprecated alias).
260
+ The bouncing dots are host CSS keyframes — the library ships no
261
+ CSS and no animated loader primitive exists in 0.15.28. Seconds
262
+ are a local mount timer: the runtime timing hooks are not wired
263
+ in the published build (see handoff doc). */}
264
+ <AuiIf condition={(s) => s.thread.isRunning}>
265
+ <RunningIndicator />
266
+ </AuiIf>
267
+ </ThreadPrimitive.Viewport>
268
+ {/* ⑤ 官方原语:到底部时 disabled(见 createActionButton),CSS :disabled 隐藏。 */}
269
+ <ThreadPrimitive.ScrollToBottom className="scroll-bottom" title="滚动到最新">
270
+ ↓
271
+ </ThreadPrimitive.ScrollToBottom>
272
+ </div>
273
+
274
+ {confirms.length > 0 && (
275
+ <div className="confirms">
276
+ {confirms.map((c) => (
277
+ <ConfirmCard key={c.toolCallId} request={c} onAnswer={(allow) => answerConfirm(c, allow)} />
278
+ ))}
279
+ </div>
280
+ )}
281
+ {notices.length > 0 && (
282
+ <div className="notices">
283
+ {notices.map((n) => (
284
+ <div className={`notice ${n.level}`} key={n.key}>{n.message}</div>
285
+ ))}
286
+ </div>
287
+ )}
288
+ {uiPrompts.length > 0 && (
289
+ <div className="confirms">
290
+ {uiPrompts.map((p) => (
291
+ <UIPromptCard key={p.id} prompt={p} onAnswer={(a) => answerUI(p, a)} />
292
+ ))}
293
+ </div>
294
+ )}
295
+ {queue.length > 0 && <QueueBar queue={queue} onSteer={steer} onDrop={drop} />}
296
+ {usage && (
297
+ <div className="statusbar">
298
+ 本次用量 {usage.total} tokens(输入 {usage.input} / 输出 {usage.output})
299
+ </div>
300
+ )}
301
+ <Composer
302
+ running={running}
303
+ commands={commands}
304
+ tiers={branding.tiers}
305
+ tier={tier}
306
+ onTier={onTier}
307
+ onSend={send}
308
+ onStop={() => runtime.thread.cancelRun()}
309
+ />
310
+ <Lightbox />
311
+ </ThreadPrimitive.Root>
312
+ </div>
313
+ </AssistantRuntimeProvider>
314
+ );
315
+ }
316
+
317
+ /** Shown while a run is streaming: animated dots + seconds since this run's
318
+ * indicator mounted (unmount/remount per run resets the counter by design). */
319
+ function RunningIndicator() {
320
+ const [sec, setSec] = useState(0);
321
+ useEffect(() => {
322
+ const t = setInterval(() => setSec((s) => s + 1), 1000);
323
+ return () => clearInterval(t);
324
+ }, []);
325
+ return (
326
+ <div className="loading" role="status" aria-live="polite">
327
+ <span className="dots" aria-hidden="true">
328
+ <i />
329
+ <i />
330
+ <i />
331
+ </span>
332
+ 正在生成 {sec}s
333
+ </div>
334
+ );
335
+ }
336
+
337
+ /** Timestamp from the message state; the local runtime fills createdAt for
338
+ * live messages and restored history already carries it (fromThreadMessageLike:
339
+ * `createdAt ?? new Date()`). */
340
+ function MessageTime() {
341
+ const createdAt = useAuiState((s) => s.message.createdAt);
342
+ // E3: the adapter measured the wait for the first visible output; restored
343
+ // history and pre-stream errors carry no timing, so the label just stays away.
344
+ const firstTokenTime = useMessageTiming()?.firstTokenTime;
345
+ const d = new Date(createdAt);
346
+ return (
347
+ <div className="msg-time">
348
+ {`${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`}
349
+ {firstTokenTime !== undefined && <span className="msg-ttft">· 首字 {(firstTokenTime / 1000).toFixed(1)}s</span>}
350
+ </div>
351
+ );
352
+ }
353
+
354
+ function UserMessage() {
355
+ return (
356
+ <MessagePrimitive.Root className="msg user">
357
+ {/* File parts have no default renderer in the library (it renders null),
358
+ so converted documents must be mapped explicitly or they are invisible. */}
359
+ <MessagePrimitive.Parts components={{ File: DocChip }} />
360
+ <MessageTime />
361
+ <ActionBarPrimitive.Root hideWhenRunning autohide="not-last" className="actions">
362
+ <ActionBarPrimitive.Edit title="编辑这条消息(会丢弃它之后的回答并重新提问)">编辑</ActionBarPrimitive.Edit>
363
+ </ActionBarPrimitive.Root>
364
+ </MessagePrimitive.Root>
365
+ );
366
+ }
367
+
368
+ /**
369
+ * Shown in place of UserMessage while its Edit button is active.
370
+ *
371
+ * assistant-ui picks this by `s.message.composer.isEditing`, so it must be
372
+ * passed as `components.UserEditComposer` — without it the edit state renders
373
+ * the plain bubble and there is no way to type. The attachment strip is not
374
+ * decoration: the edit composer lifts a user message's images out of `content`
375
+ * into `attachments`, so without rendering them the user cannot see what the
376
+ * edit kept (it keeps them; adapter.ts reads both lists).
377
+ */
378
+ function UserEditComposer() {
379
+ const aui = useAui();
380
+ // ③ Same auto-grow as the main composer (CSS caps it at the token height).
381
+ const taRef = useRef<HTMLTextAreaElement>(null);
382
+ const text = useAuiState((s) => s.composer.text);
383
+ useEffect(() => {
384
+ const el = taRef.current;
385
+ if (!el) return;
386
+ el.style.height = "auto";
387
+ el.style.height = `${el.scrollHeight}px`;
388
+ }, [text]);
389
+ // Both submit paths (Enter submits the form; the Send button is a plain
390
+ // button calling send() from onClick) run before the official send, so the
391
+ // flag is set in time. The guard mirrors the library's composerSendDisabled:
392
+ // a submit it would refuse must not leave the flag behind, or the next
393
+ // ordinary message would truncate a turn nobody edited.
394
+ const mark = () => {
395
+ const thread = aui.thread.getState();
396
+ if (!thread.isDisabled && !thread.isRunning && aui.composer.getState().canSend) markEdit();
397
+ };
398
+ return (
399
+ <ComposerPrimitive.Root className="edit-composer" onSubmit={mark}>
400
+ <ComposerPrimitive.Attachments components={{ Image: EditThumb, File: EditFile }} />
401
+ <ComposerPrimitive.Input ref={taRef} className="edit-input" autoFocus submitMode="enter" aria-label="编辑消息" />
402
+ <div className="edit-actions">
403
+ <ComposerPrimitive.Cancel className="edit-btn">取消</ComposerPrimitive.Cancel>
404
+ <ComposerPrimitive.Send className="edit-btn primary" onClick={mark}>
405
+ 重新发送
406
+ </ComposerPrimitive.Send>
407
+ </div>
408
+ </ComposerPrimitive.Root>
409
+ );
410
+ }
411
+
412
+ /** An image kept by the edit composer, read from the attachment in scope. */
413
+ function EditThumb() {
414
+ const image = useAuiState((s) => {
415
+ const part = s.attachment.content?.find((p) => p.type === "image");
416
+ return part?.type === "image" ? part.image : undefined;
417
+ });
418
+ return image ? <img src={image} alt="附件" /> : null;
419
+ }
420
+
421
+ /** A converted document kept by the edit composer (B4-A). */
422
+ function EditFile() {
423
+ const doc = useAuiState((s) => {
424
+ const part = s.attachment.content?.find((p) => p.type === "file");
425
+ return part?.type === "file" ? { filename: part.filename, chars: part.data.length } : undefined;
426
+ });
427
+ return doc ? <span className="doc-chip">📄 {doc.filename ?? "文档"}({doc.chars} 字符)</span> : null;
428
+ }
429
+
430
+ /** The document attachment shown inside a sent user bubble. */
431
+ function DocChip({ filename, data }: FileMessagePartProps) {
432
+ return (
433
+ <details className="doc-chip" title="上传文件已由浏览器转换为文本随消息发送">
434
+ <summary>📄 {filename ?? "文档"}</summary>
435
+ <pre>{data}</pre>
436
+ </details>
437
+ );
438
+ }
439
+
440
+ function AssistantMessage() {
441
+ return (
442
+ <MessagePrimitive.Root className="msg assistant">
443
+ <MessagePrimitive.Parts
444
+ components={{ Text: MarkdownText, Reasoning: ReasoningBlock, tools: { Fallback: ToolCard } }}
445
+ />
446
+ <MessageTime />
447
+ <ActionBarPrimitive.Root hideWhenRunning autohide="not-last" className="actions">
448
+ <ActionBarPrimitive.Copy title="复制回答">复制</ActionBarPrimitive.Copy>
449
+ <ActionBarPrimitive.Reload title="重新生成(旧回答仍留在服务端上下文里)">重新生成</ActionBarPrimitive.Reload>
450
+ <ActionBarPrimitive.FeedbackPositive title="这条回答有用">👍</ActionBarPrimitive.FeedbackPositive>
451
+ <ActionBarPrimitive.FeedbackNegative title="这条回答有问题">👎</ActionBarPrimitive.FeedbackNegative>
452
+ </ActionBarPrimitive.Root>
453
+ </MessagePrimitive.Root>
454
+ );
455
+ }
456
+
457
+ /** Markdown rendering for answer text; reads its own text from the message part context. */
458
+ function MarkdownText() {
459
+ return <MarkdownTextPrimitive className="md" smooth components={{ CodeHeader: CodeCopyHeader }} />;
460
+ }
461
+
462
+ function ReasoningBlock({ text }: ReasoningMessagePartProps) {
463
+ return (
464
+ <details className="reasoning">
465
+ <summary>思考过程</summary>
466
+ <div className="reasoning-body">{text}</div>
467
+ </details>
468
+ );
469
+ }
470
+
471
+ /**
472
+ * 工具的用户可见中文名(SSE 首帧 tools_meta,manifest `agent.toolLabels`)。
473
+ * 用户视角零实现细节(README 边界):不显示 `mcp__<server>__<tool>` 声明名、
474
+ * 不显示参数/结果原始 JSON;受限原因(⛔)是人话,必须直出。
475
+ */
476
+ const ToolLabels = createContext<Record<string, string>>({});
477
+
478
+ /** 产物卡渲染器由产品 AppDef 注入:core 只透传 details,不认识任何业务字段。 */
479
+ const CardRenderer = createContext<(details: unknown) => ReactNode>(() => null);
480
+
481
+ /** 通用卡片槽:产品没注入 renderer 时什么也不画。 */
482
+ function CardSlot({ details }: { details?: unknown }) {
483
+ const render = useContext(CardRenderer);
484
+ return <>{render(details)}</>;
485
+ }
486
+
487
+ function ToolCard({ toolName, result, isError, status }: ToolCallMessagePartProps) {
488
+ const labels = useContext(ToolLabels);
489
+ const pending = status?.type === "running";
490
+ // adapter 把结果包成 {text, details}(details 走 protocol 现成通道)。
491
+ const view = (typeof result === "object" && result !== null ? result : { text: String(result ?? "") }) as {
492
+ text?: string;
493
+ /** 平台只认受限提示;其余字段原样交给产品 renderer。 */
494
+ details?: { blocked?: string; user_message?: string; [key: string]: unknown };
495
+ };
496
+ const blocked = !isError && Boolean(view.details?.blocked);
497
+ return (
498
+ <div className={`tool${isError ? " err" : blocked ? " blocked" : ""}`}>
499
+ <div className="tool-head">
500
+ <span className="tool-name">{labels[toolName] ?? "调用工具"}</span>
501
+ {pending && <span className="tool-run">执行中…</span>}
502
+ {!pending && isError && <span className="tool-run bad">✗ 失败</span>}
503
+ {!pending && blocked && <span className="tool-run warn">⛔ 受限</span>}
504
+ {!pending && !isError && !blocked && <span className="tool-run ok">✓ 完成</span>}
505
+ </div>
506
+ {/* 受限原因必须给用户看:这是「为什么拿不到」,不是实现细节。 */}
507
+ {blocked && view.details?.user_message && <p className="tool-blocked">{view.details.user_message}</p>}
508
+ {!pending && !isError && !blocked && <CardSlot details={view.details} />}
509
+ {isError && view.text && <pre className="tool-err-text">{view.text}</pre>}
510
+ </div>
511
+ );
512
+ }
513
+
514
+ function Composer({
515
+ running,
516
+ commands,
517
+ tiers,
518
+ tier,
519
+ onTier,
520
+ onSend,
521
+ onStop,
522
+ }: {
523
+ running: boolean;
524
+ commands: ChatCommand[];
525
+ tiers?: ModelTier[];
526
+ tier?: string;
527
+ onTier: (id: string) => void;
528
+ onSend: (t: string, images: ChatImage[], docs: DocEntry[]) => void;
529
+ onStop: () => void;
530
+ }) {
531
+ const [text, setText] = useState("");
532
+ const [images, setImages] = useState<{ url: string; image: ChatImage }[]>([]);
533
+ // B4-A: converted documents, held as finished text — the heavy parsing has
534
+ // already happened in the browser before anything lands here.
535
+ const [docs, setDocs] = useState<DocEntry[]>([]);
536
+ const [docBusy, setDocBusy] = useState<string | null>(null);
537
+ const [docError, setDocError] = useState<string | null>(null);
538
+ const fileRef = useRef<HTMLInputElement>(null);
539
+ // ③ Auto-grow: keep the textarea exactly as tall as its content, up to the
540
+ // CSS max-height (after which it scrolls internally).
541
+ const taRef = useRef<HTMLTextAreaElement>(null);
542
+ useEffect(() => {
543
+ const el = taRef.current;
544
+ if (!el) return;
545
+ el.style.height = "auto";
546
+ el.style.height = `${el.scrollHeight}px`;
547
+ }, [text]);
548
+
549
+ // "/" opens the picker: it is UI-only, the server expands the command before
550
+ // the model sees anything. Once a space is typed the command is settled.
551
+ const slash = /^\/([a-z0-9-]*)$/.exec(text)?.[1];
552
+ const matches = slash === undefined ? [] : commands.filter((c) => c.name.startsWith(slash));
553
+
554
+ const pickCommand = (name: string) => setText(`/${name} `);
555
+
556
+ const pick = async (fileList: FileList | null) => {
557
+ const pickedImages: { url: string; image: ChatImage }[] = [];
558
+ const newDocs: DocEntry[] = [];
559
+ const errors: string[] = [];
560
+ for (const file of Array.from(fileList ?? [])) {
561
+ if (docKind(file.name)) {
562
+ if (docs.length + newDocs.length >= MAX_DOCS) {
563
+ errors.push(`文档最多 ${MAX_DOCS} 个`);
564
+ continue;
565
+ }
566
+ setDocBusy(file.name);
567
+ setDocError(null);
568
+ try {
569
+ newDocs.push(await fileToDoc(file));
570
+ } catch (err) {
571
+ errors.push((err as Error).message);
572
+ } finally {
573
+ setDocBusy(null);
574
+ }
575
+ } else if (pickedImages.length < 4) {
576
+ const url = await new Promise<string>((resolve) => {
577
+ const r = new FileReader();
578
+ r.onload = () => resolve(String(r.result));
579
+ r.readAsDataURL(file);
580
+ });
581
+ const image = dataUrlToImage(url);
582
+ if (image) pickedImages.push({ url, image });
583
+ else errors.push(`暂不支持的文件:${file.name}`);
584
+ }
585
+ }
586
+ if (pickedImages.length > 0) setImages((prev) => [...prev, ...pickedImages].slice(0, 4));
587
+ if (newDocs.length > 0) setDocs((prev) => [...prev, ...newDocs].slice(0, MAX_DOCS));
588
+ setDocError(errors.length > 0 ? errors.join(";") : null);
589
+ };
590
+
591
+ const submit = () => {
592
+ const text2 = text.trim();
593
+ if (!text2 && images.length === 0 && docs.length === 0) return;
594
+ // Never send while a document is mid-parse: the chip is not in `docs` yet.
595
+ if (docBusy !== null) return;
596
+ // An unknown "/foo" is never sent: the server would 400 it, and the picker
597
+ // is the only way to name a command.
598
+ if (text2.startsWith("/") && !commands.some((c) => text2 === `/${c.name}` || text2.startsWith(`/${c.name} `))) return;
599
+ onSend(text2, images.map((i) => i.image), docs);
600
+ setText("");
601
+ // E2: the queue carries images too, so the composer always hands them off.
602
+ setImages([]);
603
+ setDocs([]);
604
+ setDocError(null);
605
+ };
606
+
607
+ return (
608
+ <div className="composer">
609
+ {matches.length > 0 && (
610
+ <div className="cmds" role="listbox" aria-label="指令">
611
+ {matches.map((c) => (
612
+ <button type="button" key={c.name} className="cmd" role="option" aria-selected={false} onClick={() => pickCommand(c.name)}>
613
+ <span className="cmd-name">/{c.name}</span>
614
+ <span className="cmd-desc">{c.description}</span>
615
+ </button>
616
+ ))}
617
+ </div>
618
+ )}
619
+ {images.length > 0 && (
620
+ <div className="attach">
621
+ {images.map((img, i) => (
622
+ <span className="attach-thumb" key={i}>
623
+ <img src={img.url} alt={`附件 ${i + 1}`} />
624
+ <button type="button" title="移除图片" onClick={() => setImages((p) => p.filter((_, j) => j !== i))}>
625
+ ×
626
+ </button>
627
+ </span>
628
+ ))}
629
+ </div>
630
+ )}
631
+ {(docs.length > 0 || docBusy !== null) && (
632
+ <div className="attach">
633
+ {docs.map((d, i) => (
634
+ <span className="doc-chip" key={i} title={`${d.text.length} 字符${d.truncated ? "(已截断)" : ""}`}>
635
+ 📄 {d.name}
636
+ <button type="button" title="移除文档" onClick={() => setDocs((p) => p.filter((_, j) => j !== i))}>
637
+ ×
638
+ </button>
639
+ </span>
640
+ ))}
641
+ {docBusy !== null && <span className="doc-chip pending">⏳ 正在解析 {docBusy}…</span>}
642
+ </div>
643
+ )}
644
+ {docError !== null && <div className="attach-err">{docError}</div>}
645
+ <textarea
646
+ ref={taRef}
647
+ rows={1}
648
+ value={text}
649
+ onChange={(e) => setText(e.target.value)}
650
+ onPaste={(e) => {
651
+ const files = Array.from(e.clipboardData.files);
652
+ if (files.length > 0) {
653
+ e.preventDefault();
654
+ void pick(e.clipboardData.files);
655
+ }
656
+ }}
657
+ onKeyDown={(e) => {
658
+ if (e.key === "Enter" && !e.shiftKey) {
659
+ e.preventDefault();
660
+ submit();
661
+ }
662
+ }}
663
+ placeholder={running ? "输入追加需求,将在当前回答后执行…" : "输入问题,Enter 发送(可粘贴或选择图片/文档)"}
664
+ />
665
+ <input
666
+ ref={fileRef}
667
+ type="file"
668
+ accept="image/png,image/jpeg,image/webp,image/gif,.md,.markdown,.txt,.log,.json,.yaml,.yml,.csv,.tsv,.pdf,.docx,.xlsx,.xlsm"
669
+ multiple
670
+ hidden
671
+ onChange={(e) => {
672
+ void pick(e.target.files);
673
+ e.target.value = "";
674
+ }}
675
+ />
676
+ <button type="button" className="attach-btn" title="添加图片或文档(各最多 4 个)" onClick={() => fileRef.current?.click()}>
677
+ 📎
678
+ </button>
679
+ {/* 档位下拉放在发送旁(DSH 选模型的位置);只出现 label/倍率,物理模型名不进浏览器 */}
680
+ {tiers && tiers.length > 0 && <TierPicker tiers={tiers} value={tier} onChange={onTier} />}
681
+ {running ? (
682
+ <button className="stop" onClick={onStop}>
683
+ 停止
684
+ </button>
685
+ ) : (
686
+ <button className="send" disabled={(!text.trim() && images.length === 0 && docs.length === 0) || docBusy !== null} onClick={submit}>
687
+ 发送
688
+ </button>
689
+ )}
690
+ </div>
691
+ );
692
+ }