@fish-under-sea/dsh-ssh-fish 1.0.1 → 1.1.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 (41) hide show
  1. package/NOTICE +1 -1
  2. package/README.en.md +5 -5
  3. package/README.md +5 -5
  4. package/README.zh.md +5 -5
  5. package/lib/client.js +783 -170
  6. package/lib/client.js.map +1 -1
  7. package/lib/index.js +128 -14
  8. package/lib/types/client/api.d.ts +21 -0
  9. package/lib/types/client/locales.d.ts +13 -2
  10. package/lib/types/client/panel/TerminalTab.d.ts +12 -7
  11. package/lib/types/client/panel/controller.d.ts +185 -21
  12. package/lib/types/engine/connection-pool.d.ts +52 -1
  13. package/lib/types/engine.d.ts +7 -0
  14. package/lib/types/index.d.ts +10 -0
  15. package/lib/types/loopback.d.ts +41 -1
  16. package/lib/types/protocol.d.ts +18 -1
  17. package/lib/types/store.d.ts +7 -0
  18. package/lib/types/tool-surface.d.ts +1 -0
  19. package/lib/types/tools.d.ts +1 -0
  20. package/locale/en.json +6 -0
  21. package/locale/zh.json +6 -0
  22. package/package.json +24 -21
  23. package/src/client/api.ts +70 -0
  24. package/src/client/index.ts +1 -2
  25. package/src/client/locales.ts +26 -4
  26. package/src/client/panel/HostFormDialog.tsx +16 -2
  27. package/src/client/panel/HostsTab.tsx +3 -0
  28. package/src/client/panel/SshPanel.tsx +7 -15
  29. package/src/client/panel/TerminalTab.tsx +371 -151
  30. package/src/client/panel/controller.ts +370 -30
  31. package/src/client/panel/panel.module.css +108 -0
  32. package/src/client/settings-binding.ts +0 -1
  33. package/src/engine/connection-pool.ts +96 -4
  34. package/src/engine.ts +10 -0
  35. package/src/index.ts +16 -1
  36. package/src/loopback.ts +57 -1
  37. package/src/protocol.ts +18 -1
  38. package/src/routes.ts +4 -1
  39. package/src/store.ts +26 -0
  40. package/src/tool-surface.ts +1 -0
  41. package/src/tools.ts +9 -4
