dsh-app-controls 0.0.0-stage → 0.5.2
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/LICENSE +21 -0
- package/README.md +249 -2
- package/cordis.patch.yml +4 -0
- package/icon.svg +6 -0
- package/lib/cache.js +491 -0
- package/lib/client.js +1476 -0
- package/lib/index.js +647 -0
- package/lib/settings.js +186 -0
- package/lib/update.js +518 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +69 -4
- package/tray/dsh-tray.py +975 -0
package/lib/settings.js
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Persistent settings for dsh-app-controls.
|
|
3
|
+
*
|
|
4
|
+
* The Web settings panel, the launcher and the tray helper share one JSON file
|
|
5
|
+
* under the XDG state directory so a setting saved in the UI is effective on
|
|
6
|
+
* the next DSH start/launch without editing the profile patch.
|
|
7
|
+
*/
|
|
8
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
|
|
9
|
+
import { spawn } from 'node:child_process'
|
|
10
|
+
import os from 'node:os'
|
|
11
|
+
import path from 'node:path'
|
|
12
|
+
import { fileURLToPath } from 'node:url'
|
|
13
|
+
|
|
14
|
+
export const STATE_DIR = path.join(
|
|
15
|
+
process.env.XDG_STATE_HOME ?? path.join(os.homedir(), '.local', 'state'),
|
|
16
|
+
'dsh-app-controls',
|
|
17
|
+
)
|
|
18
|
+
export const SETTINGS_FILE = path.join(STATE_DIR, 'settings.json')
|
|
19
|
+
export const TRAY_PID_FILE = path.join(STATE_DIR, 'tray.pid')
|
|
20
|
+
export const AUTOSTART_FILE = path.join(os.homedir(), '.config', 'autostart', 'dsh-tray.desktop')
|
|
21
|
+
export const PACKAGE_DIR = path.dirname(path.dirname(fileURLToPath(import.meta.url)))
|
|
22
|
+
const TRAY_SCRIPT = path.join(PACKAGE_DIR, 'tray', 'dsh-tray.py')
|
|
23
|
+
const ICON_FILE = path.join(PACKAGE_DIR, 'icon.svg')
|
|
24
|
+
const TRAY_DISABLED = process.env.DSH_APP_CONTROLS_DISABLE_TRAY === '1'
|
|
25
|
+
const PYTHON = process.env.DSH_TRAY_PYTHON ?? '/usr/bin/python3'
|
|
26
|
+
|
|
27
|
+
export const DEFAULT_SETTINGS = {
|
|
28
|
+
version: 1,
|
|
29
|
+
trayEnabled: true,
|
|
30
|
+
features: {
|
|
31
|
+
updateButton: true,
|
|
32
|
+
quitButton: true,
|
|
33
|
+
headerControls: true,
|
|
34
|
+
mainOverlay: true,
|
|
35
|
+
},
|
|
36
|
+
window: {
|
|
37
|
+
width: 1400,
|
|
38
|
+
height: 900,
|
|
39
|
+
},
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function asBoolean(value, fallback) {
|
|
43
|
+
return typeof value === 'boolean' ? value : fallback
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function asSize(value) {
|
|
47
|
+
const number = typeof value === 'number' ? value : Number(value)
|
|
48
|
+
if (!Number.isFinite(number) || number <= 0) return 0
|
|
49
|
+
return Math.min(10000, Math.max(600, Math.round(number)))
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Accept partial user input and return a complete, validated settings object. */
|
|
53
|
+
export function normalizeSettings(input) {
|
|
54
|
+
const source = input !== null && typeof input === 'object' ? input : {}
|
|
55
|
+
const features = source.features !== null && typeof source.features === 'object' ? source.features : {}
|
|
56
|
+
const window = source.window !== null && typeof source.window === 'object' ? source.window : {}
|
|
57
|
+
let width = asSize(window.width)
|
|
58
|
+
let height = asSize(window.height)
|
|
59
|
+
if (width === 0 || height === 0) {
|
|
60
|
+
width = 0
|
|
61
|
+
height = 0
|
|
62
|
+
}
|
|
63
|
+
return {
|
|
64
|
+
version: 1,
|
|
65
|
+
trayEnabled: asBoolean(source.trayEnabled, DEFAULT_SETTINGS.trayEnabled),
|
|
66
|
+
features: {
|
|
67
|
+
updateButton: asBoolean(features.updateButton, DEFAULT_SETTINGS.features.updateButton),
|
|
68
|
+
quitButton: asBoolean(features.quitButton, DEFAULT_SETTINGS.features.quitButton),
|
|
69
|
+
headerControls: asBoolean(features.headerControls, DEFAULT_SETTINGS.features.headerControls),
|
|
70
|
+
mainOverlay: asBoolean(features.mainOverlay, DEFAULT_SETTINGS.features.mainOverlay),
|
|
71
|
+
},
|
|
72
|
+
window: { width, height },
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function readSettings() {
|
|
77
|
+
try {
|
|
78
|
+
const parsed = JSON.parse(readFileSync(SETTINGS_FILE, 'utf8'))
|
|
79
|
+
return normalizeSettings(parsed)
|
|
80
|
+
} catch {
|
|
81
|
+
return normalizeSettings(DEFAULT_SETTINGS)
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function writeSettings(settings) {
|
|
86
|
+
const normalized = normalizeSettings(settings)
|
|
87
|
+
mkdirSync(STATE_DIR, { recursive: true, mode: 0o700 })
|
|
88
|
+
chmodSync(STATE_DIR, 0o700)
|
|
89
|
+
const temporary = `${SETTINGS_FILE}.${process.pid}.tmp`
|
|
90
|
+
writeFileSync(temporary, `${JSON.stringify(normalized, null, 2)}\n`, { mode: 0o600 })
|
|
91
|
+
renameSync(temporary, SETTINGS_FILE)
|
|
92
|
+
try {
|
|
93
|
+
chmodSync(SETTINGS_FILE, 0o600)
|
|
94
|
+
} catch {
|
|
95
|
+
// best effort
|
|
96
|
+
}
|
|
97
|
+
return normalized
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function readTrayPid() {
|
|
101
|
+
try {
|
|
102
|
+
const pid = Number(readFileSync(TRAY_PID_FILE, 'utf8').trim())
|
|
103
|
+
return Number.isInteger(pid) && pid > 0 ? pid : undefined
|
|
104
|
+
} catch {
|
|
105
|
+
return undefined
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function pidIsAlive(pid) {
|
|
110
|
+
if (pid === undefined) return false
|
|
111
|
+
try {
|
|
112
|
+
process.kill(pid, 0)
|
|
113
|
+
return true
|
|
114
|
+
} catch {
|
|
115
|
+
return false
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function autostartContent() {
|
|
120
|
+
return (
|
|
121
|
+
'[Desktop Entry]\n'
|
|
122
|
+
+ 'Type=Application\n'
|
|
123
|
+
+ 'Name=DeepSeek Harness Tray\n'
|
|
124
|
+
+ 'Comment=DeepSeek Harness status and controls in the system tray\n'
|
|
125
|
+
+ `Exec=${PYTHON} "${TRAY_SCRIPT}"\n`
|
|
126
|
+
+ `Icon=${ICON_FILE}\n`
|
|
127
|
+
+ 'Terminal=false\n'
|
|
128
|
+
+ 'X-KDE-autostart-after=panel\n'
|
|
129
|
+
+ 'OnlyShowIn=KDE;\n'
|
|
130
|
+
)
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function enableTray(log) {
|
|
134
|
+
try {
|
|
135
|
+
mkdirSync(path.dirname(AUTOSTART_FILE), { recursive: true })
|
|
136
|
+
writeFileSync(AUTOSTART_FILE, autostartContent(), { mode: 0o644 })
|
|
137
|
+
} catch (error) {
|
|
138
|
+
log('failed to write tray autostart entry', error)
|
|
139
|
+
}
|
|
140
|
+
const pid = readTrayPid()
|
|
141
|
+
if (pidIsAlive(pid)) return
|
|
142
|
+
if (!existsSync(TRAY_SCRIPT)) {
|
|
143
|
+
log('tray script is missing', TRAY_SCRIPT)
|
|
144
|
+
return
|
|
145
|
+
}
|
|
146
|
+
try {
|
|
147
|
+
const child = spawn(PYTHON, [TRAY_SCRIPT], {
|
|
148
|
+
detached: true,
|
|
149
|
+
stdio: 'ignore',
|
|
150
|
+
env: process.env,
|
|
151
|
+
})
|
|
152
|
+
child.unref()
|
|
153
|
+
log('tray started')
|
|
154
|
+
} catch (error) {
|
|
155
|
+
log('failed to start tray', error)
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function disableTray(log) {
|
|
160
|
+
try {
|
|
161
|
+
rmSync(AUTOSTART_FILE, { force: true })
|
|
162
|
+
} catch (error) {
|
|
163
|
+
log('failed to remove tray autostart entry', error)
|
|
164
|
+
}
|
|
165
|
+
const pid = readTrayPid()
|
|
166
|
+
if (pidIsAlive(pid)) {
|
|
167
|
+
try {
|
|
168
|
+
process.kill(pid, 'SIGTERM')
|
|
169
|
+
log('tray stopped')
|
|
170
|
+
} catch (error) {
|
|
171
|
+
log('failed to stop tray', error)
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
try {
|
|
175
|
+
rmSync(TRAY_PID_FILE, { force: true })
|
|
176
|
+
} catch {
|
|
177
|
+
// best effort
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** Apply tray enable/disable and the login autostart entry from settings. */
|
|
182
|
+
export function applyTraySettings(settings, log = () => {}) {
|
|
183
|
+
if (TRAY_DISABLED) return
|
|
184
|
+
if (settings.trayEnabled) enableTray(log)
|
|
185
|
+
else disableTray(log)
|
|
186
|
+
}
|
package/lib/update.js
ADDED
|
@@ -0,0 +1,518 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Version check and update helpers for the DeepSeek Harness Web GUI buttons.
|
|
3
|
+
*
|
|
4
|
+
* This module intentionally has no DeepSeek Harness imports: it only uses
|
|
5
|
+
* Node.js builtins and the global fetch/Response/AbortSignal APIs, so it can
|
|
6
|
+
* be unit-tested with plain `node`. The host plugin (./index.js) wires it to
|
|
7
|
+
* authenticated `/api` routes.
|
|
8
|
+
*
|
|
9
|
+
* Update semantics follow npm: the running installation is located from
|
|
10
|
+
* `process.argv[1]` (the `dsh` bin), and the candidate is the newest published
|
|
11
|
+
* version that satisfies the dependency spec recorded by that installation.
|
|
12
|
+
* The update itself is an `npm install` into the installation root, i.e. the
|
|
13
|
+
* npx cache directory for `npx @deepseek-ai/dsh` installations.
|
|
14
|
+
*/
|
|
15
|
+
import { spawn } from 'node:child_process'
|
|
16
|
+
import fs from 'node:fs'
|
|
17
|
+
import os from 'node:os'
|
|
18
|
+
import path from 'node:path'
|
|
19
|
+
|
|
20
|
+
export const PACKAGE_NAME = '@deepseek-ai/dsh'
|
|
21
|
+
|
|
22
|
+
const REGISTRY = 'https://registry.npmjs.org'
|
|
23
|
+
const VIEW_TIMEOUT_MS = 60_000
|
|
24
|
+
const INSTALL_TIMEOUT_MS = 900_000
|
|
25
|
+
const OUTPUT_LIMIT = 200_000
|
|
26
|
+
const SEMVER = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/
|
|
27
|
+
const STATE_DIR = path.join(
|
|
28
|
+
process.env.XDG_STATE_HOME ?? path.join(os.homedir(), '.local', 'state'),
|
|
29
|
+
'dsh-app-controls',
|
|
30
|
+
)
|
|
31
|
+
const TIMING_FILE = path.join(STATE_DIR, 'update-timing.json')
|
|
32
|
+
const DEFAULT_INSTALL_MS = 5 * 60 * 1000
|
|
33
|
+
const MIN_EXPECTED_MS = 20 * 1000
|
|
34
|
+
const MAX_EXPECTED_MS = 30 * 60 * 1000
|
|
35
|
+
const ANSI = /\u001b\[[0-9;]*m/gu
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Locate the running DSH installation.
|
|
39
|
+
*
|
|
40
|
+
* @param {string} [argv1] - launcher script path; defaults to `process.argv[1]`.
|
|
41
|
+
* @returns {{ root: string, packageDir: string, version: string, range: string | undefined }}
|
|
42
|
+
* `root` is the npm project that dependencies live under (the npx cache
|
|
43
|
+
* directory for npx installs), `packageDir` the `@deepseek-ai/dsh` package.
|
|
44
|
+
*/
|
|
45
|
+
export function locateInstall(argv1 = process.argv[1]) {
|
|
46
|
+
if (!argv1) throw new Error('无法定位 DSH 安装:process.argv[1] 为空')
|
|
47
|
+
const realBin = fs.realpathSync(argv1)
|
|
48
|
+
const packageDir = path.resolve(path.dirname(realBin), '..')
|
|
49
|
+
const installed = JSON.parse(fs.readFileSync(path.join(packageDir, 'package.json'), 'utf8'))
|
|
50
|
+
const root = path.dirname(path.dirname(path.dirname(packageDir)))
|
|
51
|
+
let range
|
|
52
|
+
try {
|
|
53
|
+
const rootPackage = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'))
|
|
54
|
+
const spec = rootPackage?.dependencies?.[PACKAGE_NAME]
|
|
55
|
+
if (typeof spec === 'string') range = spec
|
|
56
|
+
} catch {
|
|
57
|
+
// The root may be a global prefix or a read-only location; the version
|
|
58
|
+
// check falls back to the `latest` dist-tag in that case.
|
|
59
|
+
}
|
|
60
|
+
return { root, packageDir, version: String(installed.version), range }
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function parseVersion(value) {
|
|
64
|
+
const match = SEMVER.exec(String(value).trim())
|
|
65
|
+
if (match === null) return undefined
|
|
66
|
+
return {
|
|
67
|
+
major: Number(match[1]),
|
|
68
|
+
minor: Number(match[2]),
|
|
69
|
+
patch: Number(match[3]),
|
|
70
|
+
prerelease: match[4] === undefined ? [] : match[4].split('.'),
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function comparePrerelease(left, right) {
|
|
75
|
+
const length = Math.min(left.length, right.length)
|
|
76
|
+
for (let index = 0; index < length; index += 1) {
|
|
77
|
+
const a = left[index]
|
|
78
|
+
const b = right[index]
|
|
79
|
+
const aNumeric = /^\d+$/.test(a)
|
|
80
|
+
const bNumeric = /^\d+$/.test(b)
|
|
81
|
+
if (aNumeric && bNumeric) {
|
|
82
|
+
const numericA = Number(a)
|
|
83
|
+
const numericB = Number(b)
|
|
84
|
+
if (numericA !== numericB) return numericA < numericB ? -1 : 1
|
|
85
|
+
continue
|
|
86
|
+
}
|
|
87
|
+
if (aNumeric !== bNumeric) return aNumeric ? -1 : 1
|
|
88
|
+
if (a !== b) return a < b ? -1 : 1
|
|
89
|
+
}
|
|
90
|
+
if (left.length === right.length) return 0
|
|
91
|
+
return left.length < right.length ? -1 : 1
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Compare two semantic versions.
|
|
96
|
+
*
|
|
97
|
+
* @param {string} left - version A.
|
|
98
|
+
* @param {string} right - version B.
|
|
99
|
+
* @returns {-1 | 0 | 1} negative when A is older, 0 when equal, positive when newer.
|
|
100
|
+
*/
|
|
101
|
+
export function compareVersions(left, right) {
|
|
102
|
+
const a = parseVersion(left)
|
|
103
|
+
const b = parseVersion(right)
|
|
104
|
+
if (a === undefined || b === undefined) throw new Error(`无法解析版本号:${a === undefined ? left : right}`)
|
|
105
|
+
if (a.major !== b.major) return a.major < b.major ? -1 : 1
|
|
106
|
+
if (a.minor !== b.minor) return a.minor < b.minor ? -1 : 1
|
|
107
|
+
if (a.patch !== b.patch) return a.patch < b.patch ? -1 : 1
|
|
108
|
+
if (a.prerelease.length === 0 && b.prerelease.length === 0) return 0
|
|
109
|
+
if (a.prerelease.length === 0) return 1
|
|
110
|
+
if (b.prerelease.length === 0) return -1
|
|
111
|
+
return comparePrerelease(a.prerelease, b.prerelease)
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function findNpmCli() {
|
|
115
|
+
const candidates = []
|
|
116
|
+
if (process.env.npm_execpath) candidates.push(process.env.npm_execpath)
|
|
117
|
+
candidates.push(path.join(path.dirname(process.execPath), 'npm'))
|
|
118
|
+
for (const dir of String(process.env.PATH ?? '').split(path.delimiter)) {
|
|
119
|
+
if (dir) candidates.push(path.join(dir, 'npm'))
|
|
120
|
+
}
|
|
121
|
+
for (const candidate of candidates) {
|
|
122
|
+
try {
|
|
123
|
+
const real = fs.realpathSync(candidate)
|
|
124
|
+
if (fs.statSync(real).isFile()) return real
|
|
125
|
+
} catch {
|
|
126
|
+
// try the next candidate
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
return undefined
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Run the npm CLI in a child process, collecting bounded output.
|
|
134
|
+
*
|
|
135
|
+
* @param {string[]} args - npm arguments.
|
|
136
|
+
* @param {{ timeoutMs?: number, onLine?: (line: string) => void }} [options]
|
|
137
|
+
* timeout override, plus an optional complete-line callback (used to show the
|
|
138
|
+
* last npm activity in the update progress dialog).
|
|
139
|
+
* @returns {Promise<{ ok: boolean, code: number | null, timedOut: boolean, stdout: string, stderr: string }>}
|
|
140
|
+
*/
|
|
141
|
+
export function runNpm(args, options = {}) {
|
|
142
|
+
const timeoutMs = options.timeoutMs ?? VIEW_TIMEOUT_MS
|
|
143
|
+
const onLine = typeof options.onLine === 'function' ? options.onLine : undefined
|
|
144
|
+
return new Promise((resolve) => {
|
|
145
|
+
const cli = findNpmCli()
|
|
146
|
+
if (cli === undefined) {
|
|
147
|
+
resolve({ ok: false, code: null, timedOut: false, stdout: '', stderr: '找不到 npm 可执行文件' })
|
|
148
|
+
return
|
|
149
|
+
}
|
|
150
|
+
let child
|
|
151
|
+
try {
|
|
152
|
+
child = spawn(process.execPath, [cli, ...args], {
|
|
153
|
+
env: { ...process.env, npm_config_update_notifier: 'false', NO_UPDATE_NOTIFIER: '1' },
|
|
154
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
155
|
+
windowsHide: true,
|
|
156
|
+
})
|
|
157
|
+
} catch (error) {
|
|
158
|
+
resolve({ ok: false, code: null, timedOut: false, stdout: '', stderr: String(error) })
|
|
159
|
+
return
|
|
160
|
+
}
|
|
161
|
+
let stdout = ''
|
|
162
|
+
let stderr = ''
|
|
163
|
+
let timedOut = false
|
|
164
|
+
let settled = false
|
|
165
|
+
const buffers = { stdout: '', stderr: '' }
|
|
166
|
+
const feedLines = (stream, text) => {
|
|
167
|
+
if (onLine === undefined) return
|
|
168
|
+
buffers[stream] += text
|
|
169
|
+
if (buffers[stream].length > 4096) buffers[stream] = buffers[stream].slice(-2048)
|
|
170
|
+
let index = buffers[stream].indexOf('\n')
|
|
171
|
+
while (index >= 0) {
|
|
172
|
+
const line = buffers[stream].slice(0, index).replace(ANSI, '').trim()
|
|
173
|
+
buffers[stream] = buffers[stream].slice(index + 1)
|
|
174
|
+
if (line !== '') {
|
|
175
|
+
try {
|
|
176
|
+
onLine(line)
|
|
177
|
+
} catch {
|
|
178
|
+
// progress reporting must never break the install
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
index = buffers[stream].indexOf('\n')
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
const finish = (result) => {
|
|
185
|
+
if (settled) return
|
|
186
|
+
settled = true
|
|
187
|
+
clearTimeout(timer)
|
|
188
|
+
resolve(result)
|
|
189
|
+
}
|
|
190
|
+
child.stdout?.on('data', (chunk) => {
|
|
191
|
+
const text = chunk.toString('utf8')
|
|
192
|
+
if (stdout.length < OUTPUT_LIMIT) stdout += text
|
|
193
|
+
feedLines('stdout', text)
|
|
194
|
+
})
|
|
195
|
+
child.stderr?.on('data', (chunk) => {
|
|
196
|
+
const text = chunk.toString('utf8')
|
|
197
|
+
if (stderr.length < OUTPUT_LIMIT) stderr += text
|
|
198
|
+
feedLines('stderr', text)
|
|
199
|
+
})
|
|
200
|
+
const timer = setTimeout(() => {
|
|
201
|
+
timedOut = true
|
|
202
|
+
child.kill('SIGKILL')
|
|
203
|
+
}, timeoutMs)
|
|
204
|
+
child.once('error', (error) => {
|
|
205
|
+
finish({ ok: false, code: null, timedOut: false, stdout, stderr: stderr + String(error) })
|
|
206
|
+
})
|
|
207
|
+
child.once('close', (code) => {
|
|
208
|
+
finish({ ok: !timedOut && code === 0, code, timedOut, stdout, stderr })
|
|
209
|
+
})
|
|
210
|
+
})
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function tail(text, limit = 1500) {
|
|
214
|
+
const trimmed = String(text ?? '').trim()
|
|
215
|
+
if (trimmed.length <= limit) return trimmed
|
|
216
|
+
return trimmed.slice(-limit)
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function firstLine(text) {
|
|
220
|
+
const line = String(text ?? '').trim().split(/\r?\n/u).find((item) => item.trim() !== '')
|
|
221
|
+
return line === undefined ? '' : line.trim()
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function clampNumber(value, min, max) {
|
|
225
|
+
return Math.min(max, Math.max(min, value))
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** Expected npm-install duration learned from the previous successful update. */
|
|
229
|
+
function expectedInstallMs() {
|
|
230
|
+
try {
|
|
231
|
+
const data = JSON.parse(fs.readFileSync(TIMING_FILE, 'utf8'))
|
|
232
|
+
if (typeof data?.installMs === 'number' && Number.isFinite(data.installMs)) {
|
|
233
|
+
return clampNumber(data.installMs, MIN_EXPECTED_MS, MAX_EXPECTED_MS)
|
|
234
|
+
}
|
|
235
|
+
} catch {
|
|
236
|
+
// no saved timing yet
|
|
237
|
+
}
|
|
238
|
+
return DEFAULT_INSTALL_MS
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
function recordInstallMs(installMs) {
|
|
242
|
+
try {
|
|
243
|
+
fs.mkdirSync(STATE_DIR, { recursive: true, mode: 0o700 })
|
|
244
|
+
fs.writeFileSync(TIMING_FILE, `${JSON.stringify({ installMs: Math.round(installMs), at: new Date().toISOString() })}\n`)
|
|
245
|
+
} catch {
|
|
246
|
+
// a missing estimate is a nicety; never fail the update over it
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* Ask npm which published versions satisfy one spec.
|
|
252
|
+
*
|
|
253
|
+
* @param {string} spec - package or package range, e.g. `@deepseek-ai/dsh@^0.2.2-rc.1`.
|
|
254
|
+
* @returns {Promise<{ ok: true, versions: string[] } | { ok: false, error: string }>}
|
|
255
|
+
*/
|
|
256
|
+
export async function npmViewVersions(spec) {
|
|
257
|
+
const result = await runNpm(['view', spec, 'version', '--json'], { timeoutMs: VIEW_TIMEOUT_MS })
|
|
258
|
+
if (!result.ok) {
|
|
259
|
+
return { ok: false, error: firstLine(result.stderr) || `npm view 退出码 ${String(result.code)}` }
|
|
260
|
+
}
|
|
261
|
+
const text = result.stdout.trim()
|
|
262
|
+
if (text === '') return { ok: false, error: 'npm view 没有返回内容' }
|
|
263
|
+
let parsed
|
|
264
|
+
try {
|
|
265
|
+
parsed = JSON.parse(text)
|
|
266
|
+
} catch {
|
|
267
|
+
return { ok: false, error: 'npm view 返回了非 JSON 内容' }
|
|
268
|
+
}
|
|
269
|
+
const versions = (Array.isArray(parsed) ? parsed : [parsed])
|
|
270
|
+
.filter((item) => typeof item === 'string')
|
|
271
|
+
.sort(compareVersions)
|
|
272
|
+
if (versions.length === 0) return { ok: false, error: 'npm view 没有返回版本号' }
|
|
273
|
+
return { ok: true, versions }
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* Read the newest published version that the running installation may install,
|
|
278
|
+
* plus the current version.
|
|
279
|
+
*
|
|
280
|
+
* @param {string} [argv1] - launcher script path override (tests).
|
|
281
|
+
* @returns {Promise<object>} status payload for the button.
|
|
282
|
+
*/
|
|
283
|
+
export async function checkUpdates(argv1 = process.argv[1]) {
|
|
284
|
+
const install = locateInstall(argv1)
|
|
285
|
+
let versions = []
|
|
286
|
+
let source = 'range'
|
|
287
|
+
if (install.range !== undefined) {
|
|
288
|
+
const view = await npmViewVersions(`${PACKAGE_NAME}@${install.range}`)
|
|
289
|
+
if (view.ok) versions = view.versions
|
|
290
|
+
}
|
|
291
|
+
if (versions.length === 0) {
|
|
292
|
+
source = 'latest'
|
|
293
|
+
const view = await npmViewVersions(`${PACKAGE_NAME}@latest`)
|
|
294
|
+
if (!view.ok) throw new Error(view.error)
|
|
295
|
+
versions = view.versions
|
|
296
|
+
}
|
|
297
|
+
const candidate = versions[versions.length - 1]
|
|
298
|
+
let tags
|
|
299
|
+
try {
|
|
300
|
+
const response = await fetch(`${REGISTRY}/-/package/${PACKAGE_NAME}/dist-tags`, {
|
|
301
|
+
signal: AbortSignal.timeout(8000),
|
|
302
|
+
})
|
|
303
|
+
if (response.ok) tags = await response.json()
|
|
304
|
+
} catch {
|
|
305
|
+
// dist-tags are a display nicety only
|
|
306
|
+
}
|
|
307
|
+
const channel = tags !== undefined && candidate === tags.next
|
|
308
|
+
? 'next'
|
|
309
|
+
: tags !== undefined && candidate === tags.latest
|
|
310
|
+
? 'latest'
|
|
311
|
+
: 'published'
|
|
312
|
+
return {
|
|
313
|
+
ok: true,
|
|
314
|
+
current: install.version,
|
|
315
|
+
candidate,
|
|
316
|
+
updateAvailable: compareVersions(candidate, install.version) > 0,
|
|
317
|
+
channel,
|
|
318
|
+
source,
|
|
319
|
+
range: install.range ?? null,
|
|
320
|
+
versions: versions.slice(-8),
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
function runCp(source, target, extraArgs) {
|
|
325
|
+
return new Promise((resolve) => {
|
|
326
|
+
let child
|
|
327
|
+
try {
|
|
328
|
+
child = spawn('cp', ['-a', ...extraArgs, source, target], { stdio: ['ignore', 'pipe', 'pipe'] })
|
|
329
|
+
} catch (error) {
|
|
330
|
+
resolve({ ok: false, error: String(error) })
|
|
331
|
+
return
|
|
332
|
+
}
|
|
333
|
+
let stderr = ''
|
|
334
|
+
let settled = false
|
|
335
|
+
const finish = (result) => {
|
|
336
|
+
if (settled) return
|
|
337
|
+
settled = true
|
|
338
|
+
resolve(result)
|
|
339
|
+
}
|
|
340
|
+
child.stderr?.on('data', (chunk) => {
|
|
341
|
+
stderr += chunk.toString('utf8')
|
|
342
|
+
})
|
|
343
|
+
child.once('error', (error) => finish({ ok: false, error: String(error) }))
|
|
344
|
+
child.once('close', (code) => finish(code === 0 ? { ok: true } : { ok: false, error: tail(stderr, 800) || `cp 退出码 ${String(code)}` }))
|
|
345
|
+
})
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/**
|
|
349
|
+
* Copy an installation root into a sibling staging directory. The live copy is
|
|
350
|
+
* never touched during the (slow) install, so a running server keeps working
|
|
351
|
+
* until the final atomic swap.
|
|
352
|
+
*
|
|
353
|
+
* @param {string} root - installation root to copy.
|
|
354
|
+
* @param {string} staging - destination directory (must not matter if present).
|
|
355
|
+
* @returns {Promise<{ ok: true } | { ok: false, error: string }>}
|
|
356
|
+
*/
|
|
357
|
+
export async function copyInstallRoot(root, staging) {
|
|
358
|
+
fs.rmSync(staging, { recursive: true, force: true })
|
|
359
|
+
let result = await runCp(root, staging, ['--reflink=auto'])
|
|
360
|
+
if (!result.ok) {
|
|
361
|
+
fs.rmSync(staging, { recursive: true, force: true })
|
|
362
|
+
result = await runCp(root, staging, [])
|
|
363
|
+
}
|
|
364
|
+
return result
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/**
|
|
368
|
+
* Atomically re-point the installation root at a staged directory. The previous
|
|
369
|
+
* copy is renamed aside first and restored when the second rename fails.
|
|
370
|
+
*
|
|
371
|
+
* @param {string} root - live installation root.
|
|
372
|
+
* @param {string} staging - prepared replacement.
|
|
373
|
+
* @returns {{ ok: true, backup: string } | { ok: false, error: string }}
|
|
374
|
+
*/
|
|
375
|
+
export function swapInstallRoot(root, staging) {
|
|
376
|
+
const backup = `${root}.backup-${Date.now()}`
|
|
377
|
+
try {
|
|
378
|
+
fs.renameSync(root, backup)
|
|
379
|
+
} catch (error) {
|
|
380
|
+
return { ok: false, error: `无法备份当前安装:${error.message}` }
|
|
381
|
+
}
|
|
382
|
+
try {
|
|
383
|
+
fs.renameSync(staging, root)
|
|
384
|
+
} catch (error) {
|
|
385
|
+
try {
|
|
386
|
+
fs.renameSync(backup, root)
|
|
387
|
+
} catch {
|
|
388
|
+
// leave the backup in place; the updater reports the failure
|
|
389
|
+
}
|
|
390
|
+
return { ok: false, error: `无法启用新安装:${error.message}` }
|
|
391
|
+
}
|
|
392
|
+
return { ok: true, backup }
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
function removeDetached(target) {
|
|
396
|
+
try {
|
|
397
|
+
const child = spawn('rm', ['-rf', target], { detached: true, stdio: 'ignore' })
|
|
398
|
+
child.unref()
|
|
399
|
+
} catch {
|
|
400
|
+
// a leftover backup directory only costs disk space
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/**
|
|
405
|
+
* Install `candidate` next to the running installation and swap it in.
|
|
406
|
+
*
|
|
407
|
+
* The new version is installed into a staging copy while the live files stay
|
|
408
|
+
* untouched; only after the staged version is verified does the root get
|
|
409
|
+
* renamed into place. The caller must exit the process afterwards: the running
|
|
410
|
+
* code and the files below it now disagree.
|
|
411
|
+
*
|
|
412
|
+
* Progress events drive the Web UI dialog. The install phase is estimated from
|
|
413
|
+
* the previous successful update (or five minutes), because npm has no
|
|
414
|
+
* machine-readable percentage.
|
|
415
|
+
*
|
|
416
|
+
* @param {string} candidate - exact version to install.
|
|
417
|
+
* @param {string} [argv1] - launcher script path override (tests).
|
|
418
|
+
* @param {(event: { phase: string, percent: number, message: string, activity?: string, elapsedMs?: number }) => void} [onProgress] - progress sink.
|
|
419
|
+
* @returns {Promise<object>} outcome payload.
|
|
420
|
+
*/
|
|
421
|
+
export async function updateTo(candidate, argv1 = process.argv[1], onProgress) {
|
|
422
|
+
const emit = (phase, percent, message, extra = {}) => {
|
|
423
|
+
if (typeof onProgress !== 'function') return
|
|
424
|
+
try {
|
|
425
|
+
onProgress({ phase, percent, message, ...extra })
|
|
426
|
+
} catch {
|
|
427
|
+
// progress reporting must never break the update
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
const install = locateInstall(argv1)
|
|
431
|
+
if (compareVersions(candidate, install.version) <= 0) {
|
|
432
|
+
return { ok: true, updated: false, current: install.version, to: install.version }
|
|
433
|
+
}
|
|
434
|
+
const fail = (error, detail) => ({
|
|
435
|
+
ok: false,
|
|
436
|
+
error,
|
|
437
|
+
detail,
|
|
438
|
+
current: install.version,
|
|
439
|
+
candidate,
|
|
440
|
+
})
|
|
441
|
+
const cleanup = () => {
|
|
442
|
+
try {
|
|
443
|
+
fs.rmSync(staging, { recursive: true, force: true })
|
|
444
|
+
} catch {
|
|
445
|
+
// a leftover staging directory only costs disk space
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
const staging = `${install.root}.staging-${Date.now()}-${process.pid}`
|
|
449
|
+
let ticker
|
|
450
|
+
try {
|
|
451
|
+
emit('copy', 3, '正在准备运行时副本…')
|
|
452
|
+
const copy = await copyInstallRoot(install.root, staging)
|
|
453
|
+
if (!copy.ok) {
|
|
454
|
+
cleanup()
|
|
455
|
+
emit('failed', 3, `准备失败:${copy.error}`)
|
|
456
|
+
return fail('copy-failed', copy.error)
|
|
457
|
+
}
|
|
458
|
+
const expectedMs = expectedInstallMs()
|
|
459
|
+
const installStartedAt = Date.now()
|
|
460
|
+
let installMs = 0
|
|
461
|
+
let lastActivity = ''
|
|
462
|
+
emit('install', 8, '正在下载并安装依赖…', { elapsedMs: 0 })
|
|
463
|
+
ticker = setInterval(() => {
|
|
464
|
+
installMs = Date.now() - installStartedAt
|
|
465
|
+
const fraction = Math.min(1, installMs / expectedMs)
|
|
466
|
+
const percent = Math.round(8 + 84 * fraction)
|
|
467
|
+
const message = fraction >= 1
|
|
468
|
+
? '正在下载并安装依赖(比预计更久,仍在进行)…'
|
|
469
|
+
: '正在下载并安装依赖…'
|
|
470
|
+
emit('install', percent, message, { activity: lastActivity, elapsedMs: installMs })
|
|
471
|
+
}, 1000)
|
|
472
|
+
const result = await runNpm(
|
|
473
|
+
['install', '--prefix', staging, '--no-audit', '--no-fund', '--loglevel=info', `${PACKAGE_NAME}@${candidate}`],
|
|
474
|
+
{
|
|
475
|
+
timeoutMs: INSTALL_TIMEOUT_MS,
|
|
476
|
+
onLine: (line) => {
|
|
477
|
+
lastActivity = line.length > 160 ? line.slice(0, 160) : line
|
|
478
|
+
},
|
|
479
|
+
},
|
|
480
|
+
)
|
|
481
|
+
clearInterval(ticker)
|
|
482
|
+
ticker = undefined
|
|
483
|
+
installMs = Date.now() - installStartedAt
|
|
484
|
+
if (!result.ok) {
|
|
485
|
+
cleanup()
|
|
486
|
+
emit('failed', 8, result.timedOut ? '安装超时' : '安装失败')
|
|
487
|
+
return fail(result.timedOut ? 'update-timeout' : 'update-failed', tail(result.stderr) || tail(result.stdout))
|
|
488
|
+
}
|
|
489
|
+
emit('verify', 92, '正在校验新版本…', { elapsedMs: installMs })
|
|
490
|
+
let version
|
|
491
|
+
try {
|
|
492
|
+
version = String(JSON.parse(fs.readFileSync(path.join(staging, 'node_modules', PACKAGE_NAME, 'package.json'), 'utf8')).version)
|
|
493
|
+
} catch {
|
|
494
|
+
cleanup()
|
|
495
|
+
return fail('version-unreadable', tail(result.stdout))
|
|
496
|
+
}
|
|
497
|
+
if (compareVersions(version, install.version) <= 0) {
|
|
498
|
+
cleanup()
|
|
499
|
+
return fail('version-unchanged', tail(result.stdout))
|
|
500
|
+
}
|
|
501
|
+
emit('swap', 96, '正在切换到新版本…', { elapsedMs: installMs })
|
|
502
|
+
const swap = swapInstallRoot(install.root, staging)
|
|
503
|
+
if (!swap.ok) {
|
|
504
|
+
cleanup()
|
|
505
|
+
return fail('swap-failed', swap.error)
|
|
506
|
+
}
|
|
507
|
+
removeDetached(swap.backup)
|
|
508
|
+
recordInstallMs(installMs)
|
|
509
|
+
emit('done', 100, `更新完成:${version}`, { elapsedMs: installMs })
|
|
510
|
+
return { ok: true, updated: true, from: install.version, to: version, detail: tail(result.stdout) }
|
|
511
|
+
} catch (error) {
|
|
512
|
+
emit('failed', 0, `更新异常:${error instanceof Error ? error.message : String(error)}`)
|
|
513
|
+
cleanup()
|
|
514
|
+
return fail('update-failed', error instanceof Error ? error.message : String(error))
|
|
515
|
+
} finally {
|
|
516
|
+
if (ticker !== undefined) clearInterval(ticker)
|
|
517
|
+
}
|
|
518
|
+
}
|