@fish-under-sea/dsh-ssh-fish 0.0.0-stage → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/LICENSE +202 -0
  2. package/README.i18n.yaml +6 -0
  3. package/README.md +98 -2
  4. package/README.zh.md +99 -0
  5. package/cordis.patch.yml +12 -0
  6. package/icon.svg +3 -0
  7. package/lib/client.js +16487 -0
  8. package/lib/client.js.map +1 -0
  9. package/lib/index.js +3511 -0
  10. package/lib/types/client/api.d.ts +141 -0
  11. package/lib/types/client/index.d.ts +37 -0
  12. package/lib/types/client/locales.d.ts +164 -0
  13. package/lib/types/client/native-panel.d.ts +70 -0
  14. package/lib/types/client/panel/ClusterTab.d.ts +7 -0
  15. package/lib/types/client/panel/HostFormDialog.d.ts +12 -0
  16. package/lib/types/client/panel/HostsTab.d.ts +25 -0
  17. package/lib/types/client/panel/SshPanel.d.ts +14 -0
  18. package/lib/types/client/panel/TerminalTab.d.ts +22 -0
  19. package/lib/types/client/panel/TransferTab.d.ts +7 -0
  20. package/lib/types/client/panel/TunnelsTab.d.ts +19 -0
  21. package/lib/types/client/panel/controller.d.ts +89 -0
  22. package/lib/types/client/panel/helpers.d.ts +45 -0
  23. package/lib/types/client/panel/xterm.css.d.ts +2 -0
  24. package/lib/types/client/settings-binding.d.ts +61 -0
  25. package/lib/types/dsh-home.d.ts +16 -0
  26. package/lib/types/engine/cluster.d.ts +19 -0
  27. package/lib/types/engine/connection-pool.d.ts +112 -0
  28. package/lib/types/engine/proxy-command.d.ts +36 -0
  29. package/lib/types/engine/pty.d.ts +32 -0
  30. package/lib/types/engine/sftp.d.ts +20 -0
  31. package/lib/types/engine/terminal-sessions.d.ts +67 -0
  32. package/lib/types/engine/tunnel.d.ts +36 -0
  33. package/lib/types/engine.d.ts +89 -0
  34. package/lib/types/http.d.ts +59 -0
  35. package/lib/types/index.d.ts +83 -0
  36. package/lib/types/loopback.d.ts +24 -0
  37. package/lib/types/mount-once.d.ts +55 -0
  38. package/lib/types/protocol.d.ts +239 -0
  39. package/lib/types/routes.d.ts +33 -0
  40. package/lib/types/ssh-config.d.ts +34 -0
  41. package/lib/types/store.d.ts +71 -0
  42. package/lib/types/tool-surface.d.ts +71 -0
  43. package/lib/types/tools.d.ts +42 -0
  44. package/package.json +106 -4
  45. package/src/client/api.ts +562 -0
  46. package/src/client/css-modules.d.ts +5 -0
  47. package/src/client/index.ts +137 -0
  48. package/src/client/locales.ts +338 -0
  49. package/src/client/native-panel.tsx +141 -0
  50. package/src/client/panel/ClusterTab.tsx +123 -0
  51. package/src/client/panel/HostFormDialog.tsx +258 -0
  52. package/src/client/panel/HostsTab.tsx +325 -0
  53. package/src/client/panel/SshPanel.tsx +90 -0
  54. package/src/client/panel/TerminalTab.tsx +330 -0
  55. package/src/client/panel/TransferTab.tsx +232 -0
  56. package/src/client/panel/TunnelsTab.tsx +244 -0
  57. package/src/client/panel/controller.ts +167 -0
  58. package/src/client/panel/helpers.ts +84 -0
  59. package/src/client/panel/panel.module.css +876 -0
  60. package/src/client/panel/xterm.css.ts +2 -0
  61. package/src/client/settings-binding.ts +165 -0
  62. package/src/dsh-home.ts +42 -0
  63. package/src/engine/cluster.ts +60 -0
  64. package/src/engine/connection-pool.ts +543 -0
  65. package/src/engine/proxy-command.ts +248 -0
  66. package/src/engine/pty.ts +78 -0
  67. package/src/engine/sftp.ts +226 -0
  68. package/src/engine/terminal-sessions.ts +280 -0
  69. package/src/engine/tunnel.ts +194 -0
  70. package/src/engine.ts +176 -0
  71. package/src/http.ts +127 -0
  72. package/src/index.ts +234 -0
  73. package/src/loopback.ts +63 -0
  74. package/src/mount-once.ts +142 -0
  75. package/src/protocol.ts +230 -0
  76. package/src/routes.ts +494 -0
  77. package/src/ssh-config.ts +153 -0
  78. package/src/store.ts +419 -0
  79. package/src/tool-surface.ts +95 -0
  80. package/src/tools.ts +404 -0