@@ -1,16 +1,27 @@
1
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).
2
+ * Terminal tab: ONE xterm.js view over the host's WebSocket terminal route,
3
+ * with a tab strip over host-side PTY sessions.
4
+ *
5
+ * Session ownership stays on the Host (\`src/engine/terminal-sessions.ts\`): a
6
+ * view that is not showing a session detaches its socket, and the host keeps
7
+ * the shell alive plus a bounded scrollback that a reattach replays. That is
8
+ * what lets the panel hold several tabs while this component keeps a single
9
+ * xterm instance: switching a tab rebinds the one terminal instead of stacking
10
+ * terminals, and every tab's alias, host session id, status and pending
11
+ * keyboard-interactive challenge lives in the panel controller because the
12
+ * layout unmounts this page whenever another panel is selected.
13
+ *
14
+ * A tab that has NOT reported its session id yet cannot be detached (there is
15
+ * no id to reattach with), so switching away or unmounting hands the socket to
16
+ * the controller, which applies "detach" or "close" the moment the id arrives.
17
+ * That is the orphan-free rule: no host PTY is ever left without an owner.
7
18
  */
8
- import { useEffect, useRef, useState, useSyncExternalStore } from 'react'
19
+ import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react'
9
20
  import { Terminal, type IDisposable } from '@xterm/xterm'
10
21
  import { FitAddon } from '@xterm/addon-fit'
11
22
  import type { SshApi, TerminalConnection } from '../api.ts'
12
23
  import type { SshHostSummary } from '../../protocol.ts'
13
- import type { PanelController } from './controller.ts'
24
+ import type { PanelController, TerminalTabRecord } from './controller.ts'
14
25
  import { XTERM_CSS } from './xterm.css.ts'
15
26
  import { errorMessage, resolveTerminalFontFamily, tt, type TerminalFontSource } from './helpers.ts'
16
27
  import css from './panel.module.css'
@@ -18,14 +29,10 @@ import css from './panel.module.css'
18
29
  /** Terminal tab props. */
19
30
  export interface TerminalTabProps {
20
31
  api: SshApi
21
- /** The panel controller that owns the live host session id across mounts. */
32
+ /** The panel controller that owns the tabs and their host session ids. */
22
33
  controller: PanelController
23
- /** Host session to reattach to on mount (survives a panel switch). */
24
- sessionId?: string
25
34
  /** Alias preselected by a "connect" action from the hosts tab. */
26
35
  presetAlias?: string
27
- /** Monotonic id of the connect request (re-applies presetAlias). */
28
- requestId?: number
29
36
  /**
30
37
  * Live terminal-font setting source (issue #577). Absent in tests and
31
38
  * legacy mounts: the font then comes from the CSS custom-property chain.
@@ -33,19 +40,10 @@ export interface TerminalTabProps {
33
40
  terminalFont?: TerminalFontSource
34
41
  }
35
42
 
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 }>
43
+ /** The socket currently bound to the single terminal view. */
44
+ interface BoundLink {
45
+ tabId: string
46
+ connection: TerminalConnection
49
47
  }
50
48
 
51
49
  /** Injected-once guard for the xterm stylesheet (one tag per page load). */
@@ -67,20 +65,56 @@ const NO_FONT_SOURCE: TerminalFontSource = {
67
65
  subscribe: () => () => undefined,
68
66
  }
69
67
 
70
- /** The xterm terminal view. */
71
- export function TerminalTab({ api, controller, sessionId, presetAlias, requestId, terminalFont }: TerminalTabProps) {
68
+ /**
69
+ * The state word a tab shows in the strip, or undefined when it is simply up.
70
+ * A pending challenge wins over the lifecycle word: it is the one state the
71
+ * user has to act on.
72
+ * @param tab - the tab record.
73
+ * @returns the short label, or undefined for a connected tab.
74
+ */
75
+ function tabStateLabel(tab: TerminalTabRecord): string | undefined {
76
+ if (tab.authPrompt !== undefined) return tt('terminal.authPending')
77
+ if (tab.status === 'connecting') return tt('terminal.connecting')
78
+ if (tab.status === 'exited') return tt('terminal.tabExited')
79
+ // A close that never reached the host keeps a live session, so it is not an
80
+ // `error` tab; it still has to be visible without making that tab current.
81
+ if (tab.closeError !== undefined) return tt('terminal.tabError')
82
+ if (tab.status === 'error') return tt('terminal.tabError')
83
+ return undefined
84
+ }
85
+
86
+ /**
87
+ * Whether the visible challenge form may answer on the bound socket: the form
88
+ * and the socket must belong to the same tab. Both are read at submit time, and
89
+ * the window between a tab switch's commit and the effect that rebinds the
90
+ * socket is exactly when they can disagree.
91
+ * @param linkTabId - the tab the bound socket belongs to.
92
+ * @param formTabId - the tab whose challenge form is on screen.
93
+ */
94
+ export function challengeBelongsToLink(linkTabId: string | undefined, formTabId: string | undefined): boolean {
95
+ return linkTabId !== undefined && linkTabId === formTabId
96
+ }
97
+
98
+ /** The terminal view with its tab strip. */
99
+ export function TerminalTab({ api, controller, presetAlias, terminalFont }: TerminalTabProps) {
100
+ const { terminalTabs, activeTerminalTabId, draftAlias } = useSyncExternalStore(
101
+ useCallback(listener => controller.subscribe(listener), [controller]),
102
+ useCallback(() => controller.getSnapshot(), [controller]),
103
+ )
72
104
  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[]>([])
105
+ const [listError, setListError] = useState<string | undefined>(undefined)
77
106
  const containerRef = useRef<HTMLDivElement | null>(null)
78
107
  const termRef = useRef<Terminal | null>(null)
79
108
  const fitRef = useRef<FitAddon | null>(null)
80
- const connRef = useRef<TerminalConnection | null>(null)
109
+ const linkRef = useRef<BoundLink | null>(null)
81
110
  const dataSubRef = useRef<IDisposable | null>(null)
111
+ /** Tab whose screen the terminal currently holds. */
112
+ const renderedRef = useRef<string | undefined>(undefined)
113
+ /** Tabs with a background close in flight, so one click cannot open two. */
114
+ const closingRef = useRef<Set<string>>(new Set())
82
115
  const fontSource = terminalFont ?? NO_FONT_SOURCE
83
116
  const fontOverride = useSyncExternalStore(fontSource.subscribe, fontSource.get)
117
+ const activeTab = terminalTabs.find(tab => tab.id === activeTerminalTabId)
84
118
 
85
119
  useEffect(() => { ensureXtermCss() }, [])
86
120
 
@@ -94,7 +128,8 @@ export function TerminalTab({ api, controller, sessionId, presetAlias, requestId
94
128
  if (term.options.fontFamily === next) return
95
129
  term.options.fontFamily = next
96
130
  fitRef.current?.fit()
97
- connRef.current?.resize(term.cols, term.rows)
131
+ const link = linkRef.current
132
+ if (link !== null) link.connection.resize(term.cols, term.rows)
98
133
  }, [fontOverride])
99
134
 
100
135
  // Fetch the host list on tab activation.
@@ -105,48 +140,17 @@ export function TerminalTab({ api, controller, sessionId, presetAlias, requestId
105
140
  const list = await api.listHosts()
106
141
  if (!disposed) setHosts(list)
107
142
  } catch (cause) {
108
- if (!disposed) setStatus({ kind: 'error', detail: errorMessage(cause) })
143
+ if (!disposed) setListError(errorMessage(cause))
109
144
  }
110
145
  })()
111
146
  return () => { disposed = true }
112
147
  }, [api])
113
148
 
114
- // A hosts-tab connect action preselects its alias here.
149
+ // A hosts-tab connect action preselects its alias in the toolbar.
115
150
  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') }, [])
151
+ if (presetAlias === undefined || presetAlias === '') return
152
+ controller.setDraftAlias(presetAlias)
153
+ }, [presetAlias, controller])
150
154
 
151
155
  // Keep the terminal fitted to its container. A window resize is only one
152
156
  // trigger: the status banner appearing after connect, panel resizes, and
@@ -162,11 +166,11 @@ export function TerminalTab({ api, controller, sessionId, presetAlias, requestId
162
166
  const fit = fitRef.current
163
167
  if (term === null || fit === null) return
164
168
  fit.fit()
165
- const conn = connRef.current
166
- if (conn !== null && (term.cols !== lastCols || term.rows !== lastRows)) {
169
+ const link = linkRef.current
170
+ if (link !== null && (term.cols !== lastCols || term.rows !== lastRows)) {
167
171
  lastCols = term.cols
168
172
  lastRows = term.rows
169
- conn.resize(term.cols, term.rows)
173
+ link.connection.resize(term.cols, term.rows)
170
174
  }
171
175
  }
172
176
  window.addEventListener('resize', sync)
@@ -182,16 +186,13 @@ export function TerminalTab({ api, controller, sessionId, presetAlias, requestId
182
186
  }
183
187
  }, [])
184
188
 
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 => {
189
+ /** Build the one xterm instance and its input subscription, once. */
190
+ const ensureTerm = (): { term: Terminal; fit: FitAddon } | undefined => {
191
+ const openTerm = termRef.current
192
+ const openFit = fitRef.current
193
+ if (openTerm !== null && openFit !== null) return { term: openTerm, fit: openFit }
190
194
  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
+ if (container === null) return undefined
195
196
  const term = new Terminal({
196
197
  convertEol: false,
197
198
  cursorBlink: true,
@@ -203,104 +204,327 @@ export function TerminalTab({ api, controller, sessionId, presetAlias, requestId
203
204
  term.loadAddon(fit)
204
205
  term.open(container)
205
206
  fit.fit()
206
- const connection = open(term.cols, term.rows)
207
207
  termRef.current = term
208
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(() => ''))
209
+ // One input subscription for the terminal, routed to whichever tab is
210
+ // bound: rebinding a tab must not stack listeners on the xterm.
211
+ dataSubRef.current = term.onData(data => { linkRef.current?.connection.send(data) })
212
+ return { term, fit }
213
+ }
214
+
215
+ /** Dispose the xterm and its subscription (no tabs left, or unmount). */
216
+ const disposeTerm = (): void => {
217
+ dataSubRef.current?.dispose()
218
+ dataSubRef.current = null
219
+ termRef.current?.dispose()
220
+ termRef.current = null
221
+ fitRef.current = null
222
+ renderedRef.current = undefined
223
+ }
224
+
225
+ /** Release the bound socket: detach it, or adopt it while it connects. */
226
+ const releaseLink = (): void => {
227
+ const link = linkRef.current
228
+ linkRef.current = null
229
+ if (link === null) return
230
+ const connection = link.connection
231
+ connection.onReady = undefined
232
+ connection.onOutput = undefined
233
+ connection.onExit = undefined
234
+ connection.onAuthPrompt = undefined
235
+ const tab = controller.terminalTab(link.tabId)
236
+ if (tab === undefined) {
237
+ // The tab was closed while this socket was already releasing: nothing can
238
+ // reattach to it, so the session has to end rather than be detached into
239
+ // an ownerless PTY.
240
+ controller.adoptTerminalLink(link.tabId, connection, 'close')
241
+ return
216
242
  }
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 })
243
+ if (tab.status === 'connecting') {
244
+ // No session id yet, so a detach frame would end nothing: the host would
245
+ // keep connecting into a session nobody can attach to. Hand it to the
246
+ // controller, which detaches (or closes) the moment the id arrives.
247
+ controller.adoptTerminalLink(link.tabId, connection, 'detach')
248
+ return
249
+ }
250
+ connection.detach()
251
+ }
252
+
253
+ /**
254
+ * Whether the single terminal still shows another tab. A terminal that was
255
+ * just created (or disposed) holds nothing, so it needs no clear; every other
256
+ * rebind must start from a blank screen or the previous tab's output and
257
+ * cursor stay on it.
258
+ * @param tabId - the tab about to be bound.
259
+ */
260
+ const needsScreenClear = (tabId: string): boolean => {
261
+ const rendered = renderedRef.current
262
+ return rendered !== undefined && rendered !== tabId
263
+ }
264
+
265
+ /**
266
+ * Draw a retained screen the host cannot replay (adopted output, or a tab
267
+ * whose session is gone) and mark the terminal as this tab's.
268
+ * @param term - the single terminal.
269
+ * @param tabId - the tab that owns the text.
270
+ * @param retained - the text to draw; empty leaves a blank screen.
271
+ */
272
+ const drawRetained = (term: Terminal, tabId: string, retained: string): void => {
273
+ if (needsScreenClear(tabId)) term.reset()
274
+ if (retained !== '') term.write(retained)
275
+ renderedRef.current = tabId
276
+ }
277
+
278
+ /** Bind one connection's frames onto the single terminal. */
279
+ const bindConnection = (tab: TerminalTabRecord, connection: TerminalConnection): void => {
280
+ const view = ensureTerm()
281
+ if (view === undefined) return
282
+ linkRef.current = { tabId: tab.id, connection }
283
+ renderedRef.current = tab.id
284
+ view.term.options.disableStdin = false
285
+ connection.onReady = (sessionId) => {
286
+ controller.clearTerminalAuthPrompt(tab.id)
287
+ controller.readyTerminalTab(tab.id, sessionId)
288
+ }
289
+ connection.onOutput = (data) => {
290
+ view.term.write(data)
291
+ controller.appendTerminalOutput(tab.id, data)
292
+ }
293
+ connection.onAuthPrompt = (name, instructions, prompts) => {
294
+ // The challenge and the answer being typed live on the tab record: a
295
+ // prompt for another tab must not touch the field on screen, and two
296
+ // challenges must never share one draft.
297
+ controller.setTerminalAuthPrompt(tab.id, { name, instructions, prompts })
225
298
  }
226
- connection.onOutput = data => { term.write(data) }
227
299
  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 })
300
+ const bound = linkRef.current
301
+ const wasBound = bound !== null && bound.connection === connection
302
+ if (wasBound) linkRef.current = null
303
+ connection.onReady = undefined
304
+ connection.onOutput = undefined
305
+ connection.onAuthPrompt = undefined
306
+ connection.onExit = undefined
307
+ view.term.options.disableStdin = true
308
+ if (!wasBound) return
309
+ // The tab keeps its screen and its place; only the dead id is dropped.
310
+ controller.exitTerminalTab(tab.id, error)
240
311
  }
241
312
  }
242
313
 
243
- const connect = (): void => {
244
- const target = alias
245
- if (target === '') return
246
- startSession((cols, rows) => api.openTerminal(target, cols, rows))
314
+ /** Bind the tab the controller says is current, without opening a second PTY. */
315
+ const bindTab = (tab: TerminalTabRecord): void => {
316
+ const view = ensureTerm()
317
+ if (view === undefined) return
318
+ if (tab.status === 'connecting' || (tab.status === 'connected' && tab.sessionId !== undefined)) {
319
+ const adopted = controller.reclaimTerminalLink(tab.id)
320
+ if (adopted !== undefined) {
321
+ // The socket kept reporting while the tab was in the background, so its
322
+ // retained screen holds that window; draw it before the live frames
323
+ // resume rather than showing a gap.
324
+ drawRetained(view.term, tab.id, controller.readTerminalOutput(tab.id))
325
+ bindConnection(tab, adopted)
326
+ return
327
+ }
328
+ }
329
+ if (tab.status === 'connecting') {
330
+ // A tab that opens a socket starts from a blank screen: without this the
331
+ // previous tab's output stays on the one terminal until the host speaks.
332
+ drawRetained(view.term, tab.id, '')
333
+ controller.clearTerminalOutput(tab.id)
334
+ bindConnection(tab, api.openTerminal(tab.alias, view.term.cols, view.term.rows))
335
+ return
336
+ }
337
+ if (tab.status === 'connected' && tab.sessionId !== undefined) {
338
+ const sessionId = tab.sessionId
339
+ if (needsScreenClear(tab.id)) {
340
+ // The host replays its scrollback on attach, so the screen starts empty
341
+ // and the retained copy is replaced by that replay.
342
+ view.term.reset()
343
+ controller.clearTerminalOutput(tab.id)
344
+ renderedRef.current = tab.id
345
+ }
346
+ bindConnection(tab, api.attachTerminal(sessionId, view.term.cols, view.term.rows))
347
+ return
348
+ }
349
+ // exited / error: no live session to attach to. The tab keeps the screen it
350
+ // last showed instead of an empty terminal under a placeholder.
351
+ view.term.options.disableStdin = true
352
+ if (renderedRef.current === tab.id) return
353
+ drawRetained(view.term, tab.id, controller.readTerminalOutput(tab.id))
247
354
  }
248
355
 
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)
356
+ // Bind the shown tab, releasing whatever the previous one held.
253
357
  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])
358
+ const bound = linkRef.current
359
+ if (bound !== null && bound.tabId === activeTerminalTabId) return
360
+ releaseLink()
361
+ if (activeTerminalTabId === undefined) {
362
+ disposeTerm()
363
+ return
364
+ }
365
+ const tab = controller.terminalTab(activeTerminalTabId)
366
+ if (tab === undefined) return
367
+ bindTab(tab)
368
+ // Only the tab identity and its lifecycle decide a rebind: output and auth
369
+ // frames update the controller without touching the terminal geometry.
370
+ // eslint-disable-next-line react-hooks/exhaustive-deps
371
+ }, [activeTerminalTabId, activeTab?.status, activeTab?.sessionId])
372
+
373
+ // Unmount cleanup: the host keeps every shell alive, so returning to this
374
+ // panel reattaches by session id and replays the scrollback. A connection
375
+ // that has not reported its id yet is adopted rather than dropped.
376
+ useEffect(() => () => {
377
+ releaseLink()
378
+ disposeTerm()
379
+ // eslint-disable-next-line react-hooks/exhaustive-deps
380
+ }, [])
259
381
 
260
- const disconnect = (): void => {
261
- teardown('close')
262
- controller.clearTerminalSession()
263
- setStatus({ kind: 'idle' })
382
+ /** Open a tab on the toolbar's host (the "+"/Connect control). */
383
+ const connect = (): void => {
384
+ const target = draftAlias
385
+ if (target === '') return
386
+ controller.openTerminalTab(target)
387
+ }
388
+
389
+ /**
390
+ * Close one tab. The shown one ends its session over its own socket; a
391
+ * background tab is ended through one short-lived attach, and a close that
392
+ * cannot be delivered keeps the tab instead of pretending it is gone.
393
+ * @param tabId - the tab to close.
394
+ */
395
+ const closeTab = (tabId: string): void => {
396
+ const tab = controller.terminalTab(tabId)
397
+ if (tab === undefined) return
398
+ const bound = linkRef.current
399
+ if (bound !== null && bound.tabId === tabId) {
400
+ linkRef.current = null
401
+ const connection = bound.connection
402
+ connection.onReady = undefined
403
+ connection.onOutput = undefined
404
+ connection.onExit = undefined
405
+ connection.onAuthPrompt = undefined
406
+ if (tab.status === 'connecting') controller.adoptTerminalLink(tabId, connection, 'close')
407
+ else connection.close()
408
+ controller.closeTerminalTab(tabId)
409
+ return
410
+ }
411
+ if (tab.status === 'connected' && tab.sessionId !== undefined) {
412
+ // One attempt at a time: a second click while the attach is in flight
413
+ // would open another socket for the same session and could report the
414
+ // later outcome over the earlier one.
415
+ if (closingRef.current.has(tabId)) return
416
+ closingRef.current.add(tabId)
417
+ const sessionId = tab.sessionId
418
+ void (async () => {
419
+ try {
420
+ const gone = await api.closeTerminalSession(sessionId)
421
+ if (gone) {
422
+ controller.closeTerminalTab(tabId)
423
+ return
424
+ }
425
+ // Not delivered: the session may still be running, so the tab stays
426
+ // with its session id. Recovery is the same control (retry) or the
427
+ // tab in front, whose own socket can end the shell for certain.
428
+ controller.markTerminalCloseFailed(tabId, 'undelivered')
429
+ } finally {
430
+ closingRef.current.delete(tabId)
431
+ }
432
+ })()
433
+ return
434
+ }
435
+ controller.closeTerminalTab(tabId)
264
436
  }
265
437
 
266
438
  const submitAuth = (e?: React.FormEvent): void => {
267
439
  e?.preventDefault()
268
- if (connRef.current === null || authPrompt === undefined) return
269
- connRef.current.sendAuthResponse(authInputs)
270
- setAuthPrompt(undefined)
440
+ const link = linkRef.current
441
+ const tab = activeTab
442
+ if (link === null || tab === undefined || tab.authPrompt === undefined) return
443
+ // The form and the socket must agree on the tab. A submit that arrives in
444
+ // the window between a tab switch and the rebind would otherwise carry this
445
+ // tab's answers onto the previous tab's connection.
446
+ if (!challengeBelongsToLink(link.tabId, tab.id)) return
447
+ // The answers belong to the tab that shows the form: another tab's draft
448
+ // can never be submitted here.
449
+ link.connection.sendAuthResponse(tab.authAnswers ?? [])
450
+ controller.clearTerminalAuthPrompt(tab.id)
271
451
  }
272
452
 
273
- const active = status.kind === 'connecting' || status.kind === 'connected'
453
+ const stateLabel = activeTab === undefined ? undefined : tabStateLabel(activeTab)
274
454
 
275
455
  return (
276
456
  <div className={css.termBody}>
457
+ {terminalTabs.length > 0 && (
458
+ <div className={css.termTabs} role="tablist" aria-label={tt('terminal.tabs')} data-dsh-part="tab-bar">
459
+ {terminalTabs.map(tab => {
460
+ const label = tabStateLabel(tab)
461
+ return (
462
+ <div key={tab.id} className={css.termTab} data-active={tab.id === activeTab?.id ? '' : undefined}>
463
+ <button
464
+ type="button"
465
+ role="tab"
466
+ className={css.termTabLabel}
467
+ aria-selected={tab.id === activeTab?.id}
468
+ data-dsh-part="tab"
469
+ title={tab.alias}
470
+ onClick={() => { controller.setActiveTerminalTab(tab.id) }}
471
+ >
472
+ <span className={css.termTabAlias}>{tab.alias}</span>
473
+ {label !== undefined && <span className={css.termTabState} data-state={tab.status}>{label}</span>}
474
+ </button>
475
+ <button
476
+ type="button"
477
+ className={css.termTabClose}
478
+ aria-label={tt('terminal.closeTab')}
479
+ title={tt('terminal.closeTab')}
480
+ onClick={() => { closeTab(tab.id) }}
481
+ >
482
+ <span aria-hidden="true">{'\u00d7'}</span>
483
+ </button>
484
+ </div>
485
+ )
486
+ })}
487
+ <button
488
+ type="button"
489
+ className={css.termTabNew}
490
+ aria-label={tt('terminal.newTab')}
491
+ title={tt('terminal.newTab')}
492
+ disabled={draftAlias === ''}
493
+ onClick={connect}
494
+ >
495
+ <span aria-hidden="true">+</span>
496
+ </button>
497
+ </div>
498
+ )}
277
499
  <div className={css.controls}>
278
- <select className={css.input} value={alias} onChange={event => { setAlias(event.target.value) }}>
500
+ <select className={css.input} value={draftAlias} onChange={event => { controller.setDraftAlias(event.target.value) }}>
279
501
  <option value="">{tt('terminal.selectHost')}</option>
280
502
  {hosts.map(host => <option key={host.alias} value={host.alias}>{host.alias} ({host.host})</option>)}
281
503
  </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>
504
+ <button type="button" className={css.primaryButton} disabled={draftAlias === ''} onClick={connect}>{tt('terminal.connect')}</button>
505
+ <button type="button" className={css.ghostButton} disabled={activeTab === undefined} onClick={() => { if (activeTab !== undefined) closeTab(activeTab.id) }}>{tt('terminal.disconnect')}</button>
284
506
  </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>
507
+ {activeTab?.status === 'connecting' && <div className={css.banner} data-kind="info">{tt('terminal.connecting')}</div>}
508
+ {activeTab?.status === 'connected' && stateLabel === undefined && <div className={css.banner} data-kind="ok">{tt('terminal.ready', { alias: activeTab.alias })}</div>}
509
+ {activeTab?.status === 'exited' && (
510
+ <div className={css.banner} data-kind="info">{tt('terminal.exited', { alias: activeTab.alias })}{activeTab.detail !== undefined ? ' (' + activeTab.detail + ')' : ''}</div>
289
511
  )}
290
- {status.kind === 'error' && <div className={css.banner} data-kind="error">{tt('terminal.error', { error: status.detail })}</div>}
512
+ {activeTab?.status === 'error' && <div className={css.banner} data-kind="error">{tt('terminal.error', { error: activeTab.detail ?? '' })}</div>}
513
+ {activeTab?.closeError !== undefined && <div className={css.banner} data-kind="error">{tt('terminal.closeFailed')}</div>}
514
+ {listError !== undefined && <div className={css.banner} data-kind="error">{tt('terminal.error', { error: listError })}</div>}
291
515
  <div className={css.termWrap}>
292
516
  <div ref={containerRef} className={css.termContainer} data-dsh-part="terminal" />
293
- {status.kind === 'idle' && (
517
+ {terminalTabs.length === 0 && (
294
518
  <div className={css.termPlaceholder}>{hosts.length === 0 ? tt('hosts.empty') : tt('terminal.placeholder')}</div>
295
519
  )}
296
- {authPrompt !== undefined && (
520
+ {activeTab?.authPrompt !== undefined && (
297
521
  <div className={css.modalBackdrop} style={{ position: 'absolute', zIndex: 10 }}>
298
522
  <form className={css.modalCard} style={{ maxWidth: 420 }} onSubmit={submitAuth}>
299
523
  <div className={css.modalHeader}>
300
- <h3 className={css.modalTitle}>{authPrompt.name || tt('terminal.auth.title')}</h3>
524
+ <h3 className={css.modalTitle}>{activeTab.authPrompt.name || tt('terminal.auth.title')}</h3>
301
525
  </div>
302
- <p className={css.hint}>{authPrompt.instructions || tt('terminal.auth.hint')}</p>
303
- {authPrompt.prompts.map((p, idx) => (
526
+ <p className={css.hint}>{activeTab.authPrompt.instructions || tt('terminal.auth.hint')}</p>
527
+ {activeTab.authPrompt.prompts.map((p, idx) => (
304
528
  <label key={idx} className={css.field}>
305
529
  <span className={css.fieldLabel}>{p.prompt.trim() || tt('terminal.auth.title')}</span>
306
530
  <input
@@ -308,17 +532,13 @@ export function TerminalTab({ api, controller, sessionId, presetAlias, requestId
308
532
  className={css.input}
309
533
  type={p.echo ? 'text' : 'password'}
310
534
  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
- }}
535
+ value={activeTab.authAnswers?.[idx] ?? ''}
536
+ onChange={event => { controller.setTerminalAuthAnswer(activeTab.id, idx, event.target.value) }}
317
537
  />
318
538
  </label>
319
539
  ))}
320
540
  <div className={css.modalFooter}>
321
- <button type="button" className={css.ghostButton} onClick={disconnect}>{tt('terminal.auth.cancel')}</button>
541
+ <button type="button" className={css.ghostButton} onClick={() => { if (activeTab !== undefined) closeTab(activeTab.id) }}>{tt('terminal.auth.cancel')}</button>
322
542
  <button type="submit" className={css.primaryButton}>{tt('terminal.auth.submit')}</button>
323
543
  </div>
324
544
  </form>