dsh-ssh-hub 0.0.0-stage → 0.2.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 (133) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +271 -2
  3. package/cordis.patch.yml +16 -0
  4. package/icon.svg +3 -0
  5. package/lib/client.js +13975 -0
  6. package/lib/index.js +6908 -0
  7. package/lib/types/activity/history.d.ts +50 -0
  8. package/lib/types/alerting/notify.d.ts +89 -0
  9. package/lib/types/alerting/prompt-summary.d.ts +28 -0
  10. package/lib/types/alerting/rules.d.ts +135 -0
  11. package/lib/types/alerting/tools.d.ts +30 -0
  12. package/lib/types/audit/audit-log.d.ts +84 -0
  13. package/lib/types/audit/recorder.d.ts +50 -0
  14. package/lib/types/client/api.d.ts +222 -0
  15. package/lib/types/client/index.d.ts +45 -0
  16. package/lib/types/client/locales.d.ts +319 -0
  17. package/lib/types/client/native-panel.d.ts +70 -0
  18. package/lib/types/client/panel/ClusterTab.d.ts +7 -0
  19. package/lib/types/client/panel/DeployTab.d.ts +10 -0
  20. package/lib/types/client/panel/FleetTab.d.ts +10 -0
  21. package/lib/types/client/panel/HostFormDialog.d.ts +12 -0
  22. package/lib/types/client/panel/HostsTab.d.ts +25 -0
  23. package/lib/types/client/panel/LogsTab.d.ts +10 -0
  24. package/lib/types/client/panel/SshPanel.d.ts +14 -0
  25. package/lib/types/client/panel/TerminalTab.d.ts +27 -0
  26. package/lib/types/client/panel/TransferTab.d.ts +7 -0
  27. package/lib/types/client/panel/TunnelEditDialog.d.ts +15 -0
  28. package/lib/types/client/panel/TunnelsTab.d.ts +27 -0
  29. package/lib/types/client/panel/controller.d.ts +253 -0
  30. package/lib/types/client/panel/helpers.d.ts +45 -0
  31. package/lib/types/client/panel/tabs.d.ts +62 -0
  32. package/lib/types/client/panel/xterm.css.d.ts +2 -0
  33. package/lib/types/client/settings-binding.d.ts +71 -0
  34. package/lib/types/deploy/orchestrator.d.ts +158 -0
  35. package/lib/types/deploy/tools.d.ts +14 -0
  36. package/lib/types/dsh-home.d.ts +16 -0
  37. package/lib/types/engine/cluster.d.ts +19 -0
  38. package/lib/types/engine/connection-pool.d.ts +183 -0
  39. package/lib/types/engine/proxy-command.d.ts +36 -0
  40. package/lib/types/engine/pty.d.ts +32 -0
  41. package/lib/types/engine/sftp.d.ts +20 -0
  42. package/lib/types/engine/terminal-sessions.d.ts +67 -0
  43. package/lib/types/engine/tunnel-discovery.d.ts +89 -0
  44. package/lib/types/engine/tunnel-remarks.d.ts +49 -0
  45. package/lib/types/engine/tunnel.d.ts +76 -0
  46. package/lib/types/engine.d.ts +103 -0
  47. package/lib/types/http.d.ts +59 -0
  48. package/lib/types/index.d.ts +128 -0
  49. package/lib/types/inspect/checks.d.ts +118 -0
  50. package/lib/types/inspect/inspection.d.ts +111 -0
  51. package/lib/types/inspect/tools.d.ts +50 -0
  52. package/lib/types/logs/search.d.ts +131 -0
  53. package/lib/types/logs/tools.d.ts +6 -0
  54. package/lib/types/loopback.d.ts +64 -0
  55. package/lib/types/monitor/loop.d.ts +133 -0
  56. package/lib/types/monitor/metrics.d.ts +151 -0
  57. package/lib/types/mount-once.d.ts +55 -0
  58. package/lib/types/protocol.d.ts +524 -0
  59. package/lib/types/routes.d.ts +82 -0
  60. package/lib/types/security/known-hosts.d.ts +153 -0
  61. package/lib/types/security/master-secret.d.ts +157 -0
  62. package/lib/types/security/redact.d.ts +44 -0
  63. package/lib/types/security/secrets.d.ts +70 -0
  64. package/lib/types/ssh-config.d.ts +42 -0
  65. package/lib/types/store.d.ts +183 -0
  66. package/lib/types/tool-surface.d.ts +72 -0
  67. package/lib/types/tools.d.ts +56 -0
  68. package/locale/en.json +6 -0
  69. package/locale/zh.json +6 -0
  70. package/package.json +126 -6
  71. package/src/activity/history.ts +117 -0
  72. package/src/alerting/notify.ts +212 -0
  73. package/src/alerting/prompt-summary.ts +71 -0
  74. package/src/alerting/rules.ts +281 -0
  75. package/src/alerting/tools.ts +263 -0
  76. package/src/audit/audit-log.ts +199 -0
  77. package/src/audit/recorder.ts +73 -0
  78. package/src/client/api.ts +782 -0
  79. package/src/client/css-modules.d.ts +5 -0
  80. package/src/client/index.ts +150 -0
  81. package/src/client/locales.ts +654 -0
  82. package/src/client/native-panel.tsx +141 -0
  83. package/src/client/panel/ClusterTab.tsx +141 -0
  84. package/src/client/panel/DeployTab.tsx +314 -0
  85. package/src/client/panel/FleetTab.tsx +494 -0
  86. package/src/client/panel/HostFormDialog.tsx +289 -0
  87. package/src/client/panel/HostsTab.tsx +395 -0
  88. package/src/client/panel/LogsTab.tsx +208 -0
  89. package/src/client/panel/SshPanel.tsx +105 -0
  90. package/src/client/panel/TerminalTab.tsx +550 -0
  91. package/src/client/panel/TransferTab.tsx +238 -0
  92. package/src/client/panel/TunnelEditDialog.tsx +174 -0
  93. package/src/client/panel/TunnelsTab.tsx +328 -0
  94. package/src/client/panel/controller.ts +507 -0
  95. package/src/client/panel/helpers.ts +84 -0
  96. package/src/client/panel/panel.module.css +1734 -0
  97. package/src/client/panel/tabs.ts +52 -0
  98. package/src/client/panel/xterm.css.ts +2 -0
  99. package/src/client/settings-binding.ts +184 -0
  100. package/src/deploy/orchestrator.ts +326 -0
  101. package/src/deploy/tools.ts +225 -0
  102. package/src/dsh-home.ts +42 -0
  103. package/src/engine/cluster.ts +60 -0
  104. package/src/engine/connection-pool.ts +721 -0
  105. package/src/engine/proxy-command.ts +248 -0
  106. package/src/engine/pty.ts +78 -0
  107. package/src/engine/sftp.ts +229 -0
  108. package/src/engine/terminal-sessions.ts +280 -0
  109. package/src/engine/tunnel-discovery.ts +353 -0
  110. package/src/engine/tunnel-remarks.ts +120 -0
  111. package/src/engine/tunnel.ts +300 -0
  112. package/src/engine.ts +195 -0
  113. package/src/http.ts +127 -0
  114. package/src/index.ts +690 -0
  115. package/src/inspect/checks.ts +251 -0
  116. package/src/inspect/inspection.ts +321 -0
  117. package/src/inspect/tools.ts +366 -0
  118. package/src/logs/search.ts +251 -0
  119. package/src/logs/tools.ts +160 -0
  120. package/src/loopback.ts +119 -0
  121. package/src/monitor/loop.ts +265 -0
  122. package/src/monitor/metrics.ts +333 -0
  123. package/src/mount-once.ts +142 -0
  124. package/src/protocol.ts +534 -0
  125. package/src/routes.ts +998 -0
  126. package/src/security/known-hosts.ts +342 -0
  127. package/src/security/master-secret.ts +334 -0
  128. package/src/security/redact.ts +119 -0
  129. package/src/security/secrets.ts +152 -0
  130. package/src/ssh-config.ts +182 -0
  131. package/src/store.ts +757 -0
  132. package/src/tool-surface.ts +96 -0
  133. package/src/tools.ts +550 -0
