@moonsand/dsh-ui-optimize 0.11.10 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client.js CHANGED
@@ -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',
@@ -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': '已更新',
@@ -846,7 +868,18 @@ body:not([data-ds-dark-theme]) .dsuik-mc > .dsuik-mc-b{display:none;}
846
868
  const restartGate = featureGate('restart', env)
847
869
  /* The shelf also needs the slot API: without it the switch stays off and
848
870
  * says why, instead of offering something that cannot work. */
849
- const sidebarGate = slotsCoreApi
871
+ /* What the shelf actually needs is the slots *service* (entriesOfSlot);
872
+ * the resolveSlotLabel helper is a bonus for nicer labels. Gating on the
873
+ * module alone disabled the switch on hosts that do not expose it. */
874
+ let slotsService = null
875
+ try {
876
+ slotsService = ctx.slots || (typeof ctx.get === 'function' ? ctx.get('slots') : null)
877
+ } catch (err) {
878
+ slotsService = null
879
+ }
880
+ const shelfReady =
881
+ (slotsService && typeof slotsService.entriesOfSlot === 'function') || slotsCoreApi !== null
882
+ const sidebarGate = shelfReady
850
883
  ? featureGate('sidebar', env)
851
884
  : { available: false, reason: translate('sidebar.unavailable') }
852
885
 
@@ -1541,6 +1574,11 @@ body:not([data-ds-dark-theme]) .dsuik-mc > .dsuik-mc-b{display:none;}
1541
1574
  const SHELF_ID = 'muik-panels'
1542
1575
  const SHELF_ATTR = 'data-muik-shelf'
1543
1576
  const SHELF_ROW_ATTR = 'data-muik-shelf-row'
1577
+ /* The rows we need to hide live in the same list as our own row. Marking that
1578
+ * list is nesting-proof: earlier builds nested it two levels below the
1579
+ * sidebar root, newer ones deeper, and a fixed `> nav > *` selector silently
1580
+ * stopped matching — which showed the whole menu twice. */
1581
+ const SHELF_LIST_ATTR = 'data-muik-shelf-list'
1544
1582
 
1545
1583
  let slotsCoreApi = null
