chatluna-plugin-kb 0.1.7 → 0.2.7

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/index.mjs CHANGED
@@ -41,11 +41,12 @@ import { createSystemdController } from './src/engine/systemd.mjs'
41
41
  import { ensureBootstrap } from './src/engine/bootstrap.mjs'
42
42
  import { registerKbProxy } from './src/proxy/webui-proxy.mjs'
43
43
  import { registerKbWebUI } from './src/webui/server.mjs'
44
- import { registerInstallRoutes } from './src/webui/install-routes.mjs'
44
+ import { registerInstallRoutes, createInstallStatusBridge } from './src/webui/install-routes.mjs'
45
45
  import { registerModelRoutes } from './src/webui/model-routes.mjs'
46
46
  import { createModelBridge } from './src/webui/models.mjs'
47
47
  import { createInstaller, DEFAULT_RELEASE_MANIFEST_URL, platformInfo } from './src/engine/installer.mjs'
48
48
  import { detectEnvironment } from './src/engine/runtime-probe.mjs'
49
+ import { ensureLocalOcrDeps } from './src/engine/deps-installer.mjs'
49
50
  import { resolveScope } from './src/policy/scope.mjs'
50
51
  import {
51
52
  denied,
@@ -428,6 +429,14 @@ export function apply(ctx, config) {
428
429
  } catch {}
429
430
  }
430
431
 
432
+ // 安装器快照 → 事件桥:进度只推 install;进入终态(installed/failed/cancelled)或
433
+ // installed 翻转时补推 status,同一结论只发一次,三条安装路径(一键/URL/离线上传)共用。
434
+ const installEvents = createInstallStatusBridge({
435
+ emitInstall,
436
+ emitStatus,
437
+ isInstalled: () => existsSync(binaryPath)
438
+ })
439
+
431
440
  // ---- 安装器(仅 managed:负责下载/校验/解包到 <dataDir>/weknora-lite) ----
432
441
  let installer = null
