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

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