dsh-podwave 0.11.20 → 0.11.21

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/src/catalog.js CHANGED
@@ -212,6 +212,29 @@ export function artifactFor(platform, engine) {
212
212
  }
213
213
  }
214
214
 
215
+ // 配置里存的是目录名(artifact.dir),不是 catalog 的 key。
216
+ // 靠正则猜「这是不是 SenseVoice」在换模型后必错,所以按元数据反查。
217
+ export function artifactByDir(dir, kind) {
218
+ if (!dir) return null
219
+ const name = String(dir)
220
+ for (const artifact of Object.values(CATALOG)) {
221
+ if (kind && artifact.kind !== kind) continue
222
+ if (artifact.dir === name || artifact.id === name) return artifact
223
+ }
224
+ return null
225
+ }
226
+
227
+ // 当前平台「应该用哪个模型/引擎」——配置默认值、安装检查、运行时判定都以它为准。
228
+ export function expectedModels(platform, engine) {
229
+ const artifacts = artifactFor(platform, engine)
230
+ return {
231
+ asrModel: artifacts.asr.dir,
232
+ translateModel: artifacts.translate.dir,
233
+ asrEngine: artifacts.asr.engine,
234
+ translateEngine: artifacts.translate.engine,
235
+ }
236
+ }
237
+
215
238
  export function llamaAsset(platform) {
216
239
  const name = LLAMA_BINARY.assets[platformKey(platform)]
217
240
  if (!name) return null
package/src/config.js CHANGED
@@ -1,11 +1,33 @@
1
1
  // 统一配置:~/.podwave/config.json(schemaVersion 1)。
2
2
  // 首次启动时把旧的 ui.json / translate.json / models.json 迁入,并把旧文件改名为 *.bak。
3
+ //
4
+ // 两条容易踩的坑,都在这里兜住:
5
+ // 1. 默认模型必须按平台算,不能写死 MLX——那套模型只有 Apple Silicon 能装。
6
+ // 2. 缓存不能盲信。宿主进程常驻,而「一键安装」是另一个进程写盘;如果保存时拿内存里的
7
+ // 旧快照整份写回,安装结果就被吞掉了。所以每次保存都先比对磁盘是否被别人改过。
3
8
  import fs from 'node:fs'
4
9
  import path from 'node:path'
5
10
  import { DATA_DIR } from './state.js'
11
+ import { detectPlatform, recommendEngine } from './platform.js'
12
+ import { expectedModels } from './catalog.js'
6
13
 
7
14
  export const CONFIG_PATH = path.join(DATA_DIR, 'config.json')
8
15
 
16
+ function defaultModels() {
17
+ const platform = detectPlatform()
18
+ const engine = recommendEngine(platform)
19
+ const models = expectedModels(platform, engine)
20
+ return { asrModel: models.asrModel, translateModel: models.translateModel }
21
+ }
22
+
23
+ // detectPlatform() 会去探测 GPU(可能 spawn 子进程),不能放在模块顶层每次求值。
24
+ // 用惰性 getter + 缓存:既保证「默认模型按平台算」,又不会拖慢 import。
25
+ let defaultsCache = null
26
+ function cachedDefaultModels() {
27
+ if (!defaultsCache) defaultsCache = defaultModels()
28
+ return defaultsCache
29
+ }
30
+
9
31
  export const CONFIG_DEFAULTS = {
10
32
  schemaVersion: 1,
11
33
  ui: { showSidebarPanel: true, sidebarCollapsed: false },
@@ -16,7 +38,10 @@ export const CONFIG_DEFAULTS = {
16
38
  apiModel: 'deepseek-chat',
17
39
  apiKey: '',
18
40
  },
19
- models: { asrModel: 'qwen3-asr-1.7b-8bit', translateModel: 'hy-mt2-1.8b-4bit' },
41
+ // 默认模型绝不能写死 MLX:那套模型 platform 是 darwin-arm64,Windows 装不了。
42
+ get models() {
43
+ return { ...cachedDefaultModels() }
44
+ },
20
45
  transcribe: { hotwords: [], chunkMinutes: 1, diarize: true },
21
46
  import: { mode: 'copy' },
22
47
  }
@@ -48,6 +73,16 @@ function readJson(file) {
48
73
  }
49
74
  }
50
75
 
