dsh-remote 0.8.91 → 0.8.93

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.
Files changed (181) hide show
  1. package/LICENSE +21 -21
  2. package/README.en.md +369 -368
  3. package/README.md +354 -353
  4. package/cordis.patch.yml +9 -9
  5. package/lib/audit.js +45 -45
  6. package/lib/binding.js +172 -172
  7. package/lib/client.js +4647 -4550
  8. package/lib/credential.js +270 -263
  9. package/lib/errors.js +141 -141
  10. package/lib/exec-job.js +242 -242
  11. package/lib/file-reference.js +457 -457
  12. package/lib/forwards.js +258 -258
  13. package/lib/host-api.js +822 -822
  14. package/lib/hostkey.js +108 -108
  15. package/lib/http-transport.js +201 -201
  16. package/lib/ignore.js +202 -202
  17. package/lib/index.js +4488 -4394
  18. package/lib/instructions-dynamic.js +415 -415
  19. package/lib/instructions.js +288 -288
  20. package/lib/open-folder.js +56 -56
  21. package/lib/openssh.js +940 -881
  22. package/lib/paths.js +292 -292
  23. package/lib/pool.js +1029 -970
  24. package/lib/posix-shell.cjs +34 -0
  25. package/lib/registry.js +296 -296
  26. package/lib/remote-fs.js +173 -173
  27. package/lib/remote-sandbox.js +183 -183
  28. package/lib/remote-shell-child.cjs +397 -400
  29. package/lib/remote-shell.js +697 -697
  30. package/lib/remote-skills.js +312 -0
  31. package/lib/routes-audit.js +58 -58
  32. package/lib/routes-forwards.js +72 -72
  33. package/lib/routes-fs.js +251 -245
  34. package/lib/routes-machines.js +186 -186
  35. package/lib/routes-misc.js +187 -150
  36. package/lib/routes-term.js +169 -169
  37. package/lib/routes-update.js +143 -143
  38. package/lib/routes-web-attach.js +112 -112
  39. package/lib/routes-workspace.js +312 -312
  40. package/lib/search.js +235 -235
  41. package/lib/sftp-surface.js +119 -119
  42. package/lib/sshconfig.js +779 -779
  43. package/lib/sync.js +350 -350
  44. package/lib/tasks.js +95 -95
  45. package/lib/telemetry.js +247 -247
  46. package/lib/terminal.js +205 -205
  47. package/lib/tui/flow.js +130 -130
  48. package/lib/tui/format.js +380 -380
  49. package/lib/tui/i18n.js +350 -350
  50. package/lib/tui/index.js +531 -531
  51. package/lib/tui/provider.js +344 -344
  52. package/lib/tui/scene.js +986 -986
  53. package/lib/update.js +490 -472
  54. package/lib/web-attach.js +860 -850
  55. package/lib/workspace-cleanup.js +337 -337
  56. package/package.json +103 -100
  57. package/node_modules/buildcheck/.eslintrc.js +0 -5
  58. package/node_modules/buildcheck/.github/workflows/ci.yml +0 -88
  59. package/node_modules/buildcheck/.github/workflows/lint.yml +0 -27
  60. package/node_modules/buildcheck/.npmignore +0 -3
  61. package/node_modules/buildcheck/LICENSE +0 -19
  62. package/node_modules/buildcheck/README.md +0 -106
  63. package/node_modules/buildcheck/deps/Find-VisualStudio.cs +0 -250
  64. package/node_modules/buildcheck/lib/findvs.js +0 -361
  65. package/node_modules/buildcheck/lib/index.js +0 -738
  66. package/node_modules/buildcheck/package.json +0 -36
  67. package/node_modules/buildcheck/test/test.js +0 -8
  68. package/node_modules/cpu-features/.eslintrc.js +0 -5
  69. package/node_modules/cpu-features/.github/workflows/ci.yml +0 -74
  70. package/node_modules/cpu-features/.github/workflows/lint.yml +0 -27
  71. package/node_modules/cpu-features/LICENSE +0 -19
  72. package/node_modules/cpu-features/README.md +0 -59
  73. package/node_modules/cpu-features/binding.gyp +0 -16
  74. package/node_modules/cpu-features/buildcheck.js +0 -32
  75. package/node_modules/cpu-features/deps/cpu_features/.clang-format +0 -4
  76. package/node_modules/cpu-features/deps/cpu_features/.dockerignore +0 -31
  77. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/Dockerfile +0 -5
  78. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/aarch64_linux_cmake.yml +0 -30
  79. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/amd64_freebsd_cmake.yml +0 -22
  80. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/amd64_linux_bazel.yml +0 -26
  81. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/amd64_linux_cmake.yml +0 -31
  82. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/amd64_macos_cmake.yml +0 -43
  83. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/amd64_windows_cmake.yml +0 -25
  84. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/arm_linux_cmake.yml +0 -31
  85. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/clang_format.yml +0 -24
  86. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/mips_linux_cmake.yml +0 -30
  87. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/power_linux_cmake.yml +0 -29
  88. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/riscv_linux_cmake.yml +0 -28
  89. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/s390x_linux_cmake.yml +0 -27
  90. package/node_modules/cpu-features/deps/cpu_features/.grenrc.yml +0 -21
  91. package/node_modules/cpu-features/deps/cpu_features/BUILD.bazel +0 -329
  92. package/node_modules/cpu-features/deps/cpu_features/CMakeLists.txt +0 -261
  93. package/node_modules/cpu-features/deps/cpu_features/CONTRIBUTING.md +0 -23
  94. package/node_modules/cpu-features/deps/cpu_features/LICENSE +0 -230
  95. package/node_modules/cpu-features/deps/cpu_features/README.md +0 -272
  96. package/node_modules/cpu-features/deps/cpu_features/WORKSPACE +0 -19
  97. package/node_modules/cpu-features/deps/cpu_features/bazel/ci/README.md +0 -5
  98. package/node_modules/cpu-features/deps/cpu_features/bazel/platforms.bzl +0 -11
  99. package/node_modules/cpu-features/deps/cpu_features/cmake/CpuFeaturesConfig.cmake.in +0 -3
  100. package/node_modules/cpu-features/deps/cpu_features/cmake/CpuFeaturesNdkCompatConfig.cmake.in +0 -3
  101. package/node_modules/cpu-features/deps/cpu_features/cmake/README.md +0 -30
  102. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/Makefile +0 -252
  103. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/README.md +0 -40
  104. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/doc/docker.dot +0 -64
  105. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/doc/docker.svg +0 -312
  106. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/doc/generate_image.sh +0 -7
  107. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/docker/amd64/Dockerfile +0 -48
  108. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/docker/toolchain/Dockerfile +0 -34
  109. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/sample/CMakeLists.txt +0 -22
  110. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/sample/main.cpp +0 -11
  111. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/vagrant/freebsd/Vagrantfile +0 -107
  112. package/node_modules/cpu-features/deps/cpu_features/cmake/googletest.CMakeLists.txt.in +0 -15
  113. package/node_modules/cpu-features/deps/cpu_features/cpu_features.gyp +0 -105
  114. package/node_modules/cpu-features/deps/cpu_features/include/cpu_features_cache_info.h +0 -54
  115. package/node_modules/cpu-features/deps/cpu_features/include/cpu_features_macros.h +0 -384
  116. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_aarch64.h +0 -259
  117. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_arm.h +0 -121
  118. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_mips.h +0 -74
  119. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_ppc.h +0 -149
  120. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_riscv.h +0 -72
  121. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_s390x.h +0 -108
  122. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_x86.h +0 -288
  123. package/node_modules/cpu-features/deps/cpu_features/include/internal/bit_utils.h +0 -40
  124. package/node_modules/cpu-features/deps/cpu_features/include/internal/cpuid_x86.h +0 -37
  125. package/node_modules/cpu-features/deps/cpu_features/include/internal/filesystem.h +0 -39
  126. package/node_modules/cpu-features/deps/cpu_features/include/internal/hwcaps.h +0 -240
  127. package/node_modules/cpu-features/deps/cpu_features/include/internal/stack_line_reader.h +0 -49
  128. package/node_modules/cpu-features/deps/cpu_features/include/internal/string_view.h +0 -110
  129. package/node_modules/cpu-features/deps/cpu_features/include/internal/windows_utils.h +0 -70
  130. package/node_modules/cpu-features/deps/cpu_features/ndk_compat/CMakeLists.txt +0 -60
  131. package/node_modules/cpu-features/deps/cpu_features/ndk_compat/README.md +0 -4
  132. package/node_modules/cpu-features/deps/cpu_features/ndk_compat/cpu-features.c +0 -205
  133. package/node_modules/cpu-features/deps/cpu_features/ndk_compat/cpu-features.h +0 -320
  134. package/node_modules/cpu-features/deps/cpu_features/ndk_compat/ndk-compat-test.c +0 -12
  135. package/node_modules/cpu-features/deps/cpu_features/patches/0001-Add-Apple-Silicon-Support.patch +0 -456
  136. package/node_modules/cpu-features/deps/cpu_features/scripts/generate_badges.d +0 -165
  137. package/node_modules/cpu-features/deps/cpu_features/scripts/make_release.sh +0 -75
  138. package/node_modules/cpu-features/deps/cpu_features/scripts/run_integration.sh +0 -490
  139. package/node_modules/cpu-features/deps/cpu_features/scripts/test_integration.sh +0 -79
  140. package/node_modules/cpu-features/deps/cpu_features/src/copy.inl +0 -19
  141. package/node_modules/cpu-features/deps/cpu_features/src/define_introspection.inl +0 -86
  142. package/node_modules/cpu-features/deps/cpu_features/src/define_introspection_and_hwcaps.inl +0 -26
  143. package/node_modules/cpu-features/deps/cpu_features/src/equals.inl +0 -22
  144. package/node_modules/cpu-features/deps/cpu_features/src/filesystem.c +0 -62
  145. package/node_modules/cpu-features/deps/cpu_features/src/hwcaps.c +0 -169
  146. package/node_modules/cpu-features/deps/cpu_features/src/impl_aarch64__base_implementation.inl +0 -88
  147. package/node_modules/cpu-features/deps/cpu_features/src/impl_aarch64_linux_or_android.c +0 -79
  148. package/node_modules/cpu-features/deps/cpu_features/src/impl_aarch64_macos_or_iphone.c +0 -82
  149. package/node_modules/cpu-features/deps/cpu_features/src/impl_aarch64_windows.c +0 -138
  150. package/node_modules/cpu-features/deps/cpu_features/src/impl_arm_linux_or_android.c +0 -212
  151. package/node_modules/cpu-features/deps/cpu_features/src/impl_mips_linux_or_android.c +0 -93
  152. package/node_modules/cpu-features/deps/cpu_features/src/impl_ppc_linux.c +0 -163
  153. package/node_modules/cpu-features/deps/cpu_features/src/impl_riscv_linux.c +0 -111
  154. package/node_modules/cpu-features/deps/cpu_features/src/impl_s390x_linux.c +0 -120
  155. package/node_modules/cpu-features/deps/cpu_features/src/impl_x86__base_implementation.inl +0 -2055
  156. package/node_modules/cpu-features/deps/cpu_features/src/impl_x86_freebsd.c +0 -68
  157. package/node_modules/cpu-features/deps/cpu_features/src/impl_x86_linux_or_android.c +0 -58
  158. package/node_modules/cpu-features/deps/cpu_features/src/impl_x86_macos.c +0 -57
  159. package/node_modules/cpu-features/deps/cpu_features/src/impl_x86_windows.c +0 -58
  160. package/node_modules/cpu-features/deps/cpu_features/src/stack_line_reader.c +0 -132
  161. package/node_modules/cpu-features/deps/cpu_features/src/string_view.c +0 -192
  162. package/node_modules/cpu-features/deps/cpu_features/src/utils/list_cpu_features.c +0 -461
  163. package/node_modules/cpu-features/deps/cpu_features/test/CMakeLists.txt +0 -114
  164. package/node_modules/cpu-features/deps/cpu_features/test/bit_utils_test.cc +0 -53
  165. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_aarch64_test.cc +0 -396
  166. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_arm_test.cc +0 -384
  167. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_mips_test.cc +0 -176
  168. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_ppc_test.cc +0 -131
  169. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_riscv_test.cc +0 -180
  170. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_s390x_test.cc +0 -82
  171. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_x86_test.cc +0 -1729
  172. package/node_modules/cpu-features/deps/cpu_features/test/filesystem_for_testing.cc +0 -103
  173. package/node_modules/cpu-features/deps/cpu_features/test/filesystem_for_testing.h +0 -61
  174. package/node_modules/cpu-features/deps/cpu_features/test/hwcaps_for_testing.cc +0 -52
  175. package/node_modules/cpu-features/deps/cpu_features/test/hwcaps_for_testing.h +0 -31
  176. package/node_modules/cpu-features/deps/cpu_features/test/stack_line_reader_test.cc +0 -132
  177. package/node_modules/cpu-features/deps/cpu_features/test/string_view_test.cc +0 -202
  178. package/node_modules/cpu-features/lib/index.js +0 -5
  179. package/node_modules/cpu-features/package.json +0 -40
  180. package/node_modules/cpu-features/src/binding.cc +0 -151
  181. package/node_modules/cpu-features/test/test.js +0 -12