1546
1584
  try {
@@ -1558,6 +1596,7 @@ body:not([data-ds-dark-theme]) .dsuik-mc > .dsuik-mc-b{display:none;}
1558
1596
 
1559
1597
  const SHELF_CSS = `
1560
1598
  [${SHELF_ATTR}="on"] > nav > *:not([${SHELF_ROW_ATTR}]):not([data-muik-keep]){display:none!important}
1599
+ [${SHELF_LIST_ATTR}] > *:not([${SHELF_ROW_ATTR}]):not([data-muik-keep]){display:none!important}
1561
1600
  button.muik-shelf-row{display:flex;align-items:center;gap:10px;box-sizing:border-box;width:100%;height:36px;padding:0 10px;border:0;border-radius:8px;background:transparent;color:var(--dsw-alias-label-primary,inherit);font:inherit;font-size:13px;text-align:left;cursor:pointer}
1562
1601
  button.muik-shelf-row:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(127,127,127,.12))}
1563
1602
  button.muik-shelf-row:focus-visible{outline:2px solid var(--dsw-alias-brand-primary,#4d6bfe);outline-offset:-2px}
@@ -1697,13 +1736,28 @@ button.muik-shelf-row:focus-visible{outline:2px solid var(--dsw-alias-brand-prim
1697
1736
  // label itself, so the row to mark is that wrapper — not our glyph.
1698
1737
  const row = glyph && typeof glyph.closest === 'function' ? glyph.closest('button') : null
1699
1738
  if (!row) return undefined
1700
- const nav = row.parentElement
1739
+ /* Newer shells wrap every row in its own element (`panelEntry` in
1740
+ * 0.2.2-rc.3), so `row.parentElement` is a one-child wrapper, not the
1741
+ * list. Walk up through single-child wrappers to find the real list:
1742
+ * hiding that list's other children is what folds the menu. */
1743
+ let entry = row
1744
+ for (let depth = 0; depth < 5; depth += 1) {
1745
+ const parent = entry.parentElement
1746
+ if (!parent || parent.children.length !== 1) break
1747
+ entry = parent
1748
+ }
1749
+ const list = entry.parentElement
1750
+ const nav = list || row.parentElement
1701
1751
  const root = nav ? nav.parentElement : null
1702
1752
  if (!root) return undefined
1703
1753
  rowRef.current = row
1704
1754
  row.setAttribute(SHELF_ROW_ATTR, '')
1755
+ /* The wrapper has to survive too: hiding it would take our row with it. */
1756
+ if (entry !== row) entry.setAttribute(SHELF_ROW_ATTR, '')
1705
1757
  row.style.display = enabled ? '' : 'none'
1706
1758
  root.setAttribute(SHELF_ATTR, enabled ? 'on' : 'off')
1759
+ if (enabled) nav.setAttribute(SHELF_LIST_ATTR, '')
1760
+ else nav.removeAttribute(SHELF_LIST_ATTR)
1707
1761
 
1708
1762
  // The shell appends its own "More" row after the registered rows, and its
1709
1763
  // menu holds content that is not a panellist entry. Hiding that row would
@@ -1714,7 +1768,7 @@ button.muik-shelf-row:focus-visible{outline:2px solid var(--dsw-alias-brand-prim
1714
1768
  if (actions.length > 0) {
1715
1769
  const kids = nav.children
1716
1770
  for (let i = kids.length - 1; i >= 0; i -= 1) {
1717
- if (kids[i] !== row) {
1771
+ if (kids[i] !== row && kids[i] !== entry) {
1718
1772
  keepRow = kids[i]
1719
1773
  // Kept visible on purpose. The shell's More menu only opens from a
1720
1774
  // trusted click: synthetic click(), full pointer sequences and a
@@ -2353,6 +2407,7 @@ button.muik-shelf-row:focus-visible{outline:2px solid var(--dsw-alias-brand-prim
2353
2407
  stats.failed += 1
2354
2408
  continue
2355
2409
  }
2410
+ if (item.name === SELF_NAME) continue
2356
2411
  if (compareVersions(doc.latest, item.version) <= 0) continue
2357
2412
  const published = doc.time[doc.latest]
2358
2413
  const stamp = published === undefined ? NaN : Date.parse(published)
@@ -2362,8 +2417,13 @@ button.muik-shelf-row:focus-visible{outline:2px solid var(--dsw-alias-brand-prim
2362
2417
  * and waiting for it before painting made an already-slow list feel
2363
2418
  * frozen. The compatibility verdict lands on the row a moment later. */
2364
2419
  const row = {
2365
- compat: null,
2420
+ compat: compatBlocked.has(item.name) ? { runtime: '', required: '' } : null,
2366
2421
  name: item.name,
2422
+ /* An enabled bundle is loaded in the running host, and the host
2423
+ * refuses to replace a loaded module (`bundle-in-use`). Such a row
2424
+ * cannot be updated from here — it goes to the "restart required"
2425
+ * list with a command to run while DSH is stopped. */
2426
+ enabled: item.enabled === true,
2367
2427
  installed: item.version,
2368
2428
  latest: doc.latest,
2369
2429
  age: age,
@@ -2610,6 +2670,7 @@ button.muik-shelf-row:focus-visible{outline:2px solid var(--dsw-alias-brand-prim
2610
2670
 
2611
2671
  function updateLabel(row) {
2612
2672
  if (row.state === 'running') return translate('updates.running')
2673
+ if (row.state === 'applied') return translate('updates.waitingRestart')
2613
2674
  if (row.state === 'succeeded') return translate('updates.succeeded')
2614
2675
  if (row.state === 'failed') return translate('updates.failed')
2615
2676
  if (row.age === undefined) return translate('updates.readingAge')
@@ -2647,8 +2708,11 @@ button.muik-shelf-row:focus-visible{outline:2px solid var(--dsw-alias-brand-prim
2647
2708
  const fallbackOn = store.state.updatesFallback === true
2648
2709
  /* Same rule as the list: a fallback row counts only when the
2649
2710
  * previous release is actually newer than what is installed. */
2711
+ /* Same rule as the button: a row the running DSH cannot load is not
2712
+ * something the user can act on, so it must not inflate the badge. */
2650
2713
  updateBadge.set(
2651
2714
  scan.rows.filter(function (row) {
2715
+ if (row.compat) return false
2652
2716
  if (typeof row.age === 'number' && row.age >= FRESH_RELEASE_MS) return true
2653
2717
  if (!fallbackOn || !row.fallbackVersion) return false
2654
2718
  return compareVersions(row.fallbackVersion, row.installed) > 0
@@ -2692,6 +2756,25 @@ button.muik-shelf-row:focus-visible{outline:2px solid var(--dsw-alias-brand-prim
2692
2756
 
2693
2757
  /* Progress lives outside the component: switching tabs unmounts it,
2694
2758
  * and an install that is still running must not vanish with the view. */
2759
+ /* Versions the host rejected at install time because the running DSH cannot
2760
+ * load them. Remembered so the row lands in the incompatibility section
2761
+ * instead of offering the same doomed update on every rescan. */
2762
+ /* This plugin is running the very page that offers the update: a bundle
2763
+ * cannot replace itself while it is loaded, so it never enters the list. */
2764
+ const SELF_NAME = '@moonsand/dsh-ui-optimize'
2765
+
2766
+ const COMPAT_KEY = 'dsh-ui-optimize:compat-blocked'
2767
+ const compatBlocked = new Set()
2768
+ try {
2769
+ const saved = window.localStorage.getItem(COMPAT_KEY)
2770
+ if (saved) JSON.parse(saved).forEach(function (name) { compatBlocked.add(String(name)) })
2771
+ } catch (err) { /* private mode or bad json: start empty */ }
2772
+ function rememberCompatBlocked(name) {
2773
+ if (compatBlocked.has(name)) return
2774
+ compatBlocked.add(name)
2775
+ try { window.localStorage.setItem(COMPAT_KEY, JSON.stringify([...compatBlocked])) } catch (err) { /* ignore */ }
2776
+ }
2777
+
2695
2778
  const updateRun = {
2696
2779
  rows: [],
2697
2780
  checked: 0,
@@ -2723,6 +2806,7 @@ button.muik-shelf-row:focus-visible{outline:2px solid var(--dsw-alias-brand-prim
2723
2806
  setPhase(next)
2724
2807
  }
2725
2808
  const [run, setRun] = React.useState(updateRun.snapshot())
2809
+ /* Which command was just copied, so the button can say so briefly. */
2726
2810
  const rows = run.rows
2727
2811
  const checked = run.checked
2728
2812
  const busy = run.busy
@@ -2770,6 +2854,28 @@ button.muik-shelf-row:focus-visible{outline:2px solid var(--dsw-alias-brand-prim
2770
2854
  }
2771
2855
  }, [])
2772
2856
 
2857
+ React.useEffect(function () {
2858
+ /* Restarting DSH swaps the process under this page without reloading
2859
+ * it, so nothing would ever re-scan: the tab would keep showing rows
2860
+ * from the old process until the user switched tabs. Revalidate on a
2861
+ * slow timer, and immediately when the page comes back into view. */
2862
+ function revalidate() {
2863
+ if (document.visibilityState !== 'visible') return
2864
+ if (store.state.updates === false) return
2865
+ load().catch(function (err) {
2866
+ console.warn('[dsh-ui-optimize] revalidate failed', err)
2867
+ })
2868
+ }
2869
+ const timer = setInterval(revalidate, 60000)
2870
+ document.addEventListener('visibilitychange', revalidate)
2871
+ window.addEventListener('focus', revalidate)
2872
+ return function () {
2873
+ clearInterval(timer)
2874
+ document.removeEventListener('visibilitychange', revalidate)
2875
+ window.removeEventListener('focus', revalidate)
2876
+ }
2877
+ }, [])
2878
+
2773
2879
  function patch(name, changes) {
2774
2880
  setRows(function (previous) {
2775
2881
  return previous.map(function (row) {
@@ -2779,6 +2885,9 @@ button.muik-shelf-row:focus-visible{outline:2px solid var(--dsw-alias-brand-prim
2779
2885
  }
2780
2886
 
2781
2887
  async function load(force) {
2888
+ /* The previous run's verdict ("refresh to apply") must not sit under a
2889
+ * list that has just been re-read and shows nothing to do. */
2890
+ if (updateRun.busy !== true) setMessage('')
2782
2891
  /* "Check again" has to mean it: the cached scan would answer
2783
2892
  * instantly and the button would look broken. */
2784
2893
  if (force === true) {
@@ -2799,7 +2908,11 @@ button.muik-shelf-row:focus-visible{outline:2px solid var(--dsw-alias-brand-prim
2799
2908
  * opening the tab always re-checks, but never blanks the list or makes
2800
2909
  * the user press "Check again" to see current numbers. */
2801
2910
  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' })
2911
+ /* Only in-flight rows survive a rescan. Finished ones used to be
2912
+ * carried over as well, which left a green "updated" card sitting in
2913
+ * the list forever — the scan already says it is up to date, so the
2914
+ * card no longer belongs anywhere. */
2915
+ const carried = updateRun.rows.filter(function (row) { return row.state === 'running' })
2803
2916
  if (warm) {
2804
2917
  const merged = carried.slice()
2805
2918
  warm.rows.forEach(function (row) {
@@ -2894,7 +3007,10 @@ button.muik-shelf-row:focus-visible{outline:2px solid var(--dsw-alias-brand-prim
2894
3007
  return null
2895
3008
  }
2896
3009
 
2897
- /* The version this row will actually end up on — the changelog range has
3010
+ /* Rows the running host refuses to replace (`bundle-in-use`) are not
3011
+ * errors, they are work for the next start: we hand over the exact
3012
+ * command instead of pretending we can install them live. */
3013
+ /* The version this row will actually end up on — the changelog range has
2898
3014
  * to stop there, otherwise a fallback row would list changes for a
2899
3015
  * release it is deliberately not installing today. */
2900
3016
  function targetVersion(row) {
@@ -2902,20 +3018,83 @@ button.muik-shelf-row:focus-visible{outline:2px solid var(--dsw-alias-brand-prim
2902
3018
  return target ? target.version : row.latest
2903
3019
  }
2904
3020
 
3021
+ /* Declared before the badge effect: that effect's dependency array is
3022
+ * evaluated during render, so a later declaration would be a TDZ hit. */
3023
+ const pendingCount = rows.filter(function (row) {
3024
+ return row.enabled === true && row.state !== 'running' && targetOf(row) !== null
3025
+ }).length
3026
+
2905
3027
  const eligible = rows.filter(function (row) {
2906
- return row.state !== 'succeeded' && targetOf(row) !== null
3028
+ /* 'applied' means the host already queued this package and is about to
3029
+ * restart DSH; offering it again would only spend another round trip. */
3030
+ return row.state !== 'succeeded' && row.state !== 'applied' && targetOf(row) !== null && row.enabled !== true
2907
3031
  })
2908
3032
 
2909
3033
  React.useEffect(function () {
2910
- updateBadge.set(eligible.length)
2911
- }, [eligible.length])
3034
+ updateBadge.set(eligible.length + pendingCount)
3035
+ }, [eligible.length, pendingCount])
3036
+
3037
+ /* Rows the host refuses to replace while it is running go to the plugin's
3038
+ * host half: it pins them, then asks the fnOS gateway to restart DSH so
3039
+ * the new versions are what actually loads. One click, one batch. */
3040
+ async function applyPending(items) {
3041
+ const body = {
3042
+ packages: items.map(function (row) {
3043
+ const target = targetOf(row)
3044
+ return { name: row.name, version: (target && target.version) || row.latest }
3045
+ }),
3046
+ }
3047
+ const candidates = []
3048
+ try {
3049
+ candidates.push(new URL('ui-optimize/desktop/apply', document.baseURI).href)
3050
+ } catch (err) {
3051
+ /* malformed baseURI: fall through to the root-relative URL */
3052
+ }
3053
+ candidates.push('/ui-optimize/desktop/apply')
3054
+ let lastError = null
3055
+ for (let i = 0; i < candidates.length; i += 1) {
3056
+ try {
3057
+ const response = await fetch(candidates[i], {
3058
+ method: 'POST',
3059
+ headers: { 'content-type': 'application/json', 'x-ui-optimize-apply': '1' },
3060
+ credentials: 'same-origin',
3061
+ cache: 'no-store',
3062
+ body: JSON.stringify(body),
3063
+ signal: AbortSignal.timeout(15000),
3064
+ })
3065
+ /* The NAS gateway answers unknown paths with 200 and a plain-text
3066
+ * "invalid token" body, so a 200 alone proves nothing: only a JSON
3067
+ * answer means the host route actually ran. */
3068
+ const text = await response.text()
3069
+ let payload = null
3070
+ try {
3071
+ payload = JSON.parse(text)
3072
+ } catch (err) {
3073
+ payload = null
3074
+ }
3075
+ if (payload === null) {
3076
+ lastError = new Error('HTTP ' + response.status + ' 非 JSON 应答')
3077
+ continue
3078
+ }
3079
+ if (!response.ok || payload.ok !== true) {
3080
+ lastError = new Error('HTTP ' + response.status + ' ' + String(payload.reason || ''))
3081
+ continue
3082
+ }
3083
+ return payload
3084
+ } catch (err) {
3085
+ lastError = err
3086
+ }
3087
+ }
3088
+ throw lastError || new Error('apply endpoint unreachable')
3089
+ }
2912
3090
 
2913
3091
  async function updateAll() {
2914
3092
  if (busy) return
3093
+ const pendingRows = groups.pending.slice()
2915
3094
  const targets = eligible.map(function (row) {
2916
3095
  return { name: row.name, from: row.installed, target: targetOf(row) }
2917
3096
  })
2918
- if (targets.length === 0) return
3097
+ if (targets.length === 0 && pendingRows.length === 0) return
2919
3098
  setBusy(true)
2920
3099
  setMessage('')
2921
3100
  let restarts = 0
@@ -2938,8 +3117,17 @@ button.muik-shelf-row:focus-visible{outline:2px solid var(--dsw-alias-brand-prim
2938
3117
  const needs = !ok ? '' : operation && operation.restartRequired ? 'restart' : 'refresh'
2939
3118
  if (needs === 'restart') restarts += 1
2940
3119
  else if (needs === 'refresh') refreshes += 1
3120
+ /* The host reports code 'UPDATE_REJECTED' for several reasons and
3121
+ * puts the real one in `message` — matching only the code meant
3122
+ * this branch never ran and the doomed row kept coming back. */
3123
+ const failureText = !ok && operation && operation.failure
3124
+ ? String(operation.failure.code || '') + ' ' + String(operation.failure.message || '')
3125
+ : ''
3126
+ const blockedNow = /incompatible/i.test(failureText)
3127
+ if (blockedNow) rememberCompatBlocked(name)
2941
3128
  patch(name, {
2942
3129
  state: ok ? 'succeeded' : 'failed',
3130
+ compat: blockedNow ? { runtime: '', required: '' } : undefined,
2943
3131
  needs: needs,
2944
3132
  percent: 100,
2945
3133
  done: ok
@@ -2951,6 +3139,18 @@ button.muik-shelf-row:focus-visible{outline:2px solid var(--dsw-alias-brand-prim
2951
3139
  ? operation.failure.code + ' — ' + operation.failure.message
2952
3140
  : (operation && operation.state) || 'failed',
2953
3141
  })
3142
+ /* The green confirmation is feedback, not a list entry: clear it
3143
+ * after a few seconds, otherwise it sits under a "0 updatable"
3144
+ * heading until the page is reloaded. */
3145
+ if (ok) {
3146
+ setTimeout(function () {
3147
+ updateRun.set({
3148
+ rows: updateRun.rows.filter(function (item) {
3149
+ return !(item.name === name && item.state === 'succeeded')
3150
+ }),
3151
+ })
3152
+ }, 10000)
3153
+ }
2954
3154
  } catch (err) {
2955
3155
  patch(name, { state: 'failed', percent: 100, detail: err.message })
2956
3156
  }
@@ -2958,19 +3158,45 @@ button.muik-shelf-row:focus-visible{outline:2px solid var(--dsw-alias-brand-prim
2958
3158
  /* The batch may outlive this mount: write the result to the shared
2959
3159
  * run state unconditionally, or a remount would come back with the
2960
3160
  * button stuck on "busy" forever. */
3161
+ let appliedPending = 0
3162
+ let applyFailed = false
3163
+ let applyError = ''
3164
+ if (pendingRows.length > 0) {
3165
+ try {
3166
+ await applyPending(pendingRows)
3167
+ appliedPending = pendingRows.length
3168
+ /* The host answers 202 before pnpm starts, so show the batch as in
3169
+ * flight right away — otherwise the click looks like a no-op until
3170
+ * the page reloads under the new DSH process. */
3171
+ pendingRows.forEach(function (row) {
3172
+ patch(row.name, { state: 'applied', percent: null, detail: translate('updates.pendingStarting') })
3173
+ })
3174
+ } catch (err) {
3175
+ applyFailed = true
3176
+ applyError = err && err.message ? String(err.message) : String(err)
3177
+ }
3178
+ }
2961
3179
  setBusy(false)
2962
3180
  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
- )
3181
+ if (applyFailed) {
3182
+ setMessage(translate('updates.applyFailed') + (applyError ? '(' + applyError + ')' : ''))
3183
+ } else if (appliedPending > 0) {
3184
+ setMessage(translate('updates.applyStarted').replace('{n}', String(appliedPending)))
3185
+ } else {
3186
+ setMessage(
3187
+ restarts > 0
3188
+ ? translate('updates.needRestartHint').replace('{n}', String(restarts))
3189
+ : refreshes > 0
3190
+ ? translate('updates.needRefreshHint')
3191
+ : translate('updates.reloadHint'),
3192
+ )
3193
+ }
2970
3194
  }
2971
3195
  refreshUpdateBadge()
2972
3196
  }
2973
3197
 
3198
+ /* The header is built before the grouping below, so the pending count it
3199
+ * shows has to be computed here with the same rule the section uses. */
2974
3200
  const header = h(
2975
3201
  'div',
2976
3202
  { className: 'dsuik-up-header' },
@@ -2992,9 +3218,13 @@ button.muik-shelf-row:focus-visible{outline:2px solid var(--dsw-alias-brand-prim
2992
3218
  h('button', {
2993
3219
  type: 'button',
2994
3220
  className: 'dsuik-up-btn is-primary',
2995
- disabled: busy || phase !== 'ready' || eligible.length === 0,
3221
+ /* One button covers both batches: what the host can replace now,
3222
+ * plus what it will replace on the next start. */
3223
+ disabled: busy || phase !== 'ready' || eligible.length + pendingCount === 0,
2996
3224
  onClick: updateAll,
2997
- }, busy ? translate('updates.updating') : translate('updates.updateAll') + ' (' + String(eligible.length) + ')'),
3225
+ }, busy
3226
+ ? translate('updates.updating')
3227
+ : translate('updates.updateAll') + ' (' + String(eligible.length + pendingCount) + ')'),
2998
3228
  ),
2999
3229
  )
3000
3230
 
@@ -3086,7 +3316,10 @@ button.muik-shelf-row:focus-visible{outline:2px solid var(--dsw-alias-brand-prim
3086
3316
  /* A running or finished row speaks with its state, not with the plan:
3087
3317
  * the "previous release" tag belongs to a row that has not started yet,
3088
3318
  * otherwise 更新中 never gets a chance to show. */
3089
- const label = idle ? (quiet || usingFallback ? '' : updateLabel(row)) : updateLabel(row)
3319
+ /* A row the host cannot load is not a failed update to retry: it reads
3320
+ * as one fact ("this DSH cannot load it"), with the raw failure code
3321
+ * left in the log rather than on the card. */
3322
+ const label = row.compat ? '' : (idle ? (quiet || usingFallback ? '' : updateLabel(row)) : updateLabel(row))
3090
3323
  /* Nothing to install yet: say how far the nearest candidate is, so a
3091
3324
  * row that is "waiting" does not look like the plugin forgot it.
3092
3325
  * Only idle rows: a finished row must not read "已更新 · 剩余 5.1 小时". */
@@ -3104,7 +3337,7 @@ button.muik-shelf-row:focus-visible{outline:2px solid var(--dsw-alias-brand-prim
3104
3337
  className: 'dsuik-up-row'
3105
3338
  + (row.state === 'running' ? ' is-running' : '')
3106
3339
  + (row.state === 'succeeded' ? ' is-ok' : '')
3107
- + (row.state === 'failed' ? ' is-fail' : '')
3340
+ + (row.state === 'failed' && !row.compat ? ' is-fail' : '')
3108
3341
  + (isOpen ? ' is-open' : ''),
3109
3342
  style: { animationDelay: String(Math.min(index, 12) * 18) + 'ms' },
3110
3343
  },
@@ -3141,11 +3374,13 @@ button.muik-shelf-row:focus-visible{outline:2px solid var(--dsw-alias-brand-prim
3141
3374
  soon ? h('span', { className: 'dsuik-up-soon' }, soon) : null,
3142
3375
  label ? h('span', { className: 'dsuik-up-tag' }, label) : null,
3143
3376
  fallbackShown ? h('span', { className: 'dsuik-up-tag', title: translate('updates.fallbackWhy') }, translate('updates.fallbackTag')) : null,
3144
- row.compat && !row.state
3377
+ row.compat
3145
3378
  ? h('span', { className: 'dsuik-up-tag is-warn', title: translate('updates.section.blockedHint') },
3146
- translate('updates.compatTag').replace('{version}', String(row.compat.required || row.compat.runtime || '?')))
3379
+ row.compat.required || row.compat.runtime
3380
+ ? translate('updates.compatTag').replace('{version}', String(row.compat.required || row.compat.runtime))
3381
+ : translate('updates.compatTagUnknown'))
3147
3382
  : null,
3148
- row.detail ? h('span', { className: 'dsuik-up-detail' }, row.detail) : null,
3383
+ row.detail && !row.compat ? h('span', { className: 'dsuik-up-detail' }, row.detail) : null,
3149
3384
  ),
3150
3385
  h('span', { className: 'dsuik-up-chev', 'aria-hidden': 'true' }, isOpen ? '▾' : '▸'),
3151
3386
  ),
@@ -3161,14 +3396,15 @@ button.muik-shelf-row:focus-visible{outline:2px solid var(--dsw-alias-brand-prim
3161
3396
 
3162
3397
  /* Two areas: everything the 24-hour rule lets us touch on top, the rest
3163
3398
  * below it, so the button above always matches the list above. */
3164
- const groups = { ready: [], blocked: [], waiting: [] }
3399
+ const groups = { ready: [], pending: [], blocked: [], waiting: [] }
3165
3400
  rows.forEach(function (row) {
3166
3401
  /* A row we are actively installing belongs with the rows you can act
3167
3402
  * on, even when its release is still inside the 24-hour window —
3168
3403
  * otherwise a forced update disappears into the "waiting" list while
3169
3404
  * its progress bar is still moving. */
3170
3405
  const ready = row.state === 'succeeded' || row.state === 'running' || targetOf(row) !== null
3171
- if (ready) groups.ready.push(row)
3406
+ if (row.enabled === true && row.state !== 'running' && targetOf(row) !== null) groups.pending.push(row)
3407
+ else if (ready) groups.ready.push(row)
3172
3408
  else if (row.compat && row.state !== 'succeeded') groups.blocked.push(row)
3173
3409
  else groups.waiting.push(row)
3174
3410
  })
@@ -3186,14 +3422,15 @@ button.muik-shelf-row:focus-visible{outline:2px solid var(--dsw-alias-brand-prim
3186
3422
  * "30 checked" next to ten visible rows reads like a failed scan. */
3187
3423
  const upToDate = Math.max(0, checked - rows.length)
3188
3424
 
3189
- function sectionArea(titleKey, items, muted, hintKey, always) {
3425
+ function sectionArea(titleKey, items, muted, hintKey, always, count) {
3190
3426
  if (items.length === 0 && !always) return null
3427
+ const shown = typeof count === 'number' ? count : items.length
3191
3428
  return h(
3192
3429
  'section',
3193
3430
  { className: 'dsuik-up-section' + (muted ? ' is-muted' : '') },
3194
3431
  h('div', { className: 'dsuik-up-section-head' },
3195
3432
  h('p', { className: 'dsuik-up-section-title' },
3196
- translate(titleKey) + ' (' + String(items.length) + ')'),
3433
+ translate(titleKey) + ' (' + String(shown) + ')'),
3197
3434
  hintKey
3198
3435
  ? h('p', { className: 'dsuik-up-section-hint' },
3199
3436
  hintKey.indexOf('updates.') === 0 ? translate(hintKey) : hintKey)
@@ -3230,10 +3467,28 @@ button.muik-shelf-row:focus-visible{outline:2px solid var(--dsw-alias-brand-prim
3230
3467
  : null,
3231
3468
  /* The ready area stays on screen even when it is empty, so the page
3232
3469
  * always answers "is there anything for me?" instead of going blank. */
3233
- phase === 'ready' ? sectionArea('updates.section.ready', groups.ready, false, null, true) : null,
3470
+ phase === 'ready'
3471
+ ? sectionArea(
3472
+ 'updates.section.ready',
3473
+ groups.ready,
3474
+ false,
3475
+ null,
3476
+ true,
3477
+ groups.ready.filter(function (row) { return row.state !== 'succeeded' }).length,
3478
+ )
3479
+ : null,
3234
3480
  /* The closing hint belongs to the batch it talks about: right under the
3235
3481
  * rows you just updated, not after two unrelated sections. */
3236
3482
  phase === 'ready' && message ? h('p', { className: 'dsuik-up-note is-after-ready' }, message) : null,
3483
+ phase === 'ready'
3484
+ ? sectionArea(
3485
+ 'updates.section.pending',
3486
+ groups.pending,
3487
+ true,
3488
+ groups.pending.length > 0 ? 'updates.section.pendingHint' : 'updates.section.pendingEmpty',
3489
+ true,
3490
+ )
3491
+ : null,
3237
3492
  phase === 'ready' ? sectionArea('updates.section.waiting', groups.waiting, true, 'updates.section.waitingHint', false) : null,
3238
3493
  phase === 'ready'
3239
3494
  ? sectionArea(
@@ -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.10",
3
+ "version": "0.12.1",
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",
@@ -50,7 +50,8 @@
50
50
  "platform": "web",
51
51
  "immediately": true,
52
52
  "inject": [
53
- "@deepseek-ai/dsh-api-remotes"
53
+ "@deepseek-ai/dsh-api-remotes",
54
+ "@deepseek-ai/dsh-client-ui-slots"
54
55
  ]
55
56
  }
56
57
  }