76
+ // 磁盘指纹:别的进程改过 config.json 时,缓存必须失效。
77
+ function statKey() {
78
+ try {
79
+ const stat = fs.statSync(CONFIG_PATH)
80
+ return `${stat.mtimeMs}:${stat.size}`
81
+ } catch {
82
+ return 'missing'
83
+ }
84
+ }
85
+
51
86
  function writeConfig(config) {
52
87
  fs.mkdirSync(DATA_DIR, { recursive: true })
53
88
  const tmp = `${CONFIG_PATH}.tmp`
@@ -74,19 +109,24 @@ function migrateLegacy() {
74
109
  }
75
110
 
76
111
  let cache = null
112
+ let cacheKey = null
77
113
 
78
114
  export function loadConfig() {
79
- if (!cache) {
80
- const stored = readJson(CONFIG_PATH)
81
- cache = stored ? merge(clone(CONFIG_DEFAULTS), stored) : migrateLegacy()
82
- }
115
+ const key = statKey()
116
+ if (cache && cacheKey === key) return clone(cache)
117
+ const stored = key === 'missing' ? null : readJson(CONFIG_PATH)
118
+ cache = stored ? merge(clone(CONFIG_DEFAULTS), stored) : migrateLegacy()
119
+ cacheKey = statKey()
83
120
  return clone(cache)
84
121
  }
85
122
 
86
123
  export function saveConfig(patch) {
124
+ // 先 loadConfig():它会比对磁盘指纹,把别的进程(比如安装器)刚写进去的模型名读进来,
125
+ // 再和这次 patch 合并,避免用旧快照覆盖安装结果。
87
126
  const next = merge(loadConfig(), patch)
88
127
  cache = next
89
128
  writeConfig(next)
129
+ cacheKey = statKey()
90
130
  return clone(next)
91
131
  }
92
132
 
@@ -101,3 +141,11 @@ export function updateSection(name, patch) {
101
141
  export function configFile() {
102
142
  return CONFIG_PATH
103
143
  }
144
+
145
+ // 测试与诊断用:当前平台推荐的模型组合。
146
+ export function platformDefaults() {
147
+ const platform = detectPlatform()
148
+ const engine = recommendEngine(platform)
149
+ const models = expectedModels(platform, engine)
150
+ return { platform: { os: platform.os, arch: platform.arch, osLabel: platform.osLabel }, engine: engine.id, models }
151
+ }
package/src/downloader.js CHANGED
@@ -94,6 +94,10 @@ function runCapture(cmd, args) {
94
94
  })
95
95
  }
96
96
 
97
+ // 非 zip 压缩包(.tar.bz2 / .tar.gz / .tar.xz)的条目列表。
98
+ // GNU tar(Git for Windows、MSYS、Cygwin 会把它的目录排到 PATH 前面)会把 C:/... 当成
99
+ // host:path 远程语法,直接 `tar -tf C:/...` 会报 "Cannot connect to C: resolve failed"。
100
+ // 所以这里也要多候选,否则安全检查会被静默跳过。
97
101
  async function listArchiveEntries(file) {
98
102
  const lower = file.toLowerCase()
99
103
  if (lower.endsWith('.zip')) {
@@ -108,8 +112,43 @@ async function listArchiveEntries(file) {
108
112
  }
109
113
  return null
110
114
  }
111
- const output = await runCapture('tar', ['-tf', file])
112
- return output ? output.split(/\r?\n/).filter(Boolean) : null
115
+ for (const [cmd, args] of tarListAttempts(file)) {
116
+ const output = await runCapture(cmd, args)
117
+ if (output) return output.split(/\r?\n/).filter(Boolean)
118
+ }
119
+ return null
120
+ }
121
+
122
+ function systemTar() {
123
+ if (process.platform !== 'win32') return null
124
+ const root = process.env.SystemRoot || process.env.windir || 'C:\\Windows'
125
+ return path.join(root, 'System32', 'tar.exe')
126
+ }
127
+
128
+ // 解压/列目录的候选命令。顺序有意义:
129
+ // 1. 裸 tar:bsdtar(Windows 自带、macOS 自带)与 GNU tar 都能跑相对路径。
130
+ // 2. --force-local:只有 GNU tar 认,用来救「绝对路径被当成远程主机」的情况。
131
+ // bsdtar 会明确拒绝这个选项,所以必须放在裸 tar 之后、失败后才轮到。
132
+ // 3. Windows 自带的 System32\tar.exe:显式绕开 PATH 上被 Git-Bash 顶掉的 GNU tar。
133
+ // 4. python -m tarfile:最后兜底,不依赖任何外部 tar。
134
+ function tarAttempts(file, destDir) {
135
+ const list = [['tar', ['-xf', file, '-C', destDir]]]
136
+ list.push(['tar', ['--force-local', '-xf', file, '-C', destDir]])
137
+ const sysTar = systemTar()
138
+ if (sysTar) list.push([sysTar, ['-xf', file, '-C', destDir]])
139
+ list.push(['python', ['-m', 'tarfile', '-e', file, destDir]])
140
+ list.push(['python3', ['-m', 'tarfile', '-e', file, destDir]])
141
+ return list
142
+ }
143
+
144
+ function tarListAttempts(file) {
145
+ const list = [['tar', ['-tf', file]]]
146
+ list.push(['tar', ['--force-local', '-tf', file]])
147
+ const sysTar = systemTar()
148
+ if (sysTar) list.push([sysTar, ['-tf', file]])
149
+ list.push(['python', ['-c', 'import sys,tarfile;print("\n".join(tarfile.open(sys.argv[1]).getnames()))', file]])
150
+ list.push(['python3', ['-c', 'import sys,tarfile;print("\n".join(tarfile.open(sys.argv[1]).getnames()))', file]])
151
+ return list
113
152
  }