433
442
  if (managed) {
@@ -439,8 +448,8 @@ export function apply(ctx, config) {
439
448
  releaseManifestUrl: config.releaseManifestUrl || DEFAULT_RELEASE_MANIFEST_URL,
440
449
  mirrors: Array.isArray(config.installMirrors) ? config.installMirrors : [],
441
450
  pluginVersion: String(config.pluginVersion ?? '').trim(),
442
- onStatus: () => {
443
- emitInstall()
451
+ onStatus: (snap) => {
452
+ installEvents.handleStatus(snap)
444
453
  },
445
454
  logger
446
455
  })
@@ -454,6 +463,33 @@ export function apply(ctx, config) {
454
463
  ? installer.status()
455
464
  : { supported: false, state: 'unavailable', installed: existsSync(binaryPath) }
456
465
 
466
+ // 本地 OCR 系统组件补齐:非阻塞;失败只返回警告,绝不把核心引擎安装标为失败。
467
+ // 成功后清空探测缓存并广播 status,让向导/引擎状态页立刻看到 OCR 变绿。
468
+ async function installDeps() {
469
+ let result
470
+ try {
471
+ result = await ensureLocalOcrDeps({
472
+ probe: () => probeEnvironment(),
473
+ logger
474
+ })
475
+ } catch (err) {
476
+ result = {
477
+ ok: false,
478
+ skipped: false,
479
+ ready: false,
480
+ missing: ['tesseract', 'pdftoppm'],
481
+ manager: null,
482
+ message: `本地 OCR 组件安装失败:${sanitizeError(err)}`,
483
+ code: 'INSTALL_FAILED'
484
+ }
485
+ }
486
+ envProbe.key = ''
487
+ envProbe.at = 0
488
+ envProbe.promise = null
489
+ emitStatus()
490
+ return result
491
+ }
492
+
457
493
  // ---- 运行环境探测(只读、60s 缓存;状态快照与 kb.detect 共用) ----------
458
494
  const ENV_PROBE_TTL_MS = 60_000
459
495
  const envProbe = { key: '', at: 0, promise: null }
@@ -979,12 +1015,10 @@ export function apply(ctx, config) {
979
1015
  const engineInstaller = requireInstaller('自动安装')
980
1016
  try {
981
1017
  const result = await engineInstaller.installFromRelease()
982
- emitInstall()
983
- emitStatus()
1018
+ installEvents.handleStatus({ state: 'ready' })
984
1019
  return result ?? { ok: true }
985
1020
  } catch (err) {
986
- emitInstall()
987
- emitStatus()
1021
+ installEvents.handleStatus({ state: 'error' })
988
1022
  throw new Error(sanitizeError(err))
989
1023
  }
990
1024
  }
@@ -996,12 +1030,10 @@ export function apply(ctx, config) {
996
1030
  try {
997
1031
  const options = typeof input?.sha256 === 'string' && input.sha256 !== '' ? { sha256: input.sha256 } : {}
998
1032
  const result = await engineInstaller.installFromUrl(url, options)
999
- emitInstall()
1000
- emitStatus()
1033
+ installEvents.handleStatus({ state: 'ready' })
1001
1034
  return result ?? { ok: true }
1002
1035
  } catch (err) {
1003
- emitInstall()
1004
- emitStatus()
1036
+ installEvents.handleStatus({ state: 'error' })
1005
1037
  throw new Error(sanitizeError(err))
1006
1038
  }
1007
1039
  }
@@ -1018,12 +1050,10 @@ export function apply(ctx, config) {
1018
1050
  try {
1019
1051
  const options = typeof input?.sha256 === 'string' && input.sha256 !== '' ? { sha256: input.sha256 } : {}
1020
1052
  const result = await engineInstaller.installFromFile(path, options)
1021
- emitInstall()
1022
- emitStatus()
1053
+ installEvents.handleStatus({ state: 'ready' })
1023
1054
  return result ?? { ok: true }
1024
1055
  } catch (err) {
1025
- emitInstall()
1026
- emitStatus()
1056
+ installEvents.handleStatus({ state: 'error' })
1027
1057
  throw new Error(sanitizeError(err))
1028
1058
  }
1029
1059
  }
@@ -1183,6 +1213,8 @@ export function apply(ctx, config) {
1183
1213
  // ---- ChatLuna → WeKnora 模型复制桥:列表只读元数据,导入时临时物化密钥 ----
1184
1214
  const modelBridge = createModelBridge({
1185
1215
  ctx,
1216
+ bootstrapFile: join(dataDir, 'bootstrap.json'),
1217
+ defaultKbId: runtime.kbId,
1186
1218
  baseUrl: () => {
1187
1219
  if (runtime.baseUrl !== '') return runtime.baseUrl
1188
1220
  const engineStatus = typeof manager?.status === 'function' ? (manager.status() ?? {}) : {}
@@ -1200,6 +1232,7 @@ export function apply(ctx, config) {
1200
1232
  const listChatlunaModels = () => modelBridge.listChatlunaModels()
1201
1233
  const importChatlunaModel = (input) => modelBridge.importChatlunaModel(input)
1202
1234
  const listWeKnoraModels = () => modelBridge.listWeKnoraModels()
1235
+ const syncChatlunaModels = (input) => modelBridge.syncChatlunaModels(input)
1203
1236
  async function catalog() {
1204
1237
  if (catalogCache !== null && Date.now() - catalogCache.at < CATALOG_TTL_MS) return catalogCache.list
1205
1238
  const list = await client.listKbsRaw()
@@ -1626,6 +1659,7 @@ export function apply(ctx, config) {
1626
1659
  prefix: '/kb-admin',
1627
1660
  installer,
1628
1661
  authorize: (context, req) => isWebuiAuthorized(context ?? ctx, req, logger),
1662
+ onInstalled: (snapshot) => installEvents.handleStatus(snapshot),
1629
1663
  maxBytes: INSTALL_UPLOAD_MAX,
1630
1664
  logger
1631
1665
  })
@@ -1647,6 +1681,7 @@ export function apply(ctx, config) {
1647
1681
  authorize: (context, req) => isWebuiAuthorized(context ?? ctx, req, logger),
1648
1682
  listModels: listChatlunaModels,
1649
1683
  importModel: importChatlunaModel,
1684
+ syncModels: syncChatlunaModels,
1650
1685
  listWeKnoraModels,
1651
1686
  logger
1652
1687
  })
@@ -1680,9 +1715,11 @@ export function apply(ctx, config) {
1680
1715
  cancelInstall,
1681
1716
  testEmbedding,
1682
1717
  saveEmbedding,
1718
+ installDeps,
1683
1719
  // 模型复制:列表已脱敏;导入返回 WeKnora 模型 id/维度,不含密钥。
1684
1720
  listChatlunaModels,
1685
1721
  importChatlunaModel,
1722
+ syncChatlunaModels,
1686
1723
  listWeKnoraModels,
1687
1724
  ruleOptions: readRuleOptions
1688
1725
  })
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "chatluna-plugin-kb",
3
- "version": "0.1.7",
3
+ "version": "0.2.7",
4
4
  "description": "ChatLuna v2 knowledge base plugin: WeKnora REST tools, managed weknora-lite engine and WebUI install wizard",
5
5
  "type": "module",
6
6
  "main": "index.mjs",
@@ -0,0 +1,410 @@
1
+ // 本地 OCR 系统依赖补齐(向导安装步骤 / 引擎状态页「一键补齐」共用)。
2
+ //
3
+ // 不变量(改代码前先读):
4
+ // - 全程 execFile + 固定白名单参数数组:绝不使用 shell 字符串拼接,命令与参数都由本模块常量给出。
5
+ // - 绝不 throw:无权限、未知发行版、未知平台、无包管理器、断网、包管理器失败、超时/取消
6
+ // 一律返回 { ok:false, ... } 的非阻塞降级结果,由调用方继续推进核心引擎安装。
7
+ // - 有界执行:每次外部命令都有超时,整体硬超时默认 180s;每一步都按剩余预算设置 timeout,
8
+ // 并透传 AbortSignal(向导「取消安装」),超时只降级不重试。
9
+ // - 提权最小化:仅 Linux 非 root 时探测 `sudo -n true`;失败即放弃,绝不尝试交互式 sudo 或密码。
10
+ // - 先探测后安装:tesseract / pdftoppm 已就绪直接跳过;安装成功后重新探测,以探测结果为准。
11
+ // - 日志只记录阶段与包管理器名称:绝不打印环境变量、命令输出或任何凭据。
12
+ import { execFile } from 'node:child_process'
13
+
14
+ import { detectEnvironment } from './runtime-probe.mjs'
15
+
16
+ const DEFAULT_TIMEOUT_MS = 180_000
17
+ const COMMAND_EXISTS_TIMEOUT_MS = 2_000
18
+ const SUDO_CHECK_TIMEOUT_MS = 5_000
19
+ const MAX_BUFFER_BYTES = 256 * 1024
20
+
21
+ const DEP_LABELS = ['tesseract', 'pdftoppm']
22
+
23
+ // 白名单:命令 + 参数数组。env 只用于强制非交互,绝不从外部输入拼接。
24
+ const MANAGERS = {
25
+ 'apt-get': {
26
+ label: 'apt-get',
27
+ manual: 'sudo apt-get update && sudo apt-get install -y --no-install-recommends tesseract-ocr poppler-utils',
28
+ steps: () => [
29
+ { args: ['update'], env: { DEBIAN_FRONTEND: 'noninteractive' } },
30
+ {
31
+ args: ['install', '-y', '--no-install-recommends', 'tesseract-ocr', 'poppler-utils'],
32
+ env: { DEBIAN_FRONTEND: 'noninteractive' }
33
+ }
34
+ ]
35
+ },
36
+ apk: {
37
+ label: 'apk',
38
+ manual: 'sudo apk add --no-cache tesseract-ocr poppler-utils',
39
+ steps: () => [{ args: ['add', '--no-cache', 'tesseract-ocr', 'poppler-utils'] }]
40
+ },
41
+ dnf: {
42
+ label: 'dnf',
43
+ manual: 'sudo dnf install -y tesseract poppler-utils',
44
+ steps: () => [{ args: ['install', '-y', 'tesseract', 'poppler-utils'] }]
45
+ },
46
+ yum: {
47
+ label: 'yum',
48
+ manual: 'sudo yum install -y tesseract poppler-utils',
49
+ steps: () => [{ args: ['install', '-y', 'tesseract', 'poppler-utils'] }]
50
+ },
51
+ pacman: {
52
+ label: 'pacman',
53
+ manual: 'sudo pacman -Sy --noconfirm --needed tesseract poppler',
54
+ steps: () => [{ args: ['-Sy', '--noconfirm', '--needed', 'tesseract', 'poppler'] }]
55
+ },
56
+ brew: {
57
+ label: 'brew',
58
+ manual: 'brew install tesseract poppler',
59
+ steps: () => [{ args: ['install', 'tesseract', 'poppler'] }]
60
+ }
61
+ }
62
+
63
+ const LINUX_MANAGER_ORDER = ['apt-get', 'apk', 'dnf', 'yum', 'pacman']
64
+
65
+ function int(value, min, max, fallback) {
66
+ const n = Number(value)
67
+ if (!Number.isFinite(n)) return fallback
68
+ return Math.min(max, Math.max(min, Math.trunc(n)))
69
+ }
70
+
71
+ function safeLog(logger, level, message) {
72
+ try {
73
+ const fn = logger?.[level]
74
+ if (typeof fn === 'function') fn.call(logger, message)
75
+ } catch {
76
+ // 日志失败绝不影响安装流程。
77
+ }
78
+ }
79
+
80
+ function result({ ok, skipped, ready, missing, manager, message, code }) {
81
+ return { ok, skipped, ready, missing, manager, message, code }
82
+ }
83
+
84
+ // 探测结果归一化:接受 detectEnvironment 的完整快照或最小 { tesseractFound, pdftoppmFound }。
85
+ function normalizeProbe(value) {
86
+ const tesseractFound = value?.tesseractFound === true || value?.ocr?.tesseractFound === true
87
+ const pdftoppmFound = value?.pdftoppmFound === true || value?.ocr?.pdftoppmFound === true
88
+ const missing = []
89
+ if (!tesseractFound) missing.push('tesseract')
90
+ if (!pdftoppmFound) missing.push('pdftoppm')
91
+ return { ready: missing.length === 0, missing }
92
+ }
93
+
94
+ function createRunCommand(execFileImpl, deadline, externalSignal) {
95
+ return function runCommand(command, args, { timeoutMs, env } = {}) {
96
+ const remaining = Math.min(timeoutMs ?? DEFAULT_TIMEOUT_MS, deadline - Date.now())
97
+ return new Promise((resolvePromise) => {
98
+ const signal = externalSignal
99
+ if (signal?.aborted) {
100
+ resolvePromise({ ok: false, code: 'ABORTED' })
101
+ return
102
+ }
103
+ if (remaining <= 0) {
104
+ resolvePromise({ ok: false, code: 'TIMEOUT' })
105
+ return
106
+ }
107
+
108
+ const options = {
109
+ timeout: remaining,
110
+ killSignal: 'SIGKILL',
111
+ maxBuffer: MAX_BUFFER_BYTES,
112
+ windowsHide: true
113
+ }
114
+ if (env && typeof env === 'object') options.env = env
115
+ if (signal) options.signal = signal
116
+
117
+ let settled = false
118
+ let timer = null
119
+ const finish = (outcome) => {
120
+ if (settled) return
121
+ settled = true
122
+ clearTimeout(timer)
123
+ if (signal && typeof signal.removeEventListener === 'function') {
124
+ signal.removeEventListener('abort', onAbort)
125
+ }
126
+ resolvePromise(outcome)
127
+ }
128
+ function onAbort() {
129
+ finish({ ok: false, code: 'ABORTED' })
130
+ }
131
+ if (signal && typeof signal.addEventListener === 'function') {
132
+ signal.addEventListener('abort', onAbort, { once: true })
133
+ }
134
+ timer = setTimeout(() => finish({ ok: false, code: 'TIMEOUT' }), remaining)
135
+ timer.unref?.()
136
+
137
+ try {
138
+ execFileImpl(command, args, options, (err, stdout, stderr) => {
139
+ if (!err) {
140
+ finish({ ok: true, code: 'OK', stdout, stderr })
141
+ return
142
+ }
143
+ const code = err.code === 'ENOENT' ? 'ENOENT' : 'FAILED'
144
+ finish({ ok: false, code, error: err, stdout, stderr })
145
+ })
146
+ } catch (err) {
147
+ finish({ ok: false, code: err?.code === 'ENOENT' ? 'ENOENT' : 'FAILED', error: err })
148
+ }
149
+ })
150
+ }
151
+ }
152
+
153
+ function baseEnv(env) {
154
+ if (env && typeof env === 'object') return env
155
+ return process.env
156
+ }
157
+
158
+ function stepEnv(step, env) {
159
+ if (!step.env) return env && typeof env === 'object' ? env : undefined
160
+ return { ...baseEnv(env), ...step.env }
161
+ }
162
+
163
+ function isRoot(getuid) {
164
+ try {
165
+ return typeof getuid === 'function' && getuid() === 0
166
+ } catch {
167
+ return false
168
+ }
169
+ }
170
+
171
+ export async function ensureLocalOcrDeps(options = {}) {
172
+ const execFileImpl = typeof options.execFileImpl === 'function' ? options.execFileImpl : execFile
173
+ const platform = options.platform ?? process.platform
174
+ const getuid = options.getuid === undefined ? process.getuid : options.getuid
175
+ const logger = options.logger ?? null
176
+ const timeoutMs = int(options.timeoutMs, 100, 3_600_000, DEFAULT_TIMEOUT_MS)
177
+ const force = options.force === true
178
+ const externalSignal = options.signal ?? null
179
+ const env = options.env && typeof options.env === 'object' ? options.env : undefined
180
+
181
+ let initialMissing = [...DEP_LABELS]
182
+ let manager = null
183
+ let useSudo = false
184
+
185
+ try {
186
+ if (externalSignal?.aborted) {
187
+ return result({
188
+ ok: false,
189
+ skipped: false,
190
+ ready: false,
191
+ missing: initialMissing,
192
+ manager: null,
193
+ message: '已取消本地 OCR 组件安装',
194
+ code: 'CANCELLED'
195
+ })
196
+ }
197
+
198
+ const deadline = Date.now() + timeoutMs
199
+ const runCommand = createRunCommand(execFileImpl, deadline, externalSignal)
200
+
201
+ const probe =
202
+ typeof options.probe === 'function'
203
+ ? options.probe
204
+ : () => detectEnvironment({ platform, env })
205
+
206
+ const probeOnce = async () => normalizeProbe(await probe())
207
+ const first = await probeOnce()
208
+ initialMissing = first.missing
209
+
210
+ if (first.ready && !force) {
211
+ return result({
212
+ ok: true,
213
+ skipped: true,
214
+ ready: true,
215
+ missing: [],
216
+ manager: null,
217
+ message: '本地 OCR 组件已就绪(tesseract / pdftoppm)',
218
+ code: 'ALREADY_READY'
219
+ })
220
+ }
221
+
222
+ const commandExists = async (command) => {
223
+ const res = await runCommand(command, ['--version'], { timeoutMs: COMMAND_EXISTS_TIMEOUT_MS })
224
+ return res.code !== 'ENOENT' && res.code !== 'ABORTED' && res.code !== 'TIMEOUT'
225
+ ? res.ok || res.code === 'FAILED'
226
+ : false
227
+ }
228
+
229
+ if (platform === 'linux') {
230
+ for (const candidate of LINUX_MANAGER_ORDER) {
231
+ if (await commandExists(candidate)) {
232
+ manager = candidate
233
+ break
234
+ }
235
+ }
236
+ } else if (platform === 'darwin') {
237
+ if (await commandExists('brew')) manager = 'brew'
238
+ } else {
239
+ return result({
240
+ ok: false,
241
+ skipped: false,
242
+ ready: false,
243
+ missing: initialMissing,
244
+ manager: null,
245
+ message: `当前平台(${platform})不支持自动安装本地 OCR 组件,如需扫描件 OCR 请手动安装 tesseract 与 poppler`,
246
+ code: 'UNSUPPORTED_PLATFORM'
247
+ })
248
+ }
249
+
250
+ if (externalSignal?.aborted) {
251
+ return result({
252
+ ok: false,
253
+ skipped: false,
254
+ ready: false,
255
+ missing: initialMissing,
256
+ manager,
257
+ message: '已取消本地 OCR 组件安装',
258
+ code: 'CANCELLED'
259
+ })
260
+ }
261
+
262
+ if (manager === null) {
263
+ return result({
264
+ ok: false,
265
+ skipped: false,
266
+ ready: false,
267
+ missing: initialMissing,
268
+ manager: null,
269
+ message: '未检测到受支持的包管理器(apt-get / apk / dnf / yum / pacman / brew),如需扫描件 OCR 请手动安装 tesseract 与 poppler',
270
+ code: 'NO_PACKAGE_MANAGER'
271
+ })
272
+ }
273
+
274
+ if (platform === 'linux' && !isRoot(getuid)) {
275
+ let sudoOk
276
+ if (typeof options.sudoCheck === 'boolean') {
277
+ sudoOk = options.sudoCheck
278
+ } else if (typeof options.sudoCheck === 'function') {
279
+ try {
280
+ sudoOk = (await options.sudoCheck()) === true
281
+ } catch {
282
+ sudoOk = false
283
+ }
284
+ } else {
285
+ const check = await runCommand('sudo', ['-n', 'true'], { timeoutMs: SUDO_CHECK_TIMEOUT_MS })
286
+ sudoOk = check.ok
287
+ }
288
+ if (!sudoOk) {
289
+ const hint = MANAGERS[manager].manual
290
+ return result({
291
+ ok: false,
292
+ skipped: false,
293
+ ready: false,
294
+ missing: initialMissing,
295
+ manager,
296
+ message: `本地 OCR 系统组件未能自动安装(原因:无系统包管理权限);如需扫描件 OCR,请手动运行:${hint}`,
297
+ code: 'NO_PERMISSION'
298
+ })
299
+ }
300
+ useSudo = true
301
+ }
302
+
303
+ safeLog(logger, 'info', `正在补齐本地 OCR 组件(${MANAGERS[manager].label})…`)
304
+
305
+ const steps = MANAGERS[manager].steps()
306
+ for (const step of steps) {
307
+ if (externalSignal?.aborted) {
308
+ return result({
309
+ ok: false,
310
+ skipped: false,
311
+ ready: false,
312
+ missing: initialMissing,
313
+ manager,
314
+ message: '已取消本地 OCR 组件安装',
315
+ code: 'CANCELLED'
316
+ })
317
+ }
318
+ const remaining = deadline - Date.now()
319
+ if (remaining <= 0) {
320
+ safeLog(logger, 'warn', `补齐本地 OCR 组件超时(${MANAGERS[manager].label})`)
321
+ return result({
322
+ ok: false,
323
+ skipped: false,
324
+ ready: false,
325
+ missing: initialMissing,
326
+ manager,
327
+ message: `本地 OCR 系统组件安装超时(${Math.round(timeoutMs / 1000)}s),已跳过,不影响文本 / Markdown / Office 解析`,
328
+ code: 'TIMEOUT'
329
+ })
330
+ }
331
+ const command = useSudo ? 'sudo' : manager
332
+ const args = useSudo ? ['-n', manager, ...step.args] : step.args
333
+ const res = await runCommand(command, args, {
334
+ timeoutMs: remaining,
335
+ env: stepEnv(step, env)
336
+ })
337
+ if (res.code === 'ABORTED') {
338
+ return result({
339
+ ok: false,
340
+ skipped: false,
341
+ ready: false,
342
+ missing: initialMissing,
343
+ manager,
344
+ message: '已取消本地 OCR 组件安装',
345
+ code: 'CANCELLED'
346
+ })
347
+ }
348
+ if (res.code === 'TIMEOUT') {
349
+ safeLog(logger, 'warn', `补齐本地 OCR 组件超时(${MANAGERS[manager].label})`)
350
+ return result({
351
+ ok: false,
352
+ skipped: false,
353
+ ready: false,
354
+ missing: initialMissing,
355
+ manager,
356
+ message: `本地 OCR 系统组件安装超时(${Math.round(timeoutMs / 1000)}s),已跳过,不影响文本 / Markdown / Office 解析`,
357
+ code: 'TIMEOUT'
358
+ })
359
+ }
360
+ if (!res.ok) {
361
+ safeLog(logger, 'warn', `补齐本地 OCR 组件失败(${MANAGERS[manager].label})`)
362
+ return result({
363
+ ok: false,
364
+ skipped: false,
365
+ ready: false,
366
+ missing: initialMissing,
367
+ manager,
368
+ message: `本地 OCR 系统组件安装失败(${MANAGERS[manager].label}),已跳过,不影响文本 / Markdown / Office 解析;如需扫描件 OCR,请手动运行:${MANAGERS[manager].manual}`,
369
+ code: 'INSTALL_FAILED'
370
+ })
371
+ }
372
+ }
373
+
374
+ const after = await probeOnce()
375
+ if (after.ready) {
376
+ safeLog(logger, 'info', `本地 OCR 组件已安装(${MANAGERS[manager].label})`)
377
+ return result({
378
+ ok: true,
379
+ skipped: false,
380
+ ready: true,
381
+ missing: [],
382
+ manager,
383
+ message: '本地 OCR 组件已安装(tesseract / pdftoppm)',
384
+ code: 'INSTALLED'
385
+ })
386
+ }
387
+
388
+ safeLog(logger, 'warn', '本地 OCR 组件安装命令已执行,但重新探测仍未就绪')
389
+ return result({
390
+ ok: false,
391
+ skipped: false,
392
+ ready: false,
393
+ missing: after.missing,
394
+ manager,
395
+ message: `安装命令已执行,但仍未检测到 ${after.missing.join(' / ')},请手动检查;文本 / Markdown / Office 解析不受影响`,
396
+ code: 'VERIFY_FAILED'
397
+ })
398
+ } catch (err) {
399
+ safeLog(logger, 'warn', '补齐本地 OCR 组件时发生内部错误,已降级跳过')
400
+ return result({
401
+ ok: false,
402
+ skipped: false,
403
+ ready: false,
404
+ missing: initialMissing,
405
+ manager,
406
+ message: '本地 OCR 系统组件补齐过程发生内部错误,已跳过,不影响文本 / Markdown / Office 解析',
407
+ code: 'INTERNAL_ERROR'
408
+ })
409
+ }
410
+ }
@@ -127,6 +127,65 @@ function disposeOf(handle) {
127
127
  else if (typeof handle?.dispose === 'function') handle.dispose()
128
128
  }
129
129
 
130
+ const INSTALLED_STATES = new Set(['ready', 'installed'])
131
+ const FAILED_STATES = new Set(['error', 'failed'])
132
+ const TERMINAL_STATES = new Set([...INSTALLED_STATES, ...FAILED_STATES, 'cancelled'])
133
+
134
+ /**
135
+ * Bridge installer snapshots to ChatLuna events.
136
+ *
137
+ * Every snapshot feeds the `install` event (progress). A `status` broadcast is added only when
138
+ * the installer reaches a terminal state (installed / failed / cancelled) or when `installed`
139
+ * flips, so the WebUI sees the outcome of all three install paths — release download, URL and
140
+ * offline upload — without a page reload. The same conclusion is emitted once: the terminal
141
+ * outcome plus the installed flag form the dedupe key, and the key resets when a new job starts
142
+ * (busy state entered from a settled one) so a retry still announces its own result.
143
+ *
144
+ * Snapshots only produce events; nothing here logs.
145
+ */
146
+ export function createInstallStatusBridge(options = {}) {
147
+ const emitInstall = typeof options.emitInstall === 'function' ? options.emitInstall : () => {}
148
+ const emitStatus = typeof options.emitStatus === 'function' ? options.emitStatus : () => {}
149
+ const isInstalled = typeof options.isInstalled === 'function' ? options.isInstalled : null
150
+
151
+ let lastState = null
152
+ let lastInstalled = false
153
+ let lastKey = ''
154
+
155
+ return {
156
+ /** @param {{ state?: string, message?: string, error?: string }} [snap] installer snapshot */
157
+ handleStatus(snap) {
158
+ emitInstall()
159
+ if (snap === null || typeof snap !== 'object') return
160
+
161
+ const state = typeof snap.state === 'string' ? snap.state.trim().toLowerCase() : ''
162
+ const previous = lastState
163
+ lastState = state
164
+
165
+ const previousBusy =
166
+ previous !== null && previous !== '' && previous !== 'idle' && !TERMINAL_STATES.has(previous)
167
+ const busy = state !== '' && state !== 'idle' && !TERMINAL_STATES.has(state)
168
+ if (busy && !previousBusy) lastKey = ''
169
+
170
+ let outcome = ''
171
+ if (INSTALLED_STATES.has(state)) outcome = 'installed'
172
+ else if (FAILED_STATES.has(state)) outcome = 'failed'
173
+ else if (state === 'cancelled' || (state === 'idle' && previousBusy)) outcome = 'cancelled'
174
+
175
+ let installed = lastInstalled
176
+ if (isInstalled !== null) installed = isInstalled() === true
177
+ const installedChanged = installed !== lastInstalled
178
+ lastInstalled = installed
179
+
180
+ if (outcome === '' && !installedChanged) return
181
+ const key = `${outcome}|${installed}`
182
+ if (key === lastKey) return
183
+ lastKey = key
184
+ emitStatus()
185
+ }
186
+ }
187
+ }
188
+
130
189
  /**
131
190
  * Register the install wizard endpoints on the ChatLuna server.
132
191
  *
@@ -135,6 +194,8 @@ function disposeOf(handle) {
135
194
  * @param {string} [options.prefix='/kb-admin']
136
195
  * @param {{ installFromStream: (stream: import('node:stream').Readable, meta: { sha256?: string, filename?: string }) => Promise<unknown>, status: () => unknown }} options.installer
137
196
  * @param {(ctx: object, req: object) => boolean | Promise<boolean>} options.authorize
197
+ * @param {(snapshot: unknown) => void} [options.onInstalled] runs after a successful upload with
198
+ * the fresh installer status so the host can broadcast `chatluna-kb/status`
138
199
  * @param {number} [options.maxBytes=314572800]
139
200
  * @param {object} [options.logger]
140
201
  * @returns {() => void} dispose
@@ -156,6 +217,9 @@ export function registerInstallRoutes(ctx, options = {}) {
156
217
  if (typeof options.authorize !== 'function') {
157
218
  throw new TypeError('registerInstallRoutes: options.authorize must be a function')
158
219
  }
220
+ if (options.onInstalled !== undefined && typeof options.onInstalled !== 'function') {
221
+ throw new TypeError('registerInstallRoutes: options.onInstalled must be a function')
222
+ }
159
223
 
160
224
  const prefix = normalizePrefix(options.prefix)
161
225
  const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES
@@ -164,6 +228,7 @@ export function registerInstallRoutes(ctx, options = {}) {
164
228
  }
165
229
  const logger = options.logger ?? defaultLogger
166
230
  const authorize = options.authorize
231
+ const onInstalled = options.onInstalled
167
232
 
168
233
  const allowed = async (req) => {
169
234
  try {
@@ -254,6 +319,13 @@ export function registerInstallRoutes(ctx, options = {}) {
254
319
  sendError(res, 500, 'INSTALL_FAILED', '无法读取安装状态')
255
320
  return
256
321
  }
322
+ if (onInstalled !== undefined) {
323
+ try {
324
+ onInstalled(snapshot)
325
+ } catch {
326
+ // Broadcasting is best-effort: a listener failure must not turn a finished upload into a 500.
327
+ }
328
+ }
257
329
  sendJson(res, 200, { success: true, data: snapshot })
258
330
  }
259
331