dsh-remote-plugin 0.7.3 → 0.7.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.mjs CHANGED
@@ -14,6 +14,8 @@ import { dirname, extname, normalize, resolve } from 'node:path'
14
14
  import { fileURLToPath } from 'node:url'
15
15
  import { createPluginCenter, detectProfile } from './plugin-center.mjs'
16
16
  import { readCostInsights } from './insights.mjs'
17
+ import { serveSessionFile } from './session-file.mjs'
18
+ import { createSkillsAdapter } from './skills.mjs'
17
19
 
18
20
  export const name = 'dsh-remote'
19
21
  export const inject = ['webServer', 'commands', 'agents', 'connection']
@@ -194,7 +196,7 @@ function readBody(req, maxBytes) {
194
196
  })
195
197
  }
196
198
 
197
- /** 转发到本地网关管理 API; 失败/超时返回 null。 */
199
+ /** 转发到本地网关管理 API;缺少令牌返回 null,超时与连接失败保留具体错误。 */
198
200
  async function proxyGateway(path, method, body) {
199
201
  const token = gatewayToken()
200
202
  if (!token) return null
@@ -207,12 +209,14 @@ async function proxyGateway(path, method, body) {
207
209
  'x-dsh-remote-client': 'admin',
208
210
  },
209
211
  body: method === 'POST' ? body : undefined,
210
- signal: AbortSignal.timeout(1500),
212
+ signal: AbortSignal.timeout(path.startsWith('/admin/api/dsh') ? 15000 : 5000),
211
213
  })
212
214
  const json = await res.json().catch(() => ({ ok: false, error: `gateway ${res.status}` }))
213
215
  return { status: res.status, json }
214
- } catch {
215
- return null
216
+ } catch (error) {
217
+ const timeout = error?.name === 'TimeoutError' || error?.name === 'AbortError'
218
+ return { status: timeout ? 504 : 502, json: { ok: false, code: timeout ? 'GATEWAY_TIMEOUT' : 'GATEWAY_UNREACHABLE',
219
+ error: timeout ? '本地网关响应超时,请稍后重试' : '无法连接本地网关,请检查网关运行状态' } }
216
220
  }
217
221
  }
218
222
 
@@ -274,10 +278,18 @@ function portInUse(port) {
274
278
  })
275
279
  }
276
280
 
