@njuptlzf/agent-chat-web 0.0.0-stage → 0.1.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/package.json +66 -4
- package/src/agent-chat/AgentChat.tsx +692 -0
- package/src/agent-chat/AgentChatApp.tsx +206 -0
- package/src/agent-chat/Dock.tsx +74 -0
- package/src/agent-chat/PersonasPage.tsx +678 -0
- package/src/agent-chat/adapter.ts +272 -0
- package/src/agent-chat/app-def-check.ts +215 -0
- package/src/agent-chat/app.tsx +327 -0
- package/src/agent-chat/auth.ts +83 -0
- package/src/agent-chat/dock.ts +162 -0
- package/src/agent-chat/docs.ts +179 -0
- package/src/agent-chat/index.ts +17 -0
- package/src/agent-chat/mount.tsx +123 -0
- package/src/agent-chat/qual.ts +55 -0
- package/src/agent-chat/sse.ts +104 -0
- package/src/agent-chat/theme.ts +23 -0
- package/src/agent-chat/ui/CodeCopyHeader.tsx +29 -0
- package/src/agent-chat/ui/ConfirmCard.tsx +32 -0
- package/src/agent-chat/ui/Lightbox.tsx +32 -0
- package/src/agent-chat/ui/QueueBar.tsx +70 -0
- package/src/agent-chat/ui/Splitter.tsx +81 -0
- package/src/agent-chat/ui/ThemeToggle.tsx +25 -0
- package/src/agent-chat/ui/TierPicker.tsx +112 -0
- package/src/agent-chat/ui/UIPromptCard.tsx +68 -0
- package/src/agent-chat/ui/timefmt.ts +110 -0
- package/src/agent-chat/ui/useNarrow.ts +20 -0
- package/src/styles.css +1478 -0
- package/README.md +0 -3
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Browser-side document -> Markdown conversion (批 B4-A).
|
|
3
|
+
*
|
|
4
|
+
* Everything we send the model must be text, so the browser converts the
|
|
5
|
+
* user's file and the result travels as `ChatRequest.attachments`. The server
|
|
6
|
+
* parses nothing — that is the design decision this module exists for
|
|
7
|
+
* (the B5 design doc in docs/ records the server-side alternative).
|
|
8
|
+
*
|
|
9
|
+
* Accepted fidelity loss (user's call): text layers of pdf/docx/xlsx are
|
|
10
|
+
* extracted roughly linearly; layout, complex tables and scanned pages come
|
|
11
|
+
* out degraded, and an empty extraction is surfaced as an error instead of
|
|
12
|
+
* being sent. The heavy parsers are dynamically imported so the base bundle
|
|
13
|
+
* stays lean.
|
|
14
|
+
*/
|
|
15
|
+
import type { ChatAttachment } from "@njuptlzf/agent-chat-protocol";
|
|
16
|
+
|
|
17
|
+
export const MAX_DOCS = 4;
|
|
18
|
+
/** Keep in sync with the server's MAX_ATTACHMENT_CHARS; the server is the gate. */
|
|
19
|
+
export const MAX_DOC_CHARS = 24_000;
|
|
20
|
+
|
|
21
|
+
export type DocKind = "text" | "csv" | "pdf" | "docx" | "xlsx";
|
|
22
|
+
|
|
23
|
+
const EXT_KIND: Record<string, DocKind> = {
|
|
24
|
+
md: "text", markdown: "text", txt: "text", log: "text", json: "text",
|
|
25
|
+
yaml: "text", yml: "text", toml: "text", ini: "text",
|
|
26
|
+
csv: "csv", tsv: "csv",
|
|
27
|
+
pdf: "pdf",
|
|
28
|
+
docx: "docx",
|
|
29
|
+
xlsx: "xlsx", xlsm: "xlsx",
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
export function docKind(fileName: string): DocKind | undefined {
|
|
33
|
+
const dot = fileName.lastIndexOf(".");
|
|
34
|
+
if (dot < 0) return undefined;
|
|
35
|
+
return EXT_KIND[fileName.slice(dot + 1).toLowerCase()];
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** An attachment plus what the user needs to know about its conversion. */
|
|
39
|
+
export interface DocEntry extends ChatAttachment {
|
|
40
|
+
truncated: boolean;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Hard cap with a human-readable marker. The result stays under `cap` chars
|
|
45
|
+
* (marker included) so a client-capped document never trips the server check.
|
|
46
|
+
*/
|
|
47
|
+
export function truncateDoc(text: string, cap = MAX_DOC_CHARS): { text: string; truncated: boolean } {
|
|
48
|
+
const clean = text.trim();
|
|
49
|
+
if (clean.length <= cap) return { text: clean, truncated: false };
|
|
50
|
+
const keep = cap - 100;
|
|
51
|
+
return {
|
|
52
|
+
text: `${clean.slice(0, keep)}\n\n…[已截断:原文 ${clean.length} 字符,只上传了前 ${keep} 字符]`,
|
|
53
|
+
truncated: true,
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* The file-part carrier for the local runtime. The adapter re-reads these
|
|
59
|
+
* back into ChatRequest.attachments by mimeType, so "text/markdown" here
|
|
60
|
+
* means "converted document text" (data is the Markdown itself, not base64).
|
|
61
|
+
*/
|
|
62
|
+
export function docPart(doc: ChatAttachment): { type: "file"; filename: string; mimeType: string; data: string } {
|
|
63
|
+
return { type: "file", filename: doc.name, mimeType: "text/markdown", data: doc.text };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Rows -> Markdown table; every cell escaped so no pipe can forge a column. */
|
|
67
|
+
export function tableFromRows(rows: string[][]): string {
|
|
68
|
+
if (rows.length === 0) return "";
|
|
69
|
+
const esc = (v: string) => v.trim().replace(/\|/g, "\\|").replace(/\r?\n/g, " ");
|
|
70
|
+
const width = rows.reduce((m, r) => Math.max(m, r.length), 0);
|
|
71
|
+
const grid = rows.map((r) => Array.from({ length: width }, (_, i) => esc(r[i] ?? "")));
|
|
72
|
+
const line = (cells: string[]) => `| ${cells.join(" | ")} |`;
|
|
73
|
+
return [line(grid[0]!), line(grid[0]!.map(() => "---")), ...grid.slice(1).map(line)].join("\n");
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Minimal quote-aware delimited-text parser with first-line delimiter sniffing. */
|
|
77
|
+
function parseDelimited(text: string): string[][] {
|
|
78
|
+
const src = text.replace(/\r\n?/g, "\n").replace(/\n$/, "");
|
|
79
|
+
const nl = src.indexOf("\n");
|
|
80
|
+
const firstLine = nl < 0 ? src : src.slice(0, nl);
|
|
81
|
+
const count = (d: string) => firstLine.split(d).length;
|
|
82
|
+
const delim = [",", "\t", ";"].reduce((a, b) => (count(b) > count(a) ? b : a), ",");
|
|
83
|
+
const rows: string[][] = [];
|
|
84
|
+
let row: string[] = [];
|
|
85
|
+
let field = "";
|
|
86
|
+
let quoted = false;
|
|
87
|
+
for (let i = 0; i < src.length; i++) {
|
|
88
|
+
const c = src[i]!;
|
|
89
|
+
if (quoted) {
|
|
90
|
+
if (c === '"') {
|
|
91
|
+
if (src[i + 1] === '"') { field += '"'; i++; } else quoted = false;
|
|
92
|
+
} else field += c;
|
|
93
|
+
} else if (c === '"') quoted = true;
|
|
94
|
+
else if (c === delim) { row.push(field); field = ""; }
|
|
95
|
+
else if (c === "\n") { row.push(field); rows.push(row); row = []; field = ""; }
|
|
96
|
+
else field += c;
|
|
97
|
+
}
|
|
98
|
+
row.push(field);
|
|
99
|
+
rows.push(row);
|
|
100
|
+
return rows.filter((r) => r.some((f) => f.trim() !== ""));
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function csvToMarkdown(text: string): string {
|
|
104
|
+
return tableFromRows(parseDelimited(text));
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
let pdfWorkerConfigured = false;
|
|
108
|
+
|
|
109
|
+
async function pdfToMarkdown(data: ArrayBuffer): Promise<string> {
|
|
110
|
+
const pdfjs = await import("pdfjs-dist");
|
|
111
|
+
if (!pdfWorkerConfigured) {
|
|
112
|
+
pdfWorkerConfigured = true;
|
|
113
|
+
const { default: workerUrl } = await import("pdfjs-dist/build/pdf.worker.min.mjs?url");
|
|
114
|
+
pdfjs.GlobalWorkerOptions.workerSrc = workerUrl;
|
|
115
|
+
}
|
|
116
|
+
const doc = await pdfjs.getDocument({ data: new Uint8Array(data) }).promise;
|
|
117
|
+
const pages: string[] = [];
|
|
118
|
+
for (let i = 1; i <= doc.numPages; i++) {
|
|
119
|
+
const content = await (await doc.getPage(i)).getTextContent();
|
|
120
|
+
let text = "";
|
|
121
|
+
let lastY: number | undefined;
|
|
122
|
+
for (const item of content.items) {
|
|
123
|
+
if (!("str" in item)) continue;
|
|
124
|
+
const y = item.transform[5];
|
|
125
|
+
if (lastY !== undefined && Math.abs(y - lastY) > 4) text += "\n";
|
|
126
|
+
text += item.str;
|
|
127
|
+
lastY = y;
|
|
128
|
+
}
|
|
129
|
+
pages.push(doc.numPages > 1 ? `【第 ${i} 页】\n${text.trim()}` : text.trim());
|
|
130
|
+
}
|
|
131
|
+
return pages.join("\n\n");
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
async function docxToMarkdown(data: ArrayBuffer): Promise<string> {
|
|
135
|
+
const mammoth = (await import("mammoth")).default;
|
|
136
|
+
// The shipped lib/index.d.ts has not caught up with the runtime:
|
|
137
|
+
// convertToMarkdown exists (lib/index.js:14) but is not declared on the
|
|
138
|
+
// interface. Local cast instead of patching global types.
|
|
139
|
+
const convert = (mammoth as unknown as {
|
|
140
|
+
convertToMarkdown: (input: { arrayBuffer: ArrayBuffer }) => Promise<{ value: string }>;
|
|
141
|
+
}).convertToMarkdown;
|
|
142
|
+
const result = await convert({ arrayBuffer: data });
|
|
143
|
+
return result.value;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
async function xlsxToMarkdown(data: ArrayBuffer): Promise<string> {
|
|
147
|
+
const { Workbook } = await import("exceljs");
|
|
148
|
+
const wb = new Workbook();
|
|
149
|
+
await wb.xlsx.load(data);
|
|
150
|
+
const parts: string[] = [];
|
|
151
|
+
for (const ws of wb.worksheets) {
|
|
152
|
+
const rows: string[][] = [];
|
|
153
|
+
ws.eachRow({ includeEmpty: false }, (row) => {
|
|
154
|
+
const cells: string[] = [];
|
|
155
|
+
row.eachCell({ includeEmpty: true }, (cell) => cells.push(cell.text));
|
|
156
|
+
rows.push(cells);
|
|
157
|
+
});
|
|
158
|
+
if (rows.length > 0) parts.push(`【工作表 ${ws.name}】\n${tableFromRows(rows)}`);
|
|
159
|
+
}
|
|
160
|
+
return parts.join("\n\n");
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** Convert one browser File to a sendable attachment. Throws with a user-readable message. */
|
|
164
|
+
export async function fileToDoc(file: File): Promise<DocEntry> {
|
|
165
|
+
const kind = docKind(file.name);
|
|
166
|
+
if (!kind) throw new Error(`暂不支持的文件类型:${file.name}`);
|
|
167
|
+
let raw: string;
|
|
168
|
+
switch (kind) {
|
|
169
|
+
case "text": raw = await file.text(); break;
|
|
170
|
+
case "csv": raw = csvToMarkdown(await file.text()); break;
|
|
171
|
+
case "pdf": raw = await pdfToMarkdown(await file.arrayBuffer()); break;
|
|
172
|
+
case "docx": raw = await docxToMarkdown(await file.arrayBuffer()); break;
|
|
173
|
+
case "xlsx": raw = await xlsxToMarkdown(await file.arrayBuffer()); break;
|
|
174
|
+
}
|
|
175
|
+
// Empty extraction (scanned pdf, empty file) must not silently reach the model.
|
|
176
|
+
if (raw.trim() === "") throw new Error(`未检出可提取文本(扫描件或空文件?):${file.name}`);
|
|
177
|
+
const t = truncateDoc(raw);
|
|
178
|
+
return { name: file.name, text: t.text, truncated: t.truncated };
|
|
179
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@njuptlzf/agent-chat-web` 的公共入口。
|
|
3
|
+
*
|
|
4
|
+
* 平台前端壳对外只有《[PUBLIC_API](../../../../docs/design/PUBLIC_API.md)》
|
|
5
|
+
* 登记的 13 项:产品 web 通过 `@njuptlzf/agent-chat-web` 取 `AppDef` / `HostCtx` /
|
|
6
|
+
* `AgentApp` 与几个 HTTP 小工具,不再走 `apps/web/src/agent-chat/*` 深路径。
|
|
7
|
+
* 壳内部(卡片槽、AppShell、面板)都是实现,随时可改。
|
|
8
|
+
*/
|
|
9
|
+
export type { AppDef, HostCtx } from "./app.tsx";
|
|
10
|
+
export { apiHeaders, auth } from "./auth.ts";
|
|
11
|
+
export { sendToChat } from "./dock.ts";
|
|
12
|
+
export { AgentApp } from "./mount.tsx";
|
|
13
|
+
export { default as PersonasPage } from "./PersonasPage.tsx";
|
|
14
|
+
export { isEnabled } from "./qual.ts";
|
|
15
|
+
export { deleteJson, fetchJson, postJson } from "./sse.ts";
|
|
16
|
+
export { fmtDate, fmtTime, relativeTime } from "./ui/timefmt.ts";
|
|
17
|
+
export { applyThemeMode, loadThemeMode, saveThemeMode, type ThemeMode } from "./theme.ts";
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 组合根的通用实现(接缝的最后一层,2026-11-03)。
|
|
3
|
+
*
|
|
4
|
+
* 以前这份接线长在 `apps/web/src/App.tsx` 里(113 行),产品事实与机械传参
|
|
5
|
+
* 混在一处——第二个产品只能**把整份文件复制走再改 import**。这里把机械部分
|
|
6
|
+
* 收进 core,产品只保留自己的事实(导航注册表、文案兜底、侧栏入口、宿主级组件)。
|
|
7
|
+
*
|
|
8
|
+
* 插槽契约(照抄时最容易踩的一条):
|
|
9
|
+
* `footer` / `extras` 是**普通闭包**,不是组件——它们在 AgentApp 的 render
|
|
10
|
+
* 期间被调用,所以里面**不要调用 hook**(要 state 就在产品自己的组件里
|
|
11
|
+
* 用 useState,闭包里只捕获 setter)。
|
|
12
|
+
*
|
|
13
|
+
* 依赖方向恒为 产品 → agent-chat:本文件不 import 任何产品代码。
|
|
14
|
+
*/
|
|
15
|
+
import type { ReactNode } from "react";
|
|
16
|
+
import type { BrandingResponse } from "@njuptlzf/agent-chat-protocol";
|
|
17
|
+
import AgentChatApp from "./AgentChatApp.tsx";
|
|
18
|
+
import Dock from "./Dock.tsx";
|
|
19
|
+
import { AppShell, themeVarsOf, useAppHost, type AppDef } from "./app.tsx";
|
|
20
|
+
|
|
21
|
+
/** 宿主状态(`useAppHost` 的返回值):插槽从这里取品牌、身份、路由、人格。 */
|
|
22
|
+
export type AppHost = ReturnType<typeof useAppHost>;
|
|
23
|
+
|
|
24
|
+
/** 产品给的界面文案:全由 branding(manifest 声明)与当前人格决定。 */
|
|
25
|
+
export interface AppTexts {
|
|
26
|
+
/** 坞标题(换人格时要换,否则点了「声明人格」还写着「默认助手」)。 */
|
|
27
|
+
title: string;
|
|
28
|
+
/** 助手在界面上的叫法(「正在回答」这类提示语用)。 */
|
|
29
|
+
assistantLabel: string;
|
|
30
|
+
/** 提示条:这个助手是谁、不做什么。 */
|
|
31
|
+
policyNote?: string;
|
|
32
|
+
welcome?: string;
|
|
33
|
+
suggestions?: string[];
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface AgentAppProps {
|
|
37
|
+
/** 导航注册表(产品事实)。 */
|
|
38
|
+
def: AppDef;
|
|
39
|
+
/** 文案兜底:core 不认得任何人格名,也不写死任何一句话。 */
|
|
40
|
+
texts(branding: BrandingResponse, persona: string): AppTexts;
|
|
41
|
+
/** 侧栏底部的产品入口(声明人格、反馈问题…)。闭包,不能调 hook。 */
|
|
42
|
+
footer?(host: AppHost): ReactNode;
|
|
43
|
+
/** 宿主级组件(每日总结、反馈抽屉…)。闭包,不能调 hook。 */
|
|
44
|
+
extras?(host: AppHost): ReactNode;
|
|
45
|
+
/** 加载失败时给产品的启动提示(core 不知道启动命令长什么样)。 */
|
|
46
|
+
loadErrorHint?: ReactNode;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* 产品组合根:branding/whoami → 宿主状态 → 侧栏 + 坞 + 页面。
|
|
51
|
+
*
|
|
52
|
+
* 与改造前 `App.tsx` 的行为逐项对齐(full/compact 的判据、key 重挂、插槽位置),
|
|
53
|
+
* 差别只有一处:人格不再由 core 判断"谁是声明人格"——`host.persona` 原样传给
|
|
54
|
+
* `AgentChatApp`("" 收敛成 undefined = 产品默认助手),文案由 `texts` 决定。
|
|
55
|
+
*/
|
|
56
|
+
export function AgentApp({ def, texts, footer, extras, loadErrorHint }: AgentAppProps) {
|
|
57
|
+
const host = useAppHost(def);
|
|
58
|
+
if (host.loadError) {
|
|
59
|
+
return (
|
|
60
|
+
<div className="center">
|
|
61
|
+
<p>无法连接服务:{host.loadError}</p>
|
|
62
|
+
{loadErrorHint}
|
|
63
|
+
</div>
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
if (!host.ready) return <div className="center">加载中…</div>;
|
|
67
|
+
|
|
68
|
+
const { branding, who, qual, route, shown, onQuals, persona, go, ctx } = host;
|
|
69
|
+
// 坞是否撑满内容区。同一个判据喂给 Dock.full 与 AgentChatApp.compact
|
|
70
|
+
// (2026-11-03:以前 compact 单独判「路由不是聊天页」,漏了选项页这种
|
|
71
|
+
// 「路由还是 chatRoute 但坞不是全屏」的状态,会话侧栏把输入框挤成 56px)。
|
|
72
|
+
const dockFull = !onQuals && route === def.chatRoute;
|
|
73
|
+
const t = texts(branding, persona);
|
|
74
|
+
|
|
75
|
+
return (
|
|
76
|
+
<div className="shell" style={themeVarsOf(branding)}>
|
|
77
|
+
<AppShell
|
|
78
|
+
branding={branding}
|
|
79
|
+
qual={qual}
|
|
80
|
+
route={shown}
|
|
81
|
+
nav={def.navItems(ctx!)}
|
|
82
|
+
who={who}
|
|
83
|
+
// 侧栏导航回聊天路由 = 回**默认人格**(2026-11-04):从声明人格切「默认助手」时只改
|
|
84
|
+
// 路由的话,人格还挂在声明人格上,标题/预备问题都不换。人格化入口(人格化按钮)
|
|
85
|
+
// 走 host.go 自己先 setPersona,不经过这里,所以不会被这条冲掉。
|
|
86
|
+
onRoute={(r) => {
|
|
87
|
+
if (r === def.chatRoute && host.persona) host.setPersona("");
|
|
88
|
+
go(r);
|
|
89
|
+
}}
|
|
90
|
+
onQuals={() => go("quals")}
|
|
91
|
+
switchTitle={def.labels?.switchTitle}
|
|
92
|
+
footer={footer?.(host)}
|
|
93
|
+
>
|
|
94
|
+
<Dock
|
|
95
|
+
title={t.title}
|
|
96
|
+
full={dockFull}
|
|
97
|
+
onClose={host.closeChat}
|
|
98
|
+
chat={
|
|
99
|
+
<AgentChatApp
|
|
100
|
+
// key 让切人格时重挂:会话绑死人格,同一个实例换 persona 只会撞 persona_mismatch。
|
|
101
|
+
key={persona}
|
|
102
|
+
branding={branding}
|
|
103
|
+
scope={qual?.id}
|
|
104
|
+
renderCard={def.cardRenderer}
|
|
105
|
+
// core 只做形状收敛("" → undefined = 产品默认助手),不认识具体名字。
|
|
106
|
+
persona={persona || undefined}
|
|
107
|
+
title={t.title}
|
|
108
|
+
assistantLabel={t.assistantLabel}
|
|
109
|
+
policyNote={t.policyNote}
|
|
110
|
+
welcome={t.welcome}
|
|
111
|
+
suggestions={t.suggestions}
|
|
112
|
+
compact={!dockFull}
|
|
113
|
+
/>
|
|
114
|
+
}
|
|
115
|
+
>
|
|
116
|
+
{def.page(ctx!)}
|
|
117
|
+
</Dock>
|
|
118
|
+
{/* 宿主级、只在 boot 拉一次的东西(每日总结弹窗等):切路由不该让它重挂。 */}
|
|
119
|
+
{extras?.(host)}
|
|
120
|
+
</AppShell>
|
|
121
|
+
</div>
|
|
122
|
+
);
|
|
123
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
|
|
2
|
+
/**
|
|
3
|
+
* 当前选项的本地偏好(从 <product>/qual.ts 拆入 core):
|
|
4
|
+
* 产品可选项目录是通用协议形状,"记住上次选了哪一项"是壳机制不是产品事实。
|
|
5
|
+
* 存储键保持 `ac.qual` 不变——老用户的偏好直接沿用。
|
|
6
|
+
*
|
|
7
|
+
* 产品侧只留具体选项的语义与路由映射。
|
|
8
|
+
*/
|
|
9
|
+
const KEY = "ac.qual";
|
|
10
|
+
|
|
11
|
+
function loadQual(): string | null {
|
|
12
|
+
try {
|
|
13
|
+
return localStorage.getItem(KEY);
|
|
14
|
+
} catch {
|
|
15
|
+
return null;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function saveQual(id: string): void {
|
|
20
|
+
try {
|
|
21
|
+
localStorage.setItem(KEY, id);
|
|
22
|
+
} catch {
|
|
23
|
+
// 隐私模式下 localStorage 可能抛错;选项只是偏好,丢了回选择页即可。
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** 可用 = 内容已就绪(`enabled` 不为 false)。 */
|
|
28
|
+
export function isEnabled(q: { enabled?: boolean }): boolean {
|
|
29
|
+
return q.enabled !== false;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** 当前选项:本地记忆优先,否则回落第一个可用的选项。 */
|
|
33
|
+
export function currentQual<T extends { id: string; enabled?: boolean }>(quals: T[] | undefined): T | null {
|
|
34
|
+
if (!quals || quals.length === 0) return null;
|
|
35
|
+
const saved = loadQual();
|
|
36
|
+
const hit = saved ? quals.find((q) => q.id === saved && isEnabled(q)) : undefined;
|
|
37
|
+
return hit ?? quals.find(isEnabled) ?? null;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* 深链里的选项(`#/<业务页>?qual=<轨道>&id=…`)。
|
|
42
|
+
*
|
|
43
|
+
* 为什么需要:页面记住的选项(ac.qual)与会话的 `AC_SCOPE` 是两件事——助手在
|
|
44
|
+
* system-integration 的会话里给了一张题卡,点进去时页面可能还停在 architect,
|
|
45
|
+
* 结果 404。深链把选项带上,壳静默切过去。
|
|
46
|
+
*
|
|
47
|
+
* 只认 `?` 之后的 query 段:路径里也可能出现 qual 字样(`#/quals`),用 includes
|
|
48
|
+
* 判断会误伤。空值当没写。
|
|
49
|
+
*/
|
|
50
|
+
export function qualFromHash(hash: string): string | null {
|
|
51
|
+
const q = hash.indexOf("?");
|
|
52
|
+
if (q < 0) return null;
|
|
53
|
+
const id = new URLSearchParams(hash.slice(q + 1)).get("qual");
|
|
54
|
+
return id ? id : null;
|
|
55
|
+
}
|
|
@@ -0,0 +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
|
+
}
|
|
@@ -0,0 +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
|
+
}
|
|
@@ -0,0 +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
|
+
}
|
|
@@ -0,0 +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
|
+
}
|
|
@@ -0,0 +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
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Waiting-queue bar (custom component, UI-R3).
|
|
3
|
+
*
|
|
4
|
+
* Why not the official queue: `ComposerPrimitive.Queue` + `unstable_enableMessageQueue`
|
|
5
|
+
* cover enqueue/remove, but the local runtime wires the queue driver WITHOUT a
|
|
6
|
+
* `cancel` callback, so a steer-lane move degrades to "process next" instead of
|
|
7
|
+
* interrupting the running answer; and `notifyCancelled` pauses queue advance
|
|
8
|
+
* after a user-initiated stop, which kills our "stop then flush next" behavior.
|
|
9
|
+
* Forensics: @assistant-ui/core local-thread-runtime-core.js:356-366,
|
|
10
|
+
* message-queue.d.ts:13-30. Kept as a reusable custom component per the
|
|
11
|
+
* official-first rule (it does not match).
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
/** A content part a queued send can carry: the composer only produces these three. */
|
|
15
|
+
export type QueuedPart =
|
|
16
|
+
| { type: "text"; text: string }
|
|
17
|
+
| { type: "image"; image: string }
|
|
18
|
+
| { type: "file"; filename?: string; mimeType: string; data: string };
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* One queued send (E2, documents since B4-A). It holds content parts rather
|
|
22
|
+
* than a string because a message waiting behind the current answer may carry
|
|
23
|
+
* images and converted documents too — the queue is only a local staging
|
|
24
|
+
* area, and whatever sits here is appended to the thread verbatim once the run
|
|
25
|
+
* ends.
|
|
26
|
+
*/
|
|
27
|
+
export type QueuedMessage = readonly QueuedPart[];
|
|
28
|
+
|
|
29
|
+
/** What the bar shows for one queued message (the payload itself is a parts array). */
|
|
30
|
+
export function queuedPreview(message: QueuedMessage): { text: string; images: number; docs: number } {
|
|
31
|
+
const text = message
|
|
32
|
+
.filter((p): p is Extract<QueuedPart, { type: "text" }> => p.type === "text")
|
|
33
|
+
.map((p) => p.text)
|
|
34
|
+
.join("");
|
|
35
|
+
const images = message.filter((p) => p.type === "image").length;
|
|
36
|
+
const docs = message.filter((p) => p.type === "file").length;
|
|
37
|
+
return { text: text.trim(), images, docs };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function QueueBar({
|
|
41
|
+
queue,
|
|
42
|
+
onSteer,
|
|
43
|
+
onDrop,
|
|
44
|
+
}: {
|
|
45
|
+
queue: readonly QueuedMessage[];
|
|
46
|
+
onSteer: (i: number) => void;
|
|
47
|
+
onDrop: (i: number) => void;
|
|
48
|
+
}) {
|
|
49
|
+
return (
|
|
50
|
+
<div className="queuebar">
|
|
51
|
+
<span className="q-label">等待 {queue.length} 条</span>
|
|
52
|
+
{queue.map((q, i) => {
|
|
53
|
+
const { text, images, docs } = queuedPreview(q);
|
|
54
|
+
return (
|
|
55
|
+
<span className="q-item" key={i} title={text || `${images} 图片 / ${docs} 文档`}>
|
|
56
|
+
{images > 0 && <span className="q-img" aria-label={`${images} 张图片`}>🖼{images > 1 ? `×${images}` : ""}</span>}
|
|
57
|
+
{docs > 0 && <span className="q-img" aria-label={`${docs} 个文档`}>📄{docs > 1 ? `×${docs}` : ""}</span>}
|
|
58
|
+
<span className="q-text">{text}</span>
|
|
59
|
+
<button onClick={() => onSteer(i)} title="中止当前回答,优先发送这条">
|
|
60
|
+
插队
|
|
61
|
+
</button>
|
|
62
|
+
<button onClick={() => onDrop(i)} title="从队列移除">
|
|
63
|
+
移除
|
|
64
|
+
</button>
|
|
65
|
+
</span>
|
|
66
|
+
);
|
|
67
|
+
})}
|
|
68
|
+
</div>
|
|
69
|
+
);
|
|
70
|
+
}
|