dsh-oc-tui 0.1.4 → 0.2.0-pre.13

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/lib/updates.js CHANGED
@@ -1,697 +1,1028 @@
1
- // In-app update manager for dsh and dsh-oc-tui. All npm/pnpm interaction is
2
- // concentrated here (async spawn, no spawnSync), so the rest of the plugin only
3
- // wires the results into the settings UI. Version comparison is deliberately
4
- // dependency-free: major.minor.patch numerics plus a pre-release segment.
5
- import { spawn } from 'node:child_process'
6
- import { existsSync, readFileSync, readdirSync, realpathSync, unlinkSync, writeFileSync } from 'node:fs'
7
- import { createRequire } from 'node:module'
8
- import { delimiter, dirname, join, resolve } from 'node:path'
9
- import { homedir } from 'node:os'
10
- import { fileURLToPath } from 'node:url'
11
- import { stripAnsi } from './util.js'
12
- import { SETTINGS_MENU } from './web-settings.js'
13
-
14
- export const DSH_PACKAGE = '@deepseek-ai/dsh'
15
- export const TUI_PACKAGE = 'dsh-oc-tui'
16
-
17
- const PACKAGE_ROOT = dirname(fileURLToPath(new URL('../package.json', import.meta.url)))
18
- const TUI_MANIFEST = JSON.parse(readFileSync(join(PACKAGE_ROOT, 'package.json'), 'utf8'))
19
-
20
- // ---- version parsing / comparison (pure) ---------------------------------
21
-
22
- // Split a version into numeric core segments (padded to 3) and its pre-release
23
- // tail. Build metadata (`+...`) is stripped first, as is an optional leading
24
- // `v`/`=`. Non-numeric core parts degrade to 0 so a malformed version never
25
- // throws — it just compares as "older".
26
- export function splitVersion(version) {
27
- const text = String(version ?? '').trim()
28
- const withoutBuild = text.split('+')[0]
29
- const dash = withoutBuild.indexOf('-')
30
- const core = dash === -1 ? withoutBuild : withoutBuild.slice(0, dash)
31
- const pre = dash === -1 ? '' : withoutBuild.slice(dash + 1)
32
- const clean = core.replace(/^[v=]/, '')
33
- const segments = clean.split('.').map((part) => {
34
- const n = parseInt(part, 10)
35
- return Number.isFinite(n) ? n : 0
36
- })
37
- while (segments.length < 3) segments.push(0)
38
- return { segments, pre }
39
- }
40
-
41
- export function isPrerelease(version) {
42
- return splitVersion(version).pre !== ''
43
- }
44
-
45
- export function coreSegments(version) {
46
- return splitVersion(version).segments
47
- }
48
-
49
- // Semver-style pre-release comparison: numeric identifiers compare numerically
50
- // and sort below alphanumeric ones; a shorter list sorts first.
51
- function comparePrerelease(a, b) {
52
- const ap = a.split('.')
53
- const bp = b.split('.')
54
- const len = Math.max(ap.length, bp.length)
55
- for (let i = 0; i < len; i++) {
56
- const x = ap[i]
57
- const y = bp[i]
58
- if (x === undefined) return -1
59
- if (y === undefined) return 1
60
- const xn = /^\d+$/.test(x)
61
- const yn = /^\d+$/.test(y)
62
- if (xn && yn) {
63
- const diff = Number(x) - Number(y)
64
- if (diff !== 0) return diff
65
- } else if (xn !== yn) {
66
- return xn ? -1 : 1
67
- } else if (x < y) {
68
- return -1
69
- } else if (x > y) {
70
- return 1
71
- }
72
- }
73
- return 0
74
- }
75
-
76
- // Ascending comparison. A stable release sorts above a pre-release sharing its
77
- // core; otherwise cores decide first, then the pre-release tail.
78
- export function compareVersions(a, b) {
79
- const av = splitVersion(a)
80
- const bv = splitVersion(b)
81
- for (let i = 0; i < 3; i++) {
82
- if (av.segments[i] !== bv.segments[i]) return av.segments[i] - bv.segments[i]
83
- }
84
- if (av.pre === '' && bv.pre !== '') return 1
85
- if (av.pre !== '' && bv.pre === '') return -1
86
- if (av.pre === bv.pre) return 0
87
- return comparePrerelease(av.pre, bv.pre)
88
- }
89
-
90
- export function latestStable(versions) {
91
- if (!Array.isArray(versions)) return null
92
- let best = null
93
- for (const version of versions) {
94
- if (typeof version !== 'string' || version === '' || isPrerelease(version)) continue
95
- if (best === null || compareVersions(version, best) > 0) best = version
96
- }
97
- return best
98
- }
99
-
100
- // The "is there an update?" rule, stable releases only (pre-releases never
101
- // prompt). `installed` may be null/undefined (package not found).
102
- export function updateStatus(installed, registry) {
103
- const stable = latestStable(registry?.versions)
104
- if (stable === null) return { kind: 'no-stable' }
105
- if (installed === null || installed === undefined) return { kind: 'available', target: stable }
106
- const installedPre = isPrerelease(installed)
107
- const cmp = compareVersions(stable, installed)
108
- if (cmp > 0 || (cmp === 0 && installedPre)) return { kind: 'available', target: stable }
109
- return { kind: 'up-to-date' }
110
- }
111
-
112
- // ---- registry / install spawn helpers ------------------------------------
113
-
114
- // Parse `npm view <pkg> versions dist-tags --json`. Defensive: a versions
115
- // string degrades to a single-element array, missing/odd fields become empty.
116
- export function parseRegistryView(json) {
117
- let data
118
- try { data = JSON.parse(String(json ?? '')) } catch { data = null }
119
- const obj = data && typeof data === 'object' && !Array.isArray(data) ? data : {}
120
- let versions = obj.versions
121
- if (typeof versions === 'string') versions = [versions]
122
- if (!Array.isArray(versions)) versions = []
123
- versions = versions.filter((version) => typeof version === 'string' && version !== '')
124
- const distTags = obj['dist-tags'] && typeof obj['dist-tags'] === 'object' && !Array.isArray(obj['dist-tags'])
125
- ? obj['dist-tags']
126
- : {}
127
- const tags = {}
128
- for (const [tag, version] of Object.entries(distTags)) {
129
- if (typeof version === 'string' && version !== '') tags[tag] = version
130
- }
131
- return { versions, distTags: tags }
132
- }
133
-
134
- function findOnPath(name) {
135
- const path = process.env.PATH || ''
136
- const names = process.platform === 'win32' ? [name + '.cmd', name + '.exe', name] : [name]
137
- for (const directory of path.split(delimiter)) {
138
- if (directory === '') continue
139
- for (const candidate of names) {
140
- const full = join(directory, candidate)
141
- if (existsSync(full)) return full
142
- }
143
- }
144
- return undefined
145
- }
146
-
147
- // Resolve the dsh package's bin entry from an npm shim next to its install,
148
- // mirroring the launcher: returning the JS entry lets Windows run it through
149
- // node directly (avoids .cmd EINVAL hardening and shell quoting).
150
- function resolveDshEntry(dshExecutable) {
151
- try {
152
- const packagePath = createRequire(resolve(dshExecutable)).resolve(`${DSH_PACKAGE}/package.json`)
153
- const manifest = JSON.parse(readFileSync(packagePath, 'utf8'))
154
- const entry = typeof manifest.bin === 'string' ? manifest.bin : manifest.bin?.dsh
155
- if (typeof entry === 'string' && entry !== '') return resolve(dirname(packagePath), entry)
156
- } catch {
157
- // Not an npm shim beside the dsh install, or a non-npm layout.
158
- }
159
- return undefined
160
- }
161
-
162
- function npmCommand() {
163
- const bundled = join(dirname(process.execPath), 'node_modules', 'npm', 'bin', 'npm-cli.js')
164
- if (existsSync(bundled)) return { command: process.execPath, args: [bundled] }
165
- const onPath = findOnPath('npm')
166
- if (onPath !== undefined) return { command: onPath, args: [] }
167
- return undefined
168
- }
169
-
170
- function npxCommand() {
171
- const bundled = join(dirname(process.execPath), 'node_modules', 'npm', 'bin', 'npx-cli.js')
172
- if (existsSync(bundled)) return { command: process.execPath, args: [bundled] }
173
- const onPath = findOnPath('npx')
174
- if (onPath !== undefined) return { command: onPath, args: [] }
175
- return undefined
176
- }
177
-
178
- // Async spawn that collects stdout/stderr and resolves with the outcome. A
179
- // timeout kills the child instead of letting a hung registry/install freeze the
180
- // TUI. `.cmd`/`.bat` shims go through cmd.exe on Windows.
181
- function runCommand(command, args, timeoutMs) {
182
- if (process.platform === 'win32' && /\.(cmd|bat)$/i.test(command)) {
183
- return runCommand('cmd.exe', ['/d', '/s', '/c', command, ...args], timeoutMs)
184
- }
185
- return new Promise((resolve) => {
186
- let stdout = ''
187
- let stderr = ''
188
- let settled = false
189
- let child
190
- try {
191
- child = spawn(command, args, { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true })
192
- } catch (error) {
193
- resolve({ code: null, signal: null, stdout: '', stderr: error?.message ?? String(error) })
194
- return
195
- }
196
- const timer = setTimeout(() => {
197
- if (settled) return
198
- settled = true
199
- try { child.kill() } catch { /* already gone */ }
200
- resolve({ code: null, signal: 'timeout', stdout, stderr: stderr + `\n(timed out after ${timeoutMs}ms)` })
201
- }, timeoutMs)
202
- child.stdout.on('data', (chunk) => { stdout += chunk })
203
- child.stderr.on('data', (chunk) => { stderr += chunk })
204
- child.on('error', (error) => {
205
- if (settled) return
206
- settled = true
207
- clearTimeout(timer)
208
- resolve({ code: null, signal: null, stdout, stderr: stderr + '\n' + (error?.message ?? String(error)) })
209
- })
210
- child.on('close', (code, signal) => {
211
- if (settled) return
212
- settled = true
213
- clearTimeout(timer)
214
- resolve({ code, signal, stdout, stderr })
215
- })
216
- })
217
- }
218
-
219
- function runNpm(npmArgs, timeoutMs) {
220
- const npm = npmCommand()
221
- if (!npm) return Promise.resolve({ code: null, signal: null, stdout: '', stderr: 'npm not found on PATH' })
222
- return runCommand(npm.command, [...npm.args, ...npmArgs], timeoutMs)
223
- }
224
-
225
- function runDsh(dshArgs, timeoutMs, dshEntry) {
226
- if (dshEntry) return runCommand(process.execPath, [dshEntry, ...dshArgs], timeoutMs)
227
- const dshExecutable = findOnPath('dsh')
228
- if (dshExecutable !== undefined) {
229
- const entry = resolveDshEntry(dshExecutable)
230
- if (entry !== undefined) return runCommand(process.execPath, [entry, ...dshArgs], timeoutMs)
231
- return runCommand(dshExecutable, dshArgs, timeoutMs)
232
- }
233
- const npx = npxCommand()
234
- if (npx) return runCommand(npx.command, [...npx.args, '--yes', DSH_PACKAGE, ...dshArgs], timeoutMs)
235
- return Promise.resolve({ code: null, signal: null, stdout: '', stderr: 'dsh not found on PATH' })
236
- }
237
-
238
- // The last ~3 non-empty stderr lines, ANSI stripped and length-capped — the
239
- // digest shown in a failure toast.
240
- export function stderrSummary(stderr) {
241
- const text = stripAnsi(String(stderr ?? '')).trim()
242
- if (!text) return '(no output)'
243
- const lines = text.split(/\r?\n/).filter((line) => line.trim() !== '')
244
- const joined = lines.slice(-3).join(' · ')
245
- return joined.length > 240 ? joined.slice(0, 240) + '…' : joined
246
- }
247
-
248
- export async function registryInfo(pkg) {
249
- const result = await runNpm(['view', pkg, 'versions', 'dist-tags', '--json'], 30_000)
250
- if (result.code !== 0) throw new Error(stderrSummary(result.stderr) || `npm view ${pkg} exited ${result.code}`)
251
- return parseRegistryView(result.stdout)
252
- }
253
-
254
- export async function installDsh(version) {
255
- return runNpm(['install', '-g', `${DSH_PACKAGE}@${version}`], 300_000)
256
- }
257
-
258
- export async function installTui(version, profile, dshEntry) {
259
- return runDsh(['plugin', '--profile', profile, 'add', '-E', `${TUI_PACKAGE}@${version}`], 300_000, dshEntry)
260
- }
261
-
262
- // ---- install safety (Windows self-update lock) ----------------------------
263
- //
264
- // A `npm install -g @deepseek-ai/dsh` while any dsh process is alive can leave
265
- // a hybrid old/new tree behind: memory-mapped native DLLs (sharp) block npm's
266
- // directory retire/cleanup with EPERM, and npm still exits 0. The helpers here
267
- // exist so the UI can (a) refuse to run the install until every other dsh
268
- // process is gone (the TUI defers its own install to exit time), and (b) never
269
- // trust the exit code alone — after npm exits 0 the on-disk manifest must still
270
- // report the requested version.
271
-
272
- // A dsh process is running whose entry lives in `node_modules/@deepseek-ai/dsh`
273
- // (global CLI, `dsh web`, or another TUI). The path fragment is matched
274
- // case-insensitively with either separator, surviving quoting and both `node
275
- // dsh.cmd` (cmd shim name only) and resolved absolute paths.
276
- const DSH_ENTRY_FRAGMENT = 'dsh\\lib\\bin.js'
277
-
278
- function commandLineMatchesDsh(commandLine) {
279
- const normalized = String(commandLine ?? '').toLowerCase().replace(/\//g, '\\')
280
- return normalized.includes(DSH_ENTRY_FRAGMENT)
281
- }
282
-
283
- // Parse a tasklist row — either csv cells (["node.exe","8100","Console",…])
284
- // or the plain table format ("node.exe 8100 Console …"), where column
285
- // padding is not guaranteed to exceed one space.
286
- function parseTasklistRow(row) {
287
- if (Array.isArray(row)) {
288
- if (row.length < 2) return null
289
- const pid = Number(row[1])
290
- if (!Number.isInteger(pid) || pid <= 0) return null
291
- return { pid, name: String(row[0] ?? '') }
292
- }
293
- const m = /^(\S+)\s+(\d+)\s/.exec(String(row ?? ''))
294
- if (m === null) return null
295
- const pid = Number(m[2])
296
- return { pid, name: m[1] }
297
- }
298
-
299
- // Build the list of *other* running dsh processes. `rows` is a tasklist table
300
- // (arrays of csv cells or whitespace-split strings), `commandLineOf(pid)` an
301
- // optional wmic-style lookup, `selfPid` excluded (this TUI is itself a dsh
302
- // process). Merged by pid, first row wins: the node.exe row carries the real
303
- // command line, a later shim row (dsh.cmd) adds nothing.
304
- export function dshLockEntries(rows, commandLineOf, selfPid = 0) {
305
- const commandLine = typeof commandLineOf === 'function' ? commandLineOf : () => undefined
306
- const byPid = new Map()
307
- for (const row of Array.isArray(rows) ? rows : []) {
308
- const parsed = parseTasklistRow(row)
309
- if (parsed === null) continue
310
- if (parsed.pid === selfPid) continue
311
- if (byPid.has(parsed.pid)) continue
312
- if (parsed.name.toLowerCase() === 'node.exe') {
313
- const cmd = commandLine(parsed.pid) ?? ''
314
- if (commandLineMatchesDsh(cmd)) {
315
- byPid.set(parsed.pid, { pid: parsed.pid, name: parsed.name, commandLine: cmd })
316
- }
317
- } else if (parsed.name.toLowerCase().startsWith('dsh')) {
318
- byPid.set(parsed.pid, { pid: parsed.pid, name: parsed.name, commandLine: commandLine(parsed.pid) ?? '' })
319
- }
320
- }
321
- return [...byPid.values()]
322
- }
323
-
324
- // The live process table on Windows: [{ pid, name, commandLine }], self
325
- // excluded. wmic is gone on current Windows builds, so PowerShell CIM lists
326
- // node processes with their command lines in one shot. Any spawn failure
327
- // degrades to "no locks" — the install then proceeds and is still covered by
328
- // the post-install verification.
329
- export async function detectDshLocks(selfPid = 0) {
330
- if (process.platform !== 'win32') return []
331
- const ps = await runCommand('powershell.exe', ['-NoProfile', '-Command',
332
- "Get-CimInstance Win32_Process -Filter \"Name='node.exe'\" | ForEach-Object { \"{0}`t{1}`t{2}\" -f $_.ProcessId, $_.Name, $_.CommandLine }"], 30_000)
333
- if (ps.code !== 0) return []
334
- const rows = []
335
- const cmdlines = new Map()
336
- for (const line of ps.stdout.split(/\r?\n/)) {
337
- const m = /^(\d+)\t(\S+)\t(.*)$/.exec(String(line ?? '').trim())
338
- if (m === null) continue
339
- const pid = Number(m[1])
340
- rows.push([m[2], String(pid)])
341
- cmdlines.set(pid, m[3])
342
- }
343
- return dshLockEntries(rows, (pid) => cmdlines.get(pid), selfPid)
344
- }
345
-
346
- // Classify a finished `npm install -g dsh` run. npm exit 0 is downgraded to
347
- // `corrupt` unless the on-disk manifest exists and reports the requested
348
- // version — the exact shape of the 2026-09-04 hybrid-tree incident (npm
349
- // exited 0 while the tree mixed 0.1.1-rc.2 manifests with 0.1.2-rc.1 code).
350
- // `manifest` is the freshly-read dsh package.json object, or null/undefined
351
- // when it cannot be read at all (also corrupt: the install should never end
352
- // with the package gone).
353
- export function installResultFrom(spawnResult, manifest, requestedVersion) {
354
- const code = spawnResult?.code
355
- const stderr = spawnResult?.stderr ?? ''
356
- // Any npm failure (non-zero exit, kill, timeout) is 'failed' — the version
357
- // check below only decides between 'installed' and a *silent* corruption.
358
- if (code !== 0 || spawnResult?.signal) {
359
- return { kind: 'failed', code, stderr, reason: stderrSummary(stderr) || `install exited ${code ?? 'killed'}` }
360
- }
361
- const installed = manifest && typeof manifest === 'object' ? manifest.version : undefined
362
- if (code !== 0 || installed !== requestedVersion) {
363
- return {
364
- kind: 'corrupt',
365
- code,
366
- stderr,
367
- found: installed ?? null,
368
- reason: `install reported success but the installed version is ${installed ?? 'unreadable'} (expected ${requestedVersion}) — repair: fully close dsh, then npm install -g ${DSH_PACKAGE}@${requestedVersion}`,
369
- }
370
- }
371
- return { kind: 'installed', code, stderr, reason: '' }
372
- }
373
-
374
- // ---- deferred install on exit (Windows self-update) ------------------------
375
-
376
- // The inline CJS script the detached installer runs. argv (after `node -e
377
- // <script> …`): parentPid, npm command, npm args…, requested version, marker
378
- // path. It polls the parent pid (bounded — a reused pid must not wedge the
379
- // child forever), runs the npm install once the parent is gone, then records
380
- // the outcome in the marker.
381
- const DEFERRED_INSTALL_SCRIPT = [
382
- '(function () {',
383
- ' var argv = process.argv.slice(1)',
384
- ' var parentPid = Number(argv[0])',
385
- ' var npmCommand = argv[1]',
386
- ' var requested = argv[argv.length - 2]',
387
- ' var marker = argv[argv.length - 1]',
388
- ' var npmArgs = argv.slice(2, -2)',
389
- ' var deadline = Date.now() + 600000',
390
- ' var fs = require("fs")',
391
- ' var cp = require("child_process")',
392
- ' function alive(pid) { try { process.kill(pid, 0); return true } catch (err) { return false } }',
393
- ' function finish(code) {',
394
- ' try { fs.writeFileSync(marker, JSON.stringify({ requested: requested, code: code, finishedAt: Date.now() })) } catch (err) {}',
395
- ' process.exit(0)',
396
- ' }',
397
- ' ;(function poll() {',
398
- ' if (alive(parentPid) && Date.now() < deadline) { setTimeout(poll, 500); return }',
399
- ' if (alive(parentPid)) { finish(1) }',
400
- ' var child = cp.spawn(npmCommand, npmArgs, { stdio: "ignore", windowsHide: true })',
401
- ' child.on("error", function () { finish(1) })',
402
- ' child.on("close", function (code) { finish(code === null ? 1 : code) })',
403
- ' })()',
404
- '})()',
405
- ].join('\n')
406
-
407
- // Marker file recording the outcome of the last deferred install, read (and
408
- // drained) on the next boot to verify what the detached child actually did.
409
- export function installMarkerPath() {
410
- const home = process.env.DSH_HOME || homedir()
411
- return join(home, 'tui-dsh-install.json')
412
- }
413
-
414
- // Pure argv/options builder for the detached installer; `npm` defaults to
415
- // npmCommand() (the node + npm-cli bootstrap), `markerPath` to
416
- // installMarkerPath(). The install target args are appended here so the
417
- // spawned child receives the complete npm argv. Exposed for tests.
418
- export function deferredInstallSpec(version, parentPid, npm, markerPath) {
419
- const resolved = npm ?? npmCommand()
420
- const marker = markerPath ?? installMarkerPath()
421
- return {
422
- command: resolved.command,
423
- args: [
424
- '-e', DEFERRED_INSTALL_SCRIPT,
425
- String(parentPid), resolved.command, ...resolved.args,
426
- 'install', '-g', `${DSH_PACKAGE}@${version}`,
427
- String(version), marker,
428
- ],
429
- options: { detached: true, stdio: 'ignore', windowsHide: true },
430
- }
431
- }
432
-
433
- // Spawn the exit-time installer. Detached + unref'd: the child outlives this
434
- // process and never owns the terminal. Returns false when npm cannot be
435
- // located (nothing spawned, nothing recorded).
436
- export function spawnDeferredDshInstall(version, parentPid) {
437
- const npm = npmCommand()
438
- if (!npm) return false
439
- const spec = deferredInstallSpec(version, parentPid, npm)
440
- try {
441
- const child = spawn(spec.command, spec.args, spec.options)
442
- child.unref()
443
- return true
444
- } catch {
445
- return false
446
- }
447
- }
448
-
449
- // fs injectable for tests (existsSync / readFileSync / writeFileSync /
450
- // unlinkSync; default: node fs).
451
- const MARKER_FS = () => ({ existsSync, readFileSync, writeFileSync, unlinkSync })
452
-
453
- // Record the outcome of the last dsh install attempt.
454
- export function writeInstallMarker(fs, path, record) {
455
- const f = fs ?? MARKER_FS()
456
- try {
457
- f.writeFileSync(path, JSON.stringify({ requested: record?.requested, code: record?.code, finishedAt: Date.now() }))
458
- } catch {
459
- // Unwritable home: the next boot simply has nothing to verify.
460
- }
461
- }
462
-
463
- // Read and drain the marker: returns { requested, code, finishedAt } or null.
464
- // Missing and malformed markers both drain to null — a bad file must never
465
- // wedge the Update page.
466
- export function readInstallMarker(fs, path) {
467
- const f = fs ?? MARKER_FS()
468
- const file = path ?? installMarkerPath()
469
- if (!f.existsSync(file)) return null
470
- let text
471
- try { text = f.readFileSync(file, 'utf8') } catch { return null }
472
- try { f.unlinkSync(file) } catch { /* next write recreates it */ }
473
- try {
474
- const record = JSON.parse(text)
475
- if (record && typeof record === 'object' && typeof record.requested === 'string' && Number.isInteger(record.code)) {
476
- return { requested: record.requested, code: record.code, finishedAt: record.finishedAt ?? 0 }
477
- }
478
- } catch { /* malformed marker */ }
479
- return null
480
- }
481
-
482
- // Evaluate a drained marker against the version live on disk. Returns the
483
- // same shapes as installResultFrom: 'installed' means the deferred install
484
- // landed, 'corrupt' means exit 0 with the wrong version on disk (silent
485
- // hybrid tree), 'failed' means npm itself failed.
486
- export function deferredInstallOutcome(marker, installedVersion) {
487
- if (!marker) return null
488
- return installResultFrom({ code: marker.code, stderr: '' }, { version: installedVersion }, marker.requested)
489
- }
490
-
491
- // ---- local install detection ---------------------------------------------
492
-
493
- // Read the active profile's package.json and report whether dsh-oc-tui is
494
- // installed from a local path / file: reference (which `plugin add` will switch
495
- // to a registry version).
496
- export function tuiInstallIsLocal(profile) {
497
- try {
498
- const home = process.env.DSH_HOME || homedir()
499
- const manifest = JSON.parse(readFileSync(join(home, 'profiles', profile, 'package.json'), 'utf8'))
500
- const dep = manifest?.dependencies?.[TUI_PACKAGE] ?? manifest?.devDependencies?.[TUI_PACKAGE]
501
- if (typeof dep !== 'string' || dep === '') return false
502
- return dep.startsWith('file:') || dep.startsWith('link:') || dep.startsWith('.')
503
- || dep.startsWith('/') || /^[A-Za-z]:/.test(dep)
504
- } catch {
505
- return false
506
- }
507
- }
508
-
509
- // The version of this running dsh-oc-tui package (its own package.json).
510
- export function tuiInstalledVersion() {
511
- return TUI_MANIFEST.version
512
- }
513
-
514
- // The dsh install on PATH: version + JS bin entry, or `{ found: false }`.
515
- // Millisecond-scale — no spawn.
516
- export function detectDshInstall() {
517
- const dshExecutable = findOnPath('dsh')
518
- if (dshExecutable === undefined) return { found: false }
519
- try {
520
- const packagePath = createRequire(resolve(dshExecutable)).resolve(`${DSH_PACKAGE}/package.json`)
521
- const manifest = JSON.parse(readFileSync(packagePath, 'utf8'))
522
- return { found: true, version: manifest.version ?? null, entry: resolveDshEntry(dshExecutable) }
523
- } catch {
524
- return { found: false }
525
- }
526
- }
527
-
528
- function safeRealpath(realpath, path) {
529
- try { return realpath(path) } catch { return path }
530
- }
531
-
532
- // Which profile is this TUI booted under? Priority:
533
- // 1. DSH_TUI_BOOT_PROFILE (injected by the launcher);
534
- // 2. the profile whose node_modules/dsh-oc-tui realpaths to this package root
535
- // (survives pnpm symlinks);
536
- // 3. the default profile name 'tui'.
537
- // `fs` is injectable for tests (readdirSync / realpathSync / env / homedir).
538
- export function resolveActiveProfile(fs = {}) {
539
- const env = fs.env ?? process.env
540
- if (env.DSH_TUI_BOOT_PROFILE) return env.DSH_TUI_BOOT_PROFILE
541
- const readdir = fs.readdirSync ?? readdirSync
542
- const realpath = fs.realpathSync ?? realpathSync
543
- const homeFn = fs.homedir ?? homedir
544
- const home = env.DSH_HOME || homeFn()
545
- const profilesDir = join(home, 'profiles')
546
- const selfRoot = safeRealpath(realpath, PACKAGE_ROOT)
547
- let entries
548
- try {
549
- entries = readdir(profilesDir, { withFileTypes: true })
550
- } catch {
551
- return 'tui'
552
- }
553
- for (const entry of entries ?? []) {
554
- if (!entry || typeof entry.isDirectory !== 'function' || !entry.isDirectory()) continue
555
- const candidate = join(profilesDir, entry.name, 'node_modules', TUI_PACKAGE)
556
- if (safeRealpath(realpath, candidate) === selfRoot) return entry.name
557
- }
558
- return 'tui'
559
- }
560
-
561
- // ---- item builders (pure) ------------------------------------------------
562
-
563
- function infoRow(label, value, extra = {}) {
564
- return { kind: 'update-info', label, value, disabled: true, ...extra }
565
- }
566
-
567
- function statusText(status, error, installed, corrupt, note) {
568
- if (corrupt) return 'Install damaged — reinstall below'
569
- if (note) return note
570
- if (!installed && !status && !error) return '—'
571
- if (error) return 'Registry check failed: ' + error
572
- if (!status) return '—'
573
- if (status.kind === 'available') return 'Update available → ' + status.target
574
- if (status.kind === 'up-to-date') return 'Up to date'
575
- return 'No stable release — pick from Versions'
576
- }
577
-
578
- // Build the Update page's item rows from a state snapshot (see
579
- // `loadUpdateView` for the shape). Pure so the smoke tests can drive it.
580
- export function buildUpdateItems(state) {
581
- const items = []
582
- const pushBlock = (pkg, label, section) => {
583
- items.push({ kind: 'header', label, value: '', disabled: true })
584
- const installed = section.installed
585
- const registry = section.registry
586
- const status = installed && registry ? updateStatus(installed, registry) : null
587
- items.push(infoRow('Installed', installed ?? (section.found ? 'unknown' : 'not found on PATH')))
588
- items.push(infoRow('Latest (npm tag)', registry?.distTags?.latest ?? (section.error ? 'unavailable' : '—')))
589
- items.push(infoRow('Status', statusText(status, section.error, installed, section.corrupt === true, section.note),
590
- section.corrupt === true ? { tone: 'error', pkg } : status?.kind === 'available' || section.note ? { tone: 'warning', pkg } : { pkg }))
591
- items.push({ kind: 'update-versions', label: 'Versions', value: 'Select version…', pkg, disabled: false })
592
- }
593
- items.push(infoRow('profile', state.profile))
594
- pushBlock('dsh', 'dsh (@deepseek-ai/dsh)', state.dsh)
595
- pushBlock('tui', 'dsh-oc-tui', state.tui)
596
- items.push({ kind: 'header', label: 'Actions', value: '', disabled: true })
597
- items.push({ kind: 'update-check', label: 'Check now', value: state.checking ? 'Checking…' : 'Enter', disabled: state.busy === true })
598
- items.push({
599
- kind: 'choice',
600
- ns: 'tui-updates',
601
- field: 'startupCheck',
602
- label: 'Startup check',
603
- value: state.startupCheck ?? 'on',
604
- options: ['on', 'off'],
605
- revision: state.startupCheckRevision ?? 0,
606
- disabled: state.startupCheck === null || state.settingsWritable === false,
607
- })
608
- return items
609
- }
610
-
611
- // Build the version picker rows for one package, newest first, with the
612
- // dist-tags and the installed marker attached for the renderer to color.
613
- export function buildVersionItems(registry, installed) {
614
- const versions = Array.isArray(registry?.versions) ? registry.versions.slice() : []
615
- const distTags = registry?.distTags && typeof registry.distTags === 'object' ? registry.distTags : {}
616
- const tagsByVersion = new Map()
617
- for (const [tag, version] of Object.entries(distTags)) {
618
- if (typeof version !== 'string' || version === '') continue
619
- if (!tagsByVersion.has(version)) tagsByVersion.set(version, [])
620
- tagsByVersion.get(version).push(tag)
621
- }
622
- versions.sort((a, b) => compareVersions(b, a))
623
- return versions.map((version) => ({
624
- kind: 'update-version',
625
- label: version,
626
- value: '',
627
- version,
628
- tags: tagsByVersion.get(version) ?? [],
629
- installed: version === installed,
630
- disabled: false,
631
- }))
632
- }
633
-
634
- // ---- the Update settings loader ------------------------------------------
635
-
636
- export async function loadUpdateView(ctx) {
637
- const settings = ctx.get('settings')
638
- let updDescriptor
639
- let startupCheck = 'on'
640
- let startupCheckRevision = 0
641
- if (settings) {
642
- try {
643
- updDescriptor = settings.describe({ redactSecrets: true }).find((entry) => String(entry.ns) === 'tui-updates')
644
- startupCheck = updDescriptor?.value?.startupCheck ?? 'on'
645
- startupCheckRevision = updDescriptor?.revision ?? 0
646
- } catch {
647
- updDescriptor = undefined
648
- }
649
- }
650
- const state = {
651
- profile: resolveActiveProfile(),
652
- dsh: { found: false, installed: null, entry: undefined, registry: null, error: null },
653
- tui: { installed: tuiInstalledVersion(), registry: null, error: null },
654
- startupCheck: settings ? startupCheck : null,
655
- startupCheckRevision,
656
- settingsWritable: settings?.writable !== false,
657
- checking: false,
658
- busy: false,
659
- }
660
- const dshInstall = detectDshInstall()
661
- state.dsh.found = dshInstall.found
662
- state.dsh.installed = dshInstall.version ?? null
663
- // On every Update-page load: consume the deferred-install marker (left by
664
- // the exit-time installer of a previous run) and, when the TUI boots fine
665
- // but the manifest mismatches its own files, surface the hybrid-tree state
666
- // from the 2026-09-04 incident so the user is pointed at a reinstall.
667
- const marker = readInstallMarker()
668
- if (marker) {
669
- const outcome = deferredInstallOutcome(marker, dshInstall.version ?? undefined)
670
- if (outcome?.kind === 'failed') {
671
- state.dsh.note = `Deferred install failed (exit ${marker.code}) — retry from Versions`
672
- } else if (outcome?.kind === 'corrupt') {
673
- state.dsh.corrupt = true
674
- state.dsh.note = outcome.reason
675
- }
676
- // 'installed' needs no note — the Installed row already shows the version.
677
- }
678
- state.dsh.entry = dshInstall.entry
679
- const [dshResult, tuiResult] = await Promise.all([
680
- registryInfo(DSH_PACKAGE).then((registry) => ({ registry })).catch((error) => ({ error: error?.message ?? String(error) })),
681
- registryInfo(TUI_PACKAGE).then((registry) => ({ registry })).catch((error) => ({ error: error?.message ?? String(error) })),
682
- ])
683
- state.dsh.registry = dshResult.registry ?? null
684
- state.dsh.error = dshResult.error ?? null
685
- state.tui.registry = tuiResult.registry ?? null
686
- state.tui.error = tuiResult.error ?? null
687
-
688
- return {
689
- settings,
690
- items: buildUpdateItems(state),
691
- title: 'Update',
692
- subtitle: 'Enter select · installs need a restart to apply',
693
- menu: SETTINGS_MENU,
694
- menuIndex: Math.max(0, SETTINGS_MENU.findIndex((entry) => entry.id === 'update')),
695
- state,
696
- }
697
- }
1
+ // In-app update manager for dsh and dsh-oc-tui. Every network/package-manager
2
+ // interaction is concentrated here (async spawn plus a streaming fetch, never a
3
+ // blocking install), so the rest of the plugin only wires results into the
4
+ // settings UI. Version comparison is deliberately dependency-free:
5
+ // major.minor.patch numerics plus a pre-release segment.
6
+ import { spawn } from 'node:child_process'
7
+ import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'
8
+ import { createHash } from 'node:crypto'
9
+ import { createRequire } from 'node:module'
10
+ import { delimiter, dirname, join, resolve } from 'node:path'
11
+ import { homedir } from 'node:os'
12
+ import { fileURLToPath } from 'node:url'
13
+ import { stripAnsi } from './util.js'
14
+ import { SETTINGS_MENU, resolveTuiSetting } from './web-settings.js'
15
+ import { t, valueChoices } from './i18n.js'
16
+
17
+ export const DSH_PACKAGE = '@deepseek-ai/dsh'
18
+ export const TUI_PACKAGE = 'dsh-oc-tui'
19
+
20
+ const PACKAGE_ROOT = dirname(fileURLToPath(new URL('../package.json', import.meta.url)))
21
+ const TUI_MANIFEST = JSON.parse(readFileSync(join(PACKAGE_ROOT, 'package.json'), 'utf8'))
22
+
23
+ // ---- version parsing / comparison (pure) ---------------------------------
24
+
25
+ // Split a version into numeric core segments (padded to 3) and its pre-release
26
+ // tail. Build metadata (`+...`) is stripped first, as is an optional leading
27
+ // `v`/`=`. Non-numeric core parts degrade to 0 so a malformed version never
28
+ // throws — it just compares as "older".
29
+ export function splitVersion(version) {
30
+ const text = String(version ?? '').trim()
31
+ const withoutBuild = text.split('+')[0]
32
+ const dash = withoutBuild.indexOf('-')
33
+ const core = dash === -1 ? withoutBuild : withoutBuild.slice(0, dash)
34
+ const pre = dash === -1 ? '' : withoutBuild.slice(dash + 1)
35
+ const clean = core.replace(/^[v=]/, '')
36
+ const segments = clean.split('.').map((part) => {
37
+ const n = parseInt(part, 10)
38
+ return Number.isFinite(n) ? n : 0
39
+ })
40
+ while (segments.length < 3) segments.push(0)
41
+ return { segments, pre }
42
+ }
43
+
44
+ export function isPrerelease(version) {
45
+ return splitVersion(version).pre !== ''
46
+ }
47
+
48
+ export function coreSegments(version) {
49
+ return splitVersion(version).segments
50
+ }
51
+
52
+ // Semver-style pre-release comparison: numeric identifiers compare numerically
53
+ // and sort below alphanumeric ones; a shorter list sorts first.
54
+ function comparePrerelease(a, b) {
55
+ const ap = a.split('.')
56
+ const bp = b.split('.')
57
+ const len = Math.max(ap.length, bp.length)
58
+ for (let i = 0; i < len; i++) {
59
+ const x = ap[i]
60
+ const y = bp[i]
61
+ if (x === undefined) return -1
62
+ if (y === undefined) return 1
63
+ const xn = /^\d+$/.test(x)
64
+ const yn = /^\d+$/.test(y)
65
+ if (xn && yn) {
66
+ const diff = Number(x) - Number(y)
67
+ if (diff !== 0) return diff
68
+ } else if (xn !== yn) {
69
+ return xn ? -1 : 1
70
+ } else if (x < y) {
71
+ return -1
72
+ } else if (x > y) {
73
+ return 1
74
+ }
75
+ }
76
+ return 0
77
+ }
78
+
79
+ // Ascending comparison. A stable release sorts above a pre-release sharing its
80
+ // core; otherwise cores decide first, then the pre-release tail.
81
+ export function compareVersions(a, b) {
82
+ const av = splitVersion(a)
83
+ const bv = splitVersion(b)
84
+ for (let i = 0; i < 3; i++) {
85
+ if (av.segments[i] !== bv.segments[i]) return av.segments[i] - bv.segments[i]
86
+ }
87
+ if (av.pre === '' && bv.pre !== '') return 1
88
+ if (av.pre !== '' && bv.pre === '') return -1
89
+ if (av.pre === bv.pre) return 0
90
+ return comparePrerelease(av.pre, bv.pre)
91
+ }
92
+
93
+ export function latestStable(versions) {
94
+ if (!Array.isArray(versions)) return null
95
+ let best = null
96
+ for (const version of versions) {
97
+ if (typeof version !== 'string' || version === '' || isPrerelease(version)) continue
98
+ if (best === null || compareVersions(version, best) > 0) best = version
99
+ }
100
+ return best
101
+ }
102
+
103
+ // The "is there an update?" rule, stable releases only (pre-releases never
104
+ // prompt). `installed` may be null/undefined (package not found).
105
+ export function updateStatus(installed, registry) {
106
+ const stable = latestStable(registry?.versions)
107
+ if (stable === null) return { kind: 'no-stable' }
108
+ if (installed === null || installed === undefined) return { kind: 'available', target: stable }
109
+ const installedPre = isPrerelease(installed)
110
+ const cmp = compareVersions(stable, installed)
111
+ if (cmp > 0 || (cmp === 0 && installedPre)) return { kind: 'available', target: stable }
112
+ return { kind: 'up-to-date' }
113
+ }
114
+
115
+ // ---- registry / install spawn helpers ------------------------------------
116
+
117
+ // Parse `npm view <pkg> versions dist-tags --json`. Defensive: a versions
118
+ // string degrades to a single-element array, missing/odd fields become empty.
119
+ export function parseRegistryView(json) {
120
+ let data
121
+ try { data = JSON.parse(String(json ?? '')) } catch { data = null }
122
+ const obj = data && typeof data === 'object' && !Array.isArray(data) ? data : {}
123
+ let versions = obj.versions
124
+ if (typeof versions === 'string') versions = [versions]
125
+ if (!Array.isArray(versions)) versions = []
126
+ versions = versions.filter((version) => typeof version === 'string' && version !== '')
127
+ const distTags = obj['dist-tags'] && typeof obj['dist-tags'] === 'object' && !Array.isArray(obj['dist-tags'])
128
+ ? obj['dist-tags']
129
+ : {}
130
+ const tags = {}
131
+ for (const [tag, version] of Object.entries(distTags)) {
132
+ if (typeof version === 'string' && version !== '') tags[tag] = version
133
+ }
134
+ return { versions, distTags: tags }
135
+ }
136
+
137
+ function findOnPath(name) {
138
+ const path = process.env.PATH || ''
139
+ const names = process.platform === 'win32' ? [name + '.cmd', name + '.exe', name] : [name]
140
+ for (const directory of path.split(delimiter)) {
141
+ if (directory === '') continue
142
+ for (const candidate of names) {
143
+ const full = join(directory, candidate)
144
+ if (existsSync(full)) return full
145
+ }
146
+ }
147
+ return undefined
148
+ }
149
+
150
+ // Resolve the dsh package's bin entry from an npm shim next to its install,
151
+ // mirroring the launcher: returning the JS entry lets Windows run it through
152
+ // node directly (avoids .cmd EINVAL hardening and shell quoting).
153
+ function resolveDshEntry(dshExecutable) {
154
+ try {
155
+ const packagePath = createRequire(resolve(dshExecutable)).resolve(`${DSH_PACKAGE}/package.json`)
156
+ const manifest = JSON.parse(readFileSync(packagePath, 'utf8'))
157
+ const entry = typeof manifest.bin === 'string' ? manifest.bin : manifest.bin?.dsh
158
+ if (typeof entry === 'string' && entry !== '') return resolve(dirname(packagePath), entry)
159
+ } catch {
160
+ // Not an npm shim beside the dsh install, or a non-npm layout.
161
+ }
162
+ return undefined
163
+ }
164
+
165
+ export function npmCommand() {
166
+ const bundled = join(dirname(process.execPath), 'node_modules', 'npm', 'bin', 'npm-cli.js')
167
+ if (existsSync(bundled)) return { command: process.execPath, args: [bundled] }
168
+ const onPath = findOnPath('npm')
169
+ if (onPath !== undefined) return { command: onPath, args: [] }
170
+ return undefined
171
+ }
172
+
173
+ // Async spawn that collects stdout/stderr and resolves with the outcome. A
174
+ // timeout kills the child instead of letting a hung registry/install freeze the
175
+ // TUI. `.cmd`/`.bat` shims go through cmd.exe on Windows.
176
+ function runCommand(command, args, timeoutMs) {
177
+ if (process.platform === 'win32' && /\.(cmd|bat)$/i.test(command)) {
178
+ return runCommand('cmd.exe', ['/d', '/s', '/c', command, ...args], timeoutMs)
179
+ }
180
+ return new Promise((resolve) => {
181
+ let stdout = ''
182
+ let stderr = ''
183
+ let settled = false
184
+ let child
185
+ try {
186
+ child = spawn(command, args, { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true })
187
+ } catch (error) {
188
+ resolve({ code: null, signal: null, stdout: '', stderr: error?.message ?? String(error) })
189
+ return
190
+ }
191
+ const timer = setTimeout(() => {
192
+ if (settled) return
193
+ settled = true
194
+ try { child.kill() } catch { /* already gone */ }
195
+ resolve({ code: null, signal: 'timeout', stdout, stderr: stderr + t('update.timedOut', { ms: timeoutMs }) })
196
+ }, timeoutMs)
197
+ child.stdout.on('data', (chunk) => { stdout += chunk })
198
+ child.stderr.on('data', (chunk) => { stderr += chunk })
199
+ child.on('error', (error) => {
200
+ if (settled) return
201
+ settled = true
202
+ clearTimeout(timer)
203
+ resolve({ code: null, signal: null, stdout, stderr: stderr + '\n' + (error?.message ?? String(error)) })
204
+ })
205
+ child.on('close', (code, signal) => {
206
+ if (settled) return
207
+ settled = true
208
+ clearTimeout(timer)
209
+ resolve({ code, signal, stdout, stderr })
210
+ })
211
+ })
212
+ }
213
+
214
+ function runNpm(npmArgs, timeoutMs) {
215
+ const npm = npmCommand()
216
+ if (!npm) return Promise.resolve({ code: null, signal: null, stdout: '', stderr: t('update.npmMissing') })
217
+ return runCommand(npm.command, [...npm.args, ...npmArgs], timeoutMs)
218
+ }
219
+
220
+ // The last ~3 non-empty stderr lines, ANSI stripped and length-capped — the
221
+ // digest shown in a failure toast.
222
+ export function stderrSummary(stderr) {
223
+ const text = stripAnsi(String(stderr ?? '')).trim()
224
+ if (!text) return t('update.noOutput')
225
+ const lines = text.split(/\r?\n/).filter((line) => line.trim() !== '')
226
+ const joined = lines.slice(-3).join(' · ')
227
+ return joined.length > 240 ? joined.slice(0, 240) + '…' : joined
228
+ }
229
+
230
+ export async function registryInfo(pkg) {
231
+ const result = await runNpm(['view', pkg, 'versions', 'dist-tags', '--json'], 30_000)
232
+ if (result.code !== 0) throw new Error(stderrSummary(result.stderr) || t('update.npmViewFailed', { package: pkg, code: result.code }))
233
+ return parseRegistryView(result.stdout)
234
+ }
235
+
236
+ // The dsh executable on PATH (an npm shim on Windows). The applier uses it to
237
+ // re-resolve the dsh bin entry *after* a dsh update, so a layout change in the
238
+ // new version cannot break the relaunch.
239
+ export function dshShimPath() {
240
+ return findOnPath('dsh') ?? null
241
+ }
242
+
243
+ // Args the running dsh was started with (everything after its bin entry) — the
244
+ // relaunch replays them verbatim so `--profile tui --resume` survives.
245
+ export function dshProcessArgs() {
246
+ return process.argv.slice(2)
247
+ }
248
+
249
+ // ---- install safety (Windows self-update lock) ----------------------------
250
+ //
251
+ // A `npm install -g @deepseek-ai/dsh` while any dsh process is alive can leave
252
+ // a hybrid old/new tree behind: memory-mapped native DLLs (sharp) block npm's
253
+ // directory retire/cleanup with EPERM, and npm still exits 0. The helpers here
254
+ // exist so the UI can (a) refuse to run the install until every other dsh
255
+ // process is gone (the TUI defers its own install to exit time), and (b) never
256
+ // trust the exit code alone — after npm exits 0 the on-disk manifest must still
257
+ // report the requested version.
258
+
259
+ // A dsh process is running whose entry lives in `node_modules/@deepseek-ai/dsh`
260
+ // (global CLI, `dsh web`, or another TUI). The path fragment is matched
261
+ // case-insensitively with either separator, surviving quoting and both `node
262
+ // dsh.cmd` (cmd shim name only) and resolved absolute paths.
263
+ const DSH_ENTRY_FRAGMENT = 'dsh\\lib\\bin.js'
264
+
265
+ function commandLineMatchesDsh(commandLine) {
266
+ const normalized = String(commandLine ?? '').toLowerCase().replace(/\//g, '\\')
267
+ return normalized.includes(DSH_ENTRY_FRAGMENT)
268
+ }
269
+
270
+ // Parse a tasklist row — either csv cells (["node.exe","8100","Console",…])
271
+ // or the plain table format ("node.exe 8100 Console …"), where column
272
+ // padding is not guaranteed to exceed one space.
273
+ function parseTasklistRow(row) {
274
+ if (Array.isArray(row)) {
275
+ if (row.length < 2) return null
276
+ const pid = Number(row[1])
277
+ if (!Number.isInteger(pid) || pid <= 0) return null
278
+ return { pid, name: String(row[0] ?? '') }
279
+ }
280
+ const m = /^(\S+)\s+(\d+)\s/.exec(String(row ?? ''))
281
+ if (m === null) return null
282
+ const pid = Number(m[2])
283
+ return { pid, name: m[1] }
284
+ }
285
+
286
+ // Build the list of *other* running dsh processes. `rows` is a tasklist table
287
+ // (arrays of csv cells or whitespace-split strings), `commandLineOf(pid)` an
288
+ // optional wmic-style lookup, `selfPid` excluded (this TUI is itself a dsh
289
+ // process). Merged by pid, first row wins: the node.exe row carries the real
290
+ // command line, a later shim row (dsh.cmd) adds nothing.
291
+ export function dshLockEntries(rows, commandLineOf, selfPid = 0) {
292
+ const commandLine = typeof commandLineOf === 'function' ? commandLineOf : () => undefined
293
+ const byPid = new Map()
294
+ for (const row of Array.isArray(rows) ? rows : []) {
295
+ const parsed = parseTasklistRow(row)
296
+ if (parsed === null) continue
297
+ if (parsed.pid === selfPid) continue
298
+ if (byPid.has(parsed.pid)) continue
299
+ if (parsed.name.toLowerCase() === 'node.exe') {
300
+ const cmd = commandLine(parsed.pid) ?? ''
301
+ if (commandLineMatchesDsh(cmd)) {
302
+ byPid.set(parsed.pid, { pid: parsed.pid, name: parsed.name, commandLine: cmd })
303
+ }
304
+ } else if (parsed.name.toLowerCase().startsWith('dsh')) {
305
+ byPid.set(parsed.pid, { pid: parsed.pid, name: parsed.name, commandLine: commandLine(parsed.pid) ?? '' })
306
+ }
307
+ }
308
+ return [...byPid.values()]
309
+ }
310
+
311
+ // The live process table on Windows: [{ pid, name, commandLine }], self
312
+ // excluded. wmic is gone on current Windows builds, so PowerShell CIM lists
313
+ // node processes with their command lines in one shot. Any spawn failure
314
+ // degrades to "no locks" — the install then proceeds and is still covered by
315
+ // the post-install verification.
316
+ export async function detectDshLocks(selfPid = 0) {
317
+ if (process.platform !== 'win32') return []
318
+ const ps = await runCommand('powershell.exe', ['-NoProfile', '-Command',
319
+ "Get-CimInstance Win32_Process -Filter \"Name='node.exe'\" | ForEach-Object { \"{0}`t{1}`t{2}\" -f $_.ProcessId, $_.Name, $_.CommandLine }"], 30_000)
320
+ if (ps.code !== 0) return []
321
+ const rows = []
322
+ const cmdlines = new Map()
323
+ for (const line of ps.stdout.split(/\r?\n/)) {
324
+ const m = /^(\d+)\t(\S+)\t(.*)$/.exec(String(line ?? '').trim())
325
+ if (m === null) continue
326
+ const pid = Number(m[1])
327
+ rows.push([m[2], String(pid)])
328
+ cmdlines.set(pid, m[3])
329
+ }
330
+ return dshLockEntries(rows, (pid) => cmdlines.get(pid), selfPid)
331
+ }
332
+
333
+ // Classify a finished `npm install -g dsh` run. npm exit 0 is downgraded to
334
+ // `corrupt` unless the on-disk manifest exists and reports the requested
335
+ // version — the exact shape of the 2026-09-04 hybrid-tree incident (npm
336
+ // exited 0 while the tree mixed 0.1.1-rc.2 manifests with 0.1.2-rc.1 code).
337
+ // `manifest` is the freshly-read package.json object, or null/undefined when
338
+ // it cannot be read at all (also corrupt: the install should never end with
339
+ // the package gone). `repair` overrides the repair hint for the TUI package,
340
+ // which is repaired through the profile rather than through npm.
341
+ export function installResultFrom(spawnResult, manifest, requestedVersion, repair) {
342
+ const code = spawnResult?.code
343
+ const stderr = spawnResult?.stderr ?? ''
344
+ // Any npm failure (non-zero exit, kill, timeout) is 'failed' — the version
345
+ // check below only decides between 'installed' and a *silent* corruption.
346
+ if (code !== 0 || spawnResult?.signal) {
347
+ return { kind: 'failed', code, stderr, reason: stderrSummary(stderr) || `install exited ${code ?? 'killed'}` }
348
+ }
349
+ const installed = manifest && typeof manifest === 'object' ? manifest.version : undefined
350
+ if (code !== 0 || installed !== requestedVersion) {
351
+ return {
352
+ kind: 'corrupt',
353
+ code,
354
+ stderr,
355
+ found: installed ?? null,
356
+ reason: t('update.installUnreadable', {
357
+ installed: installed ?? 'unreadable',
358
+ expected: requestedVersion,
359
+ repair: repair ?? `fully close dsh, then npm install -g ${DSH_PACKAGE}@${requestedVersion}`,
360
+ }),
361
+ }
362
+ }
363
+ return { kind: 'installed', code, stderr, reason: '' }
364
+ }
365
+
366
+ // ---- download, stage, restart (the whole update path) ---------------------
367
+ //
368
+ // Updating never installs inline. The TUI downloads the registry tarball
369
+ // itself — so the user watches real byte progress instead of a spinner — and
370
+ // stages it under $DSH_HOME/updates, recording what is staged in `staged.json`.
371
+ // Applying is a *restart*: this process exits, and a detached applier child
372
+ // (bin/apply-update.cjs) waits for it to die, installs from the staged tarball,
373
+ // verifies the on-disk version, writes the install marker, then relaunches dsh
374
+ // in the same terminal. Two properties fall out of that shape:
375
+ //
376
+ // * the install never runs while this process holds the files, so the Windows
377
+ // self-update hazard (npm exiting 0 over a hybrid old/new tree) cannot be
378
+ // triggered from inside the TUI — the exit *is* the handoff;
379
+ // * the staged tarball stays on disk, so a rollback to an older version is a
380
+ // verified cache hit through exactly the same code path as an update.
381
+
382
+ const DSH_REGISTRY = 'https://registry.npmjs.org'
383
+ const METADATA_TIMEOUT_MS = 30_000
384
+
385
+ // ---- byte / progress formatting (pure) -----------------------------------
386
+
387
+ // Human-readable byte count: bytes below 1 KiB, then one decimal that drops to
388
+ // zero above 100, so '1.2 GB' and '120 GB' both fit a narrow row.
389
+ export function formatBytes(bytes) {
390
+ const n = Number(bytes)
391
+ if (!Number.isFinite(n) || n <= 0) return '0 B'
392
+ if (n < 1024) return n + ' B'
393
+ const units = ['KB', 'MB', 'GB', 'TB']
394
+ let value = n / 1024
395
+ let unit = 0
396
+ while (value >= 1024 && unit < units.length - 1) {
397
+ value /= 1024
398
+ unit += 1
399
+ }
400
+ return (value >= 100 ? value.toFixed(0) : value.toFixed(1)) + ' ' + units[unit]
401
+ }
402
+
403
+ // Progress text for a running download. An unknown total (no content-length,
404
+ // chunked transfer) reports bytes only — never an invented percentage.
405
+ export function formatDownloadProgress(received, total) {
406
+ const got = Number.isFinite(Number(received)) ? Math.max(0, Number(received)) : 0
407
+ const want = Number(total)
408
+ if (!Number.isFinite(want) || want <= 0) return { text: formatBytes(got), percent: null }
409
+ const percent = Math.max(0, Math.min(100, Math.round((got / want) * 100)))
410
+ return { text: formatBytes(got) + ' / ' + formatBytes(want) + ' · ' + percent + '%', percent }
411
+ }
412
+
413
+ // ---- staging paths -------------------------------------------------------
414
+
415
+ // Cache file name prefix for a package: `deepseek-ai-dsh-`, `dsh-oc-tui-`.
416
+ function tarballPrefix(pkg) {
417
+ return String(pkg ?? '').replace(/^@/, '').replace(/[/\\]/g, '-') + '-'
418
+ }
419
+
420
+ // One flat cache file per package + version: `deepseek-ai-dsh-0.2.0-rc.2.tgz`,
421
+ // `dsh-oc-tui-0.1.4.tgz`.
422
+ export function tarballFileName(pkg, version) {
423
+ return tarballPrefix(pkg) + String(version ?? '') + '.tgz'
424
+ }
425
+
426
+ export function updateCacheDir() {
427
+ const home = process.env.DSH_HOME || join(homedir(), '.dsh')
428
+ return join(home, 'updates')
429
+ }
430
+
431
+ export function tarballCachePath(pkg, version) {
432
+ return join(updateCacheDir(), tarballFileName(pkg, version))
433
+ }
434
+
435
+ // The record of a downloaded-but-not-applied install.
436
+ export function stagedInstallPath() {
437
+ return join(updateCacheDir(), 'staged.json')
438
+ }
439
+
440
+ const STAGED_FS = () => ({ existsSync, readFileSync, writeFileSync, unlinkSync, mkdirSync })
441
+
442
+ export function writeStagedInstall(fs, path, record) {
443
+ const f = fs ?? STAGED_FS()
444
+ try {
445
+ if (typeof f.mkdirSync === 'function') f.mkdirSync(dirname(path), { recursive: true })
446
+ f.writeFileSync(path, JSON.stringify(record))
447
+ return true
448
+ } catch {
449
+ return false // unwritable home: the restart row simply never appears
450
+ }
451
+ }
452
+
453
+ // Read the staged install, or null. A record whose tarball is gone (the user
454
+ // cleaned the cache) drains to null — a stale row must not offer a restart that
455
+ // cannot work.
456
+ export function readStagedInstall(fs, path) {
457
+ const f = fs ?? STAGED_FS()
458
+ const file = path ?? stagedInstallPath()
459
+ try {
460
+ if (!f.existsSync(file)) return null
461
+ const record = JSON.parse(f.readFileSync(file, 'utf8'))
462
+ if (!record || typeof record !== 'object') return null
463
+ if (typeof record.pkg !== 'string') return null
464
+ if (record.pkg !== 'dsh' && record.pkg !== 'tui') return null
465
+ if (typeof record.version !== 'string' || record.version === '') return null
466
+ if (typeof record.tarball !== 'string' || record.tarball === '') return null
467
+ if (!f.existsSync(record.tarball)) return null
468
+ return record
469
+ } catch {
470
+ return null
471
+ }
472
+ }
473
+
474
+ export function clearStagedInstall(fs, path) {
475
+ const f = fs ?? STAGED_FS()
476
+ try { f.unlinkSync(path ?? stagedInstallPath()) } catch { /* nothing staged */ }
477
+ }
478
+
479
+ // Versions already downloaded for one package — the rollback cache.
480
+ export function cachedTarballVersions(pkg) {
481
+ const prefix = tarballPrefix(pkg)
482
+ try {
483
+ return new Set(readdirSync(updateCacheDir())
484
+ .filter((name) => name.startsWith(prefix) && name.endsWith('.tgz'))
485
+ .map((name) => name.slice(prefix.length, -'.tgz'.length)))
486
+ } catch {
487
+ return new Set()
488
+ }
489
+ }
490
+
491
+ // ---- registry metadata + streaming download ------------------------------
492
+
493
+ // The tarball URL and integrity hash for one exact version, from the
494
+ // abbreviated registry document (`…/<pkg>/<version>` — a few hundred bytes,
495
+ // unlike the full packument).
496
+ export async function registryTarball(pkg, version) {
497
+ const url = DSH_REGISTRY + '/' + pkg + '/' + encodeURIComponent(version)
498
+ let response
499
+ try {
500
+ // No custom Accept header: the registry answers the plain JSON request
501
+ // with the full version document, and a packument-specific media type
502
+ // earns a 406.
503
+ response = await fetch(url, { signal: AbortSignal.timeout(METADATA_TIMEOUT_MS) })
504
+ } catch (error) {
505
+ throw new Error(t('update.registryUnreachable', { error: error?.message ?? String(error) }))
506
+ }
507
+ if (response.status === 404) throw new Error(t('update.notOnRegistry', { package: pkg + '@' + version }))
508
+ if (!response.ok) throw new Error(t('update.registryHttp', { status: response.status, package: pkg + '@' + version }))
509
+ const doc = await response.json()
510
+ const tarball = doc?.dist?.tarball
511
+ if (typeof tarball !== 'string' || tarball === '') throw new Error(t('update.noTarballUrl'))
512
+ return { tarball, integrity: typeof doc?.dist?.integrity === 'string' ? doc.dist.integrity : null }
513
+ }
514
+
515
+ // Compare a computed sha512 (base64) against a registry `dist.integrity`. An
516
+ // absent or non-sha512 value reports `checked: false` — every npm-published
517
+ // tarball we care about is sha512.
518
+ export function checkIntegrity(sha512Base64, integrity) {
519
+ if (typeof integrity !== 'string' || integrity.trim() === '') return { ok: true, checked: false }
520
+ const m = /^sha512-(.+)$/i.exec(integrity.trim())
521
+ if (!m) return { ok: true, checked: false }
522
+ return { ok: m[1] === sha512Base64, checked: true }
523
+ }
524
+
525
+ // Stream a tarball to disk, reporting progress. `signal` aborts (Esc in the
526
+ // UI); a failed download leaves no partial file behind.
527
+ export async function downloadTarball(url, destPath, options = {}) {
528
+ const { onProgress, signal } = options
529
+ const response = await fetch(url, { signal })
530
+ if (!response.ok) throw new Error(t('update.downloadHttp', { status: response.status, url }))
531
+ const length = Number(response.headers?.get?.('content-length'))
532
+ const total = Number.isFinite(length) && length > 0 ? length : null
533
+ const body = response.body
534
+ if (!body) throw new Error(t('update.downloadEmpty'))
535
+ const chunks = []
536
+ let received = 0
537
+ let lastReport = 0
538
+ const report = (force) => {
539
+ if (typeof onProgress !== 'function') return
540
+ const now = Date.now()
541
+ if (!force && now - lastReport < 100) return
542
+ lastReport = now
543
+ try {
544
+ onProgress({
545
+ received,
546
+ total,
547
+ percent: total === null ? null : Math.max(0, Math.min(100, Math.round((received / total) * 100))),
548
+ })
549
+ } catch { /* a repaint must never kill the download */ }
550
+ }
551
+ const reader = body.getReader()
552
+ for (;;) {
553
+ const { done, value } = await reader.read()
554
+ if (done) break
555
+ const chunk = Buffer.isBuffer(value) ? value : Buffer.from(value.buffer, value.byteOffset, value.byteLength)
556
+ chunks.push(chunk)
557
+ received += chunk.length
558
+ report(false)
559
+ }
560
+ const data = Buffer.concat(chunks)
561
+ report(true)
562
+ mkdirSync(dirname(destPath), { recursive: true })
563
+ writeFileSync(destPath + '.part', data)
564
+ renameSync(destPath + '.part', destPath)
565
+ return { bytes: received, sha512: createHash('sha512').update(data).digest('base64') }
566
+ }
567
+
568
+ // Download one exact version into the cache and record it as staged. A tarball
569
+ // already in the cache is integrity-checked and reused, so a cache hit cannot
570
+ // resurrect a corrupt file — that is what makes a rollback instant.
571
+ export async function stageInstall(input = {}) {
572
+ const { pkg, version, profile, cwd, onProgress, signal } = input
573
+ const packageName = pkg === 'tui' ? TUI_PACKAGE : DSH_PACKAGE
574
+ const cache = tarballCachePath(packageName, version)
575
+ const meta = await registryTarball(packageName, version)
576
+ let bytes = 0
577
+ let cached = false
578
+ if (existsSync(cache)) {
579
+ const data = readFileSync(cache)
580
+ bytes = data.length
581
+ if (checkIntegrity(createHash('sha512').update(data).digest('base64'), meta.integrity).ok) cached = true
582
+ else { try { unlinkSync(cache) } catch { /* re-downloaded below */ } }
583
+ }
584
+ if (!cached) {
585
+ const result = await downloadTarball(meta.tarball, cache, { onProgress, signal })
586
+ bytes = result.bytes
587
+ const check = checkIntegrity(result.sha512, meta.integrity)
588
+ if (!check.ok) {
589
+ try { unlinkSync(cache) } catch { /* nothing else to clean */ }
590
+ throw new Error(t('update.integrityFailed', { file: packageName + '@' + version }))
591
+ }
592
+ } else if (typeof onProgress === 'function') {
593
+ try { onProgress({ received: bytes, total: bytes, percent: 100 }) } catch { /* ignore */ }
594
+ }
595
+ const record = {
596
+ pkg,
597
+ packageName,
598
+ version,
599
+ tarball: cache,
600
+ url: meta.tarball,
601
+ integrity: meta.integrity,
602
+ bytes,
603
+ cached,
604
+ profile: profile ?? 'tui',
605
+ cwd: cwd ?? process.cwd(),
606
+ finishedAt: Date.now(),
607
+ }
608
+ writeStagedInstall(null, stagedInstallPath(), record)
609
+ return record
610
+ }
611
+
612
+ // ---- manifest paths the applier verifies ---------------------------------
613
+
614
+ // The on-disk manifest of the global dsh install, or null when dsh is not on
615
+ // PATH. The applier re-reads it *after* installing: npm's exit code alone is
616
+ // not proof (2026-09-04 hybrid-tree incident).
617
+ export function dshManifestPath() {
618
+ const shim = findOnPath('dsh')
619
+ if (shim === undefined) return null
620
+ try {
621
+ return createRequire(resolve(shim)).resolve(DSH_PACKAGE + '/package.json')
622
+ } catch {
623
+ return null
624
+ }
625
+ }
626
+
627
+ // The installed copy of this plugin inside one profile (a junction into
628
+ // .pnpm — reading the manifest through it is fine).
629
+ export function tuiInstalledManifestPath(profile) {
630
+ const home = process.env.DSH_HOME || join(homedir(), '.dsh')
631
+ return join(home, 'profiles', profile ?? 'tui', 'node_modules', TUI_PACKAGE, 'package.json')
632
+ }
633
+
634
+ // ---- restart plan + applier spawn ----------------------------------------
635
+
636
+ // Marker file recording the outcome of the last restart-applied install, read
637
+ // (and drained) on the next boot to verify what the detached child did.
638
+ export function installMarkerPath() {
639
+ const home = process.env.DSH_HOME || homedir()
640
+ return join(home, 'tui-dsh-install.json')
641
+ }
642
+
643
+ // Plain data describing what the detached applier must do. Pure builder: the
644
+ // tests drive it without touching the filesystem; `spawnApplyUpdater` persists
645
+ // it as a file (restartPlanPath) and hands that file to the applier.
646
+ export function restartPlan(input = {}) {
647
+ return {
648
+ parentPid: Number(input.parentPid ?? process.pid),
649
+ pkg: input.pkg,
650
+ packageName: input.packageName ?? (input.pkg === 'tui' ? TUI_PACKAGE : DSH_PACKAGE),
651
+ version: input.version,
652
+ tarball: input.tarball,
653
+ profile: input.profile ?? 'tui',
654
+ cwd: input.cwd ?? process.cwd(),
655
+ verifyPath: input.verifyPath ?? null,
656
+ marker: input.marker ?? installMarkerPath(),
657
+ npm: input.npm ?? npmCommand() ?? null,
658
+ dsh: input.dsh ?? null,
659
+ dshShim: input.dshShim ?? dshShimPath(),
660
+ dshArgs: input.dshArgs ?? dshProcessArgs(),
661
+ relaunch: input.relaunch ?? null,
662
+ }
663
+ }
664
+
665
+ // The shipped applier script, resolved from this package's root.
666
+ export function applierPath() {
667
+ return join(PACKAGE_ROOT, 'bin', 'apply-update.cjs')
668
+ }
669
+
670
+ // The plan is handed over as a file, not an argv blob: it stays inspectable
671
+ // after the fact (a failed install is much easier to diagnose), and it cannot
672
+ // hit a command-line length limit.
673
+ export function restartPlanPath() {
674
+ return join(updateCacheDir(), 'restart-plan.json')
675
+ }
676
+
677
+ export function writeRestartPlan(fs, path, plan) {
678
+ const f = fs ?? STAGED_FS()
679
+ try {
680
+ if (typeof f.mkdirSync === 'function') f.mkdirSync(dirname(path), { recursive: true })
681
+ f.writeFileSync(path, JSON.stringify(plan))
682
+ return true
683
+ } catch {
684
+ return false
685
+ }
686
+ }
687
+
688
+ // Spawn spec for the applier: `node bin/apply-update.cjs <plan.json>`.
689
+ // Detached so it outlives this process, stdio inherited so the install runs in
690
+ // the user's own terminal and the relaunched TUI reopens there.
691
+ export function restartSpec(plan, planPath) {
692
+ return {
693
+ command: process.execPath,
694
+ args: [applierPath(), planPath ?? restartPlanPath()],
695
+ options: { detached: true, stdio: 'inherit', windowsHide: false },
696
+ }
697
+ }
698
+
699
+ // Spawn the applier and let it go. Returns false when it cannot be spawned (or
700
+ // the script is missing) so the caller can report instead of exiting quietly.
701
+ export function spawnApplyUpdater(plan, planPath) {
702
+ const file = planPath ?? restartPlanPath()
703
+ if (!existsSync(applierPath())) return false
704
+ if (!writeRestartPlan(null, file, plan)) return false
705
+ const spec = restartSpec(plan, file)
706
+ try {
707
+ const child = spawn(spec.command, spec.args, spec.options)
708
+ child.unref()
709
+ return true
710
+ } catch {
711
+ return false
712
+ }
713
+ }
714
+
715
+ // fs injectable for tests (existsSync / readFileSync / writeFileSync /
716
+ // unlinkSync; default: node fs).
717
+ const MARKER_FS = () => ({ existsSync, readFileSync, writeFileSync, unlinkSync })
718
+
719
+ // Record the outcome of the last dsh install attempt.
720
+ export function writeInstallMarker(fs, path, record) {
721
+ const f = fs ?? MARKER_FS()
722
+ try {
723
+ f.writeFileSync(path, JSON.stringify({
724
+ requested: record?.requested,
725
+ // The marker is shared by both packages; 'dsh' is the default so a marker
726
+ // written by an older build still routes somewhere sane.
727
+ pkg: record?.pkg === 'tui' ? 'tui' : 'dsh',
728
+ code: record?.code,
729
+ finishedAt: Date.now(),
730
+ }))
731
+ } catch {
732
+ // Unwritable home: the next boot simply has nothing to verify.
733
+ }
734
+ }
735
+
736
+ // Read and drain the marker: returns { requested, code, finishedAt } or null.
737
+ // Missing and malformed markers both drain to null — a bad file must never
738
+ // wedge the Update page.
739
+ export function readInstallMarker(fs, path) {
740
+ const f = fs ?? MARKER_FS()
741
+ const file = path ?? installMarkerPath()
742
+ if (!f.existsSync(file)) return null
743
+ let text
744
+ try { text = f.readFileSync(file, 'utf8') } catch { return null }
745
+ try { f.unlinkSync(file) } catch { /* next write recreates it */ }
746
+ try {
747
+ const record = JSON.parse(text)
748
+ if (record && typeof record === 'object' && typeof record.requested === 'string' && Number.isInteger(record.code)) {
749
+ return {
750
+ requested: record.requested,
751
+ code: record.code,
752
+ finishedAt: record.finishedAt ?? 0,
753
+ // 'dsh' unless the applier said otherwise: the marker is shared by both
754
+ // packages, and the next boot must check the right one on disk.
755
+ pkg: record.pkg === 'tui' ? 'tui' : 'dsh',
756
+ }
757
+ }
758
+ } catch { /* malformed marker */ }
759
+ return null
760
+ }
761
+
762
+ // Evaluate a drained marker against the version live on disk. Returns the
763
+ // same shapes as installResultFrom: 'installed' means the deferred install
764
+ // landed, 'corrupt' means exit 0 with the wrong version on disk (silent
765
+ // hybrid tree), 'failed' means npm itself failed.
766
+ export function deferredInstallOutcome(marker, installedVersion, repair) {
767
+ if (!marker) return null
768
+ return installResultFrom({ code: marker.code, stderr: '' }, { version: installedVersion }, marker.requested, repair)
769
+ }
770
+
771
+ // ---- local install detection ---------------------------------------------
772
+
773
+ // Read the active profile's package.json and report whether dsh-oc-tui is
774
+ // installed from a local path / file: reference (which `plugin add` will switch
775
+ // to a registry version).
776
+ export function tuiInstallIsLocal(profile) {
777
+ try {
778
+ const home = process.env.DSH_HOME || homedir()
779
+ const manifest = JSON.parse(readFileSync(join(home, 'profiles', profile, 'package.json'), 'utf8'))
780
+ const dep = manifest?.dependencies?.[TUI_PACKAGE] ?? manifest?.devDependencies?.[TUI_PACKAGE]
781
+ if (typeof dep !== 'string' || dep === '') return false
782
+ return dep.startsWith('file:') || dep.startsWith('link:') || dep.startsWith('.')
783
+ || dep.startsWith('/') || /^[A-Za-z]:/.test(dep)
784
+ } catch {
785
+ return false
786
+ }
787
+ }
788
+
789
+ // The version of this running dsh-oc-tui package (its own package.json).
790
+ export function tuiInstalledVersion() {
791
+ return TUI_MANIFEST.version
792
+ }
793
+
794
+ // The dsh install on PATH: version + JS bin entry, or `{ found: false }`.
795
+ // Millisecond-scale — no spawn.
796
+ export function detectDshInstall() {
797
+ const dshExecutable = findOnPath('dsh')
798
+ if (dshExecutable === undefined) return { found: false }
799
+ try {
800
+ const packagePath = createRequire(resolve(dshExecutable)).resolve(`${DSH_PACKAGE}/package.json`)
801
+ const manifest = JSON.parse(readFileSync(packagePath, 'utf8'))
802
+ return { found: true, version: manifest.version ?? null, entry: resolveDshEntry(dshExecutable) }
803
+ } catch {
804
+ return { found: false }
805
+ }
806
+ }
807
+
808
+ function safeRealpath(realpath, path) {
809
+ try { return realpath(path) } catch { return path }
810
+ }
811
+
812
+ // Which profile is this TUI booted under? Priority:
813
+ // 1. DSH_TUI_BOOT_PROFILE (injected by the launcher);
814
+ // 2. the profile whose node_modules/dsh-oc-tui realpaths to this package root
815
+ // (survives pnpm symlinks);
816
+ // 3. the default profile name 'tui'.
817
+ // `fs` is injectable for tests (readdirSync / realpathSync / env / homedir).
818
+ export function resolveActiveProfile(fs = {}) {
819
+ const env = fs.env ?? process.env
820
+ if (env.DSH_TUI_BOOT_PROFILE) return env.DSH_TUI_BOOT_PROFILE
821
+ const readdir = fs.readdirSync ?? readdirSync
822
+ const realpath = fs.realpathSync ?? realpathSync
823
+ const homeFn = fs.homedir ?? homedir
824
+ const home = env.DSH_HOME || homeFn()
825
+ const profilesDir = join(home, 'profiles')
826
+ const selfRoot = safeRealpath(realpath, PACKAGE_ROOT)
827
+ let entries
828
+ try {
829
+ entries = readdir(profilesDir, { withFileTypes: true })
830
+ } catch {
831
+ return 'tui'
832
+ }
833
+ for (const entry of entries ?? []) {
834
+ if (!entry || typeof entry.isDirectory !== 'function' || !entry.isDirectory()) continue
835
+ const candidate = join(profilesDir, entry.name, 'node_modules', TUI_PACKAGE)
836
+ if (safeRealpath(realpath, candidate) === selfRoot) return entry.name
837
+ }
838
+ return 'tui'
839
+ }
840
+
841
+ // ---- item builders (pure) ------------------------------------------------
842
+
843
+ function infoRow(label, value, extra = {}) {
844
+ return { kind: 'update-info', label, value, disabled: true, ...extra }
845
+ }
846
+
847
+ function statusText(status, error, installed, corrupt, note) {
848
+ if (corrupt) return t('update.statusCorrupt')
849
+ if (note) return note
850
+ if (!installed && !status && !error) return '—'
851
+ if (error) return t('update.statusError', { error })
852
+ if (!status) return '—'
853
+ if (status.kind === 'available') return t('update.statusAvailable', { version: status.target })
854
+ if (status.kind === 'up-to-date') return t('update.statusUpToDate')
855
+ return t('update.statusNoStable')
856
+ }
857
+
858
+ // Build the Update page's item rows from a state snapshot (see
859
+ // `loadUpdateView` for the shape). Pure so the smoke tests can drive it.
860
+ export function buildUpdateItems(state) {
861
+ const items = []
862
+ const pushBlock = (pkg, label, section) => {
863
+ items.push({ kind: 'header', label, value: '', disabled: true })
864
+ const installed = section.installed
865
+ const registry = section.registry
866
+ const status = installed && registry ? updateStatus(installed, registry) : null
867
+ items.push(infoRow(t('update.installed'), installed ?? (section.found ? t('common.unknown') : t('update.notOnPath'))))
868
+ items.push(infoRow(t('update.latest'), registry?.distTags?.latest ?? (section.error ? t('common.unavailable') : '—')))
869
+ items.push(infoRow(t('update.status'), statusText(status, section.error, installed, section.corrupt === true, section.note),
870
+ section.corrupt === true ? { tone: 'error', pkg } : status?.kind === 'available' || section.note ? { tone: 'warning', pkg } : { pkg }))
871
+ // A downloaded-but-unapplied install waits here: one Enter restarts and
872
+ // applies it, the second row drops the staged tarball again.
873
+ const staged = state.staged && state.staged.pkg === pkg ? state.staged : null
874
+ if (staged) {
875
+ items.push({
876
+ kind: 'update-restart',
877
+ label: t('update.restartApply', { version: staged.version }),
878
+ value: t('update.enterRestart'),
879
+ pkg,
880
+ staged,
881
+ tone: 'warning',
882
+ disabled: false,
883
+ })
884
+ items.push({ kind: 'update-discard', label: t('update.discard', { version: staged.version }), value: 'Enter', pkg, staged, disabled: false })
885
+ }
886
+ items.push({ kind: 'update-versions', label: t('update.versions'), value: t('update.selectVersion'), pkg, disabled: false })
887
+ }
888
+ items.push(infoRow(t('update.profile'), state.profile))
889
+ pushBlock('dsh', t('update.dshPackage'), state.dsh)
890
+ pushBlock('tui', 'dsh-oc-tui', state.tui)
891
+ items.push({ kind: 'header', label: t('update.actions'), value: '', disabled: true })
892
+ items.push({ kind: 'update-check', label: t('update.checkNow'), value: state.checking ? t('update.checkingShort') : 'Enter', disabled: state.busy === true })
893
+ const startupCheck = state.startupCheck ?? 'on'
894
+ items.push({
895
+ kind: 'choice',
896
+ ns: state.startupCheckNs ?? 'tui-updates',
897
+ field: state.startupCheckField ?? 'startupCheck',
898
+ label: t('update.startupCheck'),
899
+ value: startupCheck,
900
+ // The stored id is what gets committed; the row shows its catalog label
901
+ // (the same valueLabel convention lib/web-settings.js uses for choice rows).
902
+ valueLabel: t(startupCheck === 'off' ? 'value.off' : 'value.on'),
903
+ options: valueChoices(['on', 'off']),
904
+ revision: state.startupCheckRevision ?? 0,
905
+ disabled: state.startupCheck === null || state.settingsWritable === false,
906
+ })
907
+ return items
908
+ }
909
+
910
+ // Build the version picker rows for one package, newest first, with the
911
+ // dist-tags and the installed marker attached for the renderer to color.
912
+ // `options.cached` (a Set or a predicate) marks versions whose tarball is
913
+ // already on disk — a rollback to one of them needs no download; `staged`
914
+ // marks the version waiting to be applied on the next restart.
915
+ export function buildVersionItems(registry, installed, options = {}) {
916
+ const isCached = typeof options.cached === 'function'
917
+ ? options.cached
918
+ : (options.cached instanceof Set ? (version) => options.cached.has(version) : () => false)
919
+ const versions = Array.isArray(registry?.versions) ? registry.versions.slice() : []
920
+ const distTags = registry?.distTags && typeof registry.distTags === 'object' ? registry.distTags : {}
921
+ const tagsByVersion = new Map()
922
+ for (const [tag, version] of Object.entries(distTags)) {
923
+ if (typeof version !== 'string' || version === '') continue
924
+ if (!tagsByVersion.has(version)) tagsByVersion.set(version, [])
925
+ tagsByVersion.get(version).push(tag)
926
+ }
927
+ versions.sort((a, b) => compareVersions(b, a))
928
+ const stagedVersion = typeof options.staged === 'string' ? options.staged : null
929
+ return versions.map((version) => {
930
+ const tags = [...(tagsByVersion.get(version) ?? [])]
931
+ if (isCached(version)) tags.push(t('update.tagCached'))
932
+ if (version === stagedVersion) tags.push(t('update.tagStaged'))
933
+ return {
934
+ kind: 'update-version',
935
+ label: version,
936
+ value: '',
937
+ version,
938
+ tags,
939
+ installed: version === installed,
940
+ cached: isCached(version),
941
+ staged: version === stagedVersion,
942
+ disabled: false,
943
+ }
944
+ })
945
+ }
946
+
947
+ // ---- the Update settings loader ------------------------------------------
948
+
949
+ export async function loadUpdateView(ctx) {
950
+ const settings = ctx.get('settings')
951
+ let startupCheck = 'on'
952
+ let startupCheckRevision = 0
953
+ let startupCheckNs = 'tui-updates'
954
+ let startupCheckField = 'startupCheck'
955
+ if (settings) {
956
+ try {
957
+ // Same two-generation resolution the Main tab uses: a 0.1.x provider
958
+ // stores this in the `tui-updates` namespace, a 0.2.0 host in the
959
+ // plugin's own Config, and the row has to write back where it read.
960
+ const descriptors = new Map(settings.describe({ redactSecrets: true }).map((entry) => [String(entry.ns), entry]))
961
+ const target = resolveTuiSetting(ctx, descriptors, 'tui-updates', 'startupCheck')
962
+ if (target) {
963
+ startupCheck = target.value ?? 'on'
964
+ startupCheckRevision = target.descriptor.revision ?? 0
965
+ startupCheckNs = target.ns
966
+ startupCheckField = target.field
967
+ }
968
+ } catch { /* settings unavailable; keep the default */ }
969
+ }
970
+ const state = {
971
+ profile: resolveActiveProfile(),
972
+ dsh: { found: false, installed: null, entry: undefined, registry: null, error: null },
973
+ tui: { installed: tuiInstalledVersion(), registry: null, error: null },
974
+ // A tarball downloaded but not applied yet (this run or a previous one).
975
+ staged: null,
976
+ startupCheck: settings ? startupCheck : null,
977
+ startupCheckRevision,
978
+ startupCheckNs,
979
+ startupCheckField,
980
+ settingsWritable: settings?.writable !== false,
981
+ checking: false,
982
+ busy: false,
983
+ }
984
+ const dshInstall = detectDshInstall()
985
+ state.dsh.found = dshInstall.found
986
+ state.dsh.installed = dshInstall.version ?? null
987
+ // On every Update-page load: consume the install marker the applier left
988
+ // behind and, when the TUI boots fine but the manifest mismatches its own
989
+ // files, surface the hybrid-tree state from the 2026-09-04 incident so the
990
+ // user is pointed at a reinstall. The marker says which package it belongs
991
+ // to, so a TUI install is checked against the profile, not against dsh.
992
+ const marker = readInstallMarker()
993
+ if (marker) {
994
+ const section = marker.pkg === 'tui' ? state.tui : state.dsh
995
+ const installed = marker.pkg === 'tui' ? state.tui.installed ?? undefined : dshInstall.version ?? undefined
996
+ const outcome = deferredInstallOutcome(marker, installed,
997
+ marker.pkg === 'tui' ? t('update.installFailedRetry') : undefined)
998
+ if (outcome?.kind === 'failed') {
999
+ section.note = t('update.installFailed', { code: marker.code })
1000
+ } else if (outcome?.kind === 'corrupt') {
1001
+ section.corrupt = true
1002
+ section.note = outcome.reason
1003
+ }
1004
+ // 'installed' needs no note — the Installed row already shows the version.
1005
+ }
1006
+ state.dsh.entry = dshInstall.entry
1007
+ state.staged = readStagedInstall()
1008
+ const [dshResult, tuiResult] = await Promise.all([
1009
+ registryInfo(DSH_PACKAGE).then((registry) => ({ registry })).catch((error) => ({ error: error?.message ?? String(error) })),
1010
+ registryInfo(TUI_PACKAGE).then((registry) => ({ registry })).catch((error) => ({ error: error?.message ?? String(error) })),
1011
+ ])
1012
+ state.dsh.registry = dshResult.registry ?? null
1013
+ state.dsh.error = dshResult.error ?? null
1014
+ state.tui.registry = tuiResult.registry ?? null
1015
+ state.tui.error = tuiResult.error ?? null
1016
+
1017
+ return {
1018
+ settings,
1019
+ items: buildUpdateItems(state),
1020
+ title: t('update.title'),
1021
+ subtitle: state.staged
1022
+ ? t('update.subtitleStaged', { package: state.staged.packageName, version: state.staged.version })
1023
+ : t('update.subtitleIdle'),
1024
+ menu: SETTINGS_MENU,
1025
+ menuIndex: Math.max(0, SETTINGS_MENU.findIndex((entry) => entry.id === 'update')),
1026
+ state,
1027
+ }
1028
+ }