281
+ let gatewayHealthJob = null
277
282
  async function gatewayRunning() {
283
+ const base = gatewayBase()
284
+ if (gatewayHealthJob?.base === base) return gatewayHealthJob.promise
285
+ const job = { base }
286
+ gatewayHealthJob = job
287
+ job.promise = probeGatewayRunning(base).finally(() => { if (gatewayHealthJob === job) gatewayHealthJob = null })
288
+ return job.promise
289
+ }
290
+ async function probeGatewayRunning(base) {
278
291
  try {
279
- const base = gatewayBase()
280
- const res = await fetch(`${base}/health`, { signal: AbortSignal.timeout(6000) })
292
+ const res = await fetch(`${base}/health?probe=live`, { signal: AbortSignal.timeout(6000) })
281
293
  if (!res.ok) return { running: false }
282
294
  const data = await res.json().catch(() => ({}))
283
295
  if (data.service !== 'dsh-remote' || !Number.isInteger(data.pid) || data.pid <= 1
@@ -365,7 +377,7 @@ async function startGateway() {
365
377
  if (health.running) {
366
378
  const auth = await proxyGateway('/admin/api/state', 'GET', '')
367
379
  if (!auth || auth.status !== 200 || auth.json.ok !== true) {
368
- return { ok: false, running: true, started: false, error: GATEWAY_AUTH_HINT }
380
+ return { ok: false, running: true, started: false, error: auth?.status === 401 || auth?.status === 403 ? GATEWAY_AUTH_HINT : auth?.json?.error || '本地网关管理接口响应异常,请稍后重试' }
369
381
  }
370
382
  setGatewayEnabled(true)
371
383
  return { ok: true, running: true, started: false }
@@ -642,6 +654,28 @@ async function resolveFile(pathname) {
642
654
 
643
655
  async function serveStatic(req, res, ctx) {
644
656
  const pathname = new URL(req.url ?? '/', 'http://x').pathname
657
+ if (pathname.startsWith(`${MOUNT}/api/skills/`)) {
658
+ res.setHeader('cache-control', 'no-store')
659
+ if (!remoteCommandAuthorized(req)) return sendJson(res, 401, { ok: false, code: 'unauthorized' })
660
+ const adapter = createSkillsAdapter(async path => {
661
+ // Use this host's listener, never a URL, origin or cookie supplied by the caller.
662
+ const base = upstreamUrlForListener({ host: ctx.webServer.host, port: ctx.webServer.port })
663
+ let cookie = ''
664
+ try { cookie = readFileSync(dshUpstreamCookieFile(), 'utf8').trim() } catch {}
665
+ const response = await fetch(base + path, { headers: cookie ? { cookie } : {}, redirect: 'error', signal: AbortSignal.timeout(10000) })
666
+ if (!response.ok) { await response.body?.cancel(); throw Object.assign(new Error('native-read-failed'), { status: response.status }) }
667
+ const chunks = []; let bytes = 0
668
+ for await (const chunk of response.body) {
669
+ bytes += chunk.length
670
+ if (bytes > 2 * 1024 * 1024) throw new Error('response-too-large')
671
+ chunks.push(chunk)
672
+ }
673
+ try { return JSON.parse(Buffer.concat(chunks).toString('utf8')) } catch { throw new Error('unsupported') }
674
+ })
675
+ const url = new URL(req.url, 'http://x')
676
+ const result = await adapter.handle(req.method, pathname.slice(`${MOUNT}/api/skills`.length), url.searchParams)
677
+ return sendJson(res, result.status, result.body)
678
+ }
645
679
  if (pathname === `${MOUNT}/api/insights/cost`) {
646
680
  if (!remoteCommandAuthorized(req)) return sendJson(res, 401, { ok: false, code: 'unauthorized' })
647
681
  if (req.method !== 'GET') return sendJson(res, 405, { ok: false, code: 'read-only' })
@@ -702,11 +736,15 @@ async function serveStatic(req, res, ctx) {
702
736
  sendJson(res, proxied.status, { ...proxied.json, token: localToken, mode: 'gateway', via: 'gateway', gatewayInstalled })
703
737
  return
704
738
  }
739
+ if (health.running && proxied?.status >= 500) {
740
+ sendJson(res, proxied.status, { ...proxied.json, gatewayRunning: true })
741
+ return
742
+ }
705
743
  sendJson(res, 200, {
706
744
  ok: true,
707
745
  mode: 'plugin',
708
746
  gatewayRunning: health.running,
709
- gatewayAuthError: health.running ? GATEWAY_AUTH_HINT : '',
747
+ gatewayAuthError: health.running && (!localToken || proxied?.status === 401 || proxied?.status === 403) ? GATEWAY_AUTH_HINT : '',
710
748
  gatewayVersion: health.version || '',
711
749
  version,
712
750
  token: health.running ? '' : localToken || '',
@@ -854,7 +892,8 @@ async function serveStatic(req, res, ctx) {
854
892
  return
855
893
  }
856
894
  const body = req.method === 'POST' ? await readBody(req, 4096) : ''
857
- const proxied = await proxyGateway('/admin/api/dsh', req.method, body)
895
+ const query = new URL(req.url, 'http://x').search
896
+ const proxied = await proxyGateway('/admin/api/dsh' + query, req.method, body)
858
897
  if (proxied !== null) {
859
898
  sendJson(res, proxied.status, proxied.json)
860
899
  } else {
@@ -863,6 +902,10 @@ async function serveStatic(req, res, ctx) {
863
902
  return
864
903
  }
865
904
 
905
+ if (pathname === `${MOUNT}/api/session-file`) {
906
+ if (!remoteCommandAuthorized(req)) { sendJson(res,401,{ok:false,message:'unauthorized'});return }
907
+ return serveSessionFile(ctx, req, res, new URL(req.url, 'http://host'))
908
+ }
866
909
  // 命令状态:由插件进程跟踪长期操作,客户端重连后可恢复可见状态。
867
910
  if (pathname === `${MOUNT}/api/command-status`) {
868
911
  if (req.method !== 'GET') {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-remote-plugin",
3
- "version": "0.7.3",
3
+ "version": "0.7.5",
4
4
  "description": "DSH Remote 官方 bundle 插件:DSH 左侧原生边栏入口 + 右侧抽屉内嵌管理控制台;内置网关随 DSH 自动启停(systemd 独立单元),抽屉直显令牌与设备监控;网关提供 /fs/* 文件传输端点(列表/断点下载/上传),配合 Android App 远程操控会话/审批/提问/goal 与文件互传(多服务器测速切换、聊天记录离线缓存)。",
5
5
  "type": "module",
6
6
  "main": "./index.mjs",
@@ -20,7 +20,9 @@
20
20
  "cordis.patch.yml",
21
21
  "*.md",
22
22
  "plugin-center.mjs",
23
- "insights.mjs"
23
+ "insights.mjs",
24
+ "skills.mjs",
25
+ "session-file.mjs"
24
26
  ],
25
27
  "keywords": [
26
28
  "dsh-plugin",
package/plugin-center.mjs CHANGED
@@ -1,9 +1,9 @@
1
1
  /* Profile-scoped plugin management. No shell input, dependencies or client-selected paths. */
2
- import { readFileSync, writeFileSync, renameSync, mkdirSync, existsSync, readdirSync, copyFileSync, unlinkSync, realpathSync, openSync, closeSync } from 'node:fs'
2
+ import { readFileSync, writeFileSync, renameSync, mkdirSync, existsSync, readdirSync, copyFileSync, cpSync, unlinkSync, realpathSync, openSync, closeSync } from 'node:fs'
3
3
  import { dirname, basename, join, resolve } from 'node:path'
4
4
  import { fileURLToPath } from 'node:url'
5
5
  import { createHash } from 'node:crypto'
6
- import { spawn } from 'node:child_process'
6
+ import { spawn, execFile } from 'node:child_process'
7
7
 
8
8
  const REGISTRY = 'https://registry.npmjs.org'
9
9
  const SELF = fileURLToPath(import.meta.url)
@@ -19,22 +19,78 @@ function atomic(path, value) {
19
19
  const fail = (message, status = 400) => Object.assign(new Error(message), { status })
20
20
  const protectedPackage = name => name === 'dsh-remote-plugin' || name.startsWith('@deepseek-ai/')
21
21
  const revision = path => createHash('sha256').update(readFileSync(path)).digest('hex')
22
+ // A detached worker can replace/delete its ledger between two manager reads.
23
+ // Windows sharing violations are uncertain ownership, never proof of death.
24
+ function ownershipText(path) {
25
+ try { return readFileSync(path, 'utf8') } catch (error) {
26
+ if (error.code === 'ENOENT') return null
27
+ if (['EPERM', 'EBUSY', 'EACCES'].includes(error.code)) return undefined
28
+ throw error
29
+ }
30
+ }
31
+ const ownershipPending = '任务锁正在更新或暂时无法读取,已保留锁;请稍后刷新。'
22
32
 
23
- function alive(pid) {
24
- if (!Number.isInteger(pid) || pid <= 0) return false
25
- try { process.kill(pid, 0); return true } catch (error) { return error.code !== 'ESRCH' }
33
+ let windowsProbe
34
+ function windowsProcessIds() {
35
+ // Windows can return EPERM for an exited PID. Enumerate OS processes instead;
36
+ // failure or malformed output must never be interpreted as an empty list.
37
+ if (!windowsProbe) windowsProbe = new Promise((resolveIds, reject) => {
38
+ execFile(join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'),
39
+ ['-NoProfile', '-NonInteractive', '-Command', '$ErrorActionPreference="Stop"; ConvertTo-Json -Compress -InputObject @(Get-Process -ErrorAction Stop | Select-Object -ExpandProperty Id)'],
40
+ { windowsHide: true, timeout: 5000, maxBuffer: 1024 * 1024 }, (error, stdout) => {
41
+ if (error) return reject(error)
42
+ try {
43
+ const ids = JSON.parse(stdout.replace(/^\uFEFF/, ''))
44
+ if (!Array.isArray(ids) || !ids.length || !ids.every(Number.isInteger)) throw new Error('Invalid process list')
45
+ resolveIds(new Set(ids))
46
+ } catch (error) { reject(error) }
47
+ })
48
+ }).finally(() => { windowsProbe = null })
49
+ return windowsProbe
50
+ }
51
+
52
+ export async function probeProcesses(pids, runtime = process, enumerate = windowsProcessIds) {
53
+ const states = new Map(), uncertain = []
54
+ for (const pid of new Set(pids.filter(pid => Number.isInteger(pid) && pid > 0))) {
55
+ try { runtime.kill(pid, 0); states.set(pid, 'alive') }
56
+ catch (error) {
57
+ states.set(pid, error.code === 'ESRCH' ? 'dead' : 'unknown')
58
+ if (error.code === 'EPERM' && runtime.platform === 'win32') uncertain.push(pid)
59
+ }
60
+ }
61
+ if (uncertain.length) {
62
+ try {
63
+ const ids = await enumerate()
64
+ for (const pid of uncertain) states.set(pid, ids.has(pid) ? 'alive' : 'dead')
65
+ } catch { /* Keep unknown on timeout, denied access or unavailable OS query. */ }
66
+ }
67
+ return states
26
68
  }
27
69
 
28
70
  // Never clear a live worker or its package-manager child. PID reuse fails closed.
29
- function recoverDeadLock(storage) {
71
+ async function recoverDeadLock(storage, probe = probeProcesses) {
30
72
  const path = join(storage, 'lock.json')
31
- if (!existsSync(path)) return
32
- const owner = read(path)
73
+ const original = ownershipText(path)
74
+ if (original === null) return
75
+ if (original === undefined) return ownershipPending
76
+ const owner = JSON.parse(original)
33
77
  if (!idPattern.test(owner.id || '')) throw fail('插件任务锁损坏,请在主机检查', 409)
34
78
  const launchPath = join(storage, 'launch-' + owner.id + '.json')
35
- const workerPid = owner.workerPid || (existsSync(launchPath) ? read(launchPath).pid : null)
36
- if (alive(workerPid) || alive(owner.cliPid)) return
37
- if (!workerPid && (!owner.launcherPid || alive(owner.launcherPid) || Date.now() - owner.createdAt < 30000)) return
79
+ const launchRecord = ownershipText(launchPath)
80
+ if (launchRecord === undefined) return ownershipPending
81
+ const workerPid = owner.workerPid || (launchRecord ? JSON.parse(launchRecord).pid : null)
82
+ const pids = workerPid ? [workerPid, owner.cliPid] : [owner.launcherPid, owner.cliPid]
83
+ if (pids.some(pid => pid != null && (!Number.isSafeInteger(pid) || pid <= 0))) return '任务锁进程信息损坏,已保留锁;请在主机检查。'
84
+ const states = await probe(pids)
85
+ const currentOwner = ownershipText(path), currentLaunch = ownershipText(launchPath)
86
+ if (currentOwner === undefined || currentLaunch === undefined) return ownershipPending
87
+ if (currentOwner !== original || currentLaunch !== launchRecord) return
88
+ if ([...states.values()].some(state => state !== 'dead')) {
89
+ return [...states.values()].includes('unknown')
90
+ ? '无法确认任务进程是否已退出,已保留锁;请在主机检查进程权限与操作记录。'
91
+ : '主机任务进程仍在运行,其他修改暂不可用;可展开操作记录查看日志。'
92
+ }
93
+ if (!workerPid && (!owner.launcherPid || !Number.isFinite(owner.createdAt) || Date.now() - owner.createdAt < 30000)) return
38
94
  const jobPath = join(storage, 'job-' + owner.id + '.json')
39
95
  if (existsSync(jobPath)) {
40
96
  const job = read(jobPath)
@@ -45,7 +101,25 @@ function recoverDeadLock(storage) {
45
101
  }
46
102
  }
47
103
  // All reads/writes here are synchronous; recheck ownership before unlinking.
48
- if (read(path).id === owner.id) unlinkSync(path)
104
+ if (ownershipText(path) === original) {
105
+ copyFileSync(path, join(storage, 'recovered-lock-' + owner.id + '.json'))
106
+ unlinkSync(path)
107
+ }
108
+ }
109
+
110
+ async function profileLock(dir, probe = probeProcesses) {
111
+ const path = join(dir, 'package.json.lock')
112
+ if (!existsSync(path)) return null
113
+ const raw = readFileSync(path, 'utf8'), text = raw.trim()
114
+ const pid = /^\d+$/.test(text) ? Number(text) : null
115
+ if (!Number.isSafeInteger(pid) || pid <= 0) return { path, raw, state: 'unknown', message: 'DSH 配置锁格式无法识别,请在主机检查 package.json.lock。' }
116
+ const state = (await probe([pid])).get(pid) || 'unknown'
117
+ if (!existsSync(path)) return null
118
+ if (readFileSync(path, 'utf8') !== raw) return { state: 'unknown', message: 'DSH 配置锁已变化,请刷新后重试。' }
119
+ return { path, raw, pid, state, message: state === 'dead'
120
+ ? '检测到已退出进程遗留的 DSH 配置锁;下一次操作会备份并回收。'
121
+ : state === 'alive' ? 'DSH 配置被进程 ' + pid + ' 占用,请等待主机操作结束后重试。'
122
+ : '无法确认 DSH 配置锁进程 ' + pid + ' 是否已退出,请在主机检查;锁已保留。' }
49
123
  }
50
124
 
51
125
  export function detectProfile(ctx, cli = process.argv[1], runtime = process) {
@@ -114,6 +188,7 @@ export async function pluginDetails(name, version = 'latest') {
114
188
  export function createPluginCenter(ctx, options = {}) {
115
189
  const profile = options.profile === undefined ? detectProfile(ctx) : options.profile
116
190
  const details = options.details || pluginDetails
191
+ const probe = options.probeProcesses || probeProcesses
117
192
  const launch = options.launch || (args => {
118
193
  const desktop = profile?.cliMode === 'desktop'
119
194
  const errorLog = openSync(join(profile.dir, '.remote-plugin-center', 'worker-' + args[2] + '.log'), 'a', 0o600)
@@ -134,7 +209,7 @@ export function createPluginCenter(ctx, options = {}) {
134
209
  const storage = profile && join(profile.dir, '.remote-plugin-center')
135
210
  let submitting = false
136
211
  async function inventory() {
137
- if (storage) recoverDeadLock(storage)
212
+ const busyReason = storage ? await recoverDeadLock(storage, probe) : ''
138
213
  let runtime = [], runtimeAvailable = false
139
214
  const loader = ctx.get?.('loader') || ctx.loader
140
215
  if (loader?.entries) {
@@ -157,6 +232,7 @@ export function createPluginCenter(ctx, options = {}) {
157
232
  return { name, displayName, version: pkg?.version || '', requested: manifest.dependencies?.[name] || '',
158
233
  enabled: bundles.includes(name), bundle: !!pkg?.dsh?.bundle?.patch || bundles.includes(name),
159
234
  managed: !!manifest.dependencies?.[name] && !protectedPackage(name),
235
+ selfUpdate: name === 'dsh-remote-plugin' && !!profile.cli,
160
236
  description: pkg?.description || '', runtime: runtime.filter(entry => entry.name === name) }
161
237
  })
162
238
  let operations = []
@@ -164,14 +240,17 @@ export function createPluginCenter(ctx, options = {}) {
164
240
  try { return read(join(storage, name)) } catch { return null }
165
241
  }).filter(Boolean).sort((a, b) => b.startedAt - a.startedAt).slice(0, 20).map(publicJob)
166
242
  const lockPath = join(storage, 'lock.json')
167
- const owner = existsSync(lockPath) ? read(lockPath) : null
243
+ const ownerText = ownershipText(lockPath)
244
+ const owner = ownerText === null ? null : ownerText === undefined ? {} : JSON.parse(ownerText)
168
245
  const legacyLock = owner && idPattern.test(owner.id || '') && !owner.launcherPid && !owner.workerPid && !owner.cliPid && !existsSync(join(storage, 'launch-' + owner.id + '.json'))
169
246
  return { ok: true, profile: profile.name, revision: revision(manifestPath), writable: !!profile.cli,
170
247
  reason: profile.cli ? '' : profile.name === 'desktop'
171
248
  ? '未能验证当前桌面安装的插件管理入口;仅显示状态,请检查 DSH Desktop 版本与安装完整性。'
172
249
  : '当前启动方式没有可验证的 DSH CLI,管理操作不可用。',
173
250
  pendingRestart: revision(manifestPath) !== initialRevision || operations.some(job => job.phase === 'interrupted' && job.restartRequired),
174
- busy: submitting || !!owner, recovery: legacyLock ? { id: owner.id, reason: '旧任务锁没有进程信息,需在主机核对后手动解除。' } : null,
251
+ busy: submitting || !!owner, busyReason: owner ? busyReason || '主机任务正在启动;可查看操作记录。' : '',
252
+ profileLock: await profileLock(profile.dir, probe).then(lock => lock && ({ state: lock.state, message: lock.message })),
253
+ recovery: legacyLock ? { id: owner.id, reason: '旧任务锁没有进程信息,需在主机核对后手动解除。' } : null,
175
254
  items, runtime, runtimeAvailable, operations }
176
255
  }
177
256
  function recoverLegacy(body) {
@@ -199,9 +278,11 @@ export function createPluginCenter(ctx, options = {}) {
199
278
  if (!body || typeof body !== 'object' || Array.isArray(body)) throw fail('Invalid operation')
200
279
  const { id, action, name, version } = body
201
280
  if (!idPattern.test(id || '') || !packagePattern.test(name || '') || !['install', 'update', 'remove', 'enable', 'disable'].includes(action)) throw fail('Invalid operation')
202
- if (protectedPackage(name)) throw fail('核心插件与 Remote 自身请通过主机维护流程管理', 409)
281
+ const selfUpdate = name === 'dsh-remote-plugin' && action === 'update'
282
+ if (protectedPackage(name) && !selfUpdate) throw fail('核心插件与 Remote 的卸载、启停请通过主机维护流程管理', 409)
283
+ if (selfUpdate && body.confirmSelfUpdate !== true) throw fail('请确认 Remote 本体更新及重启后生效', 409)
203
284
  mkdirSync(storage, { recursive: true, mode: 0o700 })
204
- recoverDeadLock(storage)
285
+ await recoverDeadLock(storage, probe)
205
286
  const jobPath = join(storage, 'job-' + id + '.json')
206
287
  if (existsSync(jobPath)) {
207
288
  const previous = read(jobPath)
@@ -228,7 +309,7 @@ export function createPluginCenter(ctx, options = {}) {
228
309
  const lock = join(storage, 'lock.json')
229
310
  try { writeFileSync(lock, JSON.stringify({ id, launcherPid: process.pid, createdAt: Date.now() }), { flag: 'wx', mode: 0o600 }) }
230
311
  catch (error) { if (error.code === 'EEXIST') throw fail('已有插件任务运行中;请查看操作记录', 409); throw error }
231
- const job = { id, action, name, version: version || '', revision: body.revision, profile: profile.name, phase: 'queued', startedAt: Date.now(), log: '', restartRequired: false }
312
+ const job = { id, action, name, version: version || '', revision: body.revision, profile: profile.name, phase: 'queued', stage: 'queued', startedAt: Date.now(), updatedAt: Date.now(), log: '', restartRequired: false }
232
313
  try {
233
314
  atomic(jobPath, job)
234
315
  const pid = await launch([profile.dir, profile.cli, id, profile.cliMode || 'node'])
@@ -260,11 +341,11 @@ export function createPluginCenter(ctx, options = {}) {
260
341
  }
261
342
 
262
343
  function publicJob(job) {
263
- const { id, action, name, version, profile, phase, startedAt, endedAt, log, message, restartRequired } = job
264
- return { id, action, name, version, profile, phase, startedAt, endedAt, log, message, restartRequired }
344
+ const { id, action, name, version, profile, phase, stage, startedAt, endedAt, updatedAt, lastOutputAt, log, message, restartRequired } = job
345
+ return { id, action, name, version, profile, phase, stage, startedAt, endedAt, updatedAt, lastOutputAt, log, message, restartRequired }
265
346
  }
266
347
 
267
- export async function runWorker(dir, cli, id, execute = runCli, cliMode = 'node') {
348
+ export async function runWorker(dir, cli, id, execute = runCli, cliMode = 'node', probe = probeProcesses) {
268
349
  if (!idPattern.test(id || '')) throw fail('Invalid worker id')
269
350
  const storage = join(dir, '.remote-plugin-center')
270
351
  const lock = join(storage, 'lock.json')
@@ -276,24 +357,42 @@ export async function runWorker(dir, cli, id, execute = runCli, cliMode = 'node'
276
357
  const manifestPath = join(dir, 'package.json')
277
358
  const disabledPath = join(storage, 'disabled.json')
278
359
  let disabled
279
- const save = () => atomic(jobPath, job)
360
+ const save = () => { job.updatedAt = Date.now(); atomic(jobPath, job) }
361
+ const progress = (stage, message) => { job.stage = stage; job.message = message; save() }
362
+ let heartbeat
280
363
  try {
281
- job.phase = 'running'; save()
364
+ job.phase = 'running'; progress('backup', '正在备份配置文件。')
365
+ heartbeat = setInterval(save, 4000); heartbeat.unref()
282
366
  if (job.revision !== revision(manifestPath)) throw fail('任务开始前 profile 已变化,请刷新后重试')
283
367
  disabled = new Set(existsSync(disabledPath) ? read(disabledPath) : [])
284
368
  const backup = join(storage, 'backup-' + id)
285
369
  mkdirSync(backup, { mode: 0o700 })
286
- for (const name of ['package.json', 'pnpm-lock.yaml', 'pnpm-workspace.yaml', 'cordis.patch.yml']) {
370
+ for (const name of ['package.json', 'pnpm-lock.yaml', 'pnpm-workspace.yaml', 'cordis.patch.yml', 'cordis.yml']) {
287
371
  if (existsSync(join(dir, name))) copyFileSync(join(dir, name), join(backup, name))
288
372
  }
289
373
  if (existsSync(disabledPath)) copyFileSync(disabledPath, join(backup, 'disabled.json'))
374
+ if (job.name === 'dsh-remote-plugin') cpSync(join(dir, 'node_modules', 'dsh-remote-plugin'), join(backup, 'remote-plugin'), { recursive: true, dereference: true })
375
+ progress('profile-lock', '正在检查 DSH 配置锁。')
376
+ const existingLock = await profileLock(dir, probe)
377
+ if (existingLock) {
378
+ if (existingLock.state !== 'dead') throw fail(existingLock.message, 409)
379
+ // No await between final ownership comparison, backup and removal.
380
+ if (!existsSync(existingLock.path) || readFileSync(existingLock.path, 'utf8') !== existingLock.raw) throw fail('DSH 配置锁已变化,请刷新后重试', 409)
381
+ copyFileSync(existingLock.path, join(backup, 'package.json.lock'))
382
+ unlinkSync(existingLock.path)
383
+ job.log += '已备份并回收确认退出的进程遗留的 DSH 配置锁。\n'
384
+ }
385
+ if (job.revision !== revision(manifestPath)) throw fail('检查配置锁期间 profile 已变化,请刷新后重试')
290
386
  if (['install', 'update', 'remove'].includes(job.action)) {
387
+ progress('cli', '正在运行 DSH 插件命令,等待主机输出。')
291
388
  const args = job.action === 'remove' ? ['remove', job.name, '--config.ignore-scripts=true'] : ['add', job.name + '@' + job.version, '--save-exact', '--ignore-scripts', '--registry=' + REGISTRY]
292
389
  await execute(cli, ['plugin', '--profile', basename(dir), ...args], dir, chunk => {
390
+ job.lastOutputAt = Date.now()
293
391
  job.log = (job.log + chunk.replace(/\x1b\[[0-9;]*m/g, '').replace(/(token|password|authorization)\s*[=:]\s*\S+/gi, '$1=[redacted]')).slice(-12000)
294
392
  save()
295
393
  }, pid => atomic(lock, { ...read(lock), cliPid: pid }), cliMode)
296
394
  }
395
+ progress('verify', '正在保存配置并核验插件状态。')
297
396
  if (job.action === 'disable') disabled.add(job.name)
298
397
  if (job.action === 'enable' || job.action === 'remove') disabled.delete(job.name)
299
398
  const manifest = read(manifestPath)
@@ -307,15 +406,16 @@ export async function runWorker(dir, cli, id, execute = runCli, cliMode = 'node'
307
406
  const pkg = read(join(dir, 'node_modules', ...job.name.split('/'), 'package.json'))
308
407
  if (pkg.version !== job.version || !pkg.dsh?.bundle?.patch) throw fail('安装后的包版本或 bundle 校验失败')
309
408
  }
310
- job.phase = 'complete'; job.restartRequired = true
409
+ job.phase = 'complete'; job.stage = 'complete'; job.restartRequired = true
311
410
  job.message = '配置已保存;重启 DSH 后生效。安装脚本未执行。'
312
411
  } catch (error) {
313
412
  job.phase = 'failed'; job.message = String(error.message || error)
314
413
  // A failed package manager may have changed files. Never claim rollback.
315
414
  job.restartRequired = true
316
415
  } finally {
416
+ clearInterval(heartbeat)
317
417
  job.endedAt = Date.now(); save()
318
- if (read(lock).id === id) unlinkSync(lock)
418
+ if (existsSync(lock) && read(lock).id === id) unlinkSync(lock)
319
419
  }
320
420
  }
321
421
 
package/public/admin.js CHANGED
@@ -419,17 +419,30 @@ function renderDeviceKeys(st, isGateway) {
419
419
  document.querySelectorAll('[data-device-key-revoke]').forEach(button => button.addEventListener('click', () => revokeDeviceKey(byId(button.dataset.deviceKeyRevoke))))
420
420
  }
421
421
 
422
+ let stateLoadJob = null
422
423
  async function loadState() {
423
424
  if (!token && !pluginMode) return
425
+ if (stateLoadJob?.token === token) return stateLoadJob.promise
426
+ const job = { token }
427
+ stateLoadJob = job
428
+ job.promise = readState(job).finally(() => { if (stateLoadJob === job) stateLoadJob = null })
429
+ return job.promise
430
+ }
431
+ async function readState(job) {
424
432
  try {
425
433
  const res = await fetch(`${API}/state`, {
426
- headers: adminHeaders(), credentials: 'same-origin'
434
+ headers: adminHeaders({}, job.token), credentials: 'same-origin',
435
+ signal: typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function' ? AbortSignal.timeout(10000) : undefined
427
436
  })
437
+ if (stateLoadJob !== job || token !== job.token) return
438
+ if (!res.ok && res.status !== 401) throw new Error('HTTP ' + res.status)
428
439
  if (res.status === 401) throw new Error(pluginMode ? 'AUTH_LAYER' : 'AUTH')
429
440
  if (pluginMode && !String(res.headers.get('content-type') || '').includes('application/json')) throw new Error('AUTH_LAYER')
430
441
  const st = await res.json()
442
+ if (stateLoadJob !== job || token !== job.token) return
431
443
  render(st)
432
444
  } catch (e) {
445
+ if (stateLoadJob !== job || token !== job.token) return
433
446
  if (e.message === 'AUTH') {
434
447
  toast(t('toast.tokenInvalid'), 'err')
435
448
  logout()
@@ -835,7 +848,7 @@ $('btn-host-ip-add').addEventListener('click', addManualHostIP)
835
848
  $('conn-badge').addEventListener('click', () => {
836
849
  const st = lastState
837
850
  if (!st || st.mode !== 'gateway') { toast(t('toast.gatewayDown'), 'err'); return }
838
- const host = location.hostname || '127.0.0.1'
851
+ const host = location.protocol === 'dsh-app:' ? '127.0.0.1' : location.hostname || '127.0.0.1'
839
852
  const port = st.port || 8787
840
853
  const url = `http://${host}:${port}/admin?token=${encodeURIComponent(shownToken || token)}`
841
854
  try {