package/lib/tui/scene.js CHANGED
@@ -1,986 +1,986 @@
1
- // dsh-remote TUI — `/dsh-remote` 全屏「远程服务器」管理页。
2
- //
3
- // 硬约束(dsh-tui 场景契约,见 dsh-adapter/scenes.d.ts):
4
- // · hooks 只能用 props 注入的 React;元素只能 React.createElement(仓库没有
5
- // JSX 编译器,也没有构建步骤)
6
- // · 渲染期禁止同步 I/O / 网络:机器列表、状态、目录全部在 useEffect 或按键
7
- // 回调里异步取;组件卸载后(alive ref = false)丢弃结果
8
- // · 密码 / passphrase 永不回显:编辑时输入框恒为空,留空 = 不修改
9
- //
10
- // 视图状态机:list → menu / form / browse / confirm。
11
- // Esc / q:子视图先回列表,列表根视图关闭场景。
12
-
13
- import {
14
- AUTH_MODES,
15
- basenameRemote,
16
- emptyMachineForm,
17
- formatBytes,
18
- formFromMachine,
19
- statusLine,
20
- targetFromWorkspace,
21
- validateMachineForm,
22
- } from './format.js'
23
-
24
- /** 动作菜单项(顺序即渲染顺序)。 */
25
- const MENU_ACTIONS = ['connect', 'workspaces', 'edit', 'delete', 'probe', 'browse']
26
- /** 表单里永远出现的字段。 */
27
- const BASE_FORM_FIELDS = ['name', 'host', 'useSshConfig', 'port', 'username', 'auth']
28
-
29
- /** 取错误对象里面向用户的一句话。 */
30
- function messageOf(error) {
31
- if (!error) return ''
32
- return String((error && error.message) || error)
33
- }
34
-
35
- /** 按**码点**截断(不是 UTF-16 码元),避免切出孤立代理对(emoji、CJK 扩展 B)。 */
36
- function clip(text, max) {
37
- const value = String(text === undefined || text === null ? '' : text)
38
- const limit = Math.max(0, Number(max) || 0)
39
- if (!limit) return value
40
- const points = Array.from(value)
41
- if (points.length <= limit) return value
42
- return points.slice(0, Math.max(0, limit - 1)).join('') + '…'
43
- }
44
-
45
- /** 掩码显示:只体现“有值”,永远不回显内容本身。 */
46
- function maskValue(value) {
47
- const length = String(value === undefined || value === null ? '' : value).length
48
- return length ? '•'.repeat(Math.min(length, 20)) : ''
49
- }
50
-
51
- /** 机器显示名:name → host → id。 */
52
- function machineName(machine) {
53
- if (!machine) return ''
54
- const name = String(machine.name || '').trim()
55
- return name || String(machine.host || machine.id || '')
56
- }
57
-
58
- /** `user@host:port` 单行身份。 */
59
- function machineAddress(machine) {
60
- if (!machine) return ''
61
- const host = String(machine.host || '')
62
- const user = String(machine.username || '')
63
- const port = Number(machine.port) || 22
64
- return `${user ? user + '@' : ''}${host}:${port}`
65
- }
66
-
67
- /** 认证方式循环切换。 */
68
- function nextAuth(current, step) {
69
- const index = Math.max(0, AUTH_MODES.indexOf(current))
70
- const next = (index + (step || 1) + AUTH_MODES.length) % AUTH_MODES.length
71
- return AUTH_MODES[next]
72
- }
73
-
74
- /** 表单可见字段(认证方式决定密码 / 私钥组是否出现)。 */
75
- function fieldsFor(form) {
76
- const fields = [...BASE_FORM_FIELDS]
77
- if (!form || form.auth === 'password') fields.push('password')
78
- else if (form.auth === 'key') fields.push('privateKeyPath', 'passphrase')
79
- fields.push('group')
80
- return fields
81
- }
82
-
83
- /** 以 selected 为中心切出可视窗口(只用状态派生,不存滚动偏移)。 */
84
- function windowSlice(items, selected, height) {
85
- const list = Array.isArray(items) ? items : []
86
- const size = Math.max(1, Number(height) || 1)
87
- if (list.length <= size) return { offset: 0, items: list }
88
- let offset = Math.max(0, Math.min(Number(selected) || 0, list.length - 1) - Math.floor(size / 2))
89
- offset = Math.min(offset, list.length - size)
90
- return { offset, items: list.slice(offset, offset + size) }
91
- }
92
-
93
- /**
94
- * 创建全屏场景组件。
95
- *
96
- * @param {object} deps
97
- * @param {object} deps.api - 宿主进程内 API(apiVersion 1)。
98
- * @param {object} [deps.config] - 行 config(tuiAutoSwitchWorkspace 等)。
99
- * @param {object} [deps.i18n] - createI18n 的返回值。
100
- * @param {(text: string, options?: object) => void} [deps.notify] - 无 channel 时的提示通道。
101
- * @returns {Function} React 组件(props: { React, ui, channel, close })。
102
- */
103
- export function createSceneComponent({ api, config, i18n, notify } = {}) {
104
- const t = i18n && typeof i18n.t === 'function' ? i18n.t : (key) => String(key)
105
- const autoSwitch = !config || config.tuiAutoSwitchWorkspace !== false
106
-
107
- /** Host kit is mandatory; the guard lives OUTSIDE the hooking component so the
108
- * hook count never depends on props (React requires a constant hook order). */
109
- return function DshRemoteScene(props) {
110
- const React = props && props.React
111
- if (!React || !props.ui) return null
112
- return React.createElement(DshRemoteSceneBody, props)
113
- }
114
-
115
- /** The real scene: every hook runs here, unconditionally. */
116
- function DshRemoteSceneBody(props) {
117
- const React = props.React
118
- const ui = props.ui
119
- const channel = props && props.channel
120
- const close = props && props.close
121
-
122
- const { useCallback, useEffect, useRef, useState } = React
123
- const { Box, Text, useInput, useTerminalSize } = ui
124
- const h = React.createElement
125
-
126
- // ── 状态 ──────────────────────────────────────────────────────────────
127
- const [machines, setMachines] = useState([])
128
- const [currentId, setCurrentId] = useState(null)
129
- const [status, setStatus] = useState(null)
130
- const [selected, setSelected] = useState(0)
131
- const [view, setView] = useState('list')
132
- const [menuIndex, setMenuIndex] = useState(0)
133
- const [form, setForm] = useState(null)
134
- const [formField, setFormField] = useState(0)
135
- const [formErrors, setFormErrors] = useState([])
136
- const [browse, setBrowse] = useState(null)
137
- const [confirmMachine, setConfirmMachine] = useState(null)
138
- const [workspaces, setWorkspaces] = useState(null)
139
- const [wsIndex, setWsIndex] = useState(0)
140
- const [wsMachine, setWsMachine] = useState(null)
141
- const [wsConfirm, setWsConfirm] = useState(null)
142
- const [busy, setBusy] = useState('')
143
- const [error, setError] = useState('')
144
- const alive = useRef(true)
145
- const terminal = useTerminalSize()
146
- const columns = Math.max(24, Number(terminal && terminal.columns) || 80)
147
- const rows = Math.max(10, Number(terminal && terminal.rows) || 24)
148
- /** 列表 / 表单 / 浏览共用的内容高度(头部 2 行 + 页脚 2 行)。 */
149
- const bodyHeight = Math.max(4, rows - 6)
150
-
151
- // ── 生命周期:挂载标记 + 首次加载 + 宿主变更订阅 ─────────────────────
152
- useEffect(() => {
153
- alive.current = true
154
- return () => { alive.current = false }
155
- }, [])
156
-
157
- useEffect(() => {
158
- void reload()
159
- // eslint-disable-next-line react-hooks/exhaustive-deps
160
- }, [api])
161
-
162
- useEffect(() => {
163
- if (!api || typeof api.subscribe !== 'function') return undefined
164
- let off
165
- try {
166
- off = api.subscribe(() => { void reload() })
167
- } catch {
168
- off = undefined
169
- }
170
- return () => {
171
- if (typeof off !== 'function') return
172
- try { off() } catch { /* teardown is best-effort */ }
173
- }
174
- // eslint-disable-next-line react-hooks/exhaustive-deps
175
- }, [api])
176
-
177
- // ── 数据加载 ──────────────────────────────────────────────────────────
178
- async function reload() {
179
- if (!api || typeof api.listMachines !== 'function') {
180
- if (alive.current) setError(t('error.noApi'))
181
- return
182
- }
183
- try {
184
- const result = await api.listMachines()
185
- if (!alive.current) return
186
- const list = Array.isArray(result && result.machines) ? result.machines : []
187
- setMachines(list)
188
- setCurrentId(result && result.currentId !== undefined ? result.currentId : null)
189
- setSelected((previous) => Math.min(previous, Math.max(0, list.length - 1)))
190
- let nextStatus
191
- try {
192
- nextStatus = await api.status()
193
- } catch {
194
- nextStatus = undefined
195
- }
196
- if (alive.current && nextStatus) setStatus(nextStatus)
197
- } catch (failure) {
198
- if (alive.current) setError(messageOf(failure))
199
- }
200
- }
201
-
202
- /** Monotonic token: only the newest directory listing may paint. */
203
- const dirToken = useRef(0)
204
- /** Same guard for the workspace-cleanup list. */
205
- const wsToken = useRef(0)
206
- async function loadDir(machine, dirPath) {
207
- if (!api || typeof api.listDir !== 'function' || !machine) return
208
- const token = ++dirToken.current
209
- setBusy(t('busy.listing'))
210
- setError('')
211
- try {
212
- const listing = await api.listDir({ machineId: machine.id, path: dirPath })
213
- if (!alive.current || token !== dirToken.current) return
214
- setBrowse({
215
- machine,
216
- path: String((listing && listing.path) || dirPath || ''),
217
- parent: listing && listing.parent !== undefined ? listing.parent : null,
218
- items: Array.isArray(listing && listing.items) ? listing.items : [],
219
- selected: 0,
220
- })
221
- } catch (failure) {
222
- if (alive.current && token === dirToken.current) setError(messageOf(failure))
223
- } finally {
224
- if (alive.current && token === dirToken.current) setBusy('')
225
- }
226
- }
227
-
228
- /** 统一异步动作包装:设置加载态、把失败写到页脚、卸载后丢弃。 */
229
- const runOp = useCallback(async (what, action) => {
230
- setBusy(what)
231
- setError('')
232
- try {
233
- return await action()
234
- } catch (failure) {
235
- if (alive.current) setError(messageOf(failure))
236
- return undefined
237
- } finally {
238
- if (alive.current) setBusy('')
239
- }
240
- }, [])
241
-
242
- /** 提示:优先用活会话 channel.notify,其次注入的 notify(宿主 toast)。 */
243
- const toast = useCallback((text, options) => {
244
- const message = String(text)
245
- try {
246
- if (channel && typeof channel.notify === 'function') {
247
- channel.notify(message, options)
248
- return
249
- }
250
- } catch { /* fall through to the injected channel */ }
251
- try {
252
- if (typeof notify === 'function') notify(message, options)
253
- } catch { /* notifications are best-effort */ }
254
- }, [channel, notify])
255
-
256
- /** 切换工作区(宿主拒绝 / 异常只提示,不改场景状态)。 */
257
- async function switchWorkspace(target) {
258
- if (!autoSwitch || !target) return
259
- try {
260
- if (!channel || typeof channel.switchWorkspace !== 'function') return
261
- const switched = await channel.switchWorkspace(target)
262
- if (switched === false) toast(t('notify.switchRefused', { label: target.label }), { color: 'warning' })
263
- } catch (failure) {
264
- toast(t('notify.switchFailed', { err: messageOf(failure) }), { color: 'warning' })
265
- }
266
- }
267
-
268
- /** 把 ensure/pick 的结果转成 target,并提示 + 可选切换。 */
269
- async function adoptWorkspace(machine, workspace, remotePath) {
270
- const target = targetFromWorkspace({
271
- machine,
272
- localMirror: workspace && workspace.localMirror,
273
- remotePath: (workspace && workspace.remotePath) || remotePath,
274
- title: workspace && workspace.title,
275
- })
276
- if (!target) {
277
- setError(t('error.badWorkspace'))
278
- return
279
- }
280
- toast(t('notify.workspaceSet', { label: target.label }), { color: 'success' })
281
- await switchWorkspace(target)
282
- }
283
-
284
- // ── 动作 ──────────────────────────────────────────────────────────────
285
- async function connectMachine(machine) {
286
- if (!machine) return
287
- const result = await runOp(t('busy.connecting'), () => api.connect({ machineId: machine.id, persist: true }))
288
- if (!result) return
289
- if (result.connected === false) {
290
- setError(t('notify.probeFailed', { err: result.activeSource || t('error.generic') }))
291
- return
292
- }
293
- toast(t('notify.connected', { target: machineAddress(machine) }), { color: 'success' })
294
- await reload()
295
- }
296
-
297
- /** 在系统文件管理器里打开本机 dsh-remote 的镜像根目录(remote-workspaces)。 */
298
- async function revealMirrorFolder() {
299
- if (typeof api.revealMirrorFolder !== 'function') return
300
- const result = await runOp(t('busy.revealFolder'), () => api.revealMirrorFolder())
301
- if (!result) return
302
- toast(t('notify.revealed', { path: result.path }), { color: 'success' })
303
- }
304
-
305
- async function probeMachine(machine) {
306
- if (!machine || typeof api.probeMachine !== 'function') return
307
- const patch = {
308
- id: machine.id,
309
- host: machine.host,
310
- port: Number(machine.port) || 22,
311
- username: machine.username,
312
- useSshConfig: machine.useSshConfig === true,
313
- privateKeyPath: machine.privateKeyPath || '',
314
- useAgent: machine.useAgent === true,
315
- backend: machine.backend || 'native',
316
- sshBinary: machine.sshBinary || '',
317
- keyboardInteractive: machine.keyboardInteractive === true,
318
- }
319
- const probe = await runOp(t('busy.probing'), () => api.probeMachine(patch))
320
- if (!probe) return
321
- if (probe.ok === false) {
322
- const message = probe.error || t('error.generic')
323
- setError(messageOf(message))
324
- toast(t('notify.probeFailed', { err: messageOf(message) }), { color: 'error' })
325
- return
326
- }
327
- const target = `${probe.user || machine.username || ''}@${probe.host || machine.host || ''}`
328
- const latency = typeof probe.latencyMs === 'number' ? Math.round(probe.latencyMs) : '-'
329
- toast(t('notify.probeOk', { target, latency }), { color: 'success' })
330
- }
331
-
332
- async function deleteMachine(machine) {
333
- if (!machine || typeof api.removeMachine !== 'function') return
334
- const result = await runOp(t('busy.deleting'), () => api.removeMachine(machine.id))
335
- if (!result || !alive.current) return
336
- toast(t('notify.deleted', { name: machineName(machine) }), { color: 'success' })
337
- setView('list')
338
- await reload()
339
- }
340
-
341
- async function pickBrowseWorkspace() {
342
- const current = browse
343
- if (!current) return
344
- if (!current.path) {
345
- toast(t('browse.noSelection'), { color: 'warning' })
346
- return
347
- }
348
- setBusy(t('busy.settingWorkspace'))
349
- setError('')
350
- try {
351
- const workspace = await api.pickRemoteWorkspace({
352
- machineId: current.machine.id,
353
- remotePath: current.path,
354
- registerWorkspace: true,
355
- })
356
- if (!alive.current) return
357
- await adoptWorkspace(current.machine, workspace, current.path)
358
- } catch (failure) {
359
- if (alive.current) {
360
- setError(messageOf(failure))
361
- toast(t('notify.pickFailed', { err: messageOf(failure) }), { color: 'warning' })
362
- }
363
- } finally {
364
- if (alive.current) setBusy('')
365
- }
366
- }
367
-
368
- async function saveForm() {
369
- if (!form) return
370
- const { errors, patch } = validateMachineForm(form, t)
371
- if (errors.length) {
372
- setFormErrors(errors)
373
- return
374
- }
375
- setFormErrors([])
376
- const result = await runOp(t('busy.saving'), () => api.upsertMachine(patch))
377
- if (!result || !alive.current) return
378
- const name = (result.machine && result.machine.name) || patch.name || patch.host
379
- toast(t('notify.saved', { name }), { color: 'success' })
380
- if (Array.isArray(result.warnings) && result.warnings.length) {
381
- toast(t('notify.warnings', { text: result.warnings.join('; ') }), { color: 'warning', timeoutMs: 8000 })
382
- }
383
- setView('list')
384
- await reload()
385
- }
386
-
387
- // ── 视图切换 ──────────────────────────────────────────────────────────
388
- const backToList = () => {
389
- setView('list')
390
- setFormErrors([])
391
- setError('')
392
- }
393
-
394
- function openMenu(machine) {
395
- if (!machine) return
396
- setMenuIndex(0)
397
- setView('menu')
398
- }
399
-
400
- function openForm(machine) {
401
- setForm(machine ? formFromMachine(machine) : emptyMachineForm())
402
- setFormField(0)
403
- setFormErrors([])
404
- setError('')
405
- setView('form')
406
- }
407
-
408
- function openBrowse(machine) {
409
- if (!machine) return
410
- setBrowse({ machine, path: '', parent: null, items: [], selected: 0 })
411
- setError('')
412
- setView('browse')
413
- // Start at the machine's recorded remote workspace when there is one,
414
- // instead of whatever the host considers its current directory.
415
- void loadDir(machine, machine.workspace || undefined)
416
- }
417
-
418
- // ── 工作区清理(删除镜像 / 删除对话 / 移出最近列表) ──────────────────
419
- function selectedWorkspace() {
420
- const list = workspaces || []
421
- if (!list.length) return undefined
422
- return list[Math.max(0, Math.min(wsIndex, list.length - 1))]
423
- }
424
-
425
- async function loadWorkspaces(machine) {
426
- if (!api || typeof api.listWorkspaceMirrors !== 'function') {
427
- setError(t('ws.noApi'))
428
- return
429
- }
430
- if (!machine) return
431
- const token = ++wsToken.current
432
- setBusy(t('busy.loadingMirrors'))
433
- setError('')
434
- try {
435
- const list = await api.listWorkspaceMirrors({ machineId: machine.id })
436
- if (!alive.current || token !== wsToken.current) return
437
- const items = Array.isArray(list) ? list : []
438
- setWorkspaces(items)
439
- setWsIndex((previous) => Math.min(previous, Math.max(0, items.length - 1)))
440
- } catch (failure) {
441
- if (alive.current && token === wsToken.current) setError(messageOf(failure))
442
- } finally {
443
- if (alive.current && token === wsToken.current) setBusy('')
444
- }
445
- }
446
-
447
- function openWorkspaces(machine) {
448
- if (!machine) return
449
- setWsMachine(machine)
450
- setWorkspaces(null)
451
- setWsIndex(0)
452
- setWsConfirm(null)
453
- setError('')
454
- setView('workspaces')
455
- void loadWorkspaces(machine)
456
- }
457
-
458
- function openWsConfirm(action) {
459
- const item = selectedWorkspace()
460
- if (!item) {
461
- toast(t('ws.empty'), { color: 'warning' })
462
- return
463
- }
464
- setWsConfirm({ action, item })
465
- setError('')
466
- setView('wsconfirm')
467
- }
468
-
469
- async function runWsConfirm() {
470
- const pending = wsConfirm
471
- if (!pending) return
472
- const { action, item } = pending
473
- const label = item.title || basenameRemote(item.remotePath)
474
- const what = action === 'delete' ? t('ws.busyDelete')
475
- : action === 'sessions' ? t('ws.busySessions') : t('ws.busyRecent')
476
- setBusy(what)
477
- setError('')
478
- try {
479
- if (action === 'delete') {
480
- if (typeof api.deleteRemoteWorkspace !== 'function') throw new Error(t('ws.noApi'))
481
- const result = await api.deleteRemoteWorkspace({ localMirror: item.localMirror, deleteSessions: true })
482
- if (!alive.current) return
483
- toast(t('ws.deleted', { name: label, sessions: String(Number(result && result.removedSessions) || 0) }), { color: 'success' })
484
- } else if (action === 'sessions') {
485
- if (typeof api.deleteWorkspaceSessions !== 'function') throw new Error(t('ws.noApi'))
486
- const result = await api.deleteWorkspaceSessions({ localMirror: item.localMirror })
487
- if (!alive.current) return
488
- const removed = Number(result && result.removedSessions) || 0
489
- const skipped = Array.isArray(result && result.skippedLiveSessions) ? result.skippedLiveSessions.length : 0
490
- toast(skipped
491
- ? t('ws.sessionsPartial', { n: String(removed), live: String(skipped) })
492
- : t('ws.sessionsDeleted', { n: String(removed) }), { color: skipped ? 'warning' : 'success' })
493
- } else {
494
- if (typeof api.forgetWorkspaceRecent !== 'function') throw new Error(t('ws.noApi'))
495
- await api.forgetWorkspaceRecent({ localMirror: item.localMirror })
496
- if (!alive.current) return
497
- toast(t('ws.recentForgotten', { name: label }), { color: 'success' })
498
- }
499
- if (!alive.current) return
500
- setWsConfirm(null)
501
- setView('workspaces')
502
- await loadWorkspaces(wsMachine)
503
- } catch (failure) {
504
- if (!alive.current) return
505
- // A refused deletion is not a dead end: return to the list (the footer
506
- // explains what must stop) so the person can retry after Ctrl+X.
507
- setWsConfirm(null)
508
- setView('workspaces')
509
- const live = failure && Array.isArray(failure.liveSessions) ? failure.liveSessions.length : 0
510
- setError(live ? t('ws.busyError', { n: String(live) }) : messageOf(failure))
511
- } finally {
512
- if (alive.current) setBusy('')
513
- }
514
- }
515
-
516
- function openConfirm(machine) {
517
- if (!machine) return
518
- setConfirmMachine(machine)
519
- setView('confirm')
520
- }
521
-
522
- /** 执行动作菜单 / 快捷键对应的动作。 */
523
- function executeAction(action, machine) {
524
- if (!machine) return
525
- switch (action) {
526
- case 'connect': void connectMachine(machine); break
527
- case 'workspaces': openWorkspaces(machine); break
528
- case 'edit': openForm(machine); break
529
- case 'delete': openConfirm(machine); break
530
- case 'probe': void probeMachine(machine); break
531
- case 'browse': openBrowse(machine); break
532
- default: break
533
- }
534
- }
535
-
536
- // ── 键盘 ──────────────────────────────────────────────────────────────
537
- const selectedMachine = machines.length
538
- ? machines[Math.max(0, Math.min(selected, machines.length - 1))]
539
- : undefined
540
-
541
- function handleListKey(input, key) {
542
- // Escape FIRST: a lone Esc carries `meta: true` in this TUI, so any
543
- // modifier guard before it swallows every Esc press.
544
- if (key.escape || input === 'q') {
545
- if (typeof close === 'function') close()
546
- return
547
- }
548
- if (key.ctrl || key.meta) return
549
- if (key.leftArrow) {
550
- if (typeof close === 'function') close()
551
- return
552
- }
553
- if (key.rightArrow) {
554
- openMenu(selectedMachine)
555
- return
556
- }
557
- if (key.upArrow || input === 'k') {
558
- setSelected((previous) => Math.max(0, previous - 1))
559
- return
560
- }
561
- if (key.downArrow || input === 'j') {
562
- setSelected((previous) => Math.min(Math.max(0, machines.length - 1), previous + 1))
563
- return
564
- }
565
- if (key.return) {
566
- openMenu(selectedMachine)
567
- return
568
- }
569
- switch (input) {
570
- case 'a': openForm(undefined); break
571
- case 'c': void connectMachine(selectedMachine); break
572
- case 'e': openForm(selectedMachine); break
573
- case 'd': openConfirm(selectedMachine); break
574
- case 't': void probeMachine(selectedMachine); break
575
- case 'b': openBrowse(selectedMachine); break
576
- case 'o': void revealMirrorFolder(); break
577
- default: break
578
- }
579
- }
580
-
581
- function handleMenuKey(input, key) {
582
- if (key.escape || input === 'q' || key.leftArrow) {
583
- backToList()
584
- return
585
- }
586
- if (key.ctrl || key.meta) return
587
- if (key.upArrow || input === 'k') {
588
- setMenuIndex((previous) => Math.max(0, previous - 1))
589
- return
590
- }
591
- if (key.downArrow || input === 'j') {
592
- setMenuIndex((previous) => Math.min(MENU_ACTIONS.length - 1, previous + 1))
593
- return
594
- }
595
- if (key.return || key.rightArrow) {
596
- const action = MENU_ACTIONS[Math.max(0, Math.min(menuIndex, MENU_ACTIONS.length - 1))]
597
- executeAction(action, selectedMachine)
598
- return
599
- }
600
- if (input === 'c') executeAction('connect', selectedMachine)
601
- else if (input === 'e') executeAction('edit', selectedMachine)
602
- else if (input === 'd') executeAction('delete', selectedMachine)
603
- else if (input === 't') executeAction('probe', selectedMachine)
604
- else if (input === 'b') executeAction('browse', selectedMachine)
605
- else if (input === 'm') executeAction('workspaces', selectedMachine)
606
- }
607
-
608
- function handleConfirmKey(input, key) {
609
- if (key.escape || input === 'n' || input === 'q' || key.leftArrow) {
610
- backToList()
611
- return
612
- }
613
- if (key.ctrl || key.meta) return
614
- if (key.return || key.rightArrow || input === 'y') {
615
- const target = confirmMachine
616
- setConfirmMachine(null)
617
- void deleteMachine(target)
618
- }
619
- }
620
-
621
- function handleFormKey(input, key) {
622
- if (!form) {
623
- backToList()
624
- return
625
- }
626
- const fields = fieldsFor(form)
627
- const bounded = Math.max(0, Math.min(formField, fields.length - 1))
628
- if (key.escape) {
629
- backToList()
630
- return
631
- }
632
- if (key.ctrl || key.meta) return
633
- if (key.tab) {
634
- const next = key.shift ? bounded - 1 : bounded + 1
635
- setFormField(Math.max(0, Math.min(fields.length - 1, next)))
636
- return
637
- }
638
- if (key.upArrow) {
639
- setFormField(Math.max(0, bounded - 1))
640
- return
641
- }
642
- if (key.downArrow) {
643
- setFormField(Math.min(fields.length - 1, bounded + 1))
644
- return
645
- }
646
- if (key.return) {
647
- void saveForm()
648
- return
649
- }
650
- const field = fields[bounded]
651
- if (!field) return
652
- if (field === 'useSshConfig') {
653
- if (input === ' ' || key.leftArrow || key.rightArrow) {
654
- setForm((previous) => ({ ...previous, useSshConfig: !(previous && previous.useSshConfig) }))
655
- }
656
- return
657
- }
658
- if (field === 'auth') {
659
- if (input === ' ' || key.leftArrow || key.rightArrow) {
660
- const auth = nextAuth(form.auth, key.leftArrow ? -1 : 1)
661
- setForm({ ...form, auth })
662
- setFormField((index) => Math.min(index, fieldsFor({ auth }).length - 1))
663
- }
664
- return
665
- }
666
- if (key.backspace || key.delete) {
667
- setForm((previous) => {
668
- const value = String((previous && previous[field]) || '')
669
- return { ...previous, [field]: value.slice(0, -1) }
670
- })
671
- return
672
- }
673
- if (!input || /[\u0000-\u001f\u007f]/.test(input)) return
674
- const chunk = input.replace(/[\r\n]+/g, '')
675
- if (!chunk) return
676
- setForm((previous) => {
677
- const value = String((previous && previous[field]) || '') + chunk
678
- const next = field === 'port' ? value.replace(/[^\d]/g, '').slice(0, 5) : value
679
- return { ...previous, [field]: next }
680
- })
681
- }
682
-
683
- function handleBrowseKey(input, key) {
684
- if (key.escape || input === 'q') {
685
- backToList()
686
- return
687
- }
688
- if (key.ctrl || key.meta) return
689
- const current = browse
690
- const dirs = current ? current.items.filter((item) => item && item.type === 'dir') : []
691
- const bounded = current ? Math.max(0, Math.min(current.selected, dirs.length - 1)) : 0
692
- if (key.upArrow || input === 'k') {
693
- setBrowse((previous) => previous
694
- ? { ...previous, selected: Math.max(0, Math.min(previous.selected, dirs.length - 1) - 1) }
695
- : previous)
696
- return
697
- }
698
- if (key.downArrow || input === 'j') {
699
- setBrowse((previous) => previous
700
- ? { ...previous, selected: Math.min(Math.max(0, dirs.length - 1), previous.selected + 1) }
701
- : previous)
702
- return
703
- }
704
- if (key.return || key.rightArrow) {
705
- const dir = dirs[bounded]
706
- if (dir && current) void loadDir(current.machine, dir.path)
707
- else toast(t('browse.noSelection'), { color: 'warning' })
708
- return
709
- }
710
- if (key.leftArrow || key.backspace || key.delete) {
711
- // ← = one DIRECTORY level up (same as Backspace); at the root it leaves
712
- // the browse view instead of doing nothing.
713
- if (current && current.parent) void loadDir(current.machine, current.parent)
714
- else backToList()
715
- return
716
- }
717
- if (input === 'w') void pickBrowseWorkspace()
718
- }
719
-
720
- function handleWorkspacesKey(input, key) {
721
- if (key.escape || input === 'q' || key.leftArrow) {
722
- backToList()
723
- return
724
- }
725
- if (key.ctrl || key.meta) return
726
- const list = workspaces || []
727
- if (key.upArrow || input === 'k') {
728
- setWsIndex((previous) => Math.max(0, previous - 1))
729
- return
730
- }
731
- if (key.downArrow || input === 'j') {
732
- setWsIndex((previous) => Math.min(Math.max(0, list.length - 1), previous + 1))
733
- return
734
- }
735
- if (input === 'd') { openWsConfirm('delete'); return }
736
- if (input === 'x') { openWsConfirm('sessions'); return }
737
- if (input === 'r') { openWsConfirm('recent'); return }
738
- }
739
-
740
- function handleWsConfirmKey(input, key) {
741
- if (key.escape || input === 'n' || input === 'q' || key.leftArrow) {
742
- setWsConfirm(null)
743
- setView('workspaces')
744
- return
745
- }
746
- if (key.ctrl || key.meta) return
747
- if (key.return || key.rightArrow || input === 'y') void runWsConfirm()
748
- }
749
-
750
- useInput((input, key) => {
751
- const pressed = key || {}
752
- if (view === 'list') handleListKey(input, pressed)
753
- else if (view === 'menu') handleMenuKey(input, pressed)
754
- else if (view === 'form') handleFormKey(input, pressed)
755
- else if (view === 'browse') handleBrowseKey(input, pressed)
756
- else if (view === 'workspaces') handleWorkspacesKey(input, pressed)
757
- else if (view === 'wsconfirm') handleWsConfirmKey(input, pressed)
758
- else if (view === 'confirm') handleConfirmKey(input, pressed)
759
- })
760
-
761
- // ── 渲染 ──────────────────────────────────────────────────────────────
762
- function renderHeader() {
763
- const connected = status && status.connected === true
764
- return h(Box, { key: 'header', flexDirection: 'row', width: '100%', paddingX: 1 },
765
- h(Text, { bold: true, color: 'accent' }, t('title')),
766
- h(Box, { flexGrow: 1 }),
767
- h(Text, { color: connected ? 'success' : 'subtle' }, status ? statusLine(status, t) : t('status.loading')),
768
- )
769
- }
770
-
771
- function renderList() {
772
- const children = []
773
- if (!machines.length) {
774
- children.push(h(Text, { key: 'empty', color: 'subtle' }, t('list.empty')))
775
- } else {
776
- const slicing = windowSlice(machines, selected, bodyHeight - 1)
777
- slicing.items.forEach((machine, index) => {
778
- const absolute = slicing.offset + index
779
- const focused = absolute === selected
780
- const current = machine.id === currentId
781
- children.push(h(Box, { key: machine.id || `machine-${absolute}`, flexDirection: 'row', width: '100%' },
782
- h(Text, { color: focused ? 'accent' : undefined, inverse: focused }, focused ? '› ' : ' '),
783
- h(Text, { color: current ? 'success' : 'subtle' }, current ? '● ' : '○ '),
784
- h(Text, { bold: focused || current }, clip(machineName(machine), Math.max(8, Math.floor(columns * 0.32)))),
785
- h(Text, { dimColor: true }, clip(` ${machineAddress(machine)}`, Math.max(10, Math.floor(columns * 0.3)))),
786
- machine.group ? h(Text, { color: 'subtle' }, clip(` [${machine.group}]`, 16)) : null,
787
- machine.useSshConfig ? h(Text, { color: 'subtle' }, ' ssh-config') : null,
788
- h(Box, { flexGrow: 1 }),
789
- h(Text, { color: 'subtle' }, machine.workspace ? clip(basenameRemote(machine.workspace), 18) : ''),
790
- ))
791
- })
792
- }
793
- return h(Box, { key: 'body', flexDirection: 'column', width: '100%', paddingX: 1 }, ...children)
794
- }
795
-
796
- function renderMenu() {
797
- const machine = selectedMachine
798
- if (!machine) return h(Box, { key: 'body', flexDirection: 'column', width: '100%', paddingX: 1 },
799
- h(Text, { color: 'subtle' }, t('list.empty')))
800
- const children = [
801
- h(Text, { key: 'title', bold: true, color: 'accent' }, t('menu.title', { name: machineName(machine) })),
802
- h(Text, { key: 'addr', color: 'subtle' }, `${machineAddress(machine)}${machine.workspace ? ' · ' + clip(machine.workspace, 48) : ''}`),
803
- ]
804
- MENU_ACTIONS.forEach((action, index) => {
805
- const focused = index === menuIndex
806
- children.push(h(Text, { key: action, color: focused ? 'accent' : undefined, inverse: focused },
807
- `${focused ? '› ' : ' '}${index + 1}. ${t('menu.' + action)}`))
808
- })
809
- return h(Box, { key: 'body', flexDirection: 'column', width: '100%', paddingX: 1 }, ...children)
810
- }
811
-
812
- function formValueText(field) {
813
- if (!form) return ''
814
- if (field === 'useSshConfig') return form.useSshConfig ? '[x]' : '[ ]'
815
- if (field === 'auth') return `◂ ${t('auth.' + form.auth)} ▸`
816
- if (field === 'password') {
817
- const masked = maskValue(form.password)
818
- if (masked) return masked
819
- return form.id ? t('form.passwordUnchanged') : t('form.passwordPlaceholder')
820
- }
821
- if (field === 'passphrase') {
822
- const masked = maskValue(form.passphrase)
823
- if (masked) return masked
824
- return form.id ? t('form.passwordUnchanged') : t('form.passphrasePlaceholder')
825
- }
826
- if (field === 'privateKeyPath') return String(form.privateKeyPath || '') || t('form.optional')
827
- return String(form[field] === undefined || form[field] === null ? '' : form[field])
828
- }
829
-
830
- function renderForm() {
831
- if (!form) return h(Box, { key: 'body', flexDirection: 'column', width: '100%', paddingX: 1 })
832
- const fields = fieldsFor(form)
833
- const bounded = Math.max(0, Math.min(formField, fields.length - 1))
834
- const children = [
835
- h(Text, { key: 'title', bold: true, color: 'accent' },
836
- form.id ? t('form.titleEdit', { name: machineName(form) || form.host }) : t('form.titleNew')),
837
- ]
838
- const slicing = windowSlice(fields, bounded, bodyHeight - 2)
839
- slicing.items.forEach((field, index) => {
840
- const absolute = slicing.offset + index
841
- const focused = absolute === bounded
842
- const label = t('form.' + field)
843
- const value = formValueText(field)
844
- children.push(h(Box, { key: field, flexDirection: 'row', width: '100%' },
845
- h(Text, { color: focused ? 'accent' : 'subtle', bold: focused }, `${focused ? '› ' : ' '}${label}: `),
846
- h(Text, { inverse: focused, color: focused ? 'accent' : undefined },
847
- clip(value + (focused && field !== 'useSshConfig' && field !== 'auth' ? '▌' : ''), Math.max(8, columns - 18))),
848
- ))
849
- })
850
- return h(Box, { key: 'body', flexDirection: 'column', width: '100%', paddingX: 1 }, ...children)
851
- }
852
-
853
- function renderBrowse() {
854
- const current = browse
855
- if (!current) {
856
- return h(Box, { key: 'body', flexDirection: 'column', width: '100%', paddingX: 1 },
857
- h(Text, { color: 'subtle' }, t('browse.loading')))
858
- }
859
- const dirs = current.items.filter((item) => item && item.type === 'dir')
860
- const files = current.items.filter((item) => item && item.type !== 'dir')
861
- const combined = [...dirs, ...files]
862
- const selection = dirs.length ? Math.max(0, Math.min(current.selected, dirs.length - 1)) : 0
863
- const children = [
864
- h(Text, { key: 'title', bold: true, color: 'accent' }, t('browse.title', { path: clip(current.path || '/', Math.max(8, columns - 20)) })),
865
- h(Text, { key: 'machine', color: 'subtle' }, `${machineName(current.machine)} · ${machineAddress(current.machine)}`),
866
- ]
867
- if (!combined.length) {
868
- children.push(h(Text, { key: 'empty', color: 'subtle' }, busy ? t('browse.loading') : t('browse.empty')))
869
- } else {
870
- const slicing = windowSlice(combined, selection, Math.max(1, bodyHeight - 3))
871
- slicing.items.forEach((item, index) => {
872
- const absolute = slicing.offset + index
873
- const isDir = item.type === 'dir'
874
- const focused = isDir && absolute === selection
875
- const icon = isDir ? '▸' : '·'
876
- const suffix = isDir ? '/' : ''
877
- children.push(h(Text, {
878
- key: `${item.path || item.name || index}`,
879
- color: focused ? 'accent' : isDir ? undefined : 'subtle',
880
- dimColor: !isDir,
881
- inverse: focused,
882
- }, `${focused ? '› ' : ' '}${icon} ${clip(String(item.name || ''), Math.max(8, columns - 8))}${suffix}`))
883
- })
884
- }
885
- return h(Box, { key: 'body', flexDirection: 'column', width: '100%', paddingX: 1 }, ...children)
886
- }
887
-
888
- function renderConfirm() {
889
- const machine = confirmMachine
890
- const children = [
891
- h(Text, { key: 'title', bold: true, color: 'warning' }, t('confirm.deleteTitle')),
892
- h(Text, { key: 'message' }, t('confirm.delete', { name: machineName(machine) })),
893
- h(Text, { key: 'addr', color: 'subtle' }, machineAddress(machine)),
894
- ]
895
- return h(Box, { key: 'body', flexDirection: 'column', width: '100%', paddingX: 1 }, ...children)
896
- }
897
-
898
- function renderWorkspaces() {
899
- const machine = wsMachine
900
- const list = workspaces || []
901
- const children = [
902
- h(Text, { key: 'title', bold: true, color: 'accent' }, t('ws.title', { name: machine ? machineName(machine) : '' })),
903
- h(Text, { key: 'addr', color: 'subtle' }, machine ? machineAddress(machine) : ''),
904
- ]
905
- if (workspaces === null) {
906
- children.push(h(Text, { key: 'loading', color: 'subtle' }, busy || t('busy.loading')))
907
- } else if (!list.length) {
908
- children.push(h(Text, { key: 'empty', color: 'subtle' }, t('ws.empty')))
909
- } else {
910
- const slicing = windowSlice(list, Math.max(0, Math.min(wsIndex, list.length - 1)), Math.max(2, Math.floor((bodyHeight - 2) / 2)))
911
- slicing.items.forEach((item, index) => {
912
- const absolute = slicing.offset + index
913
- const focused = absolute === wsIndex
914
- const tags = []
915
- if (item.registered) tags.push(t('ws.registered'))
916
- if (item.recent) tags.push(t('ws.recent'))
917
- const live = Number(item.liveSessionCount) || 0
918
- children.push(h(Box, { key: `ws-${item.localMirror || absolute}`, flexDirection: 'row', width: '100%' },
919
- h(Text, { color: focused ? 'accent' : undefined, inverse: focused }, focused ? '› ' : ' '),
920
- h(Text, { bold: focused }, clip(item.title || basenameRemote(item.remotePath), Math.max(12, Math.floor(columns * 0.34)))),
921
- h(Text, { color: 'subtle' }, ` ${t('ws.sessions', { n: String(Number(item.sessionCount) || 0) })}`),
922
- live ? h(Text, { color: 'warning' }, ` ${t('ws.live', { n: String(live) })}`) : null,
923
- h(Text, { dimColor: true }, ` ${t('ws.size', { size: formatBytes(item.mirrorBytes) })}`),
924
- tags.length ? h(Text, { color: 'subtle' }, ` [${tags.join(' · ')}]`) : null,
925
- ))
926
- children.push(h(Text, { key: `ws-path-${item.localMirror || absolute}`, color: 'subtle', dimColor: true },
927
- clip(` ${item.username ? item.username + '@' : ''}${item.host}:${item.remotePath}`, Math.max(20, columns - 3))))
928
- })
929
- }
930
- return h(Box, { key: 'body', flexDirection: 'column', width: '100%', paddingX: 1 }, ...children)
931
- }
932
-
933
- function renderWsConfirm() {
934
- const pending = wsConfirm
935
- const item = pending && pending.item
936
- const action = pending && pending.action
937
- const titleKey = action === 'delete' ? 'ws.confirmTitleDelete'
938
- : action === 'sessions' ? 'ws.confirmTitleSessions' : 'ws.confirmTitleRecent'
939
- const bodyKey = action === 'delete' ? 'ws.confirmDelete'
940
- : action === 'sessions' ? 'ws.confirmSessions' : 'ws.confirmRecent'
941
- const name = item ? (item.title || basenameRemote(item.remotePath)) : ''
942
- const sessions = item ? Number(item.sessionCount) || 0 : 0
943
- return h(Box, { key: 'body', flexDirection: 'column', width: '100%', paddingX: 1 },
944
- h(Text, { key: 'title', bold: true, color: 'warning' }, t(titleKey, { name })),
945
- h(Text, { key: 'message' }, clip(t(bodyKey, { n: String(sessions), name }), Math.max(20, columns - 4))),
946
- h(Text, { key: 'path', color: 'subtle' }, clip(item ? `${item.username ? item.username + '@' : ''}${item.host}:${item.remotePath}` : '', Math.max(20, columns - 4))),
947
- h(Text, { key: 'mirror', color: 'subtle' }, clip(item ? item.localMirror : '', Math.max(20, columns - 4))),
948
- )
949
- }
950
-
951
- function hintForView() {
952
- if (view === 'menu') return t('menu.hints')
953
- if (view === 'form') return t('form.hints')
954
- if (view === 'browse') return t('browse.hints')
955
- if (view === 'workspaces') return t('ws.hints')
956
- if (view === 'wsconfirm') return t('ws.confirmHints')
957
- if (view === 'confirm') return t('confirm.hints')
958
- return t('list.hints')
959
- }
960
-
961
- function renderFooter() {
962
- const children = []
963
- if (busy) children.push(h(Text, { key: 'busy', color: 'accent' }, t('busy.line', { what: busy })))
964
- const failure = view === 'form' && formErrors.length ? formErrors.join(' · ') : error
965
- if (failure) children.push(h(Text, { key: 'error', color: 'error' }, t('footer.error', { err: failure })))
966
- children.push(h(Text, { key: 'hint', color: 'subtle' }, clip(hintForView(), Math.max(20, columns - 2))))
967
- return h(Box, { key: 'footer', flexDirection: 'column', width: '100%', paddingX: 1 }, ...children)
968
- }
969
-
970
- function renderBody() {
971
- if (view === 'menu') return renderMenu()
972
- if (view === 'form') return renderForm()
973
- if (view === 'browse') return renderBrowse()
974
- if (view === 'workspaces') return renderWorkspaces()
975
- if (view === 'wsconfirm') return renderWsConfirm()
976
- if (view === 'confirm') return renderConfirm()
977
- return renderList()
978
- }
979
-
980
- return h(Box, { flexDirection: 'column', width: '100%', flexGrow: 1, paddingY: 0 },
981
- renderHeader(),
982
- renderBody(),
983
- renderFooter(),
984
- )
985
- }
986
- }
1
+ // dsh-remote TUI — `/dsh-remote` 全屏「远程服务器」管理页。
2
+ //
3
+ // 硬约束(dsh-tui 场景契约,见 dsh-adapter/scenes.d.ts):
4
+ // · hooks 只能用 props 注入的 React;元素只能 React.createElement(仓库没有
5
+ // JSX 编译器,也没有构建步骤)
6
+ // · 渲染期禁止同步 I/O / 网络:机器列表、状态、目录全部在 useEffect 或按键
7
+ // 回调里异步取;组件卸载后(alive ref = false)丢弃结果
8
+ // · 密码 / passphrase 永不回显:编辑时输入框恒为空,留空 = 不修改
9
+ //
10
+ // 视图状态机:list → menu / form / browse / confirm。
11
+ // Esc / q:子视图先回列表,列表根视图关闭场景。
12
+
13
+ import {
14
+ AUTH_MODES,
15
+ basenameRemote,
16
+ emptyMachineForm,
17
+ formatBytes,
18
+ formFromMachine,
19
+ statusLine,
20
+ targetFromWorkspace,
21
+ validateMachineForm,
22
+ } from './format.js'
23
+
24
+ /** 动作菜单项(顺序即渲染顺序)。 */
25
+ const MENU_ACTIONS = ['connect', 'workspaces', 'edit', 'delete', 'probe', 'browse']
26
+ /** 表单里永远出现的字段。 */
27
+ const BASE_FORM_FIELDS = ['name', 'host', 'useSshConfig', 'port', 'username', 'auth']
28
+
29
+ /** 取错误对象里面向用户的一句话。 */
30
+ function messageOf(error) {
31
+ if (!error) return ''
32
+ return String((error && error.message) || error)
33
+ }
34
+
35
+ /** 按**码点**截断(不是 UTF-16 码元),避免切出孤立代理对(emoji、CJK 扩展 B)。 */
36
+ function clip(text, max) {
37
+ const value = String(text === undefined || text === null ? '' : text)
38
+ const limit = Math.max(0, Number(max) || 0)
39
+ if (!limit) return value
40
+ const points = Array.from(value)
41
+ if (points.length <= limit) return value
42
+ return points.slice(0, Math.max(0, limit - 1)).join('') + '…'
43
+ }
44
+
45
+ /** 掩码显示:只体现“有值”,永远不回显内容本身。 */
46
+ function maskValue(value) {
47
+ const length = String(value === undefined || value === null ? '' : value).length
48
+ return length ? '•'.repeat(Math.min(length, 20)) : ''
49
+ }
50
+
51
+ /** 机器显示名:name → host → id。 */
52
+ function machineName(machine) {
53
+ if (!machine) return ''
54
+ const name = String(machine.name || '').trim()
55
+ return name || String(machine.host || machine.id || '')
56
+ }
57
+
58
+ /** `user@host:port` 单行身份。 */
59
+ function machineAddress(machine) {
60
+ if (!machine) return ''
61
+ const host = String(machine.host || '')
62
+ const user = String(machine.username || '')
63
+ const port = Number(machine.port) || 22
64
+ return `${user ? user + '@' : ''}${host}:${port}`
65
+ }
66
+
67
+ /** 认证方式循环切换。 */
68
+ function nextAuth(current, step) {
69
+ const index = Math.max(0, AUTH_MODES.indexOf(current))
70
+ const next = (index + (step || 1) + AUTH_MODES.length) % AUTH_MODES.length
71
+ return AUTH_MODES[next]
72
+ }
73
+
74
+ /** 表单可见字段(认证方式决定密码 / 私钥组是否出现)。 */
75
+ function fieldsFor(form) {
76
+ const fields = [...BASE_FORM_FIELDS]
77
+ if (!form || form.auth === 'password') fields.push('password')
78
+ else if (form.auth === 'key') fields.push('privateKeyPath', 'passphrase')
79
+ fields.push('group')
80
+ return fields
81
+ }
82
+
83
+ /** 以 selected 为中心切出可视窗口(只用状态派生,不存滚动偏移)。 */
84
+ function windowSlice(items, selected, height) {
85
+ const list = Array.isArray(items) ? items : []
86
+ const size = Math.max(1, Number(height) || 1)
87
+ if (list.length <= size) return { offset: 0, items: list }
88
+ let offset = Math.max(0, Math.min(Number(selected) || 0, list.length - 1) - Math.floor(size / 2))
89
+ offset = Math.min(offset, list.length - size)
90
+ return { offset, items: list.slice(offset, offset + size) }
91
+ }
92
+
93
+ /**
94
+ * 创建全屏场景组件。
95
+ *
96
+ * @param {object} deps
97
+ * @param {object} deps.api - 宿主进程内 API(apiVersion 1)。
98
+ * @param {object} [deps.config] - 行 config(tuiAutoSwitchWorkspace 等)。
99
+ * @param {object} [deps.i18n] - createI18n 的返回值。
100
+ * @param {(text: string, options?: object) => void} [deps.notify] - 无 channel 时的提示通道。
101
+ * @returns {Function} React 组件(props: { React, ui, channel, close })。
102
+ */
103
+ export function createSceneComponent({ api, config, i18n, notify } = {}) {
104
+ const t = i18n && typeof i18n.t === 'function' ? i18n.t : (key) => String(key)
105
+ const autoSwitch = !config || config.tuiAutoSwitchWorkspace !== false
106
+
107
+ /** Host kit is mandatory; the guard lives OUTSIDE the hooking component so the
108
+ * hook count never depends on props (React requires a constant hook order). */
109
+ return function DshRemoteScene(props) {
110
+ const React = props && props.React
111
+ if (!React || !props.ui) return null
112
+ return React.createElement(DshRemoteSceneBody, props)
113
+ }
114
+
115
+ /** The real scene: every hook runs here, unconditionally. */
116
+ function DshRemoteSceneBody(props) {
117
+ const React = props.React
118
+ const ui = props.ui
119
+ const channel = props && props.channel
120
+ const close = props && props.close
121
+
122
+ const { useCallback, useEffect, useRef, useState } = React
123
+ const { Box, Text, useInput, useTerminalSize } = ui
124
+ const h = React.createElement
125
+
126
+ // ── 状态 ──────────────────────────────────────────────────────────────
127
+ const [machines, setMachines] = useState([])
128
+ const [currentId, setCurrentId] = useState(null)
129
+ const [status, setStatus] = useState(null)
130
+ const [selected, setSelected] = useState(0)
131
+ const [view, setView] = useState('list')
132
+ const [menuIndex, setMenuIndex] = useState(0)
133
+ const [form, setForm] = useState(null)
134
+ const [formField, setFormField] = useState(0)
135
+ const [formErrors, setFormErrors] = useState([])
136
+ const [browse, setBrowse] = useState(null)
137
+ const [confirmMachine, setConfirmMachine] = useState(null)
138
+ const [workspaces, setWorkspaces] = useState(null)
139
+ const [wsIndex, setWsIndex] = useState(0)
140
+ const [wsMachine, setWsMachine] = useState(null)
141
+ const [wsConfirm, setWsConfirm] = useState(null)
142
+ const [busy, setBusy] = useState('')
143
+ const [error, setError] = useState('')
144
+ const alive = useRef(true)
145
+ const terminal = useTerminalSize()
146
+ const columns = Math.max(24, Number(terminal && terminal.columns) || 80)
147
+ const rows = Math.max(10, Number(terminal && terminal.rows) || 24)
148
+ /** 列表 / 表单 / 浏览共用的内容高度(头部 2 行 + 页脚 2 行)。 */
149
+ const bodyHeight = Math.max(4, rows - 6)
150
+
151
+ // ── 生命周期:挂载标记 + 首次加载 + 宿主变更订阅 ─────────────────────
152
+ useEffect(() => {
153
+ alive.current = true
154
+ return () => { alive.current = false }
155
+ }, [])
156
+
157
+ useEffect(() => {
158
+ void reload()
159
+ // eslint-disable-next-line react-hooks/exhaustive-deps
160
+ }, [api])
161
+
162
+ useEffect(() => {
163
+ if (!api || typeof api.subscribe !== 'function') return undefined
164
+ let off
165
+ try {
166
+ off = api.subscribe(() => { void reload() })
167
+ } catch {
168
+ off = undefined
169
+ }
170
+ return () => {
171
+ if (typeof off !== 'function') return
172
+ try { off() } catch { /* teardown is best-effort */ }
173
+ }
174
+ // eslint-disable-next-line react-hooks/exhaustive-deps
175
+ }, [api])
176
+
177
+ // ── 数据加载 ──────────────────────────────────────────────────────────
178
+ async function reload() {
179
+ if (!api || typeof api.listMachines !== 'function') {
180
+ if (alive.current) setError(t('error.noApi'))
181
+ return
182
+ }
183
+ try {
184
+ const result = await api.listMachines()
185
+ if (!alive.current) return
186
+ const list = Array.isArray(result && result.machines) ? result.machines : []
187
+ setMachines(list)
188
+ setCurrentId(result && result.currentId !== undefined ? result.currentId : null)
189
+ setSelected((previous) => Math.min(previous, Math.max(0, list.length - 1)))
190
+ let nextStatus
191
+ try {
192
+ nextStatus = await api.status()
193
+ } catch {
194
+ nextStatus = undefined
195
+ }
196
+ if (alive.current && nextStatus) setStatus(nextStatus)
197
+ } catch (failure) {
198
+ if (alive.current) setError(messageOf(failure))
199
+ }
200
+ }
201
+
202
+ /** Monotonic token: only the newest directory listing may paint. */
203
+ const dirToken = useRef(0)
204
+ /** Same guard for the workspace-cleanup list. */
205
+ const wsToken = useRef(0)
206
+ async function loadDir(machine, dirPath) {
207
+ if (!api || typeof api.listDir !== 'function' || !machine) return
208
+ const token = ++dirToken.current
209
+ setBusy(t('busy.listing'))
210
+ setError('')
211
+ try {
212
+ const listing = await api.listDir({ machineId: machine.id, path: dirPath })
213
+ if (!alive.current || token !== dirToken.current) return
214
+ setBrowse({
215
+ machine,
216
+ path: String((listing && listing.path) || dirPath || ''),
217
+ parent: listing && listing.parent !== undefined ? listing.parent : null,
218
+ items: Array.isArray(listing && listing.items) ? listing.items : [],
219
+ selected: 0,
220
+ })
221
+ } catch (failure) {
222
+ if (alive.current && token === dirToken.current) setError(messageOf(failure))
223
+ } finally {
224
+ if (alive.current && token === dirToken.current) setBusy('')
225
+ }
226
+ }
227
+
228
+ /** 统一异步动作包装:设置加载态、把失败写到页脚、卸载后丢弃。 */
229
+ const runOp = useCallback(async (what, action) => {
230
+ setBusy(what)
231
+ setError('')
232
+ try {
233
+ return await action()
234
+ } catch (failure) {
235
+ if (alive.current) setError(messageOf(failure))
236
+ return undefined
237
+ } finally {
238
+ if (alive.current) setBusy('')
239
+ }
240
+ }, [])
241
+
242
+ /** 提示:优先用活会话 channel.notify,其次注入的 notify(宿主 toast)。 */
243
+ const toast = useCallback((text, options) => {
244
+ const message = String(text)
245
+ try {
246
+ if (channel && typeof channel.notify === 'function') {
247
+ channel.notify(message, options)
248
+ return
249
+ }
250
+ } catch { /* fall through to the injected channel */ }
251
+ try {
252
+ if (typeof notify === 'function') notify(message, options)
253
+ } catch { /* notifications are best-effort */ }
254
+ }, [channel, notify])
255
+
256
+ /** 切换工作区(宿主拒绝 / 异常只提示,不改场景状态)。 */
257
+ async function switchWorkspace(target) {
258
+ if (!autoSwitch || !target) return
259
+ try {
260
+ if (!channel || typeof channel.switchWorkspace !== 'function') return
261
+ const switched = await channel.switchWorkspace(target)
262
+ if (switched === false) toast(t('notify.switchRefused', { label: target.label }), { color: 'warning' })
263
+ } catch (failure) {
264
+ toast(t('notify.switchFailed', { err: messageOf(failure) }), { color: 'warning' })
265
+ }
266
+ }
267
+
268
+ /** 把 ensure/pick 的结果转成 target,并提示 + 可选切换。 */
269
+ async function adoptWorkspace(machine, workspace, remotePath) {
270
+ const target = targetFromWorkspace({
271
+ machine,
272
+ localMirror: workspace && workspace.localMirror,
273
+ remotePath: (workspace && workspace.remotePath) || remotePath,
274
+ title: workspace && workspace.title,
275
+ })
276
+ if (!target) {
277
+ setError(t('error.badWorkspace'))
278
+ return
279
+ }
280
+ toast(t('notify.workspaceSet', { label: target.label }), { color: 'success' })
281
+ await switchWorkspace(target)
282
+ }
283
+
284
+ // ── 动作 ──────────────────────────────────────────────────────────────
285
+ async function connectMachine(machine) {
286
+ if (!machine) return
287
+ const result = await runOp(t('busy.connecting'), () => api.connect({ machineId: machine.id, persist: true }))
288
+ if (!result) return
289
+ if (result.connected === false) {
290
+ setError(t('notify.probeFailed', { err: result.activeSource || t('error.generic') }))
291
+ return
292
+ }
293
+ toast(t('notify.connected', { target: machineAddress(machine) }), { color: 'success' })
294
+ await reload()
295
+ }
296
+
297
+ /** 在系统文件管理器里打开本机 dsh-remote 的镜像根目录(remote-workspaces)。 */
298
+ async function revealMirrorFolder() {
299
+ if (typeof api.revealMirrorFolder !== 'function') return
300
+ const result = await runOp(t('busy.revealFolder'), () => api.revealMirrorFolder())
301
+ if (!result) return
302
+ toast(t('notify.revealed', { path: result.path }), { color: 'success' })
303
+ }
304
+
305
+ async function probeMachine(machine) {
306
+ if (!machine || typeof api.probeMachine !== 'function') return
307
+ const patch = {
308
+ id: machine.id,
309
+ host: machine.host,
310
+ port: Number(machine.port) || 22,
311
+ username: machine.username,
312
+ useSshConfig: machine.useSshConfig === true,
313
+ privateKeyPath: machine.privateKeyPath || '',
314
+ useAgent: machine.useAgent === true,
315
+ backend: machine.backend || 'native',
316
+ sshBinary: machine.sshBinary || '',
317
+ keyboardInteractive: machine.keyboardInteractive === true,
318
+ }
319
+ const probe = await runOp(t('busy.probing'), () => api.probeMachine(patch))
320
+ if (!probe) return
321
+ if (probe.ok === false) {
322
+ const message = probe.error || t('error.generic')
323
+ setError(messageOf(message))
324
+ toast(t('notify.probeFailed', { err: messageOf(message) }), { color: 'error' })
325
+ return
326
+ }
327
+ const target = `${probe.user || machine.username || ''}@${probe.host || machine.host || ''}`
328
+ const latency = typeof probe.latencyMs === 'number' ? Math.round(probe.latencyMs) : '-'
329
+ toast(t('notify.probeOk', { target, latency }), { color: 'success' })
330
+ }
331
+
332
+ async function deleteMachine(machine) {
333
+ if (!machine || typeof api.removeMachine !== 'function') return
334
+ const result = await runOp(t('busy.deleting'), () => api.removeMachine(machine.id))
335
+ if (!result || !alive.current) return
336
+ toast(t('notify.deleted', { name: machineName(machine) }), { color: 'success' })
337
+ setView('list')
338
+ await reload()
339
+ }
340
+
341
+ async function pickBrowseWorkspace() {
342
+ const current = browse
343
+ if (!current) return
344
+ if (!current.path) {
345
+ toast(t('browse.noSelection'), { color: 'warning' })
346
+ return
347
+ }
348
+ setBusy(t('busy.settingWorkspace'))
349
+ setError('')
350
+ try {
351
+ const workspace = await api.pickRemoteWorkspace({
352
+ machineId: current.machine.id,
353
+ remotePath: current.path,
354
+ registerWorkspace: true,
355
+ })
356
+ if (!alive.current) return
357
+ await adoptWorkspace(current.machine, workspace, current.path)
358
+ } catch (failure) {
359
+ if (alive.current) {
360
+ setError(messageOf(failure))
361
+ toast(t('notify.pickFailed', { err: messageOf(failure) }), { color: 'warning' })
362
+ }
363
+ } finally {
364
+ if (alive.current) setBusy('')
365
+ }
366
+ }
367
+
368
+ async function saveForm() {
369
+ if (!form) return
370
+ const { errors, patch } = validateMachineForm(form, t)
371
+ if (errors.length) {
372
+ setFormErrors(errors)
373
+ return
374
+ }
375
+ setFormErrors([])
376
+ const result = await runOp(t('busy.saving'), () => api.upsertMachine(patch))
377
+ if (!result || !alive.current) return
378
+ const name = (result.machine && result.machine.name) || patch.name || patch.host
379
+ toast(t('notify.saved', { name }), { color: 'success' })
380
+ if (Array.isArray(result.warnings) && result.warnings.length) {
381
+ toast(t('notify.warnings', { text: result.warnings.join('; ') }), { color: 'warning', timeoutMs: 8000 })
382
+ }
383
+ setView('list')
384
+ await reload()
385
+ }
386
+
387
+ // ── 视图切换 ──────────────────────────────────────────────────────────
388
+ const backToList = () => {
389
+ setView('list')
390
+ setFormErrors([])
391
+ setError('')
392
+ }
393
+
394
+ function openMenu(machine) {
395
+ if (!machine) return
396
+ setMenuIndex(0)
397
+ setView('menu')
398
+ }
399
+
400
+ function openForm(machine) {
401
+ setForm(machine ? formFromMachine(machine) : emptyMachineForm())
402
+ setFormField(0)
403
+ setFormErrors([])
404
+ setError('')
405
+ setView('form')
406
+ }
407
+
408
+ function openBrowse(machine) {
409
+ if (!machine) return
410
+ setBrowse({ machine, path: '', parent: null, items: [], selected: 0 })
411
+ setError('')
412
+ setView('browse')
413
+ // Start at the machine's recorded remote workspace when there is one,
414
+ // instead of whatever the host considers its current directory.
415
+ void loadDir(machine, machine.workspace || undefined)
416
+ }
417
+
418
+ // ── 工作区清理(删除镜像 / 删除对话 / 移出最近列表) ──────────────────
419
+ function selectedWorkspace() {
420
+ const list = workspaces || []
421
+ if (!list.length) return undefined
422
+ return list[Math.max(0, Math.min(wsIndex, list.length - 1))]
423
+ }
424
+
425
+ async function loadWorkspaces(machine) {
426
+ if (!api || typeof api.listWorkspaceMirrors !== 'function') {
427
+ setError(t('ws.noApi'))
428
+ return
429
+ }
430
+ if (!machine) return
431
+ const token = ++wsToken.current
432
+ setBusy(t('busy.loadingMirrors'))
433
+ setError('')
434
+ try {
435
+ const list = await api.listWorkspaceMirrors({ machineId: machine.id })
436
+ if (!alive.current || token !== wsToken.current) return
437
+ const items = Array.isArray(list) ? list : []
438
+ setWorkspaces(items)
439
+ setWsIndex((previous) => Math.min(previous, Math.max(0, items.length - 1)))
440
+ } catch (failure) {
441
+ if (alive.current && token === wsToken.current) setError(messageOf(failure))
442
+ } finally {
443
+ if (alive.current && token === wsToken.current) setBusy('')
444
+ }
445
+ }
446
+
447
+ function openWorkspaces(machine) {
448
+ if (!machine) return
449
+ setWsMachine(machine)
450
+ setWorkspaces(null)
451
+ setWsIndex(0)
452
+ setWsConfirm(null)
453
+ setError('')
454
+ setView('workspaces')
455
+ void loadWorkspaces(machine)
456
+ }
457
+
458
+ function openWsConfirm(action) {
459
+ const item = selectedWorkspace()
460
+ if (!item) {
461
+ toast(t('ws.empty'), { color: 'warning' })
462
+ return
463
+ }
464
+ setWsConfirm({ action, item })
465
+ setError('')
466
+ setView('wsconfirm')
467
+ }
468
+
469
+ async function runWsConfirm() {
470
+ const pending = wsConfirm
471
+ if (!pending) return
472
+ const { action, item } = pending
473
+ const label = item.title || basenameRemote(item.remotePath)
474
+ const what = action === 'delete' ? t('ws.busyDelete')
475
+ : action === 'sessions' ? t('ws.busySessions') : t('ws.busyRecent')
476
+ setBusy(what)
477
+ setError('')
478
+ try {
479
+ if (action === 'delete') {
480
+ if (typeof api.deleteRemoteWorkspace !== 'function') throw new Error(t('ws.noApi'))
481
+ const result = await api.deleteRemoteWorkspace({ localMirror: item.localMirror, deleteSessions: true })
482
+ if (!alive.current) return
483
+ toast(t('ws.deleted', { name: label, sessions: String(Number(result && result.removedSessions) || 0) }), { color: 'success' })
484
+ } else if (action === 'sessions') {
485
+ if (typeof api.deleteWorkspaceSessions !== 'function') throw new Error(t('ws.noApi'))
486
+ const result = await api.deleteWorkspaceSessions({ localMirror: item.localMirror })
487
+ if (!alive.current) return
488
+ const removed = Number(result && result.removedSessions) || 0
489
+ const skipped = Array.isArray(result && result.skippedLiveSessions) ? result.skippedLiveSessions.length : 0
490
+ toast(skipped
491
+ ? t('ws.sessionsPartial', { n: String(removed), live: String(skipped) })
492
+ : t('ws.sessionsDeleted', { n: String(removed) }), { color: skipped ? 'warning' : 'success' })
493
+ } else {
494
+ if (typeof api.forgetWorkspaceRecent !== 'function') throw new Error(t('ws.noApi'))
495
+ await api.forgetWorkspaceRecent({ localMirror: item.localMirror })
496
+ if (!alive.current) return
497
+ toast(t('ws.recentForgotten', { name: label }), { color: 'success' })
498
+ }
499
+ if (!alive.current) return
500
+ setWsConfirm(null)
501
+ setView('workspaces')
502
+ await loadWorkspaces(wsMachine)
503
+ } catch (failure) {
504
+ if (!alive.current) return
505
+ // A refused deletion is not a dead end: return to the list (the footer
506
+ // explains what must stop) so the person can retry after Ctrl+X.
507
+ setWsConfirm(null)
508
+ setView('workspaces')
509
+ const live = failure && Array.isArray(failure.liveSessions) ? failure.liveSessions.length : 0
510
+ setError(live ? t('ws.busyError', { n: String(live) }) : messageOf(failure))
511
+ } finally {
512
+ if (alive.current) setBusy('')
513
+ }
514
+ }
515
+
516
+ function openConfirm(machine) {
517
+ if (!machine) return
518
+ setConfirmMachine(machine)
519
+ setView('confirm')
520
+ }
521
+
522
+ /** 执行动作菜单 / 快捷键对应的动作。 */
523
+ function executeAction(action, machine) {
524
+ if (!machine) return
525
+ switch (action) {
526
+ case 'connect': void connectMachine(machine); break
527
+ case 'workspaces': openWorkspaces(machine); break
528
+ case 'edit': openForm(machine); break
529
+ case 'delete': openConfirm(machine); break
530
+ case 'probe': void probeMachine(machine); break
531
+ case 'browse': openBrowse(machine); break
532
+ default: break
533
+ }
534
+ }
535
+
536
+ // ── 键盘 ──────────────────────────────────────────────────────────────
537
+ const selectedMachine = machines.length
538
+ ? machines[Math.max(0, Math.min(selected, machines.length - 1))]
539
+ : undefined
540
+
541
+ function handleListKey(input, key) {
542
+ // Escape FIRST: a lone Esc carries `meta: true` in this TUI, so any
543
+ // modifier guard before it swallows every Esc press.
544
+ if (key.escape || input === 'q') {
545
+ if (typeof close === 'function') close()
546
+ return
547
+ }
548
+ if (key.ctrl || key.meta) return
549
+ if (key.leftArrow) {
550
+ if (typeof close === 'function') close()
551
+ return
552
+ }
553
+ if (key.rightArrow) {
554
+ openMenu(selectedMachine)
555
+ return
556
+ }
557
+ if (key.upArrow || input === 'k') {
558
+ setSelected((previous) => Math.max(0, previous - 1))
559
+ return
560
+ }
561
+ if (key.downArrow || input === 'j') {
562
+ setSelected((previous) => Math.min(Math.max(0, machines.length - 1), previous + 1))
563
+ return
564
+ }
565
+ if (key.return) {
566
+ openMenu(selectedMachine)
567
+ return
568
+ }
569
+ switch (input) {
570
+ case 'a': openForm(undefined); break
571
+ case 'c': void connectMachine(selectedMachine); break
572
+ case 'e': openForm(selectedMachine); break
573
+ case 'd': openConfirm(selectedMachine); break
574
+ case 't': void probeMachine(selectedMachine); break
575
+ case 'b': openBrowse(selectedMachine); break
576
+ case 'o': void revealMirrorFolder(); break
577
+ default: break
578
+ }
579
+ }
580
+
581
+ function handleMenuKey(input, key) {
582
+ if (key.escape || input === 'q' || key.leftArrow) {
583
+ backToList()
584
+ return
585
+ }
586
+ if (key.ctrl || key.meta) return
587
+ if (key.upArrow || input === 'k') {
588
+ setMenuIndex((previous) => Math.max(0, previous - 1))
589
+ return
590
+ }
591
+ if (key.downArrow || input === 'j') {
592
+ setMenuIndex((previous) => Math.min(MENU_ACTIONS.length - 1, previous + 1))
593
+ return
594
+ }
595
+ if (key.return || key.rightArrow) {
596
+ const action = MENU_ACTIONS[Math.max(0, Math.min(menuIndex, MENU_ACTIONS.length - 1))]
597
+ executeAction(action, selectedMachine)
598
+ return
599
+ }
600
+ if (input === 'c') executeAction('connect', selectedMachine)
601
+ else if (input === 'e') executeAction('edit', selectedMachine)
602
+ else if (input === 'd') executeAction('delete', selectedMachine)
603
+ else if (input === 't') executeAction('probe', selectedMachine)
604
+ else if (input === 'b') executeAction('browse', selectedMachine)
605
+ else if (input === 'm') executeAction('workspaces', selectedMachine)
606
+ }
607
+
608
+ function handleConfirmKey(input, key) {
609
+ if (key.escape || input === 'n' || input === 'q' || key.leftArrow) {
610
+ backToList()
611
+ return
612
+ }
613
+ if (key.ctrl || key.meta) return
614
+ if (key.return || key.rightArrow || input === 'y') {
615
+ const target = confirmMachine
616
+ setConfirmMachine(null)
617
+ void deleteMachine(target)
618
+ }
619
+ }
620
+
621
+ function handleFormKey(input, key) {
622
+ if (!form) {
623
+ backToList()
624
+ return
625
+ }
626
+ const fields = fieldsFor(form)
627
+ const bounded = Math.max(0, Math.min(formField, fields.length - 1))
628
+ if (key.escape) {
629
+ backToList()
630
+ return
631
+ }
632
+ if (key.ctrl || key.meta) return
633
+ if (key.tab) {
634
+ const next = key.shift ? bounded - 1 : bounded + 1
635
+ setFormField(Math.max(0, Math.min(fields.length - 1, next)))
636
+ return
637
+ }
638
+ if (key.upArrow) {
639
+ setFormField(Math.max(0, bounded - 1))
640
+ return
641
+ }
642
+ if (key.downArrow) {
643
+ setFormField(Math.min(fields.length - 1, bounded + 1))
644
+ return
645
+ }
646
+ if (key.return) {
647
+ void saveForm()
648
+ return
649
+ }
650
+ const field = fields[bounded]
651
+ if (!field) return
652
+ if (field === 'useSshConfig') {
653
+ if (input === ' ' || key.leftArrow || key.rightArrow) {
654
+ setForm((previous) => ({ ...previous, useSshConfig: !(previous && previous.useSshConfig) }))
655
+ }
656
+ return
657
+ }
658
+ if (field === 'auth') {
659
+ if (input === ' ' || key.leftArrow || key.rightArrow) {
660
+ const auth = nextAuth(form.auth, key.leftArrow ? -1 : 1)
661
+ setForm({ ...form, auth })
662
+ setFormField((index) => Math.min(index, fieldsFor({ auth }).length - 1))
663
+ }
664
+ return
665
+ }
666
+ if (key.backspace || key.delete) {
667
+ setForm((previous) => {
668
+ const value = String((previous && previous[field]) || '')
669
+ return { ...previous, [field]: value.slice(0, -1) }
670
+ })
671
+ return
672
+ }
673
+ if (!input || /[\u0000-\u001f\u007f]/.test(input)) return
674
+ const chunk = input.replace(/[\r\n]+/g, '')
675
+ if (!chunk) return
676
+ setForm((previous) => {
677
+ const value = String((previous && previous[field]) || '') + chunk
678
+ const next = field === 'port' ? value.replace(/[^\d]/g, '').slice(0, 5) : value
679
+ return { ...previous, [field]: next }
680
+ })
681
+ }
682
+
683
+ function handleBrowseKey(input, key) {
684
+ if (key.escape || input === 'q') {
685
+ backToList()
686
+ return
687
+ }
688
+ if (key.ctrl || key.meta) return
689
+ const current = browse
690
+ const dirs = current ? current.items.filter((item) => item && item.type === 'dir') : []
691
+ const bounded = current ? Math.max(0, Math.min(current.selected, dirs.length - 1)) : 0
692
+ if (key.upArrow || input === 'k') {
693
+ setBrowse((previous) => previous
694
+ ? { ...previous, selected: Math.max(0, Math.min(previous.selected, dirs.length - 1) - 1) }
695
+ : previous)
696
+ return
697
+ }
698
+ if (key.downArrow || input === 'j') {
699
+ setBrowse((previous) => previous
700
+ ? { ...previous, selected: Math.min(Math.max(0, dirs.length - 1), previous.selected + 1) }
701
+ : previous)
702
+ return
703
+ }
704
+ if (key.return || key.rightArrow) {
705
+ const dir = dirs[bounded]
706
+ if (dir && current) void loadDir(current.machine, dir.path)
707
+ else toast(t('browse.noSelection'), { color: 'warning' })
708
+ return
709
+ }
710
+ if (key.leftArrow || key.backspace || key.delete) {
711
+ // ← = one DIRECTORY level up (same as Backspace); at the root it leaves
712
+ // the browse view instead of doing nothing.
713
+ if (current && current.parent) void loadDir(current.machine, current.parent)
714
+ else backToList()
715
+ return
716
+ }
717
+ if (input === 'w') void pickBrowseWorkspace()
718
+ }
719
+
720
+ function handleWorkspacesKey(input, key) {
721
+ if (key.escape || input === 'q' || key.leftArrow) {
722
+ backToList()
723
+ return
724
+ }
725
+ if (key.ctrl || key.meta) return
726
+ const list = workspaces || []
727
+ if (key.upArrow || input === 'k') {
728
+ setWsIndex((previous) => Math.max(0, previous - 1))
729
+ return
730
+ }
731
+ if (key.downArrow || input === 'j') {
732
+ setWsIndex((previous) => Math.min(Math.max(0, list.length - 1), previous + 1))
733
+ return
734
+ }
735
+ if (input === 'd') { openWsConfirm('delete'); return }
736
+ if (input === 'x') { openWsConfirm('sessions'); return }
737
+ if (input === 'r') { openWsConfirm('recent'); return }
738
+ }
739
+
740
+ function handleWsConfirmKey(input, key) {
741
+ if (key.escape || input === 'n' || input === 'q' || key.leftArrow) {
742
+ setWsConfirm(null)
743
+ setView('workspaces')
744
+ return
745
+ }
746
+ if (key.ctrl || key.meta) return
747
+ if (key.return || key.rightArrow || input === 'y') void runWsConfirm()
748
+ }
749
+
750
+ useInput((input, key) => {
751
+ const pressed = key || {}
752
+ if (view === 'list') handleListKey(input, pressed)
753
+ else if (view === 'menu') handleMenuKey(input, pressed)
754
+ else if (view === 'form') handleFormKey(input, pressed)
755
+ else if (view === 'browse') handleBrowseKey(input, pressed)
756
+ else if (view === 'workspaces') handleWorkspacesKey(input, pressed)
757
+ else if (view === 'wsconfirm') handleWsConfirmKey(input, pressed)
758
+ else if (view === 'confirm') handleConfirmKey(input, pressed)
759
+ })
760
+
761
+ // ── 渲染 ──────────────────────────────────────────────────────────────
762
+ function renderHeader() {
763
+ const connected = status && status.connected === true
764
+ return h(Box, { key: 'header', flexDirection: 'row', width: '100%', paddingX: 1 },
765
+ h(Text, { bold: true, color: 'accent' }, t('title')),
766
+ h(Box, { flexGrow: 1 }),
767
+ h(Text, { color: connected ? 'success' : 'subtle' }, status ? statusLine(status, t) : t('status.loading')),
768
+ )
769
+ }
770
+
771
+ function renderList() {
772
+ const children = []
773
+ if (!machines.length) {
774
+ children.push(h(Text, { key: 'empty', color: 'subtle' }, t('list.empty')))
775
+ } else {
776
+ const slicing = windowSlice(machines, selected, bodyHeight - 1)
777
+ slicing.items.forEach((machine, index) => {
778
+ const absolute = slicing.offset + index
779
+ const focused = absolute === selected
780
+ const current = machine.id === currentId
781
+ children.push(h(Box, { key: machine.id || `machine-${absolute}`, flexDirection: 'row', width: '100%' },
782
+ h(Text, { color: focused ? 'accent' : undefined, inverse: focused }, focused ? '› ' : ' '),
783
+ h(Text, { color: current ? 'success' : 'subtle' }, current ? '● ' : '○ '),
784
+ h(Text, { bold: focused || current }, clip(machineName(machine), Math.max(8, Math.floor(columns * 0.32)))),
785
+ h(Text, { dimColor: true }, clip(` ${machineAddress(machine)}`, Math.max(10, Math.floor(columns * 0.3)))),
786
+ machine.group ? h(Text, { color: 'subtle' }, clip(` [${machine.group}]`, 16)) : null,
787
+ machine.useSshConfig ? h(Text, { color: 'subtle' }, ' ssh-config') : null,
788
+ h(Box, { flexGrow: 1 }),
789
+ h(Text, { color: 'subtle' }, machine.workspace ? clip(basenameRemote(machine.workspace), 18) : ''),
790
+ ))
791
+ })
792
+ }
793
+ return h(Box, { key: 'body', flexDirection: 'column', width: '100%', paddingX: 1 }, ...children)
794
+ }
795
+
796
+ function renderMenu() {
797
+ const machine = selectedMachine
798
+ if (!machine) return h(Box, { key: 'body', flexDirection: 'column', width: '100%', paddingX: 1 },
799
+ h(Text, { color: 'subtle' }, t('list.empty')))
800
+ const children = [
801
+ h(Text, { key: 'title', bold: true, color: 'accent' }, t('menu.title', { name: machineName(machine) })),
802
+ h(Text, { key: 'addr', color: 'subtle' }, `${machineAddress(machine)}${machine.workspace ? ' · ' + clip(machine.workspace, 48) : ''}`),
803
+ ]
804
+ MENU_ACTIONS.forEach((action, index) => {
805
+ const focused = index === menuIndex
806
+ children.push(h(Text, { key: action, color: focused ? 'accent' : undefined, inverse: focused },
807
+ `${focused ? '› ' : ' '}${index + 1}. ${t('menu.' + action)}`))
808
+ })
809
+ return h(Box, { key: 'body', flexDirection: 'column', width: '100%', paddingX: 1 }, ...children)
810
+ }
811
+
812
+ function formValueText(field) {
813
+ if (!form) return ''
814
+ if (field === 'useSshConfig') return form.useSshConfig ? '[x]' : '[ ]'
815
+ if (field === 'auth') return `◂ ${t('auth.' + form.auth)} ▸`
816
+ if (field === 'password') {
817
+ const masked = maskValue(form.password)
818
+ if (masked) return masked
819
+ return form.id ? t('form.passwordUnchanged') : t('form.passwordPlaceholder')
820
+ }
821
+ if (field === 'passphrase') {
822
+ const masked = maskValue(form.passphrase)
823
+ if (masked) return masked
824
+ return form.id ? t('form.passwordUnchanged') : t('form.passphrasePlaceholder')
825
+ }
826
+ if (field === 'privateKeyPath') return String(form.privateKeyPath || '') || t('form.optional')
827
+ return String(form[field] === undefined || form[field] === null ? '' : form[field])
828
+ }
829
+
830
+ function renderForm() {
831
+ if (!form) return h(Box, { key: 'body', flexDirection: 'column', width: '100%', paddingX: 1 })
832
+ const fields = fieldsFor(form)
833
+ const bounded = Math.max(0, Math.min(formField, fields.length - 1))
834
+ const children = [
835
+ h(Text, { key: 'title', bold: true, color: 'accent' },
836
+ form.id ? t('form.titleEdit', { name: machineName(form) || form.host }) : t('form.titleNew')),
837
+ ]
838
+ const slicing = windowSlice(fields, bounded, bodyHeight - 2)
839
+ slicing.items.forEach((field, index) => {
840
+ const absolute = slicing.offset + index
841
+ const focused = absolute === bounded
842
+ const label = t('form.' + field)
843
+ const value = formValueText(field)
844
+ children.push(h(Box, { key: field, flexDirection: 'row', width: '100%' },
845
+ h(Text, { color: focused ? 'accent' : 'subtle', bold: focused }, `${focused ? '› ' : ' '}${label}: `),
846
+ h(Text, { inverse: focused, color: focused ? 'accent' : undefined },
847
+ clip(value + (focused && field !== 'useSshConfig' && field !== 'auth' ? '▌' : ''), Math.max(8, columns - 18))),
848
+ ))
849
+ })
850
+ return h(Box, { key: 'body', flexDirection: 'column', width: '100%', paddingX: 1 }, ...children)
851
+ }
852
+
853
+ function renderBrowse() {
854
+ const current = browse
855
+ if (!current) {
856
+ return h(Box, { key: 'body', flexDirection: 'column', width: '100%', paddingX: 1 },
857
+ h(Text, { color: 'subtle' }, t('browse.loading')))
858
+ }
859
+ const dirs = current.items.filter((item) => item && item.type === 'dir')
860
+ const files = current.items.filter((item) => item && item.type !== 'dir')
861
+ const combined = [...dirs, ...files]
862
+ const selection = dirs.length ? Math.max(0, Math.min(current.selected, dirs.length - 1)) : 0
863
+ const children = [
864
+ h(Text, { key: 'title', bold: true, color: 'accent' }, t('browse.title', { path: clip(current.path || '/', Math.max(8, columns - 20)) })),
865
+ h(Text, { key: 'machine', color: 'subtle' }, `${machineName(current.machine)} · ${machineAddress(current.machine)}`),
866
+ ]
867
+ if (!combined.length) {
868
+ children.push(h(Text, { key: 'empty', color: 'subtle' }, busy ? t('browse.loading') : t('browse.empty')))
869
+ } else {
870
+ const slicing = windowSlice(combined, selection, Math.max(1, bodyHeight - 3))
871
+ slicing.items.forEach((item, index) => {
872
+ const absolute = slicing.offset + index
873
+ const isDir = item.type === 'dir'
874
+ const focused = isDir && absolute === selection
875
+ const icon = isDir ? '▸' : '·'
876
+ const suffix = isDir ? '/' : ''
877
+ children.push(h(Text, {
878
+ key: `${item.path || item.name || index}`,
879
+ color: focused ? 'accent' : isDir ? undefined : 'subtle',
880
+ dimColor: !isDir,
881
+ inverse: focused,
882
+ }, `${focused ? '› ' : ' '}${icon} ${clip(String(item.name || ''), Math.max(8, columns - 8))}${suffix}`))
883
+ })
884
+ }
885
+ return h(Box, { key: 'body', flexDirection: 'column', width: '100%', paddingX: 1 }, ...children)
886
+ }
887
+
888
+ function renderConfirm() {
889
+ const machine = confirmMachine
890
+ const children = [
891
+ h(Text, { key: 'title', bold: true, color: 'warning' }, t('confirm.deleteTitle')),
892
+ h(Text, { key: 'message' }, t('confirm.delete', { name: machineName(machine) })),
893
+ h(Text, { key: 'addr', color: 'subtle' }, machineAddress(machine)),
894
+ ]
895
+ return h(Box, { key: 'body', flexDirection: 'column', width: '100%', paddingX: 1 }, ...children)
896
+ }
897
+
898
+ function renderWorkspaces() {
899
+ const machine = wsMachine
900
+ const list = workspaces || []
901
+ const children = [
902
+ h(Text, { key: 'title', bold: true, color: 'accent' }, t('ws.title', { name: machine ? machineName(machine) : '' })),
903
+ h(Text, { key: 'addr', color: 'subtle' }, machine ? machineAddress(machine) : ''),
904
+ ]
905
+ if (workspaces === null) {
906
+ children.push(h(Text, { key: 'loading', color: 'subtle' }, busy || t('busy.loading')))
907
+ } else if (!list.length) {
908
+ children.push(h(Text, { key: 'empty', color: 'subtle' }, t('ws.empty')))
909
+ } else {
910
+ const slicing = windowSlice(list, Math.max(0, Math.min(wsIndex, list.length - 1)), Math.max(2, Math.floor((bodyHeight - 2) / 2)))
911
+ slicing.items.forEach((item, index) => {
912
+ const absolute = slicing.offset + index
913
+ const focused = absolute === wsIndex
914
+ const tags = []
915
+ if (item.registered) tags.push(t('ws.registered'))
916
+ if (item.recent) tags.push(t('ws.recent'))
917
+ const live = Number(item.liveSessionCount) || 0
918
+ children.push(h(Box, { key: `ws-${item.localMirror || absolute}`, flexDirection: 'row', width: '100%' },
919
+ h(Text, { color: focused ? 'accent' : undefined, inverse: focused }, focused ? '› ' : ' '),
920
+ h(Text, { bold: focused }, clip(item.title || basenameRemote(item.remotePath), Math.max(12, Math.floor(columns * 0.34)))),
921
+ h(Text, { color: 'subtle' }, ` ${t('ws.sessions', { n: String(Number(item.sessionCount) || 0) })}`),
922
+ live ? h(Text, { color: 'warning' }, ` ${t('ws.live', { n: String(live) })}`) : null,
923
+ h(Text, { dimColor: true }, ` ${t('ws.size', { size: formatBytes(item.mirrorBytes) })}`),
924
+ tags.length ? h(Text, { color: 'subtle' }, ` [${tags.join(' · ')}]`) : null,
925
+ ))
926
+ children.push(h(Text, { key: `ws-path-${item.localMirror || absolute}`, color: 'subtle', dimColor: true },
927
+ clip(` ${item.username ? item.username + '@' : ''}${item.host}:${item.remotePath}`, Math.max(20, columns - 3))))
928
+ })
929
+ }
930
+ return h(Box, { key: 'body', flexDirection: 'column', width: '100%', paddingX: 1 }, ...children)
931
+ }
932
+
933
+ function renderWsConfirm() {
934
+ const pending = wsConfirm
935
+ const item = pending && pending.item
936
+ const action = pending && pending.action
937
+ const titleKey = action === 'delete' ? 'ws.confirmTitleDelete'
938
+ : action === 'sessions' ? 'ws.confirmTitleSessions' : 'ws.confirmTitleRecent'
939
+ const bodyKey = action === 'delete' ? 'ws.confirmDelete'
940
+ : action === 'sessions' ? 'ws.confirmSessions' : 'ws.confirmRecent'
941
+ const name = item ? (item.title || basenameRemote(item.remotePath)) : ''
942
+ const sessions = item ? Number(item.sessionCount) || 0 : 0
943
+ return h(Box, { key: 'body', flexDirection: 'column', width: '100%', paddingX: 1 },
944
+ h(Text, { key: 'title', bold: true, color: 'warning' }, t(titleKey, { name })),
945
+ h(Text, { key: 'message' }, clip(t(bodyKey, { n: String(sessions), name }), Math.max(20, columns - 4))),
946
+ h(Text, { key: 'path', color: 'subtle' }, clip(item ? `${item.username ? item.username + '@' : ''}${item.host}:${item.remotePath}` : '', Math.max(20, columns - 4))),
947
+ h(Text, { key: 'mirror', color: 'subtle' }, clip(item ? item.localMirror : '', Math.max(20, columns - 4))),
948
+ )
949
+ }
950
+
951
+ function hintForView() {
952
+ if (view === 'menu') return t('menu.hints')
953
+ if (view === 'form') return t('form.hints')
954
+ if (view === 'browse') return t('browse.hints')
955
+ if (view === 'workspaces') return t('ws.hints')
956
+ if (view === 'wsconfirm') return t('ws.confirmHints')
957
+ if (view === 'confirm') return t('confirm.hints')
958
+ return t('list.hints')
959
+ }
960
+
961
+ function renderFooter() {
962
+ const children = []
963
+ if (busy) children.push(h(Text, { key: 'busy', color: 'accent' }, t('busy.line', { what: busy })))
964
+ const failure = view === 'form' && formErrors.length ? formErrors.join(' · ') : error
965
+ if (failure) children.push(h(Text, { key: 'error', color: 'error' }, t('footer.error', { err: failure })))
966
+ children.push(h(Text, { key: 'hint', color: 'subtle' }, clip(hintForView(), Math.max(20, columns - 2))))
967
+ return h(Box, { key: 'footer', flexDirection: 'column', width: '100%', paddingX: 1 }, ...children)
968
+ }
969
+
970
+ function renderBody() {
971
+ if (view === 'menu') return renderMenu()
972
+ if (view === 'form') return renderForm()
973
+ if (view === 'browse') return renderBrowse()
974
+ if (view === 'workspaces') return renderWorkspaces()
975
+ if (view === 'wsconfirm') return renderWsConfirm()
976
+ if (view === 'confirm') return renderConfirm()
977
+ return renderList()
978
+ }
979
+
980
+ return h(Box, { flexDirection: 'column', width: '100%', flexGrow: 1, paddingY: 0 },
981
+ renderHeader(),
982
+ renderBody(),
983
+ renderFooter(),
984
+ )
985
+ }
986
+ }