dsh-app-controls 0.0.0-stage → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/client.js ADDED
@@ -0,0 +1,1476 @@
1
+ // Browser half of dsh-app-controls.
2
+ //
3
+ // Adds two small controls to the conversation header's right-aligned
4
+ // utilities row:
5
+ // - check / update DeepSeek Harness (opens a styled modal, then a progress
6
+ // dialog driven by the host's update job),
7
+ // - quit the local dsh web process (styled confirm, then closes the window
8
+ // after the service stops).
9
+ //
10
+ // Hand-written in the lazy-CJS bundle protocol (window.__ModuleLoader__.load
11
+ // with a factory returning Cordis-plugin exports), so no build step is needed.
12
+ // Only the shell's baseline `react` module is required at runtime.
13
+ window.__ModuleLoader__.load({
14
+ id: 'dsh-app-controls',
15
+ factory: (require) => {
16
+ var module = { exports: {} }
17
+ var exports = module.exports
18
+
19
+ const React = require('react')
20
+ const h = React.createElement
21
+
22
+ const SLOT = 'conversation.session.header.utilities'
23
+ const STATUS_ENDPOINT = 'api/dsh-app-controls/update'
24
+ const START_ENDPOINT = 'api/dsh-app-controls/update'
25
+ const PROGRESS_ENDPOINT = 'api/dsh-app-controls/update-progress'
26
+ const STATE_ENDPOINT = 'api/dsh-app-controls/state'
27
+ const SETTINGS_ENDPOINT = 'api/dsh-app-controls/settings'
28
+ const CACHE_ENDPOINT = 'api/dsh-app-controls/cache'
29
+ const CACHE_CLEAN_ENDPOINT = 'api/dsh-app-controls/cache/clean'
30
+ const QUIT_ENDPOINT = 'api/dsh-app-controls/quit'
31
+ const STYLE_ID = 'dsh-app-controls-style'
32
+ const MODAL_ID = 'dsh-app-controls-modal'
33
+ const EXIT_ID = 'dsh-app-controls-exit'
34
+ const CLOSE_HINT_ID = 'dsh-app-controls-close-hint'
35
+ const POLL_INTERVAL_MS = 800
36
+
37
+ let activeModal = null
38
+ let modalDismissible = false
39
+ let modalOnClose = null
40
+ let pollTimer = 0
41
+ let statePollTimer = 0
42
+
43
+ // ── small helpers ────────────────────────────────────────────────────────
44
+ function apiUrl(relative) {
45
+ return new URL(relative, document.baseURI).href
46
+ }
47
+
48
+ function errorMessage(error) {
49
+ if (error && typeof error === 'object' && typeof error.message === 'string') return error.message
50
+ return String(error)
51
+ }
52
+
53
+ async function readJson(response) {
54
+ try {
55
+ return await response.json()
56
+ } catch {
57
+ return null
58
+ }
59
+ }
60
+
61
+ function failureText(body, status) {
62
+ if (body && typeof body === 'object') {
63
+ if (typeof body.message === 'string' && body.message !== '') return body.message
64
+ if (typeof body.error === 'string' && body.error !== '') return body.error
65
+ }
66
+ return `HTTP ${status}`
67
+ }
68
+
69
+ function formatDuration(ms) {
70
+ const total = Math.max(0, Math.round(ms / 1000))
71
+ const minutes = Math.floor(total / 60)
72
+ const seconds = total % 60
73
+ if (minutes <= 0) return `${seconds} 秒`
74
+ return `${minutes} 分 ${String(seconds).padStart(2, '0')} 秒`
75
+ }
76
+
77
+ function formatBytes(bytes) {
78
+ const value = typeof bytes === 'number' && Number.isFinite(bytes) ? Math.max(0, bytes) : 0
79
+ if (value < 1024) return `${Math.round(value)} B`
80
+ const units = ['KB', 'MB', 'GB', 'TB']
81
+ let size = value / 1024
82
+ let unit = 0
83
+ while (size >= 1024 && unit < units.length - 1) {
84
+ size /= 1024
85
+ unit += 1
86
+ }
87
+ return `${size >= 100 ? size.toFixed(0) : size.toFixed(1)} ${units[unit]}`
88
+ }
89
+
90
+ // ── settings ─────────────────────────────────────────────────────────────
91
+ const SETTINGS_NS = 'dsh-app-controls'
92
+ const DEFAULT_SETTINGS = {
93
+ version: 1,
94
+ trayEnabled: true,
95
+ features: {
96
+ updateButton: true,
97
+ quitButton: true,
98
+ headerControls: true,
99
+ mainOverlay: true,
100
+ },
101
+ window: { width: 1400, height: 900 },
102
+ }
103
+ const SETTINGS_TEXT = {
104
+ zh: {
105
+ title: '应用控制设置',
106
+ intro: '设置保存在本机,下次启动 DSH 时自动生效;按钮显示/隐藏会立即生效。',
107
+ general: '常规',
108
+ buttons: '按钮显示',
109
+ window: '默认启动窗口大小',
110
+ trayEnabled: '系统托盘图标',
111
+ updateButton: '检查并更新按钮',
112
+ quitButton: '退出服务按钮',
113
+ headerControls: '对话标题栏入口',
114
+ mainOverlay: '主界面右上角入口',
115
+ windowNote: '宽度和高度留空或填 0 表示让 Chrome 记住;设置在下一次打开窗口时生效。',
116
+ width: '宽度',
117
+ height: '高度',
118
+ rememberCurrent: '记住当前窗口大小',
119
+ autoSize: '恢复自动',
120
+ currentWindow: '当前窗口',
121
+ cache: '缓存清理',
122
+ cacheIntro: '选择要清理的缓存类型。只删除可重新生成的缓存,不会删除运行中的 DSH、插件源码、设置、会话或登录状态。',
123
+ cacheNote: '清理后会重新生成,可能暂时增加一点加载时间;正在运行或正在使用的缓存会被自动跳过。',
124
+ cacheRefresh: '重新扫描',
125
+ cacheClean: '清理选中',
126
+ cacheSelectAll: '全选可清理项',
127
+ cacheScanning: '正在统计缓存…',
128
+ cacheNone: '暂无可清理的缓存。',
129
+ cacheSelected: '已选',
130
+ cacheFreed: '已释放',
131
+ cachePartial: '部分完成,已释放',
132
+ cacheFailed: '清理失败',
133
+ cacheScanFailed: '无法读取缓存信息',
134
+ cacheUnavailable: '不可用',
135
+ cacheCleaning: '清理中…',
136
+ cacheProtected: '已跳过正在使用的项',
137
+ cacheApp: '应用缓存',
138
+ cacheAppDetail: 'DSH 的附件图片缓存,可安全重建',
139
+ cacheNpx: 'npx 安装缓存',
140
+ cacheNpxDetail: '旧版临时安装;保留当前正在运行的版本',
141
+ cacheNpm: 'npm 下载缓存',
142
+ cacheNpmDetail: '下载的包缓存;下次安装时会重新下载',
143
+ cachePnpm: '卸载插件的缓存',
144
+ cachePnpmDetail: 'pnpm store 中未被任何项目引用的包;不会删除已安装插件',
145
+ cacheBackups: '更新残留',
146
+ cacheBackupsDetail: '7 天前的旧运行时备份和临时副本',
147
+ saved: '已保存',
148
+ saving: '保存中…',
149
+ saveFailed: '保存失败',
150
+ },
151
+ en: {
152
+ title: 'App controls settings',
153
+ intro: 'Saved locally and applied on the next DSH start; button visibility changes immediately.',
154
+ general: 'General',
155
+ buttons: 'Button visibility',
156
+ window: 'Default window size',
157
+ trayEnabled: 'System tray icon',
158
+ updateButton: 'Check/update button',
159
+ quitButton: 'Quit button',
160
+ headerControls: 'Conversation header entry',
161
+ mainOverlay: 'Main-interface top-right entry',
162
+ windowNote: 'Leave width and height empty or 0 to let Chrome remember; applied the next time a window opens.',
163
+ width: 'Width',
164
+ height: 'Height',
165
+ rememberCurrent: 'Remember current size',
166
+ autoSize: 'Use automatic size',
167
+ currentWindow: 'Current window',
168
+ cache: 'Cache cleanup',
169
+ cacheIntro: 'Choose which caches to clean. Only regenerable caches are deleted; the running DSH, plugin source, settings, sessions and sign-in state are never touched.',
170
+ cacheNote: 'Caches are rebuilt on demand and may add a little loading time after cleanup; active entries are skipped automatically.',
171
+ cacheRefresh: 'Scan again',
172
+ cacheClean: 'Clean selected',
173
+ cacheSelectAll: 'Select all cleanable',
174
+ cacheScanning: 'Scanning caches…',
175
+ cacheNone: 'No cleanable cache found.',
176
+ cacheSelected: 'Selected',
177
+ cacheFreed: 'Freed',
178
+ cachePartial: 'Partially completed, freed',
179
+ cacheFailed: 'Cleanup failed',
180
+ cacheScanFailed: 'Could not read cache information',
181
+ cacheUnavailable: 'Unavailable',
182
+ cacheCleaning: 'Cleaning…',
183
+ cacheProtected: 'Skipped entries currently in use',
184
+ cacheApp: 'Application cache',
185
+ cacheAppDetail: 'DSH attachment-image cache; safe to rebuild',
186
+ cacheNpx: 'npx install cache',
187
+ cacheNpxDetail: 'Obsolete temporary installs; the running version is kept',
188
+ cacheNpm: 'npm download cache',
189
+ cacheNpmDetail: 'Downloaded package cache; re-downloaded on next install',
190
+ cachePnpm: 'Uninstalled-plugin cache',
191
+ cachePnpmDetail: 'Packages in the pnpm store not referenced by any project; installed plugins are untouched',
192
+ cacheBackups: 'Update leftovers',
193
+ cacheBackupsDetail: 'Runtime backups and staging copies older than 7 days',
194
+ saved: 'Saved',
195
+ saving: 'Saving…',
196
+ saveFailed: 'Save failed',
197
+ },
198
+ }
199
+
200
+ let clientSettings = normalizeClientSettings(DEFAULT_SETTINGS)
201
+ let clientSettingsLoaded = false
202
+ let clientSettingsLoading = null
203
+ let clientContext = null
204
+ let translate = (key) => SETTINGS_TEXT.zh[key] ?? key
205
+ const CACHE_LABEL_KEYS = {
206
+ app: 'cacheApp',
207
+ npx: 'cacheNpx',
208
+ npm: 'cacheNpm',
209
+ pnpm: 'cachePnpm',
210
+ backups: 'cacheBackups',
211
+ }
212
+ function cacheLabel(id) {
213
+ return translate(CACHE_LABEL_KEYS[id] ?? id)
214
+ }
215
+ function cacheDetail(id) {
216
+ return translate(`${CACHE_LABEL_KEYS[id] ?? id}Detail`)
217
+ }
218
+
219
+ function normalizeClientSettings(input) {
220
+ const source = input !== null && typeof input === 'object' ? input : {}
221
+ const features = source.features !== null && typeof source.features === 'object' ? source.features : {}
222
+ const windowSize = source.window !== null && typeof source.window === 'object' ? source.window : {}
223
+ const boolean = (value, fallback) => (typeof value === 'boolean' ? value : fallback)
224
+ const size = (value) => {
225
+ const number = typeof value === 'number' ? value : Number(value)
226
+ if (!Number.isFinite(number) || number <= 0) return 0
227
+ return Math.min(10000, Math.max(600, Math.round(number)))
228
+ }
229
+ let width = size(windowSize.width)
230
+ let height = size(windowSize.height)
231
+ if (width === 0 || height === 0) {
232
+ width = 0
233
+ height = 0
234
+ }
235
+ return {
236
+ version: 1,
237
+ trayEnabled: boolean(source.trayEnabled, DEFAULT_SETTINGS.trayEnabled),
238
+ features: {
239
+ updateButton: boolean(features.updateButton, DEFAULT_SETTINGS.features.updateButton),
240
+ quitButton: boolean(features.quitButton, DEFAULT_SETTINGS.features.quitButton),
241
+ headerControls: boolean(features.headerControls, DEFAULT_SETTINGS.features.headerControls),
242
+ mainOverlay: boolean(features.mainOverlay, DEFAULT_SETTINGS.features.mainOverlay),
243
+ },
244
+ window: { width, height },
245
+ }
246
+ }
247
+
248
+ function applyClientSettings(next) {
249
+ clientSettings = normalizeClientSettings(next)
250
+ if (typeof document !== 'undefined' && document.body !== null && document.body.classList) {
251
+ document.body.classList.toggle('dsh-ac-hide-update', !clientSettings.features.updateButton)
252
+ document.body.classList.toggle('dsh-ac-hide-quit', !clientSettings.features.quitButton)
253
+ document.body.classList.toggle('dsh-ac-hide-header', !clientSettings.features.headerControls)
254
+ document.body.classList.toggle('dsh-ac-hide-overlay', !clientSettings.features.mainOverlay)
255
+ }
256
+ return clientSettings
257
+ }
258
+
259
+ function clearClientSettingsClasses() {
260
+ if (typeof document === 'undefined' || document.body === null || !document.body.classList) return
261
+ for (const name of ['dsh-ac-hide-update', 'dsh-ac-hide-quit', 'dsh-ac-hide-header', 'dsh-ac-hide-overlay']) {
262
+ document.body.classList.remove(name)
263
+ }
264
+ }
265
+
266
+ function canUseFetch() {
267
+ return typeof fetch === 'function' && typeof document !== 'undefined' && typeof document.baseURI === 'string'
268
+ }
269
+
270
+ function loadClientSettings() {
271
+ if (clientSettingsLoading !== null) return clientSettingsLoading
272
+ clientSettingsLoading = (async () => {
273
+ if (!canUseFetch()) {
274
+ clientSettingsLoaded = true
275
+ return clientSettings
276
+ }
277
+ try {
278
+ const response = await fetch(apiUrl(SETTINGS_ENDPOINT), {
279
+ headers: { accept: 'application/json' },
280
+ cache: 'no-store',
281
+ })
282
+ const body = await readJson(response)
283
+ if (response.ok && body !== null && body.settings !== undefined) {
284
+ applyClientSettings(body.settings)
285
+ }
286
+ } catch {
287
+ // keep the defaults; the host may be starting
288
+ }
289
+ clientSettingsLoaded = true
290
+ return clientSettings
291
+ })()
292
+ return clientSettingsLoading
293
+ }
294
+
295
+ function bindSettingsLocale(ctx) {
296
+ try {
297
+ let locale = undefined
298
+ if (ctx && typeof ctx.get === 'function') locale = ctx.get('locale')
299
+ if (locale === undefined && ctx) locale = ctx.locale
300
+ if (locale && typeof locale.register === 'function' && typeof locale.bind === 'function') {
301
+ locale.register(SETTINGS_NS, SETTINGS_TEXT)
302
+ translate = locale.bind(SETTINGS_NS)
303
+ return
304
+ }
305
+ } catch {
306
+ // fall through to the navigator-based dictionary
307
+ }
308
+ const language = typeof navigator !== 'undefined' && navigator.language ? navigator.language : 'zh'
309
+ const dictionary = language.toLowerCase().startsWith('zh') ? SETTINGS_TEXT.zh : SETTINGS_TEXT.en
310
+ translate = (key) => dictionary[key] ?? key
311
+ }
312
+
313
+ function SettingsPanel() {
314
+ const [draft, setDraft] = React.useState(clientSettings)
315
+ const [saving, setSaving] = React.useState(false)
316
+ const [status, setStatus] = React.useState('')
317
+ const [cache, setCache] = React.useState(null)
318
+ const [cacheLoading, setCacheLoading] = React.useState(false)
319
+ const [cacheCleaning, setCacheCleaning] = React.useState(false)
320
+ const [cacheStatus, setCacheStatus] = React.useState('')
321
+ const [selected, setSelected] = React.useState({})
322
+
323
+ React.useEffect(() => {
324
+ let cancelled = false
325
+ void loadClientSettings().then(() => {
326
+ if (!cancelled) setDraft(clientSettings)
327
+ })
328
+ return () => {
329
+ cancelled = true
330
+ }
331
+ }, [])
332
+
333
+ React.useEffect(() => {
334
+ void loadCache()
335
+ }, [])
336
+
337
+ async function loadCache() {
338
+ setCacheLoading(true)
339
+ setCacheStatus('')
340
+ setSelected({})
341
+ try {
342
+ if (!canUseFetch()) throw new Error('host is unavailable')
343
+ const response = await fetch(apiUrl(CACHE_ENDPOINT), {
344
+ headers: { accept: 'application/json' },
345
+ cache: 'no-store',
346
+ })
347
+ const body = await readJson(response)
348
+ if (!response.ok || body === null || !Array.isArray(body.categories)) {
349
+ throw new Error(failureText(body, response.status))
350
+ }
351
+ setCache(body)
352
+ } catch (error) {
353
+ setCacheStatus(`${translate('cacheScanFailed')}:${errorMessage(error)}`)
354
+ } finally {
355
+ setCacheLoading(false)
356
+ }
357
+ }
358
+
359
+ async function cleanSelected() {
360
+ const categories = (cache !== null && Array.isArray(cache.categories) ? cache.categories : [])
361
+ .filter((category) => category.available && selected[category.id])
362
+ .map((category) => category.id)
363
+ if (categories.length === 0) return
364
+ setCacheCleaning(true)
365
+ setCacheStatus('')
366
+ try {
367
+ if (!canUseFetch()) throw new Error('host is unavailable')
368
+ const response = await fetch(apiUrl(CACHE_CLEAN_ENDPOINT), {
369
+ method: 'POST',
370
+ headers: { 'content-type': 'application/json' },
371
+ body: JSON.stringify({ categories }),
372
+ })
373
+ const body = await readJson(response)
374
+ if (!response.ok || body === null) {
375
+ throw new Error(failureText(body, response.status))
376
+ }
377
+ if (body.inventory !== undefined) setCache(body.inventory)
378
+ setSelected({})
379
+ const freed = formatBytes(body.freedBytes ?? 0)
380
+ const partial = Array.isArray(body.results) && body.results.some((result) => result && result.ok === false)
381
+ setCacheStatus(`${translate(partial ? 'cachePartial' : 'cacheFreed')} ${freed}`)
382
+ } catch (error) {
383
+ setCacheStatus(`${translate('cacheFailed')}:${errorMessage(error)}`)
384
+ } finally {
385
+ setCacheCleaning(false)
386
+ }
387
+ }
388
+
389
+ async function commit(next) {
390
+ setDraft(next)
391
+ setSaving(true)
392
+ setStatus('')
393
+ try {
394
+ if (!canUseFetch()) throw new Error('host is unavailable')
395
+ const response = await fetch(apiUrl(SETTINGS_ENDPOINT), {
396
+ method: 'POST',
397
+ headers: { 'content-type': 'application/json' },
398
+ body: JSON.stringify(next),
399
+ })
400
+ const body = await readJson(response)
401
+ if (!response.ok || body === null || body.settings === undefined) {
402
+ throw new Error(failureText(body, response.status))
403
+ }
404
+ applyClientSettings(body.settings)
405
+ setDraft(clientSettings)
406
+ setStatus(translate('saved'))
407
+ } catch (error) {
408
+ setStatus(`${translate('saveFailed')}:${errorMessage(error)}`)
409
+ } finally {
410
+ setSaving(false)
411
+ }
412
+ }
413
+
414
+ function patch(partial) {
415
+ const next = normalizeClientSettings({
416
+ ...draft,
417
+ ...partial,
418
+ features: { ...draft.features, ...(partial.features ?? {}) },
419
+ window: { ...draft.window, ...(partial.window ?? {}) },
420
+ })
421
+ void commit(next)
422
+ }
423
+
424
+ function editDraft(partial) {
425
+ setDraft(normalizeClientSettings({
426
+ ...draft,
427
+ ...partial,
428
+ features: { ...draft.features, ...(partial.features ?? {}) },
429
+ window: { ...draft.window, ...(partial.window ?? {}) },
430
+ }))
431
+ }
432
+
433
+ function featureRow(key, label) {
434
+ return h(
435
+ 'label',
436
+ { className: 'dsh-ac-settings-row' },
437
+ h('span', null, translate(label)),
438
+ h('input', {
439
+ type: 'checkbox',
440
+ checked: draft.features[key],
441
+ disabled: saving,
442
+ onChange: (event) => patch({ features: { [key]: event.target.checked } }),
443
+ }),
444
+ )
445
+ }
446
+
447
+ const currentWidth = typeof window !== 'undefined' ? Math.round(window.outerWidth || window.innerWidth || 0) : 0
448
+ const currentHeight = typeof window !== 'undefined' ? Math.round(window.outerHeight || window.innerHeight || 0) : 0
449
+ const cacheCategories = cache !== null && Array.isArray(cache.categories) ? cache.categories : []
450
+ const selectedBytes = cacheCategories.reduce(
451
+ (sum, category) => sum + (category.available && selected[category.id] ? category.sizeBytes || 0 : 0),
452
+ 0,
453
+ )
454
+ const hasSelected = cacheCategories.some((category) => category.available && selected[category.id])
455
+ const cleanable = cacheCategories.some((category) => category.available)
456
+
457
+ return h(
458
+ 'section',
459
+ { className: 'dsh-ac-settings' },
460
+ h(
461
+ 'div',
462
+ { className: 'dsh-ac-settings-heading' },
463
+ h('h3', { className: 'dsh-ac-settings-title' }, translate('title')),
464
+ h('p', { className: 'dsh-ac-settings-intro' }, translate('intro')),
465
+ ),
466
+ h(
467
+ 'div',
468
+ { className: 'dsh-ac-settings-group' },
469
+ h('div', { className: 'dsh-ac-settings-group-title' }, translate('general')),
470
+ h(
471
+ 'label',
472
+ { className: 'dsh-ac-settings-row' },
473
+ h('span', null, translate('trayEnabled')),
474
+ h('input', {
475
+ type: 'checkbox',
476
+ checked: draft.trayEnabled,
477
+ disabled: saving,
478
+ onChange: (event) => patch({ trayEnabled: event.target.checked }),
479
+ }),
480
+ ),
481
+ ),
482
+ h(
483
+ 'div',
484
+ { className: 'dsh-ac-settings-group' },
485
+ h('div', { className: 'dsh-ac-settings-group-title' }, translate('buttons')),
486
+ featureRow('updateButton', 'updateButton'),
487
+ featureRow('quitButton', 'quitButton'),
488
+ featureRow('headerControls', 'headerControls'),
489
+ featureRow('mainOverlay', 'mainOverlay'),
490
+ ),
491
+ h(
492
+ 'div',
493
+ { className: 'dsh-ac-settings-group' },
494
+ h('div', { className: 'dsh-ac-settings-group-title' }, translate('window')),
495
+ h('p', { className: 'dsh-ac-settings-note' }, translate('windowNote')),
496
+ h(
497
+ 'div',
498
+ { className: 'dsh-ac-settings-size' },
499
+ h(
500
+ 'label',
501
+ null,
502
+ translate('width'),
503
+ h('input', {
504
+ type: 'number',
505
+ min: 600,
506
+ max: 10000,
507
+ value: draft.window.width === 0 ? '' : String(draft.window.width),
508
+ disabled: saving,
509
+ onChange: (event) => {
510
+ const value = event.target.value === '' ? 0 : Number(event.target.value)
511
+ editDraft({ window: { width: value, height: draft.window.height } })
512
+ },
513
+ onBlur: () => patch({ window: { width: draft.window.width, height: draft.window.height } }),
514
+ }),
515
+ ),
516
+ h(
517
+ 'label',
518
+ null,
519
+ translate('height'),
520
+ h('input', {
521
+ type: 'number',
522
+ min: 600,
523
+ max: 10000,
524
+ value: draft.window.height === 0 ? '' : String(draft.window.height),
525
+ disabled: saving,
526
+ onChange: (event) => {
527
+ const value = event.target.value === '' ? 0 : Number(event.target.value)
528
+ editDraft({ window: { width: draft.window.width, height: value } })
529
+ },
530
+ onBlur: () => patch({ window: { width: draft.window.width, height: draft.window.height } }),
531
+ }),
532
+ ),
533
+ h(
534
+ 'button',
535
+ {
536
+ type: 'button',
537
+ disabled: saving,
538
+ onClick: () => patch({ window: { width: currentWidth, height: currentHeight } }),
539
+ },
540
+ translate('rememberCurrent'),
541
+ ),
542
+ h(
543
+ 'button',
544
+ {
545
+ type: 'button',
546
+ disabled: saving,
547
+ onClick: () => patch({ window: { width: 0, height: 0 } }),
548
+ },
549
+ translate('autoSize'),
550
+ ),
551
+ ),
552
+ h('p', { className: 'dsh-ac-settings-note' }, `${translate('currentWindow')}: ${currentWidth} × ${currentHeight}`),
553
+ ),
554
+ h(
555
+ 'div',
556
+ { className: 'dsh-ac-settings-group dsh-ac-cache-group' },
557
+ h('div', { className: 'dsh-ac-settings-group-title' }, translate('cache')),
558
+ h('p', { className: 'dsh-ac-settings-note' }, translate('cacheIntro')),
559
+ h('p', { className: 'dsh-ac-settings-note' }, translate('cacheNote')),
560
+ h(
561
+ 'div',
562
+ { className: 'dsh-ac-cache-summary' },
563
+ cacheLoading
564
+ ? translate('cacheScanning')
565
+ : cache === null
566
+ ? translate('cacheNone')
567
+ : `${translate('cacheSelected')}: ${formatBytes(selectedBytes)}`,
568
+ ),
569
+ cacheCategories.length === 0
570
+ ? h('p', { className: 'dsh-ac-settings-note' }, cacheLoading ? translate('cacheScanning') : translate('cacheNone'))
571
+ : h(
572
+ 'div',
573
+ { className: 'dsh-ac-cache-list' },
574
+ cacheCategories.map((category) => h(
575
+ 'label',
576
+ { key: category.id, className: 'dsh-ac-cache-row' },
577
+ h('input', {
578
+ type: 'checkbox',
579
+ checked: Boolean(selected[category.id]),
580
+ disabled: cacheLoading || cacheCleaning || !category.available,
581
+ onChange: (event) => setSelected({ ...selected, [category.id]: event.target.checked }),
582
+ }),
583
+ h(
584
+ 'span',
585
+ { className: 'dsh-ac-cache-copy' },
586
+ h('span', { className: 'dsh-ac-cache-label' }, cacheLabel(category.id)),
587
+ h(
588
+ 'span',
589
+ { className: 'dsh-ac-cache-detail' },
590
+ category.available ? cacheDetail(category.id) : `${translate('cacheUnavailable')}:${category.reason || ''}`,
591
+ ),
592
+ ),
593
+ h('span', { className: 'dsh-ac-cache-size' }, formatBytes(category.sizeBytes || 0)),
594
+ )),
595
+ ),
596
+ h(
597
+ 'div',
598
+ { className: 'dsh-ac-cache-actions' },
599
+ h(
600
+ 'button',
601
+ { type: 'button', className: 'dsh-ac-cache-button', disabled: cacheLoading || cacheCleaning, onClick: loadCache },
602
+ translate('cacheRefresh'),
603
+ ),
604
+ h(
605
+ 'button',
606
+ {
607
+ type: 'button',
608
+ className: 'dsh-ac-cache-button',
609
+ disabled: cacheLoading || cacheCleaning || !cleanable,
610
+ onClick: () => {
611
+ const next = {}
612
+ for (const category of cacheCategories) {
613
+ if (category.available) next[category.id] = true
614
+ }
615
+ setSelected(next)
616
+ },
617
+ },
618
+ translate('cacheSelectAll'),
619
+ ),
620
+ h(
621
+ 'button',
622
+ {
623
+ type: 'button',
624
+ className: 'dsh-ac-cache-button dsh-ac-cache-button-primary',
625
+ disabled: cacheLoading || cacheCleaning || !hasSelected,
626
+ onClick: cleanSelected,
627
+ },
628
+ cacheCleaning ? translate('cacheCleaning') : translate('cacheClean'),
629
+ ),
630
+ ),
631
+ h('div', { className: 'dsh-ac-settings-footer', role: 'status' }, cacheStatus),
632
+ ),
633
+ h('div', { className: 'dsh-ac-settings-footer', role: 'status' }, saving ? translate('saving') : status),
634
+ )
635
+ }
636
+
637
+ // ── styles ───────────────────────────────────────────────────────────────
638
+ function injectStyles() {
639
+ if (document.getElementById(STYLE_ID) !== null) return
640
+ const style = document.createElement('style')
641
+ style.id = STYLE_ID
642
+ style.textContent = [
643
+ '.dsh-app-controls{display:inline-flex;align-items:center;gap:2px;margin-left:2px}',
644
+ '.dsh-ac-overlay{position:fixed;top:calc(var(--dsh-frame-top-clearance, 0px) + 8px);right:12px;z-index:70;display:inline-flex;pointer-events:auto}',
645
+ '.dsh-ac-overlay-group{display:inline-flex;align-items:center;gap:2px}',
646
+ 'body:has([data-dsh-ac-utilities]) .dsh-ac-overlay{display:none}',
647
+ '.dsh-app-controls-btn{display:inline-flex;align-items:center;justify-content:center;width:28px;height:28px;padding:0;border:0;border-radius:6px;background:transparent;color:inherit;opacity:.75;cursor:pointer;transition:background-color .12s ease,opacity .12s ease}',
648
+ '.dsh-app-controls-btn:hover{background:rgba(127,127,127,.18);opacity:1}',
649
+ '.dsh-app-controls-btn:active{background:rgba(127,127,127,.28)}',
650
+ '.dsh-app-controls-btn:disabled{opacity:.4;cursor:progress}',
651
+ 'body.dsh-ac-hide-update [data-dsh-ac-feature="update"]{display:none!important}',
652
+ 'body.dsh-ac-hide-quit [data-dsh-ac-feature="quit"]{display:none!important}',
653
+ 'body.dsh-ac-hide-header .dsh-app-controls{display:none!important}',
654
+ 'body.dsh-ac-hide-overlay .dsh-ac-overlay{display:none!important}',
655
+ '.dsh-ac-settings{display:flex;flex-direction:column;gap:16px;padding:2px 0;color:var(--dsw-alias-label-primary,inherit);font:13px/1.6 system-ui,-apple-system,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif}',
656
+ '.dsh-ac-settings-heading{display:flex;flex-direction:column;gap:4px}',
657
+ '.dsh-ac-settings-title{margin:0;font-size:16px;line-height:24px;font-weight:600}',
658
+ '.dsh-ac-settings-intro{margin:0;font-size:12px;line-height:18px;color:var(--dsw-alias-label-tertiary,inherit);opacity:.8}',
659
+ '.dsh-ac-settings-group{display:flex;flex-direction:column;gap:8px;padding:14px 16px;border:1px solid var(--dsw-alias-border-l2,rgba(127,127,127,.28));border-radius:10px}',
660
+ '.dsh-ac-settings-group-title{font-size:13px;font-weight:600;color:var(--dsw-alias-label-primary,inherit)}',
661
+ '.dsh-ac-settings-row{display:flex;align-items:center;justify-content:space-between;gap:16px;min-height:26px;font-size:13px;color:var(--dsw-alias-label-primary,inherit)}',
662
+ '.dsh-ac-settings-row input[type="checkbox"]{width:16px;height:16px;margin:0;accent-color:var(--dsw-alias-state-business-primary,#4d6bfe);cursor:pointer}',
663
+ '.dsh-ac-settings-size{display:flex;flex-wrap:wrap;align-items:center;gap:8px}',
664
+ '.dsh-ac-settings-size label{display:flex;align-items:center;gap:6px;font-size:13px;color:var(--dsw-alias-label-secondary,inherit)}',
665
+ '.dsh-ac-settings-size input{width:88px;height:30px;box-sizing:border-box;padding:0 8px;border:1px solid var(--dsw-alias-border-l2,rgba(127,127,127,.3));border-radius:6px;background:var(--dsw-alias-bg-l1,transparent);color:var(--dsw-alias-label-primary,inherit);font:inherit}',
666
+ '.dsh-ac-settings-size input:focus{outline:2px solid var(--dsw-focus-ring-color,var(--dsw-alias-state-business-primary,#4d6bfe));outline-offset:1px}',
667
+ '.dsh-ac-settings-size button{height:30px;padding:0 12px;border:1px solid var(--dsw-alias-border-l2,rgba(127,127,127,.3));border-radius:6px;background:var(--dsw-alias-bg-l1,transparent);color:var(--dsw-alias-label-primary,inherit);font:inherit;font-size:12px;cursor:pointer}',
668
+ '.dsh-ac-settings-size button:hover{background:var(--dsw-alias-bg-l2,rgba(127,127,127,.12))}',
669
+ '.dsh-ac-settings-size button:disabled{opacity:.55;cursor:default}',
670
+ '.dsh-ac-settings-note{margin:0;font-size:12px;line-height:18px;color:var(--dsw-alias-label-tertiary,inherit);opacity:.8}',
671
+ '.dsh-ac-cache-group{gap:6px}',
672
+ '.dsh-ac-cache-summary{font-size:12px;color:var(--dsw-alias-label-tertiary,inherit)}',
673
+ '.dsh-ac-cache-list{display:flex;flex-direction:column;gap:6px;margin-top:2px}',
674
+ '.dsh-ac-cache-row{display:flex;align-items:flex-start;gap:10px;padding:8px 10px;border:1px solid var(--dsw-alias-border-l2,rgba(127,127,127,.22));border-radius:8px;font-size:13px;cursor:pointer}',
675
+ '.dsh-ac-cache-row input[type="checkbox"]{width:16px;height:16px;margin:2px 0 0;flex-shrink:0;accent-color:var(--dsw-alias-state-business-primary,#4d6bfe);cursor:pointer}',
676
+ '.dsh-ac-cache-copy{display:flex;flex-direction:column;gap:2px;min-width:0;flex:1}',
677
+ '.dsh-ac-cache-label{font-size:13px;color:var(--dsw-alias-label-primary,inherit)}',
678
+ '.dsh-ac-cache-detail{font-size:12px;line-height:1.45;color:var(--dsw-alias-label-tertiary,inherit);overflow-wrap:anywhere}',
679
+ '.dsh-ac-cache-size{margin-left:auto;flex-shrink:0;font-variant-numeric:tabular-nums;font-size:12px;color:var(--dsw-alias-label-secondary,inherit);white-space:nowrap}',
680
+ '.dsh-ac-cache-actions{display:flex;flex-wrap:wrap;gap:8px;margin-top:4px}',
681
+ '.dsh-ac-cache-actions button{height:30px;padding:0 12px;border:1px solid var(--dsw-alias-border-l2,rgba(127,127,127,.3));border-radius:6px;background:transparent;color:var(--dsw-alias-label-primary,inherit);font:inherit;font-size:12px;cursor:pointer}',
682
+ '.dsh-ac-cache-actions button:hover{background:var(--dsw-alias-bg-l2,rgba(127,127,127,.12))}',
683
+ '.dsh-ac-cache-actions button:disabled{opacity:.5;cursor:default}',
684
+ '.dsh-ac-settings-footer{min-height:18px;font-size:12px;color:var(--dsw-alias-label-tertiary,inherit);opacity:.85}',
685
+ '.dsh-app-controls-btn svg{display:block;width:16px;height:16px;fill:none;stroke:currentColor;stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round}',
686
+ '.dsh-ac-backdrop{position:fixed;inset:0;z-index:2147483000;display:flex;align-items:center;justify-content:center;padding:24px;background:rgba(8,10,14,.48);backdrop-filter:blur(3px);animation:dsh-ac-fade .14s ease-out}',
687
+ '.dsh-ac-dialog{width:min(440px,calc(100vw - 40px));max-height:calc(100vh - 48px);overflow:auto;box-sizing:border-box;border-radius:14px;padding:22px 22px 18px;background:#ffffff;color:#1b1f24;box-shadow:0 18px 70px rgba(0,0,0,.34);font:14px/1.65 system-ui,-apple-system,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif;animation:dsh-ac-pop .16s ease-out}',
688
+ 'body[data-ds-dark-theme] .dsh-ac-dialog{background:#20242c;color:#e9ebef;box-shadow:0 18px 70px rgba(0,0,0,.55)}',
689
+ '.dsh-ac-title{font-size:16px;font-weight:600;line-height:1.5;margin-bottom:10px;word-break:break-word}',
690
+ '.dsh-ac-message{white-space:pre-wrap;word-break:break-word;opacity:.88;margin-bottom:16px}',
691
+ '.dsh-ac-footer{display:flex;justify-content:flex-end;gap:10px;margin-top:18px}',
692
+ '.dsh-ac-btn{appearance:none;border:1px solid transparent;border-radius:8px;padding:7px 16px;font:inherit;font-size:13px;font-weight:500;cursor:pointer;transition:background-color .12s,opacity .12s;min-width:64px}',
693
+ '.dsh-ac-btn.secondary{background:transparent;border-color:rgba(127,127,127,.42);color:inherit}',
694
+ '.dsh-ac-btn.secondary:hover{background:rgba(127,127,127,.14)}',
695
+ '.dsh-ac-btn.primary{background:#4d6bfe;color:#fff}',
696
+ '.dsh-ac-btn.primary:hover{background:#3c58e0}',
697
+ '.dsh-ac-btn.danger{background:#e5484d;color:#fff}',
698
+ '.dsh-ac-btn.danger:hover{background:#cf3b40}',
699
+ '.dsh-ac-spinner-row{display:flex;align-items:center;gap:10px;opacity:.9}',
700
+ '.dsh-ac-spinner{width:16px;height:16px;border:2px solid rgba(127,127,127,.35);border-top-color:currentColor;border-radius:50%;animation:dsh-ac-spin .8s linear infinite;flex:none}',
701
+ '.dsh-ac-progress{display:flex;flex-direction:column;gap:10px}',
702
+ '.dsh-ac-versions{font-size:13px;opacity:.75;letter-spacing:.2px}',
703
+ '.dsh-ac-track{height:8px;border-radius:999px;background:rgba(127,127,127,.22);overflow:hidden}',
704
+ '.dsh-ac-fill{height:100%;width:0%;border-radius:999px;background:linear-gradient(90deg,#4d6bfe,#6ea8ff);transition:width .4s ease;position:relative;overflow:hidden}',
705
+ '.dsh-ac-fill::after{content:"";position:absolute;inset:0;background:linear-gradient(90deg,transparent,rgba(255,255,255,.45),transparent);transform:translateX(-100%);animation:dsh-ac-shimmer 1.6s ease-in-out infinite}',
706
+ '.dsh-ac-progress-row{display:flex;justify-content:space-between;gap:12px;font-size:13px}',
707
+ '.dsh-ac-phase{opacity:.9;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
708
+ '.dsh-ac-percent{font-variant-numeric:tabular-nums;font-weight:600;flex:none}',
709
+ '.dsh-ac-activity{font-size:12px;opacity:.55;min-height:18px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-family:ui-monospace,SFMono-Regular,Menlo,monospace}',
710
+ '.dsh-ac-elapsed{font-size:12px;opacity:.55;font-variant-numeric:tabular-nums}',
711
+ '.dsh-ac-exit{position:fixed;inset:0;z-index:2147483000;display:flex;align-items:center;justify-content:center;padding:24px;background:rgba(8,10,14,.62);backdrop-filter:blur(4px);animation:dsh-ac-fade .18s ease-out}',
712
+ '.dsh-ac-exit-card{width:min(420px,calc(100vw - 40px));box-sizing:border-box;border-radius:16px;padding:28px 26px 22px;text-align:center;background:#ffffff;color:#1b1f24;box-shadow:0 18px 70px rgba(0,0,0,.35);font:14px/1.65 system-ui,-apple-system,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif}',
713
+ 'body[data-ds-dark-theme] .dsh-ac-exit-card{background:#20242c;color:#e9ebef;box-shadow:0 18px 70px rgba(0,0,0,.55)}',
714
+ '.dsh-ac-exit-mark{width:44px;height:44px;margin:0 auto 14px;border-radius:50%;display:flex;align-items:center;justify-content:center;background:rgba(63,174,99,.16);color:#3fae63;font-size:22px;font-weight:700}',
715
+ '.dsh-ac-exit-mark.busy{background:rgba(77,107,254,.16);color:#4d6bfe}',
716
+ '.dsh-ac-exit-title{font-size:16px;font-weight:600;margin-bottom:8px;word-break:break-word}',
717
+ '.dsh-ac-exit-message{opacity:.82;white-space:pre-wrap;word-break:break-word;margin-bottom:14px}',
718
+ '.dsh-ac-exit-hint{font-size:12px;opacity:.55;min-height:18px}',
719
+ '@keyframes dsh-ac-fade{from{opacity:0}to{opacity:1}}',
720
+ '@keyframes dsh-ac-pop{from{opacity:0;transform:translateY(6px) scale(.98)}to{opacity:1;transform:none}}',
721
+ '@keyframes dsh-ac-spin{to{transform:rotate(360deg)}}',
722
+ '@keyframes dsh-ac-shimmer{0%{transform:translateX(-100%)}60%,100%{transform:translateX(180%)}}',
723
+ '@media (prefers-reduced-motion: reduce){.dsh-ac-backdrop,.dsh-ac-dialog,.dsh-ac-exit,.dsh-ac-fill::after,.dsh-ac-spinner{animation:none}}',
724
+ ].join('\n')
725
+ document.head.appendChild(style)
726
+ }
727
+
728
+ // ── modal plumbing ──────────────────────────────────────────────────────
729
+ function onModalKey(event) {
730
+ if (event.key !== 'Escape') return
731
+ if (!modalDismissible || typeof modalOnClose !== 'function') return
732
+ event.preventDefault()
733
+ modalOnClose()
734
+ }
735
+
736
+ function removeModal() {
737
+ const existing = document.getElementById(MODAL_ID)
738
+ if (existing !== null) existing.remove()
739
+ document.removeEventListener('keydown', onModalKey)
740
+ activeModal = null
741
+ modalDismissible = false
742
+ modalOnClose = null
743
+ }
744
+
745
+ function closeModal() {
746
+ removeModal()
747
+ }
748
+
749
+ function buildButton(spec) {
750
+ const button = document.createElement('button')
751
+ button.type = 'button'
752
+ button.className = `dsh-ac-btn ${spec.variant ?? 'secondary'}`
753
+ button.textContent = spec.label
754
+ button.addEventListener('click', () => {
755
+ if (typeof spec.onClick === 'function') spec.onClick()
756
+ })
757
+ return button
758
+ }
759
+
760
+ function openModal(options) {
761
+ removeModal()
762
+ const backdrop = document.createElement('div')
763
+ backdrop.id = MODAL_ID
764
+ backdrop.className = 'dsh-ac-backdrop'
765
+ const dialog = document.createElement('div')
766
+ dialog.className = 'dsh-ac-dialog'
767
+ dialog.setAttribute('role', 'dialog')
768
+ dialog.setAttribute('aria-modal', 'true')
769
+ const title = document.createElement('div')
770
+ title.className = 'dsh-ac-title'
771
+ title.textContent = options.title
772
+ dialog.appendChild(title)
773
+ if (typeof options.message === 'string' && options.message !== '') {
774
+ const message = document.createElement('div')
775
+ message.className = 'dsh-ac-message'
776
+ message.textContent = options.message
777
+ dialog.appendChild(message)
778
+ }
779
+ if (options.content) dialog.appendChild(options.content)
780
+ const buttons = Array.isArray(options.buttons) ? options.buttons : []
781
+ if (buttons.length > 0) {
782
+ const footer = document.createElement('div')
783
+ footer.className = 'dsh-ac-footer'
784
+ for (const spec of buttons) footer.appendChild(buildButton(spec))
785
+ dialog.appendChild(footer)
786
+ }
787
+ backdrop.appendChild(dialog)
788
+ document.body.appendChild(backdrop)
789
+ modalDismissible = options.dismissible === true
790
+ modalOnClose = typeof options.onClose === 'function' ? options.onClose : null
791
+ if (modalDismissible) {
792
+ backdrop.addEventListener('click', (event) => {
793
+ if (event.target !== backdrop) return
794
+ if (typeof modalOnClose === 'function') modalOnClose()
795
+ })
796
+ }
797
+ document.addEventListener('keydown', onModalKey)
798
+ const primary = dialog.querySelector('.dsh-ac-btn.primary') ?? dialog.querySelector('.dsh-ac-btn')
799
+ if (primary !== null) window.setTimeout(() => primary.focus(), 30)
800
+ activeModal = backdrop
801
+ return { backdrop, dialog }
802
+ }
803
+
804
+ function openSpinner(title, message) {
805
+ const row = document.createElement('div')
806
+ row.className = 'dsh-ac-spinner-row'
807
+ const spinner = document.createElement('div')
808
+ spinner.className = 'dsh-ac-spinner'
809
+ const text = document.createElement('div')
810
+ text.textContent = message
811
+ row.appendChild(spinner)
812
+ row.appendChild(text)
813
+ return openModal({ title, content: row, dismissible: false })
814
+ }
815
+
816
+ function openInfo(title, message) {
817
+ return openModal({
818
+ title,
819
+ message,
820
+ dismissible: true,
821
+ onClose: closeModal,
822
+ buttons: [{ label: '关闭', variant: 'primary', onClick: closeModal }],
823
+ })
824
+ }
825
+
826
+ function openError(message) {
827
+ return openModal({
828
+ title: '操作失败',
829
+ message,
830
+ dismissible: true,
831
+ onClose: closeModal,
832
+ buttons: [{ label: '关闭', variant: 'primary', onClick: closeModal }],
833
+ })
834
+ }
835
+
836
+ function openProgress(from, to) {
837
+ const wrap = document.createElement('div')
838
+ wrap.className = 'dsh-ac-progress'
839
+ const versions = document.createElement('div')
840
+ versions.className = 'dsh-ac-versions'
841
+ versions.textContent = `${from} → ${to}`
842
+ wrap.appendChild(versions)
843
+ const track = document.createElement('div')
844
+ track.className = 'dsh-ac-track'
845
+ const fill = document.createElement('div')
846
+ fill.className = 'dsh-ac-fill'
847
+ track.appendChild(fill)
848
+ wrap.appendChild(track)
849
+ const row = document.createElement('div')
850
+ row.className = 'dsh-ac-progress-row'
851
+ const phase = document.createElement('span')
852
+ phase.className = 'dsh-ac-phase'
853
+ const percent = document.createElement('span')
854
+ percent.className = 'dsh-ac-percent'
855
+ row.appendChild(phase)
856
+ row.appendChild(percent)
857
+ wrap.appendChild(row)
858
+ const activity = document.createElement('div')
859
+ activity.className = 'dsh-ac-activity'
860
+ wrap.appendChild(activity)
861
+ const elapsed = document.createElement('div')
862
+ elapsed.className = 'dsh-ac-elapsed'
863
+ wrap.appendChild(elapsed)
864
+ openModal({ title: '正在更新 DeepSeek Harness', content: wrap, dismissible: false })
865
+ return {
866
+ update(state) {
867
+ const value = Math.max(0, Math.min(100, Math.round(state.percent ?? 0)))
868
+ fill.style.width = `${value}%`
869
+ percent.textContent = `${value}%`
870
+ phase.textContent = state.message || '正在更新…'
871
+ activity.textContent = state.activity ? state.activity : ''
872
+ elapsed.textContent = state.elapsedMs > 0 ? `已用时 ${formatDuration(state.elapsedMs)}` : ''
873
+ },
874
+ }
875
+ }
876
+
877
+ // ── exit screen ─────────────────────────────────────────────────────────
878
+ function removeExitScreen() {
879
+ const existing = document.getElementById(EXIT_ID)
880
+ if (existing !== null) existing.remove()
881
+ }
882
+
883
+ function showExitScreen(options) {
884
+ removeModal()
885
+ removeExitScreen()
886
+ const screen = document.createElement('div')
887
+ screen.id = EXIT_ID
888
+ screen.className = 'dsh-ac-exit'
889
+ const card = document.createElement('div')
890
+ card.className = 'dsh-ac-exit-card'
891
+ const mark = document.createElement('div')
892
+ mark.className = options.spinner === true ? 'dsh-ac-exit-mark busy' : 'dsh-ac-exit-mark'
893
+ const title = document.createElement('div')
894
+ title.className = 'dsh-ac-exit-title'
895
+ title.textContent = options.title
896
+ const message = document.createElement('div')
897
+ message.className = 'dsh-ac-exit-message'
898
+ message.textContent = options.message
899
+ const hint = document.createElement('div')
900
+ hint.id = CLOSE_HINT_ID
901
+ hint.className = 'dsh-ac-exit-hint'
902
+ hint.textContent = options.spinner === true ? '' : '正在关闭窗口…'
903
+ card.appendChild(mark)
904
+ card.appendChild(title)
905
+ card.appendChild(message)
906
+ card.appendChild(hint)
907
+ screen.appendChild(card)
908
+ document.body.appendChild(screen)
909
+ if (options.spinner === true) {
910
+ const spinner = document.createElement('div')
911
+ spinner.className = 'dsh-ac-spinner'
912
+ mark.appendChild(spinner)
913
+ } else {
914
+ mark.textContent = '✓'
915
+ }
916
+ return { screen, title, message, hint, mark }
917
+ }
918
+
919
+ function tryCloseWindow() {
920
+ window.setTimeout(() => {
921
+ try {
922
+ window.close()
923
+ } catch {
924
+ // a normal browser tab cannot be closed by script
925
+ }
926
+ }, 700)
927
+ window.setTimeout(() => {
928
+ const hint = document.getElementById(CLOSE_HINT_ID)
929
+ if (hint !== null) hint.textContent = '窗口未能自动关闭,请手动关闭这个窗口。'
930
+ }, 2200)
931
+ }
932
+
933
+ function stopPolling() {
934
+ if (pollTimer !== 0) {
935
+ window.clearTimeout(pollTimer)
936
+ pollTimer = 0
937
+ }
938
+ }
939
+
940
+ // Tray-initiated quit/update requests set `quitRequested` on the host; the
941
+ // page notices it here and closes the window after the service stops.
942
+ function stopStatePolling() {
943
+ if (statePollTimer !== 0) {
944
+ window.clearTimeout(statePollTimer)
945
+ statePollTimer = 0
946
+ }
947
+ }
948
+
949
+ function startStatePolling() {
950
+ if (typeof window.setTimeout !== 'function') return
951
+ const tick = async () => {
952
+ try {
953
+ const response = await fetch(apiUrl(STATE_ENDPOINT), {
954
+ headers: { accept: 'application/json' },
955
+ cache: 'no-store',
956
+ })
957
+ const data = await readJson(response)
958
+ if (response.ok && data !== null && data.quitRequested === true) {
959
+ if (document.getElementById(EXIT_ID) === null) {
960
+ showExitScreen({
961
+ title: 'DeepSeek Harness 已停止',
962
+ message: '本地服务已结束,正在关闭窗口…',
963
+ spinner: false,
964
+ })
965
+ }
966
+ tryCloseWindow()
967
+ return
968
+ }
969
+ } catch {
970
+ // the server may be stopping; keep the window open with the hint
971
+ }
972
+ statePollTimer = window.setTimeout(tick, 2500)
973
+ }
974
+ statePollTimer = window.setTimeout(tick, 2500)
975
+ }
976
+
977
+ // ── dynamic overlay placement ───────────────────────────────────────────
978
+ // The main interface has a CSS-grid header; the right-side controls (e.g.
979
+ // the sidebar toggle) move with the layout. Anchor the overlay right next
980
+ // to the leftmost right-side header control instead of a fixed offset, so
981
+ // no blank gap appears and the controls follow layout changes.
982
+ function positionOverlayControls() {
983
+ const overlay = document.querySelector('.dsh-ac-overlay')
984
+ if (overlay === null) return
985
+ let right = 12
986
+ let top = 8
987
+ const header = document.querySelector('header')
988
+ if (header !== null) {
989
+ const headerRect = header.getBoundingClientRect()
990
+ const controls = Array.from(header.querySelectorAll('button'))
991
+ .map((button) => button.getBoundingClientRect())
992
+ .filter((rect) => rect.width > 0 && rect.height > 0)
993
+ .filter((rect) => rect.right > headerRect.right - 320)
994
+ .filter((rect) => rect.top < headerRect.bottom + 4 && rect.bottom > headerRect.top - 4)
995
+ if (controls.length > 0) {
996
+ const left = Math.min(...controls.map((rect) => rect.left))
997
+ const controlTop = Math.min(...controls.map((rect) => rect.top))
998
+ right = Math.max(12, Math.round(window.innerWidth - left + 8))
999
+ top = Math.max(6, Math.round(controlTop))
1000
+ }
1001
+ }
1002
+ overlay.style.right = `${right}px`
1003
+ overlay.style.top = `${top}px`
1004
+ }
1005
+
1006
+ function installOverlayPositioning() {
1007
+ if (typeof window.MutationObserver !== 'function' || typeof window.ResizeObserver !== 'function') {
1008
+ return () => {}
1009
+ }
1010
+ let frame = 0
1011
+ const schedule = () => {
1012
+ if (frame !== 0) return
1013
+ frame = window.requestAnimationFrame(() => {
1014
+ frame = 0
1015
+ positionOverlayControls()
1016
+ })
1017
+ }
1018
+ positionOverlayControls()
1019
+ window.addEventListener('resize', schedule)
1020
+ const mutation = new window.MutationObserver(schedule)
1021
+ // Only structural changes and control-label changes matter; not our own
1022
+ // inline style writes (which would otherwise feed back into the observer).
1023
+ mutation.observe(document.body, {
1024
+ childList: true,
1025
+ subtree: true,
1026
+ attributes: true,
1027
+ attributeFilter: ['aria-label'],
1028
+ })
1029
+ const resize = new window.ResizeObserver(schedule)
1030
+ for (const header of document.querySelectorAll('header')) resize.observe(header)
1031
+ return () => {
1032
+ window.removeEventListener('resize', schedule)
1033
+ mutation.disconnect()
1034
+ resize.disconnect()
1035
+ if (frame !== 0) window.cancelAnimationFrame(frame)
1036
+ }
1037
+ }
1038
+
1039
+ // A tray menu entry opens the Web GUI with this hash; the SPA has no
1040
+ // deep-link route, so click the sidebar "Plugins" entry once it exists.
1041
+ const CONTROL_HASH = '#dsh-app-controls/plugins'
1042
+ const SETTINGS_HASH = '#dsh-app-controls/settings'
1043
+
1044
+ function clickPluginsNav() {
1045
+ const labels = ['插件', 'Plugins']
1046
+ const candidates = Array.from(document.querySelectorAll('button, a, [role="button"], [role="tab"], span, div'))
1047
+ .filter((element) => labels.includes((element.textContent || '').trim()))
1048
+ // Keep the innermost label: the outer wrappers carry the same text but
1049
+ // only the inner element has the click handler wired by the SPA.
1050
+ .filter((element) => !Array.from(element.children).some((child) => labels.includes((child.textContent || '').trim())))
1051
+ .filter((element) => {
1052
+ const rect = element.getBoundingClientRect()
1053
+ return rect.width > 0 && rect.height > 0 && rect.left < 420 && rect.top < window.innerHeight
1054
+ })
1055
+ for (const element of candidates) {
1056
+ element.click()
1057
+ return true
1058
+ }
1059
+ return false
1060
+ }
1061
+
1062
+ function clearControlHash() {
1063
+ try {
1064
+ window.history.replaceState(null, '', window.location.pathname + window.location.search)
1065
+ } catch {
1066
+ // keep the hash if the host does not allow history updates
1067
+ }
1068
+ }
1069
+
1070
+ function clickBundleCard() {
1071
+ const candidates = Array.from(document.querySelectorAll('button, a, [role="button"], span, div'))
1072
+ .filter((element) => {
1073
+ const text = (element.textContent || '').trim()
1074
+ return text === 'DeepSeek Harness 应用控制'
1075
+ || text === 'DeepSeek Harness App Controls'
1076
+ || text === 'dsh-app-controls'
1077
+ || text.includes('应用控制')
1078
+ || text.includes('App Controls')
1079
+ })
1080
+ .filter((element) => !Array.from(element.children).some((child) => {
1081
+ const text = (child.textContent || '').trim()
1082
+ return text.includes('应用控制') || text.includes('App Controls')
1083
+ }))
1084
+ .filter((element) => {
1085
+ const rect = element.getBoundingClientRect()
1086
+ return rect.width > 0 && rect.height > 0
1087
+ })
1088
+ for (const element of candidates) {
1089
+ element.click()
1090
+ return true
1091
+ }
1092
+ return false
1093
+ }
1094
+
1095
+ function openSettingsNavigation() {
1096
+ if (!clientContext || typeof clientContext.get !== 'function') return false
1097
+ try {
1098
+ const navigation = clientContext.get('pluginNavigation')
1099
+ if (navigation && typeof navigation.openBundle === 'function') {
1100
+ clearControlHash()
1101
+ navigation.openBundle('dsh-app-controls')
1102
+ return true
1103
+ }
1104
+ } catch {
1105
+ // fall through to the Plugins-page click path
1106
+ }
1107
+ return false
1108
+ }
1109
+
1110
+ function openControlHash() {
1111
+ if (typeof window.setTimeout !== 'function' || typeof window.location !== 'object') return
1112
+ const hash = window.location.hash
1113
+ if (hash === SETTINGS_HASH) {
1114
+ clearControlHash()
1115
+ let attempts = 0
1116
+ const openPlugins = () => {
1117
+ if (clickPluginsNav()) {
1118
+ let cardAttempts = 0
1119
+ const openCard = () => {
1120
+ if (clickBundleCard()) return
1121
+ cardAttempts += 1
1122
+ if (cardAttempts < 24) window.setTimeout(openCard, 250)
1123
+ }
1124
+ window.setTimeout(openCard, 600)
1125
+ return
1126
+ }
1127
+ attempts += 1
1128
+ if (attempts < 24) window.setTimeout(openPlugins, 250)
1129
+ }
1130
+ window.setTimeout(openPlugins, 500)
1131
+ return
1132
+ }
1133
+ if (hash !== CONTROL_HASH) return
1134
+ let attempts = 0
1135
+ const tick = () => {
1136
+ if (clickPluginsNav()) {
1137
+ clearControlHash()
1138
+ return
1139
+ }
1140
+ attempts += 1
1141
+ if (attempts < 24) window.setTimeout(tick, 250)
1142
+ }
1143
+ window.setTimeout(tick, 500)
1144
+ }
1145
+
1146
+ // ── header controls ─────────────────────────────────────────────────────
1147
+ function icon(paths) {
1148
+ return h(
1149
+ 'svg',
1150
+ { viewBox: '0 0 24 24', 'aria-hidden': 'true', focusable: 'false' },
1151
+ paths.map((d, index) => h('path', { key: index, d: d })),
1152
+ )
1153
+ }
1154
+
1155
+ const UPDATE_ICON = icon([
1156
+ 'M20.5 12a8.5 8.5 0 1 1-2.49-6.01',
1157
+ 'M20.5 4.5v5h-5',
1158
+ 'M12 8.5v7',
1159
+ 'M8.5 12.5 12 16l3.5-3.5',
1160
+ ])
1161
+ const QUIT_ICON = icon([
1162
+ 'M12 3.5v8',
1163
+ 'M6.9 6.9a7.5 7.5 0 1 0 10.2 0',
1164
+ ])
1165
+
1166
+ function IconButton(props) {
1167
+ return h(
1168
+ 'button',
1169
+ {
1170
+ type: 'button',
1171
+ className: 'dsh-app-controls-btn',
1172
+ 'data-dsh-ac-feature': props.feature,
1173
+ title: props.title,
1174
+ 'aria-label': props.title,
1175
+ onClick: props.onClick,
1176
+ },
1177
+ props.icon,
1178
+ )
1179
+ }
1180
+
1181
+ function resetUpdateButton(button) {
1182
+ if (button && button.isConnected) {
1183
+ button.disabled = false
1184
+ button.title = '检查并更新 DeepSeek Harness'
1185
+ }
1186
+ }
1187
+
1188
+ function openConfirmUpdate(status, button) {
1189
+ const channelNote = status.channel === 'next' ? '(预发布版本)' : ''
1190
+ const finish = () => {
1191
+ closeModal()
1192
+ resetUpdateButton(button)
1193
+ }
1194
+ openModal({
1195
+ title: '发现新版本',
1196
+ message:
1197
+ `当前版本:${status.current}\n` +
1198
+ `新版本:${status.candidate}${channelNote}\n\n` +
1199
+ '更新会在后台下载并安装,通常需要几分钟;期间不能结束服务,完成后会自动退出并关闭窗口。',
1200
+ dismissible: true,
1201
+ onClose: finish,
1202
+ buttons: [
1203
+ { label: '取消', variant: 'secondary', onClick: finish },
1204
+ { label: '立即更新', variant: 'primary', onClick: () => startUpdate(status, button) },
1205
+ ],
1206
+ })
1207
+ }
1208
+
1209
+ async function startUpdate(status, button) {
1210
+ closeModal()
1211
+ const progress = openProgress(status.current, status.candidate)
1212
+ progress.update({ percent: 0, message: '正在准备更新…', elapsedMs: 0 })
1213
+ try {
1214
+ const response = await fetch(apiUrl(START_ENDPOINT), {
1215
+ method: 'POST',
1216
+ headers: { 'content-type': 'application/json' },
1217
+ body: '{}',
1218
+ })
1219
+ const body = await readJson(response)
1220
+ if (!response.ok || body === null) throw new Error(failureText(body, response.status))
1221
+ if (body.ok !== true) throw new Error(body.message || '无法开始更新')
1222
+ startPolling(progress, status, button)
1223
+ } catch (error) {
1224
+ removeModal()
1225
+ resetUpdateButton(button)
1226
+ openError(`启动更新失败:${errorMessage(error)}`)
1227
+ }
1228
+ }
1229
+
1230
+ function startPolling(progress, status, button) {
1231
+ let failures = 0
1232
+ async function poll() {
1233
+ try {
1234
+ const response = await fetch(apiUrl(PROGRESS_ENDPOINT), {
1235
+ headers: { accept: 'application/json' },
1236
+ cache: 'no-store',
1237
+ })
1238
+ const data = await readJson(response)
1239
+ if (!response.ok || data === null) throw new Error('无法读取更新进度')
1240
+ failures = 0
1241
+ progress.update({
1242
+ percent: data.percent,
1243
+ message: data.message,
1244
+ activity: data.activity,
1245
+ elapsedMs: data.elapsedMs,
1246
+ })
1247
+ if (data.done === true) {
1248
+ stopPolling()
1249
+ if (data.error !== null && data.error !== undefined) {
1250
+ removeModal()
1251
+ resetUpdateButton(button)
1252
+ if (data.error === 'up-to-date') {
1253
+ openInfo('已是最新版本', data.message || 'DeepSeek Harness 已是最新版本。')
1254
+ } else {
1255
+ openError(data.message || '更新失败')
1256
+ }
1257
+ return
1258
+ }
1259
+ progress.update({
1260
+ percent: 100,
1261
+ message: data.message || '更新完成',
1262
+ activity: '',
1263
+ elapsedMs: data.elapsedMs,
1264
+ })
1265
+ window.setTimeout(() => {
1266
+ removeModal()
1267
+ showExitScreen({
1268
+ title: `更新完成:DeepSeek Harness ${data.to ?? status.candidate}`,
1269
+ message: '新版本已安装,本地服务即将退出。正在关闭窗口,之后用桌面快捷方式重新启动。',
1270
+ spinner: false,
1271
+ })
1272
+ tryCloseWindow()
1273
+ }, 900)
1274
+ return
1275
+ }
1276
+ pollTimer = window.setTimeout(poll, POLL_INTERVAL_MS)
1277
+ } catch {
1278
+ failures += 1
1279
+ if (failures >= 4) {
1280
+ stopPolling()
1281
+ removeModal()
1282
+ resetUpdateButton(button)
1283
+ openError('无法读取更新进度:服务可能已经退出。若更新可能已完成,请用桌面快捷方式重新启动 DeepSeek Harness。')
1284
+ return
1285
+ }
1286
+ pollTimer = window.setTimeout(poll, 1200)
1287
+ }
1288
+ }
1289
+ poll()
1290
+ }
1291
+
1292
+ async function onUpdate(event) {
1293
+ const button = event.currentTarget
1294
+ if (button.disabled) return
1295
+ button.disabled = true
1296
+ button.title = '正在检查更新…'
1297
+ openSpinner('检查更新', '正在查询 npm registry…')
1298
+ try {
1299
+ const response = await fetch(apiUrl(STATUS_ENDPOINT), {
1300
+ method: 'GET',
1301
+ headers: { accept: 'application/json' },
1302
+ cache: 'no-store',
1303
+ })
1304
+ const status = await readJson(response)
1305
+ if (!response.ok || status === null) throw new Error(failureText(status, response.status))
1306
+ if (status.updateAvailable !== true) {
1307
+ closeModal()
1308
+ resetUpdateButton(button)
1309
+ openInfo('已是最新版本', `DeepSeek Harness ${status.current} 已是最新版本。`)
1310
+ return
1311
+ }
1312
+ openConfirmUpdate(status, button)
1313
+ } catch (error) {
1314
+ closeModal()
1315
+ resetUpdateButton(button)
1316
+ openError(`检查更新失败:${errorMessage(error)}`)
1317
+ }
1318
+ }
1319
+
1320
+ function onQuit(event) {
1321
+ const button = event.currentTarget
1322
+ openModal({
1323
+ title: '退出 DeepSeek Harness?',
1324
+ message:
1325
+ '这会结束整个本地服务:所有会话、正在生成的回答和后台任务都会停止。\n' +
1326
+ '退出后可以用桌面快捷方式重新启动。',
1327
+ dismissible: true,
1328
+ onClose: closeModal,
1329
+ buttons: [
1330
+ { label: '取消', variant: 'secondary', onClick: closeModal },
1331
+ { label: '退出', variant: 'danger', onClick: () => performQuit(button) },
1332
+ ],
1333
+ })
1334
+ }
1335
+
1336
+ async function performQuit(button) {
1337
+ closeModal()
1338
+ if (button) button.disabled = true
1339
+ showExitScreen({
1340
+ title: '正在退出 DeepSeek Harness',
1341
+ message: '正在结束后台服务,请稍候…',
1342
+ spinner: true,
1343
+ })
1344
+ try {
1345
+ const response = await fetch(apiUrl(QUIT_ENDPOINT), {
1346
+ method: 'POST',
1347
+ headers: { 'content-type': 'application/json' },
1348
+ body: '{}',
1349
+ })
1350
+ const body = await readJson(response)
1351
+ if (!response.ok || body === null) throw new Error(failureText(body, response.status))
1352
+ showExitScreen({
1353
+ title: 'DeepSeek Harness 已退出',
1354
+ message: '本地服务已停止。正在关闭窗口,之后用桌面快捷方式重新启动。',
1355
+ spinner: false,
1356
+ })
1357
+ tryCloseWindow()
1358
+ } catch (error) {
1359
+ removeExitScreen()
1360
+ if (button && button.isConnected) button.disabled = false
1361
+ openError(`退出失败:${errorMessage(error)}`)
1362
+ }
1363
+ }
1364
+
1365
+ function controlButtons() {
1366
+ return [
1367
+ h(IconButton, {
1368
+ key: 'update',
1369
+ feature: 'update',
1370
+ title: '检查并更新 DeepSeek Harness',
1371
+ icon: UPDATE_ICON,
1372
+ onClick: onUpdate,
1373
+ }),
1374
+ h(IconButton, {
1375
+ key: 'quit',
1376
+ feature: 'quit',
1377
+ title: '退出 DeepSeek Harness(结束本地服务)',
1378
+ icon: QUIT_ICON,
1379
+ onClick: onQuit,
1380
+ }),
1381
+ ]
1382
+ }
1383
+
1384
+ // Inside a conversation: the right side of the conversation header.
1385
+ function AppControls() {
1386
+ return h(
1387
+ 'div',
1388
+ { className: 'dsh-app-controls', 'data-dsh-ac-utilities': '' },
1389
+ controlButtons(),
1390
+ )
1391
+ }
1392
+
1393
+ // Everywhere else (main interface, plugin pages): a fixed top-right
1394
+ // overlay. CSS hides it whenever the conversation header controls are
1395
+ // mounted, so the two entry points never show duplicates.
1396
+ function OverlayControls() {
1397
+ return h(
1398
+ 'div',
1399
+ { className: 'dsh-ac-overlay' },
1400
+ h('div', { className: 'dsh-ac-overlay-group' }, controlButtons()),
1401
+ )
1402
+ }
1403
+
1404
+ function apply(ctx) {
1405
+ clientContext = ctx
1406
+ injectStyles()
1407
+ bindSettingsLocale(ctx)
1408
+ applyClientSettings(clientSettings)
1409
+ void loadClientSettings()
1410
+ startStatePolling()
1411
+ openControlHash()
1412
+ const onHashChange = () => openControlHash()
1413
+ if (typeof window.addEventListener === 'function') window.addEventListener('hashchange', onHashChange)
1414
+ const stopPositioning = installOverlayPositioning()
1415
+ const disposeHeader = ctx.slots.inject(SLOT, () =>
1416
+ ctx.slots.register(
1417
+ {
1418
+ name: SLOT,
1419
+ id: 'dsh-app-controls',
1420
+ order: 100,
1421
+ registrant: 'dsh-app-controls',
1422
+ },
1423
+ AppControls,
1424
+ ),
1425
+ )
1426
+ const disposeOverlay = ctx.slots.inject('shell.overlay', () =>
1427
+ ctx.slots.register(
1428
+ {
1429
+ name: 'shell.overlay',
1430
+ id: 'dsh-app-controls-overlay',
1431
+ order: 100,
1432
+ registrant: 'dsh-app-controls',
1433
+ },
1434
+ OverlayControls,
1435
+ ),
1436
+ )
1437
+ const disposeSettings = ctx.slots.inject('plugins.bundle.config', () =>
1438
+ ctx.slots.register(
1439
+ {
1440
+ name: 'plugins.bundle.config',
1441
+ key: 'dsh-app-controls',
1442
+ locale: SETTINGS_NS,
1443
+ },
1444
+ SettingsPanel,
1445
+ ),
1446
+ )
1447
+ if (typeof ctx.effect === 'function') {
1448
+ ctx.effect(
1449
+ () => () => {
1450
+ for (const dispose of [disposeHeader, disposeOverlay, disposeSettings]) {
1451
+ try {
1452
+ if (typeof dispose === 'function') dispose()
1453
+ } catch {
1454
+ // the slot may already be gone during teardown
1455
+ }
1456
+ }
1457
+ stopPolling()
1458
+ stopStatePolling()
1459
+ if (typeof window.removeEventListener === 'function') window.removeEventListener('hashchange', onHashChange)
1460
+ removeModal()
1461
+ removeExitScreen()
1462
+ stopPositioning()
1463
+ clearClientSettingsClasses()
1464
+ const style = document.getElementById(STYLE_ID)
1465
+ if (style !== null) style.remove()
1466
+ },
1467
+ 'dsh-app-controls: header and overlay controls',
1468
+ )
1469
+ }
1470
+ }
1471
+
1472
+ exports.apply = apply
1473
+ exports.inject = ['slots']
1474
+ return module.exports
1475
+ },
1476
+ })