@njuptlzf/agent-chat-web 0.2.0 → 0.3.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.
- package/dist/AgentChat.d.ts +7 -1
- package/dist/AgentChat.js +23 -5
- package/dist/AgentChatApp.d.ts +4 -1
- package/dist/AgentChatApp.js +2 -2
- package/dist/PersonasPage.js +8 -0
- package/dist/assets/_commonjs-dynamic-modules-TDtrdbi3.js +1 -0
- package/dist/assets/exceljs.min-jlEt4kSc.js +29 -0
- package/dist/assets/index-B7uSE8SM.css +1 -0
- package/dist/assets/index-D57mU5H5.js +50 -0
- package/dist/assets/index-Dviy7gnB.js +44 -0
- package/dist/assets/pdf-CfhDiWmk.js +55 -0
- package/dist/assets/pdf.worker.min-CdXBBzB4.js +1 -0
- package/dist/assets/pdf.worker.min-CjEcRF4W.mjs +28 -0
- package/dist/index.html +13 -0
- package/dist/mount.d.ts +7 -1
- package/dist/mount.js +2 -2
- package/dist/styles.css +1492 -1478
- package/dist/suggestions.d.ts +41 -0
- package/dist/suggestions.js +98 -0
- package/dist/ui/FollowUpSuggestions.d.ts +9 -0
- package/dist/ui/FollowUpSuggestions.js +13 -0
- package/dist/ui/Icon.d.ts +8 -0
- package/dist/ui/Icon.js +26 -0
- package/dist/ui/icons.d.ts +19 -0
- package/dist/ui/icons.js +25 -0
- package/dist/ui/slots.d.ts +23 -0
- package/dist/ui/slots.js +13 -0
- package/package.json +71 -72
- package/src/App.tsx +13 -13
- package/src/agent-chat/AgentChat.tsx +729 -692
- package/src/agent-chat/AgentChatApp.tsx +211 -206
- package/src/agent-chat/PersonasPage.tsx +705 -678
- package/src/agent-chat/adapter.ts +272 -272
- package/src/agent-chat/app-def-check.ts +215 -215
- package/src/agent-chat/app.tsx +327 -327
- package/src/agent-chat/auth.ts +83 -83
- package/src/agent-chat/dock.ts +161 -161
- package/src/agent-chat/docs.ts +179 -179
- package/src/agent-chat/index.ts +17 -17
- package/src/agent-chat/mount.tsx +8 -1
- package/src/agent-chat/qual.ts +55 -55
- package/src/agent-chat/sse.ts +104 -104
- package/src/agent-chat/suggestions.ts +127 -0
- package/src/agent-chat/theme.ts +23 -23
- package/src/agent-chat/ui/CodeCopyHeader.tsx +29 -29
- package/src/agent-chat/ui/ConfirmCard.tsx +32 -32
- package/src/agent-chat/ui/FollowUpSuggestions.tsx +28 -0
- package/src/agent-chat/ui/Icon.tsx +53 -0
- package/src/agent-chat/ui/Lightbox.tsx +32 -32
- package/src/agent-chat/ui/QueueBar.tsx +70 -70
- package/src/agent-chat/ui/Splitter.tsx +81 -81
- package/src/agent-chat/ui/ThemeToggle.tsx +25 -25
- package/src/agent-chat/ui/TierPicker.tsx +112 -112
- package/src/agent-chat/ui/UIPromptCard.tsx +68 -68
- package/src/agent-chat/ui/icons.ts +31 -0
- package/src/agent-chat/ui/slots.tsx +35 -0
- package/src/agent-chat/ui/timefmt.ts +110 -110
- package/src/agent-chat/ui/useNarrow.ts +20 -20
- package/src/fake-product/entry.tsx +63 -54
- package/src/main.tsx +8 -8
- package/src/styles.css +1492 -1478
package/src/agent-chat/sse.ts
CHANGED
|
@@ -1,104 +1,104 @@
|
|
|
1
|
-
import type { ChatEvent, ChatRequest, ConfirmDecision } from "@njuptlzf/agent-chat-protocol";
|
|
2
|
-
import { apiHeaders } from "./auth.ts";
|
|
3
|
-
|
|
4
|
-
/**
|
|
5
|
-
* Turn a non-2xx response into an Error carrying the server's own message.
|
|
6
|
-
*
|
|
7
|
-
* 服务端的 400 是给人看的(「标签最多 20 个字」「unknown tag "x"」),只抛
|
|
8
|
-
* `HTTP 400` 会把这些话全丢掉,用户只能看到一个状态码。读不出 JSON 就退回状态码。
|
|
9
|
-
*/
|
|
10
|
-
async function fail(res: Response): Promise<Error> {
|
|
11
|
-
let detail = "";
|
|
12
|
-
try {
|
|
13
|
-
const body = (await res.json()) as { error?: { message?: string } };
|
|
14
|
-
detail = body?.error?.message ?? "";
|
|
15
|
-
} catch {
|
|
16
|
-
// 不是 JSON(网关错误页之类)——状态码已经够用。
|
|
17
|
-
}
|
|
18
|
-
return new Error(detail ? `${detail}(HTTP ${res.status})` : `HTTP ${res.status}`);
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
/** GET a JSON API with the optional host auth token; throws on non-2xx. */
|
|
22
|
-
export async function fetchJson<T>(path: string, authHeader?: string): Promise<T> {
|
|
23
|
-
const res = await fetch(path, { headers: apiHeaders(authHeader) });
|
|
24
|
-
if (!res.ok) throw await fail(res);
|
|
25
|
-
return res.json() as Promise<T>;
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
/** POST a JSON body with the optional host auth token; throws on non-2xx. */
|
|
29
|
-
export async function postJson<T>(path: string, body: unknown, authHeader?: string): Promise<T> {
|
|
30
|
-
const res = await fetch(path, {
|
|
31
|
-
method: "POST",
|
|
32
|
-
headers: { "content-type": "application/json", ...apiHeaders(authHeader) },
|
|
33
|
-
body: JSON.stringify(body),
|
|
34
|
-
});
|
|
35
|
-
if (!res.ok) throw await fail(res);
|
|
36
|
-
return res.json() as Promise<T>;
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
/** DELETE with the optional host auth token; throws on non-2xx. */
|
|
40
|
-
export async function deleteJson<T>(path: string, authHeader?: string): Promise<T> {
|
|
41
|
-
const res = await fetch(path, {
|
|
42
|
-
method: "DELETE",
|
|
43
|
-
headers: apiHeaders(authHeader),
|
|
44
|
-
});
|
|
45
|
-
if (!res.ok) throw await fail(res);
|
|
46
|
-
return res.json() as Promise<T>;
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
/** Answer a `tool_confirm` event; must be called while its run's stream is open. */
|
|
50
|
-
export async function postDecision(dec: ConfirmDecision, authHeader?: string): Promise<boolean> {
|
|
51
|
-
const res = await fetch("/api/decision", {
|
|
52
|
-
method: "POST",
|
|
53
|
-
headers: { "content-type": "application/json", ...apiHeaders(authHeader) },
|
|
54
|
-
body: JSON.stringify(dec),
|
|
55
|
-
});
|
|
56
|
-
return res.ok;
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
/**
|
|
60
|
-
* POST /api/chat and stream back protocol events. SSE frames are
|
|
61
|
-
* `data: <json>\n\n`; we parse them by hand because EventSource cannot POST.
|
|
62
|
-
*/
|
|
63
|
-
export async function* streamChat(
|
|
64
|
-
req: ChatRequest,
|
|
65
|
-
signal: AbortSignal,
|
|
66
|
-
authHeader?: string,
|
|
67
|
-
): AsyncGenerator<ChatEvent> {
|
|
68
|
-
const res = await fetch("/api/chat", {
|
|
69
|
-
method: "POST",
|
|
70
|
-
headers: { "content-type": "application/json", ...apiHeaders(authHeader) },
|
|
71
|
-
body: JSON.stringify(req),
|
|
72
|
-
signal,
|
|
73
|
-
});
|
|
74
|
-
|
|
75
|
-
if (!res.ok || !res.body) {
|
|
76
|
-
// Non-SSE error responses (401/404/429/…) carry { error: { code, message } }.
|
|
77
|
-
let message = `HTTP ${res.status}`;
|
|
78
|
-
try {
|
|
79
|
-
const body = (await res.json()) as { error?: { message?: string } };
|
|
80
|
-
if (body.error?.message) message = body.error.message;
|
|
81
|
-
} catch {
|
|
82
|
-
/* keep the status line */
|
|
83
|
-
}
|
|
84
|
-
yield { type: "error", code: res.status === 401 ? "unauthorized" : res.status === 429 ? "quota_exceeded" : "internal", message, retryable: false };
|
|
85
|
-
yield { type: "done", aborted: false, usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0, costUsd: 0 } };
|
|
86
|
-
return;
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
const reader = res.body.getReader();
|
|
90
|
-
const decoder = new TextDecoder();
|
|
91
|
-
let buf = "";
|
|
92
|
-
while (true) {
|
|
93
|
-
const { value, done } = await reader.read();
|
|
94
|
-
if (done) break;
|
|
95
|
-
buf += decoder.decode(value, { stream: true });
|
|
96
|
-
let idx;
|
|
97
|
-
while ((idx = buf.indexOf("\n\n")) >= 0) {
|
|
98
|
-
const frame = buf.slice(0, idx);
|
|
99
|
-
buf = buf.slice(idx + 2);
|
|
100
|
-
const line = frame.split("\n").find((l) => l.startsWith("data: "));
|
|
101
|
-
if (line) yield JSON.parse(line.slice(6)) as ChatEvent;
|
|
102
|
-
}
|
|
103
|
-
}
|
|
104
|
-
}
|
|
1
|
+
import type { ChatEvent, ChatRequest, ConfirmDecision } from "@njuptlzf/agent-chat-protocol";
|
|
2
|
+
import { apiHeaders } from "./auth.ts";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Turn a non-2xx response into an Error carrying the server's own message.
|
|
6
|
+
*
|
|
7
|
+
* 服务端的 400 是给人看的(「标签最多 20 个字」「unknown tag "x"」),只抛
|
|
8
|
+
* `HTTP 400` 会把这些话全丢掉,用户只能看到一个状态码。读不出 JSON 就退回状态码。
|
|
9
|
+
*/
|
|
10
|
+
async function fail(res: Response): Promise<Error> {
|
|
11
|
+
let detail = "";
|
|
12
|
+
try {
|
|
13
|
+
const body = (await res.json()) as { error?: { message?: string } };
|
|
14
|
+
detail = body?.error?.message ?? "";
|
|
15
|
+
} catch {
|
|
16
|
+
// 不是 JSON(网关错误页之类)——状态码已经够用。
|
|
17
|
+
}
|
|
18
|
+
return new Error(detail ? `${detail}(HTTP ${res.status})` : `HTTP ${res.status}`);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** GET a JSON API with the optional host auth token; throws on non-2xx. */
|
|
22
|
+
export async function fetchJson<T>(path: string, authHeader?: string): Promise<T> {
|
|
23
|
+
const res = await fetch(path, { headers: apiHeaders(authHeader) });
|
|
24
|
+
if (!res.ok) throw await fail(res);
|
|
25
|
+
return res.json() as Promise<T>;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** POST a JSON body with the optional host auth token; throws on non-2xx. */
|
|
29
|
+
export async function postJson<T>(path: string, body: unknown, authHeader?: string): Promise<T> {
|
|
30
|
+
const res = await fetch(path, {
|
|
31
|
+
method: "POST",
|
|
32
|
+
headers: { "content-type": "application/json", ...apiHeaders(authHeader) },
|
|
33
|
+
body: JSON.stringify(body),
|
|
34
|
+
});
|
|
35
|
+
if (!res.ok) throw await fail(res);
|
|
36
|
+
return res.json() as Promise<T>;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** DELETE with the optional host auth token; throws on non-2xx. */
|
|
40
|
+
export async function deleteJson<T>(path: string, authHeader?: string): Promise<T> {
|
|
41
|
+
const res = await fetch(path, {
|
|
42
|
+
method: "DELETE",
|
|
43
|
+
headers: apiHeaders(authHeader),
|
|
44
|
+
});
|
|
45
|
+
if (!res.ok) throw await fail(res);
|
|
46
|
+
return res.json() as Promise<T>;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Answer a `tool_confirm` event; must be called while its run's stream is open. */
|
|
50
|
+
export async function postDecision(dec: ConfirmDecision, authHeader?: string): Promise<boolean> {
|
|
51
|
+
const res = await fetch("/api/decision", {
|
|
52
|
+
method: "POST",
|
|
53
|
+
headers: { "content-type": "application/json", ...apiHeaders(authHeader) },
|
|
54
|
+
body: JSON.stringify(dec),
|
|
55
|
+
});
|
|
56
|
+
return res.ok;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* POST /api/chat and stream back protocol events. SSE frames are
|
|
61
|
+
* `data: <json>\n\n`; we parse them by hand because EventSource cannot POST.
|
|
62
|
+
*/
|
|
63
|
+
export async function* streamChat(
|
|
64
|
+
req: ChatRequest,
|
|
65
|
+
signal: AbortSignal,
|
|
66
|
+
authHeader?: string,
|
|
67
|
+
): AsyncGenerator<ChatEvent> {
|
|
68
|
+
const res = await fetch("/api/chat", {
|
|
69
|
+
method: "POST",
|
|
70
|
+
headers: { "content-type": "application/json", ...apiHeaders(authHeader) },
|
|
71
|
+
body: JSON.stringify(req),
|
|
72
|
+
signal,
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
if (!res.ok || !res.body) {
|
|
76
|
+
// Non-SSE error responses (401/404/429/…) carry { error: { code, message } }.
|
|
77
|
+
let message = `HTTP ${res.status}`;
|
|
78
|
+
try {
|
|
79
|
+
const body = (await res.json()) as { error?: { message?: string } };
|
|
80
|
+
if (body.error?.message) message = body.error.message;
|
|
81
|
+
} catch {
|
|
82
|
+
/* keep the status line */
|
|
83
|
+
}
|
|
84
|
+
yield { type: "error", code: res.status === 401 ? "unauthorized" : res.status === 429 ? "quota_exceeded" : "internal", message, retryable: false };
|
|
85
|
+
yield { type: "done", aborted: false, usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0, costUsd: 0 } };
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const reader = res.body.getReader();
|
|
90
|
+
const decoder = new TextDecoder();
|
|
91
|
+
let buf = "";
|
|
92
|
+
while (true) {
|
|
93
|
+
const { value, done } = await reader.read();
|
|
94
|
+
if (done) break;
|
|
95
|
+
buf += decoder.decode(value, { stream: true });
|
|
96
|
+
let idx;
|
|
97
|
+
while ((idx = buf.indexOf("\n\n")) >= 0) {
|
|
98
|
+
const frame = buf.slice(0, idx);
|
|
99
|
+
buf = buf.slice(idx + 2);
|
|
100
|
+
const line = frame.split("\n").find((l) => l.startsWith("data: "));
|
|
101
|
+
if (line) yield JSON.parse(line.slice(6)) as ChatEvent;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 「下一步建议」的前端层:生效模式解析 + 自定义 `SuggestionAdapter`。
|
|
3
|
+
*
|
|
4
|
+
* 挂载走 `@assistant-ui` 原生 `adapters.suggestion`(run 结束自动生成、run 开始
|
|
5
|
+
* 自动清空),不自造状态机。数据来源由服务端决定:`llm` 调 `/api/suggestions`,
|
|
6
|
+
* `static` 直接用 `branding.ui.followUp.static`;任何失败静默返回空——建议区
|
|
7
|
+
* 消失而不是报错。
|
|
8
|
+
*/
|
|
9
|
+
import type { BrandingResponse } from "@njuptlzf/agent-chat-protocol";
|
|
10
|
+
import type { SuggestionAdapter, ThreadSuggestion } from "@assistant-ui/react";
|
|
11
|
+
import { apiHeaders, auth } from "./auth.ts";
|
|
12
|
+
|
|
13
|
+
export type FollowUpMode = "off" | "static" | "llm";
|
|
14
|
+
const MODES: readonly FollowUpMode[] = ["off", "static", "llm"];
|
|
15
|
+
const isMode = (v: unknown): v is FollowUpMode =>
|
|
16
|
+
typeof v === "string" && (MODES as readonly string[]).includes(v);
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* 与服务端 `SUGGESTIONS_DEFAULTS` 各持一份的缺省值(两个包不共享模块,
|
|
20
|
+
* 单测钉住两边一致)——改这里要同步那边。
|
|
21
|
+
*/
|
|
22
|
+
export const FOLLOW_UP_DEFAULTS = {
|
|
23
|
+
count: 3,
|
|
24
|
+
maxMessages: 10,
|
|
25
|
+
messageChars: 500,
|
|
26
|
+
totalChars: 4000,
|
|
27
|
+
} as const;
|
|
28
|
+
|
|
29
|
+
/** 解析后的下一步建议配置(服务端已校验,这里再兜一道)。 */
|
|
30
|
+
export interface FollowUpConfig {
|
|
31
|
+
count: number;
|
|
32
|
+
maxMessages: number;
|
|
33
|
+
staticFallback: string[];
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** `branding.ui.followUp` 的声明形状(BrandingUi 未导出,用索引访问拿类型)。 */
|
|
37
|
+
type FollowUpDecl = NonNullable<BrandingResponse["ui"]>["followUp"];
|
|
38
|
+
|
|
39
|
+
/** `branding.ui.followUp` → 前端配置;缺字段走缺省,非法值回落。 */
|
|
40
|
+
export function followUpConfigOf(decl?: FollowUpDecl): FollowUpConfig {
|
|
41
|
+
const count =
|
|
42
|
+
typeof decl?.count === "number" && Number.isInteger(decl.count) && decl.count >= 1 && decl.count <= 5
|
|
43
|
+
? decl.count
|
|
44
|
+
: FOLLOW_UP_DEFAULTS.count;
|
|
45
|
+
const maxMessages =
|
|
46
|
+
typeof decl?.maxMessages === "number" && Number.isInteger(decl.maxMessages) && decl.maxMessages >= 1 && decl.maxMessages <= 20
|
|
47
|
+
? decl.maxMessages
|
|
48
|
+
: FOLLOW_UP_DEFAULTS.maxMessages;
|
|
49
|
+
const staticFallback = Array.isArray(decl?.static)
|
|
50
|
+
? decl.static.filter((s): s is string => typeof s === "string" && s.trim() !== "").map((s) => s.trim())
|
|
51
|
+
: [];
|
|
52
|
+
return { count, maxMessages, staticFallback };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* 生效模式:**全局 `off` 是硬地板**——全局关掉后任何人格都不能重新打开;
|
|
57
|
+
* 否则人格 `followUpMode` > 全局 `mode` > 缺省 `llm`。默认助手(persona 为
|
|
58
|
+
* undefined)用 `branding.defaultPersona` 兜底;该人格不在 personas 表里时回落全局。
|
|
59
|
+
* 服务端 `/api/suggestions` 用同一套优先级复核,两边必须一致。
|
|
60
|
+
*/
|
|
61
|
+
export function resolveFollowUpMode(branding: BrandingResponse, persona?: string): FollowUpMode {
|
|
62
|
+
const globalMode: FollowUpMode = isMode(branding.ui?.followUp?.mode) ? branding.ui.followUp.mode : "llm";
|
|
63
|
+
if (globalMode === "off") return "off";
|
|
64
|
+
const id = persona ?? branding.defaultPersona;
|
|
65
|
+
const perPersona = id ? branding.personas?.[id]?.followUpMode : undefined;
|
|
66
|
+
return isMode(perPersona) ? perPersona : globalMode;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** 只留文本 part(图片/附件/工具细节不出前端),再套单条与总量上限。 */
|
|
70
|
+
function clipForRequest(
|
|
71
|
+
messages: readonly { role: string; content: readonly { type?: string; text?: unknown }[] }[],
|
|
72
|
+
maxMessages: number,
|
|
73
|
+
): { role: string; text: string }[] {
|
|
74
|
+
const kept: { role: string; text: string }[] = [];
|
|
75
|
+
for (const message of messages) {
|
|
76
|
+
if (message.role !== "user" && message.role !== "assistant") continue;
|
|
77
|
+
for (const part of message.content ?? []) {
|
|
78
|
+
if (part?.type !== "text" || typeof part.text !== "string") continue;
|
|
79
|
+
const text = part.text.trim();
|
|
80
|
+
if (!text) continue;
|
|
81
|
+
kept.push({ role: message.role, text: text.slice(0, FOLLOW_UP_DEFAULTS.messageChars) });
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
const window = kept.slice(-Math.max(1, maxMessages));
|
|
85
|
+
let total = 0;
|
|
86
|
+
const out: { role: string; text: string }[] = [];
|
|
87
|
+
for (let i = window.length - 1; i >= 0; i--) {
|
|
88
|
+
total += window[i]!.text.length;
|
|
89
|
+
if (total > FOLLOW_UP_DEFAULTS.totalChars) break;
|
|
90
|
+
out.unshift(window[i]!);
|
|
91
|
+
}
|
|
92
|
+
return out;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** `off` 不产生 adapter(库不生成建议);`static` 本地返回、`llm` 请求服务端。 */
|
|
96
|
+
export function createFollowUpAdapter(
|
|
97
|
+
cfg: FollowUpConfig,
|
|
98
|
+
mode: Exclude<FollowUpMode, "off">,
|
|
99
|
+
personaId?: string,
|
|
100
|
+
): SuggestionAdapter {
|
|
101
|
+
if (mode === "static") {
|
|
102
|
+
const suggestions: readonly ThreadSuggestion[] = cfg.staticFallback.slice(0, cfg.count).map((prompt) => ({ prompt }));
|
|
103
|
+
return { generate: () => Promise.resolve(suggestions) };
|
|
104
|
+
}
|
|
105
|
+
return {
|
|
106
|
+
async generate({ messages, signal }) {
|
|
107
|
+
try {
|
|
108
|
+
// 不用 postJson(不带 signal):这里的 abort 由库的 suggestion controller 驱动。
|
|
109
|
+
const res = await fetch("/api/suggestions", {
|
|
110
|
+
method: "POST",
|
|
111
|
+
headers: { "content-type": "application/json", ...apiHeaders(auth.token) },
|
|
112
|
+
body: JSON.stringify({ messages: clipForRequest(messages, cfg.maxMessages), persona: personaId }),
|
|
113
|
+
signal,
|
|
114
|
+
});
|
|
115
|
+
if (!res.ok) return [];
|
|
116
|
+
const data = (await res.json()) as { suggestions?: unknown };
|
|
117
|
+
if (!Array.isArray(data.suggestions)) return [];
|
|
118
|
+
return data.suggestions
|
|
119
|
+
.filter((s): s is string => typeof s === "string" && s.trim() !== "")
|
|
120
|
+
.slice(0, cfg.count)
|
|
121
|
+
.map((prompt) => ({ prompt }));
|
|
122
|
+
} catch {
|
|
123
|
+
return [];
|
|
124
|
+
}
|
|
125
|
+
},
|
|
126
|
+
};
|
|
127
|
+
}
|
package/src/agent-chat/theme.ts
CHANGED
|
@@ -1,23 +1,23 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Theme mode (L2): "auto" follows the OS via `color-scheme: light dark` +
|
|
3
|
-
* light-dark() tokens; "light"/dark" pin it with a data-theme attribute on
|
|
4
|
-
* <html>. The choice persists per browser (localStorage) — it is a device
|
|
5
|
-
* preference, not product state, so it never travels through the protocol.
|
|
6
|
-
*/
|
|
7
|
-
export type ThemeMode = "auto" | "light" | "dark";
|
|
8
|
-
|
|
9
|
-
const KEY = "ac.theme";
|
|
10
|
-
|
|
11
|
-
export function loadThemeMode(): ThemeMode {
|
|
12
|
-
const v = globalThis.localStorage?.getItem(KEY);
|
|
13
|
-
return v === "light" || v === "dark" ? v : "auto";
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
export function applyThemeMode(mode: ThemeMode): void {
|
|
17
|
-
if (mode === "auto") document.documentElement.removeAttribute("data-theme");
|
|
18
|
-
else document.documentElement.setAttribute("data-theme", mode);
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
export function saveThemeMode(mode: ThemeMode): void {
|
|
22
|
-
globalThis.localStorage?.setItem(KEY, mode);
|
|
23
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* Theme mode (L2): "auto" follows the OS via `color-scheme: light dark` +
|
|
3
|
+
* light-dark() tokens; "light"/dark" pin it with a data-theme attribute on
|
|
4
|
+
* <html>. The choice persists per browser (localStorage) — it is a device
|
|
5
|
+
* preference, not product state, so it never travels through the protocol.
|
|
6
|
+
*/
|
|
7
|
+
export type ThemeMode = "auto" | "light" | "dark";
|
|
8
|
+
|
|
9
|
+
const KEY = "ac.theme";
|
|
10
|
+
|
|
11
|
+
export function loadThemeMode(): ThemeMode {
|
|
12
|
+
const v = globalThis.localStorage?.getItem(KEY);
|
|
13
|
+
return v === "light" || v === "dark" ? v : "auto";
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function applyThemeMode(mode: ThemeMode): void {
|
|
17
|
+
if (mode === "auto") document.documentElement.removeAttribute("data-theme");
|
|
18
|
+
else document.documentElement.setAttribute("data-theme", mode);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function saveThemeMode(mode: ThemeMode): void {
|
|
22
|
+
globalThis.localStorage?.setItem(KEY, mode);
|
|
23
|
+
}
|
|
@@ -1,29 +1,29 @@
|
|
|
1
|
-
import { useState } from "react";
|
|
2
|
-
import type { CodeHeaderProps } from "@assistant-ui/react-markdown";
|
|
3
|
-
|
|
4
|
-
/**
|
|
5
|
-
* Code-fence header with a copy button (assistant-ui's default CodeHeader
|
|
6
|
-
* renders nothing). It receives the raw `code` from the primitive, so there is
|
|
7
|
-
* no DOM scraping here — the string the model emitted is the string copied.
|
|
8
|
-
*/
|
|
9
|
-
export default function CodeCopyHeader({ language, code }: CodeHeaderProps) {
|
|
10
|
-
const [copied, setCopied] = useState(false);
|
|
11
|
-
const copy = async () => {
|
|
12
|
-
try {
|
|
13
|
-
await navigator.clipboard.writeText(code);
|
|
14
|
-
setCopied(true);
|
|
15
|
-
setTimeout(() => setCopied(false), 1500);
|
|
16
|
-
} catch {
|
|
17
|
-
// Clipboard can be refused (permissions/insecure context): stay silent,
|
|
18
|
-
// the code is still selectable by hand.
|
|
19
|
-
}
|
|
20
|
-
};
|
|
21
|
-
return (
|
|
22
|
-
<div className="code-head">
|
|
23
|
-
<span className="code-lang">{language || "text"}</span>
|
|
24
|
-
<button type="button" className="copy-code" onClick={() => void copy()}>
|
|
25
|
-
{copied ? "已复制" : "复制"}
|
|
26
|
-
</button>
|
|
27
|
-
</div>
|
|
28
|
-
);
|
|
29
|
-
}
|
|
1
|
+
import { useState } from "react";
|
|
2
|
+
import type { CodeHeaderProps } from "@assistant-ui/react-markdown";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Code-fence header with a copy button (assistant-ui's default CodeHeader
|
|
6
|
+
* renders nothing). It receives the raw `code` from the primitive, so there is
|
|
7
|
+
* no DOM scraping here — the string the model emitted is the string copied.
|
|
8
|
+
*/
|
|
9
|
+
export default function CodeCopyHeader({ language, code }: CodeHeaderProps) {
|
|
10
|
+
const [copied, setCopied] = useState(false);
|
|
11
|
+
const copy = async () => {
|
|
12
|
+
try {
|
|
13
|
+
await navigator.clipboard.writeText(code);
|
|
14
|
+
setCopied(true);
|
|
15
|
+
setTimeout(() => setCopied(false), 1500);
|
|
16
|
+
} catch {
|
|
17
|
+
// Clipboard can be refused (permissions/insecure context): stay silent,
|
|
18
|
+
// the code is still selectable by hand.
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
return (
|
|
22
|
+
<div className="code-head">
|
|
23
|
+
<span className="code-lang">{language || "text"}</span>
|
|
24
|
+
<button type="button" className="copy-code" onClick={() => void copy()}>
|
|
25
|
+
{copied ? "已复制" : "复制"}
|
|
26
|
+
</button>
|
|
27
|
+
</div>
|
|
28
|
+
);
|
|
29
|
+
}
|
|
@@ -1,32 +1,32 @@
|
|
|
1
|
-
export interface ConfirmRequest {
|
|
2
|
-
sessionId: string;
|
|
3
|
-
toolCallId: string;
|
|
4
|
-
name: string;
|
|
5
|
-
args: Record<string, unknown>;
|
|
6
|
-
}
|
|
7
|
-
|
|
8
|
-
/**
|
|
9
|
-
* Tool-execution permission card (`tool_confirm` event, custom component UI-R3).
|
|
10
|
-
* assistant-ui has no server-parked approval primitive; answering POSTs
|
|
11
|
-
* /api/decision — the caller (ChatApp) keeps that plumbing, this is pure view.
|
|
12
|
-
*/
|
|
13
|
-
export function ConfirmCard({
|
|
14
|
-
request,
|
|
15
|
-
onAnswer,
|
|
16
|
-
}: {
|
|
17
|
-
request: ConfirmRequest;
|
|
18
|
-
onAnswer: (allow: boolean) => void;
|
|
19
|
-
}) {
|
|
20
|
-
return (
|
|
21
|
-
<div className="confirm">
|
|
22
|
-
<div className="confirm-title">
|
|
23
|
-
⚠️ 助手请求执行 <b>{request.name}</b>,是否允许?
|
|
24
|
-
</div>
|
|
25
|
-
<pre className="confirm-args">{JSON.stringify(request.args, null, 2)}</pre>
|
|
26
|
-
<div className="confirm-actions">
|
|
27
|
-
<button className="allow" onClick={() => onAnswer(true)}>允许</button>
|
|
28
|
-
<button className="deny" onClick={() => onAnswer(false)}>拒绝</button>
|
|
29
|
-
</div>
|
|
30
|
-
</div>
|
|
31
|
-
);
|
|
32
|
-
}
|
|
1
|
+
export interface ConfirmRequest {
|
|
2
|
+
sessionId: string;
|
|
3
|
+
toolCallId: string;
|
|
4
|
+
name: string;
|
|
5
|
+
args: Record<string, unknown>;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Tool-execution permission card (`tool_confirm` event, custom component UI-R3).
|
|
10
|
+
* assistant-ui has no server-parked approval primitive; answering POSTs
|
|
11
|
+
* /api/decision — the caller (ChatApp) keeps that plumbing, this is pure view.
|
|
12
|
+
*/
|
|
13
|
+
export function ConfirmCard({
|
|
14
|
+
request,
|
|
15
|
+
onAnswer,
|
|
16
|
+
}: {
|
|
17
|
+
request: ConfirmRequest;
|
|
18
|
+
onAnswer: (allow: boolean) => void;
|
|
19
|
+
}) {
|
|
20
|
+
return (
|
|
21
|
+
<div className="confirm">
|
|
22
|
+
<div className="confirm-title">
|
|
23
|
+
⚠️ 助手请求执行 <b>{request.name}</b>,是否允许?
|
|
24
|
+
</div>
|
|
25
|
+
<pre className="confirm-args">{JSON.stringify(request.args, null, 2)}</pre>
|
|
26
|
+
<div className="confirm-actions">
|
|
27
|
+
<button className="allow" onClick={() => onAnswer(true)}>允许</button>
|
|
28
|
+
<button className="deny" onClick={() => onAnswer(false)}>拒绝</button>
|
|
29
|
+
</div>
|
|
30
|
+
</div>
|
|
31
|
+
);
|
|
32
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { ThreadPrimitive } from "@assistant-ui/react";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* 轮次结束后的「下一步建议」条。数据由库的 suggestion adapter 生成(run 结束自动
|
|
5
|
+
* 触发、run 开始自动清空),这里只负责渲染。必须渲染在 `ThreadPrimitive.Root` 内。
|
|
6
|
+
*
|
|
7
|
+
* `ThreadPrimitive.Suggestions` 本身不渲染包裹元素(空建议时返回 null),所以这里
|
|
8
|
+
* 提供一层 `.ac-followup` 容器;容器空时由 CSS `:empty` 收起,不留空白条。
|
|
9
|
+
* 点击即发送(`send`),与空态快捷问法 chips 的行为一致。
|
|
10
|
+
*/
|
|
11
|
+
export function FollowUpSuggestions() {
|
|
12
|
+
return (
|
|
13
|
+
<div className="ac-followup">
|
|
14
|
+
<ThreadPrimitive.Suggestions>
|
|
15
|
+
{({ suggestion }) => (
|
|
16
|
+
<ThreadPrimitive.Suggestion
|
|
17
|
+
className="ac-followup-chip"
|
|
18
|
+
prompt={suggestion.prompt}
|
|
19
|
+
send
|
|
20
|
+
title={suggestion.prompt}
|
|
21
|
+
>
|
|
22
|
+
{suggestion.title}
|
|
23
|
+
</ThreadPrimitive.Suggestion>
|
|
24
|
+
)}
|
|
25
|
+
</ThreadPrimitive.Suggestions>
|
|
26
|
+
</div>
|
|
27
|
+
);
|
|
28
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import type { ReactNode } from "react";
|
|
2
|
+
import { parseIconSpec, type BuiltinSvgName } from "./icons.ts";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* 内置 SVG(24×24 线框,stroke 走 currentColor 跟随主题,不引任何图标库)。
|
|
6
|
+
* 用惰性函数而不是模块级 JSX 常量:node 侧测试经 tsx 加载本模块时用的是
|
|
7
|
+
* classic JSX 运行时,模块级 JSX 会在 import 期执行 `React.createElement`
|
|
8
|
+
* 直接炸掉;渲染期执行就没有这个问题(浏览器走 react-jsx 自动运行时)。
|
|
9
|
+
*/
|
|
10
|
+
const PATHS: Record<BuiltinSvgName, () => ReactNode> = {
|
|
11
|
+
paperclip: () => (
|
|
12
|
+
<path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48" />
|
|
13
|
+
),
|
|
14
|
+
plus: () => <path d="M12 5v14M5 12h14" />,
|
|
15
|
+
image: () => (
|
|
16
|
+
<>
|
|
17
|
+
<rect x="3" y="3" width="18" height="18" rx="2" ry="2" />
|
|
18
|
+
<circle cx="8.5" cy="8.5" r="1.5" />
|
|
19
|
+
<polyline points="21 15 16 10 5 21" />
|
|
20
|
+
</>
|
|
21
|
+
),
|
|
22
|
+
upload: () => (
|
|
23
|
+
<>
|
|
24
|
+
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
|
|
25
|
+
<polyline points="17 8 12 3 7 8" />
|
|
26
|
+
<line x1="12" y1="3" x2="12" y2="15" />
|
|
27
|
+
</>
|
|
28
|
+
),
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* 槽位用的图标渲染器。svg 走白名单 JSX(绝不用 dangerouslySetInnerHTML)、
|
|
33
|
+
* 文本走 React 文本节点、url 走 `<img>`(协议已在 parseIconSpec 校验)。
|
|
34
|
+
*/
|
|
35
|
+
export function Icon({ spec, className = "ac-icon" }: { spec?: string; className?: string }) {
|
|
36
|
+
const icon = parseIconSpec(spec);
|
|
37
|
+
if (icon.kind === "url") return <img className={className} src={icon.href} alt="" />;
|
|
38
|
+
if (icon.kind === "text") return <span className={className} aria-hidden="true">{icon.text}</span>;
|
|
39
|
+
return (
|
|
40
|
+
<svg
|
|
41
|
+
className={className}
|
|
42
|
+
viewBox="0 0 24 24"
|
|
43
|
+
fill="none"
|
|
44
|
+
stroke="currentColor"
|
|
45
|
+
strokeWidth={2}
|
|
46
|
+
strokeLinecap="round"
|
|
47
|
+
strokeLinejoin="round"
|
|
48
|
+
aria-hidden="true"
|
|
49
|
+
>
|
|
50
|
+
{PATHS[icon.name]()}
|
|
51
|
+
</svg>
|
|
52
|
+
);
|
|
53
|
+
}
|
|
@@ -1,32 +1,32 @@
|
|
|
1
|
-
import { useEffect, useState } from "react";
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* ⑥ 图片点击放大(lightbox)。全局委托监听,只认 `.thread` 内的 `<img>`
|
|
5
|
-
* (品牌 logo、头像等不在对话区,不会触发)。点击遮罩或放大图本身关闭,
|
|
6
|
-
* Esc 也关闭。纯前端,零协议改动。
|
|
7
|
-
*/
|
|
8
|
-
export function Lightbox() {
|
|
9
|
-
const [src, setSrc] = useState<string | null>(null);
|
|
10
|
-
useEffect(() => {
|
|
11
|
-
const onClick = (e: MouseEvent) => {
|
|
12
|
-
const t = e.target as HTMLElement | null;
|
|
13
|
-
if (!(t instanceof HTMLImageElement) || !t.closest(".thread")) return;
|
|
14
|
-
setSrc(t.currentSrc || t.src);
|
|
15
|
-
};
|
|
16
|
-
const onKey = (e: KeyboardEvent) => {
|
|
17
|
-
if (e.key === "Escape") setSrc(null);
|
|
18
|
-
};
|
|
19
|
-
document.addEventListener("click", onClick, true);
|
|
20
|
-
document.addEventListener("keydown", onKey);
|
|
21
|
-
return () => {
|
|
22
|
-
document.removeEventListener("click", onClick, true);
|
|
23
|
-
document.removeEventListener("keydown", onKey);
|
|
24
|
-
};
|
|
25
|
-
}, []);
|
|
26
|
-
if (!src) return null;
|
|
27
|
-
return (
|
|
28
|
-
<div className="lightbox" role="dialog" aria-label="图片预览" onClick={() => setSrc(null)}>
|
|
29
|
-
<img src={src} alt="" />
|
|
30
|
-
</div>
|
|
31
|
-
);
|
|
32
|
-
}
|
|
1
|
+
import { useEffect, useState } from "react";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* ⑥ 图片点击放大(lightbox)。全局委托监听,只认 `.thread` 内的 `<img>`
|
|
5
|
+
* (品牌 logo、头像等不在对话区,不会触发)。点击遮罩或放大图本身关闭,
|
|
6
|
+
* Esc 也关闭。纯前端,零协议改动。
|
|
7
|
+
*/
|
|
8
|
+
export function Lightbox() {
|
|
9
|
+
const [src, setSrc] = useState<string | null>(null);
|
|
10
|
+
useEffect(() => {
|
|
11
|
+
const onClick = (e: MouseEvent) => {
|
|
12
|
+
const t = e.target as HTMLElement | null;
|
|
13
|
+
if (!(t instanceof HTMLImageElement) || !t.closest(".thread")) return;
|
|
14
|
+
setSrc(t.currentSrc || t.src);
|
|
15
|
+
};
|
|
16
|
+
const onKey = (e: KeyboardEvent) => {
|
|
17
|
+
if (e.key === "Escape") setSrc(null);
|
|
18
|
+
};
|
|
19
|
+
document.addEventListener("click", onClick, true);
|
|
20
|
+
document.addEventListener("keydown", onKey);
|
|
21
|
+
return () => {
|
|
22
|
+
document.removeEventListener("click", onClick, true);
|
|
23
|
+
document.removeEventListener("keydown", onKey);
|
|
24
|
+
};
|
|
25
|
+
}, []);
|
|
26
|
+
if (!src) return null;
|
|
27
|
+
return (
|
|
28
|
+
<div className="lightbox" role="dialog" aria-label="图片预览" onClick={() => setSrc(null)}>
|
|
29
|
+
<img src={src} alt="" />
|
|
30
|
+
</div>
|
|
31
|
+
);
|
|
32
|
+
}
|