@@ -0,0 +1,105 @@
1
+ /**
2
+ * The SSH operations panel shell: a header with a close control, a five-tab
3
+ * bar, and the active tab's content.
4
+ *
5
+ * The active tab and the terminal tabs live in the controller, not in
6
+ * component state: the layout mounts this page only while the panel is
7
+ * selected, so local state would reset the tab on every panel switch and lose
8
+ * the ids the terminal tab needs to reattach its host-side sessions. Inactive
9
+ * tabs unmount, so each tab fetches its own data on activation.
10
+ */
11
+ import { useCallback, useSyncExternalStore, type ReactNode } from 'react'
12
+ import type { SshApi } from '../api.ts'
13
+ import type { PanelController, SshTab } from './controller.ts'
14
+ import { tt, type TerminalFontSource } from './helpers.ts'
15
+ import { SSH_TABS } from './tabs.ts'
16
+ import { ClusterTab } from './ClusterTab.tsx'
17
+ import { DeployTab } from './DeployTab.tsx'
18
+ import { FleetTab } from './FleetTab.tsx'
19
+ import { HostsTab } from './HostsTab.tsx'
20
+ import { LogsTab } from './LogsTab.tsx'
21
+ import { TerminalTab } from './TerminalTab.tsx'
22
+ import { TransferTab } from './TransferTab.tsx'
23
+ import { TunnelsTab } from './TunnelsTab.tsx'
24
+ import css from './panel.module.css'
25
+
26
+ /** Panel shell props. */
27
+ export interface SshPanelProps {
28
+ /** The panel state owner (open/close/toggle, active tab, terminal session). */
29
+ controller: PanelController
30
+ /** The SSH API client every tab operates through. */
31
+ api: SshApi
32
+ /** Live terminal-font setting source handed to the terminal tab (issue #577). */
33
+ terminalFont?: TerminalFontSource
34
+ }
35
+
36
+ /** The tab bar definition (labels resolved at render time). */
37
+ const TABS = SSH_TABS
38
+
39
+ /**
40
+ * Render the active tab.
41
+ *
42
+ * A `Record<SshTab, ...>` rather than a chain of `&&` comparisons: the record
43
+ * type requires an entry for every member of the union, so a new tab that is
44
+ * added to `SshTab` and to the tab bar but forgotten here is a compile error.
45
+ * With `&&` comparisons the same omission renders an empty panel — the failure
46
+ * mode where the tab is selectable and shows nothing.
47
+ */
48
+ function renderActiveTab(
49
+ activeTab: SshTab,
50
+ { api, controller, terminalFont, panelOpen }: {
51
+ api: SshApi
52
+ controller: PanelController
53
+ terminalFont?: TerminalFontSource
54
+ panelOpen: boolean
55
+ },
56
+ ): ReactNode {
57
+ const renderers: Record<SshTab, () => ReactNode> = {
58
+ hosts: () => <HostsTab api={api} onConnect={alias => { controller.requestConnect(alias) }} />,
59
+ terminal: () => <TerminalTab api={api} controller={controller} terminalFont={terminalFont} />,
60
+ transfer: () => <TransferTab api={api} />,
61
+ tunnels: () => <TunnelsTab api={api} active={panelOpen} />,
62
+ cluster: () => <ClusterTab api={api} />,
63
+ deploy: () => <DeployTab api={api} active={panelOpen} />,
64
+ logs: () => <LogsTab api={api} active={panelOpen} />,
65
+ fleet: () => <FleetTab api={api} active={panelOpen} />,
66
+ }
67
+ return renderers[activeTab]()
68
+ }
69
+
70
+ /** The tabbed SSH panel. */
71
+ export function SshPanel({ controller, api, terminalFont }: SshPanelProps) {
72
+ const { panelOpen, activeTab } = useSyncExternalStore(
73
+ useCallback(listener => controller.subscribe(listener), [controller]),
74
+ useCallback(() => controller.getSnapshot(), [controller]),
75
+ )
76
+
77
+ return (
78
+ <div className={css.panel} data-dsh-plugin="ssh">
79
+ <div className={css.panelHeader}>
80
+ {/* Shared hook: dsh-web-all offsets center-view back controls beside the collapsed mobile sidebar. */}
81
+ <button
82
+ type="button"
83
+ className={`${css.ghostButton} ${css.backButton}`}
84
+ aria-label={tt('panel.backToConversation')}
85
+ data-dsh-center-view-back=""
86
+ onClick={() => { controller.close() }}
87
+ >
88
+ <span aria-hidden="true">‹</span>
89
+ <span>{tt('panel.backToConversation')}</span>
90
+ </button>
91
+ <h2 className={css.panelTitle}>{tt('panel.title')}</h2>
92
+ </div>
93
+ <div className={css.tabBar} role="tablist" data-dsh-part="tab-bar">
94
+ {TABS.map(tab => (
95
+ <button key={tab.id} type="button" role="tab" aria-selected={activeTab === tab.id} data-active={activeTab === tab.id ? '' : undefined} data-dsh-part="tab" className={css.tab} onClick={() => { controller.setActiveTab(tab.id) }}>
96
+ {tt(tab.labelKey)}
97
+ </button>
98
+ ))}
99
+ </div>
100
+ <div className={css.panelContent}>
101
+ {renderActiveTab(activeTab, { api, controller, terminalFont, panelOpen })}
102
+ </div>
103
+ </div>
104
+ )
105
+ }
@@ -0,0 +1,550 @@
1
+ /**
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.
18
+ */
19
+ import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react'
20
+ import { Terminal, type IDisposable } from '@xterm/xterm'
21
+ import { FitAddon } from '@xterm/addon-fit'
22
+ import type { SshApi, TerminalConnection } from '../api.ts'
23
+ import type { SshHostSummary } from '../../protocol.ts'
24
+ import type { PanelController, TerminalTabRecord } from './controller.ts'
25
+ import { XTERM_CSS } from './xterm.css.ts'
26
+ import { errorMessage, resolveTerminalFontFamily, tt, type TerminalFontSource } from './helpers.ts'
27
+ import css from './panel.module.css'
28
+
29
+ /** Terminal tab props. */
30
+ export interface TerminalTabProps {
31
+ api: SshApi
32
+ /** The panel controller that owns the tabs and their host session ids. */
33
+ controller: PanelController
34
+ /** Alias preselected by a "connect" action from the hosts tab. */
35
+ presetAlias?: string
36
+ /**
37
+ * Live terminal-font setting source (issue #577). Absent in tests and
38
+ * legacy mounts: the font then comes from the CSS custom-property chain.
39
+ */
40
+ terminalFont?: TerminalFontSource
41
+ }
42
+
43
+ /** The socket currently bound to the single terminal view. */
44
+ interface BoundLink {
45
+ tabId: string
46
+ connection: TerminalConnection
47
+ }
48
+
49
+ /** Injected-once guard for the xterm stylesheet (one tag per page load). */
50
+ let xtermCssInjected = false
51
+
52
+ function ensureXtermCss(): void {
53
+ if (xtermCssInjected || typeof document === 'undefined') return
54
+ xtermCssInjected = true
55
+ if (document.querySelector('style[data-dsh-ssh-xterm]') !== null) return
56
+ const style = document.createElement('style')
57
+ style.dataset.dshSshXterm = ''
58
+ style.textContent = XTERM_CSS
59
+ document.head.appendChild(style)
60
+ }
61
+
62
+ /** No-op source stand-in so the hook order stays stable without the prop. */
63
+ const NO_FONT_SOURCE: TerminalFontSource = {
64
+ get: () => undefined,
65
+ subscribe: () => () => undefined,
66
+ }
67
+
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
+ )
104
+ const [hosts, setHosts] = useState<SshHostSummary[]>([])
105
+ const [listError, setListError] = useState<string | undefined>(undefined)
106
+ const containerRef = useRef<HTMLDivElement | null>(null)
107
+ const termRef = useRef<Terminal | null>(null)
108
+ const fitRef = useRef<FitAddon | null>(null)
109
+ const linkRef = useRef<BoundLink | null>(null)
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())
115
+ const fontSource = terminalFont ?? NO_FONT_SOURCE
116
+ const fontOverride = useSyncExternalStore(fontSource.subscribe, fontSource.get)
117
+ const activeTab = terminalTabs.find(tab => tab.id === activeTerminalTabId)
118
+
119
+ useEffect(() => { ensureXtermCss() }, [])
120
+
121
+ // Live re-apply a terminal-font change (issue #577): xterm re-measures
122
+ // and repaints on the options write; a refit keeps cols/rows aligned with
123
+ // the new metrics and the remote PTY learns the new size.
124
+ useEffect(() => {
125
+ const term = termRef.current
126
+ if (term === null) return
127
+ const next = resolveTerminalFontFamily(fontOverride)
128
+ if (term.options.fontFamily === next) return
129
+ term.options.fontFamily = next
130
+ fitRef.current?.fit()
131
+ const link = linkRef.current
132
+ if (link !== null) link.connection.resize(term.cols, term.rows)
133
+ }, [fontOverride])
134
+
135
+ // Fetch the host list on tab activation.
136
+ useEffect(() => {
137
+ let disposed = false
138
+ void (async () => {
139
+ try {
140
+ const list = await api.listHosts()
141
+ if (!disposed) setHosts(list)
142
+ } catch (cause) {
143
+ if (!disposed) setListError(errorMessage(cause))
144
+ }
145
+ })()
146
+ return () => { disposed = true }
147
+ }, [api])
148
+
149
+ // A hosts-tab connect action preselects its alias in the toolbar.
150
+ useEffect(() => {
151
+ if (presetAlias === undefined || presetAlias === '') return
152
+ controller.setDraftAlias(presetAlias)
153
+ }, [presetAlias, controller])
154
+
155
+ // Keep the terminal fitted to its container. A window resize is only one
156
+ // trigger: the status banner appearing after connect, panel resizes, and
157
+ // sidebar toggles all change the container without a window resize, so the
158
+ // container itself is observed (otherwise the viewport keeps the pre-banner
159
+ // height and the last line is clipped below the fold). ResizeObserver may
160
+ // be absent (jsdom tests); the window listener then remains the only path.
161
+ useEffect(() => {
162
+ let lastCols = -1
163
+ let lastRows = -1
164
+ const sync = (): void => {
165
+ const term = termRef.current
166
+ const fit = fitRef.current
167
+ if (term === null || fit === null) return
168
+ fit.fit()
169
+ const link = linkRef.current
170
+ if (link !== null && (term.cols !== lastCols || term.rows !== lastRows)) {
171
+ lastCols = term.cols
172
+ lastRows = term.rows
173
+ link.connection.resize(term.cols, term.rows)
174
+ }
175
+ }
176
+ window.addEventListener('resize', sync)
177
+ const container = containerRef.current
178
+ if (container === null || typeof ResizeObserver === 'undefined') {
179
+ return () => { window.removeEventListener('resize', sync) }
180
+ }
181
+ const observer = new ResizeObserver(() => { sync() })
182
+ observer.observe(container)
183
+ return () => {
184
+ observer.disconnect()
185
+ window.removeEventListener('resize', sync)
186
+ }
187
+ }, [])
188
+
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 }
194
+ const container = containerRef.current
195
+ if (container === null) return undefined
196
+ const term = new Terminal({
197
+ convertEol: false,
198
+ cursorBlink: true,
199
+ fontSize: 13,
200
+ fontFamily: resolveTerminalFontFamily(fontOverride),
201
+ theme: { background: '#0b0e14', foreground: '#d8dee9', cursor: '#a3b8d0' },
202
+ })
203
+ const fit = new FitAddon()
204
+ term.loadAddon(fit)
205
+ term.open(container)
206
+ fit.fit()
207
+ termRef.current = term
208
+ fitRef.current = fit
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
242
+ }
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 })
298
+ }
299
+ connection.onExit = (_code, 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)
311
+ }
312
+ }
313
+
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))
354
+ }
355
+
356
+ // Bind the shown tab, releasing whatever the previous one held.
357
+ useEffect(() => {
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
+ }, [])
381
+
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)
436
+ }
437
+
438
+ const submitAuth = (e?: React.FormEvent): void => {
439
+ e?.preventDefault()
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)
451
+ }
452
+
453
+ const stateLabel = activeTab === undefined ? undefined : tabStateLabel(activeTab)
454
+
455
+ return (
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
+ )}
499
+ <div className={css.controls}>
500
+ <select className={css.input} value={draftAlias} onChange={event => { controller.setDraftAlias(event.target.value) }}>
501
+ <option value="">{tt('terminal.selectHost')}</option>
502
+ {hosts.map(host => <option key={host.alias} value={host.alias}>{host.alias} ({host.host})</option>)}
503
+ </select>
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>
506
+ </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" role="status">{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>
511
+ )}
512
+ {activeTab?.status === 'error' && <div className={css.banner} data-kind="error" role="alert">{tt('terminal.error', { error: activeTab.detail ?? '' })}</div>}
513
+ {activeTab?.closeError !== undefined && <div className={css.banner} data-kind="error" role="alert">{tt('terminal.closeFailed')}</div>}
514
+ {listError !== undefined && <div className={css.banner} data-kind="error" role="alert">{tt('terminal.error', { error: listError })}</div>}
515
+ <div className={css.termWrap}>
516
+ <div ref={containerRef} className={css.termContainer} data-dsh-part="terminal" />
517
+ {terminalTabs.length === 0 && (
518
+ <div className={css.termPlaceholder}>{hosts.length === 0 ? tt('hosts.empty') : tt('terminal.placeholder')}</div>
519
+ )}
520
+ {activeTab?.authPrompt !== undefined && (
521
+ <div className={css.modalBackdrop} style={{ position: 'absolute', zIndex: 10 }}>
522
+ <form className={css.modalCard} style={{ maxWidth: 420 }} onSubmit={submitAuth}>
523
+ <div className={css.modalHeader}>
524
+ <h3 className={css.modalTitle}>{activeTab.authPrompt.name || tt('terminal.auth.title')}</h3>
525
+ </div>
526
+ <p className={css.hint}>{activeTab.authPrompt.instructions || tt('terminal.auth.hint')}</p>
527
+ {activeTab.authPrompt.prompts.map((p, idx) => (
528
+ <label key={idx} className={css.field}>
529
+ <span className={css.fieldLabel}>{p.prompt.trim() || tt('terminal.auth.title')}</span>
530
+ <input
531
+ autoFocus={idx === 0}
532
+ className={css.input}
533
+ type={p.echo ? 'text' : 'password'}
534
+ placeholder={tt('terminal.auth.placeholder')}
535
+ value={activeTab.authAnswers?.[idx] ?? ''}
536
+ onChange={event => { controller.setTerminalAuthAnswer(activeTab.id, idx, event.target.value) }}
537
+ />
538
+ </label>
539
+ ))}
540
+ <div className={css.modalFooter}>
541
+ <button type="button" className={css.ghostButton} onClick={() => { if (activeTab !== undefined) closeTab(activeTab.id) }}>{tt('terminal.auth.cancel')}</button>
542
+ <button type="submit" className={css.primaryButton}>{tt('terminal.auth.submit')}</button>
543
+ </div>
544
+ </form>
545
+ </div>
546
+ )}
547
+ </div>
548
+ </div>
549
+ )
550
+ }