dsh-remote 0.8.78 → 0.8.80

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 CHANGED
@@ -51,10 +51,20 @@ window.__ModuleLoader__.load({
51
51
  // useModalLayer — the focus/escape layer on its own, applied to the picker's
52
52
  // custom overlay (which keeps its #52 mask guard).
53
53
  // writeClipboard — replaces the scratch-textarea copy hack.
54
+ // Switch — settings toggles (bundle-verified contract: onChange delivers
55
+ // a bare BOOLEAN, not an event, and unknown props are swallowed, so the
56
+ // stable data-testids ride on a wrapper span, never on the Switch).
57
+ // SegmentedTabs — the dir picker's 本机/远程 switch (items[{value,label}],
58
+ // value, onChange(value)); brings the sliding-indicator tablist.
59
+ // FileTypeIcon — explorer/picker row glyphs ({kind:'folder'} for dirs,
60
+ // {path:name} for files; unknown extensions land on 'other').
54
61
  const Modal = (Primitives && typeof Primitives.Modal === 'function') ? Primitives.Modal : null
55
62
  const HostMenu = (Primitives && typeof Primitives.Menu === 'function') ? Primitives.Menu : null
56
63
  const useModalLayerFn = (Primitives && typeof Primitives.useModalLayer === 'function') ? Primitives.useModalLayer : null
57
64
  const writeClipboardFn = (Primitives && typeof Primitives.writeClipboard === 'function') ? Primitives.writeClipboard : null
65
+ const HostSwitch = (Primitives && typeof Primitives.Switch === 'function') ? Primitives.Switch : null
66
+ const HostSegmentedTabs = (Primitives && typeof Primitives.SegmentedTabs === 'function') ? Primitives.SegmentedTabs : null
67
+ const HostFileTypeIcon = (Primitives && typeof Primitives.FileTypeIcon === 'function') ? Primitives.FileTypeIcon : null
58
68
 
59
69
  // Issue #93: floating layers must PORTAL to document.body, exactly like the
60
70
  // host's own Modal/Menu (and like our context menu already does with an
@@ -1262,6 +1272,19 @@ window.__ModuleLoader__.load({
1262
1272
  React.useEffect(() => {
1263
1273
  api('GET', '/dsh-remote/telemetry').then((r) => setTelemetryOn(!(r && r.enabled === false))).catch(() => {})
1264
1274
  }, [])
1275
+ // One applier per toggle, shared by the native-checkbox fallback (event
1276
+ // semantics) and the host Switch (bare-boolean callback), so both paths
1277
+ // behave identically.
1278
+ const applyExplorerAutoOpen = (on) => {
1279
+ setExplorerAuto(on)
1280
+ try { window.localStorage.setItem(EXPLORER_AUTO_OPEN_KEY, on ? '1' : '0') } catch { /* private mode: choice lasts this session only */ }
1281
+ }
1282
+ const applyTelemetryEnabled = (on) => {
1283
+ setTelemetryOn(on) // optimistic; the host answer re-syncs below
1284
+ api('POST', '/dsh-remote/telemetry', { enabled: on })
1285
+ .then((r) => setTelemetryOn(!(r && r.enabled === false)))
1286
+ .catch(() => setTelemetryOn(null))
1287
+ }
1265
1288
  const checkUpdate = (quiet) => {
1266
1289
  if (updBusy) return
1267
1290
  setUpdBusy(true); setUpdMsg('')
@@ -1976,30 +1999,51 @@ window.__ModuleLoader__.load({
1976
1999
  ),
1977
2000
  ),
1978
2001
  React.createElement('div', { style: { display: 'flex', gap: 8, alignItems: 'center', marginTop: 6, fontSize: 12 } },
1979
- React.createElement('label', { style: { display: 'flex', gap: 6, alignItems: 'center', cursor: 'pointer', opacity: 0.85 } },
1980
- React.createElement('input', {
1981
- type: 'checkbox', checked: explorerAuto, 'data-testid': 'explorer-auto-open',
1982
- onChange: (e) => {
1983
- const on = !!(e && e.target && e.target.checked)
1984
- setExplorerAuto(on)
1985
- try { window.localStorage.setItem(EXPLORER_AUTO_OPEN_KEY, on ? '1' : '0') } catch { /* private mode: choice lasts this session only */ }
1986
- },
1987
- }),
1988
- tr('settings.explorerAutoOpen'),
1989
- ),
1990
- React.createElement('label', { style: { display: 'flex', gap: 6, alignItems: 'center', cursor: telemetryOn === null ? 'default' : 'pointer', opacity: 0.85 }, title: tr('settings.telemetryHint') },
1991
- React.createElement('input', {
1992
- type: 'checkbox', checked: telemetryOn === true, disabled: telemetryOn === null, 'data-testid': 'telemetry-toggle',
1993
- onChange: (e) => {
1994
- const on = !!(e && e.target && e.target.checked)
1995
- setTelemetryOn(on) // optimistic; the host answer re-syncs below
1996
- api('POST', '/dsh-remote/telemetry', { enabled: on })
1997
- .then((r) => setTelemetryOn(!(r && r.enabled === false)))
1998
- .catch(() => setTelemetryOn(null))
1999
- },
2000
- }),
2001
- tr('settings.telemetry'),
2002
- ),
2002
+ // Host Switch when shipped: its onChange hands back a bare boolean
2003
+ // and it does not forward unknown props, so the stable test id lives
2004
+ // on the tight wrapper span. The caption keeps label-like behaviour
2005
+ // (click toggles) so the swap is purely visual. Older hosts keep the
2006
+ // native checkbox — which then OWNS the data-testid: exactly one
2007
+ // element carries each id on either path.
2008
+ HostSwitch
2009
+ ? React.createElement('span', { style: { display: 'inline-flex', gap: 6, alignItems: 'center', opacity: 0.85 } },
2010
+ React.createElement('span', { 'data-testid': 'explorer-auto-open', style: { display: 'inline-flex' } },
2011
+ React.createElement(HostSwitch, {
2012
+ checked: explorerAuto,
2013
+ label: tr('settings.explorerAutoOpen'),
2014
+ onChange: (on) => applyExplorerAutoOpen(on === true),
2015
+ })),
2016
+ React.createElement('span', { style: { cursor: 'pointer' }, onClick: () => applyExplorerAutoOpen(!explorerAuto) }, tr('settings.explorerAutoOpen')),
2017
+ )
2018
+ : React.createElement('label', { style: { display: 'flex', gap: 6, alignItems: 'center', cursor: 'pointer', opacity: 0.85 } },
2019
+ React.createElement('input', {
2020
+ type: 'checkbox', checked: explorerAuto, 'data-testid': 'explorer-auto-open',
2021
+ onChange: (e) => applyExplorerAutoOpen(!!(e && e.target && e.target.checked)),
2022
+ }),
2023
+ tr('settings.explorerAutoOpen'),
2024
+ ),
2025
+ HostSwitch
2026
+ ? React.createElement('span', { style: { display: 'inline-flex', gap: 6, alignItems: 'center', opacity: 0.85 }, title: tr('settings.telemetryHint') },
2027
+ React.createElement('span', { 'data-testid': 'telemetry-toggle', style: { display: 'inline-flex' } },
2028
+ React.createElement(HostSwitch, {
2029
+ checked: telemetryOn === true,
2030
+ disabled: telemetryOn === null,
2031
+ label: tr('settings.telemetry'),
2032
+ title: tr('settings.telemetryHint'),
2033
+ onChange: (on) => { if (telemetryOn !== null) applyTelemetryEnabled(on === true) },
2034
+ })),
2035
+ React.createElement('span', {
2036
+ style: { cursor: telemetryOn === null ? 'default' : 'pointer' },
2037
+ onClick: () => { if (telemetryOn !== null) applyTelemetryEnabled(telemetryOn !== true) },
2038
+ }, tr('settings.telemetry')),
2039
+ )
2040
+ : React.createElement('label', { style: { display: 'flex', gap: 6, alignItems: 'center', cursor: telemetryOn === null ? 'default' : 'pointer', opacity: 0.85 }, title: tr('settings.telemetryHint') },
2041
+ React.createElement('input', {
2042
+ type: 'checkbox', checked: telemetryOn === true, disabled: telemetryOn === null, 'data-testid': 'telemetry-toggle',
2043
+ onChange: (e) => applyTelemetryEnabled(!!(e && e.target && e.target.checked)),
2044
+ }),
2045
+ tr('settings.telemetry'),
2046
+ ),
2003
2047
  ),
2004
2048
  upd && upd.pendingReload
2005
2049
  ? React.createElement('div', { style: { marginTop: 6, fontSize: 12, color: T.warn } },
@@ -2603,7 +2647,9 @@ window.__ModuleLoader__.load({
2603
2647
  className: 'dsh-rw-list-item',
2604
2648
  style: { padding: '7px 12px', cursor: 'pointer', color: T.label, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', display: 'flex', gap: 8, alignItems: 'center', fontSize: 13, borderBottom: '1px solid ' + T.border },
2605
2649
  },
2606
- React.createElement('span', null, '📁'),
2650
+ // Same folder glyph as everywhere else when the host ships
2651
+ // FileTypeIcon; the emoji stays as the no-primitive fallback.
2652
+ React.createElement('span', { style: { display: 'inline-flex', flexShrink: 0 } }, HostFileTypeIcon ? React.createElement(HostFileTypeIcon, { kind: 'folder', size: 14 }) : '📁'),
2607
2653
  React.createElement('span', { style: { overflow: 'hidden', textOverflow: 'ellipsis' } }, it.name),
2608
2654
  )) : React.createElement('div', { style: { opacity: 0.6, padding: 12 } }, tr('picker.noSubdir'))),
2609
2655
  cur.truncated ? React.createElement('div', { style: { opacity: 0.6, padding: '6px 12px', fontSize: 11 } }, tr('picker.truncated')) : null,
@@ -2641,8 +2687,8 @@ window.__ModuleLoader__.load({
2641
2687
  style: { padding: '6px 10px', cursor: it.dir ? 'pointer' : 'default', color: T.label, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', display: 'flex', gap: 8, alignItems: 'center', fontSize: 13, borderBottom: '1px solid ' + T.border },
2642
2688
  },
2643
2689
  React.createElement('span', { style: { flexShrink: 0, display: 'inline-flex', color: T.label, fontSize: 13 } }, it.drive ? '💽' : (it.dir
2644
- ? React.createElement('svg', { width: 14, height: 14, viewBox: '0 0 16 16', fill: 'currentColor' }, React.createElement('path', { d: 'M1.5 3.5A1.5 1.5 0 0 1 3 2h3.2a1.5 1.5 0 0 1 1.06.44L8.5 3.7h4.5A1.5 1.5 0 0 1 14.5 5.2V12A1.5 1.5 0 0 1 13 13.5H3A1.5 1.5 0 0 1 1.5 12V3.5Zm2.5 1a.5.5 0 0 0 0 1h1.2a.5.5 0 0 0 0-1H4Z' }))
2645
- : React.createElement('svg', { width: 14, height: 14, viewBox: '0 0 16 16', fill: 'currentColor', opacity: 0.85 }, React.createElement('path', { d: 'M3.5 1.5a1 1 0 0 0-1 1v11a1 1 0 0 0 1 1h9a1 1 0 0 0 1-1V5.2a1 1 0 0 0-.29-.7L10.5 1.79a1 1 0 0 0-.7-.29H3.5Zm1.5 3h2.25a.75.75 0 0 1 0 1.5H5a.75.75 0 0 1 0-1.5ZM5 9.5h6a.75.75 0 0 1 0 1.5H5a.75.75 0 0 1 0-1.5Zm0 2.25h4a.75.75 0 0 1 0 1.5H5a.75.75 0 0 1 0-1.5Z' })))),
2690
+ ? IconFolder()
2691
+ : IconFile(it.name))),
2646
2692
  React.createElement('span', { style: { overflow: 'hidden', textOverflow: 'ellipsis', flex: 1 } }, it.name),
2647
2693
  React.createElement('span', { style: { fontSize: 11, opacity: 0.55, flexShrink: 0, fontFamily: 'monospace' } }, it.dir ? '' : (humanSize(it.size) + (it.mtime ? ' ' + fmtTime(it.mtime) : ''))),
2648
2694
  )) : React.createElement('div', { style: { opacity: 0.6, padding: 12 } }, tr('picker.emptyDir'))),
@@ -2698,10 +2744,24 @@ window.__ModuleLoader__.load({
2698
2744
  React.createElement('div', { style: { fontSize: 15, fontWeight: 650 } }, tr('picker.title')),
2699
2745
  React.createElement('button', { type: 'button', className: 'dsh-rw-btn', style: { ...buttonS, padding: '2px 8px' }, onClick: () => { if (!busy) onCancel() }, disabled: busy }, tr('picker.close')),
2700
2746
  ),
2701
- React.createElement('div', { className: 'dsh-rw-tabs', style: { marginBottom: 10, alignSelf: 'flex-start' } },
2702
- tabBtn('local', tr('picker.tabLocal')),
2703
- tabBtn('remote', tr('picker.tabRemote')),
2704
- ),
2747
+ // 本机/远程 switch: host SegmentedTabs when the bundle ships one
2748
+ // (sliding-indicator tablist, roving tabindex and arrow-key navigation
2749
+ // baked in); onChange delivers the item value, which is exactly what
2750
+ // switchTab consumes. Older hosts keep the hand-rolled button pair.
2751
+ HostSegmentedTabs
2752
+ ? React.createElement('div', { style: { marginBottom: 10, alignSelf: 'flex-start' } },
2753
+ React.createElement(HostSegmentedTabs, {
2754
+ items: [
2755
+ { value: 'local', label: tr('picker.tabLocal') },
2756
+ { value: 'remote', label: tr('picker.tabRemote') },
2757
+ ],
2758
+ value: tab,
2759
+ onChange: switchTab,
2760
+ label: tr('picker.title'),
2761
+ }))
2762
+ : React.createElement('div', { className: 'dsh-rw-tabs', style: { marginBottom: 10, alignSelf: 'flex-start' } },
2763
+ tabBtn('local', tr('picker.tabLocal')),
2764
+ tabBtn('remote', tr('picker.tabRemote'))),
2705
2765
  tab === 'local'
2706
2766
  ? React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 8 } },
2707
2767
  React.createElement('div', { style: { fontSize: 12, opacity: 0.8, lineHeight: 1.5 } }, tr('picker.localIntro')),
@@ -3059,20 +3119,28 @@ window.__ModuleLoader__.load({
3059
3119
  }
3060
3120
 
3061
3121
  // ── Remote explorer tab ────────────────────────────────────────────────
3062
- // Inline monochrome icons (fill: currentColor → follows the row text color,
3063
- // i.e. black on the sidebar). Folder open/closed + file.
3064
- const IconFolder = (open) => React.createElement('svg', {
3065
- width: 14, height: 14, viewBox: '0 0 16 16', fill: 'currentColor', style: { flexShrink: 0 },
3066
- },
3067
- open
3068
- ? React.createElement('path', { d: 'M1.5 3.5A1.5 1.5 0 0 1 3 2h3.2a1.5 1.5 0 0 1 1.06.44L8.5 3.7h4.5A1.5 1.5 0 0 1 14.5 5.2V12A1.5 1.5 0 0 1 13 13.5H3A1.5 1.5 0 0 1 1.5 12V3.5Zm2.5 1a.5.5 0 0 0 0 1h1.2a.5.5 0 0 0 0-1H4Z' })
3069
- : React.createElement('path', { d: 'M1.5 3.5A1.5 1.5 0 0 1 3 2h3.2a1.5 1.5 0 0 1 1.06.44L8.5 3.7h4.5A1.5 1.5 0 0 1 14.5 5.2V12A1.5 1.5 0 0 1 13 13.5H3A1.5 1.5 0 0 1 1.5 12V3.5Zm2.5 1a.5.5 0 0 0 0 1h1.2a.5.5 0 0 0 0-1H4Z' }),
3070
- )
3071
- const IconFile = () => React.createElement('svg', {
3072
- width: 14, height: 14, viewBox: '0 0 16 16', fill: 'currentColor', style: { flexShrink: 0, opacity: 0.85 },
3073
- },
3074
- React.createElement('path', { d: 'M3.5 1.5a1 1 0 0 0-1 1v11a1 1 0 0 0 1 1h9a1 1 0 0 0 1-1V5.2a1 1 0 0 0-.29-.7L10.5 1.79a1 1 0 0 0-.7-.29H3.5Zm1.5 3h2.25a.75.75 0 0 1 0 1.5H5a.75.75 0 0 1 0-1.5ZM5 9.5h6a.75.75 0 0 1 0 1.5H5a.75.75 0 0 1 0-1.5Zm0 2.25h4a.75.75 0 0 1 0 1.5H5a.75.75 0 0 1 0-1.5Z' }),
3075
- )
3122
+ // Row glyphs: the host FileTypeIcon when the bundle ships one —
3123
+ // directories take its 'folder' kind (the host glyph has no open/closed
3124
+ // variant, matching our old SVG which drew the same path for both states),
3125
+ // files derive the kind from the file name (an unknown extension lands on
3126
+ // the 'other' glyph). Older hosts keep the inline monochrome SVGs
3127
+ // (fill: currentColor → follows the row text color, i.e. black on the
3128
+ // sidebar). The (open)/(name) parameters survive so call sites stay
3129
+ // meaningful on both paths.
3130
+ const IconFolder = (open) => HostFileTypeIcon
3131
+ ? React.createElement(HostFileTypeIcon, { kind: 'folder', size: 14 })
3132
+ : React.createElement('svg', {
3133
+ width: 14, height: 14, viewBox: '0 0 16 16', fill: 'currentColor', style: { flexShrink: 0 },
3134
+ },
3135
+ React.createElement('path', { d: 'M1.5 3.5A1.5 1.5 0 0 1 3 2h3.2a1.5 1.5 0 0 1 1.06.44L8.5 3.7h4.5A1.5 1.5 0 0 1 14.5 5.2V12A1.5 1.5 0 0 1 13 13.5H3A1.5 1.5 0 0 1 1.5 12V3.5Zm2.5 1a.5.5 0 0 0 0 1h1.2a.5.5 0 0 0 0-1H4Z' }),
3136
+ )
3137
+ const IconFile = (name) => HostFileTypeIcon
3138
+ ? React.createElement(HostFileTypeIcon, { path: String(name || ''), size: 14 })
3139
+ : React.createElement('svg', {
3140
+ width: 14, height: 14, viewBox: '0 0 16 16', fill: 'currentColor', style: { flexShrink: 0, opacity: 0.85 },
3141
+ },
3142
+ React.createElement('path', { d: 'M3.5 1.5a1 1 0 0 0-1 1v11a1 1 0 0 0 1 1h9a1 1 0 0 0 1-1V5.2a1 1 0 0 0-.29-.7L10.5 1.79a1 1 0 0 0-.7-.29H3.5Zm1.5 3h2.25a.75.75 0 0 1 0 1.5H5a.75.75 0 0 1 0-1.5ZM5 9.5h6a.75.75 0 0 1 0 1.5H5a.75.75 0 0 1 0-1.5Zm0 2.25h4a.75.75 0 0 1 0 1.5H5a.75.75 0 0 1 0-1.5Z' }),
3143
+ )
3076
3144
 
3077
3145
  // Issue #32: the remote tree's expansion list travels on the TAB (`meta`),
3078
3146
  // never on better-sidebar's session-shared `expanded` array. Best-effort:
@@ -3551,7 +3619,7 @@ window.__ModuleLoader__.load({
3551
3619
  style: base,
3552
3620
  title: entry.path,
3553
3621
  },
3554
- React.createElement('span', { style: { flexShrink: 0, display: 'inline-flex' } }, IconFile()),
3622
+ React.createElement('span', { style: { flexShrink: 0, display: 'inline-flex' } }, IconFile(entry.name)),
3555
3623
  React.createElement('span', { style: { overflow: 'hidden', textOverflow: 'ellipsis', flex: 1 } }, entry.name),
3556
3624
  copiedMark(entry.path),
3557
3625
  (entry.size != null || entry.mtime)
package/lib/index.js CHANGED
@@ -60,6 +60,7 @@ import { createHostApi } from './host-api.js'
60
60
  import { SshPool, ActivePool, createPool } from './pool.js'
61
61
  import { isSystemOpenSshBackend, sshBinaryAvailable, resolveSshBinary } from './openssh.js'
62
62
  import { createFsRoutes } from './routes-fs.js'
63
+ import { createUpdateRoutes } from './routes-update.js'
63
64
  import { listDirStructured, removeRemoteTree } from './remote-fs.js'
64
65
 
65
66
  export const name = 'dsh-remote'
@@ -4695,114 +4696,11 @@ export async function apply(ctx, config) {
4695
4696
  }
4696
4697
  },
4697
4698
  },
4698
- {
4699
- kind: 'exact',
4700
- path: '/dsh-remote/update-check',
4701
- handler: async (req, res) => {
4702
- if (req.method !== 'GET') return sendJson(res, 405, { ok: false, error: 'method not allowed' })
4703
- // `loaded` is the code actually running; `disk` may already be newer.
4704
- // They differ between an applied update and its hot swap (or a boot).
4705
- const loaded = LOADED_VERSION
4706
- const disk = diskVersion()
4707
- // Three-layer precedence: the persisted `update-mode` override (settings
4708
- // UI) beats the profile config, which beats DEFAULT_UPDATE_MODE. The
4709
- // fallback must not hard-code a second default here, or this path would
4710
- // silently disagree with the schema default.
4711
- const rawMode = readUpdateMode() || config.updateMode || DEFAULT_UPDATE_MODE
4712
- const base = {
4713
- current: loaded,
4714
- loaded,
4715
- disk,
4716
- pendingReload: gtVersion(disk, loaded),
4717
- updateMode: ['manual', 'auto', 'off'].includes(rawMode) ? rawMode : DEFAULT_UPDATE_MODE,
4718
- updatedMarker: existsSync(path.join(selfDir(), '.dsh-remote-updated')),
4719
- // Exposed so the settings page can explain why `auto` may not act:
4720
- // a link:/dev install must not be overwritten by an npm publish.
4721
- selfUpdateAllowed: isInstalledCopy(),
4722
- // Outcome of the last hot-swap attempt (null if never tried). Without
4723
- // this the swap could fail forever while the panel kept saying a
4724
- // reload was merely pending — which is exactly what happened.
4725
- lastReload: lastSelfReload(),
4726
- }
4727
- const probe = await fetchLatestVersion()
4728
- // 即使查不到最新版,也把**本地状态**照常返回(ok:true),只把 registry
4729
- // 的失败原因放在 registryError 里。
4730
- //
4731
- // 为什么:原先 registry 失败时整条响应 ok:false,客户端遇到 !ok 就只设错误
4732
- // 文案、不 setUpd,于是面板永远停在「版本信息加载中…」——看起来像卡死,
4733
- // 而实际上本地版本、更新模式、是否允许自更新都是已知的,完全可以展示。
4734
- if (probe.error) {
4735
- return sendJson(res, 200, { ok: true, ...base, latest: null, updateAvailable: false, registryError: probe.error, registryReason: probe.reason })
4736
- }
4737
- return sendJson(res, 200, {
4738
- ok: true,
4739
- ...base,
4740
- latest: probe.version,
4741
- updateAvailable: gtVersion(probe.version, loaded),
4742
- })
4743
- },
4744
- },
4745
- {
4746
- kind: 'exact',
4747
- path: '/dsh-remote/update-apply',
4748
- handler: async (req, res) => {
4749
- if (req.method !== 'POST') return sendJson(res, 405, { ok: false, error: 'method not allowed' })
4750
- try {
4751
- // Capture the outgoing version BEFORE the swap: reading it afterwards
4752
- // reports the version we just installed, not the one we replaced.
4753
- const from = diskVersion()
4754
- const loaded = LOADED_VERSION
4755
- const body = JSON.parse((await readBody(req)) || '{}')
4756
- const target = String(body.version || '')
4757
- if (!target) return sendJson(res, 400, { ok: false, error: 'version is required' })
4758
- const result = await applyUpdate(target)
4759
- const wantReload = body.reload !== false && config.updateAutoReload !== false
4760
- // Answer first, then swap: the swap disposes the fiber serving this
4761
- // very request, so nothing may touch the plugin after it.
4762
- if (wantReload) scheduleSelfReload(ctx.loader, 300)
4763
- return sendJson(res, 200, {
4764
- ok: true,
4765
- from,
4766
- loadedBefore: loaded,
4767
- ...result,
4768
- reloadScheduled: wantReload,
4769
- // what the swap will land on, for a caller that wants to verify
4770
- loadedAfterReload: wantReload ? result.to : loaded,
4771
- })
4772
- } catch (err) {
4773
- return sendJson(res, 500, { ok: false, error: String((err && err.message) || err) })
4774
- }
4775
- },
4776
- },
4777
- {
4778
- kind: 'exact',
4779
- path: '/dsh-remote/update-reload',
4780
- handler: async (req, res) => {
4781
- if (req.method !== 'POST') return sendJson(res, 405, { ok: false, error: 'method not allowed' })
4782
- // Hot-swap the host half to whatever is on disk now. Answers first (with
4783
- // what was loaded and what it is about to become), then swaps.
4784
- const loaded = LOADED_VERSION
4785
- const disk = diskVersion()
4786
- scheduleSelfReload(ctx.loader, 300)
4787
- return sendJson(res, 200, { ok: true, scheduled: true, loaded, disk, willReloadTo: disk })
4788
- },
4789
- },
4790
- {
4791
- kind: 'exact',
4792
- path: '/dsh-remote/update-mode',
4793
- handler: async (req, res) => {
4794
- if (req.method !== 'POST') return sendJson(res, 405, { ok: false, error: 'method not allowed' })
4795
- try {
4796
- const body = JSON.parse((await readBody(req)) || '{}')
4797
- const mode = String(body.mode || '')
4798
- if (!['manual', 'auto', 'off'].includes(mode)) return sendJson(res, 400, { ok: false, error: 'mode must be manual | auto | off' })
4799
- if (!persistUpdateMode(mode)) return sendJson(res, 500, { ok: false, error: 'cannot persist mode' })
4800
- return sendJson(res, 200, { ok: true, mode })
4801
- } catch (err) {
4802
- return sendJson(res, 500, { ok: false, error: String((err && err.message) || err) })
4803
- }
4804
- },
4805
- },
4699
+ // Self-update surface (extracted for issue #82).
4700
+ ...createUpdateRoutes({
4701
+ sendJson, readBody, config, loader: ctx.loader, defaultUpdateMode: DEFAULT_UPDATE_MODE,
4702
+ }),
4703
+
4806
4704
  {
4807
4705
  kind: 'exact',
4808
4706
  path: '/dsh-remote/telemetry',
@@ -0,0 +1,143 @@
1
+ // Self-update routes: /update-check /update-apply /update-reload /update-mode.
2
+ //
3
+ // Extracted from lib/index.js (issue #82: the god-file split). Handler bodies
4
+ // moved VERBATIM; the mechanism lives in ./update.js, this file only adapts the
5
+ // HTTP surface to it. Dependencies that belong to the plugin entry (config,
6
+ // the loader handle, the default-mode constant) arrive as `deps`.
7
+ import { existsSync } from 'node:fs'
8
+ import path from 'node:path'
9
+ import {
10
+ applyUpdate,
11
+ diskVersion,
12
+ fetchLatestVersion,
13
+ gtVersion,
14
+ isInstalledCopy,
15
+ lastSelfReload,
16
+ LOADED_VERSION,
17
+ persistUpdateMode,
18
+ readUpdateMode,
19
+ scheduleSelfReload,
20
+ selfDir,
21
+ } from './update.js'
22
+
23
+ /**
24
+ * @param {object} deps
25
+ * @param {(res: object, status: number, body: object) => void} deps.sendJson
26
+ * @param {(req: object) => Promise<string>} deps.readBody
27
+ * @param {object} deps.config - validated plugin Config.
28
+ * @param {object} deps.loader - `ctx.loader`, for the hot-swap scheduling.
29
+ * @param {string} deps.defaultUpdateMode - DEFAULT_UPDATE_MODE from the entry.
30
+ * @returns {Array<object>} route descriptors for registerHttpTransports.
31
+ */
32
+ export function createUpdateRoutes({ sendJson, readBody, config, loader, defaultUpdateMode }) {
33
+ return [
34
+ {
35
+ kind: 'exact',
36
+ path: '/dsh-remote/update-check',
37
+ handler: async (req, res) => {
38
+ if (req.method !== 'GET') return sendJson(res, 405, { ok: false, error: 'method not allowed' })
39
+ // `loaded` is the code actually running; `disk` may already be newer.
40
+ // They differ between an applied update and its hot swap (or a boot).
41
+ const loaded = LOADED_VERSION
42
+ const disk = diskVersion()
43
+ // Three-layer precedence: the persisted `update-mode` override (settings
44
+ // UI) beats the profile config, which beats DEFAULT_UPDATE_MODE. The
45
+ // fallback must not hard-code a second default here, or this path would
46
+ // silently disagree with the schema default.
47
+ const rawMode = readUpdateMode() || config.updateMode || defaultUpdateMode
48
+ const base = {
49
+ current: loaded,
50
+ loaded,
51
+ disk,
52
+ pendingReload: gtVersion(disk, loaded),
53
+ updateMode: ['manual', 'auto', 'off'].includes(rawMode) ? rawMode : defaultUpdateMode,
54
+ updatedMarker: existsSync(path.join(selfDir(), '.dsh-remote-updated')),
55
+ // Exposed so the settings page can explain why `auto` may not act:
56
+ // a link:/dev install must not be overwritten by an npm publish.
57
+ selfUpdateAllowed: isInstalledCopy(),
58
+ // Outcome of the last hot-swap attempt (null if never tried). Without
59
+ // this the swap could fail forever while the panel kept saying a
60
+ // reload was merely pending — which is exactly what happened.
61
+ lastReload: lastSelfReload(),
62
+ }
63
+ const probe = await fetchLatestVersion()
64
+ // 即使查不到最新版,也把**本地状态**照常返回(ok:true),只把 registry
65
+ // 的失败原因放在 registryError 里。
66
+ //
67
+ // 为什么:原先 registry 失败时整条响应 ok:false,客户端遇到 !ok 就只设错误
68
+ // 文案、不 setUpd,于是面板永远停在「版本信息加载中…」——看起来像卡死,
69
+ // 而实际上本地版本、更新模式、是否允许自更新都是已知的,完全可以展示。
70
+ if (probe.error) {
71
+ return sendJson(res, 200, { ok: true, ...base, latest: null, updateAvailable: false, registryError: probe.error, registryReason: probe.reason })
72
+ }
73
+ return sendJson(res, 200, {
74
+ ok: true,
75
+ ...base,
76
+ latest: probe.version,
77
+ updateAvailable: gtVersion(probe.version, loaded),
78
+ })
79
+ },
80
+ },
81
+ {
82
+ kind: 'exact',
83
+ path: '/dsh-remote/update-apply',
84
+ handler: async (req, res) => {
85
+ if (req.method !== 'POST') return sendJson(res, 405, { ok: false, error: 'method not allowed' })
86
+ try {
87
+ // Capture the outgoing version BEFORE the swap: reading it afterwards
88
+ // reports the version we just installed, not the one we replaced.
89
+ const from = diskVersion()
90
+ const loaded = LOADED_VERSION
91
+ const body = JSON.parse((await readBody(req)) || '{}')
92
+ const target = String(body.version || '')
93
+ if (!target) return sendJson(res, 400, { ok: false, error: 'version is required' })
94
+ const result = await applyUpdate(target)
95
+ const wantReload = body.reload !== false && config.updateAutoReload !== false
96
+ // Answer first, then swap: the swap disposes the fiber serving this
97
+ // very request, so nothing may touch the plugin after it.
98
+ if (wantReload) scheduleSelfReload(loader, 300)
99
+ return sendJson(res, 200, {
100
+ ok: true,
101
+ from,
102
+ loadedBefore: loaded,
103
+ ...result,
104
+ reloadScheduled: wantReload,
105
+ // what the swap will land on, for a caller that wants to verify
106
+ loadedAfterReload: wantReload ? result.to : loaded,
107
+ })
108
+ } catch (err) {
109
+ return sendJson(res, 500, { ok: false, error: String((err && err.message) || err) })
110
+ }
111
+ },
112
+ },
113
+ {
114
+ kind: 'exact',
115
+ path: '/dsh-remote/update-reload',
116
+ handler: async (req, res) => {
117
+ if (req.method !== 'POST') return sendJson(res, 405, { ok: false, error: 'method not allowed' })
118
+ // Hot-swap the host half to whatever is on disk now. Answers first (with
119
+ // what was loaded and what it is about to become), then swaps.
120
+ const loaded = LOADED_VERSION
121
+ const disk = diskVersion()
122
+ scheduleSelfReload(loader, 300)
123
+ return sendJson(res, 200, { ok: true, scheduled: true, loaded, disk, willReloadTo: disk })
124
+ },
125
+ },
126
+ {
127
+ kind: 'exact',
128
+ path: '/dsh-remote/update-mode',
129
+ handler: async (req, res) => {
130
+ if (req.method !== 'POST') return sendJson(res, 405, { ok: false, error: 'method not allowed' })
131
+ try {
132
+ const body = JSON.parse((await readBody(req)) || '{}')
133
+ const mode = String(body.mode || '')
134
+ if (!['manual', 'auto', 'off'].includes(mode)) return sendJson(res, 400, { ok: false, error: 'mode must be manual | auto | off' })
135
+ if (!persistUpdateMode(mode)) return sendJson(res, 500, { ok: false, error: 'cannot persist mode' })
136
+ return sendJson(res, 200, { ok: true, mode })
137
+ } catch (err) {
138
+ return sendJson(res, 500, { ok: false, error: String((err && err.message) || err) })
139
+ }
140
+ },
141
+ },
142
+ ]
143
+ }
package/lib/tui/format.js CHANGED
@@ -330,3 +330,51 @@ export function formatBytes(value) {
330
330
  }
331
331
  return `${size >= 10 ? size.toFixed(0) : size.toFixed(1)} ${units[index]}`
332
332
  }
333
+
334
+ /** 东亚宽字符 / emoji 占两个终端单元格,其余一个(粗略但够用的 wcwidth 子集)。 */
335
+ function charCells(codePoint) {
336
+ if (codePoint === 0) return 0
337
+ if (
338
+ (codePoint >= 0x1100 && codePoint <= 0x115f)
339
+ || codePoint === 0x2329 || codePoint === 0x232a
340
+ || (codePoint >= 0x2e80 && codePoint <= 0xa4cf && codePoint !== 0x303f)
341
+ || (codePoint >= 0xac00 && codePoint <= 0xd7a3)
342
+ || (codePoint >= 0xf900 && codePoint <= 0xfaff)
343
+ || (codePoint >= 0xfe10 && codePoint <= 0xfe19)
344
+ || (codePoint >= 0xfe30 && codePoint <= 0xfe6f)
345
+ || (codePoint >= 0xff00 && codePoint <= 0xff60)
346
+ || (codePoint >= 0xffe0 && codePoint <= 0xffe6)
347
+ || (codePoint >= 0x231a && codePoint <= 0x231b)
348
+ || (codePoint >= 0x23e9 && codePoint <= 0x23f3)
349
+ || (codePoint >= 0x25fd && codePoint <= 0x25fe)
350
+ || (codePoint >= 0x2600 && codePoint <= 0x27bf)
351
+ || (codePoint >= 0x2b00 && codePoint <= 0x2bff)
352
+ || (codePoint >= 0x1f000 && codePoint <= 0x1f2ff)
353
+ || (codePoint >= 0x1f300 && codePoint <= 0x1faff)
354
+ || (codePoint >= 0x20000 && codePoint <= 0x3fffd)
355
+ ) return 2
356
+ return 1
357
+ }
358
+
359
+ /** 字符串在终端里占用的单元格数(CJK / emoji 记 2)。 */
360
+ export function displayWidth(text) {
361
+ let cells = 0
362
+ for (const char of String(text == null ? '' : text)) cells += charCells(char.codePointAt(0))
363
+ return cells
364
+ }
365
+
366
+ /** 按终端单元格截断,超宽时以 `…` 结尾(不再额外超宽)。 */
367
+ export function clipCells(text, maxCells) {
368
+ const value = String(text == null ? '' : text)
369
+ const limit = Math.max(1, Math.floor(Number(maxCells) || 0))
370
+ if (displayWidth(value) <= limit) return value
371
+ let out = ''
372
+ let used = 0
373
+ for (const char of value) {
374
+ const cells = charCells(char.codePointAt(0))
375
+ if (used + cells > limit - 1) break
376
+ out += char
377
+ used += cells
378
+ }
379
+ return `${out}…`
380
+ }
package/lib/tui/i18n.js CHANGED
@@ -18,6 +18,9 @@ const DICT = {
18
18
  'status.none': '未连接远程机',
19
19
  'status.connected': '已连接 {target}',
20
20
  'status.disconnected': '未连接 · {target}',
21
+ 'status.detailMachine': '远程机 {name}',
22
+ 'status.detailTarget': '{user}@{host}:{port}',
23
+ 'status.detailRemote': '远端 {path}',
21
24
 
22
25
  // ── 机器列表 ──────────────────────────────────────────────────────────
23
26
  'list.hints': '↑↓ 选择 · →/Enter 动作菜单 · a 新增 · c 连接 · t 探测 · b 浏览 · e 编辑 · d 删除 · ←/Esc 关闭',
@@ -168,6 +171,9 @@ const DICT = {
168
171
  'status.none': 'no remote machine',
169
172
  'status.connected': 'connected · {target}',
170
173
  'status.disconnected': 'disconnected · {target}',
174
+ 'status.detailMachine': 'machine {name}',
175
+ 'status.detailTarget': '{user}@{host}:{port}',
176
+ 'status.detailRemote': 'remote {path}',
171
177
 
172
178
  'list.hints': '↑↓ select · →/Enter actions · a add · c connect · t probe · b browse · e edit · d delete · ←/Esc close',
173
179
  'list.empty': 'no saved machines yet — press a to add one',
package/lib/tui/index.js CHANGED
@@ -9,8 +9,12 @@
9
9
  // · `installTui` 同步返回、不 await、绝不抛错:内部 try/catch + logger.warn。
10
10
  // · 每个注册返回的 disposer 都用 `ctx.effect(() => () => dispose())` 绑定生命周期。
11
11
 
12
+ import os from 'node:os'
13
+ import path from 'node:path'
14
+ import { resolveMirror } from '../binding.js'
12
15
  import { createI18n } from './i18n.js'
13
- import { createWorkspaceProvider } from './provider.js'
16
+ import { clipCells } from './format.js'
17
+ import { createWorkspaceProvider, matchMachineForMirror } from './provider.js'
14
18
  import { createSceneComponent } from './scene.js'
15
19
  import { runDialogFlow } from './flow.js'
16
20
 
@@ -139,9 +143,27 @@ export function installTui(ctx, api, config) {
139
143
  let statusService = null
140
144
  let statusFieldDispose = null
141
145
  let statusRefreshToken = 0
146
+ /** 最近进入 store 的会话 / 最近收到用户输入的会话(见 activeSessionCwd)。 */
147
+ let activeSessionId = null
148
+ let lastUserSessionId = null
149
+ /** 宿主每次会话切换都会用新 cwd 调 provider.describe():那是“当前会话”的
150
+ * 可靠提示(sessions 事件覆盖不到 live 会话切换)。见 noteHostSessionCwd。 */
151
+ let hostSessionCwd = ''
152
+ /** 插件卸载后,仍在 await 的刷新不得再写底栏。 */
153
+ let disposed = false
154
+ /** 上一次写入的 text/detail:相同值不重复 setField(宿主会无条件 emit 并记账)。 */
155
+ let lastStatusWrite = null
156
+ bindEffect(ctx, () => { disposed = true })
142
157
 
143
158
  const ensureProvider = () => {
144
- if (!provider) provider = createWorkspaceProvider({ api, config: config || {}, logger: getService(ctx, 'logger') })
159
+ if (!provider) {
160
+ provider = createWorkspaceProvider({
161
+ api,
162
+ config: config || {},
163
+ logger: getService(ctx, 'logger'),
164
+ onDescribe: noteHostSessionCwd,
165
+ })
166
+ }
145
167
  return provider
146
168
  }
147
169
 
@@ -195,12 +217,27 @@ export function installTui(ctx, api, config) {
195
217
  if (commandsSeen) registerCommand(commandsSeen)
196
218
  }
197
219
 
198
- /** 状态行字段:只在服务形状符合契约时写入,否则整段跳过(不猜 API)。 */
199
- const applyStatusField = (text) => {
220
+ /** 状态行字段:只在服务形状符合契约时写入,否则整段跳过(不猜 API)。
221
+ * `detail` 是鼠标悬停时补在空闲提示行上的说明(宿主按 `inactiveShimmer`
222
+ * 渲染,单行、上限 160 cells,与其它底栏字段的 hover 效果一致)。
223
+ * 宿主对 detail 只按 160 cells 截断、不做“适配当前宽度”的 truncate,超宽会
224
+ * wrap 进看不见的第二行;所以按终端宽度自己裁:状态行内宽是 columns-2
225
+ * (宿主 paddingX=1),再给右侧 MiniWake/activity 预留 16 格,下限 8。 */
226
+ const applyStatusField = (text, detail) => {
227
+ if (disposed) return
200
228
  if (!statusService || typeof statusService.setField !== 'function') return
201
229
  try {
230
+ const columns = Number(process.stdout && process.stdout.columns) || 80
231
+ const clipped = detail ? clipCells(detail, Math.max(8, columns - 18)) : ''
232
+ // 相同值不重复写:宿主 store 会对同 text 的 setField 也 emit,并往
233
+ // append-only 的 effect-ledger 记一笔。从未写过时也不要发“空清除”。
234
+ const previous = lastStatusWrite
235
+ if (previous && previous.text === text && previous.detail === clipped) return
236
+ if (!previous && text === undefined && !clipped) return
237
+ lastStatusWrite = { text, detail: clipped }
238
+ const options = clipped ? { ...STATUS_OPTIONS, detail: clipped } : STATUS_OPTIONS
202
239
  // 第 4 个参数是插件自己的 ctx(只用于 effect ledger 归属,可省略)。
203
- const next = statusService.setField(STATUS_KEY, text, STATUS_OPTIONS, ctx)
240
+ const next = statusService.setField(STATUS_KEY, text, options, ctx)
204
241
  if (statusFieldDispose) {
205
242
  const previous = statusFieldDispose
206
243
  statusFieldDispose = null
@@ -212,7 +249,108 @@ export function installTui(ctx, api, config) {
212
249
  }
213
250
  }
214
251
 
215
- /** 读当前机器名并写状态行;旧结果(token 过期)直接丢弃。 */
252
+ /** 子代理会话也会进 store、也会发 `user/message`,但它不是用户在看的会话。 */
253
+ const isSubagentSession = (session) => {
254
+ const origin = session && session.header && session.header.origin
255
+ return origin === 'subagent'
256
+ }
257
+
258
+ /** 本进程的 live 会话(不含子代理)。`null` = 宿主没有 sessions 服务(旧组合),
259
+ * `[]` = 服务在但读不到/读抛错 → 调用方按“没有远程会话”处理。 */
260
+ const liveSessions = () => {
261
+ const sessions = getService(ctx, 'sessions')
262
+ if (!sessions || typeof sessions.list !== 'function') return null
263
+ try {
264
+ const list = sessions.list()
265
+ if (!Array.isArray(list)) return []
266
+ return list.filter((one) => one && one.header && one.header.cwd && !isSubagentSession(one))
267
+ } catch (error) {
268
+ warn(ctx, '会话列表读取失败', error)
269
+ return []
270
+ }
271
+ }
272
+
273
+ /** 当前 TUI 会话的 cwd。
274
+ *
275
+ * TUI 进程里可以同时有多个 live session(挂载中的会话 + parked 后台会话),
276
+ * 而“切到已挂载会话”不会发 session/* 事件。插件拿不到宿主 channel,按可靠性
277
+ * 依次采信:① 宿主切换会话时传入 provider.describe() 的 cwd(只在这种情况下
278
+ * 才算数,并交叉校验它确实属于某个 live 会话);② 最近进入/用户说过话的
279
+ * 会话;③ store 里最后进入的会话。 */
280
+ const activeSessionCwd = () => {
281
+ const list = liveSessions()
282
+ if (list === null) return { supported: false, cwd: '' }
283
+ const cwds = new Set(list.map((one) => String(one.header.cwd)))
284
+ if (hostSessionCwd && cwds.has(hostSessionCwd)) return { supported: true, cwd: hostSessionCwd }
285
+ const cwdOf = (id) => {
286
+ if (!id) return ''
287
+ const one = list.find((candidate) => String(candidate.id) === String(id))
288
+ return one ? String(one.header.cwd) : ''
289
+ }
290
+ let cwd = cwdOf(activeSessionId) || cwdOf(lastUserSessionId)
291
+ if (!cwd && list.length > 0) cwd = String(list[list.length - 1].header.cwd)
292
+ return { supported: true, cwd }
293
+ }
294
+
295
+ /** 宿主在会话切换/工作区描述时把当前 cwd 交给 provider.describe();记下来,
296
+ * 由 activeSessionCwd 交叉校验后使用。 */
297
+ const noteHostSessionCwd = (cwd) => {
298
+ const value = String(cwd || '')
299
+ if (!value || value === hostSessionCwd) return
300
+ hostSessionCwd = value
301
+ void refreshStatusField()
302
+ }
303
+
304
+ /** `$DSH_HOME`:宿主的 `dshHomePath` 服务是**函数**(`(...segments) => path`),
305
+ * 老版本/测试里也可能是字符串或 `{path}`;都没有时退回环境变量/`~/.dsh`。 */
306
+ const dshHomePath = () => {
307
+ const service = getService(ctx, 'dshHomePath')
308
+ if (typeof service === 'function') {
309
+ try {
310
+ const home = service()
311
+ if (typeof home === 'string' && home) return home
312
+ } catch { /* fall through to the string forms */ }
313
+ }
314
+ if (typeof service === 'string' && service) return service
315
+ if (service && typeof service.path === 'string' && service.path) return service.path
316
+ return process.env.DSH_HOME || path.join(os.homedir(), '.dsh')
317
+ }
318
+
319
+ /** 会话在远程镜像里 → `{label, detail}`;本地会话 / 无会话 → ''。
320
+ * `detail` 供底栏 hover 使用:完整机器名 + `user@host:port` + 远端路径。
321
+ * `null` 表示宿主没有 sessions 服务(旧组合),调用方退回旧行为。 */
322
+ const remoteSessionLabel = (machines) => {
323
+ const { supported, cwd } = activeSessionCwd()
324
+ if (!supported) return null
325
+ if (!cwd) return ''
326
+ let resolved
327
+ try {
328
+ resolved = resolveMirror(cwd, path.join(dshHomePath(), 'remote-workspaces'))
329
+ } catch {
330
+ return ''
331
+ }
332
+ const machine = resolved && resolved.machine
333
+ if (!machine || !resolved.remotePath) return ''
334
+ // 与 provider 的机器匹配共用一套规则:ssh-config 别名机按 alias 命中,
335
+ // 字面机按 host/port/username 命中。
336
+ const match = matchMachineForMirror(machines, machine)
337
+ const label = String(((match && (match.name || match.host)) || machine.alias || machine.host || '')).trim()
338
+ const parts = []
339
+ if (label) parts.push(i18n.t('status.detailMachine', { name: label }))
340
+ parts.push(i18n.t('status.detailTarget', {
341
+ user: machine.username || '',
342
+ host: machine.host || '',
343
+ port: Number(machine.port) || 22,
344
+ }))
345
+ parts.push(i18n.t('status.detailRemote', { path: resolved.remotePath }))
346
+ return { label, detail: parts.filter(Boolean).join(' · ') }
347
+ }
348
+
349
+ /** 读当前机器名并写状态行;旧结果(token 过期)直接丢弃。
350
+ *
351
+ * 只在**当前会话的 cwd 落在远程镜像里**时显示(用户报告的“本地目录也显示
352
+ * 服务器名”就是待机机器被无条件写进底栏)。没有 sessions 服务的旧组合
353
+ * 退回旧行为,不猜。 */
216
354
  const refreshStatusField = async () => {
217
355
  if (!statusService || typeof statusService.setField !== 'function') return
218
356
  if (typeof api.listMachines !== 'function') return
@@ -225,12 +363,30 @@ export function installTui(ctx, api, config) {
225
363
  currentId = result && result.currentId !== undefined ? result.currentId : null
226
364
  } catch (error) {
227
365
  warn(ctx, '状态行读取机器列表失败', error)
366
+ // 读不到机器列表时不要留下旧机器名(那正是“待机机器占底栏”的观感来源)。
367
+ applyStatusField(undefined)
228
368
  return
229
369
  }
230
- if (token !== statusRefreshToken) return
370
+ if (token !== statusRefreshToken || disposed) return
231
371
  const current = machines.find((machine) => machine && machine.id === currentId)
232
- const label = current ? String(current.name || current.host || '').trim() : ''
233
- applyStatusField(label || undefined)
372
+ const remote = remoteSessionLabel(machines)
373
+ const label = remote === null
374
+ ? (current ? String(current.name || current.host || '').trim() : '')
375
+ : remote.label
376
+ applyStatusField(label || undefined, remote && remote.detail)
377
+ }
378
+
379
+ /** 会话事件合并刷新:会话进入/结束、用户在哪说话都会改变“当前会话”。
380
+ * 500ms 合并避免连续事件重复跑 listMachines。 */
381
+ const SESSION_REFRESH_MS = 500
382
+ let sessionRefreshTimer = null
383
+ const scheduleStatusRefresh = () => {
384
+ if (sessionRefreshTimer) return
385
+ sessionRefreshTimer = setTimeout(() => {
386
+ sessionRefreshTimer = null
387
+ void refreshStatusField()
388
+ }, SESSION_REFRESH_MS)
389
+ if (typeof sessionRefreshTimer.unref === 'function') sessionRefreshTimer.unref()
234
390
  }
235
391
 
236
392
  /** 任意 TUI 接缝出现后:订阅宿主变更(刷新 provider 缓存 + 状态行)。 */
@@ -251,6 +407,59 @@ export function installTui(ctx, api, config) {
251
407
  }
252
408
  bindEffect(ctx, dispose)
253
409
  }
410
+ // 会话进入/结束、用户发消息都会改变“当前会话”,据此刷新底栏字段。
411
+ if (typeof ctx.on === 'function') {
412
+ const disposers = []
413
+ const subscribe = (event, listener) => {
414
+ try {
415
+ const dispose = ctx.on(event, listener)
416
+ if (typeof dispose === 'function') disposers.push(dispose)
417
+ } catch (error) {
418
+ warn(ctx, `会话事件订阅失败(${event})`, error)
419
+ }
420
+ }
421
+ subscribe('session/created', (session) => {
422
+ if (!session || session.id == null || isSubagentSession(session)) return
423
+ activeSessionId = String(session.id)
424
+ scheduleStatusRefresh()
425
+ })
426
+ subscribe('session/disposed', (session) => {
427
+ if (!session || session.id == null || isSubagentSession(session)) return
428
+ const id = String(session.id)
429
+ if (id === activeSessionId) {
430
+ activeSessionId = lastUserSessionId && lastUserSessionId !== id ? lastUserSessionId : null
431
+ }
432
+ if (id === lastUserSessionId) lastUserSessionId = null
433
+ if (hostSessionCwd && !activeSessionId) hostSessionCwd = ''
434
+ scheduleStatusRefresh()
435
+ })
436
+ subscribe('session/event', (session, event) => {
437
+ if (!event || event.type !== 'user/message' || isSubagentSession(session)) return
438
+ if (!session || session.id == null) return
439
+ lastUserSessionId = String(session.id)
440
+ activeSessionId = String(session.id)
441
+ scheduleStatusRefresh()
442
+ })
443
+ bindEffect(ctx, () => {
444
+ if (sessionRefreshTimer) {
445
+ clearTimeout(sessionRefreshTimer)
446
+ sessionRefreshTimer = null
447
+ }
448
+ for (const dispose of disposers) {
449
+ try { dispose() } catch { /* teardown is best-effort */ }
450
+ }
451
+ })
452
+ }
453
+ // 终端变窄/变宽后详情要重新裁:否则旧字符串会 wrap 进看不见的第二行。
454
+ if (process.stdout && typeof process.stdout.on === 'function') {
455
+ const onResize = () => scheduleStatusRefresh()
456
+ try {
457
+ process.stdout.on('resize', onResize)
458
+ bindEffect(ctx, () => process.stdout.removeListener('resize', onResize))
459
+ } catch (error) {
460
+ warn(ctx, '终端 resize 订阅失败', error)
461
+ }
462
+ }
254
463
  void refreshStatusField()
255
464
  }
256
465
 
@@ -53,9 +53,39 @@ function rootFromCwd(cwd) {
53
53
  * @param {object} [deps.config] - 行 config(tuiProviderListRecent / tuiProviderRecentLimit)。
54
54
  * @param {object} [deps.logger] - cordis logger(只用于 warn,失败一律降级)。
55
55
  * @param {string} [deps.root] - 镜像 registry 根;省略时从 listRemoteProjects 结果推导。
56
+ * @param {(cwd: string) => void} [deps.onDescribe] - 宿主每次用会话 cwd 调
57
+ * `describe()` 时的只读提示(installTui 用它跟踪“当前会话”,见 lib/tui/index.js)。
56
58
  * @returns {object} TuiWorkspaceProvider(附加 `refresh()`,供 installTui 预热/订阅刷新)。
57
59
  */
58
- export function createWorkspaceProvider({ api, config, logger, root } = {}) {
60
+ /**
61
+ * 把镜像 meta 里的 `{host, port, username, alias}` 对到保存的机器记录:
62
+ * ssh-config 别名机按 alias 命中(meta 记的是解析后地址 + alias),字面机按
63
+ * host/port/username 命中。installTui 的底栏与 provider 共用这一套规则。
64
+ *
65
+ * @param {Array<object>} machines - `api.listMachines()` 的 MachineView 列表。
66
+ * @param {{host: string, port: number, username: string, alias?: string}} mirrorMachine
67
+ * @returns {object|undefined} 命中的机器记录。
68
+ */
69
+ export function matchMachineForMirror(machines, mirrorMachine) {
70
+ const list = Array.isArray(machines) ? machines : []
71
+ if (!mirrorMachine) return undefined
72
+ const alias = String(mirrorMachine.alias || '')
73
+ if (alias) {
74
+ const byAlias = list.find((m) => m && m.useSshConfig && String(m.host || '') === alias)
75
+ if (byAlias) return byAlias
76
+ }
77
+ const host = String(mirrorMachine.host || '')
78
+ const port = Number(mirrorMachine.port) || 22
79
+ const user = String(mirrorMachine.username || '')
80
+ return list.find((m) => {
81
+ if (!m || m.useSshConfig) return false
82
+ if (String(m.host || '') !== host) return false
83
+ if ((Number(m.port) || 22) !== port) return false
84
+ return !user || String(m.username || '') === user
85
+ })
86
+ }
87
+
88
+ export function createWorkspaceProvider({ api, config, logger, root, onDescribe } = {}) {
59
89
  const state = {
60
90
  targets: [],
61
91
  machines: [],
@@ -123,23 +153,7 @@ export function createWorkspaceProvider({ api, config, logger, root } = {}) {
123
153
  }
124
154
 
125
155
  /** resolveMirror 的 machine 段(meta)→ 保存的机器。 */
126
- const machineForMirror = (mirrorMachine) => {
127
- if (!mirrorMachine) return undefined
128
- const alias = String(mirrorMachine.alias || '')
129
- if (alias) {
130
- const byAlias = state.machines.find((m) => m.useSshConfig && String(m.host || '') === alias)
131
- if (byAlias) return byAlias
132
- }
133
- const host = String(mirrorMachine.host || '')
134
- const port = Number(mirrorMachine.port) || 22
135
- const user = String(mirrorMachine.username || '')
136
- return state.machines.find((m) => {
137
- if (m.useSshConfig) return false
138
- if (String(m.host || '') !== host) return false
139
- if ((Number(m.port) || 22) !== port) return false
140
- return !user || String(m.username || '') === user
141
- })
142
- }
156
+ const machineForMirror = (mirrorMachine) => matchMachineForMirror(state.machines, mirrorMachine)
143
157
 
144
158
  /** 把一个 target 放进缓存(uri 去重,先到先得)。 */
145
159
  const remember = (map, target) => {
@@ -270,8 +284,11 @@ export function createWorkspaceProvider({ api, config, logger, root } = {}) {
270
284
  return target
271
285
  }
272
286
 
273
- /** 只读同步的镜像解析:cwd 属于某个镜像 → target;否则 undefined。 */
287
+ /** 只读同步的镜像解析:cwd 属于某个镜像 → target;否则 undefined。
288
+ * 宿主在每次会话切换后都会带着新 cwd 调这里(见 dsh-tui live adoption),
289
+ * 所以顺手把 cwd 作为“当前会话”提示交给 installTui。 */
274
290
  const describe = (cwd) => {
291
+ try { if (typeof onDescribe === 'function') onDescribe(cwd) } catch { /* hint is best-effort */ }
275
292
  if (!cwd) return undefined
276
293
  const root = mirrorRoot(String(cwd))
277
294
  if (!root) return undefined
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-remote",
3
- "version": "0.8.78",
3
+ "version": "0.8.80",
4
4
  "description": "Remote-work assistant for DeepSeek Harness: connect SSH (password/key/agent/keyboard-interactive, multi-hop ProxyJump), list hosts from ~/.ssh/config, pick a remote workspace, operate on it with 21 rw_* tools, conflict-aware mirror sync, an embedded PTY terminal, remote DSH web UI attach, port forwarding, host grouping, remote sandbox fencing, audit log, keychain passwords.",
5
5
  "license": "MIT",
6
6
  "author": "flymysql <flyphp@outlook.com>",