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/client.js ADDED
@@ -0,0 +1,1174 @@
1
+ /**
2
+ * Client half of the plugin update center.
3
+ *
4
+ * Renders one entry in the sidebar foot (the official `sidebar.footer.action`
5
+ * seat next to Settings / the DSH update indicator), a DSH `Modal` listing the
6
+ * available plugin updates, and a progress bar while the Host applies them.
7
+ */
8
+
9
+ window.__ModuleLoader__.load({
10
+ id: 'dsh-plugin-update-center',
11
+ factory(require) {
12
+ const React = require('react')
13
+ const { createPortal } = require('react-dom')
14
+ const UI = require('@deepseek-ai/dsh-client-ui-primitives')
15
+ const h = React.createElement
16
+ const { useState, useEffect, useRef } = React
17
+
18
+ const NS = 'dsh-plugin-update-center'
19
+ const ROUTE = new URL('api/dsh-plugin-update-center', document.baseURI)
20
+
21
+ const zh = {
22
+ 'action.label': '插件更新',
23
+ 'action.tooltip': '{count} 个插件可更新',
24
+ 'action.running': '正在更新 {done}/{total}',
25
+ 'panel.title': '插件更新',
26
+ 'panel.progressTitle': '正在更新插件',
27
+ 'panel.close': '关闭',
28
+ 'panel.cancel': '取消',
29
+ 'panel.update': '更新 {count} 个插件',
30
+ 'panel.background': '后台运行',
31
+ 'panel.done': '完成',
32
+ 'list.summary': '发现 {count} 个可更新插件',
33
+ 'list.lastChecked': '上次检查 {time}',
34
+ 'list.recheck': '重新检查',
35
+ 'list.checking': '正在检查…',
36
+ 'list.disabled': '已停用',
37
+ 'list.empty': '所有插件都是最新版本',
38
+ 'check.checking': '正在检查插件更新…',
39
+ 'check.failed': '检查失败:{code}',
40
+ 'check.retry': '重试',
41
+ 'progress.current': '正在更新 {name}({done}/{total})',
42
+ 'progress.waiting': '准备更新…',
43
+ 'phase.verifying': '核对版本',
44
+ 'phase.removing': '移除旧版',
45
+ 'phase.installing': '安装新版',
46
+ 'phase.finished': '完成',
47
+ 'status.waiting': '等待',
48
+ 'status.done': '已更新',
49
+ 'status.restart': '待重启',
50
+ 'status.failed': '失败',
51
+ 'done.restart': '新版本已安装,重启 DSH 后生效。',
52
+ 'done.refresh': '更新已安装;如界面仍是旧版本,请刷新页面或重启 DSH。',
53
+ 'done.snapshot': '更新前快照:{path}',
54
+ 'risk.boot': '启动关键',
55
+ 'risk.provider': '被 {count} 个插件依赖',
56
+ 'risk.unselected': '{count} 个启动关键 / 被依赖插件未勾选。请单独更新它们,并在更新后立即重启验证。',
57
+ 'risk.warning': '选中的插件包含启动关键项。更新后请立即重启验证;若 DSH 无法打开,在错误对话框点「禁用第三方插件、备份 profile patch 并重启」,或运行 repair.cmd 恢复快照。',
58
+ 'done.summary': '已更新 {count} 个插件',
59
+ 'done.stopped': '更新在 {name} 处停止',
60
+ 'done.rollbackOk': '已自动回滚到旧版本。',
61
+ 'done.rollbackFailed': '回滚未完成,请到「插件」管理页手动检查。',
62
+ 'error.busy': '已有更新任务正在进行,请稍候。',
63
+ 'error.busy-session': '有会话正在运行,请等任务结束后再更新。',
64
+ 'error.check-first': '更新列表已过期,请重新检查。',
65
+ 'error.release-changed': '版本信息在检查后发生变化,已停止更新。',
66
+ 'error.invalid-request': '请求无效。',
67
+ 'error.registry-unavailable': '无法连接 npm registry。',
68
+ 'error.request-too-large': '请求内容过大。',
69
+ 'error.operation-failed': '操作未完成,请重试。',
70
+ 'error.service-unavailable': '更新服务不可用,请刷新页面。',
71
+ 'error.snapshot-failed': '无法创建 profile 快照,已取消本次更新。',
72
+ 'error.rollback-unavailable': '旧版本在 registry 中已不可用,无法安全回滚,已取消。',
73
+ 'error.verification-failed': '安装后校验失败,已自动回滚到旧版本。',
74
+ 'error.dsh-update': 'DSH 本体有更新,先完成 DSH 更新再更新插件。',
75
+ 'action.waiting': '等待任务完成',
76
+ 'queue.offer': '有任务正在运行。可以在任务完成后自动开始更新。',
77
+ 'queue.button': '任务完成后自动更新',
78
+ 'queue.title': '等待任务完成',
79
+ 'queue.waiting': '等待任务完成({agents} 个对话 / {jobs} 个后台任务)',
80
+ 'queue.waitingDesktop': '等待 DSH 本体更新完成',
81
+ 'queue.starting': '任务已完成,{seconds} 秒后开始更新',
82
+ 'queue.cancel': '取消排队',
83
+ 'desktop.blocked': 'DSH 本体有更新({phase}),先完成 DSH 更新再更新插件。',
84
+ 'refresh.countdown': '更新完成,{seconds} 秒后自动刷新页面',
85
+ 'refresh.cancel': '取消',
86
+ 'refresh.needed': '需要刷新页面才能加载新版本。',
87
+ 'refresh.now': '刷新页面',
88
+ 'refresh.done': '页面已刷新,新版本已加载。',
89
+ 'residue.title': '卸载残留',
90
+ 'residue.tooltip': '{count} 项卸载残留',
91
+ 'residue.summary': '发现 {count} 项可能由卸载遗留的引用',
92
+ 'residue.selection': 'profile 里多出的插件选择',
93
+ 'residue.patch': 'cordis.patch.yml 里的失效引用',
94
+ 'residue.data': '可能遗留的数据目录',
95
+ 'residue.cleanable': '可清理',
96
+ 'residue.manual': '需手动确认',
97
+ 'residue.note': '清理悬空的插件选择和失效的补丁条目(自动备份 profile);数据目录不会自动删除。',
98
+ 'residue.clean': '清理',
99
+ 'residue.cleaned': '已清理 {count} 项',
100
+ 'residue.scan': '重新扫描',
101
+ 'residue.line': '第 {line} 行',
102
+ }
103
+
104
+ const en = {
105
+ 'action.label': 'Plugin updates',
106
+ 'action.tooltip': '{count} plugin updates available',
107
+ 'action.running': 'Updating {done}/{total}',
108
+ 'panel.title': 'Plugin updates',
109
+ 'panel.progressTitle': 'Updating plugins',
110
+ 'panel.close': 'Close',
111
+ 'panel.cancel': 'Cancel',
112
+ 'panel.update': 'Update {count} plugins',
113
+ 'panel.background': 'Run in background',
114
+ 'panel.done': 'Done',
115
+ 'list.summary': '{count} updates available',
116
+ 'list.lastChecked': 'Checked {time}',
117
+ 'list.recheck': 'Check again',
118
+ 'list.checking': 'Checking…',
119
+ 'list.disabled': 'Disabled',
120
+ 'list.empty': 'All plugins are up to date',
121
+ 'check.checking': 'Checking for plugin updates…',
122
+ 'check.failed': 'Check failed: {code}',
123
+ 'check.retry': 'Retry',
124
+ 'progress.current': 'Updating {name} ({done}/{total})',
125
+ 'progress.waiting': 'Preparing…',
126
+ 'phase.verifying': 'Verifying release',
127
+ 'phase.removing': 'Removing previous version',
128
+ 'phase.installing': 'Installing new version',
129
+ 'phase.finished': 'Finished',
130
+ 'status.waiting': 'Waiting',
131
+ 'status.done': 'Updated',
132
+ 'status.restart': 'Restart needed',
133
+ 'status.failed': 'Failed',
134
+ 'done.restart': 'New versions are installed. Restart DSH to load them.',
135
+ 'done.refresh': 'Updates are installed. Refresh the page or restart DSH if the UI still shows the old version.',
136
+ 'done.snapshot': 'Pre-update snapshot: {path}',
137
+ 'risk.boot': 'Boot-critical',
138
+ 'risk.provider': 'Used by {count} plugins',
139
+ 'risk.unselected': '{count} boot-critical / depended-on plugins are not selected. Update them one at a time and restart to verify.',
140
+ 'risk.warning': 'The selection includes boot-critical plugins. Restart and verify right after updating; if DSH will not open, use “Disable third-party plugins” in the error dialog or run repair.cmd to restore the snapshot.',
141
+ 'done.summary': '{count} plugins updated',
142
+ 'done.stopped': 'Update stopped at {name}',
143
+ 'done.rollbackOk': 'The previous version was restored automatically.',
144
+ 'done.rollbackFailed': 'Restore did not finish. Check the Plugins page.',
145
+ 'error.busy': 'Another update is already running.',
146
+ 'error.busy-session': 'A session is running. Wait for it to finish before updating.',
147
+ 'error.check-first': 'This update list is stale. Check again.',
148
+ 'error.release-changed': 'Release metadata changed after the check. Nothing was installed.',
149
+ 'error.invalid-request': 'Invalid request.',
150
+ 'error.registry-unavailable': 'The npm registry is unreachable.',
151
+ 'error.request-too-large': 'The request was too large.',
152
+ 'error.operation-failed': 'The operation did not finish. Try again.',
153
+ 'error.service-unavailable': 'The update service is unavailable. Refresh the page.',
154
+ 'error.snapshot-failed': 'A profile snapshot could not be created, so the update was cancelled.',
155
+ 'error.rollback-unavailable': 'The previous release is no longer available on the registry, so a safe rollback is impossible. Cancelled.',
156
+ 'error.verification-failed': 'Post-install verification failed; the previous version was restored.',
157
+ 'error.dsh-update': 'DSH itself has an update. Finish the DSH update before updating plugins.',
158
+ 'action.waiting': 'Waiting for tasks',
159
+ 'queue.offer': 'A task is running. You can start the update automatically after it finishes.',
160
+ 'queue.button': 'Update after tasks finish',
161
+ 'queue.title': 'Waiting for tasks',
162
+ 'queue.waiting': 'Waiting for tasks ({agents} conversations / {jobs} background jobs)',
163
+ 'queue.waitingDesktop': 'Waiting for the DSH update to finish',
164
+ 'queue.starting': 'Tasks finished. Starting in {seconds}s',
165
+ 'queue.cancel': 'Cancel queue',
166
+ 'desktop.blocked': 'DSH has an update ({phase}). Finish the DSH update before updating plugins.',
167
+ 'refresh.countdown': 'Update complete. Refreshing the page in {seconds}s',
168
+ 'refresh.cancel': 'Cancel',
169
+ 'refresh.needed': 'Refresh the page to load the new version.',
170
+ 'refresh.now': 'Refresh page',
171
+ 'refresh.done': 'The page was refreshed and the new version is loaded.',
172
+ 'residue.title': 'Uninstall leftovers',
173
+ 'residue.tooltip': '{count} uninstall leftovers',
174
+ 'residue.summary': '{count} references may be left over from uninstalls',
175
+ 'residue.selection': 'Extra plugin selections in the profile',
176
+ 'residue.patch': 'Dangling cordis.patch.yml references',
177
+ 'residue.data': 'Possible leftover data directories',
178
+ 'residue.cleanable': 'Safe to clean',
179
+ 'residue.manual': 'Review manually',
180
+ 'residue.note': 'Dangling selections and broken patch rows are removed with a profile snapshot as backup; data directories are never deleted automatically.',
181
+ 'residue.clean': 'Clean',
182
+ 'residue.cleaned': 'Cleaned {count} items',
183
+ 'residue.scan': 'Scan again',
184
+ 'residue.line': 'line {line}',
185
+ }
186
+
187
+ const STYLE = [
188
+ '.dshpu-rowHost{display:inline-flex;flex:none;align-items:center;gap:4px;min-width:0}',
189
+ '.dshpu-chip{box-sizing:border-box;display:inline-grid;grid-template-columns:14px max-content;align-items:center;column-gap:4px;height:28px;padding:0 8px;border:1px solid color-mix(in srgb, var(--dsw-alias-brand-primary-new-colorprimary-new-color,#4176e6) 20%, transparent);border-radius:var(--dsw-radius-sm,8px);color:var(--dsw-alias-brand-primary-new-colorprimary-new-color,#4176e6);background:color-mix(in srgb, var(--dsw-alias-brand-primary-new-colorprimary-new-color,#4176e6) 8%, transparent);font-family:inherit;font-size:12px;font-weight:500;line-height:18px;white-space:nowrap;cursor:pointer;flex:none}',
190
+ '.dshpu-chip:hover{background:color-mix(in srgb, var(--dsw-alias-brand-primary-new-colorprimary-new-color,#4176e6) 14%, transparent)}',
191
+ '.dshpu-chip.is-residue{border-color:color-mix(in srgb, var(--dsw-alias-state-warn-primary,#b26a00) 25%, transparent);color:var(--dsw-alias-state-warn-primary,#b26a00);background:color-mix(in srgb, var(--dsw-alias-state-warn-primary,#b26a00) 8%, transparent)}',
192
+ '.dshpu-chip.is-residue:hover{background:color-mix(in srgb, var(--dsw-alias-state-warn-primary,#b26a00) 14%, transparent)}',
193
+ '.dshpu-chip:focus-visible{outline:var(--dsw-focus-ring-width,2px) solid var(--dsw-focus-ring-color,var(--dsw-alias-state-business-primary,#4d6bfe));outline-offset:2px}',
194
+ '.dshpu-chipIcon{display:grid;place-items:center;width:14px;height:14px}',
195
+ '.dshpu-chipText{font-variant-numeric:tabular-nums}',
196
+ '.dshpu-spin{animation:dshpu-rotate 1s linear infinite}',
197
+ '@keyframes dshpu-rotate{to{transform:rotate(360deg)}}',
198
+ '.dshpu-body{display:flex;flex-direction:column;gap:14px;min-height:160px}',
199
+ '.dshpu-summary{display:flex;align-items:center;justify-content:space-between;gap:12px;font-size:12px;line-height:18px;color:var(--dsw-alias-label-secondary,#657080)}',
200
+ '.dshpu-summaryText{min-width:0}',
201
+ '.dshpu-link{display:inline-flex;align-items:center;gap:4px;border:0;background:none;color:var(--dsw-alias-label-secondary,#657080);font:inherit;font-size:12px;line-height:18px;cursor:pointer;border-radius:6px;padding:2px 6px;flex:none}',
202
+ '.dshpu-link:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover,#f0f1f3);color:var(--dsw-alias-label-primary,#202124)}',
203
+ '.dshpu-link:disabled{opacity:.5;cursor:default}',
204
+ '.dshpu-list{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;max-height:min(46vh,360px);overflow:auto}',
205
+ '.dshpu-row{display:flex;align-items:flex-start;gap:10px;padding:10px 8px;border-radius:8px}',
206
+ '.dshpu-row:hover{background:var(--dsw-alias-interactive-bg-hover,#f0f1f3)}',
207
+ '.dshpu-row+.dshpu-row{border-top:1px solid var(--dsw-alias-border-l1,#eceef2)}',
208
+ '.dshpu-row label>span:empty{display:none}',
209
+ '.dshpu-rowMain{min-width:0;flex:1;display:flex;flex-direction:column;gap:2px}',
210
+ '.dshpu-name{font-size:13px;line-height:18px;color:var(--dsw-alias-label-primary,#202124);overflow-wrap:anywhere}',
211
+ '.dshpu-desc{font-size:12px;line-height:16px;color:var(--dsw-alias-label-tertiary,#8a94a6);overflow:hidden;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical}',
212
+ '.dshpu-risk{margin-top:2px;font-size:11px;line-height:16px;color:var(--dsw-alias-state-warn-primary,#b26a00)}',
213
+ '.dshpu-versions{display:flex;align-items:center;gap:4px;flex:none;font-family:var(--dsh-font-mono,ui-monospace,SFMono-Regular,Menlo,monospace);font-size:12px;line-height:18px;color:var(--dsw-alias-label-secondary,#657080);white-space:nowrap;padding-top:1px}',
214
+ '.dshpu-latest{color:var(--dsw-alias-brand-primary-new-colorprimary-new-color,#4176e6)}',
215
+ '.dshpu-status{flex:none;font-size:12px;line-height:18px;color:var(--dsw-alias-label-tertiary,#8a94a6);white-space:nowrap;padding-top:1px}',
216
+ '.dshpu-status[data-tone="success"]{color:var(--dsw-alias-state-success-primary,#1a8a4a)}',
217
+ '.dshpu-status[data-tone="error"]{color:var(--dsw-alias-state-error-primary,#d93025)}',
218
+ '.dshpu-status[data-tone="busy"]{color:var(--dsw-alias-brand-primary-new-colorprimary-new-color,#4176e6)}',
219
+ '.dshpu-progress{display:flex;flex-direction:column;gap:8px}',
220
+ '.dshpu-progressHead{display:flex;align-items:baseline;justify-content:space-between;gap:12px;font-size:12px;line-height:18px;color:var(--dsw-alias-label-secondary,#657080)}',
221
+ '.dshpu-progressName{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
222
+ '.dshpu-percent{flex:none;font-variant-numeric:tabular-nums;color:var(--dsw-alias-label-secondary,#657080)}',
223
+ '.dshpu-bar{height:6px;border-radius:999px;background:var(--dsw-alias-bg-layer-2,#eceef2);overflow:hidden;position:relative}',
224
+ '.dshpu-barFill{height:100%;border-radius:999px;background:var(--dsw-alias-brand-primary-new-colorprimary-new-color,#4176e6);transition:width .35s ease}',
225
+ '.dshpu-barFill.is-indeterminate{width:38%;animation:dshpu-slide 1.1s ease-in-out infinite}',
226
+ '@keyframes dshpu-slide{0%{transform:translateX(-110%)}100%{transform:translateX(360%)}}',
227
+ '.dshpu-note{display:flex;gap:8px;align-items:flex-start;border:1px solid var(--dsw-alias-border-l1,#eceef2);border-radius:10px;padding:10px 12px;font-size:12px;line-height:18px;color:var(--dsw-alias-label-secondary,#657080);background:var(--dsw-alias-bg-layer-2,#f7f8fa)}',
228
+ '.dshpu-note svg{flex:none;margin-top:1px}',
229
+ '.dshpu-note[data-tone="error"]{border-color:var(--dsw-alias-state-error-primary,#d93025);color:var(--dsw-alias-state-error-primary,#d93025)}',
230
+ '.dshpu-note[data-tone="warn"]{border-color:color-mix(in srgb, var(--dsw-alias-state-warn-primary,#b26a00) 45%, transparent);color:var(--dsw-alias-state-warn-primary,#b26a00)}',
231
+ '.dshpu-note[data-tone="success"]{color:var(--dsw-alias-state-success-primary,#1a8a4a)}',
232
+ '.dshpu-noteText{min-width:0;word-break:break-word}',
233
+ '.dshpu-group{margin:2px 0 0;font-size:12px;line-height:18px;font-weight:500;color:var(--dsw-alias-label-secondary,#657080)}',
234
+ '.dshpu-mono{font-family:var(--dsh-font-mono,ui-monospace,SFMono-Regular,Menlo,monospace)}',
235
+ '.dshpu-actions{display:flex;justify-content:flex-end;align-items:center;gap:8px;width:100%}',
236
+ '.dshpu-footerError{flex:1;min-width:0;margin-right:8px;font-size:12px;line-height:18px;color:var(--dsw-alias-state-error-primary,#d93025);text-align:left;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
237
+ '.dshpu-modal.dshpu-modal{width:560px;max-width:calc(100vw - 48px)}',
238
+ '@media (prefers-reduced-motion: reduce){.dshpu-spin{animation:none}.dshpu-barFill{transition:none}}',
239
+ ].join('')
240
+
241
+ function createStore(initial) {
242
+ let state = initial
243
+ const listeners = new Set()
244
+ return {
245
+ get: () => state,
246
+ set(next) {
247
+ state = next
248
+ for (const listener of [...listeners]) listener()
249
+ },
250
+ subscribe(listener) {
251
+ listeners.add(listener)
252
+ return () => listeners.delete(listener)
253
+ },
254
+ }
255
+ }
256
+
257
+ function errorCodeOf(error) {
258
+ const message = typeof error?.message === 'string' ? error.message : ''
259
+ return /^[a-z][a-z0-9-]{1,63}$/.test(message) ? message : 'service-unavailable'
260
+ }
261
+
262
+ function percentOf(job) {
263
+ if (job === null || job === undefined) return 0
264
+ if (job.total <= 0) return 0
265
+ if (job.state === 'done') return 100
266
+ const weight = job.current?.phase === 'verifying' ? 0.05
267
+ : job.current?.phase === 'removing' ? 0.35
268
+ : job.current?.phase === 'installing' ? 0.65
269
+ : 0
270
+ const value = Math.round(((job.done + weight) / job.total) * 100)
271
+ return Math.max(0, Math.min(job.state === 'running' ? 99 : 100, value))
272
+ }
273
+
274
+ function apply(ctx) {
275
+ const store = createStore({ snapshot: null, residue: null, loading: true, checking: false, error: null })
276
+ let disposed = false
277
+ let timer = null
278
+ let lastCheckAttempt = 0
279
+ let started = false
280
+
281
+ ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'dsh-plugin-update-center: dictionaries')
282
+ const t = ctx.locale.bind(NS)
283
+
284
+ function useLocaleTick() {
285
+ const [, force] = useState(0)
286
+ useEffect(() => {
287
+ const stop = ctx.locale.subscribe(() => force((value) => value + 1))
288
+ return () => { if (typeof stop === 'function') stop() }
289
+ }, [])
290
+ }
291
+
292
+ function message(code) {
293
+ const known = /^(busy|busy-session|check-first|release-changed|invalid-request|registry-unavailable|request-too-large|operation-failed|service-unavailable|snapshot-failed|rollback-unavailable|verification-failed|dsh-update)$/
294
+ return t(known.test(code) ? 'error.' + code : 'error.operation-failed')
295
+ }
296
+
297
+ async function api(body) {
298
+ const controller = new AbortController()
299
+ const timeout = setTimeout(() => controller.abort(), body.action === 'check' ? 90000 : 30000)
300
+ try {
301
+ const response = await fetch(ROUTE, {
302
+ method: 'POST',
303
+ credentials: 'same-origin',
304
+ cache: 'no-store',
305
+ signal: controller.signal,
306
+ headers: { 'content-type': 'application/json', 'x-dsh-plugin-update-center': '1' },
307
+ body: JSON.stringify(body),
308
+ })
309
+ const data = await response.json().catch(() => null)
310
+ if (!response.ok || data === null || data.ok !== true) throw new Error(data?.code ?? 'service-unavailable')
311
+ return data.value
312
+ } catch (error) {
313
+ if (error?.name === 'AbortError') throw new Error('service-unavailable')
314
+ throw error
315
+ } finally {
316
+ clearTimeout(timeout)
317
+ }
318
+ }
319
+
320
+ function publish(patch) {
321
+ if (disposed) return
322
+ store.set({ ...store.get(), ...patch })
323
+ }
324
+
325
+ async function refresh() {
326
+ try {
327
+ const [snapshot, residue] = await Promise.all([
328
+ api({ action: 'state' }),
329
+ api({ action: 'residue' }).catch(() => null),
330
+ ])
331
+ publish({
332
+ snapshot,
333
+ ...residue === null ? {} : { residue },
334
+ loading: false,
335
+ error: null,
336
+ })
337
+ maybeCheck(snapshot)
338
+ } catch (error) {
339
+ publish({ loading: false, error: errorCodeOf(error) })
340
+ }
341
+ }
342
+
343
+ function maybeCheck(snapshot) {
344
+ if (disposed || snapshot === null || snapshot === undefined) return
345
+ if (['queued', 'starting', 'running'].includes(snapshot.job?.state)) return
346
+ if (snapshot.checking) return
347
+ if (store.get().checking) return
348
+ const stale = snapshot.checkedAt === 0 || Date.now() - snapshot.checkedAt > 30 * 60 * 1000
349
+ if (!stale) return
350
+ if (Date.now() - lastCheckAttempt < 60000) return
351
+ lastCheckAttempt = Date.now()
352
+ void checkUpdates(false)
353
+ }
354
+
355
+ async function checkUpdates(force) {
356
+ if (disposed || store.get().checking) return
357
+ publish({ checking: true, error: null })
358
+ try {
359
+ const snapshot = await api({ action: 'check', force: force === true })
360
+ publish({ snapshot, checking: false, loading: false, error: null })
361
+ } catch (error) {
362
+ publish({ checking: false, loading: false, error: errorCodeOf(error) })
363
+ }
364
+ schedule()
365
+ }
366
+
367
+ async function startUpdates(names, waitForIdle) {
368
+ const snapshot = await api({ action: 'start', names, waitForIdle: waitForIdle === true })
369
+ publish({ snapshot, error: null })
370
+ schedule()
371
+ }
372
+
373
+ async function cancelQueued() {
374
+ try {
375
+ const snapshot = await api({ action: 'cancel' })
376
+ publish({ snapshot })
377
+ } catch {
378
+ // The next state read reconciles a stale cancel.
379
+ }
380
+ }
381
+
382
+ async function cleanResidue() {
383
+ const value = await api({ action: 'clean-residue' })
384
+ publish({ residue: value.residue })
385
+ return value
386
+ }
387
+
388
+ async function refreshResidue() {
389
+ try {
390
+ const residue = await api({ action: 'residue' })
391
+ publish({ residue })
392
+ } catch {
393
+ // The next periodic refresh retries.
394
+ }
395
+ }
396
+
397
+ const RELOAD_MARKER_PREFIX = 'dsh-plugin-update-center:reloaded:'
398
+
399
+ function hasReloadMarker(jobId) {
400
+ if (typeof jobId !== 'string') return false
401
+ try {
402
+ return globalThis.sessionStorage?.getItem(RELOAD_MARKER_PREFIX + jobId) === '1'
403
+ } catch {
404
+ return false
405
+ }
406
+ }
407
+
408
+ function writeReloadMarker(jobId) {
409
+ if (typeof jobId !== 'string') return
410
+ try {
411
+ globalThis.sessionStorage?.setItem(RELOAD_MARKER_PREFIX + jobId, '1')
412
+ } catch {
413
+ // Storage can be unavailable; the Host ack is the durable guard.
414
+ }
415
+ }
416
+
417
+ async function acknowledgeReload(jobId) {
418
+ try {
419
+ const snapshot = await api({ action: 'reload-ack', jobId })
420
+ publish({ snapshot })
421
+ } catch {
422
+ // Retried on the next state refresh.
423
+ }
424
+ }
425
+
426
+ function acknowledgeReloadSoon(jobId) {
427
+ if (typeof jobId !== 'string') return
428
+ try {
429
+ fetch(ROUTE, {
430
+ method: 'POST',
431
+ credentials: 'same-origin',
432
+ keepalive: true,
433
+ headers: { 'content-type': 'application/json', 'x-dsh-plugin-update-center': '1' },
434
+ body: JSON.stringify({ action: 'reload-ack', jobId }),
435
+ }).catch(() => {})
436
+ } catch {
437
+ // The session marker still prevents a loop.
438
+ }
439
+ }
440
+
441
+ async function dismissJob() {
442
+ try {
443
+ const snapshot = await api({ action: 'dismiss' })
444
+ publish({ snapshot })
445
+ } catch {
446
+ // A stale dismiss is harmless; the next state read reconciles it.
447
+ }
448
+ }
449
+
450
+ function schedule() {
451
+ if (disposed) return
452
+ if (timer !== null) clearTimeout(timer)
453
+ const fast = ['queued', 'starting', 'running'].includes(store.get().snapshot?.job?.state)
454
+ timer = setTimeout(async () => {
455
+ timer = null
456
+ await refresh()
457
+ schedule()
458
+ }, fast ? 700 : 30000)
459
+ }
460
+
461
+ function useStoreValue() {
462
+ const [value, setValue] = useState(store.get())
463
+ useEffect(() => store.subscribe(() => setValue(store.get())), [])
464
+ return value
465
+ }
466
+
467
+ function phaseLabel(phase) {
468
+ return t('phase.' + (phase === 'verifying' || phase === 'removing' || phase === 'installing' || phase === 'finished' ? phase : 'finished'))
469
+ }
470
+
471
+ function StatusNote({ tone = 'info', icon, children }) {
472
+ return h('div', { className: 'dshpu-note', 'data-tone': tone },
473
+ icon,
474
+ h('div', { className: 'dshpu-noteText' }, children),
475
+ )
476
+ }
477
+
478
+ function UpdateRow({ name, description, from, to, disabled, status, tone, showCheckbox, checked, onToggle, bootCritical, dependents }) {
479
+ const risks = []
480
+ if (bootCritical === true) risks.push(t('risk.boot'))
481
+ if ((dependents?.length ?? 0) > 0) risks.push(t('risk.provider', { count: dependents.length }))
482
+ return h('li', { className: 'dshpu-row' },
483
+ showCheckbox
484
+ ? h(UI.Checkbox, {
485
+ checked,
486
+ disabled,
487
+ onChange: onToggle,
488
+ })
489
+ : null,
490
+ h('div', { className: 'dshpu-rowMain' },
491
+ h('div', { className: 'dshpu-name' }, name),
492
+ description ? h('div', { className: 'dshpu-desc' }, description) : null,
493
+ risks.length > 0 ? h('div', { className: 'dshpu-risk' }, risks.join(' · ')) : null,
494
+ ),
495
+ h('div', { className: 'dshpu-versions' },
496
+ h('span', null, from),
497
+ h(UI.IconChevronRightOutlineRegular, { size: 12 }),
498
+ h('span', { className: 'dshpu-latest' }, to),
499
+ ),
500
+ status !== undefined
501
+ ? h('div', { className: 'dshpu-status', 'data-tone': tone ?? 'idle' }, status)
502
+ : null,
503
+ )
504
+ }
505
+
506
+ function ProgressView({ job, refresh }) {
507
+ const [, setTick] = useState(0)
508
+ const waiting = job.state === 'queued' || job.state === 'starting'
509
+ const needsReload = refresh?.needsReload === true
510
+ const refreshCancelled = refresh?.cancelled === true
511
+ const refreshSeconds = refresh?.seconds ?? 0
512
+
513
+ useEffect(() => {
514
+ if (job.state !== 'starting') return
515
+ const ticker = setInterval(() => setTick((value) => value + 1), 250)
516
+ return () => clearInterval(ticker)
517
+ }, [job.state])
518
+
519
+ const phaseText = job.waitingFor?.desktop === true
520
+ ? t('queue.waitingDesktop')
521
+ : t('queue.waiting', { agents: job.waitingFor?.agents ?? 0, jobs: job.waitingFor?.jobs ?? 0 })
522
+ const countdown = job.countdownEndsAt === null || job.countdownEndsAt === undefined
523
+ ? 0
524
+ : Math.max(0, Math.ceil((job.countdownEndsAt - Date.now()) / 1000))
525
+ const current = job.current
526
+ const label = waiting
527
+ ? phaseText
528
+ : job.state === 'running'
529
+ ? current === null
530
+ ? t('progress.waiting')
531
+ : t('progress.current', { name: current.name, done: job.done, total: job.total })
532
+ : job.state === 'done'
533
+ ? t('done.summary', { count: job.done })
534
+ : t('done.stopped', { name: current?.name ?? '' })
535
+ const percent = percentOf(job)
536
+ const failed = job.results.find((entry) => entry.ok !== true)
537
+ const failureText = failed === undefined
538
+ ? null
539
+ : t('done.stopped', { name: failed.name }) + ':' + message(failed.error ?? 'operation-failed')
540
+ const rollbackText = failed?.rollback == null
541
+ ? ''
542
+ : ' ' + (failed.rollback.ok === true ? t('done.rollbackOk') : t('done.rollbackFailed'))
543
+
544
+ return h(React.Fragment, null,
545
+ waiting
546
+ ? h(StatusNote, { tone: 'info', icon: h(UI.IconClockOutlineRegular, { size: 16 }) }, phaseText)
547
+ : h('div', { className: 'dshpu-progress' },
548
+ h('div', { className: 'dshpu-progressHead' },
549
+ h('div', { className: 'dshpu-progressName' }, label),
550
+ job.state === 'done' ? h('div', { className: 'dshpu-percent' }, '100%') : null,
551
+ ),
552
+ h('div', {
553
+ className: 'dshpu-bar',
554
+ role: 'progressbar',
555
+ 'aria-valuemin': 0,
556
+ 'aria-valuemax': 100,
557
+ 'aria-valuenow': Math.round(percent),
558
+ 'aria-label': label,
559
+ }, h('div', { className: 'dshpu-barFill', style: { width: percent + '%' } })),
560
+ job.state === 'running' && current !== null
561
+ ? h('div', { className: 'dshpu-summary' }, h('span', { className: 'dshpu-summaryText' }, phaseLabel(current.phase)))
562
+ : null,
563
+ ),
564
+ job.state === 'starting'
565
+ ? h(StatusNote, { tone: 'info', icon: h(UI.IconClockOutlineRegular, { size: 16 }) },
566
+ t('queue.starting', { seconds: countdown }))
567
+ : null,
568
+ h('ul', { className: 'dshpu-list' },
569
+ (job.items ?? []).map((item) => {
570
+ const result = job.results.find((entry) => entry.name === item.name)
571
+ const isCurrent = job.state === 'running' && current?.name === item.name
572
+ const status = result !== undefined
573
+ ? result.ok === true
574
+ ? result.restartRequired === true ? t('status.restart') : t('status.done')
575
+ : t('status.failed')
576
+ : isCurrent
577
+ ? phaseLabel(current.phase)
578
+ : t('status.waiting')
579
+ const tone = result !== undefined
580
+ ? result.ok === true ? 'success' : 'error'
581
+ : isCurrent ? 'busy' : 'idle'
582
+ return h(UpdateRow, {
583
+ key: item.name,
584
+ name: item.name,
585
+ description: item.description,
586
+ from: item.from,
587
+ to: item.to,
588
+ status,
589
+ tone,
590
+ showCheckbox: false,
591
+ })
592
+ }),
593
+ ),
594
+ job.state === 'failed' && failureText !== null
595
+ ? h(StatusNote, { tone: 'error', icon: h(UI.IconWarningOutlineMedium, { size: 16 }) },
596
+ failureText + rollbackText)
597
+ : null,
598
+ job.state === 'done'
599
+ ? h(StatusNote, { tone: 'success', icon: h(UI.IconCheckCircleOutlineRegular, { size: 16 }) },
600
+ t('done.summary', { count: job.done }))
601
+ : null,
602
+ // Restart wins over reload: a full restart reloads the page too.
603
+ job.state === 'done' && job.restartRequired === true
604
+ ? h(StatusNote, { tone: 'info', icon: h(UI.IconInfoOutlineRegular, { size: 16 }) }, t('done.restart'))
605
+ : null,
606
+ job.state === 'done' && refresh?.reloaded === true
607
+ ? h(StatusNote, { tone: 'info', icon: h(UI.IconRefreshOutlineRegular, { size: 16 }) }, t('refresh.done'))
608
+ : null,
609
+ needsReload && refreshCancelled !== true
610
+ ? h(StatusNote, { tone: 'info', icon: h(UI.IconRefreshOutlineRegular, { size: 16 }) },
611
+ t('refresh.countdown', { seconds: refreshSeconds }),
612
+ h('button', {
613
+ type: 'button',
614
+ className: 'dshpu-link',
615
+ onClick: () => refresh?.cancel?.(),
616
+ }, t('refresh.cancel')))
617
+ : null,
618
+ needsReload && refreshCancelled === true
619
+ ? h(StatusNote, { tone: 'info', icon: h(UI.IconRefreshOutlineRegular, { size: 16 }) },
620
+ t('refresh.needed'),
621
+ h('button', {
622
+ type: 'button',
623
+ className: 'dshpu-link',
624
+ onClick: () => { window.location.reload() },
625
+ }, t('refresh.now')))
626
+ : null,
627
+ (job.state === 'done' || job.state === 'failed' || job.state === 'cancelled') && typeof job.snapshotDir === 'string'
628
+ ? h(StatusNote, { tone: 'info', icon: h(UI.IconInfoOutlineRegular, { size: 16 }) },
629
+ t('done.snapshot', { path: job.snapshotDir }))
630
+ : null,
631
+ )
632
+ }
633
+
634
+ function ListView({ state, updates, selected, toggle, busy, queueOffer, desktopBlocked, desktopPhase }) {
635
+ const snapshot = state.snapshot
636
+ const checking = state.checking || snapshot?.checking === true
637
+ const checkedAt = snapshot?.checkedAt
638
+ const risky = (item) => item.bootCritical === true || (item.dependents?.length ?? 0) > 0
639
+ const riskySelected = updates.filter((item) => selected.has(item.name) && risky(item))
640
+ const riskyUnselected = updates.filter((item) => !selected.has(item.name) && risky(item))
641
+ return h('div', { className: 'dshpu-body' },
642
+ h('div', { className: 'dshpu-summary' },
643
+ h('div', { className: 'dshpu-summaryText' },
644
+ updates.length > 0 ? t('list.summary', { count: updates.length }) : t('list.empty'),
645
+ checkedAt ? h('span', null, ' · ', t('list.lastChecked', { time: new Date(checkedAt).toLocaleTimeString() })) : null,
646
+ ),
647
+ h('button', {
648
+ type: 'button',
649
+ className: 'dshpu-link',
650
+ disabled: checking,
651
+ onClick: () => { void checkUpdates(true) },
652
+ },
653
+ h(UI.IconRefreshOutlineRegular, { size: 14 }),
654
+ checking ? t('list.checking') : t('list.recheck'),
655
+ ),
656
+ ),
657
+ desktopBlocked === true
658
+ ? h(StatusNote, { tone: 'warn', icon: h(UI.IconWarningOutlineMedium, { size: 16 }) },
659
+ t('desktop.blocked', { phase: desktopPhase }))
660
+ : null,
661
+ queueOffer === true
662
+ ? h(StatusNote, { tone: 'info', icon: h(UI.IconClockOutlineRegular, { size: 16 }) },
663
+ t('queue.offer'))
664
+ : null,
665
+ riskyUnselected.length > 0
666
+ ? h(StatusNote, { tone: 'warn', icon: h(UI.IconWarningOutlineMedium, { size: 16 }) },
667
+ t('risk.unselected', { count: riskyUnselected.length }))
668
+ : null,
669
+ riskySelected.length > 0
670
+ ? h(StatusNote, { tone: 'warn', icon: h(UI.IconWarningOutlineMedium, { size: 16 }) },
671
+ t('risk.warning'))
672
+ : null,
673
+ updates.length > 0
674
+ ? h('ul', { className: 'dshpu-list' },
675
+ updates.map((item) => h(UpdateRow, {
676
+ key: item.name,
677
+ name: item.name,
678
+ description: item.description,
679
+ from: item.version,
680
+ to: item.latest,
681
+ disabled: busy,
682
+ showCheckbox: true,
683
+ checked: selected.has(item.name),
684
+ onToggle: (checked) => toggle(item.name, checked),
685
+ status: item.enabled === false ? t('list.disabled') : undefined,
686
+ tone: 'idle',
687
+ bootCritical: item.bootCritical,
688
+ dependents: item.dependents,
689
+ })),
690
+ )
691
+ : null,
692
+ state.error !== null && state.error !== undefined
693
+ ? h(StatusNote, { tone: 'error', icon: h(UI.IconWarningOutlineMedium, { size: 16 }) },
694
+ t('check.failed', { code: state.error }))
695
+ : null,
696
+ )
697
+ }
698
+
699
+ function EmptyOrLoading({ state }) {
700
+ if (state.error !== null) {
701
+ return h('div', { className: 'dshpu-body' },
702
+ h(StatusNote, { tone: 'error', icon: h(UI.IconWarningOutlineMedium, { size: 16 }) },
703
+ t('check.failed', { code: state.error })),
704
+ h('div', { className: 'dshpu-actions' },
705
+ h(UI.Button, { variant: 'outline', onClick: () => { void checkUpdates(true) } }, t('check.retry')),
706
+ ),
707
+ )
708
+ }
709
+ return h('div', { className: 'dshpu-body' },
710
+ h('div', { className: 'dshpu-summary' },
711
+ h('div', { className: 'dshpu-summaryText' }, t('check.checking')),
712
+ ),
713
+ h('div', { className: 'dshpu-progress' },
714
+ h('div', { className: 'dshpu-bar' },
715
+ h('div', { className: 'dshpu-barFill is-indeterminate' }),
716
+ ),
717
+ ),
718
+ )
719
+ }
720
+
721
+ function UpdatePanel({ open, onClose, refresh }) {
722
+ const state = useStoreValue()
723
+ const snapshot = state.snapshot
724
+ const job = snapshot?.job ?? null
725
+ const jobState = job?.state
726
+ const showJob = job !== null && (['queued', 'starting', 'running'].includes(jobState) || (job.results?.length ?? 0) > 0)
727
+ const checking = state.checking || snapshot?.checking === true
728
+ const updates = snapshot?.updates ?? []
729
+ const namesKey = updates.map((item) => item.name).join('|')
730
+ const desktopPhase = snapshot?.desktopUpdate?.phase
731
+ const desktopBlocked = typeof desktopPhase === 'string'
732
+ && ['available', 'downloading', 'verifying', 'installing', 'ready'].includes(desktopPhase)
733
+ const [selected, setSelected] = useState(() => new Set())
734
+ const [busy, setBusy] = useState(false)
735
+ const [actionError, setActionError] = useState(null)
736
+ const [queueOffer, setQueueOffer] = useState(false)
737
+
738
+ useLocaleTick()
739
+
740
+ useEffect(() => {
741
+ if (showJob) return
742
+ // Boot-critical plugins and providers other plugins inject are left
743
+ // unchecked: updating them alone can strand dependents on a missing
744
+ // client service and make the next DSH window fail to boot.
745
+ setSelected(new Set(updates
746
+ .filter((item) => item.bootCritical !== true && (item.dependents?.length ?? 0) === 0)
747
+ .map((item) => item.name)))
748
+ // eslint-disable-next-line react-hooks/exhaustive-deps
749
+ }, [namesKey, showJob, open])
750
+
751
+ useEffect(() => {
752
+ if (open !== true) setQueueOffer(false)
753
+ }, [open])
754
+
755
+ function toggle(name, checked) {
756
+ setSelected((current) => {
757
+ const next = new Set(current)
758
+ if (checked) next.add(name)
759
+ else next.delete(name)
760
+ return next
761
+ })
762
+ }
763
+
764
+ async function submit(waitForIdle) {
765
+ const names = [...selected]
766
+ if (names.length === 0) return
767
+ setBusy(true)
768
+ setActionError(null)
769
+ try {
770
+ await startUpdates(names, waitForIdle === true)
771
+ setQueueOffer(false)
772
+ } catch (error) {
773
+ const code = errorCodeOf(error)
774
+ if (code === 'busy-session' && waitForIdle !== true) {
775
+ setQueueOffer(true)
776
+ setActionError(null)
777
+ } else {
778
+ setActionError(code)
779
+ }
780
+ } finally {
781
+ setBusy(false)
782
+ }
783
+ }
784
+
785
+ const handleClose = () => {
786
+ if (job !== null && !['running', 'queued', 'starting'].includes(job.state)) void dismissJob()
787
+ onClose()
788
+ }
789
+
790
+ const loading = snapshot === null || snapshot === undefined || (checking && updates.length === 0)
791
+ let body
792
+ if (showJob) body = h(ProgressView, { job, refresh })
793
+ else if (loading) body = h(EmptyOrLoading, { state })
794
+ else body = h(ListView, { state, updates, selected, toggle, busy, queueOffer, desktopBlocked, desktopPhase })
795
+
796
+ const queueWaiting = showJob && (job.state === 'queued' || job.state === 'starting')
797
+ const footer = h('div', { className: 'dshpu-actions' },
798
+ actionError !== null
799
+ ? h('div', { className: 'dshpu-footerError' }, message(actionError))
800
+ : null,
801
+ showJob && job.state === 'running'
802
+ ? h(UI.Button, { variant: 'outline', onClick: handleClose }, t('panel.background'))
803
+ : null,
804
+ queueWaiting
805
+ ? h(UI.Button, { variant: 'outline', onClick: () => { void cancelQueued() } }, t('queue.cancel'))
806
+ : null,
807
+ showJob && !queueWaiting && job.state !== 'running'
808
+ ? h(UI.Button, { variant: 'primary', onClick: handleClose }, t('panel.done'))
809
+ : null,
810
+ !showJob
811
+ ? h(UI.Button, { variant: 'outline', onClick: handleClose }, t('panel.cancel'))
812
+ : null,
813
+ !showJob && updates.length > 0
814
+ ? h(UI.Button, {
815
+ variant: 'primary',
816
+ disabled: busy || checking || selected.size === 0 || desktopBlocked,
817
+ onClick: () => { void submit(queueOffer) },
818
+ }, queueOffer ? t('queue.button') : t('panel.update', { count: selected.size }))
819
+ : null,
820
+ )
821
+
822
+ const title = showJob
823
+ ? queueWaiting ? t('queue.title') : t('panel.progressTitle')
824
+ : t('panel.title')
825
+
826
+ return h(UI.Modal, {
827
+ open,
828
+ onClose: handleClose,
829
+ title,
830
+ closeLabel: t('panel.close'),
831
+ footer,
832
+ className: 'dshpu-modal',
833
+ contentClassName: 'dshpu-modalContent',
834
+ },
835
+ h('style', null, STYLE),
836
+ body,
837
+ )
838
+ }
839
+
840
+ function ResiduePanel({ open, onClose }) {
841
+ const state = useStoreValue()
842
+ const residue = state.residue
843
+ const items = residue?.items ?? []
844
+ const cleanable = residue?.cleanable ?? 0
845
+ const [busy, setBusy] = useState(false)
846
+ const [cleaned, setCleaned] = useState(null)
847
+ const [error, setError] = useState(null)
848
+ useLocaleTick()
849
+
850
+ const groups = [
851
+ ['selection', t('residue.selection')],
852
+ ['patch', t('residue.patch')],
853
+ ['data', t('residue.data')],
854
+ ]
855
+
856
+ async function run() {
857
+ if (busy) return
858
+ setBusy(true)
859
+ setError(null)
860
+ try {
861
+ const value = await cleanResidue()
862
+ setCleaned(value.cleaned?.length ?? 0)
863
+ } catch (cause) {
864
+ setError(errorCodeOf(cause))
865
+ } finally {
866
+ setBusy(false)
867
+ }
868
+ }
869
+
870
+ const footer = h('div', { className: 'dshpu-actions' },
871
+ error !== null ? h('div', { className: 'dshpu-footerError' }, message(error)) : null,
872
+ h(UI.Button, { variant: 'outline', onClick: () => { void refreshResidue() } }, t('residue.scan')),
873
+ h(UI.Button, { variant: 'outline', onClick: onClose }, t('panel.close')),
874
+ h(UI.Button, {
875
+ variant: 'primary',
876
+ disabled: busy || cleanable === 0,
877
+ onClick: () => { void run() },
878
+ }, t('residue.clean')),
879
+ )
880
+
881
+ return h(UI.Modal, {
882
+ open,
883
+ onClose,
884
+ title: t('residue.title'),
885
+ closeLabel: t('panel.close'),
886
+ footer,
887
+ className: 'dshpu-modal',
888
+ contentClassName: 'dshpu-modalContent',
889
+ },
890
+ h('style', null, STYLE),
891
+ h('div', { className: 'dshpu-body' },
892
+ h('div', { className: 'dshpu-summary' },
893
+ h('div', { className: 'dshpu-summaryText' }, t('residue.summary', { count: items.length }))),
894
+ cleaned !== null
895
+ ? h(StatusNote, { tone: 'success', icon: h(UI.IconCheckCircleOutlineRegular, { size: 16 }) },
896
+ t('residue.cleaned', { count: cleaned }))
897
+ : null,
898
+ groups.map(([kind, title]) => {
899
+ const list = items.filter((item) => item.kind === kind)
900
+ if (list.length === 0) return null
901
+ return h('div', { key: kind },
902
+ h('div', { className: 'dshpu-group' }, title),
903
+ h('ul', { className: 'dshpu-list' },
904
+ list.map((item, index) => h('li', { className: 'dshpu-row', key: kind + ':' + index },
905
+ h('div', { className: 'dshpu-rowMain' },
906
+ h('div', { className: 'dshpu-name' }, item.name),
907
+ kind === 'patch'
908
+ ? h('div', { className: 'dshpu-desc' },
909
+ t('residue.line', { line: item.line }) + (typeof item.text === 'string' ? ' · ' + item.text : ''))
910
+ : null,
911
+ kind === 'data'
912
+ ? h('div', { className: 'dshpu-desc' }, item.path)
913
+ : null,
914
+ ),
915
+ h('div', { className: 'dshpu-status' },
916
+ kind === 'data' ? t('residue.manual') : t('residue.cleanable')),
917
+ )),
918
+ ),
919
+ )
920
+ }),
921
+ h(StatusNote, { tone: 'info', icon: h(UI.IconInfoOutlineRegular, { size: 16 }) }, t('residue.note')),
922
+ ),
923
+ )
924
+ }
925
+
926
+ /**
927
+ * Keep one host span as a child of the sidebar account row, immediately
928
+ * after the account button. The row has no list slot, so the chip is
929
+ * portaled into the row the same way the shipped Desktop update chip
930
+ * lives there. The row is found by the module-stable `triggerRow` class
931
+ * suffix and the account button's stable `data-signed-out` attribute.
932
+ */
933
+ function useAccountRowHost() {
934
+ const [host, setHost] = useState(null)
935
+ useEffect(() => {
936
+ const node = document.createElement('span')
937
+ node.className = 'dshpu-rowHost'
938
+ let button = null
939
+ let rowObserver = null
940
+ let attributeObserver = null
941
+ let findTimer = null
942
+
943
+ const syncCollapsed = () => {
944
+ node.style.display = button?.getAttribute('data-collapsed') === 'true' ? 'none' : ''
945
+ }
946
+
947
+ const attach = () => {
948
+ const found = document.querySelector('button[data-signed-out]')
949
+ if (found === null) return false
950
+ const row = found.closest('[class*="_triggerRow"]')
951
+ if (row === null) return false
952
+ if (button !== found) {
953
+ attributeObserver?.disconnect()
954
+ button = found
955
+ attributeObserver = new MutationObserver(syncCollapsed)
956
+ attributeObserver.observe(button, { attributes: true, attributeFilter: ['data-collapsed'] })
957
+ syncCollapsed()
958
+ }
959
+ rowObserver?.disconnect()
960
+ rowObserver = new MutationObserver(() => {
961
+ if (!node.isConnected) attach()
962
+ })
963
+ rowObserver.observe(row, { childList: true })
964
+ if (node.parentElement !== row) row.insertBefore(node, row.children[1] ?? null)
965
+ setHost(node)
966
+ return true
967
+ }
968
+
969
+ if (!attach()) {
970
+ findTimer = setInterval(() => {
971
+ if (attach()) {
972
+ clearInterval(findTimer)
973
+ findTimer = null
974
+ }
975
+ }, 500)
976
+ }
977
+ const keepAlive = setInterval(() => {
978
+ if (!node.isConnected) attach()
979
+ }, 1500)
980
+
981
+ return () => {
982
+ clearInterval(findTimer)
983
+ clearInterval(keepAlive)
984
+ rowObserver?.disconnect()
985
+ attributeObserver?.disconnect()
986
+ node.remove()
987
+ setHost(null)
988
+ }
989
+ }, [])
990
+ return host
991
+ }
992
+
993
+ function AccountRowUpdate() {
994
+ useLocaleTick()
995
+ const state = useStoreValue()
996
+ const [open, setOpen] = useState(false)
997
+ const [openResidue, setOpenResidue] = useState(false)
998
+ const host = useAccountRowHost()
999
+ const snapshot = state.snapshot
1000
+ const updates = snapshot?.updates ?? []
1001
+ const job = snapshot?.job ?? null
1002
+ const phase = job?.state
1003
+ const running = phase === 'running'
1004
+ const waiting = phase === 'queued' || phase === 'starting'
1005
+ const count = updates.length
1006
+ const updateVisible = open || running || waiting || count > 0
1007
+ const residue = state.residue
1008
+ const residueCount = residue?.items?.length ?? 0
1009
+ const residueVisible = openResidue || residueCount > 0
1010
+ const reloadPending = job !== null && job.state === 'done' && job.reloadRequired === true && job.restartRequired !== true
1011
+ // A reload already happened for this job in this tab. Without this
1012
+ // guard the same completed job would trigger another reload forever.
1013
+ const alreadyReloaded = reloadPending && hasReloadMarker(job.id)
1014
+ const needsReload = reloadPending && alreadyReloaded !== true
1015
+ const [refreshCancelled, setRefreshCancelled] = useState(false)
1016
+ const [refreshSeconds, setRefreshSeconds] = useState(3)
1017
+
1018
+ useEffect(() => {
1019
+ setRefreshCancelled(false)
1020
+ setRefreshSeconds(3)
1021
+ }, [job?.id])
1022
+
1023
+ useEffect(() => {
1024
+ if (job === null || job.id === undefined) return
1025
+ if (reloadPending !== true || alreadyReloaded !== true) return
1026
+ // The page that performed the reload reports back once, clearing the
1027
+ // pending flag for every other window.
1028
+ void acknowledgeReload(job.id)
1029
+ }, [job?.id, reloadPending, alreadyReloaded])
1030
+
1031
+ useEffect(() => {
1032
+ if (needsReload !== true || refreshCancelled === true || job === null) return
1033
+ setRefreshSeconds(3)
1034
+ const ticker = setInterval(() => setRefreshSeconds((value) => Math.max(0, value - 1)), 1000)
1035
+ const reload = setTimeout(() => {
1036
+ writeReloadMarker(job.id)
1037
+ acknowledgeReloadSoon(job.id)
1038
+ window.location.reload()
1039
+ }, 3000)
1040
+ return () => {
1041
+ clearInterval(ticker)
1042
+ clearTimeout(reload)
1043
+ }
1044
+ }, [needsReload, refreshCancelled, job?.id])
1045
+
1046
+ const cancelRefresh = () => {
1047
+ setRefreshCancelled(true)
1048
+ if (job !== null && job.id !== undefined) {
1049
+ writeReloadMarker(job.id)
1050
+ void acknowledgeReload(job.id)
1051
+ }
1052
+ }
1053
+
1054
+ const refresh = {
1055
+ needsReload,
1056
+ cancelled: refreshCancelled,
1057
+ seconds: refreshSeconds,
1058
+ reloaded: reloadPending && alreadyReloaded,
1059
+ cancel: cancelRefresh,
1060
+ }
1061
+ const updateLabel = running
1062
+ ? t('action.running', { done: job.done, total: job.total })
1063
+ : waiting
1064
+ ? t('action.waiting')
1065
+ : count > 0
1066
+ ? t('action.tooltip', { count })
1067
+ : t('action.label')
1068
+ const residueLabel = t('residue.tooltip', { count: residueCount })
1069
+
1070
+ const chips = host !== null && (updateVisible || residueVisible)
1071
+ ? createPortal(
1072
+ h(React.Fragment, null,
1073
+ updateVisible
1074
+ ? h(UI.Tooltip, { label: updateLabel, side: 'top', align: 'end' },
1075
+ h('button', {
1076
+ type: 'button',
1077
+ className: 'dshpu-chip',
1078
+ 'aria-label': updateLabel,
1079
+ onClick: () => {
1080
+ setOpen(true)
1081
+ void refresh()
1082
+ },
1083
+ },
1084
+ h('span', { className: 'dshpu-chipIcon' },
1085
+ running
1086
+ ? h(UI.IconLoadingOutlineRegular, { size: 14, className: 'dshpu-spin' })
1087
+ : waiting
1088
+ ? h(UI.IconClockOutlineRegular, { size: 14 })
1089
+ : h(UI.IconDownloadOutlineRegular, { size: 14 }),
1090
+ ),
1091
+ h('span', { className: 'dshpu-chipText' },
1092
+ running ? job.done + '/' + job.total : String(waiting ? job.total : count)),
1093
+ ),
1094
+ )
1095
+ : null,
1096
+ residueVisible
1097
+ ? h(UI.Tooltip, { label: residueLabel, side: 'top', align: 'end' },
1098
+ h('button', {
1099
+ type: 'button',
1100
+ className: 'dshpu-chip is-residue',
1101
+ 'aria-label': residueLabel,
1102
+ onClick: () => {
1103
+ setOpenResidue(true)
1104
+ void refreshResidue()
1105
+ },
1106
+ },
1107
+ h('span', { className: 'dshpu-chipIcon' }, h(UI.IconTrashOutlineRegular, { size: 14 })),
1108
+ h('span', { className: 'dshpu-chipText' }, String(residueCount)),
1109
+ ),
1110
+ )
1111
+ : null,
1112
+ ),
1113
+ host,
1114
+ )
1115
+ : null
1116
+
1117
+ return h(React.Fragment, null,
1118
+ h('style', null, STYLE),
1119
+ chips,
1120
+ h(UpdatePanel, { open, onClose: () => setOpen(false), refresh }),
1121
+ h(ResiduePanel, { open: openResidue, onClose: () => setOpenResidue(false) }),
1122
+ )
1123
+ }
1124
+
1125
+ function bootstrap() {
1126
+ if (started || disposed) return
1127
+ started = true
1128
+ void refresh().then(() => {
1129
+ const snapshot = store.get().snapshot
1130
+ if (snapshot !== null && snapshot !== undefined) maybeCheck(snapshot)
1131
+ schedule()
1132
+ })
1133
+ }
1134
+
1135
+ ctx.slots.inject('shell.overlay', () => ctx.slots.register({
1136
+ name: 'shell.overlay',
1137
+ id: 'dsh-plugin-update-center',
1138
+ }, AccountRowUpdate))
1139
+
1140
+ ctx.effect(() => {
1141
+ bootstrap()
1142
+ return () => {
1143
+ disposed = true
1144
+ if (timer !== null) clearTimeout(timer)
1145
+ }
1146
+ }, 'dsh-plugin-update-center: client lifecycle')
1147
+
1148
+ ctx.effect(() => {
1149
+ const carrier = globalThis.dshDesktop
1150
+ const bridge = carrier?.protocolVersion === 1 ? carrier.updates : undefined
1151
+ if (bridge === undefined) return () => {}
1152
+ let alive = true
1153
+ const report = (presentation) => {
1154
+ if (!alive) return
1155
+ void api({
1156
+ action: 'desktop-update',
1157
+ phase: presentation?.phase ?? 'unknown',
1158
+ version: presentation?.version ?? null,
1159
+ }).then((snapshot) => {
1160
+ if (alive) publish({ snapshot })
1161
+ }).catch(() => {})
1162
+ }
1163
+ const unsubscribe = typeof bridge.subscribe === 'function' ? bridge.subscribe(report) : null
1164
+ if (typeof bridge.status === 'function') bridge.status().then(report, () => {})
1165
+ return () => {
1166
+ alive = false
1167
+ if (typeof unsubscribe === 'function') unsubscribe()
1168
+ }
1169
+ }, 'dsh-plugin-update-center: desktop update gate')
1170
+ }
1171
+
1172
+ return { inject: ['slots', 'locale'], apply }
1173
+ },
1174
+ })