@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,272 @@
1
+ import type { ChatAttachment, ChatEvent, ChatImage, ChatRequest, TokenUsage } from "@njuptlzf/agent-chat-protocol";
2
+ import type { ChatModelAdapter, MessageTiming, ThreadAssistantMessagePart } from "@assistant-ui/react";
3
+ import type { ToolCallMessagePart } from "@assistant-ui/react";
4
+ import { postJson, streamChat } from "./sse.ts";
5
+
6
+ /** `data:image/png;base64,AAAA` -> the bare base64 the wire wants. */
7
+ const DATA_URL = /^data:([^;,]+);base64,(.+)$/;
8
+
9
+ /** A composer attachment data URL in the wire shape, or undefined if it is not an inline image. */
10
+ export function dataUrlToImage(url: string): ChatImage | undefined {
11
+ const m = DATA_URL.exec(url);
12
+ return m ? { mimeType: m[1], data: m[2] } : undefined;
13
+ }
14
+
15
+ type PartLike = { type: string };
16
+ type LastLike = {
17
+ role: string;
18
+ content: readonly PartLike[];
19
+ attachments?: readonly { content?: readonly PartLike[] }[];
20
+ };
21
+
22
+ function imageParts(last: LastLike | undefined): ChatImage[] {
23
+ if (last?.role !== "user") return [];
24
+ const out: ChatImage[] = [];
25
+ const push = (part: PartLike) => {
26
+ if (part.type !== "image") return;
27
+ const url = (part as { image?: string }).image;
28
+ const img = typeof url === "string" ? dataUrlToImage(url) : undefined;
29
+ if (img) out.push(img);
30
+ };
31
+ for (const part of last.content) push(part);
32
+ // The edit composer lifts a user message's non-text parts out of `content`
33
+ // into `attachments`, so an edited image would otherwise be dropped on re-send.
34
+ for (const att of last.attachments ?? []) for (const part of att.content ?? []) push(part);
35
+ return out;
36
+ }
37
+
38
+ /**
39
+ * The converted-document parts docs.ts puts on a user message (type "file",
40
+ * mimeType "text/markdown", data = the Markdown itself). Same both-places scan
41
+ * as imageParts: the edit composer lifts non-text parts into `attachments`.
42
+ */
43
+ function docParts(last: LastLike | undefined): ChatAttachment[] {
44
+ if (last?.role !== "user") return [];
45
+ const out: ChatAttachment[] = [];
46
+ const push = (part: PartLike) => {
47
+ if (part.type !== "file") return;
48
+ const p = part as { filename?: string; data?: string; mimeType?: string };
49
+ if (p.mimeType !== "text/markdown" || typeof p.data !== "string" || p.data.trim() === "") return;
50
+ out.push({ name: p.filename ?? "附件", text: p.data });
51
+ };
52
+ for (const part of last.content) push(part);
53
+ for (const att of last.attachments ?? []) for (const part of att.content ?? []) push(part);
54
+ return out;
55
+ }
56
+
57
+ export interface ChatBridge {
58
+ getSessionId(): string | undefined;
59
+ setSessionId(sessionId: string): void;
60
+ getContext(): Record<string, unknown> | undefined;
61
+ getAuthToken(): string | undefined;
62
+ /** The chosen quality tier id, or undefined to run the manifest default. */
63
+ getTier(): string | undefined;
64
+ /** The scope this conversation belongs to, or undefined to run the product default. */
65
+ getScope(): string | undefined;
66
+ /** 人格:undefined = 产品默认(默认助手)。会话一旦建立就绑死,换人格会 400。 */
67
+ getPersona?(): string | undefined;
68
+ onRunEnd(info: { usage: TokenUsage | null; aborted: boolean }): void;
69
+ /** The server paused a gated tool and waits for POST /api/decision. */
70
+ onToolConfirm(info: { sessionId: string; toolCallId: string; name: string; args: Record<string, unknown> }): void;
71
+ /** A confirmed tool call finished (approved or denied); dismiss its card. */
72
+ onToolSettled(toolCallId: string): void;
73
+ /** 工具中文名:服务端首帧下发一次,UI 只显示这句,不显示 mcp__ 声明名。 */
74
+ onToolsMeta?(labels: Record<string, string>): void;
75
+ /** An extension is waiting for an answer (select/confirm/input); POST /api/ui-response when decided. */
76
+ onUiPrompt(prompt: UiPromptEvent): void;
77
+ /** An extension sent a notification; show it, no answer expected. */
78
+ onUiNotify(note: UiNotifyEvent): void;
79
+ }
80
+
81
+ /**
82
+ * Set when an edit composer submits, consumed by the next run.
83
+ *
84
+ * The server keeps the transcript, so an edited message must drop the
85
+ * superseded turn before the new one is sent. The run is the only place that
86
+ * both knows the session id and can await the cleanup, and assistant-ui gives
87
+ * the adapter no "this is an edit" flag (`sourceId` is dropped before
88
+ * ChatModelRunOptions). Module-level state is fine here: one chat runtime per
89
+ * page, and the flag is only ever set synchronously on the send path.
90
+ */
91
+ let editPending = false;
92
+
93
+ /** Mark the next run as an edit. Call it before the composer sends. */
94
+ export function markEdit(): void {
95
+ editPending = true;
96
+ }
97
+
98
+ type ToolCallPart = Extract<ThreadAssistantMessagePart, { type: "tool-call" }>;
99
+
100
+ /** An extension dialog forwarded by the server (event and POST /api/ui-response payload share this shape). */
101
+ export type UiPromptEvent = Extract<ChatEvent, { type: "ui_prompt" }>;
102
+ /** A fire-and-forget `ctx.ui.notify` from an extension. */
103
+ export type UiNotifyEvent = Extract<ChatEvent, { type: "ui_notify" }>;
104
+
105
+ /**
106
+ * Bridges our SSE wire protocol to assistant-ui's ChatModelAdapter.
107
+ *
108
+ * The server owns the conversation history (resume by sessionId), so a run
109
+ * sends only the newest user message — never the whole transcript.
110
+ */
111
+ export function createChatAdapter(bridge: ChatBridge): ChatModelAdapter {
112
+ return {
113
+ async *run({ messages, abortSignal }) {
114
+ const last = messages.at(-1);
115
+ const userText =
116
+ last?.role === "user"
117
+ ? last.content.filter((p) => p.type === "text").map((p) => (p as { text: string }).text).join("")
118
+ : "";
119
+
120
+ const req: ChatRequest = { message: userText };
121
+ const sid = bridge.getSessionId();
122
+ if (sid) req.sessionId = sid;
123
+ const ctx = bridge.getContext();
124
+ if (ctx) req.context = ctx;
125
+ const tier = bridge.getTier();
126
+ if (tier) req.tier = tier;
127
+ const scope = bridge.getScope();
128
+ if (scope) req.scope = scope;
129
+ const persona = bridge.getPersona?.();
130
+ if (persona) req.persona = persona;
131
+ const images = imageParts(last);
132
+ if (images.length > 0) req.images = images;
133
+ const docs = docParts(last);
134
+ if (docs.length > 0) req.attachments = docs;
135
+
136
+ // Drop the superseded turn before the new one is appended; the server
137
+ // rebuilds its model context from this transcript on every run, so the
138
+ // old answer must be gone before /api/chat reads it. A failed cleanup is
139
+ // surfaced as text rather than thrown: the user's message is already in
140
+ // the transcript, and silently re-sending on top of the stale turn is
141
+ // exactly the bug this feature exists to fix.
142
+ if (editPending) {
143
+ editPending = false;
144
+ if (sid) {
145
+ try {
146
+ await postJson("/api/history/truncate-last-turn", { sessionId: sid }, bridge.getAuthToken());
147
+ } catch (err) {
148
+ yield {
149
+ content: [{ type: "text", text: `⚠️ 编辑未能生效(旧回答仍在上下文里):${(err as Error).message}` }],
150
+ status: { type: "incomplete", reason: "error" },
151
+ };
152
+ bridge.onRunEnd({ usage: null, aborted: false });
153
+ return;
154
+ }
155
+ }
156
+ }
157
+
158
+ const parts: ThreadAssistantMessagePart[] = [];
159
+ const appendDelta = (kind: "text" | "reasoning", delta: string) => {
160
+ const tail = parts.at(-1);
161
+ if (tail && tail.type === kind) (tail as { text: string }).text += delta;
162
+ else parts.push({ type: kind, text: delta });
163
+ };
164
+
165
+ // E3: assistant-ui renders metadata.timing through the official
166
+ // useMessageTiming hook but has no producer on the local-runtime path
167
+ // (useStreamingTiming serves external stores; TimingTracker is not
168
+ // exported from any entry). So we measure it right here: the
169
+ // user-perceived wait from sending the request to the first visible
170
+ // output. `ready` is a transport ack and not a token; thinking and
171
+ // tool_start count, because they are the first thing on screen. The
172
+ // clock starts after the edit-truncate cleanup, which is not model wait.
173
+ const streamStartTime = Date.now();
174
+ let firstTokenAt: number | undefined;
175
+ let chunks = 0;
176
+ let toolCalls = 0;
177
+ const snapshot = (): MessageTiming => ({
178
+ streamStartTime,
179
+ totalChunks: chunks,
180
+ toolCallCount: toolCalls,
181
+ totalStreamTime: Date.now() - streamStartTime,
182
+ ...(firstTokenAt === undefined ? {} : { firstTokenTime: firstTokenAt - streamStartTime }),
183
+ });
184
+
185
+ let usage: TokenUsage | null = null;
186
+ let aborted = false;
187
+ try {
188
+ for await (const ev of streamChat(req, abortSignal, bridge.getAuthToken()) as AsyncGenerator<ChatEvent>) {
189
+ switch (ev.type) {
190
+ case "ready":
191
+ bridge.setSessionId(ev.sessionId);
192
+ continue;
193
+ case "tools_meta":
194
+ bridge.onToolsMeta?.(ev.labels);
195
+ continue;
196
+ case "text_delta":
197
+ firstTokenAt ??= Date.now();
198
+ appendDelta("text", ev.delta);
199
+ break;
200
+ case "thinking_delta":
201
+ firstTokenAt ??= Date.now();
202
+ appendDelta("reasoning", ev.delta);
203
+ break;
204
+ case "tool_start":
205
+ firstTokenAt ??= Date.now();
206
+ toolCalls++;
207
+ parts.push({
208
+ type: "tool-call",
209
+ toolCallId: ev.toolCallId,
210
+ toolName: ev.name,
211
+ args: ev.args as ToolCallPart["args"],
212
+ argsText: JSON.stringify(ev.args),
213
+ });
214
+ break;
215
+ case "tool_confirm":
216
+ bridge.onToolConfirm({ sessionId: bridge.getSessionId() ?? "", toolCallId: ev.toolCallId, name: ev.name, args: ev.args });
217
+ continue;
218
+ case "tool_update":
219
+ case "tool_end": {
220
+ if (ev.type === "tool_end") bridge.onToolSettled(ev.toolCallId);
221
+ const i = parts.findIndex((p) => p.type === "tool-call" && p.toolCallId === ev.toolCallId);
222
+ if (i >= 0) {
223
+ const p = parts[i] as ToolCallPart;
224
+ const view = ev.type === "tool_end" ? ev.result : ev.partial;
225
+ parts[i] = {
226
+ ...p,
227
+ // details 搭 tool_end 顺风车(零协议改动)——
228
+ // 卡片的排版数据从这里来,文本只喂模型/兜底展示。
229
+ result: { text: view.text, details: view.details } as ToolCallPart["result"],
230
+ isError: ev.type === "tool_end" ? !ev.ok : p.isError,
231
+ };
232
+ }
233
+ break;
234
+ }
235
+ case "error":
236
+ parts.push({ type: "text", text: `⚠️ ${ev.message}` });
237
+ break;
238
+ case "message_end":
239
+ if (ev.usage) usage = ev.usage;
240
+ continue;
241
+ case "ui_prompt":
242
+ // The server parked the run inside the extension's await; the run
243
+ // resumes when the dialog is answered (or fails closed on timeout).
244
+ bridge.onUiPrompt(ev);
245
+ continue;
246
+ case "ui_notify":
247
+ bridge.onUiNotify(ev);
248
+ continue;
249
+ case "done":
250
+ usage ??= ev.usage;
251
+ aborted = ev.aborted;
252
+ continue;
253
+ }
254
+ chunks++;
255
+ yield { content: [...parts], metadata: { timing: snapshot() } };
256
+ }
257
+ } catch (err) {
258
+ if ((err as Error).name !== "AbortError") {
259
+ parts.push({ type: "text", text: `⚠️ 网络错误:${(err as Error).message}` });
260
+ }
261
+ aborted = true;
262
+ }
263
+
264
+ bridge.onRunEnd({ usage, aborted });
265
+ yield {
266
+ content: [...parts],
267
+ status: aborted ? { type: "incomplete", reason: "cancelled" } : undefined,
268
+ metadata: usage ? { custom: { usage }, timing: snapshot() } : { timing: snapshot() },
269
+ };
270
+ },
271
+ };
272
+ }
@@ -0,0 +1,215 @@
1
+ /**
2
+ * 接缝:core 对 `AppDef` 的**结构契约**校验器。
3
+ *
4
+ * 为什么要有这个:core 的 `useAppHost` 从 def 里读七八个字段,每个字段都带着
5
+ * 一条**没说出口**的要求(写错了不报错,只是某个路由失灵)。第二接入方照抄
6
+ * `App.tsx` 时无从知道这些——只能靠「跑起来看侧栏少了一项」。
7
+ *
8
+ * 这里把隐含要求写成显式的校验器:产品写完 def 跑一遍,报错就是问题。
9
+ * core 不 import 任何产品(边界守卫守着),校验器只认结构。
10
+ */
11
+ import type { AppDef, HostCtx } from "./app.tsx";
12
+
13
+ export interface DefProblem {
14
+ /** 出问题的位置(字段名或路由键)。 */
15
+ where: string;
16
+ /** 人话说明 + 怎么修。 */
17
+ message: string;
18
+ }
19
+
20
+ /**
21
+ * 路由键的合法形状。
22
+ *
23
+ * core 的 `routeFromHash` 用 `/^#\/([a-z]+)/` 从 hash 里取路由键——**只认小写
24
+ * 字母**。所以 "my-page"、"q1"、"记录" 这类键在 hash 里取不出来,会被静默
25
+ * 打回 chatRoute(页面看着像「点不动」)。这条以前只有 core 源码里那个正则
26
+ * 说过,现在写进契约里。
27
+ */
28
+ export const ROUTE_KEY_RE = /^[a-z]+$/;
29
+
30
+ /** rewrites 的值可以带 query(`record?tab=wrong`),取路径部分来判合法性。 */
31
+ function routePathOf(target: string): string {
32
+ return target.split("?")[0]!;
33
+ }
34
+
35
+ /**
36
+ * 校验用的**标准上下文**(构建期与测试共用,避免两处各造一份漂移)。
37
+ *
38
+ * 为什么要好几个:`navItems` 与 `guard` 是**动态**的——侧栏条目随「有没有选
39
+ * 选项、这个选项有哪些科目、是不是 admin、审计有没有被取消」而变。只用一个
40
+ * 上下文校验,等于只测了其中一条分支;其余分支写错了照样发版。
41
+ *
42
+ * 四份覆盖了所有会改变导航的条件组合:未登录 / 普通用户单科 / 普通用户三科 /
43
+ * 管理员三科。第二接入方如果有更多维度(比如按会员等级显示入口),自己再补。
44
+ */
45
+ export function sampleHostContexts(): Array<{ name: string; ctx: HostCtx }> {
46
+ const branding = {
47
+ title: "示例产品",
48
+ defaultPersona: "default",
49
+ personas: { default: { label: "助手" } },
50
+ } as unknown as HostCtx["branding"];
51
+ const qual = (subjects: string[]) =>
52
+ ({ id: "demo", level: "senior", label: "示例选项", subjects }) as unknown as HostCtx["qual"];
53
+ const who = (roles: string[], extra: Record<string, unknown> = {}) =>
54
+ ({
55
+ userId: "u1",
56
+ roles,
57
+ authzEnabled: true,
58
+ memberUntil: null,
59
+ bannedUntil: null,
60
+ auditRevoked: false,
61
+ quota: { runsToday: 0, runCap: null, tokensToday: 0, tokenCap: null },
62
+ ...extra,
63
+ }) as unknown as HostCtx["who"];
64
+ const base = {
65
+ branding,
66
+ route: "",
67
+ persona: "",
68
+ onQuals: false,
69
+ go: () => {},
70
+ pickQual: () => {},
71
+ };
72
+ return [
73
+ { name: "未登录", ctx: { ...base, who: null, qual: null } as HostCtx },
74
+ { name: "普通用户·单科", ctx: { ...base, who: who(["user"]), qual: qual(["mcq"]) } as HostCtx },
75
+ { name: "普通用户·三科", ctx: { ...base, who: who(["user"]), qual: qual(["mcq", "case", "essay"]) } as HostCtx },
76
+ { name: "管理员·三科", ctx: { ...base, who: who(["admin"]), qual: qual(["mcq", "case", "essay"]) } as HostCtx },
77
+ // 审计被取消是一条独立分支:navItems 会隐去审计入口,guard 会把它弹回。
78
+ { name: "普通用户·审计被取消", ctx: { ...base, who: who(["user"], { auditRevoked: true }), qual: qual(["mcq"]) } as HostCtx },
79
+ ];
80
+ }
81
+
82
+ /**
83
+ * 校验一份 AppDef 是否满足 core 的要求。
84
+ *
85
+ * 返回**空数组** = 没问题。每条问题都指明位置与怎么修。
86
+ *
87
+ * 注意 `ctx` 是必需的:`navItems` 与 `guard` 都要 ctx 才能算出结果(它们依赖
88
+ * 当前选项与登录身份),而这两个字段的错误恰好是最难自查的(侧栏少一项 /
89
+ * 守卫把人弹到不存在的页)。
90
+ */
91
+ export function validateAppDef(def: AppDef, ctx: HostCtx): DefProblem[] {
92
+ const problems: DefProblem[] = [];
93
+ const add = (where: string, message: string) => problems.push({ where, message });
94
+
95
+ // ① routes:合法 hash 路由的键集。core 认不出的键 = 一个进不去的页面。
96
+ const routes = def.routes;
97
+ if (!routes || typeof routes !== "object" || Array.isArray(routes)) {
98
+ add("routes", "必须是对象(路由键 → 导航文案)");
99
+ return problems; // 后面几项都依赖它,缺了就别报噪音了
100
+ }
101
+ const keys = Object.keys(routes);
102
+ if (keys.length === 0) {
103
+ add("routes", "不能为空——core 用它认合法 hash 路由,空表等于所有链接都打回 chatRoute");
104
+ }
105
+ for (const k of keys) {
106
+ if (!ROUTE_KEY_RE.test(k)) {
107
+ add(`routes.${k}`, "路由键只能是小写字母(core 用 /^#\\/([a-z]+)/ 取键,含数字/连字符/中文会取不出来)");
108
+ }
109
+ if (typeof routes[k] !== "string" || !routes[k]!.trim()) {
110
+ add(`routes.${k}`, "导航文案必须是非空字符串(侧栏会显示它)");
111
+ }
112
+ }
113
+
114
+ // ② chatRoute:聊天坞的路由键。它在 routes 里才谈得上「有文案、有高亮」。
115
+ // 两条判据各管一种情况:空值(必填没填)vs 非空但不在路由表里。
116
+ if (!def.chatRoute) {
117
+ add("chatRoute", "必填(core 用它兜底:认不出的 hash 路由都回落到它)");
118
+ } else if (!(def.chatRoute in routes)) {
119
+ add("chatRoute", `"${def.chatRoute}" 不在 routes 里(core 认不出这个路由键,且侧栏没有它的文案)`);
120
+ }
121
+
122
+ // ③ home:收起聊天坞时退回的业务页。必须是合法路由,否则退回后又被打回 chatRoute。
123
+ if (!def.home) {
124
+ add("home", "必填(core 用它作为「最后一个业务页」的初值)");
125
+ } else if (!(def.home in routes)) {
126
+ add("home", `"${def.home}" 不在 routes 里(core 退回这个页时会被打回 chatRoute)`);
127
+ }
128
+
129
+ // ④ rewrites:老链接就地改写。**键是老链接**(可能早就不在 routes 里了——
130
+ // 那正是要改写的原因),只有目标必须是合法路由。
131
+ for (const [from, to] of Object.entries(def.rewrites ?? {})) {
132
+ if (typeof to !== "string" || !to.trim()) {
133
+ add(`rewrites.${from}`, "改写目标必须是非空字符串");
134
+ continue;
135
+ }
136
+ const p = routePathOf(to);
137
+ if (!(p in routes)) {
138
+ add(`rewrites.${from}`, `改写目标 "${to}" 的路由 "${p}" 不在 routes 里(改写过去就是个进不去的页)`);
139
+ }
140
+ }
141
+
142
+ // ⑤ navAlias:高亮归属。值必须是合法路由,否则高亮无处可落(那一项永远不亮)。
143
+ for (const [from, to] of Object.entries(def.navAlias ?? {})) {
144
+ if (!(from in routes)) {
145
+ add(`navAlias.${from}`, "高亮归属的键不在 routes 里");
146
+ }
147
+ if (typeof to !== "string" || !(to in routes)) {
148
+ add(`navAlias.${from}`, `高亮归属目标 "${to}" 不在 routes 里(侧栏那一项永远不高亮)`);
149
+ }
150
+ }
151
+
152
+ // ⑥ navItems:侧栏条目。每项的 route 必须有文案(core 直接渲染 label)。
153
+ try {
154
+ const items = def.navItems(ctx);
155
+ const navRoutes = items.map((i) => i.route);
156
+ for (const [i, item] of items.entries()) {
157
+ if (!item || typeof item.route !== "string" || !item.route.trim()) {
158
+ add(`navItems[${i}].route`, "必须是非空字符串");
159
+ continue;
160
+ }
161
+ if (!(item.route in routes)) {
162
+ add(`navItems[${i}].route`, `"${item.route}" 不在 routes 里(侧栏点了会跳到进不去的页)`);
163
+ }
164
+ if (typeof item.label !== "string" || !item.label.trim()) {
165
+ add(`navItems[${i}].label`, "必须是非空字符串(侧栏显示它)");
166
+ }
167
+ }
168
+ const dup = navRoutes.filter((r, i) => navRoutes.indexOf(r) !== i);
169
+ if (dup.length) {
170
+ add("navItems", `有重复路由:${[...new Set(dup)].join("、")}(同一项出现两次,侧栏会重复)`);
171
+ }
172
+ } catch (err) {
173
+ add("navItems", `调用抛错:${String((err as Error)?.message ?? err)}`);
174
+ }
175
+
176
+ // ⑦ guard:受限路由弹回的目标。返回值必须是合法路由,否则人被弹到一个进不去的页。
177
+ // core 会对**每个路由**都问一次 guard,所以同一个坏目标会重复出现——按
178
+ // 「目标」归并成一条,把触发它的路由列出来(否则一个 guard 写错能刷十几行,
179
+ // 真正要看的信息被淹掉)。
180
+ if (def.guard) {
181
+ const badTargets = new Map<string, string[]>();
182
+ for (const r of keys) {
183
+ try {
184
+ const target = def.guard(r, ctx);
185
+ if (target !== null && target !== undefined && (typeof target !== "string" || !(target in routes))) {
186
+ const key = String(target);
187
+ const from = badTargets.get(key);
188
+ if (from) from.push(r);
189
+ else badTargets.set(key, [r]);
190
+ }
191
+ } catch (err) {
192
+ add(`guard("${r}")`, `调用抛错:${String((err as Error)?.message ?? err)}`);
193
+ }
194
+ }
195
+ for (const [target, from] of badTargets) {
196
+ add(
197
+ "guard",
198
+ `弹回目标 "${target}" 不在 routes 里(人会停在一个进不去的 hash;触发它的路由:${from.join("、")})`,
199
+ );
200
+ }
201
+ }
202
+
203
+ // ⑧ page:页面渲染。缺了就没有任何页面能渲染出来。
204
+ if (typeof def.page !== "function") {
205
+ add("page", "必填(core 用它渲染页面内容)");
206
+ }
207
+
208
+ // ⑨ 侧栏可达性**不在这里查**:`navItems(ctx)` 是**动态**的(依赖当前选项的
209
+ // 科目、是否 admin、授权闸是否启用),同一个路由在某一刻不在侧栏是完全
210
+ // 正常的(<product> 的 case/essay 由科目驱动、admin/personas 只给 admin)。
211
+ // 静态查「routes 里的路由是否都在侧栏」必然误判。
212
+ // 反方向(侧栏项必须在 routes 里)才是硬要求,已在 ⑥ 查。
213
+
214
+ return problems;
215
+ }