@njuptlzf/agent-chat-web 0.2.0 → 0.4.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 (61) hide show
  1. package/dist/AgentChat.d.ts +7 -1
  2. package/dist/AgentChat.js +35 -5
  3. package/dist/AgentChatApp.d.ts +4 -1
  4. package/dist/AgentChatApp.js +2 -2
  5. package/dist/PersonasPage.js +8 -0
  6. package/dist/adapter.d.ts +9 -0
  7. package/dist/adapter.js +15 -0
  8. package/dist/mount.d.ts +7 -1
  9. package/dist/mount.js +2 -2
  10. package/dist/styles.css +1505 -1478
  11. package/dist/suggestions.d.ts +41 -0
  12. package/dist/suggestions.js +98 -0
  13. package/dist/ui/FollowUpSuggestions.d.ts +9 -0
  14. package/dist/ui/FollowUpSuggestions.js +13 -0
  15. package/dist/ui/Icon.d.ts +8 -0
  16. package/dist/ui/Icon.js +26 -0
  17. package/dist/ui/MemberCards.d.ts +15 -0
  18. package/dist/ui/MemberCards.js +13 -0
  19. package/dist/ui/icons.d.ts +19 -0
  20. package/dist/ui/icons.js +25 -0
  21. package/dist/ui/members.d.ts +42 -0
  22. package/dist/ui/members.js +53 -0
  23. package/dist/ui/slots.d.ts +29 -0
  24. package/dist/ui/slots.js +14 -0
  25. package/package.json +71 -72
  26. package/src/App.tsx +13 -13
  27. package/src/agent-chat/AgentChat.tsx +741 -692
  28. package/src/agent-chat/AgentChatApp.tsx +211 -206
  29. package/src/agent-chat/DockPanel.tsx +73 -73
  30. package/src/agent-chat/PersonasPage.tsx +705 -678
  31. package/src/agent-chat/adapter.ts +293 -272
  32. package/src/agent-chat/app-def-check.ts +215 -215
  33. package/src/agent-chat/app.tsx +327 -327
  34. package/src/agent-chat/auth.ts +83 -83
  35. package/src/agent-chat/dock.ts +161 -161
  36. package/src/agent-chat/docs.ts +179 -179
  37. package/src/agent-chat/index.ts +17 -17
  38. package/src/agent-chat/mount.tsx +130 -123
  39. package/src/agent-chat/qual.ts +55 -55
  40. package/src/agent-chat/sse.ts +104 -104
  41. package/src/agent-chat/suggestions.ts +127 -0
  42. package/src/agent-chat/theme.ts +23 -23
  43. package/src/agent-chat/ui/CodeCopyHeader.tsx +29 -29
  44. package/src/agent-chat/ui/ConfirmCard.tsx +32 -32
  45. package/src/agent-chat/ui/FollowUpSuggestions.tsx +28 -0
  46. package/src/agent-chat/ui/Icon.tsx +53 -0
  47. package/src/agent-chat/ui/Lightbox.tsx +32 -32
  48. package/src/agent-chat/ui/MemberCards.tsx +46 -0
  49. package/src/agent-chat/ui/QueueBar.tsx +70 -70
  50. package/src/agent-chat/ui/Splitter.tsx +81 -81
  51. package/src/agent-chat/ui/ThemeToggle.tsx +25 -25
  52. package/src/agent-chat/ui/TierPicker.tsx +112 -112
  53. package/src/agent-chat/ui/UIPromptCard.tsx +68 -68
  54. package/src/agent-chat/ui/icons.ts +31 -0
  55. package/src/agent-chat/ui/members.ts +106 -0
  56. package/src/agent-chat/ui/slots.tsx +41 -0
  57. package/src/agent-chat/ui/timefmt.ts +110 -110
  58. package/src/agent-chat/ui/useNarrow.ts +20 -20
  59. package/src/fake-product/entry.tsx +63 -54
  60. package/src/main.tsx +8 -8
  61. package/src/styles.css +1505 -1478
@@ -1,179 +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
- }
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
+ }
@@ -1,17 +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";
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";