dsh-remote 0.8.79 → 0.8.81

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/README.en.md CHANGED
@@ -333,7 +333,7 @@ Deploying to a product profile is a separate, explicit action (`./sync.sh`) for
333
333
  | `webAttachDshHome` | string | `''` | `DSH_HOME` exported on the remote when attaching; empty reuses the remote user's own harness home |
334
334
  | `webAttachWaitSeconds` | int | `45` | how long to wait for a freshly started remote `dsh web` to print its launch token |
335
335
  | `localTools` | string | `bootstrap` | which `rw_*` tools a LOCAL session (cwd outside every remote mirror) sees (issue #63): `bootstrap` keeps only the configuration loop `rw_machines`/`rw_connect`/`rw_pick_workspace` (the other 19 refuse a local session with "this session is LOCAL", so exposing them just wastes schema budget); `none` hides all `rw_*` (remote setup happens via the settings page only); `all` restores the legacy full surface. REMOTE sessions (cwd inside a mirror) always see everything; an invalid value degrades to `bootstrap` |
336
- | `telemetry` | bool | `true` | anonymous install heartbeat (daily-active statistics, at most once a day; the payload is a plugin-specific HMAC pseudonym + version, no machine info). `false` disables it; users also get a settings-page checkbox (persisted in `$DSH_HOME`, winning over this config) |
336
+ | `telemetry` | bool | `true` | anonymous install heartbeat (daily-active statistics, at most once a day; the payload is a plugin-specific HMAC pseudonym + version, no machine info). `false` disables it (the admin path); the 0.8.78 settings checkbox was removed in 0.8.81 — a previously persisted user opt-out is still honored |
337
337
  | `remoteTerminalDefault` | bool | `true` | make the shell menu's "remote ssh" launcher the terminal's DEFAULT shell when neither the host (`config.shell`) nor the user (a remembered menu choice) has picked one: a session rooted in a remote mirror opens a terminal already sshed into the remote workspace, any other session transparently falls back to a local shell (issue #55); `false` keeps it menu-only |
338
338
  | `tui` | bool | `true` | master switch for the TUI (dsh-tui) layer; `false` registers no `/dsh-remote` page, workspace provider or status field |
339
339
  | `tuiProviderListRecent` | bool | `true` | list each machine's recent remote projects in the TUI workspace picker |
package/README.md CHANGED
@@ -308,7 +308,7 @@ scripts/dev-run.sh --status # 是否在运行
308
308
  | `webAttachDshHome` | string | `''` | 远端启动时导出的 `DSH_HOME`;留空则复用远端用户自己的 harness home |
309
309
  | `webAttachWaitSeconds` | int | `45` | 等待远端 `dsh web` 打印启动令牌的秒数 |
310
310
  | `localTools` | string | `bootstrap` | 本地 session(cwd 不在远程镜像里)暴露哪些 `rw_*` 工具(issue #63):`bootstrap`=只暴露配置闭环 `rw_machines`/`rw_connect`/`rw_pick_workspace`(其余 19 个在本地 session 必然报 "this session is LOCAL",暴露只是白占 schema);`none`=完全不暴露 `rw_*`(远程配置只能走设置页);`all`=旧的 full 暴露。远程 session(cwd 在镜像里)不受影响,始终全量;非法值按 `bootstrap` 处理 |
311
- | `telemetry` | bool | `true` | 匿名安装心跳(日活统计,每天至多一次;内容为插件专属 HMAC 伪名+版本号,不含机器信息)。`false` 关闭;用户也可在设置页用复选框关闭(持久化在 `$DSH_HOME`,优先于此配置) |
311
+ | `telemetry` | bool | `true` | 匿名安装心跳(日活统计,每天至多一次;内容为插件专属 HMAC 伪名+版本号,不含机器信息)。`false` 关闭(管理员路径);0.8.78 曾有的设置页复选框已于 0.8.81 移除——已存在的用户关闭选择仍被尊重 |
312
312
  | `remoteTerminalDefault` | bool | `true` | 让 shell 菜单里的「remote ssh」启动器成为终端**默认 shell**(宿主未配置、用户未手动选择时):远程会话开终端即落到远端工作目录,本地会话自动回落本地 shell(issue #55);`false` 则只保留菜单项 |
313
313
  | `tui` | bool | `true` | TUI 适配层(dsh-tui)总开关;`false` 时不注册 `/dsh-remote` 页面、工作区 provider 与状态行字段 |
314
314
  | `tuiProviderListRecent` | bool | `true` | TUI 工作区选择器里是否列出每台机器最近的远程项目 |
package/lib/client.js CHANGED
@@ -251,8 +251,6 @@ window.__ModuleLoader__.load({
251
251
  'settings.updateNow': '立即更新',
252
252
  'settings.updateMode': '更新模式:',
253
253
  'settings.explorerAutoOpen': '打开远程工作区时,自动在侧边栏展开「远程文件」(需安装 better-sidebar)',
254
- 'settings.telemetry': '匿名使用统计(每日一次的安装心跳;不含任何机器信息,可随时关闭)',
255
- 'settings.telemetryHint': '上报内容只有插件专属的 HMAC 伪名与版本号;关闭后立即不再发送',
256
254
  'settings.updateManual': '手动',
257
255
  'settings.updateAuto': '自动',
258
256
  'settings.updateOff': '关闭',
@@ -559,8 +557,7 @@ window.__ModuleLoader__.load({
559
557
  'settings.updateNow': 'Update now',
560
558
  'settings.updateMode': 'Update mode:',
561
559
  'settings.explorerAutoOpen': 'Auto-open the Remote Files sidebar tab for remote workspaces (via better-sidebar)',
562
- 'settings.telemetry': 'Anonymous usage statistics (one install heartbeat per day; no machine info; can be turned off anytime)',
563
- 'settings.telemetryHint': 'Only a plugin-specific HMAC pseudonym and the version number are sent; takes effect immediately',
560
+
564
561
  'settings.updateManual': 'Manual',
565
562
  'settings.updateAuto': 'Auto',
566
563
  'settings.updateOff': 'Off',
@@ -1266,12 +1263,6 @@ window.__ModuleLoader__.load({
1266
1263
  // Issue #78: initial value comes from localStorage, so a user's choice
1267
1264
  // survives restarts (the bug was: the panel popped again every restart).
1268
1265
  const [explorerAuto, setExplorerAuto] = React.useState(() => explorerAutoOpenEnabled())
1269
- // Anonymous-heartbeat toggle: null = not loaded yet (checkbox disabled).
1270
- // Effective value is host-side (user override > profile config).
1271
- const [telemetryOn, setTelemetryOn] = React.useState(null)
1272
- React.useEffect(() => {
1273
- api('GET', '/dsh-remote/telemetry').then((r) => setTelemetryOn(!(r && r.enabled === false))).catch(() => {})
1274
- }, [])
1275
1266
  // One applier per toggle, shared by the native-checkbox fallback (event
1276
1267
  // semantics) and the host Switch (bare-boolean callback), so both paths
1277
1268
  // behave identically.
@@ -1279,12 +1270,6 @@ window.__ModuleLoader__.load({
1279
1270
  setExplorerAuto(on)
1280
1271
  try { window.localStorage.setItem(EXPLORER_AUTO_OPEN_KEY, on ? '1' : '0') } catch { /* private mode: choice lasts this session only */ }
1281
1272
  }
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
- }
1288
1273
  const checkUpdate = (quiet) => {
1289
1274
  if (updBusy) return
1290
1275
  setUpdBusy(true); setUpdMsg('')
@@ -2022,28 +2007,6 @@ window.__ModuleLoader__.load({
2022
2007
  }),
2023
2008
  tr('settings.explorerAutoOpen'),
2024
2009
  ),
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
- ),
2047
2010
  ),
2048
2011
  upd && upd.pendingReload
2049
2012
  ? React.createElement('div', { style: { marginTop: 6, fontSize: 12, color: T.warn } },
@@ -142,7 +142,12 @@ export function guardRoute(route, connectionOf) {
142
142
  return {
143
143
  ...route,
144
144
  handler: async (req, res) => {
145
- const connection = connectionOf()
145
+ // `fence: 'bearer'` routes authenticate with their OWN credential (a
146
+ // per-boot token from a 0600 file) and serve non-browser local processes
147
+ // (the askpass helper) — the Connection fence would 401 them for lacking
148
+ // the browser cookie. They still get the fail-closed fallback fence, so a
149
+ // cross-site page (which cannot read the token file) stays locked out.
150
+ const connection = route.fence === 'bearer' ? undefined : connectionOf()
146
151
  const rejection = typeof connection?.requestRejection === 'function'
147
152
  ? connection.requestRejection(req)
148
153
  : fallbackRejection(req)
package/lib/index.js CHANGED
@@ -21,7 +21,8 @@
21
21
  import z from '@deepseek-ai/schemastery'
22
22
  import { defineTool } from '@deepseek-ai/dsh-tools'
23
23
  import { execFile } from 'node:child_process'
24
- import { readFileSync, mkdirSync, writeFileSync, existsSync, readdirSync, statSync, renameSync, copyFileSync, appendFileSync, watch, rmSync } from 'node:fs'
24
+ import { readFileSync, mkdirSync, writeFileSync, existsSync, readdirSync, statSync, renameSync, copyFileSync, appendFileSync, watch, rmSync, chmodSync } from 'node:fs'
25
+ import { createHash, randomBytes, timingSafeEqual } from 'node:crypto'
25
26
  import { homedir } from 'node:os'
26
27
  import path from 'node:path'
27
28
  import { fileURLToPath } from 'node:url'
@@ -52,7 +53,7 @@ import { ForwardManager } from './forwards.js'
52
53
  import { WebAttach } from './web-attach.js'
53
54
  import { formatAuditLine, readAuditLines } from './audit.js'
54
55
 
55
- import { selfDir, diskVersion, LOADED_VERSION, gtVersion, fetchLatestVersion, applyUpdate, persistUpdateMode, readUpdateMode, reloadSelf, scheduleSelfReload, lastSelfReload, isInstalledCopy } from './update.js'
56
+ import { selfDir, diskVersion, LOADED_VERSION, gtVersion, fetchLatestVersion, applyUpdate, persistUpdateMode, readUpdateMode, reloadSelf, scheduleSelfReload, lastSelfReload, isInstalledCopy, writeFileAtomic } from './update.js'
56
57
  import { sendHeartbeat, pseudonym, heartbeatUrl, hasPersistedId, installIdPath, telemetryAllowed, persistTelemetryOpt } from './telemetry.js'
57
58
  import { loadMachines as _loadMachines, saveMachines as _saveMachines, sanitizeMachine as _sanitizeMachine, applyMachine as _applyMachine, machineId as _machineId, normalizeMachineGroup, filterMachinesByGroup, resolveProbeCredentials } from './registry.js'
58
59
  import { registerHttpTransports } from './http-transport.js'
@@ -474,6 +475,34 @@ export async function apply(ctx, config) {
474
475
  // 伪名,原始安装 id 与任何机器信息都不离开本机。
475
476
  if (telemetryAllowed(dshBase(), config.telemetry)) void sendHeartbeat(dshBase(), LOADED_VERSION)
476
477
 
478
+ // ── terminal credential bridge (saved passwords for the `remote ssh` shell) ─
479
+ // The generated terminal launcher spawns the OS ssh, which cannot receive the
480
+ // plugin's saved passwords by itself. Bridge: a per-boot bearer token in
481
+ // $DSH_HOME/remote-terminal/term-secret.json (0600) + a POST route that
482
+ // resolves the machine through the SAME credential chain a real connect uses.
483
+ // The askpass helper (written next to the launcher) is the only reader.
484
+ const termSecretFile = () => path.join(remoteTerminalRoot(), 'term-secret.json')
485
+ const termSecretToken = randomBytes(24).toString('hex')
486
+ // A stale payload from a previous boot would name a dead port with a dead
487
+ // token — and with SSH_ASKPASS_REQUIRE=force a failing bridge means NO tty
488
+ // prompt at all. Always boot from absent; only a live webServer re-creates it
489
+ // (Desktop compositions have no HTTP listener, so the bridge stays off there
490
+ // and the terminal keeps its interactive prompt).
491
+ try { rmSync(termSecretFile(), { force: true }) } catch { /* absent is fine */ }
492
+ const writeTermSecretPayload = (origin) => {
493
+ if (!origin) return false
494
+ try {
495
+ mkdirSync(remoteTerminalRoot(), { recursive: true })
496
+ writeFileAtomic(termSecretFile(), JSON.stringify({ version: 1, url: String(origin).replace(/\/+$/, ''), token: termSecretToken }))
497
+ try { chmodSync(termSecretFile(), 0o600) } catch { /* Windows: dir is already user-private */ }
498
+ return true
499
+ } catch { return false }
500
+ }
501
+ const termSecretOk = (presented) => {
502
+ const dig = (s) => createHash('sha256').update(String(s)).digest()
503
+ return timingSafeEqual(dig(presented), dig(termSecretToken))
504
+ }
505
+
477
506
  // The update marker means "a newer version landed on disk but is not the code
478
507
  // running yet". Reaching apply() with a marker naming the version we just
479
508
  // loaded means the swap already happened (or this is a plain boot into the
@@ -4723,10 +4752,63 @@ export async function apply(ctx, config) {
4723
4752
  }
4724
4753
  },
4725
4754
  },
4755
+ {
4756
+ kind: 'exact',
4757
+ path: '/dsh-remote/term-secret',
4758
+ // Owns its bearer token (per boot, 0600 file): the caller is a local
4759
+ // PROCESS (the askpass helper), not a browser, so the Connection cookie
4760
+ // fence would 401 it. The fallback fence still locks out cross-site pages
4761
+ // (they cannot read the token file).
4762
+ fence: 'bearer',
4763
+ handler: async (req, res) => {
4764
+ if (req.method !== 'POST') return sendJson(res, 405, { ok: false, error: 'method not allowed' })
4765
+ // Self-heal: a caller exists but the payload was never published (the
4766
+ // origin arrived after the first write attempts).
4767
+ if (!existsSync(termSecretFile())) {
4768
+ try {
4769
+ const ws = ctx.get('webServer')
4770
+ if (ws && typeof ws.getOrigin === 'function') writeTermSecretPayload(ws.getOrigin())
4771
+ } catch { /* still no listener: the 403 below answers honestly */ }
4772
+ }
4773
+ // Malformed bodies are a 400 with a reason even before the token check
4774
+ // (the routes matrix pins that readability contract for every POST).
4775
+ let body = {}
4776
+ try { body = JSON.parse((await readBody(req)) || '{}') } catch { return sendJson(res, 400, { ok: false, error: 'invalid JSON body' }) }
4777
+ const presented = String((req.headers && req.headers.authorization) || '').replace(/^Bearer\s+/i, '')
4778
+ if (!presented || !termSecretOk(presented)) return sendJson(res, 403, { ok: false, error: 'forbidden' })
4779
+ const alias = String(body.alias || '')
4780
+ let m = null
4781
+ if (alias) m = machines.find((x) => x && x.useSshConfig && String(x.host) === alias) || null
4782
+ if (!m) {
4783
+ const host = String(body.host || '')
4784
+ const port = Number(body.port) || 22
4785
+ const user = String(body.username || '')
4786
+ m = machines.find((x) => x && !x.useSshConfig && String(x.host) === host && (Number(x.port) || 22) === port && String(x.username || '') === user) || null
4787
+ }
4788
+ if (!m) return sendJson(res, 404, { ok: false, error: 'unknown machine' })
4789
+ const password = await machinePassword(m)
4790
+ return sendJson(res, 200, { ok: true, password })
4791
+ },
4792
+ },
4726
4793
  ]
4727
4794
 
4728
4795
  registerHttpTransports(ctx, routes)
4729
4796
 
4797
+ // Publish the credential-bridge payload as soon as the loopback origin is
4798
+ // known (the listener may still be binding at apply time — retry once).
4799
+ ctx.inject(['webServer'], (inner) => {
4800
+ const ws = inner.get('webServer')
4801
+ const publish = () => {
4802
+ try {
4803
+ return writeTermSecretPayload(typeof ws.getOrigin === 'function' ? ws.getOrigin() : '')
4804
+ } catch { return false } // listener not bound yet
4805
+ }
4806
+ if (!publish()) {
4807
+ const timer = setTimeout(publish, 2000)
4808
+ if (typeof timer.unref === 'function') timer.unref()
4809
+ }
4810
+ })
4811
+
4730
4812
  // ── remote terminal: one extra shell in the host terminal's own list ──────
4731
4813
  // Additive and optional: a composition without `terminalController` simply
4732
4814
  // keeps the terminal it already had.
@@ -266,14 +266,59 @@ function stdinIsInteractive(deps = {}) {
266
266
  }
267
267
  }
268
268
 
269
+ /**
270
+ * Whether the machine's password auth needs (and can use) the credential
271
+ * bridge. Keys, agents and ssh-config aliases authenticate without us;
272
+ * keyboard-interactive (OTP) prompts are per-login and must stay on the tty;
273
+ * everything else with a stored credential (plaintext registry or OS keychain)
274
+ * goes through the bridge.
275
+ *
276
+ * @param {object|undefined} machine - the matched registry record.
277
+ * @returns {boolean}
278
+ */
279
+ function needsAskpass(machine) {
280
+ if (!machine) return false
281
+ if (machine.useAgent || machine.useSshConfig || machine.keyboardInteractive) return false
282
+ if (String(machine.privateKeyPath || '')) return false
283
+ if (String(machine.password || '')) return true
284
+ return Boolean(machine.credentialBackend && machine.credentialBackend !== 'plain')
285
+ }
286
+
287
+ /**
288
+ * Environment additions that route ssh's password prompt to the bridge helper.
289
+ * Only applied when needsAskpass() held AND the payload file exists.
290
+ *
291
+ * `SSH_ASKPASS_REQUIRE=force` (OpenSSH ≥ 8.4) is what makes askpass run at all
292
+ * on a tty; DISPLAY feeds prehistoric ssh builds. DSH_TS_* carries the machine
293
+ * identity to the helper through the process environment.
294
+ *
295
+ * @param {object} machine
296
+ * @param {string} termDir - the launcher's directory (DSH_TERM_DIR).
297
+ * @param {string} [platform]
298
+ * @returns {object} env entries to merge over process.env
299
+ */
300
+ function askpassEnv(machine, termDir, platform = process.platform) {
301
+ const wrapper = path.join(termDir, platform === 'win32' ? 'term-askpass.cmd' : 'term-askpass')
302
+ return {
303
+ SSH_ASKPASS: wrapper,
304
+ SSH_ASKPASS_REQUIRE: 'force',
305
+ DISPLAY: process.env.DISPLAY || 'dsh-remote:0',
306
+ DSH_TS_HOST: String(machine.host || ''),
307
+ DSH_TS_PORT: String(Number(machine.port) || 22),
308
+ DSH_TS_USERNAME: String(machine.username || ''),
309
+ DSH_TS_ALIAS: String(machine.alias || ''),
310
+ }
311
+ }
312
+
269
313
  /**
270
314
  * Hand the current process over to `file args…`, propagating the exit code.
271
315
  * @param {string} file
272
316
  * @param {string[]} args
317
+ * @param {object} [extraEnv] - env entries merged over process.env (askpass).
273
318
  * @returns {import('node:child_process').ChildProcess}
274
319
  */
275
- function handover(file, args) {
276
- const child = spawn(file, args, { stdio: 'inherit' })
320
+ function handover(file, args, extraEnv) {
321
+ const child = spawn(file, args, { stdio: 'inherit', env: extraEnv ? { ...process.env, ...extraEnv } : process.env })
277
322
  child.on('error', (error) => {
278
323
  process.stderr.write(`[dsh-remote] cannot run ${file}: ${error && error.message}\n`)
279
324
  process.exit(127)
@@ -322,13 +367,24 @@ function main(argv = process.argv.slice(2), deps = {}) {
322
367
  process.stderr.write('[dsh-remote] the remote workspace is a Windows path; opening the remote default shell without changing directory.\n')
323
368
  process.stderr.write('[dsh-remote] 远端工作区是 Windows 路径,已打开默认 shell(未自动切换目录)。\n')
324
369
  }
370
+ // Saved-password bridge: when the machine needs password auth and the host
371
+ // wrote the bridge payload (Web composition only), answer ssh's password
372
+ // prompt through the plugin's credential chain instead of the tty.
373
+ const termDir = env.DSH_TERM_DIR || ''
374
+ if (termDir && needsAskpass(resolved.machine) && existsSync(path.join(termDir, 'term-secret.json'))) {
375
+ process.stderr.write('[dsh-remote] using the saved password via the local credential bridge.\n')
376
+ process.stderr.write('[dsh-remote] 已保存的密码将通过本机凭据桥自动应答。\n')
377
+ return handover(ssh, args, askpassEnv(resolved.machine, termDir, platform))
378
+ }
325
379
  return handover(ssh, args)
326
380
  }
327
381
 
328
382
  module.exports = {
329
383
  META_FILE,
384
+ askpassEnv,
330
385
  buildSshArgs,
331
386
  findMirror,
387
+ needsAskpass,
332
388
  isWindowsRemotePath,
333
389
  localShell,
334
390
  main,
@@ -250,6 +250,10 @@ export function launcherSource(spec) {
250
250
  'setlocal',
251
251
  `set "DSH_CHILD=${child}"`,
252
252
  `set "DSH_MACHINES=${machines}"`,
253
+ // Where the askpass helper + credential-bridge payload live (this .cmd's
254
+ // own directory); the child reads it to decide whether password auth can
255
+ // be bridged (see remote-shell-child.cjs askpassEnv).
256
+ 'set "DSH_TERM_DIR=%~dp0"',
253
257
  `set "DSH_NODE=${node}"`,
254
258
  'if defined DSH_NODE if exist "%DSH_NODE%" goto :run',
255
259
  'set "DSH_NODE="',
@@ -287,6 +291,8 @@ export function launcherSource(spec) {
287
291
  '# Generated by dsh-remote - do not edit; rewritten on every load.',
288
292
  `DSH_CHILD=${shqPosix(child)}`,
289
293
  `DSH_MACHINES=${shqPosix(machines)}`,
294
+ // Physical directory of this script: the askpass helper + payload live here.
295
+ 'DSH_TERM_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)',
290
296
  node ? `DSH_NODE=${shqPosix(node)}` : 'DSH_NODE=',
291
297
  'if [ -n "$DSH_NODE" ] && [ -x "$DSH_NODE" ]; then exec "$DSH_NODE" "$DSH_CHILD" --machines "$DSH_MACHINES"; fi',
292
298
  'if command -v node >/dev/null 2>&1; then exec node "$DSH_CHILD" --machines "$DSH_MACHINES"; fi',
@@ -301,6 +307,114 @@ export function shqPosix(value) {
301
307
  return "'" + String(value).replace(/'/g, "'\\''") + "'"
302
308
  }
303
309
 
310
+ // ── the credential bridge helper (saved-password terminal auth) ─────────────
311
+ //
312
+ // The `remote ssh` terminal spawns the OS ssh, which knows keys and agents but
313
+ // has no way to receive the password the plugin saved (plaintext registry or OS
314
+ // keychain). The bridge: ssh (with SSH_ASKPASS_REQUIRE=force) calls this
315
+ // helper, the helper POSTs the machine identity to the RUNNING plugin's
316
+ // loopback route `/dsh-remote/term-secret` with a per-boot bearer token, and
317
+ // the host answers through the same credential chain a real connect uses.
318
+ // The token + URL live in `term-secret.json` next to the launcher (0600); the
319
+ // helper itself carries no secret.
320
+
321
+ /** Absolute path of the askpass wrapper for the platform. */
322
+ export function askpassWrapperPath(dir, platform = process.platform) {
323
+ return path.join(dir, platform === 'win32' ? 'term-askpass.cmd' : 'term-askpass')
324
+ }
325
+
326
+ /** Body of term-askpass.cjs — plain CJS, no dependencies, no secrets. */
327
+ export function askpassHelperSource() {
328
+ return [
329
+ '#!/usr/bin/env node',
330
+ '// Generated by dsh-remote - do not edit; rewritten on every load.',
331
+ '// ssh askpass helper: fetch the saved password for DSH_TS_* (host/port/',
332
+ '// username) from the running dsh-remote host, print it on stdout.',
333
+ '// Exit nonzero without output when the bridge cannot answer - ssh then',
334
+ '// fails authentication (SSH_ASKPASS_REQUIRE=force trades the tty prompt',
335
+ '// for the bridge; the child only enables it when a credential exists).',
336
+ "'use strict'",
337
+ 'const { readFileSync } = require("node:fs")',
338
+ 'const { join } = require("node:path")',
339
+ 'const http = require("node:http")',
340
+ 'function main() {',
341
+ ' let cfg',
342
+ ' try { cfg = JSON.parse(readFileSync(join(__dirname, "term-secret.json"), "utf8")) } catch { process.exit(2) }',
343
+ ' const body = JSON.stringify({',
344
+ ' host: process.env.DSH_TS_HOST || "",',
345
+ ' port: Number(process.env.DSH_TS_PORT) || 22,',
346
+ ' username: process.env.DSH_TS_USERNAME || "",',
347
+ ' alias: process.env.DSH_TS_ALIAS || "",',
348
+ ' })',
349
+ ' const base = String(cfg.url || "").replace(/\\/+$/, "")',
350
+ ' if (!cfg.token || !base) process.exit(2)',
351
+ ' const url = new URL(base + "/dsh-remote/term-secret")',
352
+ ' const req = http.request({',
353
+ ' method: "POST", host: url.hostname, port: url.port, path: url.pathname,',
354
+ ' headers: {',
355
+ ' "content-type": "application/json",',
356
+ ' authorization: "Bearer " + cfg.token,',
357
+ ' "content-length": Buffer.byteLength(body),',
358
+ ' },',
359
+ ' timeout: 5000,',
360
+ ' }, (res) => {',
361
+ ' let buf = ""',
362
+ ' res.on("data", (chunk) => { buf += chunk })',
363
+ ' res.on("end", () => {',
364
+ ' try {',
365
+ ' const parsed = JSON.parse(buf)',
366
+ ' if (res.statusCode === 200 && parsed && parsed.ok && typeof parsed.password === "string" && parsed.password.length > 0) {',
367
+ ' process.stdout.write(parsed.password + "\\n")',
368
+ ' return',
369
+ ' }',
370
+ ' } catch { /* malformed answer */ }',
371
+ ' process.exit(3)',
372
+ ' })',
373
+ ' })',
374
+ ' req.on("timeout", () => { req.destroy(); process.exit(4) })',
375
+ ' req.on("error", () => process.exit(5))',
376
+ ' req.end(body)',
377
+ '}',
378
+ 'main()',
379
+ '',
380
+ ].join('\n')
381
+ }
382
+
383
+ /**
384
+ * Write the askpass helper + its platform wrapper next to the launcher.
385
+ * Called from writeLauncher so an upgrade rewrites both in one place.
386
+ * Carries NO secret: URL + per-boot token land in term-secret.json, written by
387
+ * the host half once the webserver origin is known (and deleted on boot when
388
+ * the composition has no webserver, so a stale bridge can never hijack the
389
+ * prompt on Desktop).
390
+ *
391
+ * @param {{ dir: string, platform?: string, nodePath?: string, fs?: object }} spec
392
+ */
393
+ export function writeTermSecretHelpers(spec) {
394
+ const platform = spec.platform || process.platform
395
+ const fs = spec.fs || { writeFileSync, chmodSync }
396
+ const node = spec.nodePath || 'node'
397
+ fs.writeFileSync(path.join(spec.dir, 'term-askpass.cjs'), askpassHelperSource(), 'utf8')
398
+ const wrapper = askpassWrapperPath(spec.dir, platform)
399
+ if (platform === 'win32') {
400
+ fs.writeFileSync(wrapper, [
401
+ '@echo off',
402
+ 'rem Generated by dsh-remote - do not edit; rewritten on every load.',
403
+ `"${node}" "%~dp0term-askpass.cjs" %*`,
404
+ '',
405
+ ].join('\r\n'), 'utf8')
406
+ } else {
407
+ fs.writeFileSync(wrapper, [
408
+ '#!/bin/sh',
409
+ '# Generated by dsh-remote - do not edit; rewritten on every load.',
410
+ `exec ${shqPosix(node)} "$(dirname -- "$0")/term-askpass.cjs" "$@"`,
411
+ '',
412
+ ].join('\n'), 'utf8')
413
+ try { fs.chmodSync(wrapper, 0o755) } catch { /* mode-less fs */ }
414
+ }
415
+ return { wrapper, helper: path.join(spec.dir, 'term-askpass.cjs') }
416
+ }
417
+
304
418
  /**
305
419
  * Remove a launcher left on disk under another spelling of the same name.
306
420
  *
@@ -353,7 +467,10 @@ export function writeLauncher(spec) {
353
467
  if (platform !== 'win32') {
354
468
  try { fs.chmodSync(file, 0o755) } catch { /* a no-op on filesystems without modes */ }
355
469
  }
356
- return { path: file, source }
470
+ // The credential-bridge helper travels with the launcher (same rewrite
471
+ // cadence, same directory the launcher exports as DSH_TERM_DIR).
472
+ const helpers = writeTermSecretHelpers({ dir: spec.dir, platform, nodePath: spec.nodePath || '', fs })
473
+ return { path: file, source, askpass: helpers.wrapper }
357
474
  }
358
475
 
359
476
  /**
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.79",
3
+ "version": "0.8.81",
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>",