@xiaofanzhao/dsh-plugin-knowledge-base 0.2.0 → 0.2.3

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 CHANGED
@@ -1,1934 +1,2000 @@
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
- });
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
+ const partialTimer = React.useRef(null);
601
+ // Office 原版式:先让 Host 把每页渲染成图片,界面自己拼阅读器
602
+ React.useEffect(() => {
603
+ const target = state.doc;
604
+ if (!target || !OFFICE_EXT.includes(target.ext)) return undefined;
605
+ if (state.previewMode === 'text' || state.caps?.officePreview === false) return undefined;
606
+ if (state.previewInfo?.docId === target.id && !state.previewInfo?.partial) return undefined;
607
+ let cancelled = false;
608
+ let tries = 0;
609
+ const timer = setTimeout(() => {
610
+ if (!cancelled && state.previewInfo?.docId !== target.id) {
611
+ patch({ previewError: '页面渲染超过 90 秒还没好;可以切到「文字版」,或「下载」原件。' });
612
+ }
613
+ }, 90000);
614
+
615
+ const fetchInfo = async () => {
616
+ try {
617
+ const data = await api(`/doc?id=${encodeURIComponent(target.id)}&action=previewinfo`);
618
+ if (cancelled) return;
619
+ patch({
620
+ previewInfo: {
621
+ docId: target.id,
622
+ pages: data.pages,
623
+ pageCount: data.pageCount,
624
+ truncated: Boolean(data.truncated),
625
+ partial: Boolean(data.partial),
626
+ width: data.width,
627
+ height: data.height,
628
+ },
629
+ previewError: '',
630
+ });
631
+ // 首屏几页出来了、后面的还在后台补:过几秒再问一次
632
+ if (data.partial && tries < 20) {
633
+ tries += 1;
634
+ partialTimer.current = setTimeout(fetchInfo, 3000);
635
+ }
636
+ } catch (error) {
637
+ if (cancelled) return;
638
+ const message = error.message || '预览生成失败';
639
+ patch({ previewInfo: { docId: target.id, error: message }, previewError: message });
640
+ }
641
+ };
642
+
643
+ fetchInfo();
644
+ return () => {
645
+ cancelled = true;
646
+ clearTimeout(timer);
647
+ if (partialTimer.current) clearTimeout(partialTimer.current);
648
+ };
649
+ }, [doc?.id, current.previewMode]);
650
+ if (!doc) {
651
+ if (current.kbs.length === 0) {
652
+ return h('div', { className: 'dsh-kb-empty' },
653
+ h('div', { className: 'dsh-kb-emptyIcon' }, h(Icon, { name: 'book', size: 28 })),
654
+ h('p', null, '先新建一个知识库,再把文件拖进来。'),
655
+ h('button', { type: 'button', className: 'dsh-kb-btn dsh-kb-btn--primary', onClick: () => createKb() }, '新建知识库'),
656
+ h('p', { className: 'dsh-kb-hint' }, '文件只存在这台电脑上,不会上传到云端。'));
657
+ }
658
+ return h('div', { className: 'dsh-kb-empty' },
659
+ h('div', { className: 'dsh-kb-emptyIcon' }, h(Icon, { name: 'book', size: 28 })),
660
+ h('p', null, current.nodes.length ? '从左边选一个文件,或把文件拖进来。' : '这个知识库还是空的。点「上传文件」或把文件拖进来。'),
661
+ h('p', { className: 'dsh-kb-hint' }, '文件只存在这台电脑上,不会上传到云端。'));
662
+ }
663
+ const failed = doc.status === 'failed';
664
+ const pending = doc.status === 'pending' || doc.status === 'parsing';
665
+ const office = OFFICE_EXT.includes(doc.ext);
666
+ const previewAvailable = current.caps?.officePreview !== false;
667
+ const officeVisual = office && previewAvailable && current.previewMode !== 'text';
668
+ const visual = isImage(doc.ext) ? false : (doc.ext === 'pdf' || officeVisual);
669
+ const officeInfo = current.previewInfo?.docId === doc.id ? current.previewInfo : null;
670
+ const totalPages = officeInfo?.pages || 0;
671
+ const pageNow = Math.min(Math.max(1, Number(current.currentPage) || 1), totalPages || 1);
672
+ const pageAspect = officeInfo?.width && officeInfo?.height
673
+ ? { aspectRatio: `${officeInfo.width} / ${officeInfo.height}` }
674
+ : undefined;
675
+ const goPage = (target) => {
676
+ const page = Math.min(Math.max(1, Math.round(Number(target) || 1)), totalPages || 1);
677
+ patch({ currentPage: page, pageInput: String(page) });
678
+ if (state.pageMode === 'single') return;
679
+ const container = pagesRef.current;
680
+ const element = container?.querySelector(`[data-page="${page}"]`);
681
+ if (container && element) container.scrollTop = Math.max(0, element.offsetTop - 10);
682
+ };
683
+ const onPagesScroll = (event) => {
684
+ const container = event.currentTarget;
685
+ let visible = 1;
686
+ for (const shot of container.querySelectorAll('[data-page]')) {
687
+ if (shot.offsetTop - container.scrollTop <= 48) visible = Number(shot.getAttribute('data-page')) || visible;
688
+ else break;
689
+ }
690
+ if (visible !== state.currentPage) patch({ currentPage: visible, pageInput: String(visible) });
691
+ };
692
+ return h('div', { className: 'dsh-kb-doc' },
693
+ h('div', { className: 'dsh-kb-docHead' },
694
+ h('div', { className: 'dsh-kb-docTitle' }, doc.name),
695
+ h('div', { className: 'dsh-kb-docMeta' },
696
+ h('span', null, bytes(doc.bytes)),
697
+ doc.ext ? h('span', null, `.${doc.ext}`) : null,
698
+ h('span', null, doc.status === 'ready' ? `已索引 · ${doc.chars} 字${doc.pageCount ? ` · ${doc.pageCount} 页` : ''}` : pending ? '解析中…' : failed ? '解析失败' : doc.status),
699
+ doc.indexedAt ? h('span', null, when(doc.indexedAt)) : null)),
700
+ h('div', { className: 'dsh-kb-docActions' },
701
+ h('button', { type: 'button', className: 'dsh-kb-btn dsh-kb-btn--primary', onClick: () => onAsk(doc) },
702
+ h(Icon, { name: 'spark', size: 14 }), '问 AI'),
703
+ h('button', {
704
+ type: 'button', className: 'dsh-kb-btn',
705
+ onClick: () => patch({ bigView: true, previewMode: office ? 'visual' : state.previewMode }),
706
+ title: '铺满整个窗口看(Esc 关闭)',
707
+ }, h(Icon, { name: 'open', size: 14 }), '大屏'),
708
+ h('a', {
709
+ className: 'dsh-kb-btn', href: rawUrl(doc, 'download=1'), download: doc.name,
710
+ onClick: (event) => event.stopPropagation(),
711
+ title: '下载原始文件',
712
+ }, '下载'),
713
+ office
714
+ ? h('span', { className: 'dsh-kb-seg', role: 'group', 'aria-label': '查看方式' },
715
+ h('button', {
716
+ type: 'button',
717
+ className: cx('dsh-kb-segBtn', officeVisual && 'dsh-kb-segBtn--on'),
718
+ onClick: () => patch({ previewMode: 'visual' }),
719
+ }, '原版式'),
720
+ h('button', {
721
+ type: 'button',
722
+ className: cx('dsh-kb-segBtn', !officeVisual && 'dsh-kb-segBtn--on'),
723
+ onClick: () => patch({ previewMode: 'text' }),
724
+ }, '文字'))
725
+ : null,
726
+ doc.status !== 'failed' && !isImage(doc.ext)
727
+ ? h('button', { type: 'button', className: 'dsh-kb-btn', onClick: () => onReindex(doc) },
728
+ h(Icon, { name: 'refresh', size: 14 }), '重新索引')
729
+ : null,
730
+ h('button', { type: 'button', className: 'dsh-kb-btn dsh-kb-btn--danger', onClick: () => onDelete(doc) },
731
+ h(Icon, { name: 'trash', size: 14 }), '删除')),
732
+ office && !previewAvailable
733
+ ? h('div', { className: 'dsh-kb-banner dsh-kb-banner--info' },
734
+ '这台机器没启用 Office 转换服务,只能看抽取出来的文字;「原文件」按钮可以用系统里的 Office 打开。')
735
+ : null,
736
+ // 预览失败的具体原因在下面那块里给(带按钮),这里不重复
737
+ current.previewError && !(current.previewInfo?.docId === doc.id && current.previewInfo?.error)
738
+ ? h('div', { className: 'dsh-kb-banner dsh-kb-banner--bad', role: 'alert' },
739
+ h('Icon', { name: 'warn', size: 15 }),
740
+ h('span', null, current.previewError),
741
+ office
742
+ ? h('button', { type: 'button', className: 'dsh-kb-btn', onClick: () => patch({ previewMode: 'text', previewError: '' }) }, '看文字版')
743
+ : null)
744
+ : null,
745
+ failed
746
+ ? h('div', { className: 'dsh-kb-banner dsh-kb-banner--bad' },
747
+ h(Icon, { name: 'warn', size: 15 }),
748
+ h('span', null, doc.error || '解析失败'),
749
+ h('button', { type: 'button', className: 'dsh-kb-btn', onClick: () => onReindex(doc) }, '重试'))
750
+ : null,
751
+ h('div', { className: cx('dsh-kb-reader', visual && 'dsh-kb-reader--visual') },
752
+ pending
753
+ ? h('div', { className: 'dsh-kb-hint' }, '正在解析并建立索引,稍等一下…')
754
+ : null,
755
+ isImage(doc.ext)
756
+ ? h('img', {
757
+ className: 'dsh-kb-image',
758
+ alt: doc.name,
759
+ src: rawUrl(doc),
760
+ })
761
+ : doc.ext === 'pdf'
762
+ ? h('iframe', {
763
+ className: 'dsh-kb-frame',
764
+ title: doc.name,
765
+ src: `${rawUrl(doc)}${PDF_FRAGMENT}`,
766
+ })
767
+ : officeVisual
768
+ ? h('div', { className: 'dsh-kb-viewer' },
769
+ officeInfo && !officeInfo.error
770
+ ? h('div', { className: 'dsh-kb-viewerBar' },
771
+ h('button', {
772
+ type: 'button', className: 'dsh-kb-navBtn', title: '显示/隐藏缩略图',
773
+ onClick: () => patch({ thumbsOpen: !state.thumbsOpen }),
774
+ }, h(Icon, { name: 'doc', size: 13 })),
775
+ h('button', {
776
+ type: 'button', className: 'dsh-kb-navBtn', title: '上一页',
777
+ disabled: pageNow <= 1, onClick: () => goPage(pageNow - 1),
778
+ }, '‹'),
779
+ h('input', {
780
+ className: 'dsh-kb-pageInput',
781
+ value: current.pageInput ?? String(pageNow),
782
+ inputMode: 'numeric',
783
+ 'aria-label': '跳到页码',
784
+ onChange: (event) => patch({ pageInput: event.target.value.replace(/[^\d]/g, '') }),
785
+ onKeyDown: (event) => {
786
+ if (event.key === 'Enter') {
787
+ goPage(state.pageInput);
788
+ event.currentTarget.blur();
789
+ }
790
+ },
791
+ }),
792
+ h('span', { className: 'dsh-kb-pageTotal' }, `/ ${officeInfo.pages}`),
793
+ h('button', {
794
+ type: 'button', className: 'dsh-kb-navBtn', title: '下一页',
795
+ disabled: pageNow >= officeInfo.pages, onClick: () => goPage(pageNow + 1),
796
+ }, '›'),
797
+ h('span', { className: 'dsh-kb-viewerGrow' }),
798
+ h('span', { className: 'dsh-kb-seg', role: 'group', 'aria-label': '翻页方式' },
799
+ h('button', {
800
+ type: 'button',
801
+ className: cx('dsh-kb-segBtn', current.pageMode !== 'single' && 'dsh-kb-segBtn--on'),
802
+ onClick: () => patch({ pageMode: 'scroll' }),
803
+ }, '连续'),
804
+ h('button', {
805
+ type: 'button',
806
+ className: cx('dsh-kb-segBtn', current.pageMode === 'single' && 'dsh-kb-segBtn--on'),
807
+ onClick: () => patch({ pageMode: 'single', currentPage: pageNow }),
808
+ }, '单页')))
809
+ : null,
810
+ officeInfo && !officeInfo.error
811
+ ? h('div', { className: 'dsh-kb-viewerBody' },
812
+ current.thumbsOpen
813
+ ? h('div', { className: 'dsh-kb-thumbs' },
814
+ Array.from({ length: officeInfo.pages }, (_, index) => index + 1).map((page) => h('button', {
815
+ type: 'button',
816
+ key: page,
817
+ className: cx('dsh-kb-thumb', page === pageNow && 'dsh-kb-thumb--on'),
818
+ title: `第 ${page} 页`,
819
+ onClick: () => goPage(page),
820
+ },
821
+ h('img', {
822
+ className: 'dsh-kb-thumbImg',
823
+ src: thumbUrl(doc, page),
824
+ loading: 'lazy',
825
+ decoding: 'async',
826
+ alt: `第 ${page} 页缩略图`,
827
+ }),
828
+ h('span', { className: 'dsh-kb-thumbNo' }, page))))
829
+ : null,
830
+ h('div', {
831
+ className: cx('dsh-kb-pages', current.pageMode === 'single' && 'dsh-kb-pages--single'),
832
+ ref: pagesRef,
833
+ onScroll: current.pageMode === 'single' ? undefined : onPagesScroll,
834
+ },
835
+ (current.pageMode === 'single' ? [pageNow] : Array.from({ length: officeInfo.pages }, (_, index) => index + 1))
836
+ .map((page) => h('div', {
837
+ className: 'dsh-kb-pageShot',
838
+ key: page,
839
+ 'data-page': page,
840
+ // 单页模式让容器自己撑满、由 object-fit 居中,不要用固定比例
841
+ style: current.pageMode === 'single' ? undefined : pageAspect,
842
+ },
843
+ h('img', {
844
+ className: 'dsh-kb-pageImg',
845
+ src: pageUrl(doc, page),
846
+ loading: page <= 2 ? 'eager' : 'lazy',
847
+ decoding: 'async',
848
+ alt: `${doc.name} 第 ${page} 页`,
849
+ }),
850
+ h('span', { className: 'dsh-kb-pageNo' }, page))),
851
+ officeInfo.truncated || officeInfo.partial
852
+ ? h('div', { className: 'dsh-kb-pagesNote' },
853
+ officeInfo.partial
854
+ ? `已生成 ${officeInfo.pages} / 共 ${officeInfo.pageCount || '?'} 页,后面的页面正在后台渲染,稍等几秒会自动出现。`
855
+ : `共 ${officeInfo.pageCount || '?'} 页,这里只渲染了前 ${officeInfo.pages} 页。`)
856
+ : null))
857
+ : current.previewInfo?.docId === doc.id && current.previewInfo?.error
858
+ ? h('div', { className: 'dsh-kb-pagesLoading dsh-kb-pagesLoading--error' },
859
+ h('div', { className: 'dsh-kb-pagesErrorTitle' },
860
+ h(Icon, { name: 'warn', size: 16 }), '原版式预览用不了'),
861
+ h('p', { className: 'dsh-kb-pagesErrorText' }, current.previewInfo.error),
862
+ h('div', { className: 'dsh-kb-row2' },
863
+ h('button', {
864
+ type: 'button', className: 'dsh-kb-btn dsh-kb-btn--primary',
865
+ onClick: () => patch({ previewMode: 'text' }),
866
+ }, '看文字版'),
867
+ h('button', {
868
+ type: 'button', className: 'dsh-kb-btn',
869
+ onClick: () => {
870
+ patch({ previewInfo: null, previewError: '' });
871
+ },
872
+ }, '重试')))
873
+ : h('div', { className: 'dsh-kb-pagesLoading' },
874
+ h('span', { className: 'dsh-kb-spinner', 'aria-hidden': 'true' }),
875
+ '正在渲染页面…第一次打开会慢一些,之后是缓存。'))
876
+ : h('div', { className: 'dsh-kb-text' }, renderText(current.docText, current.query)),
877
+ !officeVisual && doc.ext !== 'pdf' && !isImage(doc.ext) && current.docHasMore
878
+ ? h('button', {
879
+ type: 'button', className: 'dsh-kb-btn dsh-kb-more',
880
+ onClick: () => loadDoc(doc.id, { offset: current.docNext }),
881
+ }, `继续加载(已显示 ${current.docText.length} / ${current.docTotal} 字)`)
882
+ : null));
883
+ }
884
+
885
+ // ── 检索结果 ────────────────────────────────────────────────────────
886
+ function SearchView() {
887
+ const current = useStore();
888
+ const search = current.search;
889
+ if (search.loading) return h('div', { className: 'dsh-kb-hint' }, '检索中…');
890
+ if (search.error) return h('div', { className: 'dsh-kb-banner dsh-kb-banner--bad' }, search.error);
891
+ if (!search.hits.length) return h('div', { className: 'dsh-kb-hint' }, search.ran ? '没有找到匹配的内容。换个词试试,或只搜关键词。' : '');
892
+ return h('div', { className: 'dsh-kb-hits' },
893
+ h('div', { className: 'dsh-kb-hitsHead' }, `${search.hits.length} 条结果 · ${search.mode === 'hybrid' ? '关键词 + 向量' : '关键词'}`),
894
+ search.hits.map((hit) => h('button', {
895
+ key: `${hit.nodeId}-${hit.chunkId}`,
896
+ type: 'button',
897
+ className: 'dsh-kb-hit',
898
+ onClick: () => {
899
+ if (hit.ext === 'pdf' || isImage(hit.ext)) {
900
+ // PDF / 图片没有可定位的正文,只打开文件,别偷偷改偏移
901
+ loadDoc(hit.nodeId, { offset: 0 });
902
+ patch({ notice: `${hit.ext === 'pdf' ? 'PDF' : '图片'}命中的位置无法精确定位,已打开文件本身。` });
903
+ return;
904
+ }
905
+ loadDoc(hit.nodeId, { offset: Math.max(0, Number(hit.charStart) - 200) });
906
+ },
907
+ },
908
+ h('div', { className: 'dsh-kb-hitName' }, hit.name, hit.heading ? h('span', { className: 'dsh-kb-hitHead' }, ` · ${hit.heading}`) : null),
909
+ h('div', { className: 'dsh-kb-hitSnippet' }, hit.snippet))));
910
+ }
911
+
912
+ // ── 大屏预览:铺满整个窗口(不依赖 window.open / target=_blank,桌面端会拦)──
913
+ function BigView({ doc }) {
914
+ const current = useStore();
915
+ const office = OFFICE_EXT.includes(doc.ext);
916
+ const info = current.previewInfo?.docId === doc.id ? current.previewInfo : null;
917
+ const total = info?.pages || 0;
918
+ const single = current.bigMode !== 'scroll';
919
+ const page = Math.min(Math.max(1, Number(current.currentPage) || 1), total || 1);
920
+ const go = (target) => {
921
+ const next = Math.min(Math.max(1, Math.round(Number(target) || 1)), total || 1);
922
+ patch({ currentPage: next, pageInput: String(next) });
923
+ };
924
+ React.useEffect(() => {
925
+ const onKey = (event) => {
926
+ if (event.key === 'Escape') { patch({ bigView: false }); return; }
927
+ if (event.key === 'ArrowRight' || event.key === 'PageDown') {
928
+ event.preventDefault();
929
+ go((Number(state.currentPage) || 1) + 1);
930
+ }
931
+ if (event.key === 'ArrowLeft' || event.key === 'PageUp') {
932
+ event.preventDefault();
933
+ go((Number(state.currentPage) || 1) - 1);
934
+ }
935
+ };
936
+ window.addEventListener('keydown', onKey);
937
+ return () => window.removeEventListener('keydown', onKey);
938
+ }, []);
939
+ return h('div', { className: 'dsh-kb-big' },
940
+ h('div', { className: 'dsh-kb-bigBar' },
941
+ h('span', { className: 'dsh-kb-bigTitle' }, doc.name),
942
+ office && info
943
+ ? h('span', { className: 'dsh-kb-bigNav' },
944
+ h('button', { type: 'button', className: 'dsh-kb-navBtn', title: '上一页', disabled: page <= 1, onClick: () => go(page - 1) }, '‹'),
945
+ h('span', { className: 'dsh-kb-pageTotal' }, `${page} / ${info.pages}`),
946
+ h('button', { type: 'button', className: 'dsh-kb-navBtn', title: '下一页', disabled: page >= info.pages, onClick: () => go(page + 1) }, '›'),
947
+ h('span', { className: 'dsh-kb-seg', role: 'group', 'aria-label': '显示方式' },
948
+ h('button', {
949
+ type: 'button',
950
+ className: cx('dsh-kb-segBtn', single && 'dsh-kb-segBtn--on'),
951
+ onClick: () => patch({ bigMode: 'single' }),
952
+ }, '单页'),
953
+ h('button', {
954
+ type: 'button',
955
+ className: cx('dsh-kb-segBtn', !single && 'dsh-kb-segBtn--on'),
956
+ onClick: () => patch({ bigMode: 'scroll' }),
957
+ }, '连续')))
958
+ : null,
959
+ h('span', { className: 'dsh-kb-viewerGrow' }),
960
+ h('button', {
961
+ type: 'button', className: 'dsh-kb-btn dsh-kb-btn--primary', title: '恢复成面板视图(Esc)',
962
+ onClick: () => patch({ bigView: false }),
963
+ }, h(Icon, { name: 'close', size: 13 }), '恢复')),
964
+ h('div', { className: 'dsh-kb-bigBody' },
965
+ isImage(doc.ext)
966
+ ? h('img', { className: 'dsh-kb-bigImg', src: rawUrl(doc), alt: doc.name })
967
+ : doc.ext === 'pdf'
968
+ ? h('iframe', { className: 'dsh-kb-bigFrame', title: doc.name, src: `${rawUrl(doc)}${PDF_FRAGMENT}` })
969
+ : office && info && !info.error
970
+ ? h('div', { className: cx('dsh-kb-pages', single && 'dsh-kb-pages--single') },
971
+ (single ? [page] : Array.from({ length: info.pages }, (_, index) => index + 1))
972
+ .map((one) => h('div', {
973
+ className: 'dsh-kb-pageShot',
974
+ key: one,
975
+ 'data-page': one,
976
+ style: single || !info.width || !info.height ? undefined : { aspectRatio: `${info.width} / ${info.height}` },
977
+ },
978
+ h('img', {
979
+ className: 'dsh-kb-pageImg',
980
+ src: pageUrl(doc, one),
981
+ loading: one <= 2 ? 'eager' : 'lazy',
982
+ decoding: 'async',
983
+ alt: `${doc.name} 第 ${one} 页`,
984
+ }),
985
+ h('span', { className: 'dsh-kb-pageNo' }, one))))
986
+ : h('div', { className: 'dsh-kb-pagesLoading' },
987
+ h('span', { className: 'dsh-kb-spinner', 'aria-hidden': 'true' }),
988
+ office ? '正在渲染页面…' : '这个格式没有大屏预览,可以点「下载」用系统应用打开')));
989
+ }
990
+
991
+ // ── 看板:知识库规模 + 检索情况 ─────────────────────────────────────
992
+ function Dashboard() {
993
+ const current = useStore();
994
+ const data = current.dashData;
995
+ const error = current.dashError;
996
+ const loading = Boolean(current.dashLoading);
997
+
998
+ const load = async () => {
999
+ patch({ dashLoading: true });
1000
+ try {
1001
+ const result = await api('/dashboard');
1002
+ patch({ dashData: result, dashError: '' });
1003
+ } catch (problem) {
1004
+ patch({ dashError: problem.message || '读取统计失败' });
1005
+ } finally {
1006
+ patch({ dashLoading: false });
1007
+ }
1008
+ };
1009
+
1010
+ React.useEffect(() => { if (!state.dashData) load(); }, []);
1011
+
1012
+ if (error && !data) {
1013
+ return h('div', { className: 'dsh-kb-dash' },
1014
+ h('div', { className: 'dsh-kb-banner dsh-kb-banner--bad', role: 'alert' }, error),
1015
+ h('button', { type: 'button', className: 'dsh-kb-btn', onClick: load }, '重试'));
1016
+ }
1017
+ if (!data) return h('div', { className: 'dsh-kb-hint dsh-kb-hint--pad' }, loading ? '统计中…' : '');
1018
+
1019
+ const stats = data.stats || {};
1020
+ const search = data.search || {};
1021
+ const coverage = stats.chunks ? Math.round(((stats.vectors || 0) / stats.chunks) * 100) : 0;
1022
+ const maxExt = Math.max(1, ...(data.byExt || []).map((item) => item.docs));
1023
+ const maxTrend = Math.max(1, ...(data.trend || []).map((item) => item.count));
1024
+ const statusLabel = { ready: '已索引', parsing: '解析中', pending: '排队', failed: '失败' };
1025
+ const statusColor = { ready: 'ok', parsing: 'busy', pending: 'idle', failed: 'bad' };
1026
+
1027
+ const card = (label, value, hint) => h('div', { className: 'dsh-kb-metric', key: label },
1028
+ h('span', { className: 'dsh-kb-metricLabel' }, label),
1029
+ h('strong', { className: 'dsh-kb-metricValue' }, value),
1030
+ hint ? h('span', { className: 'dsh-kb-metricHint' }, hint) : null);
1031
+
1032
+ return h('div', { className: 'dsh-kb-dash' },
1033
+ h('div', { className: 'dsh-kb-dashHead' },
1034
+ h('div', { className: 'dsh-kb-docTitle' }, '知识库看板'),
1035
+ h('span', { className: 'dsh-kb-hint' }, `数据目录 ${data.root || ''}`),
1036
+ h('span', { className: 'dsh-kb-viewerGrow' }),
1037
+ h('button', { type: 'button', className: 'dsh-kb-btn', onClick: load, disabled: loading },
1038
+ h(Icon, { name: 'refresh', size: 13 }), loading ? '刷新中…' : '刷新')),
1039
+
1040
+ h('div', { className: 'dsh-kb-metrics' },
1041
+ card('知识库', stats.kbs ?? 0, '个'),
1042
+ card('文档', stats.docs ?? 0, `共 ${bytes(stats.bytes)}`),
1043
+ card('检索片段', stats.chunks ?? 0, `平均 ${stats.docs ? Math.round((stats.chunks || 0) / stats.docs) : 0} 段/篇`),
1044
+ card('向量', stats.vectors ?? 0, `覆盖率 ${coverage}%`),
1045
+ card('检索次数', search.total ?? 0, `今日 ${search.today ?? 0}`)),
1046
+
1047
+ h('div', { className: 'dsh-kb-dashGrid' },
1048
+ // 文件类型分布
1049
+ h('section', { className: 'dsh-kb-card' },
1050
+ h('h4', null, '文件类型分布'),
1051
+ (data.byExt || []).length === 0
1052
+ ? h('p', { className: 'dsh-kb-hint' }, '还没有文档')
1053
+ : (data.byExt || []).map((item) => h('div', { className: 'dsh-kb-distRow', key: item.ext },
1054
+ h('span', { className: 'dsh-kb-distLabel' }, `.${item.ext}`),
1055
+ h('span', { className: 'dsh-kb-bar' },
1056
+ h('i', { style: { width: `${Math.round((item.docs / maxExt) * 100)}%` } })),
1057
+ h('span', { className: 'dsh-kb-distValue' }, `${item.docs} · ${bytes(item.bytes)}`)))),
1058
+
1059
+ // 解析状态
1060
+ h('section', { className: 'dsh-kb-card' },
1061
+ h('h4', null, '解析状态'),
1062
+ h('div', { className: 'dsh-kb-chips' },
1063
+ Object.entries(data.byStatus || {}).map(([status, count]) => h('span', {
1064
+ className: `dsh-kb-chip dsh-kb-chip--${statusColor[status] || 'idle'}`,
1065
+ key: status,
1066
+ }, `${statusLabel[status] || status} ${count}`))),
1067
+ h('h4', { className: 'dsh-kb-subHead' }, '各知识库'),
1068
+ (data.byKb || []).map((kb) => h('div', { className: 'dsh-kb-distRow', key: kb.id },
1069
+ h('span', { className: 'dsh-kb-distLabel dsh-kb-distLabel--wide' }, kb.name),
1070
+ h('span', { className: 'dsh-kb-distValue' }, `${kb.docs} 篇 · ${bytes(kb.bytes)}`)))),
1071
+
1072
+ // 检索趋势
1073
+ h('section', { className: 'dsh-kb-card' },
1074
+ h('h4', null, '最近 7 天检索'),
1075
+ (data.trend || []).length === 0
1076
+ ? h('p', { className: 'dsh-kb-hint' }, '还没有检索记录(搜索框或 kb_search 都会记)')
1077
+ : h('div', { className: 'dsh-kb-spark' },
1078
+ (data.trend || []).map((item) => h('div', { className: 'dsh-kb-sparkCol', key: item.day, title: `${item.day}:${item.count} 次` },
1079
+ h('div', { className: 'dsh-kb-sparkBar', style: { height: `${Math.max(4, Math.round((item.count / maxTrend) * 100))}%` } }),
1080
+ h('span', { className: 'dsh-kb-sparkLabel' }, (item.day || '').slice(5))))),
1081
+ h('div', { className: 'dsh-kb-kv dsh-kb-kv--tight' },
1082
+ h('span', null, '零命中率'), h('strong', null, `${search.zeroRate ?? 0}%`),
1083
+ h('span', null, '平均耗时'), h('strong', null, `${search.avgMs ?? 0} ms`),
1084
+ h('span', null, '混合检索'), h('strong', null, `${search.hybrid ?? 0} 次`),
1085
+ h('span', null, '最近一次'), h('strong', null, search.lastAt ? when(search.lastAt) : '—'))),
1086
+
1087
+ // 热门检索词 + 最近检索
1088
+ h('section', { className: 'dsh-kb-card' },
1089
+ h('h4', null, '热门检索词'),
1090
+ (data.topQueries || []).length === 0
1091
+ ? h('p', { className: 'dsh-kb-hint' }, '还没有')
1092
+ : h('div', { className: 'dsh-kb-chips' },
1093
+ (data.topQueries || []).map((item) => h('span', { className: 'dsh-kb-chip', key: item.query }, `${item.query} · ${item.count}`))),
1094
+ h('h4', { className: 'dsh-kb-subHead' }, '最近检索'),
1095
+ (data.recent || []).length === 0
1096
+ ? h('p', { className: 'dsh-kb-hint' }, '还没有')
1097
+ : h('div', { className: 'dsh-kb-list' },
1098
+ (data.recent || []).map((item, index) => h('div', { className: 'dsh-kb-listRow', key: `${item.ts}-${index}` },
1099
+ h('span', { className: 'dsh-kb-listMain' }, item.query || '(空查询)'),
1100
+ h('span', { className: 'dsh-kb-listMeta' }, `${item.hits} 命中 · ${item.mode} · ${item.tookMs}ms`),
1101
+ h('span', { className: 'dsh-kb-listTime' }, when(item.ts)))))),
1102
+
1103
+ // 最近添加
1104
+ h('section', { className: 'dsh-kb-card' },
1105
+ h('h4', null, '最近添加'),
1106
+ (data.recentDocs || []).length === 0
1107
+ ? h('p', { className: 'dsh-kb-hint' }, '还没有文档')
1108
+ : h('div', { className: 'dsh-kb-list' },
1109
+ (data.recentDocs || []).map((doc) => h('div', { className: 'dsh-kb-listRow', key: doc.id },
1110
+ h('span', { className: 'dsh-kb-listMain' }, doc.name),
1111
+ h('span', { className: 'dsh-kb-listMeta' }, `.${doc.ext} · ${bytes(doc.bytes)} · ${statusLabel[doc.status] || doc.status}`),
1112
+ h('span', { className: 'dsh-kb-listTime' }, when(doc.createdAt))))))));
1113
+ }
1114
+
1115
+ // ── 主页面 ──────────────────────────────────────────────────────────
1116
+ // 「问 AI」的会话入口由 apply 注入(组件拿不到 ctx)
1117
+ let sessionStarter = null;
1118
+
1119
+ /** 新文件/新文件夹落在哪:选中的文件夹 → 选中文件所在目录 → 根。 */
1120
+ function currentFolderId(current) {
1121
+ const selected = current.selectedId
1122
+ ? current.nodes.find((node) => node.id === current.selectedId)
1123
+ : null;
1124
+ if (!selected) return null;
1125
+ return selected.kind === 'folder' ? selected.id : (selected.parentId ?? null);
1126
+ }
1127
+
1128
+ function createKb() {
1129
+ askText('新知识库的名字', '我的知识库', (name) => nodeAction('create-kb', { name }));
1130
+ }
1131
+
1132
+ function KbPage() {
1133
+ const current = useStore();
1134
+ const [dragging, setDragging] = React.useState(false);
1135
+ const fileInput = React.useRef(null);
1136
+ const tree = React.useMemo(() => buildTree(current.nodes), [current.nodes]);
1137
+
1138
+ React.useEffect(() => {
1139
+ if (!state.loaded) loadState();
1140
+ }, []);
1141
+
1142
+ const searchTimer = React.useRef(null);
1143
+ const onQueryChange = (value) => {
1144
+ // 搜索时离开看板/设置,否则结果被挡住看不见
1145
+ patch({ query: value, view: value.trim() ? 'search' : 'doc', dashOpen: false, showSettings: false });
1146
+ if (searchTimer.current) clearTimeout(searchTimer.current);
1147
+ searchTimer.current = setTimeout(() => runSearch(value), 280);
1148
+ };
1149
+
1150
+ const onAsk = async (doc) => {
1151
+ try {
1152
+ const data = await api('/ask', {
1153
+ method: 'POST',
1154
+ headers: { 'content-type': 'application/json' },
1155
+ body: JSON.stringify({ docId: doc.id }),
1156
+ });
1157
+ sessionStarter?.(data.prompt);
1158
+ patch({ notice: '已在会话输入框里准备好提问,接着写你的问题就行' });
1159
+ } catch (error) {
1160
+ patch({ error: error.message || '打不开会话' });
1161
+ }
1162
+ };
1163
+
1164
+ const onReindex = async (doc) => {
1165
+ try {
1166
+ await api(`/doc?id=${encodeURIComponent(doc.id)}&action=reindex`, { method: 'POST' });
1167
+ patch({ notice: '已重新排队解析' });
1168
+ schedulePoll();
1169
+ await loadDoc(doc.id);
1170
+ } catch (error) {
1171
+ patch({ error: error.message || '重建失败' });
1172
+ }
1173
+ };
1174
+
1175
+ const onDelete = (doc) => {
1176
+ askConfirm(`删除「${doc.name}」?原文件也会被删掉。`, async () => {
1177
+ const data = await nodeAction('delete', { id: doc.id });
1178
+ if (data) patch({ doc: null, docText: '', docNext: 0, selectedId: '' });
1179
+ });
1180
+ };
1181
+
1182
+ return h('div', {
1183
+ className: cx('dsh-kb-page', dragging && 'dsh-kb-page--drag'),
1184
+ onDragOver: (event) => { event.preventDefault(); setDragging(true); },
1185
+ onDragLeave: () => setDragging(false),
1186
+ onDrop: (event) => {
1187
+ event.preventDefault();
1188
+ setDragging(false);
1189
+ if (!event.dataTransfer?.files?.length) return; // 树内拖动节点,不是外部文件
1190
+ uploadFiles(event.dataTransfer.files, currentFolderId(current));
1191
+ },
1192
+ },
1193
+ // 顶部
1194
+ h('div', { className: 'dsh-kb-head' },
1195
+ h('button', {
1196
+ type: 'button', className: 'dsh-kb-iconBtn',
1197
+ title: current.sideOpen ? '收起文件树' : '展开文件树',
1198
+ 'aria-expanded': current.sideOpen,
1199
+ onClick: () => patch({ sideOpen: !state.sideOpen }),
1200
+ }, h(Icon, { name: 'chevron', size: 13, className: current.sideOpen ? 'dsh-kb-rot180' : undefined })),
1201
+ h('div', { className: 'dsh-kb-brand' },
1202
+ h('span', { className: 'dsh-kb-brandIcon' }, h(Icon, { name: 'book', size: 16 })),
1203
+ h('select', {
1204
+ className: 'dsh-kb-select',
1205
+ value: current.kbId,
1206
+ onChange: (event) => {
1207
+ patch({ doc: null, docText: '', selectedId: '' });
1208
+ loadState(event.target.value);
1209
+ },
1210
+ },
1211
+ current.kbs.length
1212
+ ? current.kbs.map((kb) => h('option', { key: kb.id, value: kb.id }, `${kb.name}(${kb.docs})`))
1213
+ : h('option', { value: '' }, '还没有知识库')),
1214
+ h('button', {
1215
+ type: 'button', className: 'dsh-kb-iconBtn', title: '新建知识库',
1216
+ onClick: () => createKb(),
1217
+ }, h(Icon, { name: 'plus', size: 14 }))),
1218
+ h('div', { className: 'dsh-kb-searchBox' },
1219
+ h(Icon, { name: 'search', size: 14, className: 'dsh-kb-searchIcon' }),
1220
+ h('input', {
1221
+ className: 'dsh-kb-searchInput',
1222
+ type: 'search',
1223
+ placeholder: '搜索标题或正文(支持中文短词)…',
1224
+ value: current.query,
1225
+ onChange: (event) => onQueryChange(event.target.value),
1226
+ }),
1227
+ current.query
1228
+ ? h('button', {
1229
+ type: 'button', className: 'dsh-kb-searchClear', title: '清空',
1230
+ onClick: () => { onQueryChange(''); },
1231
+ }, h(Icon, { name: 'close', size: 12 }))
1232
+ : null),
1233
+ h('div', { className: 'dsh-kb-headActions' },
1234
+ h('span', { className: 'dsh-kb-seg', role: 'group', 'aria-label': '视图' },
1235
+ h('button', {
1236
+ type: 'button',
1237
+ className: cx('dsh-kb-segBtn', !current.dashOpen && !current.showSettings && 'dsh-kb-segBtn--on'),
1238
+ onClick: () => patch({ dashOpen: false, showSettings: false }),
1239
+ }, '文档'),
1240
+ h('button', {
1241
+ type: 'button',
1242
+ className: cx('dsh-kb-segBtn', current.dashOpen && !current.showSettings && 'dsh-kb-segBtn--on'),
1243
+ onClick: () => patch({ dashOpen: true, showSettings: false }),
1244
+ }, '看板')),
1245
+ h('button', {
1246
+ type: 'button', className: 'dsh-kb-btn',
1247
+ onClick: () => {
1248
+ const parent = currentFolderId(current);
1249
+ askText('新文件夹的名字', '新文件夹', (name) => nodeAction('create', {
1250
+ kbId: current.kbId, parentId: parent, kind: 'folder', name,
1251
+ }));
1252
+ },
1253
+ disabled: !current.kbId,
1254
+ }, h(Icon, { name: 'folder', size: 14 }), '新建文件夹'),
1255
+ h('button', {
1256
+ type: 'button', className: 'dsh-kb-btn dsh-kb-btn--primary',
1257
+ onClick: () => fileInput.current?.click(),
1258
+ disabled: !current.kbId,
1259
+ }, h(Icon, { name: 'upload', size: 14 }), current.uploading ? `上传中 ${current.uploading}` : '上传文件'),
1260
+ h('input', {
1261
+ ref: fileInput, type: 'file', multiple: true, style: { display: 'none' },
1262
+ onChange: (event) => {
1263
+ // 从行菜单的「⋯ → 上传文件」进来时,落在对应文件夹里
1264
+ uploadFiles(event.target.files, state.importTarget || currentFolderId(current));
1265
+ event.target.value = '';
1266
+ patch({ importTarget: null });
1267
+ },
1268
+ }),
1269
+ h('button', {
1270
+ type: 'button', className: cx('dsh-kb-iconBtn', current.showSettings && 'dsh-kb-iconBtn--on'),
1271
+ title: '知识库设置',
1272
+ 'aria-pressed': Boolean(current.showSettings),
1273
+ onClick: () => patch({ showSettings: !state.showSettings }),
1274
+ }, h(Icon, { name: 'settings', size: 15 })))),
1275
+
1276
+ // 提示条
1277
+ current.notice || current.error
1278
+ ? h('div', { className: cx('dsh-kb-banner', current.error ? 'dsh-kb-banner--bad' : 'dsh-kb-banner--info') },
1279
+ h('span', null, current.error || current.notice),
1280
+ h('button', { type: 'button', className: 'dsh-kb-bannerClose', onClick: () => patch({ notice: '', error: '' }) },
1281
+ h(Icon, { name: 'close', size: 12 })))
1282
+ : null,
1283
+
1284
+ // 主体
1285
+ h('div', { className: 'dsh-kb-body' },
1286
+ current.sideOpen
1287
+ ? h('div', { className: 'dsh-kb-side' },
1288
+ current.loading
1289
+ ? h('div', { className: 'dsh-kb-hint' }, '加载中…')
1290
+ : current.kbs.length === 0
1291
+ ? h('div', { className: 'dsh-kb-empty dsh-kb-empty--side' },
1292
+ h('p', null, '还没有知识库。'),
1293
+ h('button', {
1294
+ type: 'button', className: 'dsh-kb-btn dsh-kb-btn--primary',
1295
+ onClick: () => createKb(),
1296
+ }, '新建知识库'))
1297
+ : h('div', { className: 'dsh-kb-tree' },
1298
+ h(TreeRows, { byParent: tree, parentKey: '', depth: 0 }),
1299
+ current.nodes.length === 0
1300
+ ? h('div', { className: 'dsh-kb-hint dsh-kb-hint--pad' }, '空知识库:上传文件,或新建文件夹。')
1301
+ : null))
1302
+ : null, // 收起时不再画左侧竖条:顶部的箭头按钮就是展开入口
1303
+ h('div', { className: 'dsh-kb-main' },
1304
+ current.showSettings
1305
+ ? h('div', { className: 'dsh-kb-settingsPane' },
1306
+ h('div', { className: 'dsh-kb-settingsHead' },
1307
+ h('div', { className: 'dsh-kb-docTitle' }, '知识库设置'),
1308
+ h('span', { className: 'dsh-kb-viewerGrow' }),
1309
+ h('button', {
1310
+ type: 'button', className: 'dsh-kb-btn',
1311
+ onClick: () => patch({ showSettings: false }),
1312
+ }, h(Icon, { name: 'chevron', size: 12, className: 'dsh-kb-rot180' }), '返回')),
1313
+ h(SettingsSection))
1314
+ : current.dashOpen
1315
+ ? h(Dashboard)
1316
+ : (current.view === 'search' && current.query ? h(SearchView) : h(DocView, { onAsk, onReindex, onDelete }))),
1317
+ ),
1318
+ h(Dialog),
1319
+ // 行操作菜单:fixed 定位,免得被树栏的滚动裁掉
1320
+ current.menu ? (() => {
1321
+ const node = current.nodes.find((entry) => entry.id === current.menu.id);
1322
+ if (!node) return null;
1323
+ const isFolder = node.kind === 'folder';
1324
+ const close = () => patch({ menu: null });
1325
+ const item = (label, onClick, danger) => h('button', {
1326
+ type: 'button', role: 'menuitem',
1327
+ className: cx('dsh-kb-menuItem', danger && 'dsh-kb-menuItem--danger'),
1328
+ onClick: (event) => {
1329
+ event?.stopPropagation?.();
1330
+ close();
1331
+ onClick();
1332
+ },
1333
+ }, label);
1334
+ return h(React.Fragment, null,
1335
+ h('div', { className: 'dsh-kb-menuBackdrop', onClick: close }),
1336
+ h('div', {
1337
+ className: 'dsh-kb-menu', role: 'menu',
1338
+ style: { left: `${current.menu.x}px`, top: `${current.menu.y}px` },
1339
+ },
1340
+ isFolder
1341
+ ? item('新建子文件夹', () => askText('新文件夹的名字', '新文件夹', (name) => nodeAction('create', {
1342
+ kbId: node.kbId, parentId: node.id, kind: 'folder', name,
1343
+ })))
1344
+ : null,
1345
+ // 文件夹传到自己这儿;文件传到它所在的文件夹 —— 任何一行都能上传
1346
+ item(isFolder ? '上传文件到这里' : '上传文件到所在文件夹', () => {
1347
+ patch({ importTarget: isFolder ? node.id : (node.parentId || null) });
1348
+ fileInput.current?.click();
1349
+ }),
1350
+ item('重命名', () => askText('重命名', node.name, (name) => nodeAction('rename', { id: node.id, name }))),
1351
+ item('移动到…', () => askMove(node)),
1352
+ item('删除', () => askConfirm(
1353
+ `删除「${node.name}」?${isFolder ? '里面的内容也会一起删除。' : '原文件也会被删掉。'}`,
1354
+ () => nodeAction('delete', { id: node.id }),
1355
+ ), true)));
1356
+ })() : null,
1357
+ current.bigView && current.doc ? h(BigView, { doc: current.doc }) : null);
1358
+ }
1359
+
1360
+ // ── 设置分区 ────────────────────────────────────────────────────────
1361
+ function SettingsSection() {
1362
+ const current = useStore();
1363
+ const [form, setForm] = React.useState(null);
1364
+ const [saving, setSaving] = React.useState(false);
1365
+ const [probing, setProbing] = React.useState(false);
1366
+ const [probe, setProbe] = React.useState(null);
1367
+ const [formNotice, setFormNotice] = React.useState('');
1368
+ // 图片理解(视觉模型)那一块自己的表单状态
1369
+ const [visionForm, setVisionForm] = React.useState(null);
1370
+ const [visionSaving, setVisionSaving] = React.useState(false);
1371
+ const [visionProbing, setVisionProbing] = React.useState(false);
1372
+ const [visionProbe, setVisionProbe] = React.useState(null);
1373
+ const [visionNotice, setVisionNotice] = React.useState('');
1374
+ const [visionPresets, setVisionPresets] = React.useState([]);
1375
+ const [rebuilding, setRebuilding] = React.useState(false);
1376
+ const watchRef = React.useRef(null);
1377
+
1378
+ const stopWatch = () => {
1379
+ if (watchRef.current) {
1380
+ clearInterval(watchRef.current);
1381
+ watchRef.current = null;
1382
+ }
1383
+ };
1384
+
1385
+ /** 点重建后每 1 秒刷一次状态,全部解析完就停。 */
1386
+ const startWatch = () => {
1387
+ stopWatch();
1388
+ watchRef.current = setInterval(async () => {
1389
+ try { await loadState(state.kbId, true); } catch { /* ignore */ }
1390
+ const progress = state.progress;
1391
+ if (!progress || (progress.pending + progress.parsing) === 0) {
1392
+ stopWatch();
1393
+ setRebuilding(false);
1394
+ }
1395
+ }, 1000);
1396
+ };
1397
+
1398
+ React.useEffect(() => () => stopWatch(), []);
1399
+
1400
+ const rebuildAll = async () => {
1401
+ if (rebuilding) return;
1402
+ try {
1403
+ const data = await api('/reindex-all', { method: 'POST' });
1404
+ patch({ notice: `已排队重建 ${data.queued} 篇文档的索引`, error: '' });
1405
+ setRebuilding(true);
1406
+ startWatch();
1407
+ } catch (error) {
1408
+ patch({ error: error.message || '重建失败' });
1409
+ }
1410
+ };
1411
+ React.useEffect(() => {
1412
+ if (!state.loaded) loadState();
1413
+ let cancelled = false;
1414
+ api('/settings')
1415
+ .then((data) => {
1416
+ if (cancelled) return;
1417
+ setForm({ ...data.embedding, apiKey: '' });
1418
+ setVisionForm({ ...(data.vision || { enabled: false, baseUrl: '', model: '' }), apiKey: '' });
1419
+ setVisionPresets(Array.isArray(data.visionPresets) ? data.visionPresets : []);
1420
+ })
1421
+ .catch(() => {
1422
+ if (cancelled) return;
1423
+ setForm({ enabled: false, baseUrl: '', model: '', apiKey: '', hasKey: false, keyTail: '' });
1424
+ setVisionForm({ enabled: false, baseUrl: '', model: '', apiKey: '', hasKey: false, keyTail: '' });
1425
+ });
1426
+ return () => { cancelled = true; };
1427
+ }, []);
1428
+
1429
+ const saveVision = async () => {
1430
+ if (!visionForm || visionSaving) return;
1431
+ setVisionSaving(true);
1432
+ setVisionNotice('');
1433
+ try {
1434
+ const data = await api('/settings', {
1435
+ method: 'POST',
1436
+ headers: { 'content-type': 'application/json' },
1437
+ body: JSON.stringify({
1438
+ vision: {
1439
+ enabled: Boolean(visionForm.enabled),
1440
+ baseUrl: visionForm.baseUrl,
1441
+ model: visionForm.model,
1442
+ apiKey: visionForm.apiKey,
1443
+ },
1444
+ }),
1445
+ });
1446
+ setVisionForm({ ...(data.vision || {}), apiKey: '' });
1447
+ setVisionNotice('已保存,立即生效');
1448
+ await loadState(state.kbId, true);
1449
+ } catch (error) {
1450
+ setVisionNotice(`保存失败:${error.message || error}`);
1451
+ } finally {
1452
+ setVisionSaving(false);
1453
+ }
1454
+ };
1455
+
1456
+ const testVision = async () => {
1457
+ if (!visionForm || visionProbing) return;
1458
+ setVisionProbing(true);
1459
+ setVisionProbe(null);
1460
+ try {
1461
+ const data = await api('/vision-test', {
1462
+ method: 'POST',
1463
+ headers: { 'content-type': 'application/json' },
1464
+ body: JSON.stringify({ baseUrl: visionForm.baseUrl, model: visionForm.model, apiKey: visionForm.apiKey }),
1465
+ });
1466
+ setVisionProbe(data.probe || { ok: false, error: '没有返回结果' });
1467
+ } catch (error) {
1468
+ setVisionProbe({ ok: false, error: error.message || String(error) });
1469
+ } finally {
1470
+ setVisionProbing(false);
1471
+ }
1472
+ };
1473
+
1474
+ const saveEmbedding = async () => {
1475
+ if (!form || saving) return;
1476
+ setSaving(true);
1477
+ setFormNotice('');
1478
+ try {
1479
+ const data = await api('/settings', {
1480
+ method: 'POST',
1481
+ headers: { 'content-type': 'application/json' },
1482
+ body: JSON.stringify({
1483
+ embedding: {
1484
+ enabled: Boolean(form.enabled),
1485
+ baseUrl: form.baseUrl,
1486
+ model: form.model,
1487
+ apiKey: form.apiKey,
1488
+ },
1489
+ }),
1490
+ });
1491
+ setForm({ ...data.embedding, apiKey: '' });
1492
+ setFormNotice('已保存,立即生效');
1493
+ await loadState(state.kbId, true);
1494
+ } catch (error) {
1495
+ setFormNotice(`保存失败:${error.message || error}`);
1496
+ } finally {
1497
+ setSaving(false);
1498
+ }
1499
+ };
1500
+
1501
+ const testEmbedding = async () => {
1502
+ if (!form || probing) return;
1503
+ setProbing(true);
1504
+ setProbe(null);
1505
+ try {
1506
+ const data = await api('/embedding-test', {
1507
+ method: 'POST',
1508
+ headers: { 'content-type': 'application/json' },
1509
+ body: JSON.stringify({ baseUrl: form.baseUrl, model: form.model, apiKey: form.apiKey }),
1510
+ });
1511
+ setProbe(data.probe || { ok: false, error: '没有返回结果' });
1512
+ } catch (error) {
1513
+ setProbe({ ok: false, error: error.message || String(error) });
1514
+ } finally {
1515
+ setProbing(false);
1516
+ }
1517
+ };
1518
+
1519
+ const stats = current.stats;
1520
+ const embedding = current.caps?.embedding;
1521
+ return h('div', { className: 'dsh-kb-settings' },
1522
+ h('p', { className: 'dsh-kb-settingsIntro' },
1523
+ '知识库存放在本机:文件是真实文件,索引是本地 SQLite 全文索引。插件不会把内容上传到任何服务(除非你自己打开了向量检索)。'),
1524
+ h('section', { className: 'dsh-kb-card' },
1525
+ h('h4', null, '存放目录'),
1526
+ h('code', { className: 'dsh-kb-code' }, current.root || '(未初始化)'),
1527
+ h('p', { className: 'dsh-kb-hint' },
1528
+ '想换位置:在插件配置里设置 ',
1529
+ h('code', null, 'root'),
1530
+ '(插件页 → 知识库 → 配置),重启后生效。已有文件不会自动搬迁。')),
1531
+ h('section', { className: 'dsh-kb-card' },
1532
+ h('h4', null, '索引状态'),
1533
+ stats
1534
+ ? h('div', { className: 'dsh-kb-kv' },
1535
+ h('span', null, '知识库'), h('strong', null, stats.kbs),
1536
+ h('span', null, '文档'), h('strong', null, stats.docs),
1537
+ h('span', null, '检索片段'), h('strong', null, stats.chunks),
1538
+ h('span', null, '总大小'), h('strong', null, bytes(stats.bytes)),
1539
+ h('span', null, '向量'), h('strong', null, stats.vectors))
1540
+ : h('p', { className: 'dsh-kb-hint' }, '读取中…'),
1541
+ (() => {
1542
+ const progress = current.progress;
1543
+ if (!progress) return null;
1544
+ const working = progress.pending + progress.parsing;
1545
+ if (!rebuilding && working === 0) return null;
1546
+ const pct = progress.total ? Math.round((progress.done / progress.total) * 100) : 0;
1547
+ return h('div', { className: 'dsh-kb-progress', role: 'status' },
1548
+ h('div', { className: 'dsh-kb-progressTrack' },
1549
+ h('div', { className: 'dsh-kb-progressFill', style: { width: `${pct}%` } })),
1550
+ h('div', { className: 'dsh-kb-progressText' },
1551
+ working > 0
1552
+ ? `重建中:已完成 ${progress.done} / ${progress.total} 篇`
1553
+ + `${progress.parsing ? ` · 解析中 ${progress.parsing}` : ''}`
1554
+ + `${progress.queued ? ` · 排队 ${progress.queued}` : ''}`
1555
+ : `重建完成:${progress.done} / ${progress.total} 篇`));
1556
+ })(),
1557
+ h('div', { className: 'dsh-kb-row2' },
1558
+ h('button', {
1559
+ type: 'button', className: 'dsh-kb-btn',
1560
+ onClick: rebuildAll, disabled: rebuilding,
1561
+ }, h(Icon, { name: 'refresh', size: 14 }), rebuilding ? '重建中…' : '重建全部索引'),
1562
+ h('button', {
1563
+ type: 'button', className: 'dsh-kb-btn',
1564
+ onClick: () => loadState(current.kbId, true),
1565
+ }, '刷新'),
1566
+ h('button', {
1567
+ type: 'button', className: 'dsh-kb-btn',
1568
+ title: '删掉转换出来的 PDF 和逐页图片(下次打开会重新生成)',
1569
+ onClick: async () => {
1570
+ try {
1571
+ const data = await api('/purge-previews', { method: 'POST' });
1572
+ patch({ notice: `已清理 ${data.cleared} 篇文档的预览缓存`, previewInfo: null });
1573
+ } catch (error) {
1574
+ patch({ error: error.message || '清理失败' });
1575
+ }
1576
+ },
1577
+ }, '清理预览缓存'))),
1578
+ h('section', { className: 'dsh-kb-card' },
1579
+ h('h4', null, '向量检索(可选)'),
1580
+ h('p', { className: 'dsh-kb-hint' },
1581
+ '关键词检索已经可用。想让「意思相近但用词不同」也能命中,接一个 OpenAI 兼容的 embeddings 接口 —— DeepSeek 官方没有这个接口,可以接百炼 / 硅基流动 / Ollama。'),
1582
+ form
1583
+ ? h('div', { className: 'dsh-kb-form' },
1584
+ h('label', { className: 'dsh-kb-check' },
1585
+ h('input', {
1586
+ type: 'checkbox',
1587
+ checked: Boolean(form.enabled),
1588
+ onChange: (event) => setForm({ ...form, enabled: event.target.checked }),
1589
+ }),
1590
+ '启用向量检索'),
1591
+ h('label', { className: 'dsh-kb-field' },
1592
+ h('span', { className: 'dsh-kb-label' }, '接口地址'),
1593
+ h('input', {
1594
+ type: 'text',
1595
+ value: form.baseUrl || '',
1596
+ placeholder: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
1597
+ onChange: (event) => setForm({ ...form, baseUrl: event.target.value }),
1598
+ }),
1599
+ h('span', { className: 'dsh-kb-hint' }, '填到 /v1 为止,不要带 /embeddings')),
1600
+ h('label', { className: 'dsh-kb-field' },
1601
+ h('span', { className: 'dsh-kb-label' }, '模型'),
1602
+ h('input', {
1603
+ type: 'text',
1604
+ value: form.model || '',
1605
+ placeholder: 'text-embedding-v3',
1606
+ onChange: (event) => setForm({ ...form, model: event.target.value }),
1607
+ })),
1608
+ h('label', { className: 'dsh-kb-field' },
1609
+ h('span', { className: 'dsh-kb-label' }, 'API Key'),
1610
+ h('input', {
1611
+ type: 'password',
1612
+ value: form.apiKey || '',
1613
+ placeholder: form.hasKey ? `已保存(尾号 ${form.keyTail}),留空表示不改` : '接口不需要鉴权就留空',
1614
+ onChange: (event) => setForm({ ...form, apiKey: event.target.value }),
1615
+ }),
1616
+ h('span', { className: 'dsh-kb-hint' }, '只存在本机 ~/.dsh/kb/settings.json,不会写进插件配置')),
1617
+ h('div', { className: 'dsh-kb-row2' },
1618
+ h('button', {
1619
+ type: 'button', className: 'dsh-kb-btn dsh-kb-btn--primary',
1620
+ onClick: saveEmbedding, disabled: saving,
1621
+ }, saving ? '保存中…' : '保存'),
1622
+ h('button', {
1623
+ type: 'button', className: 'dsh-kb-btn',
1624
+ onClick: testEmbedding, disabled: probing,
1625
+ }, probing ? '测试中…' : '测试连接')),
1626
+ probe
1627
+ ? h('div', { className: cx('dsh-kb-banner', probe.ok ? 'dsh-kb-banner--ok' : 'dsh-kb-banner--bad'), role: 'status' },
1628
+ probe.ok ? `连接成功:返回 ${probe.dim} 维向量(${probe.model})` : `连接失败:${probe.error}`)
1629
+ : null,
1630
+ formNotice ? h('p', { className: 'dsh-kb-hint' }, formNotice) : null,
1631
+ form.enabled && (stats?.vectors || 0) === 0 && embedding?.enabled
1632
+ ? h('p', { className: 'dsh-kb-hint' }, '已启用,但现有文档还没有向量 —— 点上面「重建全部索引」补上(只补新增文档不算)。')
1633
+ : null)
1634
+ : h('p', { className: 'dsh-kb-hint' }, '读取配置中…'),
1635
+ embedding?.enabled
1636
+ ? h('p', { className: 'dsh-kb-hint' }, `当前状态:已启用 · 模型 ${embedding.model} · 检索时与关键词结果融合(RRF)`)
1637
+ : null),
1638
+ // ── 图片理解(视觉模型)──────────────────────────────────────
1639
+ h('section', { className: 'dsh-kb-card' },
1640
+ h('h4', null, '图片理解(可选)'),
1641
+ h('p', { className: 'dsh-kb-hint' },
1642
+ '图片本身没有文字,所以默认搜不到。打开这里,上传或重建时会用视觉模型把图「描述成文字」,再走同一套关键词 + 向量检索 —— 命中后 AI 也能读出图里写了什么。'),
1643
+ visionForm
1644
+ ? h('div', { className: 'dsh-kb-form' },
1645
+ h('label', { className: 'dsh-kb-check' },
1646
+ h('input', {
1647
+ type: 'checkbox',
1648
+ checked: Boolean(visionForm.enabled),
1649
+ onChange: (event) => setVisionForm({ ...visionForm, enabled: event.target.checked }),
1650
+ }),
1651
+ '启用图片理解'),
1652
+ h('label', { className: 'dsh-kb-field' },
1653
+ h('span', { className: 'dsh-kb-label' }, '服务商'),
1654
+ h('select', {
1655
+ className: 'dsh-kb-select',
1656
+ value: visionForm.preset || 'dashscope',
1657
+ onChange: (event) => {
1658
+ const id = event.target.value;
1659
+ const preset = visionPresets.find((item) => item.id === id);
1660
+ if (!preset) return;
1661
+ setVisionForm({
1662
+ ...visionForm,
1663
+ preset: id,
1664
+ baseUrl: preset.baseUrl || visionForm.baseUrl,
1665
+ model: preset.model || visionForm.model,
1666
+ });
1667
+ },
1668
+ }, (visionPresets.length ? visionPresets : [{ id: 'dashscope', label: '阿里云百炼' }, { id: 'custom', label: '自定义' }])
1669
+ .map((preset) => h('option', { key: preset.id, value: preset.id }, preset.label))),
1670
+ h('span', { className: 'dsh-kb-hint' },
1671
+ (visionPresets.find((item) => item.id === visionForm.preset) || {}).hint
1672
+ || '选一个服务商,接口地址和模型会自动填好;也可以选「自定义」手填')),
1673
+ h('label', { className: 'dsh-kb-field' },
1674
+ h('span', { className: 'dsh-kb-label' }, '接口地址'),
1675
+ h('input', {
1676
+ type: 'text',
1677
+ value: visionForm.baseUrl || '',
1678
+ placeholder: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
1679
+ onChange: (event) => {
1680
+ const value = event.target.value;
1681
+ const normalized = value.trim().replace(/\/+$/, '');
1682
+ const matched = visionPresets.find((item) => item.baseUrl && item.baseUrl === normalized);
1683
+ setVisionForm({ ...visionForm, baseUrl: value, preset: matched ? matched.id : 'custom' });
1684
+ },
1685
+ }),
1686
+ h('span', { className: 'dsh-kb-hint' }, '和向量检索一样填到 /v1 为止(自定义端点也行,只要兼容 /chat/completions)')),
1687
+ h('label', { className: 'dsh-kb-field' },
1688
+ h('span', { className: 'dsh-kb-label' }, '视觉模型'),
1689
+ h('input', {
1690
+ type: 'text',
1691
+ value: visionForm.model || '',
1692
+ placeholder: 'qwen3-vl-plus',
1693
+ onChange: (event) => setVisionForm({ ...visionForm, model: event.target.value }),
1694
+ }),
1695
+ h('span', { className: 'dsh-kb-hint' }, '百炼用 qwen3-vl-plus;OpenAI 用 gpt-4o-mini 也行')),
1696
+ h('label', { className: 'dsh-kb-field' },
1697
+ h('span', { className: 'dsh-kb-label' }, 'API Key'),
1698
+ h('input', {
1699
+ type: 'password',
1700
+ value: visionForm.apiKey || '',
1701
+ placeholder: visionForm.hasKey
1702
+ ? `已保存(尾号 ${visionForm.keyTail}),留空表示不改`
1703
+ : '留空则复用向量检索那把 Key',
1704
+ onChange: (event) => setVisionForm({ ...visionForm, apiKey: event.target.value }),
1705
+ })),
1706
+ h('div', { className: 'dsh-kb-row2' },
1707
+ h('button', {
1708
+ type: 'button', className: 'dsh-kb-btn dsh-kb-btn--primary',
1709
+ onClick: saveVision, disabled: visionSaving,
1710
+ }, visionSaving ? '保存中…' : '保存'),
1711
+ h('button', {
1712
+ type: 'button', className: 'dsh-kb-btn',
1713
+ onClick: testVision, disabled: visionProbing,
1714
+ }, visionProbing ? '测试中…' : '测试连接')),
1715
+ visionProbe
1716
+ ? h('div', { className: cx('dsh-kb-banner', visionProbe.ok ? 'dsh-kb-banner--ok' : 'dsh-kb-banner--bad'), role: 'status' },
1717
+ visionProbe.ok
1718
+ ? `连接成功:${visionProbe.model} · ${visionProbe.ms} ms · 返回「${visionProbe.sample || ''}…」`
1719
+ : `连接失败:${visionProbe.error}`)
1720
+ : null,
1721
+ visionNotice ? h('p', { className: 'dsh-kb-hint' }, visionNotice) : null,
1722
+ visionForm.enabled && !current.caps?.vision?.enabled
1723
+ ? h('p', { className: 'dsh-kb-hint' }, '已勾选但还没生效:检查接口地址和模型,保存后这里会显示「已启用」。')
1724
+ : null)
1725
+ : h('p', { className: 'dsh-kb-hint' }, '读取配置中…'),
1726
+ current.caps?.vision?.enabled
1727
+ ? h('p', { className: 'dsh-kb-hint' },
1728
+ `当前状态:已启用 · 模型 ${current.caps.vision.model} · 新建或重建索引时会把图片描述成文字`)
1729
+ : h('p', { className: 'dsh-kb-hint' }, '当前状态:未启用(图片只能看,搜不到)')),
1730
+ current.error
1731
+ ? h('p', { className: 'dsh-kb-banner dsh-kb-banner--bad', role: 'alert' }, current.error)
1732
+ : null,
1733
+ current.notice ? h('p', { className: 'dsh-kb-hint' }, current.notice) : null);
1734
+ }
1735
+
1736
+ // ── 左侧栏图标 ──────────────────────────────────────────────────────
1737
+ function PanelIcon({ size, active }) {
1738
+ return h('span', { className: cx('dsh-kb-barIcon', active && 'dsh-kb-barIcon--active'), 'aria-hidden': 'true' },
1739
+ h(Icon, { name: 'book', size: size || 18 }));
1740
+ }
1741
+
1742
+ // ── 样式(只用 --dsw-alias-* token,跟随明暗主题)─────────────────────
1743
+ function installStyles() {
1744
+ const style = document.createElement('style');
1745
+ style.id = 'dsh-plugin-knowledge-base-styles';
1746
+ style.textContent = [
1747
+ '.dsh-kb-barIcon{display:inline-flex;align-items:center;justify-content:center;color:inherit;opacity:.8;}',
1748
+ '.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);}',
1749
+ '.dsh-kb-page--drag{outline:2px dashed var(--dsw-alias-label-brand,#1f6feb);outline-offset:-8px;}',
1750
+ '.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;}',
1751
+ '.dsh-kb-brand{display:flex;align-items:center;gap:6px;min-width:0;}',
1752
+ '.dsh-kb-brandIcon{display:inline-flex;color:var(--dsw-alias-label-brand,#1f6feb);}',
1753
+ '.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;}',
1754
+ '.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;}',
1755
+ '.dsh-kb-iconBtn:hover{background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-primary);}',
1756
+ '.dsh-kb-searchBox{position:relative;display:flex;align-items:center;flex:1;min-width:180px;max-width:420px;}',
1757
+ '.dsh-kb-searchIcon{position:absolute;left:9px;color:var(--dsw-alias-label-secondary);pointer-events:none;}',
1758
+ '.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;}',
1759
+ '.dsh-kb-searchInput:focus{outline:none;border-color:var(--dsw-alias-label-brand,#1f6feb);}',
1760
+ '.dsh-kb-searchClear{position:absolute;right:7px;border:none;background:transparent;color:var(--dsw-alias-label-secondary);cursor:pointer;padding:0;display:inline-flex;}',
1761
+ '.dsh-kb-headActions{display:flex;gap:6px;margin-left:auto;}',
1762
+ '.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;}',
1763
+ '.dsh-kb-btn:hover{background:var(--dsw-alias-bg-layer-2);}',
1764
+ '.dsh-kb-btn:disabled{opacity:.5;cursor:default;}',
1765
+ '.dsh-kb-btn--primary{border-color:transparent;background:var(--dsw-alias-label-brand,#1f6feb);color:#fff;}',
1766
+ '.dsh-kb-btn--primary:hover{filter:brightness(1.06);background:var(--dsw-alias-label-brand,#1f6feb);}',
1767
+ '.dsh-kb-btn--danger{color:var(--dsw-alias-label-danger,#d14343);}',
1768
+ '.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);}',
1769
+ '.dsh-kb-banner--info{background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-secondary);}',
1770
+ '.dsh-kb-banner--bad{background:rgba(209,67,67,.10);color:var(--dsw-alias-label-danger,#d14343);}',
1771
+ '.dsh-kb-bannerClose{margin-left:auto;border:none;background:transparent;color:inherit;cursor:pointer;display:inline-flex;}',
1772
+ '.dsh-kb-body{display:flex;flex:1;min-height:0;}',
1773
+ '.dsh-kb-side{width:250px;flex:none;border-right:1px solid var(--dsw-alias-border-l1);overflow-y:auto;padding:6px 0 20px;}',
1774
+ '.dsh-kb-rot180{transform:rotate(180deg);}',
1775
+ '.dsh-kb-moreBtn{font-size:15px;line-height:1;letter-spacing:1px;padding-bottom:3px;}',
1776
+ '.dsh-kb-rowBtn--on{background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-primary);}',
1777
+ '.dsh-kb-menuBackdrop{position:fixed;inset:0;z-index:40;}',
1778
+ '.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;}',
1779
+ '.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;}',
1780
+ '.dsh-kb-menuItem:hover{background:var(--dsw-alias-bg-layer-2);}',
1781
+ '.dsh-kb-menuItem--danger{color:var(--dsw-alias-label-danger,#d14343);}',
1782
+ '.dsh-kb-tree{display:flex;flex-direction:column;}',
1783
+ '.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;}',
1784
+ '.dsh-kb-row:hover{background:var(--dsw-alias-bg-layer-2);}',
1785
+ '.dsh-kb-row--active{background:var(--dsw-alias-bg-layer-2);box-shadow:inset 2px 0 0 var(--dsw-alias-label-brand,#1f6feb);}',
1786
+ '.dsh-kb-caret{display:inline-flex;width:12px;color:var(--dsw-alias-label-secondary);transition:transform .12s ease;}',
1787
+ '.dsh-kb-caret--open{transform:rotate(90deg);}',
1788
+ '.dsh-kb-rowIcon{display:inline-flex;color:var(--dsw-alias-label-secondary);flex:none;}',
1789
+ '.dsh-kb-rowName{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}',
1790
+ '.dsh-kb-dot{width:6px;height:6px;border-radius:50%;flex:none;}',
1791
+ '.dsh-kb-dot--busy{background:var(--dsw-alias-label-warning,#d9a441);}',
1792
+ '.dsh-kb-dot--bad{background:var(--dsw-alias-label-danger,#d14343);}',
1793
+ '.dsh-kb-main{flex:1;min-width:0;display:flex;flex-direction:column;overflow:hidden;}',
1794
+ '.dsh-kb-empty{display:flex;flex-direction:column;align-items:flex-start;gap:6px;padding:40px 28px;color:var(--dsw-alias-label-secondary);}',
1795
+ '.dsh-kb-empty--side{padding:18px 16px;}',
1796
+ '.dsh-kb-emptyIcon{color:var(--dsw-alias-border-l1);}',
1797
+ '.dsh-kb-hint{font-size:12px;line-height:1.6;color:var(--dsw-alias-label-secondary);}',
1798
+ '.dsh-kb-hint--pad{padding:10px 14px;}',
1799
+ '.dsh-kb-doc{display:flex;flex-direction:column;flex:1;min-height:0;}',
1800
+ '.dsh-kb-docHead{padding:14px 20px 0;}',
1801
+ '.dsh-kb-docTitle{font-size:15px;font-weight:600;word-break:break-word;}',
1802
+ '.dsh-kb-docMeta{display:flex;gap:10px;flex-wrap:wrap;margin-top:4px;font-size:12px;color:var(--dsw-alias-label-secondary);}',
1803
+ '.dsh-kb-docActions{display:flex;gap:6px;flex-wrap:wrap;padding:10px 20px 0;}',
1804
+ '.dsh-kb-reader{flex:1;min-height:0;overflow-y:auto;padding:12px 24px 40px;}',
1805
+ // 视觉阅读(PDF / Office):铺满整块区域,去掉内边距和外框,让阅读器自己占满
1806
+ '.dsh-kb-reader--visual{display:flex;flex-direction:column;padding:0;overflow:hidden;}',
1807
+ '.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;}',
1808
+ '.dsh-kb-reader--visual .dsh-kb-frameWrap{flex:1 1 auto;min-height:0;display:flex;}',
1809
+ '.dsh-kb-reader--visual .dsh-kb-frameLoading{border:none;border-radius:0;}',
1810
+ // 逐页图片阅读器(Office):自己画,不套浏览器 PDF 阅读器
1811
+ '.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);}',
1812
+ '.dsh-kb-pageShot{position:relative;width:min(100%,1180px);}',
1813
+ '.dsh-kb-pageImg{display:block;width:100%;height:auto;border-radius:6px;background:#fff;box-shadow:0 2px 10px rgba(0,0,0,.18);}',
1814
+ '.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;}',
1815
+ '.dsh-kb-pagesNote{font-size:12px;color:var(--dsw-alias-label-secondary);padding:2px 4px 6px;text-align:center;}',
1816
+ '.dsh-kb-viewer{display:flex;flex-direction:column;flex:1;min-height:0;}',
1817
+ '.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);}',
1818
+ '.dsh-kb-viewerGrow{flex:1;min-width:8px;}',
1819
+ '.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;}',
1820
+ '.dsh-kb-navBtn:hover:not(:disabled){background:var(--dsw-alias-bg-layer-2);}',
1821
+ '.dsh-kb-navBtn:disabled{opacity:.4;cursor:default;}',
1822
+ '.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;}',
1823
+ '.dsh-kb-pageInput:focus{outline:none;border-color:var(--dsw-alias-label-brand,#1f6feb);}',
1824
+ '.dsh-kb-pageTotal{font-size:12px;color:var(--dsw-alias-label-secondary);white-space:nowrap;}',
1825
+ '.dsh-kb-pages--single{align-items:center;justify-content:center;padding:12px;overflow:hidden;}',
1826
+ '.dsh-kb-pages--single .dsh-kb-pageShot{width:100%;height:100%;max-width:1180px;display:flex;align-items:center;justify-content:center;}',
1827
+ '.dsh-kb-pages--single .dsh-kb-pageImg{width:100%;height:100%;object-fit:contain;border-radius:0;box-shadow:none;background:transparent;}',
1828
+ '.dsh-kb-pages--single .dsh-kb-pageNo{display:none;}',
1829
+ '.dsh-kb-viewerBody{display:flex;flex:1;min-height:0;}',
1830
+ '.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);}',
1831
+ '.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;}',
1832
+ '.dsh-kb-thumb:hover{border-color:var(--dsw-alias-border-l1);}',
1833
+ '.dsh-kb-thumb--on{border-color:var(--dsw-alias-label-brand,#1f6feb);}',
1834
+ '.dsh-kb-thumbImg{display:block;width:100%;height:auto;border-radius:4px;background:#fff;}',
1835
+ '.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;}',
1836
+ '.dsh-kb-pagesLoading--error{gap:12px;}',
1837
+ '.dsh-kb-pagesErrorTitle{display:flex;align-items:center;gap:6px;font-size:13.5px;font-weight:600;color:var(--dsw-alias-label-primary);}',
1838
+ '.dsh-kb-pagesErrorText{margin:0;font-size:12.5px;color:var(--dsw-alias-label-secondary);line-height:1.6;max-width:560px;}',
1839
+ '.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);}',
1840
+ '.dsh-kb-text{max-width:820px;font-size:13.5px;line-height:1.78;}',
1841
+ '.dsh-kb-p{margin:0 0 10px;white-space:pre-wrap;word-break:break-word;}',
1842
+ '.dsh-kb-h{margin:16px 0 8px;font-weight:600;}',
1843
+ '.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;}',
1844
+ '.dsh-kb-pageMark{margin:14px 0 6px;font-size:11.5px;color:var(--dsw-alias-label-secondary);letter-spacing:.04em;}',
1845
+ '.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);}',
1846
+ '.dsh-kb-mark{background:rgba(217,164,65,.32);color:inherit;border-radius:2px;}',
1847
+ '.dsh-kb-image{max-width:100%;border-radius:10px;border:1px solid var(--dsw-alias-border-l1);}',
1848
+ '.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;}',
1849
+ '.dsh-kb-frameWrap{position:relative;flex:1;min-height:520px;display:flex;}',
1850
+ '.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;}',
1851
+ '.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;}',
1852
+ '@keyframes dsh-kb-spin{to{transform:rotate(360deg);}}',
1853
+ '.dsh-kb-seg{display:inline-flex;align-items:center;gap:2px;padding:2px;border:1px solid var(--dsw-alias-border-l1);border-radius:8px;}',
1854
+ '.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;}',
1855
+ '.dsh-kb-segBtn--on{background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-primary);font-weight:600;}',
1856
+ '.dsh-kb-more{margin-top:14px;}',
1857
+ '.dsh-kb-hits{display:flex;flex-direction:column;gap:8px;padding:14px 20px 30px;overflow-y:auto;}',
1858
+ '.dsh-kb-hitsHead{font-size:12px;color:var(--dsw-alias-label-secondary);}',
1859
+ '.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;}',
1860
+ '.dsh-kb-hit:hover{background:var(--dsw-alias-bg-layer-2);}',
1861
+ '.dsh-kb-hitName{font-size:12.5px;font-weight:600;}',
1862
+ '.dsh-kb-hitHead{font-weight:400;color:var(--dsw-alias-label-secondary);}',
1863
+ '.dsh-kb-hitSnippet{font-size:12px;line-height:1.6;color:var(--dsw-alias-label-secondary);white-space:pre-wrap;}',
1864
+ '.dsh-kb-settings{display:flex;flex-direction:column;gap:14px;}',
1865
+ '.dsh-kb-settingsPane{display:flex;flex-direction:column;flex:1;min-height:0;padding:14px 20px 36px;overflow-y:auto;}',
1866
+ '.dsh-kb-settingsHead{display:flex;align-items:center;gap:10px;margin-bottom:14px;}',
1867
+ '.dsh-kb-iconBtn--on{background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-primary);}',
1868
+ '.dsh-kb-settingsIntro{margin:0;font-size:12px;line-height:1.6;color:var(--dsw-alias-label-secondary);}',
1869
+ '.dsh-kb-card{display:flex;flex-direction:column;gap:8px;padding:14px;border:1px solid var(--dsw-alias-border-l1);border-radius:12px;}',
1870
+ '.dsh-kb-card h4{margin:0;font-size:13px;font-weight:600;}',
1871
+ '.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;}',
1872
+ '.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;}',
1873
+ '.dsh-kb-kv strong{color:var(--dsw-alias-label-primary);font-weight:600;}',
1874
+ '.dsh-kb-row2{display:flex;gap:8px;}',
1875
+ '.dsh-kb-form{display:flex;flex-direction:column;gap:10px;}',
1876
+ '.dsh-kb-check{display:flex;align-items:center;gap:7px;font-size:12.5px;cursor:pointer;}',
1877
+ '.dsh-kb-check input{width:14px;height:14px;margin:0;}',
1878
+ '.dsh-kb-field{display:flex;flex-direction:column;gap:4px;}',
1879
+ '.dsh-kb-label{font-size:11.5px;color:var(--dsw-alias-label-secondary);}',
1880
+ '.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;}',
1881
+ '.dsh-kb-form input:focus{outline:none;border-color:var(--dsw-alias-label-brand,#1f6feb);}',
1882
+ '.dsh-kb-banner--ok{background:rgba(34,160,90,.12);color:#228a4e;}',
1883
+ '.dsh-kb-progress{display:flex;flex-direction:column;gap:5px;margin:2px 0 4px;}',
1884
+ '.dsh-kb-progressTrack{height:6px;border-radius:999px;background:var(--dsw-alias-bg-layer-2);overflow:hidden;}',
1885
+ '.dsh-kb-progressFill{height:100%;border-radius:999px;background:var(--dsw-alias-label-brand,#1f6feb);transition:width .25s ease;}',
1886
+ '.dsh-kb-progressText{font-size:11.5px;color:var(--dsw-alias-label-secondary);}',
1887
+ // 看板
1888
+ '.dsh-kb-dash{display:flex;flex-direction:column;gap:14px;flex:1;min-height:0;overflow-y:auto;padding:16px 20px 36px;}',
1889
+ '.dsh-kb-dashHead{display:flex;align-items:center;gap:10px;flex-wrap:wrap;}',
1890
+ '.dsh-kb-metrics{display:grid;grid-template-columns:repeat(auto-fit,minmax(120px,1fr));gap:10px;}',
1891
+ '.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);}',
1892
+ '.dsh-kb-metricLabel{font-size:11.5px;color:var(--dsw-alias-label-secondary);}',
1893
+ '.dsh-kb-metricValue{font-size:20px;font-weight:700;line-height:1.3;}',
1894
+ '.dsh-kb-metricHint{font-size:11px;color:var(--dsw-alias-label-secondary);}',
1895
+ '.dsh-kb-dashGrid{display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:12px;align-items:start;}',
1896
+ '.dsh-kb-subHead{margin-top:12px!important;}',
1897
+ '.dsh-kb-distRow{display:flex;align-items:center;gap:8px;font-size:12px;}',
1898
+ '.dsh-kb-distLabel{flex:none;width:46px;color:var(--dsw-alias-label-secondary);font-family:ui-monospace,Menlo,monospace;font-size:11.5px;}',
1899
+ '.dsh-kb-distLabel--wide{width:96px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-family:inherit;color:var(--dsw-alias-label-primary);}',
1900
+ '.dsh-kb-distValue{flex:none;font-size:11.5px;color:var(--dsw-alias-label-secondary);}',
1901
+ '.dsh-kb-bar{flex:1;height:6px;border-radius:999px;background:var(--dsw-alias-bg-layer-2);overflow:hidden;}',
1902
+ '.dsh-kb-bar i{display:block;height:100%;border-radius:999px;background:var(--dsw-alias-label-brand,#1f6feb);}',
1903
+ '.dsh-kb-chips{display:flex;flex-wrap:wrap;gap:6px;}',
1904
+ '.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);}',
1905
+ '.dsh-kb-chip--ok{color:#228a4e;border-color:rgba(34,160,90,.4);}',
1906
+ '.dsh-kb-chip--bad{color:var(--dsw-alias-label-danger,#d14343);border-color:rgba(209,67,67,.4);}',
1907
+ '.dsh-kb-chip--busy{color:#a8741a;border-color:rgba(217,164,65,.5);}',
1908
+ '.dsh-kb-spark{display:flex;align-items:flex-end;gap:6px;height:76px;padding:6px 2px 0;}',
1909
+ '.dsh-kb-sparkCol{flex:1;display:flex;flex-direction:column;align-items:center;justify-content:flex-end;gap:4px;height:100%;}',
1910
+ '.dsh-kb-sparkBar{width:100%;max-width:26px;border-radius:4px 4px 0 0;background:var(--dsw-alias-label-brand,#1f6feb);opacity:.75;}',
1911
+ '.dsh-kb-sparkLabel{font-size:10px;color:var(--dsw-alias-label-secondary);}',
1912
+ '.dsh-kb-kv--tight{grid-template-columns:auto 1fr auto 1fr;font-size:11.5px;}',
1913
+ '.dsh-kb-list{display:flex;flex-direction:column;gap:4px;}',
1914
+ '.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);}',
1915
+ '.dsh-kb-listRow:last-child{border-bottom:none;}',
1916
+ '.dsh-kb-listMain{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}',
1917
+ '.dsh-kb-listMeta{flex:none;font-size:11px;color:var(--dsw-alias-label-secondary);}',
1918
+ '.dsh-kb-listTime{flex:none;font-size:11px;color:var(--dsw-alias-label-secondary);width:56px;text-align:right;}',
1919
+ '.dsh-kb-barIcon--active{opacity:1;color:var(--dsw-alias-label-brand,#1f6feb);}',
1920
+ '.dsh-kb-rowActions{display:none;gap:2px;flex:none;}',
1921
+ '.dsh-kb-row:hover .dsh-kb-rowActions,.dsh-kb-row:focus-visible .dsh-kb-rowActions{display:inline-flex;}',
1922
+ '.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;}',
1923
+ '.dsh-kb-rowBtn:hover{background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary);}',
1924
+ '.dsh-kb-rowBtn--danger:hover{color:var(--dsw-alias-label-danger,#d14343);}',
1925
+ '.dsh-kb-row:focus-visible{outline:2px solid var(--dsw-alias-label-brand,#1f6feb);outline-offset:-2px;}',
1926
+ '.dsh-kb-rowHint{font-size:11.5px;color:var(--dsw-alias-label-secondary);padding:4px 8px 4px 0;}',
1927
+ '.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;}',
1928
+ '.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;}',
1929
+ '.dsh-kb-moveItem:hover{background:var(--dsw-alias-bg-layer-2);}',
1930
+ '.dsh-kb-big{position:fixed;inset:0;z-index:3000;display:flex;flex-direction:column;background:var(--dsw-alias-bg-layer-1);}',
1931
+ '.dsh-kb-bigBar{display:flex;flex:none;align-items:center;gap:10px;padding:10px 16px;border-bottom:1px solid var(--dsw-alias-border-l1);}',
1932
+ '.dsh-kb-bigTitle{font-size:13px;font-weight:600;max-width:42%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}',
1933
+ '.dsh-kb-bigNav{display:flex;align-items:center;gap:8px;}',
1934
+ '.dsh-kb-bigBody .dsh-kb-pages--single .dsh-kb-pageShot{max-width:1400px;}',
1935
+ '.dsh-kb-bigBody{flex:1;min-height:0;display:flex;flex-direction:column;background:var(--dsw-alias-bg-layer-2);}',
1936
+ '.dsh-kb-bigBody .dsh-kb-pages{padding:18px 22px 40px;}',
1937
+ '.dsh-kb-bigBody .dsh-kb-pageShot{max-width:1400px;}',
1938
+ '.dsh-kb-bigImg{max-width:100%;max-height:100%;object-fit:contain;margin:auto;display:block;}',
1939
+ '.dsh-kb-bigFrame{flex:1;min-height:0;width:100%;border:none;background:#fff;}',
1940
+ '.dsh-kb-btn--dangerSolid{border-color:transparent;background:var(--dsw-alias-label-danger,#d14343);color:#fff;}',
1941
+ '.dsh-kb-btn--dangerSolid:hover{filter:brightness(1.06);}',
1942
+ '.dsh-kb-mask{position:absolute;inset:0;z-index:20;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,.28);}',
1943
+ '.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);}',
1944
+ '.dsh-kb-modalTitle{font-size:13px;font-weight:600;line-height:1.5;}',
1945
+ '.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;}',
1946
+ '.dsh-kb-modalInput:focus{outline:none;border-color:var(--dsw-alias-label-brand,#1f6feb);}',
1947
+ '.dsh-kb-modalActions{display:flex;justify-content:flex-end;gap:8px;}',
1948
+ ].join('\n');
1949
+ document.head.appendChild(style);
1950
+ return () => style.remove();
1951
+ }
1952
+
1953
+ // ── 插件入口 ────────────────────────────────────────────────────────
1954
+ function apply(ctx) {
1955
+ const slots = ctx.get('slots');
1956
+ if (!slots) return;
1957
+ ctx.effect(installStyles, 'knowledge-base: styles');
1958
+
1959
+ // 组件拿不到 ctx,所以把"开会话"这件事留在模块作用域里
1960
+ sessionStarter = (prompt) => {
1961
+ const workspace = ctx.get('uiWorkspace');
1962
+ if (!workspace?.startSession) {
1963
+ patch({ error: '会话服务还没就绪,稍后再点一次' });
1964
+ return;
1965
+ }
1966
+ try {
1967
+ workspace.startSession(undefined, { prompt, whenDraftExists: 'append' });
1968
+ } catch (error) {
1969
+ patch({ error: `开会话失败:${error.message || error}` });
1970
+ }
1971
+ };
1972
+
1973
+ ctx.effect(() => slots.inject('sidebar.panellist', () => slots.register({
1974
+ name: 'sidebar.panellist',
1975
+ id: PANEL_ID,
1976
+ order: 25,
1977
+ label: () => '知识库',
1978
+ }, PanelIcon)), 'knowledge-base: panellist icon');
1979
+
1980
+ ctx.effect(() => slots.inject('main', () => slots.register({
1981
+ name: 'main',
1982
+ key: PANEL_ID,
1983
+ }, KbPage)), 'knowledge-base: main page');
1984
+
1985
+ ctx.effect(() => slots.inject('settings.section', () => slots.register({
1986
+ name: 'settings.section',
1987
+ id: 'dsh-knowledge-base-settings',
1988
+ order: 26,
1989
+ label: () => '知识库',
1990
+ }, SettingsSection)), 'knowledge-base: settings section');
1991
+ }
1992
+
1993
+ const plugin = { inject: ['slots'], apply };
1994
+ // 仅测试用:让离线冒烟测试能摆出各种状态再渲染(浏览器里不生效)
1995
+ if (typeof globalThis !== 'undefined' && globalThis.__DSH_KB_TEST__) {
1996
+ plugin.__test = { patch, state, askText, askConfirm, renderText, isImage };
1997
+ }
1998
+ return plugin;
1999
+ },
2000
+ });