@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,318 @@
1
+ import { jsxs as _jsxs, jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import { useCallback, useEffect, useState } from "react";
3
+ import { apiHeaders, auth } from "./auth.js";
4
+ import { fetchJson } from "./sse.js";
5
+ import { fmtTime } from "./ui/timefmt.js";
6
+ const UI_FIELDS = [
7
+ { key: "label", label: "入口名" },
8
+ { key: "icon", label: "图标" },
9
+ { key: "tag", label: "标签" },
10
+ { key: "hint", label: "悬停提示" },
11
+ // 欢迎语是整句(产品声明的那句长文案),单行 input 会像 的提示条一样被截断。
12
+ { key: "welcome", label: "空态标题", multiline: true },
13
+ // 提示条是整句话(几十个字),单行 input 会把它截成半句——截图里抓到过。
14
+ { key: "policyNote", label: "常驻提示条", multiline: true },
15
+ // 快捷问法是一组(表里叫 suggestions):一行一条,空行忽略。
16
+ { key: "suggestions", label: "快捷问法(一行一条)", multiline: true, list: true },
17
+ ];
18
+ const SOURCE_TEXT = { manifest: "manifest", file: "已改", draft: "草稿" };
19
+ const ACTION_TEXT = { save: "保存", reset: "恢复默认", rollback: "回滚" };
20
+ /** 键序无关的比较:否则「编辑后删掉一个字段」会被当成 dirty(保存按钮常亮)。 */
21
+ const canonUi = (ui) => JSON.stringify(Object.keys(ui).sort().map((k) => [k, ui[k]]));
22
+ const canonList = (list) => JSON.stringify([...list].sort());
23
+ async function send(path, method, body, version) {
24
+ const res = await fetch(path, {
25
+ method,
26
+ headers: {
27
+ ...(body === undefined ? {} : { "content-type": "application/json" }),
28
+ ...(version === undefined ? {} : { "if-match": String(version) }),
29
+ ...apiHeaders(auth.token),
30
+ },
31
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
32
+ });
33
+ const json = (await res.json().catch(() => null));
34
+ if (!res.ok)
35
+ throw new Error(json?.error?.message ?? `HTTP ${res.status}`);
36
+ return json;
37
+ }
38
+ export default function PersonasPage() {
39
+ const [list, setList] = useState(null);
40
+ const [sel, setSel] = useState(null);
41
+ const [detail, setDetail] = useState(null);
42
+ const [prompt, setPrompt] = useState("");
43
+ const [ui, setUi] = useState({});
44
+ const [disabled, setDisabled] = useState([]);
45
+ const [preview, setPreview] = useState(null);
46
+ const [versions, setVersions] = useState([]);
47
+ const [versionView, setVersionView] = useState(null);
48
+ const [trialMsg, setTrialMsg] = useState("你好,用一句话说明你是谁、能做什么。");
49
+ const [trial, setTrial] = useState(null);
50
+ const [trialErr, setTrialErr] = useState(null);
51
+ const [busy, setBusy] = useState(null);
52
+ const [err, setErr] = useState(null);
53
+ const [note, setNote] = useState(null);
54
+ const [confirmReset, setConfirmReset] = useState(false);
55
+ const loadList = useCallback(async () => {
56
+ try {
57
+ const data = await fetchJson("/api/admin/personas", auth.token);
58
+ setList(data);
59
+ setErr(null);
60
+ setSel((cur) => cur ?? data.personas[0]?.id ?? null);
61
+ }
62
+ catch (e) {
63
+ setErr(`读取失败:${e.message}`);
64
+ }
65
+ }, []);
66
+ const loadVersions = useCallback(async (id) => {
67
+ try {
68
+ const data = await fetchJson(`/api/admin/personas/${encodeURIComponent(id)}/versions`, auth.token);
69
+ setVersions(data.versions);
70
+ }
71
+ catch {
72
+ // 版本历史是辅助信息:读不到不该让整页不可用。
73
+ setVersions([]);
74
+ }
75
+ }, []);
76
+ useEffect(() => {
77
+ void loadList();
78
+ }, [loadList]);
79
+ useEffect(() => {
80
+ if (!sel)
81
+ return;
82
+ let alive = true;
83
+ setDetail(null);
84
+ setPreview(null);
85
+ setVersionView(null);
86
+ setTrial(null);
87
+ setTrialErr(null);
88
+ setConfirmReset(false);
89
+ void loadVersions(sel);
90
+ fetchJson(`/api/admin/personas/${encodeURIComponent(sel)}`, auth.token)
91
+ .then((d) => {
92
+ if (!alive)
93
+ return;
94
+ setDetail(d);
95
+ setPrompt(d.effective.prompt);
96
+ setUi((d.effective.ui ?? {}));
97
+ setDisabled(d.effective.disabledTools);
98
+ })
99
+ .catch((e) => alive && setErr(`读取 ${sel} 失败:${e.message}`));
100
+ return () => {
101
+ alive = false;
102
+ };
103
+ }, [sel, loadVersions]);
104
+ const dirty = detail !== null &&
105
+ (prompt !== detail.effective.prompt ||
106
+ canonList(disabled) !== canonList(detail.effective.disabledTools) ||
107
+ canonUi(ui) !== canonUi((detail.effective.ui ?? {})));
108
+ /**
109
+ * 只把**真的改过**的 ui 字段落成覆盖:否则 manifest 的文案会被整块复制进配置,
110
+ * 以后 manifest 改了、覆盖还压着旧文案(设计稿 的漂移问题)。
111
+ * 起点是**原始覆盖**(`overrideUi`),不是编辑器里的合并值——编辑框显示的是
112
+ * 「出厂值 + 覆盖」,直接整块保存会把出厂值也写进去。
113
+ */
114
+ const uiPatch = () => {
115
+ const patch = { ...(detail?.overrideUi ?? {}) };
116
+ const eff = (detail?.effective.ui ?? {});
117
+ for (const f of UI_FIELDS) {
118
+ const now = ui[f.key];
119
+ // 没动过这个字段 ⇒ 保留原有覆盖(有就留,没有就没有)
120
+ if (JSON.stringify(now ?? null) === JSON.stringify(eff[f.key] ?? null))
121
+ continue;
122
+ const empty = now === undefined || now === "" || (Array.isArray(now) && now.length === 0);
123
+ // 清空 = 删掉覆盖,回落到出厂值(PUT 的整块替换语义正好配合)
124
+ if (empty)
125
+ delete patch[f.key];
126
+ else
127
+ patch[f.key] = now;
128
+ }
129
+ return patch;
130
+ };
131
+ const allow = detail?.manifest.allowTools ?? null;
132
+ const candidates = allow ?? [];
133
+ const requiredMissing = (detail?.manifest.requiredSections ?? []).filter((section) => !prompt.split("\n").some((line) => line.trimStart().startsWith(section)));
134
+ const doSave = async () => {
135
+ if (!detail)
136
+ return;
137
+ setBusy("save");
138
+ setErr(null);
139
+ setNote(null);
140
+ try {
141
+ const body = { prompt };
142
+ // 空补丁不发:等于"这次只改了 prompt",ui 覆盖保持原样(或继续没有)。
143
+ const uiNext = uiPatch();
144
+ if (Object.keys(uiNext).length > 0)
145
+ body.ui = uiNext;
146
+ if (disabled.length > 0)
147
+ body.disabledTools = disabled;
148
+ await send(`/api/admin/personas/${encodeURIComponent(detail.id)}`, "PUT", body, detail.version);
149
+ setNote("已保存。新会话生效;正在进行的会话不变。");
150
+ await loadList();
151
+ setSel(detail.id);
152
+ const fresh = await fetchJson(`/api/admin/personas/${encodeURIComponent(detail.id)}`, auth.token);
153
+ setDetail(fresh);
154
+ setPrompt(fresh.effective.prompt);
155
+ setUi((fresh.effective.ui ?? {}));
156
+ setDisabled(fresh.effective.disabledTools);
157
+ setPreview(null);
158
+ await loadVersions(detail.id);
159
+ }
160
+ catch (e) {
161
+ setErr(`保存失败:${e.message}`);
162
+ }
163
+ finally {
164
+ setBusy(null);
165
+ }
166
+ };
167
+ const doReset = async () => {
168
+ if (!detail)
169
+ return;
170
+ if (!confirmReset) {
171
+ setConfirmReset(true);
172
+ setTimeout(() => setConfirmReset(false), 4000);
173
+ return;
174
+ }
175
+ setBusy("reset");
176
+ setErr(null);
177
+ try {
178
+ await send(`/api/admin/personas/${encodeURIComponent(detail.id)}`, "DELETE", undefined, detail.version);
179
+ setNote("已恢复为 manifest 默认。");
180
+ setConfirmReset(false);
181
+ await loadList();
182
+ setSel(detail.id);
183
+ const fresh = await fetchJson(`/api/admin/personas/${encodeURIComponent(detail.id)}`, auth.token);
184
+ setDetail(fresh);
185
+ setPrompt(fresh.effective.prompt);
186
+ setUi((fresh.effective.ui ?? {}));
187
+ setDisabled(fresh.effective.disabledTools);
188
+ setPreview(null);
189
+ await loadVersions(detail.id);
190
+ }
191
+ catch (e) {
192
+ setErr(`恢复失败:${e.message}`);
193
+ }
194
+ finally {
195
+ setBusy(null);
196
+ }
197
+ };
198
+ const doPreview = async () => {
199
+ if (!detail)
200
+ return;
201
+ setBusy("preview");
202
+ setErr(null);
203
+ try {
204
+ const data = (await send(`/api/admin/personas/${encodeURIComponent(detail.id)}/preview`, "POST", {
205
+ prompt,
206
+ disabledTools: disabled,
207
+ }));
208
+ setPreview(data);
209
+ }
210
+ catch (e) {
211
+ setErr(`预览失败:${e.message}`);
212
+ }
213
+ finally {
214
+ setBusy(null);
215
+ }
216
+ };
217
+ /** 看某一版当时存了什么(只读,不动编辑器)。 */
218
+ const doViewVersion = async (version) => {
219
+ if (!detail)
220
+ return;
221
+ setBusy("version");
222
+ setErr(null);
223
+ try {
224
+ const data = await fetchJson(`/api/admin/personas/${encodeURIComponent(detail.id)}/versions/${version}`, auth.token);
225
+ setVersionView(data);
226
+ }
227
+ catch (e) {
228
+ setErr(`读取 v${version} 失败:${e.message}`);
229
+ }
230
+ finally {
231
+ setBusy(null);
232
+ }
233
+ };
234
+ /** 回滚 = 用旧快照写一个新版本;历史本身一条不删。 */
235
+ const doRollback = async (version) => {
236
+ if (!detail)
237
+ return;
238
+ setBusy("rollback");
239
+ setErr(null);
240
+ setNote(null);
241
+ try {
242
+ await send(`/api/admin/personas/${encodeURIComponent(detail.id)}/rollback`, "POST", { version }, detail.version);
243
+ const fresh = await fetchJson(`/api/admin/personas/${encodeURIComponent(detail.id)}`, auth.token);
244
+ setNote(`已回滚到 v${version}(记为新版本)。新会话生效;历史版本都还在。`);
245
+ setDetail(fresh);
246
+ setPrompt(fresh.effective.prompt);
247
+ setUi((fresh.effective.ui ?? {}));
248
+ setDisabled(fresh.effective.disabledTools);
249
+ setPreview(null);
250
+ setVersionView(null);
251
+ await loadList();
252
+ await loadVersions(detail.id);
253
+ }
254
+ catch (e) {
255
+ setErr(`回滚失败:${e.message}`);
256
+ }
257
+ finally {
258
+ setBusy(null);
259
+ }
260
+ };
261
+ /** 试跑:把编辑器里的**草稿**原样发给服务端跑一次;不保存、不写历史。 */
262
+ const doTrial = async () => {
263
+ if (!detail || trialMsg.trim() === "")
264
+ return;
265
+ setBusy("trial");
266
+ setTrialErr(null);
267
+ setTrial(null);
268
+ try {
269
+ const data = (await send(`/api/admin/personas/${encodeURIComponent(detail.id)}/trial`, "POST", {
270
+ message: trialMsg,
271
+ prompt,
272
+ disabledTools: disabled,
273
+ }));
274
+ setTrial(data);
275
+ }
276
+ catch (e) {
277
+ setTrialErr(`试跑失败:${e.message}`);
278
+ }
279
+ finally {
280
+ setBusy(null);
281
+ }
282
+ };
283
+ if (err && !list)
284
+ return _jsxs("p", { className: "ps-note", children: ["\u65E0\u6CD5\u8BFB\u53D6\u4EBA\u683C\u914D\u7F6E\uFF1A", err] });
285
+ if (!list)
286
+ return _jsx("p", { className: "ps-note", children: "\u6B63\u5728\u8BFB\u53D6\u4EBA\u683C\u914D\u7F6E\u2026" });
287
+ return (_jsxs("div", { className: "ps", children: [_jsxs("header", { className: "ps-head", children: [_jsxs("div", { children: [_jsx("h2", { className: "ps-title", children: "\u4EBA\u683C" }), _jsxs("p", { className: "ps-note", children: ["\u6765\u6E90\uFF1A", _jsx("b", { children: SOURCE_TEXT[list.source] ?? list.source }), " \u00B7 \u7248\u672C ", list.version, " \u00B7", " ", _jsx("code", { className: "ps-code", title: list.file, children: list.file.split(/[\\/]/).pop() })] }), _jsxs("p", { className: "ps-note", children: ["\u4FDD\u5B58\u540E", _jsx("b", { children: "\u5BF9\u65B0\u4F1A\u8BDD\u751F\u6548" }), "\uFF1B\u5DF2\u5728\u8FDB\u884C\u4E2D\u7684\u4F1A\u8BDD\u4E0D\u53D8\uFF08\u4EBA\u683C\u4E0E prompt \u5728\u5EFA\u4F1A\u8BDD\u65F6\u5B9A\u6B7B\uFF09\u3002"] })] }), _jsxs("div", { className: "ps-actions", children: [_jsx("button", { className: "ps-btn", onClick: doPreview, disabled: busy !== null || !detail, children: busy === "preview" ? "编译中…" : "编译预览" }), _jsx("button", { className: "ps-btn primary", onClick: doSave, disabled: busy !== null || !detail || !dirty, children: busy === "save" ? "保存中…" : dirty ? "保存" : "已保存" }), _jsx("button", { className: "ps-btn", onClick: doReset, disabled: busy !== null || !detail || detail.source === "manifest", children: confirmReset ? "确认恢复?" : "恢复默认" })] })] }), list.problems.length > 0 && _jsxs("p", { className: "ps-warn", children: ["\u914D\u7F6E\u6587\u4EF6\u6709\u95EE\u9898\uFF1A", list.problems.join(";")] }), note && _jsx("p", { className: "ps-ok", children: note }), err && _jsx("p", { className: "ps-err", children: err }), _jsxs("div", { className: "ps-body", children: [_jsx("aside", { className: "ps-list", children: list.personas.map((p) => (_jsxs("button", { className: `ps-item${p.id === sel ? " on" : ""}`, onClick: () => setSel(p.id), children: [_jsx("span", { className: "ps-item-icon", children: p.icon ?? "·" }), _jsx("span", { className: "ps-item-name", children: p.label ?? p.id }), _jsx("span", { className: `ps-badge ${p.source}`, children: SOURCE_TEXT[p.source] })] }, p.id))) }), _jsx("main", { className: "ps-editor", children: !detail ? (_jsx("p", { className: "ps-note", children: "\u8BFB\u53D6\u4E2D\u2026" })) : (_jsxs(_Fragment, { children: [_jsxs("section", { className: "ps-sec", children: [_jsxs("div", { className: "ps-sec-head", children: [_jsx("h3", { children: "\u4EBA\u683C\u6B63\u6587" }), _jsxs("span", { className: "ps-note", children: [prompt.length, " \u5B57", requiredMissing.length > 0 && _jsxs("span", { className: "ps-err", children: [" \u00B7 \u7F3A\u5FC5\u5907\u6BB5\u843D\uFF1A", requiredMissing.join("、")] })] })] }), _jsx("textarea", { className: "ps-prompt", value: prompt, onChange: (e) => setPrompt(e.target.value), spellCheck: false }), detail.manifest.requiredSections.length > 0 && (_jsxs("p", { className: "ps-note", children: ["\u5FC5\u5907\u6BB5\u843D\uFF08\u4EA7\u54C1\u58F0\u660E\uFF0C\u7F3A\u4E86\u5B58\u4E0D\u8FDB\u53BB\uFF09\uFF1A", detail.manifest.requiredSections.map((s) => _jsx("code", { className: "ps-code", children: s }, s))] }))] }), _jsxs("section", { className: "ps-sec", children: [_jsxs("div", { className: "ps-sec-head", children: [_jsx("h3", { children: "\u7528\u6237\u770B\u5230\u7684" }), _jsx("span", { className: "ps-note", children: "\u53EA\u5F71\u54CD\u754C\u9762\uFF0C\u4E0D\u8FDB\u6A21\u578B" })] }), _jsx("div", { className: "ps-ui-grid", children: UI_FIELDS.map((f) => (_jsxs("label", { className: `ps-field${f.multiline ? " wide" : ""}`, children: [_jsx("span", { children: f.label }), (() => {
288
+ // 列表字段(suggestions)在界面里是"一行一条",存盘是 string[]。
289
+ const rawNow = ui[f.key];
290
+ const rawDefault = detail.manifest.ui?.[f.key];
291
+ const value = f.list
292
+ ? Array.isArray(rawNow) ? rawNow.join("\n") : ""
293
+ : typeof rawNow === "string" ? rawNow : "";
294
+ const placeholder = f.list
295
+ ? Array.isArray(rawDefault) ? rawDefault.join("\n") : ""
296
+ : typeof rawDefault === "string" ? rawDefault : "";
297
+ const onChange = (v) => {
298
+ const next = { ...ui };
299
+ if (f.list) {
300
+ const list = v.split("\n").map((x) => x.trim()).filter(Boolean);
301
+ if (list.length === 0)
302
+ delete next[f.key];
303
+ else
304
+ next[f.key] = list;
305
+ }
306
+ else if (v === "") {
307
+ delete next[f.key];
308
+ }
309
+ else {
310
+ next[f.key] = v;
311
+ }
312
+ setUi(next);
313
+ };
314
+ return f.multiline ? (_jsx("textarea", { "data-field": f.key, rows: f.list ? 3 : 2, value: value, placeholder: placeholder, onChange: (e) => onChange(e.target.value) })) : (_jsx("input", { "data-field": f.key, value: value, placeholder: placeholder, onChange: (e) => onChange(e.target.value) }));
315
+ })()] }, f.key))) }), detail.id === list.defaultPersona && (_jsxs("p", { className: "ps-note", children: ["\u9ED8\u8BA4\u52A9\u624B\u6CA1\u6709\u4FA7\u680F\u5165\u53E3\uFF1A", _jsx("b", { children: "\u56FE\u6807 / \u6807\u7B7E / \u60AC\u505C\u63D0\u793A" }), "\u76EE\u524D\u6CA1\u6709\u5C55\u793A\u4F4D\u7F6E\uFF1B", _jsx("b", { children: "\u5165\u53E3\u540D" }), "\u7528\u5728\u804A\u5929\u7A97\u6807\u9898\uFF0C", _jsx("b", { children: "\u7A7A\u6001\u6807\u9898 / \u63D0\u793A\u6761 / \u5FEB\u6377\u95EE\u6CD5" }), "\u7528\u5728\u5BF9\u8BDD\u7A7A\u6001\u3002"] }))] }), _jsxs("section", { className: "ps-sec", children: [_jsxs("div", { className: "ps-sec-head", children: [_jsx("h3", { children: "\u80FD\u529B\u9762\uFF08\u53EA\u8BFB\uFF09" }), _jsx("span", { className: "ps-note", children: "\u6765\u81EA manifest\uFF0C\u6539\u5B83\u8981\u6539\u4EE3\u7801 + review\uFF1B\u8FD9\u91CC\u53EA\u80FD\u4E34\u65F6\u505C\u7528" })] }), allow === null ? (_jsx("p", { className: "ps-note", children: "\u8BE5\u4EBA\u683C\u6CA1\u6709\u5DE5\u5177\u767D\u540D\u5355\uFF08= \u4E0D\u9650\uFF09\u3002\u505C\u7528\u4ECD\u7136\u751F\u6548\uFF0C\u4F46\u767D\u540D\u5355\u672C\u8EAB\u4E0D\u5728\u8FD9\u91CC\u6539\u3002" })) : allow.length === 0 ? (_jsx("p", { className: "ps-note", children: "\u767D\u540D\u5355\u662F\u7A7A\u6570\u7EC4\uFF1A\u4E00\u4E2A\u5DE5\u5177\u90FD\u4E0D\u7ED9\uFF08\u4E0D\u662F\u300C\u5168\u7ED9\u300D\uFF09\u3002" })) : (_jsx("ul", { className: "ps-tools", children: candidates.map((name) => (_jsx("li", { children: _jsxs("label", { children: [_jsx("input", { type: "checkbox", checked: disabled.includes(name), onChange: (e) => {
316
+ setDisabled((cur) => (e.target.checked ? [...cur, name] : cur.filter((n) => n !== name)));
317
+ } }), _jsx("code", { className: "ps-code", children: name }), _jsxs("span", { className: "ps-note", children: [" ", disabled.includes(name) ? "已停用" : "生效中"] })] }) }, name))) })), _jsx("p", { className: "ps-note", children: "\u6280\u80FD\u76EE\u5F55\u540C\u6837\u53EA\u8BFB\uFF08\u6765\u81EA manifest \u7684 `skills`\uFF09\u3002" })] }), _jsxs("section", { className: "ps-sec ps-versions", children: [_jsxs("div", { className: "ps-sec-head", children: [_jsx("h3", { children: "\u7248\u672C\u5386\u53F2" }), _jsx("span", { className: "ps-note", children: "\u6BCF\u6B21\u5199\u5165\u7559\u4E00\u7248\uFF08\u6BCF\u4EBA\u683C\u6700\u8FD1 20 \u7248\uFF09\uFF1B\u56DE\u6EDA=\u5199\u65B0\u7248\u672C\uFF0C\u5386\u53F2\u4E0D\u5220" })] }), versions.length === 0 ? (_jsx("p", { className: "ps-note", children: "\u8FD8\u6CA1\u6709\u7248\u672C\u8BB0\u5F55\uFF08\u5F53\u524D\u5C31\u662F manifest \u539F\u6837\uFF09\u3002" })) : (_jsx("ul", { className: "ps-version-list", children: versions.map((v) => (_jsxs("li", { className: "ps-version", children: [_jsxs("span", { className: "ps-vnum", children: ["v", v.version] }), _jsx("span", { className: "ps-vact", children: ACTION_TEXT[v.action] ?? v.action }), _jsxs("span", { className: "ps-note ps-vmeta", children: [v.by, " \u00B7 ", fmtTime(v.at), v.promptLen !== null ? ` · ${v.promptLen} 字` : "", v.restoredFrom !== null ? ` · 来自 v${v.restoredFrom}` : ""] }), _jsxs("span", { className: "ps-vbtns", children: [_jsxs("button", { className: "ps-btn mini", onClick: () => void doViewVersion(v.version), disabled: busy !== null, children: ["\u67E5\u770B v", v.version] }), _jsxs("button", { className: "ps-btn mini", onClick: () => void doRollback(v.version), disabled: busy !== null || v.version === versions[0]?.version, children: ["\u56DE\u6EDA\u5230 v", v.version] })] })] }, v.version))) })), versionView && (_jsxs("div", { className: "ps-vbody-wrap", children: [_jsxs("p", { className: "ps-note", children: ["v", versionView.version, " \u7684\u5FEB\u7167\uFF08", ACTION_TEXT[versionView.action] ?? versionView.action, " \u00B7 ", versionView.by, " \u00B7", " ", fmtTime(versionView.at), "\uFF09\uFF0C\u53EA\u8BFB\uFF1A"] }), _jsx("pre", { className: "ps-vbody", children: versionView.override?.prompt ?? "(这一版没有覆盖正文 = 用 manifest 原样)" })] }))] }), detail.updatedBy && (_jsxs("p", { className: "ps-note", children: ["\u6700\u540E\u4FEE\u6539\uFF1A", detail.updatedBy, " \u00B7 ", fmtTime(detail.updatedAt)] }))] })) })] }), _jsxs("section", { className: "ps-trial", children: [_jsxs("div", { className: "ps-sec-head", children: [_jsx("h3", { children: "\u8BD5\u8DD1" }), _jsxs("span", { className: "ps-note", children: ["\u7528\u7F16\u8F91\u5668\u91CC\u7684", _jsx("b", { children: "\u8349\u7A3F" }), "\u771F\u8C03\u4E00\u6B21\u6A21\u578B\uFF08\u82B1 token\uFF1B\u4E0D\u5199\u5386\u53F2\u3001\u4E0D\u8BA1\u8D39\u3001\u4E0D\u6263\u6B21\u6570\uFF0C\u53EA\u7559\u4E00\u6761\u5BA1\u8BA1\uFF09"] })] }), _jsxs("div", { className: "ps-trial-row", children: [_jsx("textarea", { className: "ps-trial-input", rows: 2, placeholder: "\u8F93\u5165\u4E00\u53E5\u8BDD\uFF0C\u770B\u770B\u8FD9\u4E2A\u4EBA\u683C\u4F1A\u600E\u4E48\u7B54", value: trialMsg, onChange: (e) => setTrialMsg(e.target.value) }), _jsx("button", { className: "ps-btn primary", onClick: () => void doTrial(), disabled: busy !== null || !detail || trialMsg.trim() === "", children: busy === "trial" ? "试跑中…" : "试跑" })] }), trialErr && _jsx("p", { className: "ps-err ps-trial-err", children: trialErr }), trial && (_jsxs("div", { className: "ps-trial-out", children: [_jsxs("div", { className: "ps-trial-meta", children: [_jsx("span", { className: `ps-badge ${trial.draft ? "draft" : "file"}`, children: trial.draft ? "草稿" : "已保存" }), _jsxs("span", { className: "ps-note", children: [trial.tokens, " tokens \u00B7 ", trial.ms, " ms \u00B7 \u5DE5\u5177\uFF1A", trial.tools.join("、") || "无", " \u00B7 \u672A\u5199\u5386\u53F2\u3001\u672A\u8BA1\u8D39"] })] }), _jsx("pre", { className: "ps-trial-reply", children: trial.reply })] }))] }), preview && (_jsxs("section", { className: "ps-preview", children: [_jsxs("div", { className: "ps-sec-head", children: [_jsx("h3", { children: "\u7F16\u8BD1\u9884\u89C8" }), _jsx("span", { className: `ps-badge ${preview.source}`, children: SOURCE_TEXT[preview.source] ?? preview.source })] }), preview.requiredSections.missing.length > 0 && (_jsxs("p", { className: "ps-err", children: ["\u7F3A\u5FC5\u5907\u6BB5\u843D\uFF1A", preview.requiredSections.missing.join("、")] })), _jsxs("div", { className: "ps-prev-grid", children: [_jsxs("div", { children: [_jsx("h4", { children: "\u6700\u7EC8 system prompt" }), _jsx("pre", { className: "ps-pre", children: preview.systemPrompt })] }), _jsxs("div", { children: [_jsx("h4", { children: "\u5DE5\u5177\uFF08\u5185\u8054\uFF09" }), preview.tools.length === 0 ? (_jsx("p", { className: "ps-note", children: "\u8BE5\u4EBA\u683C\u6CA1\u6709\u5185\u8054\u5DE5\u5177\u3002" })) : (_jsx("ul", { className: "ps-tools", children: preview.tools.map((t) => (_jsxs("li", { children: [_jsx("code", { className: "ps-code", children: t.name }), _jsxs("span", { className: "ps-note", children: [" ", t.label ? `「${t.label}」` : "", " ", t.active ? "生效" : t.disabled ? "已停用" : "不在白名单"] })] }, t.name))) })), _jsx("h4", { children: "\u6280\u80FD" }), preview.skills.length === 0 ? (_jsx("p", { className: "ps-note", children: "\u4E0D\u7EE7\u627F\u4EFB\u4F55\u6280\u80FD\u3002" })) : (_jsx("ul", { className: "ps-tools", children: preview.skills.map((s) => (_jsxs("li", { children: [_jsx("code", { className: "ps-code", children: s.name }), " ", _jsx("span", { className: "ps-note", children: s.description })] }, s.name))) })), _jsx("h4", { children: "MCP" }), preview.mcp.length === 0 ? (_jsx("p", { className: "ps-note", children: "\u6CA1\u6709\u63A5\u5165\u3002" })) : (_jsx("ul", { className: "ps-tools", children: preview.mcp.map((m) => (_jsxs("li", { children: [_jsx("code", { className: "ps-code", children: m.server }), " ", _jsx("span", { className: "ps-note", children: m.mode === "all" ? "全部可见" : m.mode === "whitelist" ? `白名单:${m.visible.join("、") || "(空)"}` : "全部可见,逐个停用" })] }, m.server))) }))] })] })] }))] }));
318
+ }
@@ -0,0 +1,52 @@
1
+ import type { ChatEvent, ChatImage, TokenUsage } from "@njuptlzf/agent-chat-protocol";
2
+ import type { ChatModelAdapter } from "@assistant-ui/react";
3
+ /** A composer attachment data URL in the wire shape, or undefined if it is not an inline image. */
4
+ export declare function dataUrlToImage(url: string): ChatImage | undefined;
5
+ export interface ChatBridge {
6
+ getSessionId(): string | undefined;
7
+ setSessionId(sessionId: string): void;
8
+ getContext(): Record<string, unknown> | undefined;
9
+ getAuthToken(): string | undefined;
10
+ /** The chosen quality tier id, or undefined to run the manifest default. */
11
+ getTier(): string | undefined;
12
+ /** The scope this conversation belongs to, or undefined to run the product default. */
13
+ getScope(): string | undefined;
14
+ /** 人格:undefined = 产品默认(默认助手)。会话一旦建立就绑死,换人格会 400。 */
15
+ getPersona?(): string | undefined;
16
+ onRunEnd(info: {
17
+ usage: TokenUsage | null;
18
+ aborted: boolean;
19
+ }): void;
20
+ /** The server paused a gated tool and waits for POST /api/decision. */
21
+ onToolConfirm(info: {
22
+ sessionId: string;
23
+ toolCallId: string;
24
+ name: string;
25
+ args: Record<string, unknown>;
26
+ }): void;
27
+ /** A confirmed tool call finished (approved or denied); dismiss its card. */
28
+ onToolSettled(toolCallId: string): void;
29
+ /** 工具中文名:服务端首帧下发一次,UI 只显示这句,不显示 mcp__ 声明名。 */
30
+ onToolsMeta?(labels: Record<string, string>): void;
31
+ /** An extension is waiting for an answer (select/confirm/input); POST /api/ui-response when decided. */
32
+ onUiPrompt(prompt: UiPromptEvent): void;
33
+ /** An extension sent a notification; show it, no answer expected. */
34
+ onUiNotify(note: UiNotifyEvent): void;
35
+ }
36
+ /** Mark the next run as an edit. Call it before the composer sends. */
37
+ export declare function markEdit(): void;
38
+ /** An extension dialog forwarded by the server (event and POST /api/ui-response payload share this shape). */
39
+ export type UiPromptEvent = Extract<ChatEvent, {
40
+ type: "ui_prompt";
41
+ }>;
42
+ /** A fire-and-forget `ctx.ui.notify` from an extension. */
43
+ export type UiNotifyEvent = Extract<ChatEvent, {
44
+ type: "ui_notify";
45
+ }>;
46
+ /**
47
+ * Bridges our SSE wire protocol to assistant-ui's ChatModelAdapter.
48
+ *
49
+ * The server owns the conversation history (resume by sessionId), so a run
50
+ * sends only the newest user message — never the whole transcript.
51
+ */
52
+ export declare function createChatAdapter(bridge: ChatBridge): ChatModelAdapter;
@@ -0,0 +1,242 @@
1
+ import { postJson, streamChat } from "./sse.js";
2
+ /** `data:image/png;base64,AAAA` -> the bare base64 the wire wants. */
3
+ const DATA_URL = /^data:([^;,]+);base64,(.+)$/;
4
+ /** A composer attachment data URL in the wire shape, or undefined if it is not an inline image. */
5
+ export function dataUrlToImage(url) {
6
+ const m = DATA_URL.exec(url);
7
+ return m ? { mimeType: m[1], data: m[2] } : undefined;
8
+ }
9
+ function imageParts(last) {
10
+ if (last?.role !== "user")
11
+ return [];
12
+ const out = [];
13
+ const push = (part) => {
14
+ if (part.type !== "image")
15
+ return;
16
+ const url = part.image;
17
+ const img = typeof url === "string" ? dataUrlToImage(url) : undefined;
18
+ if (img)
19
+ out.push(img);
20
+ };
21
+ for (const part of last.content)
22
+ push(part);
23
+ // The edit composer lifts a user message's non-text parts out of `content`
24
+ // into `attachments`, so an edited image would otherwise be dropped on re-send.
25
+ for (const att of last.attachments ?? [])
26
+ for (const part of att.content ?? [])
27
+ push(part);
28
+ return out;
29
+ }
30
+ /**
31
+ * The converted-document parts docs.ts puts on a user message (type "file",
32
+ * mimeType "text/markdown", data = the Markdown itself). Same both-places scan
33
+ * as imageParts: the edit composer lifts non-text parts into `attachments`.
34
+ */
35
+ function docParts(last) {
36
+ if (last?.role !== "user")
37
+ return [];
38
+ const out = [];
39
+ const push = (part) => {
40
+ if (part.type !== "file")
41
+ return;
42
+ const p = part;
43
+ if (p.mimeType !== "text/markdown" || typeof p.data !== "string" || p.data.trim() === "")
44
+ return;
45
+ out.push({ name: p.filename ?? "附件", text: p.data });
46
+ };
47
+ for (const part of last.content)
48
+ push(part);
49
+ for (const att of last.attachments ?? [])
50
+ for (const part of att.content ?? [])
51
+ push(part);
52
+ return out;
53
+ }
54
+ /**
55
+ * Set when an edit composer submits, consumed by the next run.
56
+ *
57
+ * The server keeps the transcript, so an edited message must drop the
58
+ * superseded turn before the new one is sent. The run is the only place that
59
+ * both knows the session id and can await the cleanup, and assistant-ui gives
60
+ * the adapter no "this is an edit" flag (`sourceId` is dropped before
61
+ * ChatModelRunOptions). Module-level state is fine here: one chat runtime per
62
+ * page, and the flag is only ever set synchronously on the send path.
63
+ */
64
+ let editPending = false;
65
+ /** Mark the next run as an edit. Call it before the composer sends. */
66
+ export function markEdit() {
67
+ editPending = true;
68
+ }
69
+ /**
70
+ * Bridges our SSE wire protocol to assistant-ui's ChatModelAdapter.
71
+ *
72
+ * The server owns the conversation history (resume by sessionId), so a run
73
+ * sends only the newest user message — never the whole transcript.
74
+ */
75
+ export function createChatAdapter(bridge) {
76
+ return {
77
+ async *run({ messages, abortSignal }) {
78
+ const last = messages.at(-1);
79
+ const userText = last?.role === "user"
80
+ ? last.content.filter((p) => p.type === "text").map((p) => p.text).join("")
81
+ : "";
82
+ const req = { message: userText };
83
+ const sid = bridge.getSessionId();
84
+ if (sid)
85
+ req.sessionId = sid;
86
+ const ctx = bridge.getContext();
87
+ if (ctx)
88
+ req.context = ctx;
89
+ const tier = bridge.getTier();
90
+ if (tier)
91
+ req.tier = tier;
92
+ const scope = bridge.getScope();
93
+ if (scope)
94
+ req.scope = scope;
95
+ const persona = bridge.getPersona?.();
96
+ if (persona)
97
+ req.persona = persona;
98
+ const images = imageParts(last);
99
+ if (images.length > 0)
100
+ req.images = images;
101
+ const docs = docParts(last);
102
+ if (docs.length > 0)
103
+ req.attachments = docs;
104
+ // Drop the superseded turn before the new one is appended; the server
105
+ // rebuilds its model context from this transcript on every run, so the
106
+ // old answer must be gone before /api/chat reads it. A failed cleanup is
107
+ // surfaced as text rather than thrown: the user's message is already in
108
+ // the transcript, and silently re-sending on top of the stale turn is
109
+ // exactly the bug this feature exists to fix.
110
+ if (editPending) {
111
+ editPending = false;
112
+ if (sid) {
113
+ try {
114
+ await postJson("/api/history/truncate-last-turn", { sessionId: sid }, bridge.getAuthToken());
115
+ }
116
+ catch (err) {
117
+ yield {
118
+ content: [{ type: "text", text: `⚠️ 编辑未能生效(旧回答仍在上下文里):${err.message}` }],
119
+ status: { type: "incomplete", reason: "error" },
120
+ };
121
+ bridge.onRunEnd({ usage: null, aborted: false });
122
+ return;
123
+ }
124
+ }
125
+ }
126
+ const parts = [];
127
+ const appendDelta = (kind, delta) => {
128
+ const tail = parts.at(-1);
129
+ if (tail && tail.type === kind)
130
+ tail.text += delta;
131
+ else
132
+ parts.push({ type: kind, text: delta });
133
+ };
134
+ // E3: assistant-ui renders metadata.timing through the official
135
+ // useMessageTiming hook but has no producer on the local-runtime path
136
+ // (useStreamingTiming serves external stores; TimingTracker is not
137
+ // exported from any entry). So we measure it right here: the
138
+ // user-perceived wait from sending the request to the first visible
139
+ // output. `ready` is a transport ack and not a token; thinking and
140
+ // tool_start count, because they are the first thing on screen. The
141
+ // clock starts after the edit-truncate cleanup, which is not model wait.
142
+ const streamStartTime = Date.now();
143
+ let firstTokenAt;
144
+ let chunks = 0;
145
+ let toolCalls = 0;
146
+ const snapshot = () => ({
147
+ streamStartTime,
148
+ totalChunks: chunks,
149
+ toolCallCount: toolCalls,
150
+ totalStreamTime: Date.now() - streamStartTime,
151
+ ...(firstTokenAt === undefined ? {} : { firstTokenTime: firstTokenAt - streamStartTime }),
152
+ });
153
+ let usage = null;
154
+ let aborted = false;
155
+ try {
156
+ for await (const ev of streamChat(req, abortSignal, bridge.getAuthToken())) {
157
+ switch (ev.type) {
158
+ case "ready":
159
+ bridge.setSessionId(ev.sessionId);
160
+ continue;
161
+ case "tools_meta":
162
+ bridge.onToolsMeta?.(ev.labels);
163
+ continue;
164
+ case "text_delta":
165
+ firstTokenAt ??= Date.now();
166
+ appendDelta("text", ev.delta);
167
+ break;
168
+ case "thinking_delta":
169
+ firstTokenAt ??= Date.now();
170
+ appendDelta("reasoning", ev.delta);
171
+ break;
172
+ case "tool_start":
173
+ firstTokenAt ??= Date.now();
174
+ toolCalls++;
175
+ parts.push({
176
+ type: "tool-call",
177
+ toolCallId: ev.toolCallId,
178
+ toolName: ev.name,
179
+ args: ev.args,
180
+ argsText: JSON.stringify(ev.args),
181
+ });
182
+ break;
183
+ case "tool_confirm":
184
+ bridge.onToolConfirm({ sessionId: bridge.getSessionId() ?? "", toolCallId: ev.toolCallId, name: ev.name, args: ev.args });
185
+ continue;
186
+ case "tool_update":
187
+ case "tool_end": {
188
+ if (ev.type === "tool_end")
189
+ bridge.onToolSettled(ev.toolCallId);
190
+ const i = parts.findIndex((p) => p.type === "tool-call" && p.toolCallId === ev.toolCallId);
191
+ if (i >= 0) {
192
+ const p = parts[i];
193
+ const view = ev.type === "tool_end" ? ev.result : ev.partial;
194
+ parts[i] = {
195
+ ...p,
196
+ // details 搭 tool_end 顺风车(零协议改动)——
197
+ // 卡片的排版数据从这里来,文本只喂模型/兜底展示。
198
+ result: { text: view.text, details: view.details },
199
+ isError: ev.type === "tool_end" ? !ev.ok : p.isError,
200
+ };
201
+ }
202
+ break;
203
+ }
204
+ case "error":
205
+ parts.push({ type: "text", text: `⚠️ ${ev.message}` });
206
+ break;
207
+ case "message_end":
208
+ if (ev.usage)
209
+ usage = ev.usage;
210
+ continue;
211
+ case "ui_prompt":
212
+ // The server parked the run inside the extension's await; the run
213
+ // resumes when the dialog is answered (or fails closed on timeout).
214
+ bridge.onUiPrompt(ev);
215
+ continue;
216
+ case "ui_notify":
217
+ bridge.onUiNotify(ev);
218
+ continue;
219
+ case "done":
220
+ usage ??= ev.usage;
221
+ aborted = ev.aborted;
222
+ continue;
223
+ }
224
+ chunks++;
225
+ yield { content: [...parts], metadata: { timing: snapshot() } };
226
+ }
227
+ }
228
+ catch (err) {
229
+ if (err.name !== "AbortError") {
230
+ parts.push({ type: "text", text: `⚠️ 网络错误:${err.message}` });
231
+ }
232
+ aborted = true;
233
+ }
234
+ bridge.onRunEnd({ usage, aborted });
235
+ yield {
236
+ content: [...parts],
237
+ status: aborted ? { type: "incomplete", reason: "cancelled" } : undefined,
238
+ metadata: usage ? { custom: { usage }, timing: snapshot() } : { timing: snapshot() },
239
+ };
240
+ },
241
+ };
242
+ }