@moonsand/dsh-ui-optimize 0.11.8 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client.js CHANGED
@@ -111,8 +111,8 @@ window.__ModuleLoader__.load({
111
111
  'updates.notesNoZhVersion': 'No Chinese notes for this version.',
112
112
  'updates.notesSpan': 'Changes since {from}',
113
113
  'updates.updateAll': 'Update all',
114
- 'updates.needRestartHint': '{n} of them only take effect after DSH restarts — the new code is on disk, the running process still has the old one. Restarting also reloads the page, so one restart covers both. Restart when convenient.',
115
- 'updates.needRefreshHint': 'Done. Reload the page to load the new client code.',
114
+ 'updates.needRestartHint': 'Restart DSH to apply {n} plugin(s) — the new code is on disk, the running process still holds the old one. One restart also reloads the page, so you do not need to refresh afterwards.',
115
+ 'updates.needRefreshHint': 'Refresh this page to apply the update — no restart needed.',
116
116
  'updates.updating': 'Updating…',
117
117
  'updates.none': 'Nothing to update.',
118
118
  'updates.upToDate': '{n} already up to date',
@@ -131,6 +131,17 @@ window.__ModuleLoader__.load({
131
131
  'updates.section.ready': 'Ready to update',
132
132
  'updates.section.waiting': 'Not yet',
133
133
  'updates.section.waitingHint': 'Published less than 24 hours ago.',
134
+ 'updates.section.pending': 'Needs a restart',
135
+ 'updates.section.pendingHint': 'Loaded in the running host, so they cannot be replaced live. Update all handles it: DSH stops, the new versions are installed, and DSH starts again.',
136
+ 'updates.section.pendingEmpty': 'Nothing needs a restart right now — everything installable has already been installed live.',
137
+ 'updates.section.blocked': 'Not loadable on this DSH',
138
+ 'updates.section.blockedHint': 'The running DSH version cannot load these releases. Upgrade DSH first, or wait for the plugin to publish a compatible one.',
139
+ 'updates.compatTag': 'Needs {version}',
140
+ 'updates.applyStarted': 'Installing {n} more that were loaded — DSH restarts when that finishes, so this page drops for a moment.',
141
+ 'updates.applyFailed': 'Could not start the background install. Try again in a moment.',
142
+ 'updates.pendingStarting': 'Stopping DSH, installing, then starting again — the page reconnects on its own.',
143
+ 'updates.waitingRestart': 'waiting for restart',
144
+ 'updates.compatTagUnknown': 'Not loadable on this DSH',
134
145
  'updates.queued': 'Queued',
135
146
  'updates.running': 'Updating',
136
147
  'updates.succeeded': 'Updated',
@@ -218,8 +229,8 @@ window.__ModuleLoader__.load({
218
229
  'updates.notesNoZhVersion': '该版本没有中文说明。',
219
230
  'updates.notesSpan': '自 {from} 以来的改动',
220
231
  'updates.updateAll': '一键更新',
221
- 'updates.needRestartHint': '{n} 个插件要重启 DSH 才真正生效——新代码已经在磁盘上,跑着的进程还是旧的。重启会连页面一起刷新,所以重启一次就都齐了,不急着马上重。',
222
- 'updates.needRefreshHint': '都更新完了,刷新页面即可加载新的客户端代码。',
232
+ 'updates.needRestartHint': '需要重启 DSH 才能生效({n} 个插件)——新代码已在磁盘上,运行中的进程还是旧代码。重启会一并刷新页面,不用再手动刷新。',
233
+ 'updates.needRefreshHint': '刷新页面即可生效——不需要重启。',
223
234
  'updates.updating': '更新中…',
224
235
  'updates.none': '没有可更新的插件。',
225
236
  'updates.upToDate': '其余 {n} 个已是最新版',
@@ -238,6 +249,17 @@ window.__ModuleLoader__.load({
238
249
  'updates.section.ready': '可更新',
239
250
  'updates.section.waiting': '暂不可更新',
240
251
  'updates.section.waitingHint': '发布不足 24 小时',
252
+ 'updates.section.pending': '需停机更新',
253
+ 'updates.section.pendingHint': '这些插件正运行在宿主里,宿主不允许直接替换已加载的模块。点「一键更新」就行:它会自动停掉 DSH、装好新版本,再启动。',
254
+ 'updates.section.pendingEmpty': '当前没有需要停机安装的更新——能当场装的都已经装好了。',
255
+ 'updates.section.blocked': '与当前 DSH 不兼容',
256
+ 'updates.section.blockedHint': '当前运行的 DSH 版本加载不了这些版本。先升级 DSH,或等插件发布兼容版本。',
257
+ 'updates.compatTag': '需要 {version}',
258
+ 'updates.applyStarted': '另外 {n} 个正在运行的插件已开始安装——装完会自动重启 DSH,页面会短暂断开,稍后刷新即可。',
259
+ 'updates.applyFailed': '后台安装没能启动,稍后再试一次。',
260
+ 'updates.pendingStarting': '正在停掉 DSH 安装新版本,随后自动启动——页面会自己重连。',
261
+ 'updates.waitingRestart': '等待重启',
262
+ 'updates.compatTagUnknown': '与当前 DSH 不兼容',
241
263
  'updates.queued': '排队中',
242
264
  'updates.running': '更新中',
243
265
  'updates.succeeded': '已更新',
@@ -2353,6 +2375,7 @@ button.muik-shelf-row:focus-visible{outline:2px solid var(--dsw-alias-brand-prim
2353
2375
  stats.failed += 1
2354
2376
  continue
2355
2377
  }
2378
+ if (item.name === SELF_NAME) continue
2356
2379
  if (compareVersions(doc.latest, item.version) <= 0) continue
2357
2380
  const published = doc.time[doc.latest]
2358
2381
  const stamp = published === undefined ? NaN : Date.parse(published)
@@ -2362,8 +2385,13 @@ button.muik-shelf-row:focus-visible{outline:2px solid var(--dsw-alias-brand-prim
2362
2385
  * and waiting for it before painting made an already-slow list feel
2363
2386
  * frozen. The compatibility verdict lands on the row a moment later. */
2364
2387
  const row = {
2365
- compat: null,
2388
+ compat: compatBlocked.has(item.name) ? { runtime: '', required: '' } : null,
2366
2389
  name: item.name,
2390
+ /* An enabled bundle is loaded in the running host, and the host
2391
+ * refuses to replace a loaded module (`bundle-in-use`). Such a row
2392
+ * cannot be updated from here — it goes to the "restart required"
2393
+ * list with a command to run while DSH is stopped. */
2394
+ enabled: item.enabled === true,
2367
2395
  installed: item.version,
2368
2396
  latest: doc.latest,
2369
2397
  age: age,
@@ -2610,6 +2638,7 @@ button.muik-shelf-row:focus-visible{outline:2px solid var(--dsw-alias-brand-prim
2610
2638
 
2611
2639
  function updateLabel(row) {
2612
2640
  if (row.state === 'running') return translate('updates.running')
2641
+ if (row.state === 'applied') return translate('updates.waitingRestart')
2613
2642
  if (row.state === 'succeeded') return translate('updates.succeeded')
2614
2643
  if (row.state === 'failed') return translate('updates.failed')
2615
2644
  if (row.age === undefined) return translate('updates.readingAge')
@@ -2647,8 +2676,11 @@ button.muik-shelf-row:focus-visible{outline:2px solid var(--dsw-alias-brand-prim
2647
2676
  const fallbackOn = store.state.updatesFallback === true
2648
2677
  /* Same rule as the list: a fallback row counts only when the
2649
2678
  * previous release is actually newer than what is installed. */
2679
+ /* Same rule as the button: a row the running DSH cannot load is not
2680
+ * something the user can act on, so it must not inflate the badge. */
2650
2681
  updateBadge.set(
2651
2682
  scan.rows.filter(function (row) {
2683
+ if (row.compat) return false
2652
2684
  if (typeof row.age === 'number' && row.age >= FRESH_RELEASE_MS) return true
2653
2685
  if (!fallbackOn || !row.fallbackVersion) return false
2654
2686
  return compareVersions(row.fallbackVersion, row.installed) > 0
@@ -2692,6 +2724,25 @@ button.muik-shelf-row:focus-visible{outline:2px solid var(--dsw-alias-brand-prim
2692
2724
 
2693
2725
  /* Progress lives outside the component: switching tabs unmounts it,
2694
2726
  * and an install that is still running must not vanish with the view. */
2727
+ /* Versions the host rejected at install time because the running DSH cannot
2728
+ * load them. Remembered so the row lands in the incompatibility section
2729
+ * instead of offering the same doomed update on every rescan. */
2730
+ /* This plugin is running the very page that offers the update: a bundle
2731
+ * cannot replace itself while it is loaded, so it never enters the list. */
2732
+ const SELF_NAME = '@moonsand/dsh-ui-optimize'
2733
+
2734
+ const COMPAT_KEY = 'dsh-ui-optimize:compat-blocked'
2735
+ const compatBlocked = new Set()
2736
+ try {
2737
+ const saved = window.localStorage.getItem(COMPAT_KEY)
2738
+ if (saved) JSON.parse(saved).forEach(function (name) { compatBlocked.add(String(name)) })
2739
+ } catch (err) { /* private mode or bad json: start empty */ }
2740
+ function rememberCompatBlocked(name) {
2741
+ if (compatBlocked.has(name)) return
2742
+ compatBlocked.add(name)
2743
+ try { window.localStorage.setItem(COMPAT_KEY, JSON.stringify([...compatBlocked])) } catch (err) { /* ignore */ }
2744
+ }
2745
+
2695
2746
  const updateRun = {
2696
2747
  rows: [],
2697
2748
  checked: 0,
@@ -2723,6 +2774,7 @@ button.muik-shelf-row:focus-visible{outline:2px solid var(--dsw-alias-brand-prim
2723
2774
  setPhase(next)
2724
2775
  }
2725
2776
  const [run, setRun] = React.useState(updateRun.snapshot())
2777
+ /* Which command was just copied, so the button can say so briefly. */
2726
2778
  const rows = run.rows
2727
2779
  const checked = run.checked
2728
2780
  const busy = run.busy
@@ -2770,6 +2822,28 @@ button.muik-shelf-row:focus-visible{outline:2px solid var(--dsw-alias-brand-prim
2770
2822
  }
2771
2823
  }, [])
2772
2824
 
2825
+ React.useEffect(function () {
2826
+ /* Restarting DSH swaps the process under this page without reloading
2827
+ * it, so nothing would ever re-scan: the tab would keep showing rows
2828
+ * from the old process until the user switched tabs. Revalidate on a
2829
+ * slow timer, and immediately when the page comes back into view. */
2830
+ function revalidate() {
2831
+ if (document.visibilityState !== 'visible') return
2832
+ if (store.state.updates === false) return
2833
+ load().catch(function (err) {
2834
+ console.warn('[dsh-ui-optimize] revalidate failed', err)
2835
+ })
2836
+ }
2837
+ const timer = setInterval(revalidate, 60000)
2838
+ document.addEventListener('visibilitychange', revalidate)
2839
+ window.addEventListener('focus', revalidate)
2840
+ return function () {
2841
+ clearInterval(timer)
2842
+ document.removeEventListener('visibilitychange', revalidate)
2843
+ window.removeEventListener('focus', revalidate)
2844
+ }
2845
+ }, [])
2846
+
2773
2847
  function patch(name, changes) {
2774
2848
  setRows(function (previous) {
2775
2849
  return previous.map(function (row) {
@@ -2779,6 +2853,9 @@ button.muik-shelf-row:focus-visible{outline:2px solid var(--dsw-alias-brand-prim
2779
2853
  }
2780
2854
 
2781
2855
  async function load(force) {
2856
+ /* The previous run's verdict ("refresh to apply") must not sit under a
2857
+ * list that has just been re-read and shows nothing to do. */
2858
+ if (updateRun.busy !== true) setMessage('')
2782
2859
  /* "Check again" has to mean it: the cached scan would answer
2783
2860
  * instantly and the button would look broken. */
2784
2861
  if (force === true) {
@@ -2799,7 +2876,11 @@ button.muik-shelf-row:focus-visible{outline:2px solid var(--dsw-alias-brand-prim
2799
2876
  * opening the tab always re-checks, but never blanks the list or makes
2800
2877
  * the user press "Check again" to see current numbers. */
2801
2878
  const warm = scanCache.value && Date.now() - scanCache.at < SCAN_CACHE_MS ? scanCache.value : null
2802
- const carried = updateRun.rows.filter(function (row) { return row.state === 'succeeded' })
2879
+ /* Only in-flight rows survive a rescan. Finished ones used to be
2880
+ * carried over as well, which left a green "updated" card sitting in
2881
+ * the list forever — the scan already says it is up to date, so the
2882
+ * card no longer belongs anywhere. */
2883
+ const carried = updateRun.rows.filter(function (row) { return row.state === 'running' })
2803
2884
  if (warm) {
2804
2885
  const merged = carried.slice()
2805
2886
  warm.rows.forEach(function (row) {
@@ -2894,7 +2975,10 @@ button.muik-shelf-row:focus-visible{outline:2px solid var(--dsw-alias-brand-prim
2894
2975
  return null
2895
2976
  }
2896
2977
 
2897
- /* The version this row will actually end up on — the changelog range has
2978
+ /* Rows the running host refuses to replace (`bundle-in-use`) are not
2979
+ * errors, they are work for the next start: we hand over the exact
2980
+ * command instead of pretending we can install them live. */
2981
+ /* The version this row will actually end up on — the changelog range has
2898
2982
  * to stop there, otherwise a fallback row would list changes for a
2899
2983
  * release it is deliberately not installing today. */
2900
2984
  function targetVersion(row) {
@@ -2902,20 +2986,83 @@ button.muik-shelf-row:focus-visible{outline:2px solid var(--dsw-alias-brand-prim
2902
2986
  return target ? target.version : row.latest
2903
2987
  }
2904
2988
 
2989
+ /* Declared before the badge effect: that effect's dependency array is
2990
+ * evaluated during render, so a later declaration would be a TDZ hit. */
2991
+ const pendingCount = rows.filter(function (row) {
2992
+ return row.enabled === true && row.state !== 'running' && targetOf(row) !== null
2993
+ }).length
2994
+
2905
2995
  const eligible = rows.filter(function (row) {
2906
- return row.state !== 'succeeded' && targetOf(row) !== null
2996
+ /* 'applied' means the host already queued this package and is about to
2997
+ * restart DSH; offering it again would only spend another round trip. */
2998
+ return row.state !== 'succeeded' && row.state !== 'applied' && targetOf(row) !== null && row.enabled !== true
2907
2999
  })
2908
3000
 
2909
3001
  React.useEffect(function () {
2910
- updateBadge.set(eligible.length)
2911
- }, [eligible.length])
3002
+ updateBadge.set(eligible.length + pendingCount)
3003
+ }, [eligible.length, pendingCount])
3004
+
3005
+ /* Rows the host refuses to replace while it is running go to the plugin's
3006
+ * host half: it pins them, then asks the fnOS gateway to restart DSH so
3007
+ * the new versions are what actually loads. One click, one batch. */
3008
+ async function applyPending(items) {
3009
+ const body = {
3010
+ packages: items.map(function (row) {
3011
+ const target = targetOf(row)
3012
+ return { name: row.name, version: (target && target.version) || row.latest }
3013
+ }),
3014
+ }
3015
+ const candidates = []
3016
+ try {
3017
+ candidates.push(new URL('ui-optimize/desktop/apply', document.baseURI).href)
3018
+ } catch (err) {
3019
+ /* malformed baseURI: fall through to the root-relative URL */
3020
+ }
3021
+ candidates.push('/ui-optimize/desktop/apply')
3022
+ let lastError = null
3023
+ for (let i = 0; i < candidates.length; i += 1) {
3024
+ try {
3025
+ const response = await fetch(candidates[i], {
3026
+ method: 'POST',
3027
+ headers: { 'content-type': 'application/json', 'x-ui-optimize-apply': '1' },
3028
+ credentials: 'same-origin',
3029
+ cache: 'no-store',
3030
+ body: JSON.stringify(body),
3031
+ signal: AbortSignal.timeout(15000),
3032
+ })
3033
+ /* The NAS gateway answers unknown paths with 200 and a plain-text
3034
+ * "invalid token" body, so a 200 alone proves nothing: only a JSON
3035
+ * answer means the host route actually ran. */
3036
+ const text = await response.text()
3037
+ let payload = null
3038
+ try {
3039
+ payload = JSON.parse(text)
3040
+ } catch (err) {
3041
+ payload = null
3042
+ }
3043
+ if (payload === null) {
3044
+ lastError = new Error('HTTP ' + response.status + ' 非 JSON 应答')
3045
+ continue
3046
+ }
3047
+ if (!response.ok || payload.ok !== true) {
3048
+ lastError = new Error('HTTP ' + response.status + ' ' + String(payload.reason || ''))
3049
+ continue
3050
+ }
3051
+ return payload
3052
+ } catch (err) {
3053
+ lastError = err
3054
+ }
3055
+ }
3056
+ throw lastError || new Error('apply endpoint unreachable')
3057
+ }
2912
3058
 
2913
3059
  async function updateAll() {
2914
3060
  if (busy) return
3061
+ const pendingRows = groups.pending.slice()
2915
3062
  const targets = eligible.map(function (row) {
2916
3063
  return { name: row.name, from: row.installed, target: targetOf(row) }
2917
3064
  })
2918
- if (targets.length === 0) return
3065
+ if (targets.length === 0 && pendingRows.length === 0) return
2919
3066
  setBusy(true)
2920
3067
  setMessage('')
2921
3068
  let restarts = 0
@@ -2938,8 +3085,17 @@ button.muik-shelf-row:focus-visible{outline:2px solid var(--dsw-alias-brand-prim
2938
3085
  const needs = !ok ? '' : operation && operation.restartRequired ? 'restart' : 'refresh'
2939
3086
  if (needs === 'restart') restarts += 1
2940
3087
  else if (needs === 'refresh') refreshes += 1
3088
+ /* The host reports code 'UPDATE_REJECTED' for several reasons and
3089
+ * puts the real one in `message` — matching only the code meant
3090
+ * this branch never ran and the doomed row kept coming back. */
3091
+ const failureText = !ok && operation && operation.failure
3092
+ ? String(operation.failure.code || '') + ' ' + String(operation.failure.message || '')
3093
+ : ''
3094
+ const blockedNow = /incompatible/i.test(failureText)
3095
+ if (blockedNow) rememberCompatBlocked(name)
2941
3096
  patch(name, {
2942
3097
  state: ok ? 'succeeded' : 'failed',
3098
+ compat: blockedNow ? { runtime: '', required: '' } : undefined,
2943
3099
  needs: needs,
2944
3100
  percent: 100,
2945
3101
  done: ok
@@ -2951,6 +3107,18 @@ button.muik-shelf-row:focus-visible{outline:2px solid var(--dsw-alias-brand-prim
2951
3107
  ? operation.failure.code + ' — ' + operation.failure.message
2952
3108
  : (operation && operation.state) || 'failed',
2953
3109
  })
3110
+ /* The green confirmation is feedback, not a list entry: clear it
3111
+ * after a few seconds, otherwise it sits under a "0 updatable"
3112
+ * heading until the page is reloaded. */
3113
+ if (ok) {
3114
+ setTimeout(function () {
3115
+ updateRun.set({
3116
+ rows: updateRun.rows.filter(function (item) {
3117
+ return !(item.name === name && item.state === 'succeeded')
3118
+ }),
3119
+ })
3120
+ }, 10000)
3121
+ }
2954
3122
  } catch (err) {
2955
3123
  patch(name, { state: 'failed', percent: 100, detail: err.message })
2956
3124
  }
@@ -2958,19 +3126,45 @@ button.muik-shelf-row:focus-visible{outline:2px solid var(--dsw-alias-brand-prim
2958
3126
  /* The batch may outlive this mount: write the result to the shared
2959
3127
  * run state unconditionally, or a remount would come back with the
2960
3128
  * button stuck on "busy" forever. */
3129
+ let appliedPending = 0
3130
+ let applyFailed = false
3131
+ let applyError = ''
3132
+ if (pendingRows.length > 0) {
3133
+ try {
3134
+ await applyPending(pendingRows)
3135
+ appliedPending = pendingRows.length
3136
+ /* The host answers 202 before pnpm starts, so show the batch as in
3137
+ * flight right away — otherwise the click looks like a no-op until
3138
+ * the page reloads under the new DSH process. */
3139
+ pendingRows.forEach(function (row) {
3140
+ patch(row.name, { state: 'applied', percent: null, detail: translate('updates.pendingStarting') })
3141
+ })
3142
+ } catch (err) {
3143
+ applyFailed = true
3144
+ applyError = err && err.message ? String(err.message) : String(err)
3145
+ }
3146
+ }
2961
3147
  setBusy(false)
2962
3148
  if (alive.current) {
2963
- setMessage(
2964
- restarts > 0
2965
- ? translate('updates.needRestartHint').replace('{n}', String(restarts))
2966
- : refreshes > 0
2967
- ? translate('updates.needRefreshHint')
2968
- : translate('updates.reloadHint'),
2969
- )
3149
+ if (applyFailed) {
3150
+ setMessage(translate('updates.applyFailed') + (applyError ? '(' + applyError + ')' : ''))
3151
+ } else if (appliedPending > 0) {
3152
+ setMessage(translate('updates.applyStarted').replace('{n}', String(appliedPending)))
3153
+ } else {
3154
+ setMessage(
3155
+ restarts > 0
3156
+ ? translate('updates.needRestartHint').replace('{n}', String(restarts))
3157
+ : refreshes > 0
3158
+ ? translate('updates.needRefreshHint')
3159
+ : translate('updates.reloadHint'),
3160
+ )
3161
+ }
2970
3162
  }
2971
3163
  refreshUpdateBadge()
2972
3164
  }
2973
3165
 
3166
+ /* The header is built before the grouping below, so the pending count it
3167
+ * shows has to be computed here with the same rule the section uses. */
2974
3168
  const header = h(
2975
3169
  'div',
2976
3170
  { className: 'dsuik-up-header' },
@@ -2992,9 +3186,13 @@ button.muik-shelf-row:focus-visible{outline:2px solid var(--dsw-alias-brand-prim
2992
3186
  h('button', {
2993
3187
  type: 'button',
2994
3188
  className: 'dsuik-up-btn is-primary',
2995
- disabled: busy || phase !== 'ready' || eligible.length === 0,
3189
+ /* One button covers both batches: what the host can replace now,
3190
+ * plus what it will replace on the next start. */
3191
+ disabled: busy || phase !== 'ready' || eligible.length + pendingCount === 0,
2996
3192
  onClick: updateAll,
2997
- }, busy ? translate('updates.updating') : translate('updates.updateAll') + ' (' + String(eligible.length) + ')'),
3193
+ }, busy
3194
+ ? translate('updates.updating')
3195
+ : translate('updates.updateAll') + ' (' + String(eligible.length + pendingCount) + ')'),
2998
3196
  ),
2999
3197
  )
3000
3198
 
@@ -3086,7 +3284,10 @@ button.muik-shelf-row:focus-visible{outline:2px solid var(--dsw-alias-brand-prim
3086
3284
  /* A running or finished row speaks with its state, not with the plan:
3087
3285
  * the "previous release" tag belongs to a row that has not started yet,
3088
3286
  * otherwise 更新中 never gets a chance to show. */
3089
- const label = idle ? (quiet || usingFallback ? '' : updateLabel(row)) : updateLabel(row)
3287
+ /* A row the host cannot load is not a failed update to retry: it reads
3288
+ * as one fact ("this DSH cannot load it"), with the raw failure code
3289
+ * left in the log rather than on the card. */
3290
+ const label = row.compat ? '' : (idle ? (quiet || usingFallback ? '' : updateLabel(row)) : updateLabel(row))
3090
3291
  /* Nothing to install yet: say how far the nearest candidate is, so a
3091
3292
  * row that is "waiting" does not look like the plugin forgot it.
3092
3293
  * Only idle rows: a finished row must not read "已更新 · 剩余 5.1 小时". */
@@ -3097,17 +3298,20 @@ button.muik-shelf-row:focus-visible{outline:2px solid var(--dsw-alias-brand-prim
3097
3298
  const isOpen = !!open[row.name]
3098
3299
  return h(
3099
3300
  'li',
3301
+ { key: row.name, className: 'dsuik-up-item' },
3302
+ h(
3303
+ 'div',
3100
3304
  {
3101
- key: row.name,
3102
3305
  className: 'dsuik-up-row'
3103
3306
  + (row.state === 'running' ? ' is-running' : '')
3104
3307
  + (row.state === 'succeeded' ? ' is-ok' : '')
3105
- + (row.state === 'failed' ? ' is-fail' : '')
3308
+ + (row.state === 'failed' && !row.compat ? ' is-fail' : '')
3106
3309
  + (isOpen ? ' is-open' : ''),
3107
3310
  style: { animationDelay: String(Math.min(index, 12) * 18) + 'ms' },
3108
3311
  },
3109
- h('button', {
3110
- type: 'button',
3312
+ h('div', {
3313
+ role: 'button',
3314
+ tabIndex: 0,
3111
3315
  className: 'dsuik-up-head',
3112
3316
  'aria-expanded': isOpen ? 'true' : 'false',
3113
3317
  title: translate('updates.notesToggle'),
@@ -3123,6 +3327,11 @@ button.muik-shelf-row:focus-visible{outline:2px solid var(--dsw-alias-brand-prim
3123
3327
  onClick: function () {
3124
3328
  toggleNotes(row)
3125
3329
  },
3330
+ onKeyDown: function (event) {
3331
+ if (event.key !== 'Enter' && event.key !== ' ') return
3332
+ event.preventDefault()
3333
+ toggleNotes(row)
3334
+ },
3126
3335
  },
3127
3336
  h('span', { className: 'dsuik-up-main' },
3128
3337
  h('span', { className: 'dsuik-up-name' }, row.name),
@@ -3133,11 +3342,13 @@ button.muik-shelf-row:focus-visible{outline:2px solid var(--dsw-alias-brand-prim
3133
3342
  soon ? h('span', { className: 'dsuik-up-soon' }, soon) : null,
3134
3343
  label ? h('span', { className: 'dsuik-up-tag' }, label) : null,
3135
3344
  fallbackShown ? h('span', { className: 'dsuik-up-tag', title: translate('updates.fallbackWhy') }, translate('updates.fallbackTag')) : null,
3136
- row.compat && !row.state
3345
+ row.compat
3137
3346
  ? h('span', { className: 'dsuik-up-tag is-warn', title: translate('updates.section.blockedHint') },
3138
- translate('updates.compatTag').replace('{version}', String(row.compat.required || row.compat.runtime || '?')))
3347
+ row.compat.required || row.compat.runtime
3348
+ ? translate('updates.compatTag').replace('{version}', String(row.compat.required || row.compat.runtime))
3349
+ : translate('updates.compatTagUnknown'))
3139
3350
  : null,
3140
- row.detail ? h('span', { className: 'dsuik-up-detail' }, row.detail) : null,
3351
+ row.detail && !row.compat ? h('span', { className: 'dsuik-up-detail' }, row.detail) : null,
3141
3352
  ),
3142
3353
  h('span', { className: 'dsuik-up-chev', 'aria-hidden': 'true' }, isOpen ? '▾' : '▸'),
3143
3354
  ),
@@ -3147,15 +3358,21 @@ button.muik-shelf-row:focus-visible{outline:2px solid var(--dsw-alias-brand-prim
3147
3358
  : h('div', { className: 'dsuik-up-bar' }, h('i', { style: { width: String(row.percent || 0) + '%' } })))
3148
3359
  : null,
3149
3360
  isOpen ? h('div', { className: 'dsuik-up-notes' }, notesView(row.name, row)) : null,
3361
+ ),
3150
3362
  )
3151
3363
  }
3152
3364
 
3153
3365
  /* Two areas: everything the 24-hour rule lets us touch on top, the rest
3154
3366
  * below it, so the button above always matches the list above. */
3155
- const groups = { ready: [], blocked: [], waiting: [] }
3367
+ const groups = { ready: [], pending: [], blocked: [], waiting: [] }
3156
3368
  rows.forEach(function (row) {
3157
- const ready = row.state === 'succeeded' || targetOf(row) !== null
3158
- if (ready) groups.ready.push(row)
3369
+ /* A row we are actively installing belongs with the rows you can act
3370
+ * on, even when its release is still inside the 24-hour window —
3371
+ * otherwise a forced update disappears into the "waiting" list while
3372
+ * its progress bar is still moving. */
3373
+ const ready = row.state === 'succeeded' || row.state === 'running' || targetOf(row) !== null
3374
+ if (row.enabled === true && row.state !== 'running' && targetOf(row) !== null) groups.pending.push(row)
3375
+ else if (ready) groups.ready.push(row)
3159
3376
  else if (row.compat && row.state !== 'succeeded') groups.blocked.push(row)
3160
3377
  else groups.waiting.push(row)
3161
3378
  })
@@ -3173,14 +3390,15 @@ button.muik-shelf-row:focus-visible{outline:2px solid var(--dsw-alias-brand-prim
3173
3390
  * "30 checked" next to ten visible rows reads like a failed scan. */
3174
3391
  const upToDate = Math.max(0, checked - rows.length)
3175
3392
 
3176
- function sectionArea(titleKey, items, muted, hintKey, always) {
3393
+ function sectionArea(titleKey, items, muted, hintKey, always, count) {
3177
3394
  if (items.length === 0 && !always) return null
3395
+ const shown = typeof count === 'number' ? count : items.length
3178
3396
  return h(
3179
3397
  'section',
3180
3398
  { className: 'dsuik-up-section' + (muted ? ' is-muted' : '') },
3181
3399
  h('div', { className: 'dsuik-up-section-head' },
3182
3400
  h('p', { className: 'dsuik-up-section-title' },
3183
- translate(titleKey) + ' (' + String(items.length) + ')'),
3401
+ translate(titleKey) + ' (' + String(shown) + ')'),
3184
3402
  hintKey
3185
3403
  ? h('p', { className: 'dsuik-up-section-hint' },
3186
3404
  hintKey.indexOf('updates.') === 0 ? translate(hintKey) : hintKey)
@@ -3217,10 +3435,28 @@ button.muik-shelf-row:focus-visible{outline:2px solid var(--dsw-alias-brand-prim
3217
3435
  : null,
3218
3436
  /* The ready area stays on screen even when it is empty, so the page
3219
3437
  * always answers "is there anything for me?" instead of going blank. */
3220
- phase === 'ready' ? sectionArea('updates.section.ready', groups.ready, false, null, true) : null,
3438
+ phase === 'ready'
3439
+ ? sectionArea(
3440
+ 'updates.section.ready',
3441
+ groups.ready,
3442
+ false,
3443
+ null,
3444
+ true,
3445
+ groups.ready.filter(function (row) { return row.state !== 'succeeded' }).length,
3446
+ )
3447
+ : null,
3221
3448
  /* The closing hint belongs to the batch it talks about: right under the
3222
3449
  * rows you just updated, not after two unrelated sections. */
3223
3450
  phase === 'ready' && message ? h('p', { className: 'dsuik-up-note is-after-ready' }, message) : null,
3451
+ phase === 'ready'
3452
+ ? sectionArea(
3453
+ 'updates.section.pending',
3454
+ groups.pending,
3455
+ true,
3456
+ groups.pending.length > 0 ? 'updates.section.pendingHint' : 'updates.section.pendingEmpty',
3457
+ true,
3458
+ )
3459
+ : null,
3224
3460
  phase === 'ready' ? sectionArea('updates.section.waiting', groups.waiting, true, 'updates.section.waitingHint', false) : null,
3225
3461
  phase === 'ready'
3226
3462
  ? sectionArea(
@@ -3266,6 +3502,8 @@ button.muik-shelf-row:focus-visible{outline:2px solid var(--dsw-alias-brand-prim
3266
3502
  .dsuik-up-loading{display:flex;align-items:center;justify-content:center;gap:8px;padding:34px 0 30px;font-size:13px;color:var(--dsw-alias-label-secondary);animation:dsuik-up-in .2s ease-out both;}
3267
3503
  @media (prefers-reduced-motion: reduce){.dsuik-up-section,.dsuik-up-row,.dsuik-up-loading{animation:none;}}
3268
3504
  .dsuik-up-list{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:10px;align-items:flex-start;}
3505
+ .dsuik-up-item{display:flex;align-items:center;gap:8px;align-self:flex-start;max-width:100%;}
3506
+ .dsuik-up-item .dsuik-up-row{align-self:auto;}
3269
3507
  .dsuik-up-row{display:flex;flex-direction:column;gap:4px;width:auto;align-self:flex-start;padding:3px 10px;border:1px solid var(--dsw-alias-border-l1);border-radius:999px;background:var(--dsw-alias-bg-layer-1);animation:dsuik-up-in .24s cubic-bezier(.2,.8,.3,1) both;transition:border-color .2s ease,opacity .25s ease;}
3270
3508
  .dsuik-up-head{display:flex;align-items:center;flex-wrap:nowrap;gap:6px;margin:0;padding:0;border:0;background:none;font:inherit;color:inherit;cursor:pointer;text-align:left;}
3271
3509
  .dsuik-up-chev{font-size:10px;line-height:1;color:var(--dsw-alias-label-tertiary, var(--dsw-alias-label-secondary));}
@@ -29,7 +29,7 @@
29
29
  * @module @moonsand/dsh-desktop-restart
30
30
  */
31
31
  import { spawn } from 'node:child_process'
32
- import { existsSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
32
+ import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
33
33
  import { tmpdir } from 'node:os'
34
34
  import { join } from 'node:path'
35
35
 
@@ -52,6 +52,17 @@ const STATUS_PATH = `${PREFIX}/status`
52
52
  /** Arming self-test: arms a watchdog without killing anything, and reports the outcome. */
53
53
  const DIAGNOSE_PATH = `${PREFIX}/diagnose`
54
54
 
55
+ /** Install the packages the running host refuses to replace. The child process
56
+ * does the pnpm run *after* this reply flushes, then asks the fnOS gateway to
57
+ * restart DSH so the new versions are what actually loads. */
58
+ const APPLY_PATH = `${PREFIX}/apply`
59
+
60
+ /** Where the detached apply run keeps its log and backups. */
61
+ const APPLY_DIR = join(process.env.DSH_HOME || tmpdir(), '.ui-optimize')
62
+
63
+ /** Registry pinned to the public one: the machine default is a read-only mirror. */
64
+ const APPLY_REGISTRY = 'https://registry.npmjs.org/'
65
+
55
66
  /** Milliseconds the helper waits before arming, so the reply can flush. */
56
67
  const RESTART_LEAD_MS = 300
57
68
 
@@ -595,8 +606,46 @@ function launchRestartHelper(executable, mode = 'restart') {
595
606
  * @param request - Node request.
596
607
  * @returns true when the caller is this application's own page.
597
608
  */
609
+ function trustedHostName(host) {
610
+ const name = String(host || '').trim().toLowerCase().replace(/^\[|\]$/g, '').split(':')[0]
611
+ if (name === '' || name === undefined) return false
612
+ if (name === '127.0.0.1' || name === 'localhost' || name === '::1') return true
613
+ const configured = String(process.env.DSH_TRUSTED_HOSTS || '')
614
+ .split(',')
615
+ .map((entry) => entry.trim().toLowerCase())
616
+ .filter(Boolean)
617
+ return configured.includes(name)
618
+ }
619
+
620
+ /**
621
+ * Whether the caller may restart this application.
622
+ *
623
+ * Three shapes are accepted.
624
+ * 1. The desktop shell's own marker header.
625
+ * 2. The page's apply header: a cross-origin page cannot set it without a preflight, and
626
+ * none of these routes answer CORS headers.
627
+ * 3. A page served by this Host (or by the NAS gateway in front of it): `Origin` and
628
+ * `Host` name the same trusted host. Browsers always send both, so the old
629
+ * "no Host and no Origin" loopback rule never matched a real page — a gateway that
630
+ * strips the custom header left the button dead.
631
+ *
632
+ * @param request - Node request.
633
+ * @returns true when the caller is this application's own page.
634
+ */
598
635
  function sameOriginCaller(request) {
599
636
  if (request.headers['x-dsh-desktop-restart'] === '1') return true
637
+ /* The page's own apply call carries this header. A cross-origin page cannot set
638
+ * it without a preflight, and this route answers no CORS headers. */
639
+ if (request.headers['x-ui-optimize-apply'] === '1') return true
640
+ const origin = request.headers.origin
641
+ const host = request.headers.host
642
+ if (typeof origin === 'string' && typeof host === 'string') {
643
+ try {
644
+ if (new URL(origin).host === host && trustedHostName(host)) return true
645
+ } catch (error) {
646
+ /* An unparsable Origin is treated as foreign. */
647
+ }
648
+ }
600
649
  if (request.headers.host !== undefined || request.headers.origin !== undefined) return false
601
650
  if (request.headers.forwarded !== undefined) return false
602
651
  const address = request.socket.remoteAddress
@@ -644,6 +693,74 @@ async function waitForArmStatus(deadlineMs) {
644
693
  * @param request - Node request.
645
694
  * @param response - Node response.
646
695
  */
696
+ const SPEC_NAME = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/i
697
+ const SPEC_VERSION = /^\d+\.\d+\.\d+(?:-[0-9a-z.-]+)?$/i
698
+
699
+ /** Read `{ packages: [{ name, version }] }` and turn it into `name@version` specs.
700
+ * Everything is validated here: the values end up in a shell script. */
701
+ function parseApplyBody(body) {
702
+ let parsed
703
+ try {
704
+ parsed = JSON.parse(body || '{}')
705
+ } catch {
706
+ throw new Error('body is not JSON')
707
+ }
708
+ const list = Array.isArray(parsed.packages) ? parsed.packages : []
709
+ if (list.length === 0) throw new Error('packages is empty')
710
+ if (list.length > 40) throw new Error('too many packages')
711
+ const seen = new Set()
712
+ const specs = []
713
+ for (const item of list) {
714
+ const name = typeof item?.name === 'string' ? item.name.trim() : ''
715
+ const version = typeof item?.version === 'string' ? item.version.trim() : ''
716
+ if (!SPEC_NAME.test(name)) throw new Error('bad package name: ' + name)
717
+ if (!SPEC_VERSION.test(version)) throw new Error('bad version: ' + version)
718
+ const spec = name + '@' + version
719
+ if (seen.has(spec)) continue
720
+ seen.add(spec)
721
+ specs.push(spec)
722
+ }
723
+ if (specs.length === 0) throw new Error('packages is empty')
724
+ return specs
725
+ }
726
+
727
+ /** Write the detached apply script and return its path. The script installs the
728
+ * pinned versions, rolls back both files when pnpm fails, and only then asks the
729
+ * fnOS gateway to restart DSH — so a failure leaves the old versions in place. */
730
+ function writeApplyScript(specs) {
731
+ mkdirSync(APPLY_DIR, { recursive: true })
732
+ const profile = join(process.env.DSH_HOME || '', 'profiles', 'web')
733
+ const script = join(APPLY_DIR, 'apply.sh')
734
+ const log = join(APPLY_DIR, 'apply.log')
735
+ const stamp = new Date().toISOString().replace(/[-:T]/g, '').slice(0, 14)
736
+ const lines = [
737
+ '#!/bin/bash',
738
+ 'set -u',
739
+ 'exec >>' + JSON.stringify(log) + ' 2>&1',
740
+ 'echo "== $(date -Is) apply start =="',
741
+ 'cd ' + JSON.stringify(profile) + ' || { echo "no profile dir"; exit 1; }',
742
+ 'cp -p package.json package.json.bak-' + stamp,
743
+ 'cp -p pnpm-lock.yaml pnpm-lock.yaml.bak-' + stamp + ' 2>/dev/null || true',
744
+ 'sleep 1',
745
+ '/vol1/@apphome/fn-deepseek-harness/.npm-global/bin/pnpm add ' +
746
+ specs.map((spec) => JSON.stringify(spec)).join(' ') +
747
+ ' --registry=' + APPLY_REGISTRY,
748
+ 'rc=$?',
749
+ 'if [ $rc -ne 0 ]; then',
750
+ ' echo "pnpm failed rc=$rc — rolling back"',
751
+ ' cp -p package.json.bak-' + stamp + ' package.json',
752
+ ' cp -p pnpm-lock.yaml.bak-' + stamp + ' pnpm-lock.yaml 2>/dev/null || true',
753
+ 'else',
754
+ ' echo "pnpm ok — asking the gateway to restart DSH"',
755
+ ' curl -sS -m 20 --unix-socket ' + JSON.stringify(process.env.DSH_GATEWAY_SOCK || '/vol1/@appcenter/fn-deepseek-harness/app.sock') +
756
+ ' -X POST -H "x-requested-with: fetch" -H "x-trim-isadmin: true" http://localhost/__fnos-gateway/control/web/restart >/dev/null 2>&1 || echo "restart request failed"',
757
+ 'fi',
758
+ 'echo "== $(date -Is) apply done (rc=$rc) =="',
759
+ ]
760
+ writeFileSync(script, lines.join('\n') + '\n', { mode: 0o700 })
761
+ return script
762
+ }
763
+
647
764
  async function handleRequest(ctx, request, response) {
648
765
  const reply = (status, body) => {
649
766
  response.writeHead(status, {
@@ -691,6 +808,37 @@ async function handleRequest(ctx, request, response) {
691
808
  logPath: HELPER_LOG_PATH,
692
809
  })
693
810
  }
811
+ if (pathname === APPLY_PATH) {
812
+ if (request.method !== 'POST') return reply(405, { ok: false, reason: 'method-not-allowed' })
813
+ if (!sameOriginCaller(request)) return reply(403, { ok: false, reason: 'cross-origin' })
814
+ let body = ''
815
+ for await (const chunk of request) {
816
+ body += chunk
817
+ if (body.length > 64 * 1024) return reply(413, { ok: false, reason: 'too-large' })
818
+ }
819
+ let specs
820
+ try {
821
+ specs = parseApplyBody(body)
822
+ } catch (error) {
823
+ return reply(400, {
824
+ ok: false,
825
+ reason: 'bad-request',
826
+ message: error instanceof Error ? error.message : String(error),
827
+ })
828
+ }
829
+ try {
830
+ const script = writeApplyScript(specs)
831
+ const child = spawn('/bin/bash', [script], { detached: true, stdio: 'ignore' })
832
+ child.unref()
833
+ return reply(202, { ok: true, specs: specs.length, logPath: join(APPLY_DIR, 'apply.log') })
834
+ } catch (error) {
835
+ return reply(500, {
836
+ ok: false,
837
+ reason: 'spawn-failed',
838
+ message: error instanceof Error ? error.message : String(error),
839
+ })
840
+ }
841
+ }
694
842
  if (pathname !== RESTART_PATH) return reply(404, { ok: false, reason: 'not-found' })
695
843
  if (request.method !== 'POST') return reply(405, { ok: false, reason: 'method-not-allowed' })
696
844
  if (!sameOriginCaller(request)) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@moonsand/dsh-ui-optimize",
3
- "version": "0.11.8",
3
+ "version": "0.12.0",
4
4
  "type": "module",
5
5
  "description": "Switches that tune how DeepSeek Harness looks and behaves across the whole interface, not just a few screens — each works on its own and more arrive as the shell grows: an eight-theme minimalist gallery, sidebar panel folding, and reload/restart buttons at the sidebar foot. · 调 DeepSeek Harness 整体观感与操作的开关集合,管的是整套界面而不只是某几块;每个开关独立生效,随宿主能力增长继续增加:8 套极简主题画廊、侧栏面板收纳,以及侧栏底部的刷新界面与重启应用按钮。",
6
6
  "license": "MIT",