dsh-plugin-update-center 0.0.0-stage → 1.0.0

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/engine.js ADDED
@@ -0,0 +1,737 @@
1
+ /**
2
+ * Update-plan engine shared by the Host route and the unit tests.
3
+ *
4
+ * The engine owns three steps: reading the profile's installed bundles, asking
5
+ * the npm registry for their latest compatible stable release, and updating the
6
+ * selected plugins through the official DSH plugin manager. The official
7
+ * manager has no `updateBundle` in the current runtime, so one update is
8
+ * `removeBundle` followed by an exact `installBundle`; a failed install restores
9
+ * the previous exact version.
10
+ */
11
+
12
+ import { randomUUID } from 'node:crypto'
13
+ import { existsSync } from 'node:fs'
14
+ import { readFile } from 'node:fs/promises'
15
+ import { join } from 'node:path'
16
+ import { compareVersions, isPrerelease, parseVersion, satisfies } from './versions.js'
17
+
18
+ export const CHECK_TTL = 30 * 60 * 1000
19
+ export const OWN_NAME = 'dsh-plugin-update-center'
20
+ export const QUEUE_DEFAULTS = Object.freeze({ pollMs: 2000, quietMs: 10000, countdownMs: 5000 })
21
+ const CONCURRENCY = 4
22
+ const INTEGRITY_PATTERN = /^sha512-[A-Za-z0-9+/]{86}==$/
23
+ const PROTOCOL_SOURCE = /^(?:file:|link:|workspace:|portal:|git\+|git:|github:|https?:|ssh:)/i
24
+ const DRIVE_PATH = /^[A-Za-z]:[\\/]/
25
+ const RELATIVE_PATH = /^\.{0,2}[\\/]/
26
+
27
+ /** One expected failure expressed as a stable client-facing code. */
28
+ export function coded(code) {
29
+ const error = new Error(code)
30
+ error.code = code
31
+ return error
32
+ }
33
+
34
+ /** Map any thrown value to its stable code. */
35
+ export function errorCode(error) {
36
+ const code = error?.code ?? error?.message
37
+ if (typeof code === 'string' && /^[a-z][a-z0-9-]{1,63}$/.test(code)) return code
38
+ return 'operation-failed'
39
+ }
40
+
41
+ /**
42
+ * Resolve the install spec of a bundle to an npm registry package.
43
+ * Local, Git, workspace, alias and bare-path installs are not handled here.
44
+ * @param {object} bundle row from `pluginManager.listBundles()`
45
+ * @returns {{ name: string, selector: string } | null}
46
+ */
47
+ export function parseBundleSource(bundle) {
48
+ const source = bundle?.source
49
+ if (typeof source !== 'string' || source.trim() === '') return null
50
+ if (PROTOCOL_SOURCE.test(source) || DRIVE_PATH.test(source) || RELATIVE_PATH.test(source)) return null
51
+ const separator = source.lastIndexOf('@')
52
+ const name = separator > 0 ? source.slice(0, separator) : source
53
+ if (name !== bundle.name) return null
54
+ return { name, selector: separator > 0 ? source.slice(separator + 1) : 'latest' }
55
+ }
56
+
57
+ /**
58
+ * Candidate rows the checker may update: installed profile-owned, removable,
59
+ * readable bundles whose dependency source is the npm registry.
60
+ * @param {unknown} bundles
61
+ */
62
+ export function selectCandidates(bundles) {
63
+ if (!Array.isArray(bundles)) return []
64
+ const seen = new Set()
65
+ const candidates = []
66
+ for (const bundle of bundles) {
67
+ if (!bundle || typeof bundle !== 'object') continue
68
+ if (bundle.installed !== true) continue
69
+ if (bundle.availability !== 'profile') continue
70
+ if (bundle.removable === false) continue
71
+ if (bundle.readOnlyReason !== undefined) continue
72
+ if (bundle.error !== undefined) continue
73
+ if (typeof bundle.name !== 'string' || typeof bundle.version !== 'string') continue
74
+ if (bundle.name === OWN_NAME) continue
75
+ if (parseVersion(bundle.version) === null) continue
76
+ if (parseBundleSource(bundle) === null) continue
77
+ if (seen.has(bundle.name)) continue
78
+ seen.add(bundle.name)
79
+ candidates.push({
80
+ name: bundle.name,
81
+ version: bundle.version,
82
+ enabled: bundle.enabled !== false,
83
+ source: bundle.source,
84
+ description: typeof bundle.description === 'string' ? bundle.description : '',
85
+ })
86
+ }
87
+ return candidates
88
+ }
89
+
90
+ /**
91
+ * Judge whether one registry release may replace the installed version.
92
+ * Unknown engine ranges are treated as compatible; the official plugin manager
93
+ * performs the authoritative check during installation.
94
+ * @param {string} version candidate version
95
+ * @param {object} manifest registry version document
96
+ * @param {{ runtimeVersion?: string, nodeVersion?: string }} environment
97
+ */
98
+ export function evaluateManifest(version, manifest, environment = {}) {
99
+ if (typeof version !== 'string' || parseVersion(version) === null) return { compatible: false, reason: 'invalid-version' }
100
+ if (isPrerelease(version)) return { compatible: false, reason: 'prerelease' }
101
+ if (!manifest || typeof manifest !== 'object') return { compatible: false, reason: 'invalid-release' }
102
+ if (manifest.deprecated) return { compatible: false, reason: 'deprecated' }
103
+ if (!manifest.dsh || typeof manifest.dsh.bundle !== 'object') return { compatible: false, reason: 'not-bundle' }
104
+ const integrity = manifest.dist?.integrity
105
+ if (typeof integrity !== 'string' || !INTEGRITY_PATTERN.test(integrity)) return { compatible: false, reason: 'invalid-integrity' }
106
+ const checks = [
107
+ [manifest.engines?.node, environment.nodeVersion, 'node-version'],
108
+ [manifest.engines?.dsh, environment.runtimeVersion, 'dsh-version'],
109
+ ]
110
+ for (const [peer, range] of Object.entries(manifest.peerDependencies ?? {})) {
111
+ if (peer === '@deepseek-ai/dsh' || peer.startsWith('@deepseek-ai/dsh-')) checks.push([range, environment.runtimeVersion, 'dsh-version'])
112
+ }
113
+ for (const [range, actual, reason] of checks) {
114
+ if (range === undefined) continue
115
+ if (typeof actual !== 'string') continue
116
+ const satisfied = satisfies(actual, range)
117
+ if (satisfied === false) return { compatible: false, reason }
118
+ }
119
+ return {
120
+ compatible: true,
121
+ integrity,
122
+ publishedAt: typeof manifest.dist?.publishedAt === 'string' ? manifest.dist.publishedAt : null,
123
+ }
124
+ }
125
+
126
+ /** `pkg/client` and `pkg` name the same client module row. */
127
+ function stripClientSuffix(name) {
128
+ return name.endsWith('/client') ? name.slice(0, -'/client'.length) : name
129
+ }
130
+
131
+ /** The JavaScript entry a package declares, relative to its directory. */
132
+ function entryFileOf(manifest) {
133
+ const pick = (value) => {
134
+ if (typeof value === 'string') return value
135
+ if (value === null || typeof value !== 'object') return undefined
136
+ return value.default ?? value.import ?? value.node ?? value.require
137
+ }
138
+ const exported = manifest?.exports
139
+ const fromExports = exported !== null && typeof exported === 'object' ? pick(exported['.']) : undefined
140
+ const raw = fromExports ?? manifest?.main
141
+ if (typeof raw !== 'string' || raw === '') return null
142
+ return raw.replace(/^\.\//, '')
143
+ }
144
+
145
+ async function readJson(path) {
146
+ try {
147
+ return JSON.parse(await readFile(path, 'utf8'))
148
+ } catch {
149
+ return null
150
+ }
151
+ }
152
+
153
+ function successful(result) {
154
+ return Boolean(result) && result.error == null && (result.application === 'applied' || result.application === 'restart-required')
155
+ }
156
+
157
+ /**
158
+ * Build the update engine.
159
+ * @param {object} options
160
+ * @param {object} options.manager host `pluginManager`
161
+ * @param {object} options.registry registry client (`latest`, `release`, `manifest`)
162
+ * @param {(bundles: unknown[]) => string | undefined} [options.runtimeVersion]
163
+ * @param {() => Promise<{ known: boolean, busy: boolean }>} [options.activity]
164
+ * @param {() => number} [options.clock]
165
+ * @param {string} [options.profileDir] profile directory for rollback snapshots and verification
166
+ * @param {{ create: Function, history?: Function } | null} [options.backup] snapshot writer
167
+ * @param {{ pollMs?: number, quietMs?: number, countdownMs?: number }} [options.queue] queue timing
168
+ * @param {{ info?: Function, warn?: Function, error?: Function }} [options.logger]
169
+ */
170
+ export function createEngine({
171
+ manager,
172
+ registry,
173
+ runtimeVersion = () => undefined,
174
+ activity = async () => ({ known: false, busy: false }),
175
+ clock = () => Date.now(),
176
+ profileDir = undefined,
177
+ backup = null,
178
+ queue = {},
179
+ logger = {},
180
+ } = {}) {
181
+ if (!manager || typeof manager.listBundles !== 'function') throw new TypeError('pluginManager.listBundles is required')
182
+ if (!manager || typeof manager.installBundle !== 'function') throw new TypeError('pluginManager.installBundle is required')
183
+ if (!manager || typeof manager.removeBundle !== 'function') throw new TypeError('pluginManager.removeBundle is required')
184
+ if (!registry || typeof registry.release !== 'function') throw new TypeError('a registry client is required')
185
+
186
+ const state = { checkedAt: 0, checking: false, rows: [], job: null, desktopUpdate: null }
187
+ const abort = new AbortController()
188
+ const queueSettings = { ...QUEUE_DEFAULTS, ...queue }
189
+ let checkPromise = null
190
+ let checkNames = new Set()
191
+
192
+ const sleep = (ms) => new Promise((resolve) => {
193
+ const timer = setTimeout(resolve, ms)
194
+ timer.unref?.()
195
+ })
196
+
197
+ const DESKTOP_UPDATE_BLOCKING = new Set(['available', 'downloading', 'verifying', 'installing', 'ready'])
198
+ function desktopBlocked() {
199
+ const phase = state.desktopUpdate?.phase
200
+ return typeof phase === 'string' && DESKTOP_UPDATE_BLOCKING.has(phase)
201
+ }
202
+ function setDesktopUpdate(info) {
203
+ state.desktopUpdate = {
204
+ phase: typeof info?.phase === 'string' ? info.phase : 'unknown',
205
+ version: typeof info?.version === 'string' ? info.version : null,
206
+ }
207
+ return snapshot()
208
+ }
209
+
210
+ const now = () => clock()
211
+ const log = (level, ...args) => {
212
+ const write = logger?.[level]
213
+ if (typeof write === 'function') write.call(logger, ...args)
214
+ }
215
+
216
+ /**
217
+ * Read every installed profile bundle's manifest once and invert client
218
+ * injections: a plugin another plugin injects is a provider whose update can
219
+ * strand its dependents on a missing client service.
220
+ */
221
+ async function analyzeRisks(bundles) {
222
+ const manifests = new Map()
223
+ if (typeof profileDir === 'string' && profileDir !== '') {
224
+ for (const bundle of bundles) {
225
+ if (!bundle || bundle.installed !== true || bundle.availability !== 'profile') continue
226
+ if (typeof bundle.name !== 'string') continue
227
+ manifests.set(bundle.name, await readJson(join(profileDir, 'node_modules', bundle.name, 'package.json')))
228
+ }
229
+ }
230
+ const dependents = new Map()
231
+ for (const [name, manifest] of manifests) {
232
+ const inject = manifest?.dsh?.client?.inject
233
+ if (!Array.isArray(inject)) continue
234
+ for (const dependency of inject) {
235
+ if (typeof dependency !== 'string') continue
236
+ const provider = stripClientSuffix(dependency)
237
+ if (provider === name || !manifests.has(provider)) continue
238
+ if (!dependents.has(provider)) dependents.set(provider, new Set())
239
+ dependents.get(provider).add(name)
240
+ }
241
+ }
242
+ return { manifests, dependents }
243
+ }
244
+
245
+ async function verifyOnce(row) {
246
+ const bundles = await manager.listBundles()
247
+ const bundle = Array.isArray(bundles) ? bundles.find((entry) => entry?.name === row.name) : undefined
248
+ if (!bundle || bundle.installed !== true) return { ok: false, reason: 'bundle-missing' }
249
+ if (bundle.version !== row.latest) return { ok: false, reason: 'version-mismatch' }
250
+ if (bundle.enabled !== row.enabled) return { ok: false, reason: 'enabled-mismatch' }
251
+ if (bundle.error !== undefined) return { ok: false, reason: bundle.error?.code ?? 'bundle-error' }
252
+ if (row.enabled === true && typeof manager.listPlugins === 'function') {
253
+ const plugins = await manager.listPlugins()
254
+ if (Array.isArray(plugins)) {
255
+ for (const entry of bundle.rows ?? []) {
256
+ const found = plugins.find((plugin) => plugin?.entryId === entry.entryId)
257
+ if (found && found.enabled === true && found.fiberPhase !== 'active') {
258
+ return { ok: false, reason: 'row-inactive', entryId: entry.entryId, phase: found.fiberPhase }
259
+ }
260
+ }
261
+ }
262
+ }
263
+ if (typeof profileDir !== 'string' || profileDir === '') return { ok: true }
264
+ const dir = join(profileDir, 'node_modules', row.name)
265
+ const manifest = await readJson(join(dir, 'package.json'))
266
+ if (manifest === null) return { ok: false, reason: 'manifest-unreadable' }
267
+ if (manifest.version !== row.latest) return { ok: false, reason: 'manifest-version-mismatch' }
268
+ const entry = entryFileOf(manifest)
269
+ if (entry !== null && !existsSync(join(dir, entry))) return { ok: false, reason: 'entry-missing' }
270
+ const patch = manifest.dsh?.bundle?.patch
271
+ if (typeof patch === 'string' && !existsSync(join(dir, patch))) return { ok: false, reason: 'patch-missing' }
272
+ return { ok: true }
273
+ }
274
+
275
+ /** Give the fresh rows a short moment to settle before judging activation. */
276
+ async function verifyInstall(row) {
277
+ let result = { ok: false, reason: 'unknown' }
278
+ for (let attempt = 0; attempt < 4; attempt += 1) {
279
+ result = await verifyOnce(row)
280
+ if (result.ok) return result
281
+ if (attempt < 3) await new Promise((resolve) => setTimeout(resolve, 400))
282
+ }
283
+ return result
284
+ }
285
+
286
+ function snapshot() {
287
+ const updates = state.rows
288
+ .filter((row) => row.available === true && row.compatible === true)
289
+ .map((row) => ({
290
+ name: row.name,
291
+ version: row.version,
292
+ latest: row.latest,
293
+ enabled: row.enabled,
294
+ description: row.description,
295
+ publishedAt: row.publishedAt,
296
+ bootCritical: row.bootCritical === true,
297
+ dependents: row.dependents ?? [],
298
+ clientDeps: row.clientDeps ?? [],
299
+ hasClient: row.hasClient === true,
300
+ }))
301
+ return {
302
+ checkedAt: state.checkedAt,
303
+ checking: state.checking,
304
+ checkingNames: [...checkNames],
305
+ updates,
306
+ checked: state.rows.length,
307
+ desktopUpdate: state.desktopUpdate === null ? null : { ...state.desktopUpdate },
308
+ job: state.job === null ? null : structuredClone(state.job),
309
+ }
310
+ }
311
+
312
+ async function checkCandidate(candidate, environment, analysis) {
313
+ const manifest = analysis?.manifests.get(candidate.name)
314
+ const client = manifest?.dsh?.client
315
+ const clientDeps = Array.isArray(client?.inject) ? client.inject : []
316
+ const dependents = [...(analysis?.dependents.get(candidate.name) ?? [])]
317
+ const bootCritical = client?.immediately === true || candidate.name === '@dsh-plugin/dsh-loader'
318
+ const hasClient = client !== undefined && client !== null
319
+ try {
320
+ const release = await registry.release(candidate.name, abort.signal)
321
+ const evaluation = evaluateManifest(release.version, release.manifest, environment)
322
+ const available = evaluation.compatible === true && compareVersions(release.version, candidate.version) === 1
323
+ return {
324
+ ...candidate,
325
+ latest: release.version,
326
+ registry: release.registry,
327
+ integrity: evaluation.integrity ?? null,
328
+ publishedAt: evaluation.publishedAt ?? null,
329
+ available,
330
+ compatible: evaluation.compatible === true,
331
+ reason: evaluation.reason ?? null,
332
+ error: null,
333
+ bootCritical,
334
+ clientDeps,
335
+ dependents,
336
+ hasClient,
337
+ checkedAt: now(),
338
+ }
339
+ } catch (error) {
340
+ abort.signal.throwIfAborted()
341
+ log('warn', 'registry check failed for %s:', candidate.name, errorCode(error))
342
+ return {
343
+ ...candidate,
344
+ latest: null,
345
+ registry: null,
346
+ integrity: null,
347
+ publishedAt: null,
348
+ available: false,
349
+ compatible: false,
350
+ reason: null,
351
+ error: errorCode(error),
352
+ bootCritical,
353
+ clientDeps,
354
+ dependents,
355
+ hasClient,
356
+ checkedAt: now(),
357
+ }
358
+ }
359
+ }
360
+
361
+ async function runCheck() {
362
+ const bundles = await manager.listBundles()
363
+ const environment = {
364
+ runtimeVersion: runtimeVersion(bundles),
365
+ nodeVersion: process.versions.node,
366
+ }
367
+ const analysis = await analyzeRisks(bundles)
368
+ const candidates = selectCandidates(bundles)
369
+ const rows = []
370
+ for (let index = 0; index < candidates.length; index += CONCURRENCY) {
371
+ const chunk = candidates.slice(index, index + CONCURRENCY)
372
+ rows.push(...await Promise.all(chunk.map((candidate) => checkCandidate(candidate, environment, analysis))))
373
+ }
374
+ state.rows = rows.sort((left, right) => left.name.localeCompare(right.name))
375
+ state.checkedAt = now()
376
+ return snapshot()
377
+ }
378
+
379
+ async function check({ force = false } = {}) {
380
+ abort.signal.throwIfAborted()
381
+ if (state.job !== null && ['queued', 'starting', 'running'].includes(state.job.state)) throw coded('busy')
382
+ if (state.checking && checkPromise !== null) return checkPromise
383
+ if (force !== true && state.checkedAt > 0 && now() - state.checkedAt < CHECK_TTL) return snapshot()
384
+ state.checking = true
385
+ checkNames = new Set()
386
+ checkPromise = (async () => {
387
+ try {
388
+ return await runCheck()
389
+ } finally {
390
+ state.checking = false
391
+ checkPromise = null
392
+ checkNames = new Set()
393
+ }
394
+ })()
395
+ return checkPromise
396
+ }
397
+
398
+ async function rollback(row) {
399
+ try {
400
+ const result = await manager.installBundle(`${row.name}@${row.version}`, {
401
+ enabled: row.enabled,
402
+ saveExact: true,
403
+ ...row.registry === null || row.registry === undefined ? {} : { registry: row.registry },
404
+ })
405
+ return { ok: successful(result), error: result?.error?.code ?? null }
406
+ } catch (error) {
407
+ log('warn', 'rollback failed for %s:', row.name, errorCode(error))
408
+ return { ok: false, error: errorCode(error) }
409
+ }
410
+ }
411
+
412
+ async function record(job, entry) {
413
+ job.results.push(entry)
414
+ try {
415
+ await backup?.history?.({ jobId: job.id, ...entry, at: now() })
416
+ } catch {
417
+ // History is diagnostic only.
418
+ }
419
+ }
420
+
421
+ async function updateOne(job, row) {
422
+ job.current = { name: row.name, from: row.version, to: row.latest, phase: 'verifying' }
423
+ let removed = false
424
+ try {
425
+ const fresh = await registry.release(row.name, abort.signal, { version: row.latest })
426
+ if (fresh.version !== row.latest || fresh.manifest?.dist?.integrity !== row.integrity) throw coded('release-changed')
427
+ // The previous version must still be obtainable, otherwise a failed
428
+ // install has no safe rollback target and the update must not start.
429
+ if (typeof registry.manifest === 'function') {
430
+ const previous = await registry.manifest(row.name, row.version, abort.signal, row.registry ?? undefined).catch(() => null)
431
+ if (previous === null || previous.manifest?.dsh?.bundle === undefined) throw coded('rollback-unavailable')
432
+ }
433
+ job.current = { ...job.current, phase: 'removing' }
434
+ const removal = await manager.removeBundle(row.name)
435
+ if (removal?.error) throw coded(removal.error.code ?? 'remove-failed')
436
+ removed = true
437
+ job.current = { ...job.current, phase: 'installing' }
438
+ const result = await manager.installBundle(`${row.name}@${row.latest}`, {
439
+ enabled: row.enabled,
440
+ saveExact: true,
441
+ ...row.registry === null || row.registry === undefined ? {} : { registry: row.registry },
442
+ requestId: `${job.id}:${row.name}`,
443
+ })
444
+ if (!successful(result)) {
445
+ const rollbackResult = await rollback(row)
446
+ await record(job, {
447
+ name: row.name,
448
+ from: row.version,
449
+ to: row.latest,
450
+ ok: false,
451
+ error: result?.error?.code ?? 'install-failed',
452
+ application: result?.application ?? null,
453
+ rollback: rollbackResult,
454
+ })
455
+ throw coded('install-failed')
456
+ }
457
+ // A package can install "successfully" yet leave a broken row, a
458
+ // truncated node_modules entry, or a missing bundle patch. Verify the
459
+ // observable state before telling the user the update is ready.
460
+ job.current = { ...job.current, phase: 'verifying-install' }
461
+ const verification = await verifyInstall(row)
462
+ if (verification.ok !== true) {
463
+ const rollbackResult = await rollback(row)
464
+ await record(job, {
465
+ name: row.name,
466
+ from: row.version,
467
+ to: row.latest,
468
+ ok: false,
469
+ error: 'verification-failed',
470
+ verification,
471
+ rollback: rollbackResult,
472
+ })
473
+ throw coded('verification-failed')
474
+ }
475
+ const restartRequired = result.application === 'restart-required'
476
+ if (restartRequired) job.restartRequired = true
477
+ await record(job, {
478
+ name: row.name,
479
+ from: row.version,
480
+ to: row.latest,
481
+ ok: true,
482
+ restartRequired,
483
+ hasClient: row.hasClient === true,
484
+ bootCritical: row.bootCritical === true,
485
+ verification,
486
+ rollback: null,
487
+ })
488
+ row.available = false
489
+ } catch (error) {
490
+ if (!job.results.some((entry) => entry.name === row.name)) {
491
+ const rollbackResult = removed ? await rollback(row) : null
492
+ await record(job, {
493
+ name: row.name,
494
+ from: row.version,
495
+ to: row.latest,
496
+ ok: false,
497
+ error: errorCode(error),
498
+ application: null,
499
+ rollback: rollbackResult,
500
+ })
501
+ }
502
+ throw error
503
+ }
504
+ }
505
+
506
+ function createJob(selected, jobState) {
507
+ return {
508
+ id: randomUUID(),
509
+ state: jobState,
510
+ total: selected.length,
511
+ done: 0,
512
+ current: null,
513
+ items: selected.map((row) => ({
514
+ name: row.name,
515
+ from: row.version,
516
+ to: row.latest,
517
+ description: row.description,
518
+ enabled: row.enabled,
519
+ bootCritical: row.bootCritical === true,
520
+ dependents: row.dependents ?? [],
521
+ hasClient: row.hasClient === true,
522
+ })),
523
+ results: [],
524
+ failure: null,
525
+ restartRequired: false,
526
+ reloadRequired: false,
527
+ snapshotDir: null,
528
+ waitingFor: null,
529
+ countdownEndsAt: null,
530
+ startedAt: now(),
531
+ finishedAt: null,
532
+ }
533
+ }
534
+
535
+ async function prepareSnapshot(job, selected) {
536
+ if (backup === null || backup === undefined) return
537
+ try {
538
+ const snapshot = await backup.create({
539
+ jobId: job.id,
540
+ runtimeVersion: runtimeVersion(await manager.listBundles()),
541
+ plugins: selected.map((row) => ({ name: row.name, from: row.version, to: row.latest, enabled: row.enabled })),
542
+ })
543
+ if (!snapshot || typeof snapshot.dir !== 'string') throw new Error('snapshot-missing')
544
+ job.snapshotDir = snapshot.dir
545
+ } catch (error) {
546
+ log('error', 'profile snapshot failed:', errorCode(error))
547
+ throw coded('snapshot-failed')
548
+ }
549
+ }
550
+
551
+ /**
552
+ * Restart wins over reload: a full restart reloads the page too, so the UI
553
+ * never asks for both. A boot-tier client plugin is treated as restart-only
554
+ * because a failed reload of that tier leaves a dead window.
555
+ */
556
+ function summarize(job) {
557
+ const successes = job.results.filter((entry) => entry.ok === true)
558
+ const bootClient = successes.some((entry) => entry.bootCritical === true && entry.hasClient === true)
559
+ job.restartRequired = job.restartRequired === true || bootClient
560
+ job.reloadRequired = job.restartRequired !== true && successes.some((entry) => entry.hasClient === true)
561
+ }
562
+
563
+ async function runJob(job, selected) {
564
+ try {
565
+ for (const row of selected) {
566
+ await updateOne(job, row)
567
+ job.done += 1
568
+ }
569
+ job.state = 'done'
570
+ } catch (error) {
571
+ job.state = 'failed'
572
+ job.failure = errorCode(error)
573
+ log('warn', 'plugin update stopped:', job.failure)
574
+ } finally {
575
+ job.finishedAt = now()
576
+ if (job.current !== null) job.current = { ...job.current, phase: 'finished' }
577
+ summarize(job)
578
+ // The next open re-checks so the list reflects the new versions.
579
+ state.checkedAt = 0
580
+ }
581
+ }
582
+
583
+ async function launch(job, selected) {
584
+ try {
585
+ await prepareSnapshot(job, selected)
586
+ } catch (error) {
587
+ job.state = 'failed'
588
+ job.failure = errorCode(error)
589
+ job.finishedAt = now()
590
+ state.checkedAt = 0
591
+ return
592
+ }
593
+ job.state = 'running'
594
+ job.startedAt = now()
595
+ await runJob(job, selected)
596
+ }
597
+
598
+ /**
599
+ * Wait until every conversation and background job is idle for the quiet
600
+ * window, then run. A new task during the countdown sends the job back to
601
+ * queued instead of starting under a live session.
602
+ */
603
+ async function runQueue(job, selected) {
604
+ const { pollMs, quietMs, countdownMs } = queueSettings
605
+ let idleSince = null
606
+ for (;;) {
607
+ await sleep(pollMs)
608
+ if (job.cancelled === true || state.job !== job) return
609
+ let guard
610
+ try { guard = await activity() } catch { guard = { known: false, busy: true } }
611
+ job.waitingFor = {
612
+ known: guard?.known === true,
613
+ busy: guard?.busy === true,
614
+ desktop: desktopBlocked(),
615
+ agents: Number.isSafeInteger(guard?.agents) ? guard.agents : 0,
616
+ jobs: Number.isSafeInteger(guard?.jobs) ? guard.jobs : 0,
617
+ }
618
+ if (guard?.known !== true || guard?.busy === true || desktopBlocked()) {
619
+ idleSince = null
620
+ continue
621
+ }
622
+ if (idleSince === null) {
623
+ idleSince = now()
624
+ continue
625
+ }
626
+ if (now() - idleSince < quietMs) continue
627
+ job.state = 'starting'
628
+ job.countdownEndsAt = now() + countdownMs
629
+ await sleep(countdownMs)
630
+ if (job.cancelled === true || state.job !== job) return
631
+ let recheck
632
+ try { recheck = await activity() } catch { recheck = { known: false, busy: true } }
633
+ if (recheck?.known !== true || recheck?.busy === true) {
634
+ job.state = 'queued'
635
+ job.countdownEndsAt = null
636
+ idleSince = null
637
+ continue
638
+ }
639
+ job.countdownEndsAt = null
640
+ await launch(job, selected)
641
+ return
642
+ }
643
+ }
644
+
645
+ async function start(names, options = {}) {
646
+ abort.signal.throwIfAborted()
647
+ if (state.job !== null && ['queued', 'starting', 'running'].includes(state.job.state)) throw coded('busy')
648
+ if (state.checking) throw coded('busy')
649
+ if (!Array.isArray(names) || names.length === 0 || names.length > 64) throw coded('invalid-request')
650
+ const byName = new Map(state.rows.filter((row) => row.available === true).map((row) => [row.name, row]))
651
+ const selected = []
652
+ for (const name of names) {
653
+ if (typeof name !== 'string') throw coded('invalid-request')
654
+ const row = byName.get(name)
655
+ if (row === undefined) throw coded('check-first')
656
+ if (!selected.includes(row)) selected.push(row)
657
+ }
658
+ if (selected.length === 0) throw coded('invalid-request')
659
+ if (desktopBlocked()) throw coded('dsh-update')
660
+ let guard
661
+ try {
662
+ guard = await activity()
663
+ } catch {
664
+ guard = { known: false, busy: true }
665
+ }
666
+ const busy = guard?.known === true && guard.busy === true
667
+ if (busy && options.waitForIdle !== true) throw coded('busy-session')
668
+ const job = createJob(selected, busy ? 'queued' : 'running')
669
+ if (busy) {
670
+ job.waitingFor = { known: true, busy: true, agents: guard.agents ?? 0, jobs: guard.jobs ?? 0 }
671
+ state.job = job
672
+ void runQueue(job, selected)
673
+ return snapshot()
674
+ }
675
+ await prepareSnapshot(job, selected)
676
+ state.job = job
677
+ void runJob(job, selected)
678
+ return snapshot()
679
+ }
680
+
681
+ function cancel() {
682
+ const job = state.job
683
+ if (job === null || job === undefined) return snapshot()
684
+ if (job.state === 'running') throw coded('busy')
685
+ job.cancelled = true
686
+ job.state = 'cancelled'
687
+ job.countdownEndsAt = null
688
+ job.finishedAt = now()
689
+ return snapshot()
690
+ }
691
+
692
+ /**
693
+ * Mark the page reload for one finished job as performed. Without this the
694
+ * client would see the same completed job after every reload and refresh
695
+ * again forever.
696
+ */
697
+ function acknowledgeReload(jobId) {
698
+ const job = state.job
699
+ if (job === null || job === undefined) return snapshot()
700
+ if (typeof jobId === 'string' && job.id !== jobId) return snapshot()
701
+ job.reloadRequired = false
702
+ job.reloadedAt = now()
703
+ return snapshot()
704
+ }
705
+
706
+ function dismiss() {
707
+ if (state.job?.state === 'running') throw coded('busy')
708
+ state.job = null
709
+ return snapshot()
710
+ }
711
+
712
+ async function dispose() {
713
+ abort.abort()
714
+ if (checkPromise !== null) await checkPromise.catch(() => {})
715
+ if (state.job !== null && state.job !== undefined) {
716
+ state.job.cancelled = true
717
+ if (state.job.state === 'running') {
718
+ state.job.state = 'failed'
719
+ state.job.failure = 'disposed'
720
+ }
721
+ }
722
+ }
723
+
724
+ return {
725
+ check,
726
+ start,
727
+ cancel,
728
+ dismiss,
729
+ acknowledgeReload,
730
+ setDesktopUpdate,
731
+ snapshot,
732
+ dispose,
733
+ get state() {
734
+ return state
735
+ },
736
+ }
737
+ }