@@ -0,0 +1,330 @@
1
+ /**
2
+ * Terminal tab: an xterm.js PTY view over the host's WebSocket terminal route.
3
+ * A host <select> plus connect/disconnect controls; the terminal container is
4
+ * sized by FitAddon (default 80x24 before first fit). On remote exit the last
5
+ * output stays visible and input is disabled. xterm's stylesheet is injected
6
+ * once per page load (module-level guard).
7
+ */
8
+ import { useEffect, useRef, useState, useSyncExternalStore } from 'react'
9
+ import { Terminal, type IDisposable } from '@xterm/xterm'
10
+ import { FitAddon } from '@xterm/addon-fit'
11
+ import type { SshApi, TerminalConnection } from '../api.ts'
12
+ import type { SshHostSummary } from '../../protocol.ts'
13
+ import type { PanelController } from './controller.ts'
14
+ import { XTERM_CSS } from './xterm.css.ts'
15
+ import { errorMessage, resolveTerminalFontFamily, tt, type TerminalFontSource } from './helpers.ts'
16
+ import css from './panel.module.css'
17
+
18
+ /** Terminal tab props. */
19
+ export interface TerminalTabProps {
20
+ api: SshApi
21
+ /** The panel controller that owns the live host session id across mounts. */
22
+ controller: PanelController
23
+ /** Host session to reattach to on mount (survives a panel switch). */
24
+ sessionId?: string
25
+ /** Alias preselected by a "connect" action from the hosts tab. */
26
+ presetAlias?: string
27
+ /** Monotonic id of the connect request (re-applies presetAlias). */
28
+ requestId?: number
29
+ /**
30
+ * Live terminal-font setting source (issue #577). Absent in tests and
31
+ * legacy mounts: the font then comes from the CSS custom-property chain.
32
+ */
33
+ terminalFont?: TerminalFontSource
34
+ }
35
+
36
+ /** The terminal session lifecycle state shown in the status banner. */
37
+ type TerminalStatus =
38
+ | { kind: 'idle' }
39
+ | { kind: 'connecting' }
40
+ | { kind: 'connected'; alias: string }
41
+ | { kind: 'exited'; alias: string; detail?: string }
42
+ | { kind: 'error'; detail: string }
43
+
44
+ /** In-flight 2FA challenge prompts. */
45
+ interface AuthPromptState {
46
+ name: string
47
+ instructions: string
48
+ prompts: Array<{ prompt: string; echo: boolean }>
49
+ }
50
+
51
+ /** Injected-once guard for the xterm stylesheet (one tag per page load). */
52
+ let xtermCssInjected = false
53
+
54
+ function ensureXtermCss(): void {
55
+ if (xtermCssInjected || typeof document === 'undefined') return
56
+ xtermCssInjected = true
57
+ if (document.querySelector('style[data-dsh-ssh-xterm]') !== null) return
58
+ const style = document.createElement('style')
59
+ style.dataset.dshSshXterm = ''
60
+ style.textContent = XTERM_CSS
61
+ document.head.appendChild(style)
62
+ }
63
+
64
+ /** No-op source stand-in so the hook order stays stable without the prop. */
65
+ const NO_FONT_SOURCE: TerminalFontSource = {
66
+ get: () => undefined,
67
+ subscribe: () => () => undefined,
68
+ }
69
+
70
+ /** The xterm terminal view. */
71
+ export function TerminalTab({ api, controller, sessionId, presetAlias, requestId, terminalFont }: TerminalTabProps) {
72
+ const [hosts, setHosts] = useState<SshHostSummary[]>([])
73
+ const [alias, setAlias] = useState(presetAlias ?? '')
74
+ const [status, setStatus] = useState<TerminalStatus>({ kind: 'idle' })
75
+ const [authPrompt, setAuthPrompt] = useState<AuthPromptState | undefined>(undefined)
76
+ const [authInputs, setAuthInputs] = useState<string[]>([])
77
+ const containerRef = useRef<HTMLDivElement | null>(null)
78
+ const termRef = useRef<Terminal | null>(null)
79
+ const fitRef = useRef<FitAddon | null>(null)
80
+ const connRef = useRef<TerminalConnection | null>(null)
81
+ const dataSubRef = useRef<IDisposable | null>(null)
82
+ const fontSource = terminalFont ?? NO_FONT_SOURCE
83
+ const fontOverride = useSyncExternalStore(fontSource.subscribe, fontSource.get)
84
+
85
+ useEffect(() => { ensureXtermCss() }, [])
86
+
87
+ // Live re-apply a terminal-font change (issue #577): xterm re-measures
88
+ // and repaints on the options write; a refit keeps cols/rows aligned with
89
+ // the new metrics and the remote PTY learns the new size.
90
+ useEffect(() => {
91
+ const term = termRef.current
92
+ if (term === null) return
93
+ const next = resolveTerminalFontFamily(fontOverride)
94
+ if (term.options.fontFamily === next) return
95
+ term.options.fontFamily = next
96
+ fitRef.current?.fit()
97
+ connRef.current?.resize(term.cols, term.rows)
98
+ }, [fontOverride])
99
+
100
+ // Fetch the host list on tab activation.
101
+ useEffect(() => {
102
+ let disposed = false
103
+ void (async () => {
104
+ try {
105
+ const list = await api.listHosts()
106
+ if (!disposed) setHosts(list)
107
+ } catch (cause) {
108
+ if (!disposed) setStatus({ kind: 'error', detail: errorMessage(cause) })
109
+ }
110
+ })()
111
+ return () => { disposed = true }
112
+ }, [api])
113
+
114
+ // A hosts-tab connect action preselects its alias here.
115
+ useEffect(() => {
116
+ if (presetAlias !== undefined) setAlias(presetAlias)
117
+ }, [presetAlias, requestId])
118
+
119
+ /**
120
+ * Tear the view down.
121
+ * @param leave - `detach` leaves the host session alive for a reattach
122
+ * (panel switch, unmount); `close` ends it (the disconnect control).
123
+ */
124
+ const teardown = (leave: 'detach' | 'close'): void => {
125
+ setAuthPrompt(undefined)
126
+ setAuthInputs([])
127
+ const connection = connRef.current
128
+ connRef.current = null
129
+ if (connection !== null) {
130
+ connection.onReady = undefined
131
+ connection.onOutput = undefined
132
+ connection.onExit = undefined
133
+ connection.onAuthPrompt = undefined
134
+ if (leave === 'detach') connection.detach()
135
+ else connection.close()
136
+ }
137
+ // Release the xterm input subscription explicitly and dispose the
138
+ // terminal so no listener (or the terminal Renderer) survives a
139
+ // disconnect or the tab unmounting.
140
+ dataSubRef.current?.dispose()
141
+ dataSubRef.current = null
142
+ termRef.current?.dispose()
143
+ termRef.current = null
144
+ fitRef.current = null
145
+ }
146
+
147
+ // Unmount cleanup (never touches state on an unmounting component). The
148
+ // host keeps the shell alive, so returning to this tab reattaches to it.
149
+ useEffect(() => () => { teardown('detach') }, [])
150
+
151
+ // Keep the terminal fitted to its container. A window resize is only one
152
+ // trigger: the status banner appearing after connect, panel resizes, and
153
+ // sidebar toggles all change the container without a window resize, so the
154
+ // container itself is observed (otherwise the viewport keeps the pre-banner
155
+ // height and the last line is clipped below the fold). ResizeObserver may
156
+ // be absent (jsdom tests); the window listener then remains the only path.
157
+ useEffect(() => {
158
+ let lastCols = -1
159
+ let lastRows = -1
160
+ const sync = (): void => {
161
+ const term = termRef.current
162
+ const fit = fitRef.current
163
+ if (term === null || fit === null) return
164
+ fit.fit()
165
+ const conn = connRef.current
166
+ if (conn !== null && (term.cols !== lastCols || term.rows !== lastRows)) {
167
+ lastCols = term.cols
168
+ lastRows = term.rows
169
+ conn.resize(term.cols, term.rows)
170
+ }
171
+ }
172
+ window.addEventListener('resize', sync)
173
+ const container = containerRef.current
174
+ if (container === null || typeof ResizeObserver === 'undefined') {
175
+ return () => { window.removeEventListener('resize', sync) }
176
+ }
177
+ const observer = new ResizeObserver(() => { sync() })
178
+ observer.observe(container)
179
+ return () => {
180
+ observer.disconnect()
181
+ window.removeEventListener('resize', sync)
182
+ }
183
+ }, [])
184
+
185
+ /**
186
+ * Build the xterm view and bind one connection to it.
187
+ * @param open - opens the transport once the terminal has a size.
188
+ */
189
+ const startSession = (open: (cols: number, rows: number) => TerminalConnection): void => {
190
+ const container = containerRef.current
191
+ if (container === null) return
192
+ if (status.kind === 'connecting' || status.kind === 'connected') return
193
+ teardown('detach')
194
+ setStatus({ kind: 'connecting' })
195
+ const term = new Terminal({
196
+ convertEol: false,
197
+ cursorBlink: true,
198
+ fontSize: 13,
199
+ fontFamily: resolveTerminalFontFamily(fontOverride),
200
+ theme: { background: '#0b0e14', foreground: '#d8dee9', cursor: '#a3b8d0' },
201
+ })
202
+ const fit = new FitAddon()
203
+ term.loadAddon(fit)
204
+ term.open(container)
205
+ fit.fit()
206
+ const connection = open(term.cols, term.rows)
207
+ termRef.current = term
208
+ fitRef.current = fit
209
+ connRef.current = connection
210
+ let settled = false
211
+ let connectedAlias = ''
212
+ dataSubRef.current = term.onData(data => { connection.send(data) })
213
+ connection.onAuthPrompt = (name, instructions, prompts) => {
214
+ setAuthPrompt({ name, instructions, prompts })
215
+ setAuthInputs(prompts.map(() => ''))
216
+ }
217
+ connection.onReady = (id, readyAlias) => {
218
+ // Remember the host session so a later mount of this tab reattaches to
219
+ // the same shell instead of opening a second one.
220
+ connectedAlias = readyAlias
221
+ controller.setTerminalSession(id)
222
+ setAuthPrompt(undefined)
223
+ setAuthInputs([])
224
+ setStatus({ kind: 'connected', alias: readyAlias })
225
+ }
226
+ connection.onOutput = data => { term.write(data) }
227
+ connection.onExit = (_code, error) => {
228
+ if (settled) return
229
+ settled = true
230
+ setAuthPrompt(undefined)
231
+ setAuthInputs([])
232
+ dataSubRef.current?.dispose()
233
+ dataSubRef.current = null
234
+ term.options.disableStdin = true
235
+ connRef.current = null
236
+ // The session is gone: drop the id so the next mount starts fresh.
237
+ controller.clearTerminalSession()
238
+ // Keep the last output visible; input is now disabled.
239
+ setStatus({ kind: 'exited', alias: connectedAlias !== '' ? connectedAlias : alias, detail: error })
240
+ }
241
+ }
242
+
243
+ const connect = (): void => {
244
+ const target = alias
245
+ if (target === '') return
246
+ startSession((cols, rows) => api.openTerminal(target, cols, rows))
247
+ }
248
+
249
+ // Reattach to a host session that outlived this view (panel switch or a
250
+ // remount of the page). The host replays its scrollback before ready, so
251
+ // the terminal comes back with its history instead of a blank screen.
252
+ const reattachedRef = useRef<string | undefined>(undefined)
253
+ useEffect(() => {
254
+ if (sessionId === undefined || connRef.current !== null) return
255
+ if (reattachedRef.current === sessionId) return
256
+ reattachedRef.current = sessionId
257
+ startSession((cols, rows) => api.attachTerminal(sessionId, cols, rows))
258
+ }, [sessionId])
259
+
260
+ const disconnect = (): void => {
261
+ teardown('close')
262
+ controller.clearTerminalSession()
263
+ setStatus({ kind: 'idle' })
264
+ }
265
+
266
+ const submitAuth = (e?: React.FormEvent): void => {
267
+ e?.preventDefault()
268
+ if (connRef.current === null || authPrompt === undefined) return
269
+ connRef.current.sendAuthResponse(authInputs)
270
+ setAuthPrompt(undefined)
271
+ }
272
+
273
+ const active = status.kind === 'connecting' || status.kind === 'connected'
274
+
275
+ return (
276
+ <div className={css.termBody}>
277
+ <div className={css.controls}>
278
+ <select className={css.input} value={alias} onChange={event => { setAlias(event.target.value) }}>
279
+ <option value="">{tt('terminal.selectHost')}</option>
280
+ {hosts.map(host => <option key={host.alias} value={host.alias}>{host.alias} ({host.host})</option>)}
281
+ </select>
282
+ <button type="button" className={css.primaryButton} disabled={alias === '' || active} onClick={connect}>{tt('terminal.connect')}</button>
283
+ <button type="button" className={css.ghostButton} disabled={!active} onClick={disconnect}>{tt('terminal.disconnect')}</button>
284
+ </div>
285
+ {status.kind === 'connecting' && <div className={css.banner} data-kind="info">{tt('terminal.connecting')}</div>}
286
+ {status.kind === 'connected' && <div className={css.banner} data-kind="ok">{tt('terminal.ready', { alias: status.alias })}</div>}
287
+ {status.kind === 'exited' && (
288
+ <div className={css.banner} data-kind="info">{tt('terminal.exited', { alias: status.alias })}{status.detail !== undefined ? ' (' + status.detail + ')' : ''}</div>
289
+ )}
290
+ {status.kind === 'error' && <div className={css.banner} data-kind="error">{tt('terminal.error', { error: status.detail })}</div>}
291
+ <div className={css.termWrap}>
292
+ <div ref={containerRef} className={css.termContainer} data-dsh-part="terminal" />
293
+ {status.kind === 'idle' && (
294
+ <div className={css.termPlaceholder}>{hosts.length === 0 ? tt('hosts.empty') : tt('terminal.placeholder')}</div>
295
+ )}
296
+ {authPrompt !== undefined && (
297
+ <div className={css.modalBackdrop} style={{ position: 'absolute', zIndex: 10 }}>
298
+ <form className={css.modalCard} style={{ maxWidth: 420 }} onSubmit={submitAuth}>
299
+ <div className={css.modalHeader}>
300
+ <h3 className={css.modalTitle}>{authPrompt.name || tt('terminal.auth.title')}</h3>
301
+ </div>
302
+ <p className={css.hint}>{authPrompt.instructions || tt('terminal.auth.hint')}</p>
303
+ {authPrompt.prompts.map((p, idx) => (
304
+ <label key={idx} className={css.field}>
305
+ <span className={css.fieldLabel}>{p.prompt.trim() || tt('terminal.auth.title')}</span>
306
+ <input
307
+ autoFocus={idx === 0}
308
+ className={css.input}
309
+ type={p.echo ? 'text' : 'password'}
310
+ placeholder={tt('terminal.auth.placeholder')}
311
+ value={authInputs[idx] ?? ''}
312
+ onChange={event => {
313
+ const next = [...authInputs]
314
+ next[idx] = event.target.value
315
+ setAuthInputs(next)
316
+ }}
317
+ />
318
+ </label>
319
+ ))}
320
+ <div className={css.modalFooter}>
321
+ <button type="button" className={css.ghostButton} onClick={disconnect}>{tt('terminal.auth.cancel')}</button>
322
+ <button type="submit" className={css.primaryButton}>{tt('terminal.auth.submit')}</button>
323
+ </div>
324
+ </form>
325
+ </div>
326
+ )}
327
+ </div>
328
+ </div>
329
+ )
330
+ }
@@ -0,0 +1,232 @@
1
+ /**
2
+ * Transfer tab: upload/download one file with progress, plus a toggleable
3
+ * remote directory browser (api.ls) whose file rows fill the remote path
4
+ * input and whose directory rows navigate.
5
+ */
6
+ import { useEffect, useRef, useState, type ChangeEvent } from 'react'
7
+ import type { SshApi } from '../api.ts'
8
+ import type { RemoteDirEntry, SshHostSummary, TransferProgress } from '../../protocol.ts'
9
+ import { errorMessage, tt } from './helpers.ts'
10
+ import css from './panel.module.css'
11
+
12
+ /** Transfer tab props. */
13
+ export interface TransferTabProps {
14
+ api: SshApi
15
+ }
16
+
17
+ /** One in-flight transfer (drives the progress bar). */
18
+ interface TransferState {
19
+ kind: 'upload' | 'download'
20
+ phase: TransferProgress['phase']
21
+ percent: number
22
+ speedBps?: number
23
+ file: string
24
+ }
25
+
26
+ /** The last transfer's outcome line. */
27
+ type TransferStatus = { kind: 'ok'; bytes: number } | { kind: 'error'; error: string }
28
+
29
+ /** Join a directory path with a child entry name. */
30
+ function joinRemotePath(dir: string, name: string): string {
31
+ const base = dir.endsWith('/') ? dir : dir + '/'
32
+ return base + name
33
+ }
34
+
35
+ /** Parent path of a remote directory ('/' stays '/'). */
36
+ function parentOf(dir: string): string {
37
+ const trimmed = dir.replace(/\/+$/, '')
38
+ const index = trimmed.lastIndexOf('/')
39
+ if (index <= 0) return '/'
40
+ return trimmed.slice(0, index)
41
+ }
42
+
43
+ /** Human byte sizes through the transfer.* locale templates. */
44
+ function formatBytes(bytes: number): string {
45
+ if (bytes < 1024) return tt('transfer.bytes', { value: bytes })
46
+ if (bytes < 1024 * 1024) return tt('transfer.kib', { value: (bytes / 1024).toFixed(1) })
47
+ if (bytes < 1024 * 1024 * 1024) return tt('transfer.mib', { value: (bytes / (1024 * 1024)).toFixed(1) })
48
+ return tt('transfer.gib', { value: (bytes / (1024 * 1024 * 1024)).toFixed(1) })
49
+ }
50
+
51
+ /** The upload/download tab. */
52
+ export function TransferTab({ api }: TransferTabProps) {
53
+ const [hosts, setHosts] = useState<SshHostSummary[]>([])
54
+ const [listError, setListError] = useState<string | null>(null)
55
+ const [alias, setAlias] = useState('')
56
+ const [remotePath, setRemotePath] = useState('')
57
+ const [browseOpen, setBrowseOpen] = useState(false)
58
+ const [browseDir, setBrowseDir] = useState('/')
59
+ const [entries, setEntries] = useState<RemoteDirEntry[]>([])
60
+ const [browsing, setBrowsing] = useState(false)
61
+ const [transfer, setTransfer] = useState<TransferState | null>(null)
62
+ const [status, setStatus] = useState<TransferStatus | null>(null)
63
+ const fileRef = useRef<HTMLInputElement | null>(null)
64
+ const seqRef = useRef(0)
65
+
66
+ useEffect(() => {
67
+ let disposed = false
68
+ void (async () => {
69
+ try {
70
+ const list = await api.listHosts()
71
+ if (!disposed) setHosts(list)
72
+ } catch (cause) {
73
+ if (!disposed) setListError(errorMessage(cause))
74
+ }
75
+ })()
76
+ return () => { disposed = true }
77
+ }, [api])
78
+
79
+ const loadDir = async (path: string): Promise<void> => {
80
+ if (alias === '') return
81
+ const seq = ++seqRef.current
82
+ setBrowsing(true)
83
+ try {
84
+ const list = await api.ls(alias, path)
85
+ if (seq !== seqRef.current) return
86
+ const sorted = [...list].sort((a, b) => {
87
+ if (a.type !== b.type) return a.type === 'dir' ? -1 : 1
88
+ return a.name.localeCompare(b.name)
89
+ })
90
+ setEntries(sorted)
91
+ setBrowseDir(path)
92
+ setListError(null)
93
+ } catch (cause) {
94
+ if (seq === seqRef.current) setListError(errorMessage(cause))
95
+ } finally {
96
+ if (seq === seqRef.current) setBrowsing(false)
97
+ }
98
+ }
99
+
100
+ const openBrowse = (): void => {
101
+ if (alias === '') return
102
+ setBrowseOpen(true)
103
+ const path = remotePath.trim() === '' ? '/' : remotePath.trim()
104
+ void loadDir(path)
105
+ }
106
+
107
+ const handleFile = async (event: ChangeEvent<HTMLInputElement>): Promise<void> => {
108
+ const file = event.target.files?.[0]
109
+ event.target.value = ''
110
+ if (file === undefined || alias === '' || remotePath.trim() === '' || transfer !== null) return
111
+ setStatus(null)
112
+ setTransfer({ kind: 'upload', phase: 'connecting', percent: 0, file: file.name })
113
+ try {
114
+ const outcome = await api.uploadFile(file, alias, remotePath.trim(), progress => {
115
+ setTransfer(prev => prev === null ? prev : {
116
+ kind: 'upload',
117
+ phase: progress.phase,
118
+ percent: progress.percent,
119
+ speedBps: progress.speedBps,
120
+ file: progress.file,
121
+ })
122
+ })
123
+ setStatus({ kind: 'ok', bytes: outcome.transferredBytes })
124
+ } catch (cause) {
125
+ setStatus({ kind: 'error', error: errorMessage(cause) })
126
+ } finally {
127
+ setTransfer(null)
128
+ }
129
+ }
130
+
131
+ const handleDownload = async (): Promise<void> => {
132
+ if (alias === '' || remotePath.trim() === '' || transfer !== null) return
133
+ setStatus(null)
134
+ setTransfer({ kind: 'download', phase: 'connecting', percent: 0, file: remotePath.trim() })
135
+ try {
136
+ const result = await api.downloadFile(alias, remotePath.trim(), progress => {
137
+ setTransfer(prev => prev === null ? prev : {
138
+ kind: 'download',
139
+ phase: progress.phase,
140
+ percent: progress.percent,
141
+ speedBps: progress.speedBps,
142
+ file: progress.file,
143
+ })
144
+ })
145
+ // Streamed downloads (File System Access API) were already saved; the
146
+ // Blob fallback triggers a browser save here.
147
+ if (!result.streamed && result.blob !== undefined) {
148
+ const url = URL.createObjectURL(result.blob)
149
+ const anchor = document.createElement('a')
150
+ anchor.href = url
151
+ anchor.download = result.filename
152
+ document.body.appendChild(anchor)
153
+ anchor.click()
154
+ anchor.remove()
155
+ // Defer the revoke: some engines need the URL alive past the click.
156
+ setTimeout(() => { URL.revokeObjectURL(url) }, 10_000)
157
+ }
158
+ setStatus({ kind: 'ok', bytes: result.bytes })
159
+ } catch (cause) {
160
+ setStatus({ kind: 'error', error: errorMessage(cause) })
161
+ } finally {
162
+ setTransfer(null)
163
+ }
164
+ }
165
+
166
+ const ready = alias !== '' && remotePath.trim() !== '' && transfer === null
167
+
168
+ return (
169
+ <div className={css.tabBody}>
170
+ <div className={css.controls}>
171
+ <select className={css.input} value={alias} onChange={event => { setAlias(event.target.value) }}>
172
+ <option value="">{tt('transfer.selectHost')}</option>
173
+ {hosts.map(host => <option key={host.alias} value={host.alias}>{host.alias} ({host.host})</option>)}
174
+ </select>
175
+ <input className={css.input} placeholder={tt('transfer.remotePathHint')} value={remotePath} onChange={event => { setRemotePath(event.target.value) }} />
176
+ <button type="button" className={css.ghostButton} disabled={alias === ''} onClick={openBrowse}>{tt('transfer.browseRemote')}</button>
177
+ <div className={css.toolbarSpacer} />
178
+ <button type="button" className={css.primaryButton} disabled={!ready} onClick={() => { fileRef.current?.click() }}>{tt('transfer.upload')}</button>
179
+ <button type="button" className={css.ghostButton} disabled={!ready} onClick={() => { void handleDownload() }}>{tt('transfer.download')}</button>
180
+ <input ref={fileRef} type="file" className={css.hiddenFile} onChange={event => { void handleFile(event) }} />
181
+ </div>
182
+ {listError !== null && <div className={css.banner} data-kind="error">{tt('common.error', { error: listError })}</div>}
183
+ {browseOpen && (
184
+ <div className={css.browsePanel}>
185
+ <div className={css.browseHeader}>
186
+ <span className={css.browsePath}>{browseDir}</span>
187
+ <button type="button" className={css.linkButton} disabled={browsing} onClick={() => { void loadDir(browseDir) }}>{tt('transfer.refresh')}</button>
188
+ </div>
189
+ <div className={css.browseList}>
190
+ {browseDir !== '/' && (
191
+ <button type="button" className={css.dirRow} data-up onClick={() => { void loadDir(parentOf(browseDir)) }}>
192
+ <span className={css.dirName}>{tt('transfer.upLevel')}</span>
193
+ <span className={css.dirType} />
194
+ <span className={css.dirSize} />
195
+ </button>
196
+ )}
197
+ {entries.map(entry => (
198
+ <button key={entry.name} type="button" className={css.dirRow} data-type={entry.type} onClick={() => {
199
+ if (entry.type === 'dir') {
200
+ void loadDir(joinRemotePath(browseDir, entry.name))
201
+ } else {
202
+ setRemotePath(joinRemotePath(browseDir, entry.name))
203
+ }
204
+ }}>
205
+ <span className={css.dirName}>{entry.name}</span>
206
+ <span className={css.dirType}>{entry.type === 'dir' ? '[' + tt('transfer.dir') + ']' : entry.type === 'file' ? '[' + tt('transfer.file') + ']' : ''}</span>
207
+ <span className={css.dirSize}>{formatBytes(entry.size)}</span>
208
+ </button>
209
+ ))}
210
+ </div>
211
+ </div>
212
+ )}
213
+ {transfer !== null && (
214
+ <div className={css.transferBlock}>
215
+ <div className={css.progressMeta}>
216
+ <span>{transfer.kind === 'upload' ? tt('transfer.uploading', { file: transfer.file }) : tt('transfer.downloading')}</span>
217
+ <span>{tt('transfer.percent', { value: Math.round(transfer.percent) })}</span>
218
+ {transfer.speedBps !== undefined && transfer.phase === 'transferring' && <span>{tt('transfer.speed', { value: formatBytes(transfer.speedBps) })}</span>}
219
+ </div>
220
+ <div className={css.progressTrack}>
221
+ <div className={css.progressBar} style={{ width: Math.min(100, Math.max(0, transfer.percent)) + '%' }} />
222
+ </div>
223
+ </div>
224
+ )}
225
+ {status !== null && (
226
+ <div className={css.banner} data-kind={status.kind}>
227
+ {status.kind === 'ok' ? tt('transfer.done', { bytes: status.bytes }) : tt('transfer.failed', { error: status.error })}
228
+ </div>
229
+ )}
230
+ </div>
231
+ )
232
+ }