@xiaofanzhao/dsh-plugin-knowledge-base 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.
package/client.js ADDED
@@ -0,0 +1,1934 @@
1
+ // ============================================================================
2
+ // dsh-plugin-knowledge-base — Client 半部
3
+ //
4
+ // 三个挂载点:
5
+ // sidebar.panellist 左栏图标(id 必须与 main 的 key 一致)
6
+ // main[key] 知识库主页面:目录树 + 阅读器 + 检索
7
+ // settings.section 「设置 → 知识库」:存放目录、索引统计、重建索引
8
+ //
9
+ // 浏览器端只认 window.__ModuleLoader__.load({ id, factory }),所以本文件里
10
+ // 不能出现 import / export。React 从模块表里拿:require('react')。
11
+ // ============================================================================
12
+ window.__ModuleLoader__.load({
13
+ id: 'dsh-plugin-knowledge-base',
14
+ factory(require) {
15
+ const React = require('react');
16
+ const h = React.createElement;
17
+
18
+ const API = '/api/kb/v1';
19
+ const PANEL_ID = 'dsh-knowledge-base';
20
+ const TEXT_PAGE = 24000;
21
+ const OFFICE_EXT = ['doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx'];
22
+ const IMAGE_EXT = ['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'svg'];
23
+ // Chromium PDF 阅读器的参数:适应宽度 + 收起缩略图栏
24
+ const PDF_FRAGMENT = '#view=FitH&navpanes=0';
25
+
26
+ // ── 小工具 ──────────────────────────────────────────────────────────
27
+ const cx = (...names) => names.filter(Boolean).join(' ');
28
+
29
+ function bytes(value) {
30
+ const number = Number(value) || 0;
31
+ if (number < 1024) return `${number} B`;
32
+ if (number < 1048576) return `${(number / 1024).toFixed(1)} KB`;
33
+ return `${(number / 1048576).toFixed(1)} MB`;
34
+ }
35
+
36
+ function when(ms) {
37
+ const value = Number(ms) || 0;
38
+ if (!value) return '';
39
+ const delta = Date.now() - value;
40
+ if (delta < 60000) return '刚刚';
41
+ if (delta < 3600000) return `${Math.floor(delta / 60000)} 分钟前`;
42
+ if (delta < 86400000) return `${Math.floor(delta / 3600000)} 小时前`;
43
+ return new Date(value).toLocaleDateString();
44
+ }
45
+
46
+ function iconPath(name) {
47
+ return {
48
+ book: ['M4 3.5h6.5A2.5 2.5 0 0 1 13 6v8.5H6.5A2.5 2.5 0 0 0 4 17V3.5Z', 'M4 14.5A2.5 2.5 0 0 1 6.5 12H13'],
49
+ folder: ['M2 5.5h4l1.4 1.8H14v7.2H2V5.5Z'],
50
+ folderOpen: ['M2 5.5h4l1.4 1.8H14v7.2H2V5.5Z', 'M4.4 8.6h10.2'],
51
+ doc: ['M4.5 2.5h5L12 5v9H4.5V2.5Z', 'M9.5 2.5V5H12'],
52
+ search: ['M7.2 11.4a4.2 4.2 0 1 0 0-8.4 4.2 4.2 0 0 0 0 8.4Z', 'M10.4 10.4 14 14'],
53
+ plus: ['M8 3.5v9M3.5 8h9'],
54
+ upload: ['M8 11.5V3.5', 'M5 6.2 8 3.2l3 3', 'M3 11.5v2h10v-2'],
55
+ spark: ['M8 2.5v2.6M8 10.9v2.6M2.5 8h2.6M10.9 8h2.6', 'M4.7 4.7l1.8 1.8M9.5 9.5l1.8 1.8M11.3 4.7 9.5 6.5M6.5 9.5l-1.8 1.8'],
56
+ refresh: ['M13 8a5 5 0 1 1-1.5-3.6', 'M13.2 2.6v3h-3'],
57
+ settings: ['M2.5 5.5h11', 'M2.5 10.5h11', 'M6 3.5v4', 'M10 8.5v4'],
58
+ trash: ['M3.5 5h9', 'M6.5 5V3.5h3V5', 'M5 5l.6 8h4.8L11 5'],
59
+ close: ['M3.5 3.5l9 9M12.5 3.5l-9 9'],
60
+ open: ['M9.5 3.5h3v3', 'M12.5 3.5 6 10', 'M11 10.5v2.5H3.5V5.5H6'],
61
+ chevron: ['M6 4.5 9.8 8 6 11.5'],
62
+ check: ['M3.5 8.4l3 3 6-6.4'],
63
+ warn: ['M8 2.6 14 13H2L8 2.6Z', 'M8 6.6v3M8 11.2v.5'],
64
+ }[name] || [];
65
+ }
66
+
67
+ function Icon({ name, size = 16, className }) {
68
+ return h('svg', {
69
+ width: size, height: size, viewBox: '0 0 16 16', fill: 'none',
70
+ stroke: 'currentColor', strokeWidth: 1.4, strokeLinecap: 'round', strokeLinejoin: 'round',
71
+ className, 'aria-hidden': 'true', focusable: 'false',
72
+ }, iconPath(name).map((d, index) => h('path', { key: index, d })));
73
+ }
74
+
75
+ // ── 请求 ────────────────────────────────────────────────────────────
76
+ async function api(path, options = {}) {
77
+ const response = await fetch(API + path, {
78
+ ...options,
79
+ headers: { 'x-kb-client': '1', ...(options.headers || {}) },
80
+ });
81
+ const type = response.headers.get('content-type') || '';
82
+ if (!type.includes('application/json')) {
83
+ if (!response.ok) throw new Error(`请求失败(HTTP ${response.status})`);
84
+ return null;
85
+ }
86
+ const body = await response.json();
87
+ if (!response.ok || body?.ok === false) throw new Error(body?.error || `请求失败(HTTP ${response.status})`);
88
+ return body;
89
+ }
90
+
91
+ // ── 状态 ────────────────────────────────────────────────────────────
92
+ const state = {
93
+ loaded: false,
94
+ loading: true,
95
+ error: '',
96
+ notice: '',
97
+ busy: '',
98
+ kbs: [],
99
+ kbId: '',
100
+ nodes: [],
101
+ stats: null,
102
+ progress: null,
103
+ caps: null,
104
+ root: '',
105
+ token: '',
106
+ view: 'doc',
107
+ expanded: {},
108
+ selectedId: '',
109
+ doc: null,
110
+ docText: '',
111
+ docOffset: 0,
112
+ docNext: 0,
113
+ docTotal: 0,
114
+ docHasMore: false,
115
+ docLoading: false,
116
+ dialog: null,
117
+ query: '',
118
+ search: { loading: false, hits: [], mode: 'keyword', ran: false, error: '' },
119
+ uploading: 0,
120
+ previewMode: 'visual',
121
+ previewLoaded: false,
122
+ previewError: '',
123
+ previewInfo: null,
124
+ currentPage: 1,
125
+ pageMode: 'scroll',
126
+ pageInput: '1',
127
+ thumbsOpen: true,
128
+ bigView: false,
129
+ bigMode: 'single',
130
+ sideOpen: true,
131
+ showSettings: false,
132
+ dashOpen: false,
133
+ dashData: null,
134
+ dashError: '',
135
+ dashLoading: false,
136
+ menu: null,
137
+ importTarget: null,
138
+ };
139
+
140
+ const listeners = new Set();
141
+ function subscribe(listener) {
142
+ listeners.add(listener);
143
+ return () => listeners.delete(listener);
144
+ }
145
+ function patch(next) {
146
+ Object.assign(state, next);
147
+ for (const listener of [...listeners]) listener();
148
+ }
149
+ function useStore() {
150
+ const [, force] = React.useState(0);
151
+ React.useEffect(() => subscribe(() => force((value) => value + 1)), []);
152
+ return state;
153
+ }
154
+
155
+ let pollTimer = null;
156
+ let pollCount = 0;
157
+ function schedulePoll() {
158
+ if (pollTimer) return;
159
+ pollTimer = setTimeout(async () => {
160
+ pollTimer = null;
161
+ const pending = state.nodes.some((node) => node.kind === 'doc' && (node.status === 'pending' || node.status === 'parsing'));
162
+ if (!pending) { pollCount = 0; return; }
163
+ if (pollCount > 40) {
164
+ pollCount = 0;
165
+ patch({ notice: '有文件解析时间较长,可以点文档上的「重新索引」重试。' });
166
+ return;
167
+ }
168
+ pollCount += 1;
169
+ try { await loadState(state.kbId, true); } catch { /* ignore */ }
170
+ if (state.selectedId && state.doc?.id === state.selectedId) await loadDoc(state.selectedId, { quiet: true });
171
+ schedulePoll();
172
+ }, 2000);
173
+ }
174
+
175
+ async function loadState(kbId = '', quiet = false) {
176
+ if (!quiet) patch({ loading: true, error: '' });
177
+ try {
178
+ const data = await api(`/state${kbId ? `?kb=${encodeURIComponent(kbId)}` : ''}`);
179
+ const expanded = { ...state.expanded };
180
+ for (const node of data.nodes) if (node.kind === 'folder' && expanded[node.id] === undefined) expanded[node.id] = true;
181
+ patch({
182
+ loaded: true, loading: false, error: '',
183
+ kbs: data.kbs, kbId: data.kbId, nodes: data.nodes,
184
+ stats: data.stats, progress: data.progress || null, caps: data.capabilities, root: data.root, token: data.token || '',
185
+ expanded,
186
+ });
187
+ if (state.nodes.some((node) => node.status === 'pending' || node.status === 'parsing')) schedulePoll();
188
+ return data;
189
+ } catch (error) {
190
+ patch({ loading: false, error: error.message || '加载失败' });
191
+ return null;
192
+ }
193
+ }
194
+
195
+ async function loadDoc(nodeId, { offset = 0 } = {}) {
196
+ if (!nodeId) return;
197
+ patch({ docLoading: true });
198
+ try {
199
+ const data = await api(`/doc?id=${encodeURIComponent(nodeId)}&action=text&offset=${offset}&limit=${TEXT_PAGE}`);
200
+ const sameDoc = Boolean(state.doc && state.doc.id === data.node.id);
201
+ // 只有"接着上一页"才拼接:偏移必须正好落在上一页的末尾
202
+ const appending = sameDoc && offset > 0 && offset === state.docNext;
203
+ patch({
204
+ selectedId: nodeId,
205
+ view: 'doc',
206
+ showSettings: false,
207
+ dashOpen: false,
208
+ doc: data.node,
209
+ docText: appending ? `${state.docText}\n\n${data.text}` : data.text,
210
+ docNext: data.end,
211
+ docTotal: data.totalChars,
212
+ docHasMore: data.hasMore,
213
+ docLoading: false,
214
+ previewLoaded: false,
215
+ previewError: '',
216
+ previewInfo: null,
217
+ currentPage: 1,
218
+ pageInput: '1',
219
+ search: { ...state.search, ran: false },
220
+ });
221
+ } catch (error) {
222
+ patch({ docLoading: false, error: error.message || '读取失败' });
223
+ }
224
+ }
225
+
226
+ /** 行操作下拉菜单的宽度(与 .dsh-kb-menu 的 width 保持一致) */
227
+ const MENU_WIDTH = 184;
228
+
229
+ let searchSeq = 0;
230
+ async function runSearch(query) {
231
+ const text = String(query ?? '').trim();
232
+ patch({ query: text, view: text ? 'search' : 'doc' });
233
+ if (!text) {
234
+ patch({ search: { loading: false, hits: [], mode: 'keyword', ran: false, error: '' } });
235
+ return;
236
+ }
237
+ const seq = ++searchSeq;
238
+ patch({ search: { ...state.search, loading: true, ran: true, error: '' } });
239
+ try {
240
+ const data = await api(`/search?q=${encodeURIComponent(text)}&limit=30${state.kbId ? `&kb=${encodeURIComponent(state.kbId)}` : ''}`);
241
+ if (seq !== searchSeq) return;
242
+ patch({ search: { loading: false, hits: data.hits, mode: data.mode, ran: true, error: '' } });
243
+ } catch (error) {
244
+ if (seq !== searchSeq) return;
245
+ patch({ search: { loading: false, hits: [], mode: 'keyword', ran: true, error: error.message || '检索失败' } });
246
+ }
247
+ }
248
+
249
+ async function uploadFiles(fileList, parentId) {
250
+ const files = [...(fileList || [])].filter(Boolean);
251
+ if (!files.length) return;
252
+ if (!state.kbId) {
253
+ patch({ notice: '先新建一个知识库' });
254
+ return;
255
+ }
256
+ patch({ uploading: state.uploading + files.length, notice: '' });
257
+ const failed = [];
258
+ for (const file of files) {
259
+ try {
260
+ // eslint-disable-next-line no-await-in-loop
261
+ await api(`/upload?kb=${encodeURIComponent(state.kbId)}${parentId ? `&parent=${encodeURIComponent(parentId)}` : ''}`, {
262
+ method: 'POST',
263
+ headers: { 'x-kb-filename': encodeURIComponent(file.name) },
264
+ body: file,
265
+ });
266
+ } catch (error) {
267
+ failed.push(`${file.name}:${error.message}`);
268
+ }
269
+ patch({ uploading: Math.max(0, state.uploading - 1) });
270
+ }
271
+ await loadState(state.kbId, true);
272
+ schedulePoll();
273
+ patch({ notice: failed.length ? `有 ${failed.length} 个文件没传上去:${failed.join(';')}` : `已导入 ${files.length} 个文件,正在后台解析` });
274
+ }
275
+
276
+ async function nodeAction(action, payload) {
277
+ try {
278
+ const data = await api('/node', {
279
+ method: 'POST',
280
+ headers: { 'content-type': 'application/json' },
281
+ body: JSON.stringify({ action, ...payload }),
282
+ });
283
+ if (data && data.nodes) patch({ nodes: data.nodes });
284
+ const nextKb = action === 'create-kb'
285
+ ? (data?.created?.id ?? data?.kbId ?? state.kbId)
286
+ : action === 'delete-kb'
287
+ ? (data?.kbId ?? '')
288
+ : (payload.kbId || state.kbId);
289
+ await loadState(nextKb || '', true);
290
+ return data;
291
+ } catch (error) {
292
+ patch({ error: error.message || '操作失败' });
293
+ return null;
294
+ }
295
+ }
296
+
297
+ // ── 应用内对话框(Electron 渲染进程不提供 window.prompt)──────────────
298
+ function askText(title, value, onOk, okLabel) {
299
+ patch({ dialog: { kind: 'input', title, value: value || '', onOk, okLabel } });
300
+ }
301
+ function askConfirm(title, onOk, okLabel = '删除') {
302
+ patch({ dialog: { kind: 'confirm', title, onOk, okLabel, danger: true } });
303
+ }
304
+
305
+ function askMove(node) {
306
+ patch({ dialog: { kind: 'move', nodeId: node.id, title: `把「${node.name}」移动到…` } });
307
+ }
308
+
309
+ function Dialog() {
310
+ const current = useStore();
311
+ const dialog = current.dialog;
312
+ const [value, setValue] = React.useState('');
313
+ const inputRef = React.useRef(null);
314
+ React.useEffect(() => {
315
+ if (dialog?.kind === 'input') {
316
+ setValue(dialog.value || '');
317
+ const timer = setTimeout(() => inputRef.current?.focus(), 30);
318
+ return () => clearTimeout(timer);
319
+ }
320
+ return undefined;
321
+ }, [dialog]);
322
+ if (!dialog) return null;
323
+ const close = () => patch({ dialog: null });
324
+ const submit = () => {
325
+ const currentDialog = state.dialog;
326
+ if (!currentDialog) return;
327
+ if (currentDialog.kind === 'input' && !String(value).trim()) return;
328
+ patch({ dialog: null });
329
+ currentDialog.onOk?.(currentDialog.kind === 'input' ? String(value).trim() : true);
330
+ };
331
+ return h('div', {
332
+ className: 'dsh-kb-mask',
333
+ onMouseDown: (event) => { if (event.target === event.currentTarget) close(); },
334
+ },
335
+ h('div', {
336
+ className: 'dsh-kb-modal',
337
+ role: 'dialog',
338
+ 'aria-modal': 'true',
339
+ 'aria-label': dialog.title,
340
+ onKeyDown: (event) => {
341
+ if (event.key === 'Escape') close();
342
+ if (event.key === 'Enter') submit();
343
+ },
344
+ },
345
+ h('div', { className: 'dsh-kb-modalTitle' }, dialog.title),
346
+ dialog.kind === 'input'
347
+ ? h('input', {
348
+ ref: inputRef,
349
+ className: 'dsh-kb-modalInput',
350
+ value,
351
+ onChange: (event) => setValue(event.target.value),
352
+ })
353
+ : null,
354
+ dialog.kind === 'move'
355
+ ? h('div', { className: 'dsh-kb-moveList' },
356
+ (() => {
357
+ const moving = state.nodes.find((node) => node.id === dialog.nodeId);
358
+ const usable = state.nodes
359
+ .filter((node) => node.kind === 'folder' && node.id !== dialog.nodeId)
360
+ // 不能把文件夹移进自己或自己的子孙(用物化 path 判断)
361
+ .filter((node) => !moving || !node.path.startsWith(`${moving.path}/`))
362
+ .sort((left, right) => left.path.localeCompare(right.path));
363
+ const depthOf = (node) => Math.max(0, node.path.split('/').length - 2);
364
+ return [
365
+ h('button', {
366
+ type: 'button', key: 'root', className: 'dsh-kb-moveItem',
367
+ onClick: () => {
368
+ const target = dialog.nodeId;
369
+ patch({ dialog: null });
370
+ nodeAction('move', { id: target, parentId: null });
371
+ },
372
+ }, '根目录'),
373
+ ...usable.map((folder) => h('button', {
374
+ type: 'button', key: folder.id, className: 'dsh-kb-moveItem',
375
+ style: { paddingLeft: 10 + depthOf(folder) * 14 },
376
+ onClick: () => {
377
+ patch({ dialog: null });
378
+ nodeAction('move', { id: dialog.nodeId, parentId: folder.id });
379
+ },
380
+ }, folder.name)),
381
+ ];
382
+ })())
383
+ : null,
384
+ h('div', { className: 'dsh-kb-modalActions' },
385
+ h('button', { type: 'button', className: 'dsh-kb-btn', onClick: close }, '取消'),
386
+ dialog.kind === 'move'
387
+ ? null
388
+ : h('button', {
389
+ type: 'button',
390
+ className: cx('dsh-kb-btn', dialog.danger ? 'dsh-kb-btn--dangerSolid' : 'dsh-kb-btn--primary'),
391
+ onClick: submit,
392
+ disabled: dialog.kind === 'input' && !String(value).trim(),
393
+ }, dialog.okLabel || (dialog.kind === 'input' ? '确定' : '删除')))));
394
+ }
395
+
396
+ // ── 目录树 ──────────────────────────────────────────────────────────
397
+ function buildTree(nodes) {
398
+ const byParent = new Map();
399
+ for (const node of nodes) {
400
+ const key = node.parentId || '';
401
+ if (!byParent.has(key)) byParent.set(key, []);
402
+ byParent.get(key).push(node);
403
+ }
404
+ for (const list of byParent.values()) list.sort((left, right) => left.sort - right.sort);
405
+ return byParent;
406
+ }
407
+
408
+ function statusDot(node) {
409
+ if (node.kind !== 'doc') return null;
410
+ if (node.status === 'failed') return h('span', { className: 'dsh-kb-dot dsh-kb-dot--bad', title: node.error || '解析失败' });
411
+ if (node.status === 'pending' || node.status === 'parsing') return h('span', { className: 'dsh-kb-dot dsh-kb-dot--busy', title: '解析中' });
412
+ return null;
413
+ }
414
+
415
+ function TreeRows({ byParent, parentKey, depth }) {
416
+ const current = useStore();
417
+ const list = byParent.get(parentKey) || [];
418
+ return list.map((node) => {
419
+ const isFolder = node.kind === 'folder';
420
+ const open = current.expanded[node.id] !== false;
421
+ const active = current.selectedId === node.id;
422
+ const activate = () => {
423
+ if (isFolder) {
424
+ // 点文件夹 = 选中它(导入/新建就落在这里)+ 展开收起
425
+ patch({ selectedId: node.id, expanded: { ...current.expanded, [node.id]: !open } });
426
+ return;
427
+ }
428
+ loadDoc(node.id);
429
+ };
430
+ return h(React.Fragment, { key: node.id },
431
+ h('div', {
432
+ className: cx('dsh-kb-row', active && 'dsh-kb-row--active'),
433
+ style: { paddingLeft: 6 + depth * 14 },
434
+ role: 'treeitem',
435
+ tabIndex: 0,
436
+ draggable: true,
437
+ 'aria-expanded': isFolder ? open : undefined,
438
+ 'aria-selected': active,
439
+ onClick: activate,
440
+ onDragStart: (event) => {
441
+ event.dataTransfer.setData('text/kb-node', node.id);
442
+ event.dataTransfer.effectAllowed = 'move';
443
+ },
444
+ onDragOver: isFolder
445
+ ? (event) => { event.preventDefault(); event.dataTransfer.dropEffect = 'move'; }
446
+ : undefined,
447
+ onDrop: isFolder
448
+ ? (event) => {
449
+ event.preventDefault();
450
+ event.stopPropagation();
451
+ const dragged = event.dataTransfer.getData('text/kb-node');
452
+ if (dragged && dragged !== node.id) nodeAction('move', { id: dragged, parentId: node.id });
453
+ }
454
+ : undefined,
455
+ onKeyDown: (event) => {
456
+ if (event.key === 'Enter' || event.key === ' ') {
457
+ event.preventDefault();
458
+ activate();
459
+ }
460
+ if (event.key === 'F2') {
461
+ event.preventDefault();
462
+ askText('重命名', node.name, (name) => nodeAction('rename', { id: node.id, name }));
463
+ }
464
+ if (event.key === 'Delete') {
465
+ event.preventDefault();
466
+ askConfirm(`删除「${node.name}」?${isFolder ? '里面的内容也会一起删除。' : '原文件也会被删掉。'}`,
467
+ () => nodeAction('delete', { id: node.id }));
468
+ }
469
+ },
470
+ title: `${node.name}${node.kind === 'doc' ? ` · ${bytes(node.bytes)}` : ''}`,
471
+ },
472
+ h('span', { className: cx('dsh-kb-caret', isFolder && open && 'dsh-kb-caret--open') },
473
+ isFolder ? h(Icon, { name: 'chevron', size: 12 }) : null),
474
+ h('span', { className: 'dsh-kb-rowIcon' }, h(Icon, { name: isFolder ? (open ? 'folderOpen' : 'folder') : 'doc', size: 14 })),
475
+ h('span', { className: 'dsh-kb-rowName' }, node.name),
476
+ statusDot(node),
477
+ h('span', { className: 'dsh-kb-rowActions' },
478
+ h('button', {
479
+ type: 'button',
480
+ className: cx('dsh-kb-rowBtn dsh-kb-moreBtn', current.menu?.id === node.id && 'dsh-kb-rowBtn--on'),
481
+ title: '更多操作',
482
+ 'aria-haspopup': 'menu',
483
+ 'aria-expanded': current.menu?.id === node.id,
484
+ onClick: (event) => {
485
+ event?.stopPropagation?.();
486
+ // 菜单从文件树右侧弹出(不压住树里的文字),纵向对齐到这一行
487
+ const target = event?.currentTarget;
488
+ const rowElement = target?.closest?.('.dsh-kb-row') || target;
489
+ const rowRect = rowElement?.getBoundingClientRect?.();
490
+ const sideRect = rowElement?.closest?.('.dsh-kb-side')?.getBoundingClientRect?.();
491
+ const viewportWidth = typeof window !== 'undefined' && window.innerWidth ? window.innerWidth : 1280;
492
+ const viewportHeight = typeof window !== 'undefined' && window.innerHeight ? window.innerHeight : 800;
493
+ const menuHeight = (isFolder ? 5 : 4) * 30 + 10;
494
+ let x = sideRect ? Math.round(sideRect.right + 6)
495
+ : rowRect ? Math.round(rowRect.right + 6) : 260;
496
+ if (x + MENU_WIDTH > viewportWidth - 8) x = Math.max(8, viewportWidth - MENU_WIDTH - 8);
497
+ let y = rowRect ? Math.round(rowRect.bottom + 2) : 40;
498
+ y = Math.max(8, Math.min(y, viewportHeight - menuHeight - 8));
499
+ patch({
500
+ menu: current.menu?.id === node.id ? null : { id: node.id, x, y },
501
+ });
502
+ },
503
+ }, '⋯'))),
504
+ isFolder && open
505
+ ? ((byParent.get(node.id) || []).length
506
+ ? h(TreeRows, { byParent, parentKey: node.id, depth: depth + 1 })
507
+ : h('div', {
508
+ key: `${node.id}-empty`,
509
+ className: 'dsh-kb-rowHint',
510
+ style: { paddingLeft: 6 + (depth + 1) * 14 },
511
+ }, '(空文件夹:把文件拖进来,或用这一行右边的「⋯」新建子文件夹 / 上传文件)'))
512
+ : null);
513
+ });
514
+ }
515
+
516
+ // ── 正文渲染(很轻的 markdown-ish)──────────────────────────────────
517
+ function renderText(text, query) {
518
+ const lines = String(text || '').split('\n');
519
+ const out = [];
520
+ const words = String(query || '').trim().split(/\s+/).filter((word) => word.length >= 1);
521
+ let buffer = [];
522
+
523
+ const decorate = (value) => {
524
+ if (!words.length) return value;
525
+ const pattern = words
526
+ .map((word) => word.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
527
+ .filter(Boolean)
528
+ .join('|');
529
+ if (!pattern) return value;
530
+ const parts = value.split(new RegExp(`(${pattern})`, 'gi'));
531
+ return parts.map((part, index) => (index % 2 === 1
532
+ ? h('mark', { key: index, className: 'dsh-kb-mark' }, part)
533
+ : part));
534
+ };
535
+
536
+ const flush = () => {
537
+ if (!buffer.length) return;
538
+ const body = buffer.join('\n');
539
+ buffer = [];
540
+ out.push(h('p', { key: out.length, className: 'dsh-kb-p' }, decorate(body)));
541
+ };
542
+
543
+ for (const line of lines) {
544
+ const heading = /^(#{1,6})\s+(.*)$/.exec(line);
545
+ const pageMark = /^\u3014第\s*(\d+)\s*页\u3015$/.exec(line.trim());
546
+ if (heading) {
547
+ flush();
548
+ const level = heading[1].length;
549
+ out.push(h('div', {
550
+ key: out.length,
551
+ className: `dsh-kb-h dsh-kb-h${level}`,
552
+ }, decorate(heading[2])));
553
+ continue;
554
+ }
555
+ if (pageMark) {
556
+ flush();
557
+ out.push(h('div', { key: out.length, className: 'dsh-kb-pageMark' }, `第 ${pageMark[1]} 页`));
558
+ continue;
559
+ }
560
+ if (/^\|/.test(line)) {
561
+ flush();
562
+ out.push(h('div', { key: out.length, className: 'dsh-kb-tablerow' }, decorate(line)));
563
+ continue;
564
+ }
565
+ if (!line.trim()) {
566
+ flush();
567
+ continue;
568
+ }
569
+ buffer.push(line);
570
+ }
571
+ flush();
572
+ return out.length ? out : [h('p', { key: 0, className: 'dsh-kb-hint' }, '(没有正文:可能还在解析,或这个格式抽不出文字)')];
573
+ }
574
+
575
+ function isImage(ext) {
576
+ return ['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'svg'].includes(ext);
577
+ }
578
+
579
+ function rawUrl(doc, extra) {
580
+ return `${API}/doc?id=${encodeURIComponent(doc.id)}&action=raw&t=${encodeURIComponent(state.token)}${extra ? `&${extra}` : ''}`;
581
+ }
582
+
583
+ function previewUrl(doc) {
584
+ return `${API}/doc?id=${encodeURIComponent(doc.id)}&action=preview&t=${encodeURIComponent(state.token)}`;
585
+ }
586
+
587
+ function pageUrl(doc, page) {
588
+ return `${API}/doc?id=${encodeURIComponent(doc.id)}&action=page&n=${page}&t=${encodeURIComponent(state.token)}`;
589
+ }
590
+
591
+ function thumbUrl(doc, page) {
592
+ return `${API}/doc?id=${encodeURIComponent(doc.id)}&action=thumb&n=${page}&t=${encodeURIComponent(state.token)}`;
593
+ }
594
+
595
+ // ── 读取区 ──────────────────────────────────────────────────────────
596
+ function DocView({ onAsk, onReindex, onDelete }) {
597
+ const current = useStore();
598
+ const doc = current.doc;
599
+ const pagesRef = React.useRef(null);
600
+ // Office 原版式:先让 Host 把每页渲染成图片,界面自己拼阅读器
601
+ React.useEffect(() => {
602
+ const target = state.doc;
603
+ if (!target || !OFFICE_EXT.includes(target.ext)) return undefined;
604
+ if (state.previewMode === 'text' || state.caps?.officePreview === false) return undefined;
605
+ if (state.previewInfo?.docId === target.id) return undefined;
606
+ let cancelled = false;
607
+ const timer = setTimeout(() => {
608
+ if (!cancelled && state.previewInfo?.docId !== target.id) {
609
+ patch({ previewError: '页面渲染超过 90 秒还没好;可以点「新窗口」看 PDF,或切到「文字」。' });
610
+ }
611
+ }, 90000);
612
+ api(`/doc?id=${encodeURIComponent(target.id)}&action=previewinfo`)
613
+ .then((data) => {
614
+ if (cancelled) return;
615
+ patch({
616
+ previewInfo: {
617
+ docId: target.id,
618
+ pages: data.pages,
619
+ pageCount: data.pageCount,
620
+ truncated: Boolean(data.truncated),
621
+ width: data.width,
622
+ height: data.height,
623
+ },
624
+ previewError: '',
625
+ });
626
+ })
627
+ .catch((error) => {
628
+ if (cancelled) return;
629
+ const message = error.message || '预览生成失败';
630
+ patch({ previewInfo: { docId: target.id, error: message }, previewError: message });
631
+ });
632
+ return () => { cancelled = true; clearTimeout(timer); };
633
+ }, [doc?.id, current.previewMode]);
634
+ if (!doc) {
635
+ if (current.kbs.length === 0) {
636
+ return h('div', { className: 'dsh-kb-empty' },
637
+ h('div', { className: 'dsh-kb-emptyIcon' }, h(Icon, { name: 'book', size: 28 })),
638
+ h('p', null, '先新建一个知识库,再把文件拖进来。'),
639
+ h('button', { type: 'button', className: 'dsh-kb-btn dsh-kb-btn--primary', onClick: () => createKb() }, '新建知识库'),
640
+ h('p', { className: 'dsh-kb-hint' }, '文件只存在这台电脑上,不会上传到云端。'));
641
+ }
642
+ return h('div', { className: 'dsh-kb-empty' },
643
+ h('div', { className: 'dsh-kb-emptyIcon' }, h(Icon, { name: 'book', size: 28 })),
644
+ h('p', null, current.nodes.length ? '从左边选一个文件,或把文件拖进来。' : '这个知识库还是空的。点「上传文件」或把文件拖进来。'),
645
+ h('p', { className: 'dsh-kb-hint' }, '文件只存在这台电脑上,不会上传到云端。'));
646
+ }
647
+ const failed = doc.status === 'failed';
648
+ const pending = doc.status === 'pending' || doc.status === 'parsing';
649
+ const office = OFFICE_EXT.includes(doc.ext);
650
+ const previewAvailable = current.caps?.officePreview !== false;
651
+ const officeVisual = office && previewAvailable && current.previewMode !== 'text';
652
+ const visual = isImage(doc.ext) ? false : (doc.ext === 'pdf' || officeVisual);
653
+ const officeInfo = current.previewInfo?.docId === doc.id ? current.previewInfo : null;
654
+ const totalPages = officeInfo?.pages || 0;
655
+ const pageNow = Math.min(Math.max(1, Number(current.currentPage) || 1), totalPages || 1);
656
+ const pageAspect = officeInfo?.width && officeInfo?.height
657
+ ? { aspectRatio: `${officeInfo.width} / ${officeInfo.height}` }
658
+ : undefined;
659
+ const goPage = (target) => {
660
+ const page = Math.min(Math.max(1, Math.round(Number(target) || 1)), totalPages || 1);
661
+ patch({ currentPage: page, pageInput: String(page) });
662
+ if (state.pageMode === 'single') return;
663
+ const container = pagesRef.current;
664
+ const element = container?.querySelector(`[data-page="${page}"]`);
665
+ if (container && element) container.scrollTop = Math.max(0, element.offsetTop - 10);
666
+ };
667
+ const onPagesScroll = (event) => {
668
+ const container = event.currentTarget;
669
+ let visible = 1;
670
+ for (const shot of container.querySelectorAll('[data-page]')) {
671
+ if (shot.offsetTop - container.scrollTop <= 48) visible = Number(shot.getAttribute('data-page')) || visible;
672
+ else break;
673
+ }
674
+ if (visible !== state.currentPage) patch({ currentPage: visible, pageInput: String(visible) });
675
+ };
676
+ return h('div', { className: 'dsh-kb-doc' },
677
+ h('div', { className: 'dsh-kb-docHead' },
678
+ h('div', { className: 'dsh-kb-docTitle' }, doc.name),
679
+ h('div', { className: 'dsh-kb-docMeta' },
680
+ h('span', null, bytes(doc.bytes)),
681
+ doc.ext ? h('span', null, `.${doc.ext}`) : null,
682
+ h('span', null, doc.status === 'ready' ? `已索引 · ${doc.chars} 字${doc.pageCount ? ` · ${doc.pageCount} 页` : ''}` : pending ? '解析中…' : failed ? '解析失败' : doc.status),
683
+ doc.indexedAt ? h('span', null, when(doc.indexedAt)) : null)),
684
+ h('div', { className: 'dsh-kb-docActions' },
685
+ h('button', { type: 'button', className: 'dsh-kb-btn dsh-kb-btn--primary', onClick: () => onAsk(doc) },
686
+ h(Icon, { name: 'spark', size: 14 }), '问 AI'),
687
+ h('button', {
688
+ type: 'button', className: 'dsh-kb-btn',
689
+ onClick: () => patch({ bigView: true, previewMode: office ? 'visual' : state.previewMode }),
690
+ title: '铺满整个窗口看(Esc 关闭)',
691
+ }, h(Icon, { name: 'open', size: 14 }), '大屏'),
692
+ h('a', {
693
+ className: 'dsh-kb-btn', href: rawUrl(doc, 'download=1'), download: doc.name,
694
+ onClick: (event) => event.stopPropagation(),
695
+ title: '下载原始文件',
696
+ }, '下载'),
697
+ office
698
+ ? h('span', { className: 'dsh-kb-seg', role: 'group', 'aria-label': '查看方式' },
699
+ h('button', {
700
+ type: 'button',
701
+ className: cx('dsh-kb-segBtn', officeVisual && 'dsh-kb-segBtn--on'),
702
+ onClick: () => patch({ previewMode: 'visual' }),
703
+ }, '原版式'),
704
+ h('button', {
705
+ type: 'button',
706
+ className: cx('dsh-kb-segBtn', !officeVisual && 'dsh-kb-segBtn--on'),
707
+ onClick: () => patch({ previewMode: 'text' }),
708
+ }, '文字'))
709
+ : null,
710
+ doc.status !== 'failed' && !isImage(doc.ext)
711
+ ? h('button', { type: 'button', className: 'dsh-kb-btn', onClick: () => onReindex(doc) },
712
+ h(Icon, { name: 'refresh', size: 14 }), '重新索引')
713
+ : null,
714
+ h('button', { type: 'button', className: 'dsh-kb-btn dsh-kb-btn--danger', onClick: () => onDelete(doc) },
715
+ h(Icon, { name: 'trash', size: 14 }), '删除')),
716
+ office && !previewAvailable
717
+ ? h('div', { className: 'dsh-kb-banner dsh-kb-banner--info' },
718
+ '这台机器没启用 Office 转换服务,只能看抽取出来的文字;「原文件」按钮可以用系统里的 Office 打开。')
719
+ : null,
720
+ current.previewError
721
+ ? h('div', { className: 'dsh-kb-banner dsh-kb-banner--bad', role: 'alert' },
722
+ h('Icon', { name: 'warn', size: 15 }),
723
+ h('span', null, current.previewError),
724
+ office
725
+ ? h('button', { type: 'button', className: 'dsh-kb-btn', onClick: () => patch({ previewMode: 'text', previewError: '' }) }, '看文字版')
726
+ : null)
727
+ : null,
728
+ failed
729
+ ? h('div', { className: 'dsh-kb-banner dsh-kb-banner--bad' },
730
+ h(Icon, { name: 'warn', size: 15 }),
731
+ h('span', null, doc.error || '解析失败'),
732
+ h('button', { type: 'button', className: 'dsh-kb-btn', onClick: () => onReindex(doc) }, '重试'))
733
+ : null,
734
+ h('div', { className: cx('dsh-kb-reader', visual && 'dsh-kb-reader--visual') },
735
+ pending
736
+ ? h('div', { className: 'dsh-kb-hint' }, '正在解析并建立索引,稍等一下…')
737
+ : null,
738
+ isImage(doc.ext)
739
+ ? h('img', {
740
+ className: 'dsh-kb-image',
741
+ alt: doc.name,
742
+ src: rawUrl(doc),
743
+ })
744
+ : doc.ext === 'pdf'
745
+ ? h('iframe', {
746
+ className: 'dsh-kb-frame',
747
+ title: doc.name,
748
+ src: `${rawUrl(doc)}${PDF_FRAGMENT}`,
749
+ })
750
+ : officeVisual
751
+ ? h('div', { className: 'dsh-kb-viewer' },
752
+ officeInfo && !officeInfo.error
753
+ ? h('div', { className: 'dsh-kb-viewerBar' },
754
+ h('button', {
755
+ type: 'button', className: 'dsh-kb-navBtn', title: '显示/隐藏缩略图',
756
+ onClick: () => patch({ thumbsOpen: !state.thumbsOpen }),
757
+ }, h(Icon, { name: 'doc', size: 13 })),
758
+ h('button', {
759
+ type: 'button', className: 'dsh-kb-navBtn', title: '上一页',
760
+ disabled: pageNow <= 1, onClick: () => goPage(pageNow - 1),
761
+ }, '‹'),
762
+ h('input', {
763
+ className: 'dsh-kb-pageInput',
764
+ value: current.pageInput ?? String(pageNow),
765
+ inputMode: 'numeric',
766
+ 'aria-label': '跳到页码',
767
+ onChange: (event) => patch({ pageInput: event.target.value.replace(/[^\d]/g, '') }),
768
+ onKeyDown: (event) => {
769
+ if (event.key === 'Enter') {
770
+ goPage(state.pageInput);
771
+ event.currentTarget.blur();
772
+ }
773
+ },
774
+ }),
775
+ h('span', { className: 'dsh-kb-pageTotal' }, `/ ${officeInfo.pages}`),
776
+ h('button', {
777
+ type: 'button', className: 'dsh-kb-navBtn', title: '下一页',
778
+ disabled: pageNow >= officeInfo.pages, onClick: () => goPage(pageNow + 1),
779
+ }, '›'),
780
+ h('span', { className: 'dsh-kb-viewerGrow' }),
781
+ h('span', { className: 'dsh-kb-seg', role: 'group', 'aria-label': '翻页方式' },
782
+ h('button', {
783
+ type: 'button',
784
+ className: cx('dsh-kb-segBtn', current.pageMode !== 'single' && 'dsh-kb-segBtn--on'),
785
+ onClick: () => patch({ pageMode: 'scroll' }),
786
+ }, '连续'),
787
+ h('button', {
788
+ type: 'button',
789
+ className: cx('dsh-kb-segBtn', current.pageMode === 'single' && 'dsh-kb-segBtn--on'),
790
+ onClick: () => patch({ pageMode: 'single', currentPage: pageNow }),
791
+ }, '单页')))
792
+ : null,
793
+ officeInfo && !officeInfo.error
794
+ ? h('div', { className: 'dsh-kb-viewerBody' },
795
+ current.thumbsOpen
796
+ ? h('div', { className: 'dsh-kb-thumbs' },
797
+ Array.from({ length: officeInfo.pages }, (_, index) => index + 1).map((page) => h('button', {
798
+ type: 'button',
799
+ key: page,
800
+ className: cx('dsh-kb-thumb', page === pageNow && 'dsh-kb-thumb--on'),
801
+ title: `第 ${page} 页`,
802
+ onClick: () => goPage(page),
803
+ },
804
+ h('img', {
805
+ className: 'dsh-kb-thumbImg',
806
+ src: thumbUrl(doc, page),
807
+ loading: 'lazy',
808
+ decoding: 'async',
809
+ alt: `第 ${page} 页缩略图`,
810
+ }),
811
+ h('span', { className: 'dsh-kb-thumbNo' }, page))))
812
+ : null,
813
+ h('div', {
814
+ className: cx('dsh-kb-pages', current.pageMode === 'single' && 'dsh-kb-pages--single'),
815
+ ref: pagesRef,
816
+ onScroll: current.pageMode === 'single' ? undefined : onPagesScroll,
817
+ },
818
+ (current.pageMode === 'single' ? [pageNow] : Array.from({ length: officeInfo.pages }, (_, index) => index + 1))
819
+ .map((page) => h('div', {
820
+ className: 'dsh-kb-pageShot',
821
+ key: page,
822
+ 'data-page': page,
823
+ // 单页模式让容器自己撑满、由 object-fit 居中,不要用固定比例
824
+ style: current.pageMode === 'single' ? undefined : pageAspect,
825
+ },
826
+ h('img', {
827
+ className: 'dsh-kb-pageImg',
828
+ src: pageUrl(doc, page),
829
+ loading: page <= 2 ? 'eager' : 'lazy',
830
+ decoding: 'async',
831
+ alt: `${doc.name} 第 ${page} 页`,
832
+ }),
833
+ h('span', { className: 'dsh-kb-pageNo' }, page))),
834
+ officeInfo.truncated
835
+ ? h('div', { className: 'dsh-kb-pagesNote' },
836
+ `共 ${officeInfo.pageCount || '?'} 页,这里只渲染了前 ${officeInfo.pages} 页;看完整版请点「新窗口」。`)
837
+ : null))
838
+ : h('div', { className: 'dsh-kb-pagesLoading' },
839
+ h('span', { className: 'dsh-kb-spinner', 'aria-hidden': 'true' }),
840
+ '正在渲染页面…第一次打开会慢一些,之后是缓存。'))
841
+ : h('div', { className: 'dsh-kb-text' }, renderText(current.docText, current.query)),
842
+ !officeVisual && doc.ext !== 'pdf' && !isImage(doc.ext) && current.docHasMore
843
+ ? h('button', {
844
+ type: 'button', className: 'dsh-kb-btn dsh-kb-more',
845
+ onClick: () => loadDoc(doc.id, { offset: current.docNext }),
846
+ }, `继续加载(已显示 ${current.docText.length} / ${current.docTotal} 字)`)
847
+ : null));
848
+ }
849
+
850
+ // ── 检索结果 ────────────────────────────────────────────────────────
851
+ function SearchView() {
852
+ const current = useStore();
853
+ const search = current.search;
854
+ if (search.loading) return h('div', { className: 'dsh-kb-hint' }, '检索中…');
855
+ if (search.error) return h('div', { className: 'dsh-kb-banner dsh-kb-banner--bad' }, search.error);
856
+ if (!search.hits.length) return h('div', { className: 'dsh-kb-hint' }, search.ran ? '没有找到匹配的内容。换个词试试,或只搜关键词。' : '');
857
+ return h('div', { className: 'dsh-kb-hits' },
858
+ h('div', { className: 'dsh-kb-hitsHead' }, `${search.hits.length} 条结果 · ${search.mode === 'hybrid' ? '关键词 + 向量' : '关键词'}`),
859
+ search.hits.map((hit) => h('button', {
860
+ key: `${hit.nodeId}-${hit.chunkId}`,
861
+ type: 'button',
862
+ className: 'dsh-kb-hit',
863
+ onClick: () => {
864
+ if (hit.ext === 'pdf' || isImage(hit.ext)) {
865
+ // PDF / 图片没有可定位的正文,只打开文件,别偷偷改偏移
866
+ loadDoc(hit.nodeId, { offset: 0 });
867
+ patch({ notice: `${hit.ext === 'pdf' ? 'PDF' : '图片'}命中的位置无法精确定位,已打开文件本身。` });
868
+ return;
869
+ }
870
+ loadDoc(hit.nodeId, { offset: Math.max(0, Number(hit.charStart) - 200) });
871
+ },
872
+ },
873
+ h('div', { className: 'dsh-kb-hitName' }, hit.name, hit.heading ? h('span', { className: 'dsh-kb-hitHead' }, ` · ${hit.heading}`) : null),
874
+ h('div', { className: 'dsh-kb-hitSnippet' }, hit.snippet))));
875
+ }
876
+
877
+ // ── 大屏预览:铺满整个窗口(不依赖 window.open / target=_blank,桌面端会拦)──
878
+ function BigView({ doc }) {
879
+ const current = useStore();
880
+ const office = OFFICE_EXT.includes(doc.ext);
881
+ const info = current.previewInfo?.docId === doc.id ? current.previewInfo : null;
882
+ const total = info?.pages || 0;
883
+ const single = current.bigMode !== 'scroll';
884
+ const page = Math.min(Math.max(1, Number(current.currentPage) || 1), total || 1);
885
+ const go = (target) => {
886
+ const next = Math.min(Math.max(1, Math.round(Number(target) || 1)), total || 1);
887
+ patch({ currentPage: next, pageInput: String(next) });
888
+ };
889
+ React.useEffect(() => {
890
+ const onKey = (event) => {
891
+ if (event.key === 'Escape') { patch({ bigView: false }); return; }
892
+ if (event.key === 'ArrowRight' || event.key === 'PageDown') {
893
+ event.preventDefault();
894
+ go((Number(state.currentPage) || 1) + 1);
895
+ }
896
+ if (event.key === 'ArrowLeft' || event.key === 'PageUp') {
897
+ event.preventDefault();
898
+ go((Number(state.currentPage) || 1) - 1);
899
+ }
900
+ };
901
+ window.addEventListener('keydown', onKey);
902
+ return () => window.removeEventListener('keydown', onKey);
903
+ }, []);
904
+ return h('div', { className: 'dsh-kb-big' },
905
+ h('div', { className: 'dsh-kb-bigBar' },
906
+ h('span', { className: 'dsh-kb-bigTitle' }, doc.name),
907
+ office && info
908
+ ? h('span', { className: 'dsh-kb-bigNav' },
909
+ h('button', { type: 'button', className: 'dsh-kb-navBtn', title: '上一页', disabled: page <= 1, onClick: () => go(page - 1) }, '‹'),
910
+ h('span', { className: 'dsh-kb-pageTotal' }, `${page} / ${info.pages}`),
911
+ h('button', { type: 'button', className: 'dsh-kb-navBtn', title: '下一页', disabled: page >= info.pages, onClick: () => go(page + 1) }, '›'),
912
+ h('span', { className: 'dsh-kb-seg', role: 'group', 'aria-label': '显示方式' },
913
+ h('button', {
914
+ type: 'button',
915
+ className: cx('dsh-kb-segBtn', single && 'dsh-kb-segBtn--on'),
916
+ onClick: () => patch({ bigMode: 'single' }),
917
+ }, '单页'),
918
+ h('button', {
919
+ type: 'button',
920
+ className: cx('dsh-kb-segBtn', !single && 'dsh-kb-segBtn--on'),
921
+ onClick: () => patch({ bigMode: 'scroll' }),
922
+ }, '连续')))
923
+ : null,
924
+ h('span', { className: 'dsh-kb-viewerGrow' }),
925
+ h('button', {
926
+ type: 'button', className: 'dsh-kb-btn dsh-kb-btn--primary', title: '恢复成面板视图(Esc)',
927
+ onClick: () => patch({ bigView: false }),
928
+ }, h(Icon, { name: 'close', size: 13 }), '恢复')),
929
+ h('div', { className: 'dsh-kb-bigBody' },
930
+ isImage(doc.ext)
931
+ ? h('img', { className: 'dsh-kb-bigImg', src: rawUrl(doc), alt: doc.name })
932
+ : doc.ext === 'pdf'
933
+ ? h('iframe', { className: 'dsh-kb-bigFrame', title: doc.name, src: `${rawUrl(doc)}${PDF_FRAGMENT}` })
934
+ : office && info && !info.error
935
+ ? h('div', { className: cx('dsh-kb-pages', single && 'dsh-kb-pages--single') },
936
+ (single ? [page] : Array.from({ length: info.pages }, (_, index) => index + 1))
937
+ .map((one) => h('div', {
938
+ className: 'dsh-kb-pageShot',
939
+ key: one,
940
+ 'data-page': one,
941
+ style: single || !info.width || !info.height ? undefined : { aspectRatio: `${info.width} / ${info.height}` },
942
+ },
943
+ h('img', {
944
+ className: 'dsh-kb-pageImg',
945
+ src: pageUrl(doc, one),
946
+ loading: one <= 2 ? 'eager' : 'lazy',
947
+ decoding: 'async',
948
+ alt: `${doc.name} 第 ${one} 页`,
949
+ }),
950
+ h('span', { className: 'dsh-kb-pageNo' }, one))))
951
+ : h('div', { className: 'dsh-kb-pagesLoading' },
952
+ h('span', { className: 'dsh-kb-spinner', 'aria-hidden': 'true' }),
953
+ office ? '正在渲染页面…' : '这个格式没有大屏预览,可以点「下载」用系统应用打开')));
954
+ }
955
+
956
+ // ── 看板:知识库规模 + 检索情况 ─────────────────────────────────────
957
+ function Dashboard() {
958
+ const current = useStore();
959
+ const data = current.dashData;
960
+ const error = current.dashError;
961
+ const loading = Boolean(current.dashLoading);
962
+
963
+ const load = async () => {
964
+ patch({ dashLoading: true });
965
+ try {
966
+ const result = await api('/dashboard');
967
+ patch({ dashData: result, dashError: '' });
968
+ } catch (problem) {
969
+ patch({ dashError: problem.message || '读取统计失败' });
970
+ } finally {
971
+ patch({ dashLoading: false });
972
+ }
973
+ };
974
+
975
+ React.useEffect(() => { if (!state.dashData) load(); }, []);
976
+
977
+ if (error && !data) {
978
+ return h('div', { className: 'dsh-kb-dash' },
979
+ h('div', { className: 'dsh-kb-banner dsh-kb-banner--bad', role: 'alert' }, error),
980
+ h('button', { type: 'button', className: 'dsh-kb-btn', onClick: load }, '重试'));
981
+ }
982
+ if (!data) return h('div', { className: 'dsh-kb-hint dsh-kb-hint--pad' }, loading ? '统计中…' : '');
983
+
984
+ const stats = data.stats || {};
985
+ const search = data.search || {};
986
+ const coverage = stats.chunks ? Math.round(((stats.vectors || 0) / stats.chunks) * 100) : 0;
987
+ const maxExt = Math.max(1, ...(data.byExt || []).map((item) => item.docs));
988
+ const maxTrend = Math.max(1, ...(data.trend || []).map((item) => item.count));
989
+ const statusLabel = { ready: '已索引', parsing: '解析中', pending: '排队', failed: '失败' };
990
+ const statusColor = { ready: 'ok', parsing: 'busy', pending: 'idle', failed: 'bad' };
991
+
992
+ const card = (label, value, hint) => h('div', { className: 'dsh-kb-metric', key: label },
993
+ h('span', { className: 'dsh-kb-metricLabel' }, label),
994
+ h('strong', { className: 'dsh-kb-metricValue' }, value),
995
+ hint ? h('span', { className: 'dsh-kb-metricHint' }, hint) : null);
996
+
997
+ return h('div', { className: 'dsh-kb-dash' },
998
+ h('div', { className: 'dsh-kb-dashHead' },
999
+ h('div', { className: 'dsh-kb-docTitle' }, '知识库看板'),
1000
+ h('span', { className: 'dsh-kb-hint' }, `数据目录 ${data.root || ''}`),
1001
+ h('span', { className: 'dsh-kb-viewerGrow' }),
1002
+ h('button', { type: 'button', className: 'dsh-kb-btn', onClick: load, disabled: loading },
1003
+ h(Icon, { name: 'refresh', size: 13 }), loading ? '刷新中…' : '刷新')),
1004
+
1005
+ h('div', { className: 'dsh-kb-metrics' },
1006
+ card('知识库', stats.kbs ?? 0, '个'),
1007
+ card('文档', stats.docs ?? 0, `共 ${bytes(stats.bytes)}`),
1008
+ card('检索片段', stats.chunks ?? 0, `平均 ${stats.docs ? Math.round((stats.chunks || 0) / stats.docs) : 0} 段/篇`),
1009
+ card('向量', stats.vectors ?? 0, `覆盖率 ${coverage}%`),
1010
+ card('检索次数', search.total ?? 0, `今日 ${search.today ?? 0}`)),
1011
+
1012
+ h('div', { className: 'dsh-kb-dashGrid' },
1013
+ // 文件类型分布
1014
+ h('section', { className: 'dsh-kb-card' },
1015
+ h('h4', null, '文件类型分布'),
1016
+ (data.byExt || []).length === 0
1017
+ ? h('p', { className: 'dsh-kb-hint' }, '还没有文档')
1018
+ : (data.byExt || []).map((item) => h('div', { className: 'dsh-kb-distRow', key: item.ext },
1019
+ h('span', { className: 'dsh-kb-distLabel' }, `.${item.ext}`),
1020
+ h('span', { className: 'dsh-kb-bar' },
1021
+ h('i', { style: { width: `${Math.round((item.docs / maxExt) * 100)}%` } })),
1022
+ h('span', { className: 'dsh-kb-distValue' }, `${item.docs} · ${bytes(item.bytes)}`)))),
1023
+
1024
+ // 解析状态
1025
+ h('section', { className: 'dsh-kb-card' },
1026
+ h('h4', null, '解析状态'),
1027
+ h('div', { className: 'dsh-kb-chips' },
1028
+ Object.entries(data.byStatus || {}).map(([status, count]) => h('span', {
1029
+ className: `dsh-kb-chip dsh-kb-chip--${statusColor[status] || 'idle'}`,
1030
+ key: status,
1031
+ }, `${statusLabel[status] || status} ${count}`))),
1032
+ h('h4', { className: 'dsh-kb-subHead' }, '各知识库'),
1033
+ (data.byKb || []).map((kb) => h('div', { className: 'dsh-kb-distRow', key: kb.id },
1034
+ h('span', { className: 'dsh-kb-distLabel dsh-kb-distLabel--wide' }, kb.name),
1035
+ h('span', { className: 'dsh-kb-distValue' }, `${kb.docs} 篇 · ${bytes(kb.bytes)}`)))),
1036
+
1037
+ // 检索趋势
1038
+ h('section', { className: 'dsh-kb-card' },
1039
+ h('h4', null, '最近 7 天检索'),
1040
+ (data.trend || []).length === 0
1041
+ ? h('p', { className: 'dsh-kb-hint' }, '还没有检索记录(搜索框或 kb_search 都会记)')
1042
+ : h('div', { className: 'dsh-kb-spark' },
1043
+ (data.trend || []).map((item) => h('div', { className: 'dsh-kb-sparkCol', key: item.day, title: `${item.day}:${item.count} 次` },
1044
+ h('div', { className: 'dsh-kb-sparkBar', style: { height: `${Math.max(4, Math.round((item.count / maxTrend) * 100))}%` } }),
1045
+ h('span', { className: 'dsh-kb-sparkLabel' }, (item.day || '').slice(5))))),
1046
+ h('div', { className: 'dsh-kb-kv dsh-kb-kv--tight' },
1047
+ h('span', null, '零命中率'), h('strong', null, `${search.zeroRate ?? 0}%`),
1048
+ h('span', null, '平均耗时'), h('strong', null, `${search.avgMs ?? 0} ms`),
1049
+ h('span', null, '混合检索'), h('strong', null, `${search.hybrid ?? 0} 次`),
1050
+ h('span', null, '最近一次'), h('strong', null, search.lastAt ? when(search.lastAt) : '—'))),
1051
+
1052
+ // 热门检索词 + 最近检索
1053
+ h('section', { className: 'dsh-kb-card' },
1054
+ h('h4', null, '热门检索词'),
1055
+ (data.topQueries || []).length === 0
1056
+ ? h('p', { className: 'dsh-kb-hint' }, '还没有')
1057
+ : h('div', { className: 'dsh-kb-chips' },
1058
+ (data.topQueries || []).map((item) => h('span', { className: 'dsh-kb-chip', key: item.query }, `${item.query} · ${item.count}`))),
1059
+ h('h4', { className: 'dsh-kb-subHead' }, '最近检索'),
1060
+ (data.recent || []).length === 0
1061
+ ? h('p', { className: 'dsh-kb-hint' }, '还没有')
1062
+ : h('div', { className: 'dsh-kb-list' },
1063
+ (data.recent || []).map((item, index) => h('div', { className: 'dsh-kb-listRow', key: `${item.ts}-${index}` },
1064
+ h('span', { className: 'dsh-kb-listMain' }, item.query || '(空查询)'),
1065
+ h('span', { className: 'dsh-kb-listMeta' }, `${item.hits} 命中 · ${item.mode} · ${item.tookMs}ms`),
1066
+ h('span', { className: 'dsh-kb-listTime' }, when(item.ts)))))),
1067
+
1068
+ // 最近添加
1069
+ h('section', { className: 'dsh-kb-card' },
1070
+ h('h4', null, '最近添加'),
1071
+ (data.recentDocs || []).length === 0
1072
+ ? h('p', { className: 'dsh-kb-hint' }, '还没有文档')
1073
+ : h('div', { className: 'dsh-kb-list' },
1074
+ (data.recentDocs || []).map((doc) => h('div', { className: 'dsh-kb-listRow', key: doc.id },
1075
+ h('span', { className: 'dsh-kb-listMain' }, doc.name),
1076
+ h('span', { className: 'dsh-kb-listMeta' }, `.${doc.ext} · ${bytes(doc.bytes)} · ${statusLabel[doc.status] || doc.status}`),
1077
+ h('span', { className: 'dsh-kb-listTime' }, when(doc.createdAt))))))));
1078
+ }
1079
+
1080
+ // ── 主页面 ──────────────────────────────────────────────────────────
1081
+ // 「问 AI」的会话入口由 apply 注入(组件拿不到 ctx)
1082
+ let sessionStarter = null;
1083
+
1084
+ /** 新文件/新文件夹落在哪:选中的文件夹 → 选中文件所在目录 → 根。 */
1085
+ function currentFolderId(current) {
1086
+ const selected = current.selectedId
1087
+ ? current.nodes.find((node) => node.id === current.selectedId)
1088
+ : null;
1089
+ if (!selected) return null;
1090
+ return selected.kind === 'folder' ? selected.id : (selected.parentId ?? null);
1091
+ }
1092
+
1093
+ function createKb() {
1094
+ askText('新知识库的名字', '我的知识库', (name) => nodeAction('create-kb', { name }));
1095
+ }
1096
+
1097
+ function KbPage() {
1098
+ const current = useStore();
1099
+ const [dragging, setDragging] = React.useState(false);
1100
+ const fileInput = React.useRef(null);
1101
+ const tree = React.useMemo(() => buildTree(current.nodes), [current.nodes]);
1102
+
1103
+ React.useEffect(() => {
1104
+ if (!state.loaded) loadState();
1105
+ }, []);
1106
+
1107
+ const searchTimer = React.useRef(null);
1108
+ const onQueryChange = (value) => {
1109
+ // 搜索时离开看板/设置,否则结果被挡住看不见
1110
+ patch({ query: value, view: value.trim() ? 'search' : 'doc', dashOpen: false, showSettings: false });
1111
+ if (searchTimer.current) clearTimeout(searchTimer.current);
1112
+ searchTimer.current = setTimeout(() => runSearch(value), 280);
1113
+ };
1114
+
1115
+ const onAsk = async (doc) => {
1116
+ try {
1117
+ const data = await api('/ask', {
1118
+ method: 'POST',
1119
+ headers: { 'content-type': 'application/json' },
1120
+ body: JSON.stringify({ docId: doc.id }),
1121
+ });
1122
+ sessionStarter?.(data.prompt);
1123
+ patch({ notice: '已在会话输入框里准备好提问,接着写你的问题就行' });
1124
+ } catch (error) {
1125
+ patch({ error: error.message || '打不开会话' });
1126
+ }
1127
+ };
1128
+
1129
+ const onReindex = async (doc) => {
1130
+ try {
1131
+ await api(`/doc?id=${encodeURIComponent(doc.id)}&action=reindex`, { method: 'POST' });
1132
+ patch({ notice: '已重新排队解析' });
1133
+ schedulePoll();
1134
+ await loadDoc(doc.id);
1135
+ } catch (error) {
1136
+ patch({ error: error.message || '重建失败' });
1137
+ }
1138
+ };
1139
+
1140
+ const onDelete = (doc) => {
1141
+ askConfirm(`删除「${doc.name}」?原文件也会被删掉。`, async () => {
1142
+ const data = await nodeAction('delete', { id: doc.id });
1143
+ if (data) patch({ doc: null, docText: '', docNext: 0, selectedId: '' });
1144
+ });
1145
+ };
1146
+
1147
+ return h('div', {
1148
+ className: cx('dsh-kb-page', dragging && 'dsh-kb-page--drag'),
1149
+ onDragOver: (event) => { event.preventDefault(); setDragging(true); },
1150
+ onDragLeave: () => setDragging(false),
1151
+ onDrop: (event) => {
1152
+ event.preventDefault();
1153
+ setDragging(false);
1154
+ if (!event.dataTransfer?.files?.length) return; // 树内拖动节点,不是外部文件
1155
+ uploadFiles(event.dataTransfer.files, currentFolderId(current));
1156
+ },
1157
+ },
1158
+ // 顶部
1159
+ h('div', { className: 'dsh-kb-head' },
1160
+ h('button', {
1161
+ type: 'button', className: 'dsh-kb-iconBtn',
1162
+ title: current.sideOpen ? '收起文件树' : '展开文件树',
1163
+ 'aria-expanded': current.sideOpen,
1164
+ onClick: () => patch({ sideOpen: !state.sideOpen }),
1165
+ }, h(Icon, { name: 'chevron', size: 13, className: current.sideOpen ? 'dsh-kb-rot180' : undefined })),
1166
+ h('div', { className: 'dsh-kb-brand' },
1167
+ h('span', { className: 'dsh-kb-brandIcon' }, h(Icon, { name: 'book', size: 16 })),
1168
+ h('select', {
1169
+ className: 'dsh-kb-select',
1170
+ value: current.kbId,
1171
+ onChange: (event) => {
1172
+ patch({ doc: null, docText: '', selectedId: '' });
1173
+ loadState(event.target.value);
1174
+ },
1175
+ },
1176
+ current.kbs.length
1177
+ ? current.kbs.map((kb) => h('option', { key: kb.id, value: kb.id }, `${kb.name}(${kb.docs})`))
1178
+ : h('option', { value: '' }, '还没有知识库')),
1179
+ h('button', {
1180
+ type: 'button', className: 'dsh-kb-iconBtn', title: '新建知识库',
1181
+ onClick: () => createKb(),
1182
+ }, h(Icon, { name: 'plus', size: 14 }))),
1183
+ h('div', { className: 'dsh-kb-searchBox' },
1184
+ h(Icon, { name: 'search', size: 14, className: 'dsh-kb-searchIcon' }),
1185
+ h('input', {
1186
+ className: 'dsh-kb-searchInput',
1187
+ type: 'search',
1188
+ placeholder: '搜索标题或正文(支持中文短词)…',
1189
+ value: current.query,
1190
+ onChange: (event) => onQueryChange(event.target.value),
1191
+ }),
1192
+ current.query
1193
+ ? h('button', {
1194
+ type: 'button', className: 'dsh-kb-searchClear', title: '清空',
1195
+ onClick: () => { onQueryChange(''); },
1196
+ }, h(Icon, { name: 'close', size: 12 }))
1197
+ : null),
1198
+ h('div', { className: 'dsh-kb-headActions' },
1199
+ h('span', { className: 'dsh-kb-seg', role: 'group', 'aria-label': '视图' },
1200
+ h('button', {
1201
+ type: 'button',
1202
+ className: cx('dsh-kb-segBtn', !current.dashOpen && !current.showSettings && 'dsh-kb-segBtn--on'),
1203
+ onClick: () => patch({ dashOpen: false, showSettings: false }),
1204
+ }, '文档'),
1205
+ h('button', {
1206
+ type: 'button',
1207
+ className: cx('dsh-kb-segBtn', current.dashOpen && !current.showSettings && 'dsh-kb-segBtn--on'),
1208
+ onClick: () => patch({ dashOpen: true, showSettings: false }),
1209
+ }, '看板')),
1210
+ h('button', {
1211
+ type: 'button', className: 'dsh-kb-btn',
1212
+ onClick: () => {
1213
+ const parent = currentFolderId(current);
1214
+ askText('新文件夹的名字', '新文件夹', (name) => nodeAction('create', {
1215
+ kbId: current.kbId, parentId: parent, kind: 'folder', name,
1216
+ }));
1217
+ },
1218
+ disabled: !current.kbId,
1219
+ }, h(Icon, { name: 'folder', size: 14 }), '新建文件夹'),
1220
+ h('button', {
1221
+ type: 'button', className: 'dsh-kb-btn dsh-kb-btn--primary',
1222
+ onClick: () => fileInput.current?.click(),
1223
+ disabled: !current.kbId,
1224
+ }, h(Icon, { name: 'upload', size: 14 }), current.uploading ? `上传中 ${current.uploading}` : '上传文件'),
1225
+ h('input', {
1226
+ ref: fileInput, type: 'file', multiple: true, style: { display: 'none' },
1227
+ onChange: (event) => {
1228
+ // 从行菜单的「⋯ → 上传文件」进来时,落在对应文件夹里
1229
+ uploadFiles(event.target.files, state.importTarget || currentFolderId(current));
1230
+ event.target.value = '';
1231
+ patch({ importTarget: null });
1232
+ },
1233
+ }),
1234
+ h('button', {
1235
+ type: 'button', className: cx('dsh-kb-iconBtn', current.showSettings && 'dsh-kb-iconBtn--on'),
1236
+ title: '知识库设置',
1237
+ 'aria-pressed': Boolean(current.showSettings),
1238
+ onClick: () => patch({ showSettings: !state.showSettings }),
1239
+ }, h(Icon, { name: 'settings', size: 15 })))),
1240
+
1241
+ // 提示条
1242
+ current.notice || current.error
1243
+ ? h('div', { className: cx('dsh-kb-banner', current.error ? 'dsh-kb-banner--bad' : 'dsh-kb-banner--info') },
1244
+ h('span', null, current.error || current.notice),
1245
+ h('button', { type: 'button', className: 'dsh-kb-bannerClose', onClick: () => patch({ notice: '', error: '' }) },
1246
+ h(Icon, { name: 'close', size: 12 })))
1247
+ : null,
1248
+
1249
+ // 主体
1250
+ h('div', { className: 'dsh-kb-body' },
1251
+ current.sideOpen
1252
+ ? h('div', { className: 'dsh-kb-side' },
1253
+ current.loading
1254
+ ? h('div', { className: 'dsh-kb-hint' }, '加载中…')
1255
+ : current.kbs.length === 0
1256
+ ? h('div', { className: 'dsh-kb-empty dsh-kb-empty--side' },
1257
+ h('p', null, '还没有知识库。'),
1258
+ h('button', {
1259
+ type: 'button', className: 'dsh-kb-btn dsh-kb-btn--primary',
1260
+ onClick: () => createKb(),
1261
+ }, '新建知识库'))
1262
+ : h('div', { className: 'dsh-kb-tree' },
1263
+ h(TreeRows, { byParent: tree, parentKey: '', depth: 0 }),
1264
+ current.nodes.length === 0
1265
+ ? h('div', { className: 'dsh-kb-hint dsh-kb-hint--pad' }, '空知识库:上传文件,或新建文件夹。')
1266
+ : null))
1267
+ : null, // 收起时不再画左侧竖条:顶部的箭头按钮就是展开入口
1268
+ h('div', { className: 'dsh-kb-main' },
1269
+ current.showSettings
1270
+ ? h('div', { className: 'dsh-kb-settingsPane' },
1271
+ h('div', { className: 'dsh-kb-settingsHead' },
1272
+ h('div', { className: 'dsh-kb-docTitle' }, '知识库设置'),
1273
+ h('span', { className: 'dsh-kb-viewerGrow' }),
1274
+ h('button', {
1275
+ type: 'button', className: 'dsh-kb-btn',
1276
+ onClick: () => patch({ showSettings: false }),
1277
+ }, h(Icon, { name: 'chevron', size: 12, className: 'dsh-kb-rot180' }), '返回')),
1278
+ h(SettingsSection))
1279
+ : current.dashOpen
1280
+ ? h(Dashboard)
1281
+ : (current.view === 'search' && current.query ? h(SearchView) : h(DocView, { onAsk, onReindex, onDelete }))),
1282
+ ),
1283
+ h(Dialog),
1284
+ // 行操作菜单:fixed 定位,免得被树栏的滚动裁掉
1285
+ current.menu ? (() => {
1286
+ const node = current.nodes.find((entry) => entry.id === current.menu.id);
1287
+ if (!node) return null;
1288
+ const isFolder = node.kind === 'folder';
1289
+ const close = () => patch({ menu: null });
1290
+ const item = (label, onClick, danger) => h('button', {
1291
+ type: 'button', role: 'menuitem',
1292
+ className: cx('dsh-kb-menuItem', danger && 'dsh-kb-menuItem--danger'),
1293
+ onClick: (event) => {
1294
+ event?.stopPropagation?.();
1295
+ close();
1296
+ onClick();
1297
+ },
1298
+ }, label);
1299
+ return h(React.Fragment, null,
1300
+ h('div', { className: 'dsh-kb-menuBackdrop', onClick: close }),
1301
+ h('div', {
1302
+ className: 'dsh-kb-menu', role: 'menu',
1303
+ style: { left: `${current.menu.x}px`, top: `${current.menu.y}px` },
1304
+ },
1305
+ isFolder
1306
+ ? item('新建子文件夹', () => askText('新文件夹的名字', '新文件夹', (name) => nodeAction('create', {
1307
+ kbId: node.kbId, parentId: node.id, kind: 'folder', name,
1308
+ })))
1309
+ : null,
1310
+ // 文件夹传到自己这儿;文件传到它所在的文件夹 —— 任何一行都能上传
1311
+ item(isFolder ? '上传文件到这里' : '上传文件到所在文件夹', () => {
1312
+ patch({ importTarget: isFolder ? node.id : (node.parentId || null) });
1313
+ fileInput.current?.click();
1314
+ }),
1315
+ item('重命名', () => askText('重命名', node.name, (name) => nodeAction('rename', { id: node.id, name }))),
1316
+ item('移动到…', () => askMove(node)),
1317
+ item('删除', () => askConfirm(
1318
+ `删除「${node.name}」?${isFolder ? '里面的内容也会一起删除。' : '原文件也会被删掉。'}`,
1319
+ () => nodeAction('delete', { id: node.id }),
1320
+ ), true)));
1321
+ })() : null,
1322
+ current.bigView && current.doc ? h(BigView, { doc: current.doc }) : null);
1323
+ }
1324
+
1325
+ // ── 设置分区 ────────────────────────────────────────────────────────
1326
+ function SettingsSection() {
1327
+ const current = useStore();
1328
+ const [form, setForm] = React.useState(null);
1329
+ const [saving, setSaving] = React.useState(false);
1330
+ const [probing, setProbing] = React.useState(false);
1331
+ const [probe, setProbe] = React.useState(null);
1332
+ const [formNotice, setFormNotice] = React.useState('');
1333
+ // 图片理解(视觉模型)那一块自己的表单状态
1334
+ const [visionForm, setVisionForm] = React.useState(null);
1335
+ const [visionSaving, setVisionSaving] = React.useState(false);
1336
+ const [visionProbing, setVisionProbing] = React.useState(false);
1337
+ const [visionProbe, setVisionProbe] = React.useState(null);
1338
+ const [visionNotice, setVisionNotice] = React.useState('');
1339
+ const [rebuilding, setRebuilding] = React.useState(false);
1340
+ const watchRef = React.useRef(null);
1341
+
1342
+ const stopWatch = () => {
1343
+ if (watchRef.current) {
1344
+ clearInterval(watchRef.current);
1345
+ watchRef.current = null;
1346
+ }
1347
+ };
1348
+
1349
+ /** 点重建后每 1 秒刷一次状态,全部解析完就停。 */
1350
+ const startWatch = () => {
1351
+ stopWatch();
1352
+ watchRef.current = setInterval(async () => {
1353
+ try { await loadState(state.kbId, true); } catch { /* ignore */ }
1354
+ const progress = state.progress;
1355
+ if (!progress || (progress.pending + progress.parsing) === 0) {
1356
+ stopWatch();
1357
+ setRebuilding(false);
1358
+ }
1359
+ }, 1000);
1360
+ };
1361
+
1362
+ React.useEffect(() => () => stopWatch(), []);
1363
+
1364
+ const rebuildAll = async () => {
1365
+ if (rebuilding) return;
1366
+ try {
1367
+ const data = await api('/reindex-all', { method: 'POST' });
1368
+ patch({ notice: `已排队重建 ${data.queued} 篇文档的索引`, error: '' });
1369
+ setRebuilding(true);
1370
+ startWatch();
1371
+ } catch (error) {
1372
+ patch({ error: error.message || '重建失败' });
1373
+ }
1374
+ };
1375
+ React.useEffect(() => {
1376
+ if (!state.loaded) loadState();
1377
+ let cancelled = false;
1378
+ api('/settings')
1379
+ .then((data) => {
1380
+ if (cancelled) return;
1381
+ setForm({ ...data.embedding, apiKey: '' });
1382
+ setVisionForm({ ...(data.vision || { enabled: false, baseUrl: '', model: '' }), apiKey: '' });
1383
+ })
1384
+ .catch(() => {
1385
+ if (cancelled) return;
1386
+ setForm({ enabled: false, baseUrl: '', model: '', apiKey: '', hasKey: false, keyTail: '' });
1387
+ setVisionForm({ enabled: false, baseUrl: '', model: '', apiKey: '', hasKey: false, keyTail: '' });
1388
+ });
1389
+ return () => { cancelled = true; };
1390
+ }, []);
1391
+
1392
+ const saveVision = async () => {
1393
+ if (!visionForm || visionSaving) return;
1394
+ setVisionSaving(true);
1395
+ setVisionNotice('');
1396
+ try {
1397
+ const data = await api('/settings', {
1398
+ method: 'POST',
1399
+ headers: { 'content-type': 'application/json' },
1400
+ body: JSON.stringify({
1401
+ vision: {
1402
+ enabled: Boolean(visionForm.enabled),
1403
+ baseUrl: visionForm.baseUrl,
1404
+ model: visionForm.model,
1405
+ apiKey: visionForm.apiKey,
1406
+ },
1407
+ }),
1408
+ });
1409
+ setVisionForm({ ...(data.vision || {}), apiKey: '' });
1410
+ setVisionNotice('已保存,立即生效');
1411
+ await loadState(state.kbId, true);
1412
+ } catch (error) {
1413
+ setVisionNotice(`保存失败:${error.message || error}`);
1414
+ } finally {
1415
+ setVisionSaving(false);
1416
+ }
1417
+ };
1418
+
1419
+ const testVision = async () => {
1420
+ if (!visionForm || visionProbing) return;
1421
+ setVisionProbing(true);
1422
+ setVisionProbe(null);
1423
+ try {
1424
+ const data = await api('/vision-test', {
1425
+ method: 'POST',
1426
+ headers: { 'content-type': 'application/json' },
1427
+ body: JSON.stringify({ baseUrl: visionForm.baseUrl, model: visionForm.model, apiKey: visionForm.apiKey }),
1428
+ });
1429
+ setVisionProbe(data.probe || { ok: false, error: '没有返回结果' });
1430
+ } catch (error) {
1431
+ setVisionProbe({ ok: false, error: error.message || String(error) });
1432
+ } finally {
1433
+ setVisionProbing(false);
1434
+ }
1435
+ };
1436
+
1437
+ const saveEmbedding = async () => {
1438
+ if (!form || saving) return;
1439
+ setSaving(true);
1440
+ setFormNotice('');
1441
+ try {
1442
+ const data = await api('/settings', {
1443
+ method: 'POST',
1444
+ headers: { 'content-type': 'application/json' },
1445
+ body: JSON.stringify({
1446
+ embedding: {
1447
+ enabled: Boolean(form.enabled),
1448
+ baseUrl: form.baseUrl,
1449
+ model: form.model,
1450
+ apiKey: form.apiKey,
1451
+ },
1452
+ }),
1453
+ });
1454
+ setForm({ ...data.embedding, apiKey: '' });
1455
+ setFormNotice('已保存,立即生效');
1456
+ await loadState(state.kbId, true);
1457
+ } catch (error) {
1458
+ setFormNotice(`保存失败:${error.message || error}`);
1459
+ } finally {
1460
+ setSaving(false);
1461
+ }
1462
+ };
1463
+
1464
+ const testEmbedding = async () => {
1465
+ if (!form || probing) return;
1466
+ setProbing(true);
1467
+ setProbe(null);
1468
+ try {
1469
+ const data = await api('/embedding-test', {
1470
+ method: 'POST',
1471
+ headers: { 'content-type': 'application/json' },
1472
+ body: JSON.stringify({ baseUrl: form.baseUrl, model: form.model, apiKey: form.apiKey }),
1473
+ });
1474
+ setProbe(data.probe || { ok: false, error: '没有返回结果' });
1475
+ } catch (error) {
1476
+ setProbe({ ok: false, error: error.message || String(error) });
1477
+ } finally {
1478
+ setProbing(false);
1479
+ }
1480
+ };
1481
+
1482
+ const stats = current.stats;
1483
+ const embedding = current.caps?.embedding;
1484
+ return h('div', { className: 'dsh-kb-settings' },
1485
+ h('p', { className: 'dsh-kb-settingsIntro' },
1486
+ '知识库存放在本机:文件是真实文件,索引是本地 SQLite 全文索引。插件不会把内容上传到任何服务(除非你自己打开了向量检索)。'),
1487
+ h('section', { className: 'dsh-kb-card' },
1488
+ h('h4', null, '存放目录'),
1489
+ h('code', { className: 'dsh-kb-code' }, current.root || '(未初始化)'),
1490
+ h('p', { className: 'dsh-kb-hint' },
1491
+ '想换位置:在插件配置里设置 ',
1492
+ h('code', null, 'root'),
1493
+ '(插件页 → 知识库 → 配置),重启后生效。已有文件不会自动搬迁。')),
1494
+ h('section', { className: 'dsh-kb-card' },
1495
+ h('h4', null, '索引状态'),
1496
+ stats
1497
+ ? h('div', { className: 'dsh-kb-kv' },
1498
+ h('span', null, '知识库'), h('strong', null, stats.kbs),
1499
+ h('span', null, '文档'), h('strong', null, stats.docs),
1500
+ h('span', null, '检索片段'), h('strong', null, stats.chunks),
1501
+ h('span', null, '总大小'), h('strong', null, bytes(stats.bytes)),
1502
+ h('span', null, '向量'), h('strong', null, stats.vectors))
1503
+ : h('p', { className: 'dsh-kb-hint' }, '读取中…'),
1504
+ (() => {
1505
+ const progress = current.progress;
1506
+ if (!progress) return null;
1507
+ const working = progress.pending + progress.parsing;
1508
+ if (!rebuilding && working === 0) return null;
1509
+ const pct = progress.total ? Math.round((progress.done / progress.total) * 100) : 0;
1510
+ return h('div', { className: 'dsh-kb-progress', role: 'status' },
1511
+ h('div', { className: 'dsh-kb-progressTrack' },
1512
+ h('div', { className: 'dsh-kb-progressFill', style: { width: `${pct}%` } })),
1513
+ h('div', { className: 'dsh-kb-progressText' },
1514
+ working > 0
1515
+ ? `重建中:已完成 ${progress.done} / ${progress.total} 篇`
1516
+ + `${progress.parsing ? ` · 解析中 ${progress.parsing}` : ''}`
1517
+ + `${progress.queued ? ` · 排队 ${progress.queued}` : ''}`
1518
+ : `重建完成:${progress.done} / ${progress.total} 篇`));
1519
+ })(),
1520
+ h('div', { className: 'dsh-kb-row2' },
1521
+ h('button', {
1522
+ type: 'button', className: 'dsh-kb-btn',
1523
+ onClick: rebuildAll, disabled: rebuilding,
1524
+ }, h(Icon, { name: 'refresh', size: 14 }), rebuilding ? '重建中…' : '重建全部索引'),
1525
+ h('button', {
1526
+ type: 'button', className: 'dsh-kb-btn',
1527
+ onClick: () => loadState(current.kbId, true),
1528
+ }, '刷新'),
1529
+ h('button', {
1530
+ type: 'button', className: 'dsh-kb-btn',
1531
+ title: '删掉转换出来的 PDF 和逐页图片(下次打开会重新生成)',
1532
+ onClick: async () => {
1533
+ try {
1534
+ const data = await api('/purge-previews', { method: 'POST' });
1535
+ patch({ notice: `已清理 ${data.cleared} 篇文档的预览缓存`, previewInfo: null });
1536
+ } catch (error) {
1537
+ patch({ error: error.message || '清理失败' });
1538
+ }
1539
+ },
1540
+ }, '清理预览缓存'))),
1541
+ h('section', { className: 'dsh-kb-card' },
1542
+ h('h4', null, '向量检索(可选)'),
1543
+ h('p', { className: 'dsh-kb-hint' },
1544
+ '关键词检索已经可用。想让「意思相近但用词不同」也能命中,接一个 OpenAI 兼容的 embeddings 接口 —— DeepSeek 官方没有这个接口,可以接百炼 / 硅基流动 / Ollama。'),
1545
+ form
1546
+ ? h('div', { className: 'dsh-kb-form' },
1547
+ h('label', { className: 'dsh-kb-check' },
1548
+ h('input', {
1549
+ type: 'checkbox',
1550
+ checked: Boolean(form.enabled),
1551
+ onChange: (event) => setForm({ ...form, enabled: event.target.checked }),
1552
+ }),
1553
+ '启用向量检索'),
1554
+ h('label', { className: 'dsh-kb-field' },
1555
+ h('span', { className: 'dsh-kb-label' }, '接口地址'),
1556
+ h('input', {
1557
+ type: 'text',
1558
+ value: form.baseUrl || '',
1559
+ placeholder: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
1560
+ onChange: (event) => setForm({ ...form, baseUrl: event.target.value }),
1561
+ }),
1562
+ h('span', { className: 'dsh-kb-hint' }, '填到 /v1 为止,不要带 /embeddings')),
1563
+ h('label', { className: 'dsh-kb-field' },
1564
+ h('span', { className: 'dsh-kb-label' }, '模型'),
1565
+ h('input', {
1566
+ type: 'text',
1567
+ value: form.model || '',
1568
+ placeholder: 'text-embedding-v3',
1569
+ onChange: (event) => setForm({ ...form, model: event.target.value }),
1570
+ })),
1571
+ h('label', { className: 'dsh-kb-field' },
1572
+ h('span', { className: 'dsh-kb-label' }, 'API Key'),
1573
+ h('input', {
1574
+ type: 'password',
1575
+ value: form.apiKey || '',
1576
+ placeholder: form.hasKey ? `已保存(尾号 ${form.keyTail}),留空表示不改` : '接口不需要鉴权就留空',
1577
+ onChange: (event) => setForm({ ...form, apiKey: event.target.value }),
1578
+ }),
1579
+ h('span', { className: 'dsh-kb-hint' }, '只存在本机 ~/.dsh/kb/settings.json,不会写进插件配置')),
1580
+ h('div', { className: 'dsh-kb-row2' },
1581
+ h('button', {
1582
+ type: 'button', className: 'dsh-kb-btn dsh-kb-btn--primary',
1583
+ onClick: saveEmbedding, disabled: saving,
1584
+ }, saving ? '保存中…' : '保存'),
1585
+ h('button', {
1586
+ type: 'button', className: 'dsh-kb-btn',
1587
+ onClick: testEmbedding, disabled: probing,
1588
+ }, probing ? '测试中…' : '测试连接')),
1589
+ probe
1590
+ ? h('div', { className: cx('dsh-kb-banner', probe.ok ? 'dsh-kb-banner--ok' : 'dsh-kb-banner--bad'), role: 'status' },
1591
+ probe.ok ? `连接成功:返回 ${probe.dim} 维向量(${probe.model})` : `连接失败:${probe.error}`)
1592
+ : null,
1593
+ formNotice ? h('p', { className: 'dsh-kb-hint' }, formNotice) : null,
1594
+ form.enabled && (stats?.vectors || 0) === 0 && embedding?.enabled
1595
+ ? h('p', { className: 'dsh-kb-hint' }, '已启用,但现有文档还没有向量 —— 点上面「重建全部索引」补上(只补新增文档不算)。')
1596
+ : null)
1597
+ : h('p', { className: 'dsh-kb-hint' }, '读取配置中…'),
1598
+ embedding?.enabled
1599
+ ? h('p', { className: 'dsh-kb-hint' }, `当前状态:已启用 · 模型 ${embedding.model} · 检索时与关键词结果融合(RRF)`)
1600
+ : null),
1601
+ // ── 图片理解(视觉模型)──────────────────────────────────────
1602
+ h('section', { className: 'dsh-kb-card' },
1603
+ h('h4', null, '图片理解(可选)'),
1604
+ h('p', { className: 'dsh-kb-hint' },
1605
+ '图片本身没有文字,所以默认搜不到。打开这里,上传或重建时会用视觉模型把图「描述成文字」,再走同一套关键词 + 向量检索 —— 命中后 AI 也能读出图里写了什么。'),
1606
+ visionForm
1607
+ ? h('div', { className: 'dsh-kb-form' },
1608
+ h('label', { className: 'dsh-kb-check' },
1609
+ h('input', {
1610
+ type: 'checkbox',
1611
+ checked: Boolean(visionForm.enabled),
1612
+ onChange: (event) => setVisionForm({ ...visionForm, enabled: event.target.checked }),
1613
+ }),
1614
+ '启用图片理解'),
1615
+ h('label', { className: 'dsh-kb-field' },
1616
+ h('span', { className: 'dsh-kb-label' }, '接口地址'),
1617
+ h('input', {
1618
+ type: 'text',
1619
+ value: visionForm.baseUrl || '',
1620
+ placeholder: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
1621
+ onChange: (event) => setVisionForm({ ...visionForm, baseUrl: event.target.value }),
1622
+ }),
1623
+ h('span', { className: 'dsh-kb-hint' }, '和向量检索一样填到 /v1 为止')),
1624
+ h('label', { className: 'dsh-kb-field' },
1625
+ h('span', { className: 'dsh-kb-label' }, '视觉模型'),
1626
+ h('input', {
1627
+ type: 'text',
1628
+ value: visionForm.model || '',
1629
+ placeholder: 'qwen3-vl-plus',
1630
+ onChange: (event) => setVisionForm({ ...visionForm, model: event.target.value }),
1631
+ }),
1632
+ h('span', { className: 'dsh-kb-hint' }, '百炼用 qwen3-vl-plus;OpenAI 用 gpt-4o-mini 也行')),
1633
+ h('label', { className: 'dsh-kb-field' },
1634
+ h('span', { className: 'dsh-kb-label' }, 'API Key'),
1635
+ h('input', {
1636
+ type: 'password',
1637
+ value: visionForm.apiKey || '',
1638
+ placeholder: visionForm.hasKey
1639
+ ? `已保存(尾号 ${visionForm.keyTail}),留空表示不改`
1640
+ : '留空则复用向量检索那把 Key',
1641
+ onChange: (event) => setVisionForm({ ...visionForm, apiKey: event.target.value }),
1642
+ })),
1643
+ h('div', { className: 'dsh-kb-row2' },
1644
+ h('button', {
1645
+ type: 'button', className: 'dsh-kb-btn dsh-kb-btn--primary',
1646
+ onClick: saveVision, disabled: visionSaving,
1647
+ }, visionSaving ? '保存中…' : '保存'),
1648
+ h('button', {
1649
+ type: 'button', className: 'dsh-kb-btn',
1650
+ onClick: testVision, disabled: visionProbing,
1651
+ }, visionProbing ? '测试中…' : '测试连接')),
1652
+ visionProbe
1653
+ ? h('div', { className: cx('dsh-kb-banner', visionProbe.ok ? 'dsh-kb-banner--ok' : 'dsh-kb-banner--bad'), role: 'status' },
1654
+ visionProbe.ok
1655
+ ? `连接成功:${visionProbe.model} · ${visionProbe.ms} ms · 返回「${visionProbe.sample || ''}…」`
1656
+ : `连接失败:${visionProbe.error}`)
1657
+ : null,
1658
+ visionNotice ? h('p', { className: 'dsh-kb-hint' }, visionNotice) : null,
1659
+ visionForm.enabled && !current.caps?.vision?.enabled
1660
+ ? h('p', { className: 'dsh-kb-hint' }, '已勾选但还没生效:检查接口地址和模型,保存后这里会显示「已启用」。')
1661
+ : null)
1662
+ : h('p', { className: 'dsh-kb-hint' }, '读取配置中…'),
1663
+ current.caps?.vision?.enabled
1664
+ ? h('p', { className: 'dsh-kb-hint' },
1665
+ `当前状态:已启用 · 模型 ${current.caps.vision.model} · 新建或重建索引时会把图片描述成文字`)
1666
+ : h('p', { className: 'dsh-kb-hint' }, '当前状态:未启用(图片只能看,搜不到)')),
1667
+ current.error
1668
+ ? h('p', { className: 'dsh-kb-banner dsh-kb-banner--bad', role: 'alert' }, current.error)
1669
+ : null,
1670
+ current.notice ? h('p', { className: 'dsh-kb-hint' }, current.notice) : null);
1671
+ }
1672
+
1673
+ // ── 左侧栏图标 ──────────────────────────────────────────────────────
1674
+ function PanelIcon({ size, active }) {
1675
+ return h('span', { className: cx('dsh-kb-barIcon', active && 'dsh-kb-barIcon--active'), 'aria-hidden': 'true' },
1676
+ h(Icon, { name: 'book', size: size || 18 }));
1677
+ }
1678
+
1679
+ // ── 样式(只用 --dsw-alias-* token,跟随明暗主题)─────────────────────
1680
+ function installStyles() {
1681
+ const style = document.createElement('style');
1682
+ style.id = 'dsh-plugin-knowledge-base-styles';
1683
+ style.textContent = [
1684
+ '.dsh-kb-barIcon{display:inline-flex;align-items:center;justify-content:center;color:inherit;opacity:.8;}',
1685
+ '.dsh-kb-page{position:relative;display:flex;flex-direction:column;height:100%;min-height:0;font-size:13px;color:var(--dsw-alias-label-primary);background:var(--dsw-alias-bg-layer-1);}',
1686
+ '.dsh-kb-page--drag{outline:2px dashed var(--dsw-alias-label-brand,#1f6feb);outline-offset:-8px;}',
1687
+ '.dsh-kb-head{display:flex;align-items:center;gap:10px;padding:10px 16px;border-bottom:1px solid var(--dsw-alias-border-l1);flex-wrap:wrap;}',
1688
+ '.dsh-kb-brand{display:flex;align-items:center;gap:6px;min-width:0;}',
1689
+ '.dsh-kb-brandIcon{display:inline-flex;color:var(--dsw-alias-label-brand,#1f6feb);}',
1690
+ '.dsh-kb-select{max-width:200px;height:28px;border:1px solid var(--dsw-alias-border-l1);border-radius:8px;background:var(--dsw-alias-bg-layer-2);color:inherit;font:inherit;font-size:12.5px;padding:0 6px;}',
1691
+ '.dsh-kb-iconBtn{display:inline-flex;align-items:center;justify-content:center;width:26px;height:26px;border:none;border-radius:7px;background:transparent;color:var(--dsw-alias-label-secondary);cursor:pointer;}',
1692
+ '.dsh-kb-iconBtn:hover{background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-primary);}',
1693
+ '.dsh-kb-searchBox{position:relative;display:flex;align-items:center;flex:1;min-width:180px;max-width:420px;}',
1694
+ '.dsh-kb-searchIcon{position:absolute;left:9px;color:var(--dsw-alias-label-secondary);pointer-events:none;}',
1695
+ '.dsh-kb-searchInput{width:100%;height:28px;padding:0 26px 0 28px;border:1px solid var(--dsw-alias-border-l1);border-radius:8px;background:var(--dsw-alias-bg-layer-2);color:inherit;font:inherit;font-size:12.5px;}',
1696
+ '.dsh-kb-searchInput:focus{outline:none;border-color:var(--dsw-alias-label-brand,#1f6feb);}',
1697
+ '.dsh-kb-searchClear{position:absolute;right:7px;border:none;background:transparent;color:var(--dsw-alias-label-secondary);cursor:pointer;padding:0;display:inline-flex;}',
1698
+ '.dsh-kb-headActions{display:flex;gap:6px;margin-left:auto;}',
1699
+ '.dsh-kb-btn{display:inline-flex;align-items:center;gap:5px;height:28px;padding:0 10px;border:1px solid var(--dsw-alias-border-l1);border-radius:8px;background:transparent;color:var(--dsw-alias-label-primary);font:inherit;font-size:12.5px;cursor:pointer;text-decoration:none;white-space:nowrap;}',
1700
+ '.dsh-kb-btn:hover{background:var(--dsw-alias-bg-layer-2);}',
1701
+ '.dsh-kb-btn:disabled{opacity:.5;cursor:default;}',
1702
+ '.dsh-kb-btn--primary{border-color:transparent;background:var(--dsw-alias-label-brand,#1f6feb);color:#fff;}',
1703
+ '.dsh-kb-btn--primary:hover{filter:brightness(1.06);background:var(--dsw-alias-label-brand,#1f6feb);}',
1704
+ '.dsh-kb-btn--danger{color:var(--dsw-alias-label-danger,#d14343);}',
1705
+ '.dsh-kb-banner{display:flex;align-items:center;gap:8px;padding:7px 16px;font-size:12px;border-bottom:1px solid var(--dsw-alias-border-l1);}',
1706
+ '.dsh-kb-banner--info{background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-secondary);}',
1707
+ '.dsh-kb-banner--bad{background:rgba(209,67,67,.10);color:var(--dsw-alias-label-danger,#d14343);}',
1708
+ '.dsh-kb-bannerClose{margin-left:auto;border:none;background:transparent;color:inherit;cursor:pointer;display:inline-flex;}',
1709
+ '.dsh-kb-body{display:flex;flex:1;min-height:0;}',
1710
+ '.dsh-kb-side{width:250px;flex:none;border-right:1px solid var(--dsw-alias-border-l1);overflow-y:auto;padding:6px 0 20px;}',
1711
+ '.dsh-kb-rot180{transform:rotate(180deg);}',
1712
+ '.dsh-kb-moreBtn{font-size:15px;line-height:1;letter-spacing:1px;padding-bottom:3px;}',
1713
+ '.dsh-kb-rowBtn--on{background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-primary);}',
1714
+ '.dsh-kb-menuBackdrop{position:fixed;inset:0;z-index:40;}',
1715
+ '.dsh-kb-menu{position:fixed;z-index:41;width:184px;padding:4px;border:1px solid var(--dsw-alias-border-l1);border-radius:10px;background:var(--dsw-alias-bg-layer-1);box-shadow:0 10px 28px rgba(0,0,0,.3);display:flex;flex-direction:column;}',
1716
+ '.dsh-kb-menuItem{display:flex;align-items:center;height:30px;padding:0 10px;border:none;border-radius:7px;background:transparent;color:var(--dsw-alias-label-primary);font:inherit;font-size:12.5px;text-align:left;cursor:pointer;}',
1717
+ '.dsh-kb-menuItem:hover{background:var(--dsw-alias-bg-layer-2);}',
1718
+ '.dsh-kb-menuItem--danger{color:var(--dsw-alias-label-danger,#d14343);}',
1719
+ '.dsh-kb-tree{display:flex;flex-direction:column;}',
1720
+ '.dsh-kb-row{display:flex;align-items:center;gap:5px;height:28px;padding-right:8px;cursor:pointer;color:var(--dsw-alias-label-primary);border-radius:6px;margin:0 6px;}',
1721
+ '.dsh-kb-row:hover{background:var(--dsw-alias-bg-layer-2);}',
1722
+ '.dsh-kb-row--active{background:var(--dsw-alias-bg-layer-2);box-shadow:inset 2px 0 0 var(--dsw-alias-label-brand,#1f6feb);}',
1723
+ '.dsh-kb-caret{display:inline-flex;width:12px;color:var(--dsw-alias-label-secondary);transition:transform .12s ease;}',
1724
+ '.dsh-kb-caret--open{transform:rotate(90deg);}',
1725
+ '.dsh-kb-rowIcon{display:inline-flex;color:var(--dsw-alias-label-secondary);flex:none;}',
1726
+ '.dsh-kb-rowName{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}',
1727
+ '.dsh-kb-dot{width:6px;height:6px;border-radius:50%;flex:none;}',
1728
+ '.dsh-kb-dot--busy{background:var(--dsw-alias-label-warning,#d9a441);}',
1729
+ '.dsh-kb-dot--bad{background:var(--dsw-alias-label-danger,#d14343);}',
1730
+ '.dsh-kb-main{flex:1;min-width:0;display:flex;flex-direction:column;overflow:hidden;}',
1731
+ '.dsh-kb-empty{display:flex;flex-direction:column;align-items:flex-start;gap:6px;padding:40px 28px;color:var(--dsw-alias-label-secondary);}',
1732
+ '.dsh-kb-empty--side{padding:18px 16px;}',
1733
+ '.dsh-kb-emptyIcon{color:var(--dsw-alias-border-l1);}',
1734
+ '.dsh-kb-hint{font-size:12px;line-height:1.6;color:var(--dsw-alias-label-secondary);}',
1735
+ '.dsh-kb-hint--pad{padding:10px 14px;}',
1736
+ '.dsh-kb-doc{display:flex;flex-direction:column;flex:1;min-height:0;}',
1737
+ '.dsh-kb-docHead{padding:14px 20px 0;}',
1738
+ '.dsh-kb-docTitle{font-size:15px;font-weight:600;word-break:break-word;}',
1739
+ '.dsh-kb-docMeta{display:flex;gap:10px;flex-wrap:wrap;margin-top:4px;font-size:12px;color:var(--dsw-alias-label-secondary);}',
1740
+ '.dsh-kb-docActions{display:flex;gap:6px;flex-wrap:wrap;padding:10px 20px 0;}',
1741
+ '.dsh-kb-reader{flex:1;min-height:0;overflow-y:auto;padding:12px 24px 40px;}',
1742
+ // 视觉阅读(PDF / Office):铺满整块区域,去掉内边距和外框,让阅读器自己占满
1743
+ '.dsh-kb-reader--visual{display:flex;flex-direction:column;padding:0;overflow:hidden;}',
1744
+ '.dsh-kb-reader--visual .dsh-kb-frame{flex:1 1 auto;width:100%;height:100%;min-height:0;border:none;border-radius:0;background:transparent;}',
1745
+ '.dsh-kb-reader--visual .dsh-kb-frameWrap{flex:1 1 auto;min-height:0;display:flex;}',
1746
+ '.dsh-kb-reader--visual .dsh-kb-frameLoading{border:none;border-radius:0;}',
1747
+ // 逐页图片阅读器(Office):自己画,不套浏览器 PDF 阅读器
1748
+ '.dsh-kb-pages{flex:1;min-height:0;overflow-y:auto;padding:16px 18px 32px;display:flex;flex-direction:column;align-items:center;gap:14px;background:var(--dsw-alias-bg-layer-2);}',
1749
+ '.dsh-kb-pageShot{position:relative;width:min(100%,1180px);}',
1750
+ '.dsh-kb-pageImg{display:block;width:100%;height:auto;border-radius:6px;background:#fff;box-shadow:0 2px 10px rgba(0,0,0,.18);}',
1751
+ '.dsh-kb-pageNo{position:absolute;left:8px;top:8px;padding:1px 7px;border-radius:999px;background:rgba(0,0,0,.55);color:#fff;font-size:11px;line-height:1.6;}',
1752
+ '.dsh-kb-pagesNote{font-size:12px;color:var(--dsw-alias-label-secondary);padding:2px 4px 6px;text-align:center;}',
1753
+ '.dsh-kb-viewer{display:flex;flex-direction:column;flex:1;min-height:0;}',
1754
+ '.dsh-kb-viewerBar{display:flex;flex:none;align-items:center;gap:6px;padding:6px 12px;border-bottom:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-layer-1);}',
1755
+ '.dsh-kb-viewerGrow{flex:1;min-width:8px;}',
1756
+ '.dsh-kb-navBtn{display:inline-flex;align-items:center;justify-content:center;width:24px;height:24px;padding:0;border:1px solid var(--dsw-alias-border-l1);border-radius:6px;background:transparent;color:inherit;font-size:15px;line-height:1;cursor:pointer;}',
1757
+ '.dsh-kb-navBtn:hover:not(:disabled){background:var(--dsw-alias-bg-layer-2);}',
1758
+ '.dsh-kb-navBtn:disabled{opacity:.4;cursor:default;}',
1759
+ '.dsh-kb-pageInput{width:46px;height:24px;padding:0;text-align:center;border:1px solid var(--dsw-alias-border-l1);border-radius:6px;background:var(--dsw-alias-bg-layer-2);color:inherit;font:inherit;font-size:12px;}',
1760
+ '.dsh-kb-pageInput:focus{outline:none;border-color:var(--dsw-alias-label-brand,#1f6feb);}',
1761
+ '.dsh-kb-pageTotal{font-size:12px;color:var(--dsw-alias-label-secondary);white-space:nowrap;}',
1762
+ '.dsh-kb-pages--single{align-items:center;justify-content:center;padding:12px;overflow:hidden;}',
1763
+ '.dsh-kb-pages--single .dsh-kb-pageShot{width:100%;height:100%;max-width:1180px;display:flex;align-items:center;justify-content:center;}',
1764
+ '.dsh-kb-pages--single .dsh-kb-pageImg{width:100%;height:100%;object-fit:contain;border-radius:0;box-shadow:none;background:transparent;}',
1765
+ '.dsh-kb-pages--single .dsh-kb-pageNo{display:none;}',
1766
+ '.dsh-kb-viewerBody{display:flex;flex:1;min-height:0;}',
1767
+ '.dsh-kb-thumbs{flex:none;width:118px;overflow-y:auto;padding:8px 6px 16px;display:flex;flex-direction:column;gap:8px;border-right:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-layer-1);}',
1768
+ '.dsh-kb-thumb{position:relative;display:block;padding:0;margin:0;border:2px solid transparent;border-radius:6px;background:transparent;cursor:pointer;line-height:0;}',
1769
+ '.dsh-kb-thumb:hover{border-color:var(--dsw-alias-border-l1);}',
1770
+ '.dsh-kb-thumb--on{border-color:var(--dsw-alias-label-brand,#1f6feb);}',
1771
+ '.dsh-kb-thumbImg{display:block;width:100%;height:auto;border-radius:4px;background:#fff;}',
1772
+ '.dsh-kb-thumbNo{position:absolute;right:3px;bottom:3px;padding:0 4px;border-radius:4px;background:rgba(0,0,0,.55);color:#fff;font-size:10px;line-height:1.6;}',
1773
+ '.dsh-kb-pagesLoading{flex:1;min-height:320px;display:flex;align-items:center;justify-content:center;gap:8px;padding:0 24px;text-align:center;color:var(--dsw-alias-label-secondary);font-size:12.5px;line-height:1.6;background:var(--dsw-alias-bg-layer-2);}',
1774
+ '.dsh-kb-text{max-width:820px;font-size:13.5px;line-height:1.78;}',
1775
+ '.dsh-kb-p{margin:0 0 10px;white-space:pre-wrap;word-break:break-word;}',
1776
+ '.dsh-kb-h{margin:16px 0 8px;font-weight:600;}',
1777
+ '.dsh-kb-h1{font-size:16px;}.dsh-kb-h2{font-size:15px;}.dsh-kb-h3{font-size:14px;}.dsh-kb-h4,.dsh-kb-h5,.dsh-kb-h6{font-size:13.5px;}',
1778
+ '.dsh-kb-pageMark{margin:14px 0 6px;font-size:11.5px;color:var(--dsw-alias-label-secondary);letter-spacing:.04em;}',
1779
+ '.dsh-kb-tablerow{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:12px;white-space:pre-wrap;word-break:break-all;color:var(--dsw-alias-label-secondary);}',
1780
+ '.dsh-kb-mark{background:rgba(217,164,65,.32);color:inherit;border-radius:2px;}',
1781
+ '.dsh-kb-image{max-width:100%;border-radius:10px;border:1px solid var(--dsw-alias-border-l1);}',
1782
+ '.dsh-kb-frame{width:100%;height:100%;min-height:520px;border:1px solid var(--dsw-alias-border-l1);border-radius:10px;background:#fff;}', '.dsh-kb-frame--pending{opacity:0;}',
1783
+ '.dsh-kb-frameWrap{position:relative;flex:1;min-height:520px;display:flex;}',
1784
+ '.dsh-kb-frameLoading{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;gap:8px;padding:0 24px;text-align:center;border:1px solid var(--dsw-alias-border-l1);border-radius:10px;background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-secondary);font-size:12.5px;line-height:1.6;}',
1785
+ '.dsh-kb-spinner{width:14px;height:14px;flex:none;border-radius:50%;border:2px solid var(--dsw-alias-border-l1);border-top-color:var(--dsw-alias-label-brand,#1f6feb);animation:dsh-kb-spin .8s linear infinite;}',
1786
+ '@keyframes dsh-kb-spin{to{transform:rotate(360deg);}}',
1787
+ '.dsh-kb-seg{display:inline-flex;align-items:center;gap:2px;padding:2px;border:1px solid var(--dsw-alias-border-l1);border-radius:8px;}',
1788
+ '.dsh-kb-segBtn{height:22px;padding:0 9px;border:none;border-radius:6px;background:transparent;color:var(--dsw-alias-label-secondary);font:inherit;font-size:12px;cursor:pointer;}',
1789
+ '.dsh-kb-segBtn--on{background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-primary);font-weight:600;}',
1790
+ '.dsh-kb-more{margin-top:14px;}',
1791
+ '.dsh-kb-hits{display:flex;flex-direction:column;gap:8px;padding:14px 20px 30px;overflow-y:auto;}',
1792
+ '.dsh-kb-hitsHead{font-size:12px;color:var(--dsw-alias-label-secondary);}',
1793
+ '.dsh-kb-hit{display:flex;flex-direction:column;gap:4px;text-align:left;padding:10px 12px;border:1px solid var(--dsw-alias-border-l1);border-radius:10px;background:transparent;color:inherit;font:inherit;cursor:pointer;}',
1794
+ '.dsh-kb-hit:hover{background:var(--dsw-alias-bg-layer-2);}',
1795
+ '.dsh-kb-hitName{font-size:12.5px;font-weight:600;}',
1796
+ '.dsh-kb-hitHead{font-weight:400;color:var(--dsw-alias-label-secondary);}',
1797
+ '.dsh-kb-hitSnippet{font-size:12px;line-height:1.6;color:var(--dsw-alias-label-secondary);white-space:pre-wrap;}',
1798
+ '.dsh-kb-settings{display:flex;flex-direction:column;gap:14px;}',
1799
+ '.dsh-kb-settingsPane{display:flex;flex-direction:column;flex:1;min-height:0;padding:14px 20px 36px;overflow-y:auto;}',
1800
+ '.dsh-kb-settingsHead{display:flex;align-items:center;gap:10px;margin-bottom:14px;}',
1801
+ '.dsh-kb-iconBtn--on{background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-primary);}',
1802
+ '.dsh-kb-settingsIntro{margin:0;font-size:12px;line-height:1.6;color:var(--dsw-alias-label-secondary);}',
1803
+ '.dsh-kb-card{display:flex;flex-direction:column;gap:8px;padding:14px;border:1px solid var(--dsw-alias-border-l1);border-radius:12px;}',
1804
+ '.dsh-kb-card h4{margin:0;font-size:13px;font-weight:600;}',
1805
+ '.dsh-kb-code{display:block;padding:7px 9px;border-radius:8px;background:var(--dsw-alias-bg-layer-2);font-family:ui-monospace,Menlo,monospace;font-size:11.5px;word-break:break-all;}',
1806
+ '.dsh-kb-kv{display:grid;grid-template-columns:auto 1fr auto 1fr;gap:6px 12px;font-size:12px;color:var(--dsw-alias-label-secondary);align-items:center;}',
1807
+ '.dsh-kb-kv strong{color:var(--dsw-alias-label-primary);font-weight:600;}',
1808
+ '.dsh-kb-row2{display:flex;gap:8px;}',
1809
+ '.dsh-kb-form{display:flex;flex-direction:column;gap:10px;}',
1810
+ '.dsh-kb-check{display:flex;align-items:center;gap:7px;font-size:12.5px;cursor:pointer;}',
1811
+ '.dsh-kb-check input{width:14px;height:14px;margin:0;}',
1812
+ '.dsh-kb-field{display:flex;flex-direction:column;gap:4px;}',
1813
+ '.dsh-kb-label{font-size:11.5px;color:var(--dsw-alias-label-secondary);}',
1814
+ '.dsh-kb-form input[type=text],.dsh-kb-form input[type=password]{box-sizing:border-box;width:100%;height:30px;padding:0 9px;border:1px solid var(--dsw-alias-border-l1);border-radius:8px;background:var(--dsw-alias-bg-layer-2);color:inherit;font:inherit;font-size:12.5px;}',
1815
+ '.dsh-kb-form input:focus{outline:none;border-color:var(--dsw-alias-label-brand,#1f6feb);}',
1816
+ '.dsh-kb-banner--ok{background:rgba(34,160,90,.12);color:#228a4e;}',
1817
+ '.dsh-kb-progress{display:flex;flex-direction:column;gap:5px;margin:2px 0 4px;}',
1818
+ '.dsh-kb-progressTrack{height:6px;border-radius:999px;background:var(--dsw-alias-bg-layer-2);overflow:hidden;}',
1819
+ '.dsh-kb-progressFill{height:100%;border-radius:999px;background:var(--dsw-alias-label-brand,#1f6feb);transition:width .25s ease;}',
1820
+ '.dsh-kb-progressText{font-size:11.5px;color:var(--dsw-alias-label-secondary);}',
1821
+ // 看板
1822
+ '.dsh-kb-dash{display:flex;flex-direction:column;gap:14px;flex:1;min-height:0;overflow-y:auto;padding:16px 20px 36px;}',
1823
+ '.dsh-kb-dashHead{display:flex;align-items:center;gap:10px;flex-wrap:wrap;}',
1824
+ '.dsh-kb-metrics{display:grid;grid-template-columns:repeat(auto-fit,minmax(120px,1fr));gap:10px;}',
1825
+ '.dsh-kb-metric{display:flex;flex-direction:column;gap:2px;padding:12px 14px;border:1px solid var(--dsw-alias-border-l1);border-radius:12px;background:var(--dsw-alias-bg-layer-2);}',
1826
+ '.dsh-kb-metricLabel{font-size:11.5px;color:var(--dsw-alias-label-secondary);}',
1827
+ '.dsh-kb-metricValue{font-size:20px;font-weight:700;line-height:1.3;}',
1828
+ '.dsh-kb-metricHint{font-size:11px;color:var(--dsw-alias-label-secondary);}',
1829
+ '.dsh-kb-dashGrid{display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:12px;align-items:start;}',
1830
+ '.dsh-kb-subHead{margin-top:12px!important;}',
1831
+ '.dsh-kb-distRow{display:flex;align-items:center;gap:8px;font-size:12px;}',
1832
+ '.dsh-kb-distLabel{flex:none;width:46px;color:var(--dsw-alias-label-secondary);font-family:ui-monospace,Menlo,monospace;font-size:11.5px;}',
1833
+ '.dsh-kb-distLabel--wide{width:96px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-family:inherit;color:var(--dsw-alias-label-primary);}',
1834
+ '.dsh-kb-distValue{flex:none;font-size:11.5px;color:var(--dsw-alias-label-secondary);}',
1835
+ '.dsh-kb-bar{flex:1;height:6px;border-radius:999px;background:var(--dsw-alias-bg-layer-2);overflow:hidden;}',
1836
+ '.dsh-kb-bar i{display:block;height:100%;border-radius:999px;background:var(--dsw-alias-label-brand,#1f6feb);}',
1837
+ '.dsh-kb-chips{display:flex;flex-wrap:wrap;gap:6px;}',
1838
+ '.dsh-kb-chip{padding:2px 8px;border-radius:999px;font-size:11.5px;border:1px solid var(--dsw-alias-border-l1);color:var(--dsw-alias-label-secondary);}',
1839
+ '.dsh-kb-chip--ok{color:#228a4e;border-color:rgba(34,160,90,.4);}',
1840
+ '.dsh-kb-chip--bad{color:var(--dsw-alias-label-danger,#d14343);border-color:rgba(209,67,67,.4);}',
1841
+ '.dsh-kb-chip--busy{color:#a8741a;border-color:rgba(217,164,65,.5);}',
1842
+ '.dsh-kb-spark{display:flex;align-items:flex-end;gap:6px;height:76px;padding:6px 2px 0;}',
1843
+ '.dsh-kb-sparkCol{flex:1;display:flex;flex-direction:column;align-items:center;justify-content:flex-end;gap:4px;height:100%;}',
1844
+ '.dsh-kb-sparkBar{width:100%;max-width:26px;border-radius:4px 4px 0 0;background:var(--dsw-alias-label-brand,#1f6feb);opacity:.75;}',
1845
+ '.dsh-kb-sparkLabel{font-size:10px;color:var(--dsw-alias-label-secondary);}',
1846
+ '.dsh-kb-kv--tight{grid-template-columns:auto 1fr auto 1fr;font-size:11.5px;}',
1847
+ '.dsh-kb-list{display:flex;flex-direction:column;gap:4px;}',
1848
+ '.dsh-kb-listRow{display:flex;align-items:baseline;gap:8px;font-size:12px;padding:3px 0;border-bottom:1px dashed var(--dsw-alias-border-l1);}',
1849
+ '.dsh-kb-listRow:last-child{border-bottom:none;}',
1850
+ '.dsh-kb-listMain{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}',
1851
+ '.dsh-kb-listMeta{flex:none;font-size:11px;color:var(--dsw-alias-label-secondary);}',
1852
+ '.dsh-kb-listTime{flex:none;font-size:11px;color:var(--dsw-alias-label-secondary);width:56px;text-align:right;}',
1853
+ '.dsh-kb-barIcon--active{opacity:1;color:var(--dsw-alias-label-brand,#1f6feb);}',
1854
+ '.dsh-kb-rowActions{display:none;gap:2px;flex:none;}',
1855
+ '.dsh-kb-row:hover .dsh-kb-rowActions,.dsh-kb-row:focus-visible .dsh-kb-rowActions{display:inline-flex;}',
1856
+ '.dsh-kb-rowBtn{display:inline-flex;align-items:center;justify-content:center;width:20px;height:20px;border:none;border-radius:5px;background:transparent;color:var(--dsw-alias-label-secondary);cursor:pointer;padding:0;}',
1857
+ '.dsh-kb-rowBtn:hover{background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary);}',
1858
+ '.dsh-kb-rowBtn--danger:hover{color:var(--dsw-alias-label-danger,#d14343);}',
1859
+ '.dsh-kb-row:focus-visible{outline:2px solid var(--dsw-alias-label-brand,#1f6feb);outline-offset:-2px;}',
1860
+ '.dsh-kb-rowHint{font-size:11.5px;color:var(--dsw-alias-label-secondary);padding:4px 8px 4px 0;}',
1861
+ '.dsh-kb-moveList{display:flex;flex-direction:column;gap:2px;max-height:300px;overflow-y:auto;padding:4px;border:1px solid var(--dsw-alias-border-l1);border-radius:8px;}',
1862
+ '.dsh-kb-moveItem{padding:6px 10px;border:none;border-radius:6px;background:transparent;color:inherit;font:inherit;font-size:12.5px;text-align:left;cursor:pointer;}',
1863
+ '.dsh-kb-moveItem:hover{background:var(--dsw-alias-bg-layer-2);}',
1864
+ '.dsh-kb-big{position:fixed;inset:0;z-index:3000;display:flex;flex-direction:column;background:var(--dsw-alias-bg-layer-1);}',
1865
+ '.dsh-kb-bigBar{display:flex;flex:none;align-items:center;gap:10px;padding:10px 16px;border-bottom:1px solid var(--dsw-alias-border-l1);}',
1866
+ '.dsh-kb-bigTitle{font-size:13px;font-weight:600;max-width:42%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}',
1867
+ '.dsh-kb-bigNav{display:flex;align-items:center;gap:8px;}',
1868
+ '.dsh-kb-bigBody .dsh-kb-pages--single .dsh-kb-pageShot{max-width:1400px;}',
1869
+ '.dsh-kb-bigBody{flex:1;min-height:0;display:flex;flex-direction:column;background:var(--dsw-alias-bg-layer-2);}',
1870
+ '.dsh-kb-bigBody .dsh-kb-pages{padding:18px 22px 40px;}',
1871
+ '.dsh-kb-bigBody .dsh-kb-pageShot{max-width:1400px;}',
1872
+ '.dsh-kb-bigImg{max-width:100%;max-height:100%;object-fit:contain;margin:auto;display:block;}',
1873
+ '.dsh-kb-bigFrame{flex:1;min-height:0;width:100%;border:none;background:#fff;}',
1874
+ '.dsh-kb-btn--dangerSolid{border-color:transparent;background:var(--dsw-alias-label-danger,#d14343);color:#fff;}',
1875
+ '.dsh-kb-btn--dangerSolid:hover{filter:brightness(1.06);}',
1876
+ '.dsh-kb-mask{position:absolute;inset:0;z-index:20;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,.28);}',
1877
+ '.dsh-kb-modal{width:min(380px,86%);display:flex;flex-direction:column;gap:10px;padding:16px;border-radius:14px;background:var(--dsw-alias-bg-layer-1);border:1px solid var(--dsw-alias-border-l1);box-shadow:0 12px 32px rgba(0,0,0,.18);}',
1878
+ '.dsh-kb-modalTitle{font-size:13px;font-weight:600;line-height:1.5;}',
1879
+ '.dsh-kb-modalInput{height:30px;padding:0 9px;border:1px solid var(--dsw-alias-border-l1);border-radius:8px;background:var(--dsw-alias-bg-layer-2);color:inherit;font:inherit;font-size:12.5px;}',
1880
+ '.dsh-kb-modalInput:focus{outline:none;border-color:var(--dsw-alias-label-brand,#1f6feb);}',
1881
+ '.dsh-kb-modalActions{display:flex;justify-content:flex-end;gap:8px;}',
1882
+ ].join('\n');
1883
+ document.head.appendChild(style);
1884
+ return () => style.remove();
1885
+ }
1886
+
1887
+ // ── 插件入口 ────────────────────────────────────────────────────────
1888
+ function apply(ctx) {
1889
+ const slots = ctx.get('slots');
1890
+ if (!slots) return;
1891
+ ctx.effect(installStyles, 'knowledge-base: styles');
1892
+
1893
+ // 组件拿不到 ctx,所以把"开会话"这件事留在模块作用域里
1894
+ sessionStarter = (prompt) => {
1895
+ const workspace = ctx.get('uiWorkspace');
1896
+ if (!workspace?.startSession) {
1897
+ patch({ error: '会话服务还没就绪,稍后再点一次' });
1898
+ return;
1899
+ }
1900
+ try {
1901
+ workspace.startSession(undefined, { prompt, whenDraftExists: 'append' });
1902
+ } catch (error) {
1903
+ patch({ error: `开会话失败:${error.message || error}` });
1904
+ }
1905
+ };
1906
+
1907
+ ctx.effect(() => slots.inject('sidebar.panellist', () => slots.register({
1908
+ name: 'sidebar.panellist',
1909
+ id: PANEL_ID,
1910
+ order: 25,
1911
+ label: () => '知识库',
1912
+ }, PanelIcon)), 'knowledge-base: panellist icon');
1913
+
1914
+ ctx.effect(() => slots.inject('main', () => slots.register({
1915
+ name: 'main',
1916
+ key: PANEL_ID,
1917
+ }, KbPage)), 'knowledge-base: main page');
1918
+
1919
+ ctx.effect(() => slots.inject('settings.section', () => slots.register({
1920
+ name: 'settings.section',
1921
+ id: 'dsh-knowledge-base-settings',
1922
+ order: 26,
1923
+ label: () => '知识库',
1924
+ }, SettingsSection)), 'knowledge-base: settings section');
1925
+ }
1926
+
1927
+ const plugin = { inject: ['slots'], apply };
1928
+ // 仅测试用:让离线冒烟测试能摆出各种状态再渲染(浏览器里不生效)
1929
+ if (typeof globalThis !== 'undefined' && globalThis.__DSH_KB_TEST__) {
1930
+ plugin.__test = { patch, state, askText, askConfirm, renderText, isImage };
1931
+ }
1932
+ return plugin;
1933
+ },
1934
+ });