114
153
 
115
154
  async function sha256File(file) {
@@ -343,8 +382,13 @@ export async function extractArchive(file, destDir) {
343
382
  attempts.push(['tar', ['-xf', file, '-C', destDir]])
344
383
  attempts.push(['powershell.exe', ['-NoProfile', '-Command', `Expand-Archive -LiteralPath '${file}' -DestinationPath '${destDir}' -Force`]])
345
384
  attempts.push(['python3', ['-m', 'zipfile', '-e', file, destDir]])
385
+ attempts.push(['python', ['-m', 'zipfile', '-e', file, destDir]])
346
386
  } else {
347
- attempts.push(['tar', ['-xf', file, '-C', destDir]])
387
+ // 之前这里只有一次裸 tar:只要 PATH 上的 tar 是 GNU tar(Git for Windows / MSYS / Cygwin
388
+ // 都会排到前面),Windows 的 C:/ 绝对路径就会被当成 host:path,报
389
+ // "tar: Cannot connect to C: resolve failed"(exit 128)。而这发生在安装最后一步
390
+ // (说话人分离模型),前面 1.6 GB 都下完了,整次安装却被判失败。
391
+ attempts.push(...tarAttempts(file, destDir))
348
392
  }
349
393
  let lastError = null
350
394
  for (const [cmd, args] of attempts) {
package/src/host.js CHANGED
@@ -465,7 +465,7 @@ async function route(ctx, req, res) {
465
465
  return json(res, 200, {
466
466
  ok: true,
467
467
  generatedAt: new Date().toISOString(),
468
- version: '0.11.20',
468
+ version: '0.11.21',
469
469
  platform,
470
470
  engine: recommendEngine(platform),
471
471
  paths: {
@@ -494,7 +494,7 @@ async function route(ctx, req, res) {
494
494
  }
495
495
  if ((method === 'GET' || method === 'HEAD') && routePath === 'api/health') {
496
496
  await mediaReady
497
- return json(res, 200, { ok: true, app: 'podwave', version: '0.11.20', mediaBase, transcribe: runtimeInfo(), diarize: diarizeInfo(), translate: publicConfig() })
497
+ return json(res, 200, { ok: true, app: 'podwave', version: '0.11.21', mediaBase, transcribe: runtimeInfo(), diarize: diarizeInfo(), translate: publicConfig() })
498
498
  }
499
499
  if (method === 'GET' && routePath === 'api/state') {
500
500
  const state = getState()
@@ -581,7 +581,14 @@ async function route(ctx, req, res) {
581
581
  return json(res, 200, localAppStatus())
582
582
  }
583
583
  if (method === 'POST' && routePath === 'api/xyz/auth/from-app') {
584
- return json(res, 200, await loginFromLocalApp())
584
+ try {
585
+ return json(res, 200, await loginFromLocalApp())
586
+ } catch (error) {
587
+ // 「这台机器上没有小宇宙 App / 登录已失效」是环境与凭据问题,不是服务器故障:
588
+ // 用 400 让前端能直接展示原因,而不是当成 500 崩掉。
589
+ if (!error.status) error.status = 400
590
+ throw error
591
+ }
585
592
  }
586
593
  if (method === 'POST' && routePath === 'api/xyz/auth/logout') {
587
594
  return json(res, 200, logout())
package/src/library.js CHANGED
@@ -19,11 +19,17 @@ const metaCache = new Map()
19
19
  let scanPromise = null
20
20
  let scanState = { running: false, startedAt: null, finishedAt: null, error: null }
21
21
 
22
+ // Windows 用户经常直接粘资源管理器地址栏里的 %USERPROFILE%\Music、%HOMEPATH%,
23
+ // 之前只认 ~ 和 ~/,这类路径会原样返回然后扫描失败。顺带支持 ~\ 与 %NAME%。
22
24
  export function expandHome(input) {
23
- const value = String(input || '').trim()
25
+ let value = String(input || '').trim()
24
26
  if (!value) return ''
27
+ value = value.replace(/%([^%\\/]+)%/g, (whole, name) => {
28
+ const resolved = process.env[name] || process.env[name.toUpperCase()] || process.env[name.toLowerCase()]
29
+ return resolved || whole
30
+ })
25
31
  if (value === '~') return os.homedir()
26
- if (value.startsWith('~/')) return path.join(os.homedir(), value.slice(2))
32
+ if (value.startsWith('~/') || value.startsWith('~\\')) return path.join(os.homedir(), value.slice(2))
27
33
  return path.resolve(value)
28
34
  }
29
35
 
package/src/llama.js CHANGED
@@ -7,7 +7,7 @@ import { DATA_DIR } from './state.js'
7
7
  import { getSection } from './config.js'
8
8
  import { llamaBinary } from './setup.js'
9
9
  import { CATALOG } from './catalog.js'
10
- import { detectPlatform, isWindows } from './platform.js'
10
+ import { detectPlatform, isWindows, killTree } from './platform.js'
11
11
 
12
12
  const TARGET_NAMES = { zh: 'Simplified Chinese', en: 'English' }
13
13
  const IDLE_MS = 90_000
@@ -91,11 +91,9 @@ export async function ensureLlamaServer() {
91
91
 
92
92
  export function stopLlamaServer() {
93
93
  if (!server) return
94
- try {
95
- server.child.kill('SIGTERM')
96
- } catch {
97
- // ignore
98
- }
94
+ // Windows 上 SIGTERM 等于 TerminateProcess,llama-server 的临时文件不会清理;
95
+ // killTree 在 Windows 走 taskkill /T,其它平台仍是优雅 SIGTERM。
96
+ killTree(server.child.pid)
99
97
  server = null
100
98
  }
101
99
 
package/src/platform.js CHANGED
@@ -3,7 +3,7 @@
3
3
  import fs from 'node:fs'
4
4
  import os from 'node:os'
5
5
  import path from 'node:path'
6
- import { execFileSync } from 'node:child_process'
6
+ import { execFileSync, spawn } from 'node:child_process'
7
7
 
8
8
  export const isWindows = process.platform === 'win32'
9
9
  export const isMac = process.platform === 'darwin'
@@ -109,6 +109,41 @@ export function venvBin(name, dir = venvDir()) {
109
109
  return isWindows ? path.join(dir, 'Scripts', name + ext) : path.join(dir, 'bin', name + ext)
110
110
  }
111
111
 
112
+ // Windows 上 SIGTERM 实际上是 TerminateProcess(硬杀),子进程(ffmpeg 之类)会变成孤儿。
113
+ // 统一走这里:Windows 用 taskkill /T 连子孙一起收,其它平台照常 SIGTERM,超时再 SIGKILL。
114
+ export function killTree(pid, { signal = 'SIGTERM', timeoutMs = 5000, onForce } = {}) {
115
+ const target = Number(pid)
116
+ if (!Number.isInteger(target) || target <= 1) return false
117
+ try {
118
+ process.kill(target, 0)
119
+ } catch {
120
+ return false
121
+ }
122
+ if (isWindows) {
123
+ try {
124
+ spawn('taskkill', ['/PID', String(target), '/T', '/F'], { stdio: 'ignore', windowsHide: true })
125
+ } catch {
126
+ /* ignore */
127
+ }
128
+ return true
129
+ }
130
+ try {
131
+ process.kill(target, signal)
132
+ } catch {
133
+ return false
134
+ }
135
+ const timer = setTimeout(() => {
136
+ try {
137
+ process.kill(target, 'SIGKILL')
138
+ } catch {
139
+ /* 已经退出 */
140
+ }
141
+ onForce?.()
142
+ }, timeoutMs)
143
+ timer.unref?.()
144
+ return true
145
+ }
146
+
112
147
  export function detectGpu() {
113
148
  if (isAppleSilicon()) return 'metal'
114
149
  try {
package/src/setup.js CHANGED
@@ -7,9 +7,9 @@ import { execFile, spawn } from 'node:child_process'
7
7
  import { DATA_DIR } from './state.js'
8
8
  import { getSection, updateSection } from './config.js'
9
9
  import { getJob, upsertJob } from './jobs.js'
10
- import { CATALOG, FFMPEG_BINARY, LLAMA_BINARY, SOURCE_LABELS, artifactFor, ffmpegAsset, llamaAsset, sourcesFor } from './catalog.js'
10
+ import { CATALOG, FFMPEG_BINARY, LLAMA_BINARY, SOURCE_LABELS, artifactFor, expectedModels, ffmpegAsset, llamaAsset, sourcesFor } from './catalog.js'
11
11
  import { downloadArtifact, extractArchive } from './downloader.js'
12
- import { detectPlatform, findExecutable, ffmpegPath, ffprobePath, recommendEngine, venvDir, venvPython, isWindows, isMac } from './platform.js'
12
+ import { detectPlatform, findExecutable, ffmpegPath, ffprobePath, killTree, recommendEngine, venvDir, venvPython, isWindows, isMac } from './platform.js'
13
13
 
14
14
  const RUNTIME_DIR = path.join(DATA_DIR, 'runtime')
15
15
  const SETUP_PATH = path.join(DATA_DIR, 'setup.json')
@@ -27,7 +27,8 @@ export function setupJob() {
27
27
  export function cancelSetup() {
28
28
  if (!current) return false
29
29
  current.cancelled = true
30
- current.child?.kill('SIGTERM')
30
+ // Windows 上 SIGTERM 等于硬杀,uv/Python 拉起的子进程会变孤儿;killTree 处理平台差异。
31
+ killTree(current.child?.pid)
31
32
  return true
32
33
  }
33
34
 
@@ -247,12 +248,22 @@ export async function verify() {
247
248
  })
248
249
  }
249
250
 
251
+ // 只判「非空」等于没判:Mac 专用模型名、甚至是瞎编的名字都会亮绿,
252
+ // 用户看到「检查通过」却在转写时报「运行环境未安装」。这里比对本平台应有的模型。
250
253
  const config = getSection('models')
254
+ const expected = expectedModels(platform, engine)
255
+ const problems = []
256
+ if (config.asrModel !== expected.asrModel) {
257
+ problems.push(`转写模型应为 ${expected.asrModel},当前 ${config.asrModel || '未设置'}`)
258
+ }
259
+ if (config.translateModel !== expected.translateModel) {
260
+ problems.push(`翻译模型应为 ${expected.translateModel},当前 ${config.translateModel || '未设置'}`)
261
+ }
251
262
  checks.push({
252
263
  id: 'config',
253
- label: '模型配置已写入',
254
- ok: Boolean(config.asrModel && config.translateModel),
255
- detail: `${config.asrModel || '未设置'} / ${config.translateModel || '未设置'}`,
264
+ label: '模型配置与当前平台匹配',
265
+ ok: problems.length === 0,
266
+ detail: problems.length ? problems.join(';') : `${config.asrModel} / ${config.translateModel}`,
256
267
  })
257
268
 
258
269
  return {
@@ -503,25 +514,51 @@ export async function install({ source = 'auto' } = {}) {
503
514
  }
504
515
 
505
516
  // 3. 模型
517
+ // 说话人分离是可选组件:它失败不该把已经下完的 1.6 GB 判定成整次安装失败。
518
+ // 之前任何一个 tar 解压失败都会让整个 install 走到 catch,用户看到「安装失败」。
519
+ const optionalFailures = []
506
520
  for (const artifact of targets) {
507
521
  if (current.cancelled) throw new Error('用户取消了安装')
522
+ const optional = artifact.kind === 'diarization'
508
523
  report({ stage: `下载 ${artifact.label}` })
509
- const result = await downloadArtifact(artifact, {
510
- sourceId: source,
511
- signal: current.signal,
512
- onProgress: (event) => {
513
- doneBytes += event.delta || 0
514
- report({ stage: `下载 ${artifact.label}` })
515
- },
516
- })
517
- doneBytes = Math.max(doneBytes, summary.reduce((sum, item) => sum + item.bytes, 0) + result.bytes)
518
- summary.push({ id: artifact.id, label: artifact.label, bytes: result.bytes, source: result.sourceLabel })
524
+ try {
525
+ const result = await downloadArtifact(artifact, {
526
+ sourceId: source,
527
+ signal: current.signal,
528
+ onProgress: (event) => {
529
+ doneBytes += event.delta || 0
530
+ report({ stage: `下载 ${artifact.label}` })
531
+ },
532
+ })
533
+ doneBytes = Math.max(doneBytes, summary.reduce((sum, item) => sum + item.bytes, 0) + result.bytes)
534
+ summary.push({ id: artifact.id, label: artifact.label, bytes: result.bytes, source: result.sourceLabel })
535
+ } catch (error) {
536
+ if (current.cancelled) throw new Error('用户取消了安装')
537
+ if (!optional) throw error
538
+ const message = String(error?.message || error)
539
+ optionalFailures.push({ id: artifact.id, label: artifact.label, error: message })
540
+ summary.push({ id: artifact.id, label: artifact.label, bytes: 0, optional: true, skipped: true, error: message })
541
+ report({ stage: `跳过可选组件:${artifact.label}(${message})` })
542
+ }
519
543
  }
520
544
 
521
545
  // 4. 写配置
522
546
  updateSection('models', { asrModel: artifacts.asr.dir, translateModel: artifacts.translate.dir })
523
547
  writeSetup({ engine: engine.id, source, installedAt: Date.now(), lastSummary: summary })
524
- const job = updateJob({ status: 'done', stage: '完成', progress: 100, bytes: doneBytes, expected: totalBytes || doneBytes, summary })
548
+ const warning = optionalFailures.length
549
+ ? `可选组件失败,已跳过:${optionalFailures.map((item) => `${item.label}(${item.error})`).join(';')}。核心转写与翻译已就绪,可以正常使用。`
550
+ : null
551
+ const job = updateJob({
552
+ status: 'done',
553
+ stage: warning ? '完成(部分可选组件已跳过)' : '完成',
554
+ progress: 100,
555
+ bytes: doneBytes,
556
+ expected: totalBytes || doneBytes,
557
+ summary,
558
+ error: null,
559
+ warning,
560
+ optionalFailures,
561
+ })
525
562
  current.running = false
526
563
  return job
527
564
  } catch (error) {
package/src/transcribe.js CHANGED
@@ -9,15 +9,17 @@ import { copyFile, mkdir, readFile, readdir, rename, rm, writeFile } from 'node:
9
9
  import { fileURLToPath } from 'node:url'
10
10
  import { DATA_DIR } from './state.js'
11
11
  import { loadModelConfig, modelDir } from './models.js'
12
- import { ffmpegPath, ffprobePath, venvPython } from './platform.js'
12
+ import { ffmpegPath, ffprobePath, killTree, venvBin, venvPython } from './platform.js'
13
13
  import { getSection } from './config.js'
14
+ import { artifactByDir } from './catalog.js'
14
15
  import { assignSpeakers, diarizeInfo, runDiarization } from './diarize.js'
15
16
  import { flushJobs, getJob, getJobFresh, jobKey, removeJob, upsertJob } from './jobs.js'
16
17
 
17
18
  export const TRANSCRIPTS_DIR = path.join(DATA_DIR, 'transcripts')
18
19
  const WORK_DIR = path.join(TRANSCRIPTS_DIR, '.work')
19
- const RUNTIME_DIR = path.join(DATA_DIR, 'runtime')
20
- const CLI = path.join(RUNTIME_DIR, '.venv', 'bin', 'mlx-qwen3-asr')
20
+ // Windows 的虚拟环境是 .venv\Scripts\mlx-qwen3-asr.exe,不是 .venv/bin/。
21
+ // 用 venvBin() 拼平台路径,否则 Windows 上永远判定「运行环境未安装」。
22
+ const CLI = venvBin('mlx-qwen3-asr')
21
23
  const SHERPA_SCRIPT = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'scripts', 'asr_sherpa_batch.py')
22
24
  const FFMPEG = process.env.PODWAVE_FFMPEG || ffmpegPath() || 'ffmpeg'
23
25
  const FFPROBE = process.env.PODWAVE_FFPROBE || ffprobePath() || 'ffprobe'
@@ -32,27 +34,9 @@ const cancelRequested = new Set()
32
34
 
33
35
  // 宿主热重载后,新模块实例拿不到旧实例的 activeChild,取消就杀不掉那个进程。
34
36
  // 所以把当前工作进程的 pid 也写进 job,取消时先按内存找,找不到再按 pid 兜底。
37
+ // Windows 上 SIGTERM 等于硬杀,交给 killTree 用 taskkill /T 连子孙一起收。
35
38
  function stopChildByPid(pid) {
36
- const target = Number(pid)
37
- if (!Number.isInteger(target) || target <= 1) return false
38
- try {
39
- process.kill(target, 0)
40
- } catch {
41
- return false
42
- }
43
- try {
44
- process.kill(target, 'SIGTERM')
45
- } catch {
46
- return false
47
- }
48
- setTimeout(() => {
49
- try {
50
- process.kill(target, 'SIGKILL')
51
- } catch {
52
- /* ignore */
53
- }
54
- }, 5000)
55
- return true
39
+ return killTree(pid)
56
40
  }
57
41
 
58
42
  function transcriptPath(id) {
@@ -66,7 +50,11 @@ function round2(value) {
66
50
  export function currentAsrModel() {
67
51
  const name = loadModelConfig().asrModel
68
52
  const dir = modelDir(name)
69
- const engine = /sensevoice|sherpa/i.test(name) ? 'sherpa' : 'mlx'
53
+ // 不能靠模型名正则猜引擎:换个名字(比如 Windows 的 sensevoice-small-int8 之外的写法)
54
+ // 就会掉进 MLX 分支,然后去查只有 macOS 才有的 CLI,永远 installed:false。
55
+ // 以 catalog 元数据为准,查不到时再退回正则兜底。
56
+ const artifact = artifactByDir(name, 'asr')
57
+ const engine = artifact ? (artifact.engine === 'onnx' ? 'sherpa' : 'mlx') : /sensevoice|sherpa/i.test(name) ? 'sherpa' : 'mlx'
70
58
  const ready =
71
59
  engine === 'sherpa'
72
60
  ? fs.existsSync(path.join(dir, 'model.int8.onnx'))
@@ -86,13 +74,17 @@ export function runtimeInfo() {
86
74
  const model = currentAsrModel()
87
75
  const config = transcribeConfig()
88
76
  const sherpa = model.engine === 'sherpa'
77
+ // sherpa 走 venv 里的 python 跑脚本;MLX 走 venv 里的命令行工具。
78
+ // 两者都必须在 Windows 的 Scripts\ 下找,否则 installed 永远 false。
79
+ const cliPath = sherpa ? venvPython() : CLI
80
+ const installed = sherpa ? fs.existsSync(SHERPA_SCRIPT) && fs.existsSync(cliPath) : fs.existsSync(cliPath)
89
81
  return {
90
82
  engine: model.engine,
91
- installed: sherpa ? fs.existsSync(SHERPA_SCRIPT) && fs.existsSync(venvPython()) : fs.existsSync(CLI),
83
+ installed,
92
84
  modelReady: model.ready,
93
85
  model: model.dir,
94
86
  modelName: model.name,
95
- cli: sherpa ? venvPython() : CLI,
87
+ cli: cliPath,
96
88
  hotwords: config.hotwords,
97
89
  chunkMinutes: config.chunkMinutes,
98
90
  diarize: config.diarize,
@@ -749,13 +741,7 @@ async function runJob(item) {
749
741
  const cancelled = cancelRequested.has(key)
750
742
  if (cancelled) {
751
743
  // 已取消就别再写 progress 把磁盘上的 cancelling 覆盖回转写中。
752
- if (child) {
753
- try {
754
- child.kill('SIGTERM')
755
- } catch {
756
- /* ignore */
757
- }
758
- }
744
+ if (child) killTree(child.pid)
759
745
  return
760
746
  }
761
747
  const current = plan.parts.find((part) => !hasResult(resultsDir, part.index)) || null
@@ -1336,13 +1322,7 @@ export async function diarizeTranscript(episode) {
1336
1322
  }
1337
1323
 
1338
1324
  export function stopAll() {
1339
- if (activeChild) {
1340
- try {
1341
- activeChild.kill('SIGTERM')
1342
- } catch {
1343
- /* ignore */
1344
- }
1345
- }
1325
+ if (activeChild) killTree(activeChild.pid)
1346
1326
  // 插件被禁用或热重载时走到这里:把正在跑的任务在磁盘上收尾成「已停止」,
1347
1327
  // 不然新实例读到的是一条永远 running 的僵尸任务,界面上点取消也没有对象。
1348
1328
  if (active?.key && active?.episodeId) {
package/src/translate.js CHANGED
@@ -11,8 +11,11 @@ import { loadModelConfig, modelDir } from './models.js'
11
11
  import { translateWithLlama } from './llama.js'
12
12
  import { getSection, updateSection } from './config.js'
13
13
  import { getJob, jobKey, upsertJob } from './jobs.js'
14
+ import { venvPython } from './platform.js'
15
+ import { artifactByDir } from './catalog.js'
14
16
 
15
- const PYTHON = path.join(DATA_DIR, 'runtime', '.venv', 'bin', 'python')
17
+ // Windows 的虚拟环境是 .venv\Scripts\python.exe,不是 .venv/bin/python。
18
+ const PYTHON = venvPython()
16
19
  const SCRIPT = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'scripts', 'translate_local.py')
17
20
 
18
21
  export function loadConfig() {
@@ -28,7 +31,10 @@ export function currentLocalModel() {
28
31
  const dir = modelDir(name)
29
32
  const gguf = fs.existsSync(dir) ? fs.readdirSync(dir).find((file) => file.endsWith('.gguf')) : null
30
33
  const mlx = fs.existsSync(path.join(dir, 'model.safetensors'))
31
- return { name, dir, ready: Boolean(mlx || gguf), engine: mlx ? 'mlx' : gguf ? 'llama' : 'none' }
34
+ // 同样以 catalog 元数据为准,别靠文件存在与否猜引擎(MLX 与 llama 目录都可能有两种文件)。
35
+ const artifact = artifactByDir(name, 'translate')
36
+ const engine = artifact ? (artifact.engine === 'mlx' ? 'mlx' : 'llama') : mlx ? 'mlx' : gguf ? 'llama' : 'none'
37
+ return { name, dir, ready: Boolean(mlx || gguf), engine }
32
38
  }
33
39
 
34
40
  export function publicConfig() {
package/src/xyz.js CHANGED
@@ -266,9 +266,9 @@ export function logout() {
266
266
 
267
267
  // 小宇宙桌面版是 iOS App(Apple Silicon 上直跑),登录态存在共享容器的偏好设置 plist 里。
268
268
  // 这样用户只要在小宇宙 App 里登录过,就能一键把登录态搬过来,不必再开网页、按 F12 抄 header。
269
- function appPlistPath() {
269
+ function appPlistPath(home = os.homedir()) {
270
270
  return path.join(
271
- os.homedir(),
271
+ home,
272
272
  'Library',
273
273
  'Group Containers',
274
274
  'group.app.podcast.cosmos',
@@ -280,9 +280,26 @@ function appPlistPath() {
280
280
 
281
281
  function readAppPlistText(file) {
282
282
  const { execFileSync } = childProcess
283
- return execFileSync('/usr/bin/plutil', ['-convert', 'xml1', '-o', '-', file], {
284
- maxBuffer: 16 * 1024 * 1024,
285
- }).toString('utf8')
283
+ try {
284
+ return execFileSync('/usr/bin/plutil', ['-convert', 'xml1', '-o', '-', file], {
285
+ maxBuffer: 16 * 1024 * 1024,
286
+ }).toString('utf8')
287
+ } catch (error) {
288
+ // 没有 plutil(非 macOS)或 plutil 打不开时,文件本身可能已经是 XML plist——直接当文本读。
289
+ // 这样这条链路在没有 plutil 的环境里也能被测到,而不是只能靠「macOS 上人工点一下」。
290
+ if (error?.code !== 'ENOENT') {
291
+ try {
292
+ const raw = fs.readFileSync(file, 'utf8')
293
+ if (raw.includes('<plist')) return raw
294
+ } catch {
295
+ /* 落到下面统一抛错 */
296
+ }
297
+ } else {
298
+ const raw = fs.readFileSync(file, 'utf8')
299
+ if (raw.includes('<plist')) return raw
300
+ }
301
+ throw error
302
+ }
286
303
  }
287
304
 
288
305
  function plistString(xml, key) {
@@ -291,16 +308,17 @@ function plistString(xml, key) {
291
308
  return match ? match[1].trim() : ''
292
309
  }
293
310
 
294
- export function localAppStatus() {
295
- const platform = process.platform
311
+ // options 只给测试用(模拟 darwin + 假 HOME),宿主调用时不传。
312
+ export function localAppStatus({ platform = process.platform, home = os.homedir() } = {}) {
296
313
  if (platform !== 'darwin') {
297
- return { available: false, reason: platform === 'win32' ? '仅支持 macOS 上的小宇宙 App' : '仅支持 macOS 上的小宇宙 App' }
314
+ return { available: false, reason: '仅支持 macOS 上的小宇宙 App' }
298
315
  }
299
- if (!fs.existsSync(appPlistPath())) {
316
+ const file = appPlistPath(home)
317
+ if (!fs.existsSync(file)) {
300
318
  return { available: false, reason: '没有找到小宇宙 App 的登录数据,请先打开小宇宙并登录一次' }
301
319
  }
302
320
  try {
303
- const xml = readAppPlistText(appPlistPath())
321
+ const xml = readAppPlistText(file)
304
322
  const accessToken = plistString(xml, 'default-apiAccessToken')
305
323
  const refreshToken = plistString(xml, 'default-apiRefreshToken')
306
324
  const deviceId = plistString(xml, 'app.podcast.cosmos.deviceId')
@@ -313,10 +331,10 @@ export function localAppStatus() {
313
331
  }
314
332
  }
315
333
 
316
- export async function loginFromLocalApp() {
317
- const state = localAppStatus()
334
+ export async function loginFromLocalApp(options = {}) {
335
+ const state = localAppStatus(options)
318
336
  if (!state.available) throw new Error(state.reason)
319
- const xml = readAppPlistText(appPlistPath())
337
+ const xml = readAppPlistText(appPlistPath(options.home ?? os.homedir()))
320
338
  const appAccess = plistString(xml, 'default-apiAccessToken')
321
339
  const appRefresh = plistString(xml, 'default-apiRefreshToken')
322
340
  const appDevice = plistString(xml, 'app.podcast.cosmos.deviceId')