@linxin666/dsh-ssh 0.4.20 → 0.4.22

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.
@@ -4,11 +4,16 @@
4
4
  */
5
5
  import type { ClusterResult } from '../protocol.ts';
6
6
  import { type PoolEngine } from './connection-pool.ts';
7
- interface ClusterOptions {
8
- command: string;
7
+ /** Target selector fields shared by cluster engine, routes, and agent tool. */
8
+ export interface ClusterSelector {
9
9
  aliases?: string[];
10
10
  environment?: string;
11
11
  tags?: string[];
12
+ }
13
+ /** Whether at least one trimmed non-empty cluster target filter is present. */
14
+ export declare function hasClusterSelector(options: ClusterSelector): boolean;
15
+ interface ClusterOptions extends ClusterSelector {
16
+ command: string;
12
17
  timeoutMs?: number;
13
18
  maxWorkers?: number;
14
19
  /** Caller cancellation, forwarded to every host's command. */
@@ -2,6 +2,7 @@
2
2
  * Connection pool: per-alias persistent ssh2 connections with multi-hop jump
3
3
  * support, the acquire / dispose / sweep lifecycle, and the pooled exec path.
4
4
  */
5
+ import { StringDecoder } from 'node:string_decoder';
5
6
  import { Client, type ConnectConfig } from 'ssh2';
6
7
  import type { ExecResult, SshHostEntry } from '../protocol.ts';
7
8
  import { type HostStore } from '../store.ts';
@@ -102,11 +103,12 @@ export declare function readyTimeoutMessage(timeoutMs: number | undefined, hands
102
103
  export declare function isReadyTimeout(error: Error): boolean;
103
104
  /** Connect one ssh2 client (resolve on ready, reject on error/close). */
104
105
  export declare function connectClient(config: ConnectConfig, onKeyboardInteractive?: KeyboardInteractiveHandler): Promise<Client>;
105
- /** Cap captured output at the configured byte budget (marks truncation). */
106
+ /** Cap captured output at the configured UTF-8 byte budget (marks truncation). */
106
107
  export declare function appendOutput(target: {
107
108
  text: string;
108
109
  truncated: boolean;
109
- }, chunk: Buffer, maxBytes: number): void;
110
+ bytes?: number;
111
+ }, chunk: Buffer, maxBytes: number, decoder?: StringDecoder): void;
110
112
  /**
111
113
  * Parse an OpenSSH jump hop written as an address: `[user@]host[:port]`
112
114
  * (an IPv6 literal must be bracketed). Returns undefined when the value is not
@@ -142,6 +144,13 @@ export declare function connectChain(engine: PoolEngine, entry: SshHostEntry, on
142
144
  client: Client;
143
145
  hops: Client[];
144
146
  }>;
147
+ /**
148
+ * Invalidate any in-flight acquire for `alias` so a connection still handshaking
149
+ * under stale config or before a delete cannot enter `engine.pool` after completion.
150
+ */
151
+ export declare function invalidateAlias(engine: PoolEngine, alias: string): void;
152
+ /** Mark the pool disposed so in-flight acquires tear down instead of entering the pool. */
153
+ export declare function markPoolDisposed(engine: PoolEngine): void;
145
154
  /** Connect (or reuse) the pooled chain for one alias; pins nothing. */
146
155
  export declare function acquire(engine: PoolEngine, alias: string): Promise<PoolRecord>;
147
156
  /**
@@ -3,6 +3,7 @@
3
3
  * remote directory listing. Every channel is opened once per operation and
4
4
  * released exactly once so sshd's MaxSessions cap is never exhausted.
5
5
  */
6
+ import { type SFTPWrapper } from 'ssh2';
6
7
  import type { RemoteDirEntry, TransferProgress } from '../protocol.ts';
7
8
  import { type PoolEngine } from './connection-pool.ts';
8
9
  /** Walk a local directory, collecting relative paths of every file. */
@@ -18,3 +19,7 @@ export declare function download(engine: PoolEngine, alias: string, remotePath:
18
19
  }>;
19
20
  /** List a remote directory (file browser). */
20
21
  export declare function ls(engine: PoolEngine, alias: string, path: string): Promise<RemoteDirEntry[]>;
22
+ /** Create a remote directory chain (with a 1-RTT stat fast path and prefix cache). */
23
+ export declare function ensureRemoteDir(sftp: SFTPWrapper, remote: string, ensuredDirs?: Set<string>): Promise<void>;
24
+ /** One fastPut/fastGet transfer with throttled progress (the two directions share everything but the verb). */
25
+ export declare function fastTransfer(sftp: SFTPWrapper, kind: 'put' | 'get', src: string, dst: string, concurrency: number, onProgress?: (progress: TransferProgress) => void): Promise<void>;
@@ -49,15 +49,17 @@ export declare class TerminalSessionRegistry {
49
49
  private bind;
50
50
  /** Remove a socket from its session, keeping the shell alive. */
51
51
  private detach;
52
- /** End the session a socket is attached to (explicit close from the view). */
52
+ /** End the session and close every socket still attached to it. */
53
53
  private end;
54
54
  /** Mark a session exited and keep it briefly so a reattaching view sees it. */
55
55
  private finish;
56
- /** Append output to the replay buffer, trimmed to the byte cap. */
56
+ /** Keep at most `maxBytes` from the tail of `data` on a valid UTF-8 boundary. */
57
+ private trimTailToUtf8Bytes;
58
+ /** Append output to the O(1) replay ring, trimmed to the byte cap. */
57
59
  private pushOutput;
58
60
  /** Broadcast one frame to every attached socket, honoring backpressure. */
59
61
  private send;
60
- private sendTo;
62
+ private sendPayload;
61
63
  /** Pause while any attached socket is backed up; resume once all drained. */
62
64
  private applyBackpressure;
63
65
  /** Answer a keyboard-interactive challenge through whoever is attached. */
@@ -63,7 +63,6 @@ export declare class HostStore {
63
63
  * @returns import statistics.
64
64
  */
65
65
  importFromSshConfig(): ImportResult;
66
- private skippedBlocks;
67
66
  /**
68
67
  * Last parsed store keyed by file identity. list/find ride every acquire
69
68
  * and GUI refresh; re-reading and re-parsing the whole file each call is
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "@linxin666/dsh-ssh",
3
3
  "description": "Remote SSH operations for the dsh web GUI: host config store (~/.dsh/dsh-ssh.json, import from ~/.ssh/config), a persistent ssh2 connection pool with jump-host support, exec / PTY web terminal / SFTP transfer / local port-forward tunnels / cluster execution, plus agent tools (ssh_list, ssh_exec, ssh_upload, ssh_download, ssh_tunnel, ssh_cluster). Hot-pluggable — mounted via ~/.dsh/cordis.patch.yml + a profile node_modules symlink, no dsh source changes.",
4
- "version": "0.4.20",
4
+ "version": "0.4.22",
5
5
  "icon": "icon.svg",
6
6
  "type": "module",
7
7
  "engines": {
8
- "node": ">=24.9.0"
8
+ "node": "^24.22.3 || >=26.13.1"
9
9
  },
10
10
  "main": "lib/index.js",
11
11
  "types": "lib/types/index.d.ts",
@@ -25,7 +25,7 @@
25
25
  },
26
26
  "dsh": {
27
27
  "engines": {
28
- "dsh": ">=0.2.2-rc.3"
28
+ "dsh": ">=0.2.3-alpha.2"
29
29
  },
30
30
  "bundle": {
31
31
  "patch": "./cordis.patch.yml"
@@ -41,33 +41,33 @@
41
41
  }
42
42
  },
43
43
  "dependencies": {
44
- "@deepseek-ai/schemastery": "^3.19.0",
44
+ "@deepseek-ai/schemastery": "~3.20.0-alpha.1",
45
45
  "@xterm/addon-fit": "^0.11.0",
46
46
  "@xterm/xterm": "^6.0.0",
47
47
  "ssh2": "^1.17.0",
48
48
  "ws": "^8.18.0"
49
49
  },
50
50
  "peerDependencies": {
51
- "@deepseek-ai/dsh": ">=0.2.2-rc.3",
51
+ "@deepseek-ai/dsh": ">=0.2.3-alpha.2",
52
52
  "react": "^18.2.0",
53
53
  "react-dom": "^18.2.0"
54
54
  },
55
55
  "devDependencies": {
56
- "@deepseek-ai/cordis": "^4.1.0",
57
- "@deepseek-ai/dsh-client-connection": "^0.2.2-rc.3",
58
- "@deepseek-ai/dsh-client-locale": "^0.2.2-rc.3",
59
- "@deepseek-ai/dsh-client-ui-layout": "^0.2.2-rc.3",
60
- "@deepseek-ai/dsh-client-ui-renderer": "^0.2.2-rc.3",
61
- "@deepseek-ai/dsh-client-ui-settings": "^0.2.2-rc.3",
62
- "@deepseek-ai/dsh-client-ui-sidebar": "^0.2.2-rc.3",
63
- "@deepseek-ai/dsh-client-ui-slots": "^0.2.2-rc.3",
64
- "@deepseek-ai/dsh-host-webserver": "^0.2.2-rc.3",
65
- "@deepseek-ai/dsh-llm": "^0.2.2-rc.3",
66
- "@deepseek-ai/dsh-scope": "^0.2.2-rc.3",
67
- "@deepseek-ai/dsh-settings": "^0.2.2-rc.3",
68
- "@deepseek-ai/dsh-system-prompt": "^0.2.2-rc.3",
69
- "@deepseek-ai/dsh-timeout": "^0.2.2-rc.3",
70
- "@deepseek-ai/dsh-tools": "^0.2.2-rc.3",
56
+ "@deepseek-ai/cordis": "~4.2.0-alpha.1",
57
+ "@deepseek-ai/dsh-client-connection": "^0.2.3-alpha.2",
58
+ "@deepseek-ai/dsh-client-locale": "^0.2.3-alpha.2",
59
+ "@deepseek-ai/dsh-client-ui-layout": "^0.2.3-alpha.2",
60
+ "@deepseek-ai/dsh-client-ui-renderer": "^0.2.3-alpha.2",
61
+ "@deepseek-ai/dsh-client-ui-settings": "^0.2.3-alpha.2",
62
+ "@deepseek-ai/dsh-client-ui-sidebar": "^0.2.3-alpha.2",
63
+ "@deepseek-ai/dsh-client-ui-slots": "^0.2.3-alpha.2",
64
+ "@deepseek-ai/dsh-host-webserver": "^0.2.3-alpha.2",
65
+ "@deepseek-ai/dsh-llm": "^0.2.3-alpha.2",
66
+ "@deepseek-ai/dsh-scope": "^0.2.3-alpha.2",
67
+ "@deepseek-ai/dsh-settings": "^0.2.3-alpha.2",
68
+ "@deepseek-ai/dsh-system-prompt": "^0.2.3-alpha.2",
69
+ "@deepseek-ai/dsh-timeout": "^0.2.3-alpha.2",
70
+ "@deepseek-ai/dsh-tools": "^0.2.3-alpha.2",
71
71
  "@types/node": "^22.20.0",
72
72
  "@types/react": "~18.3.1",
73
73
  "@types/react-dom": "^18.3.5",
package/src/client/api.ts CHANGED
@@ -10,7 +10,6 @@ import {
10
10
  type HostPayload,
11
11
  type ImportResult,
12
12
  type RemoteDirEntry,
13
- type SshHostSummary,
14
13
  type SshKeyPayload,
15
14
  type SshKeySummary,
16
15
  type SshPanelHostSummary,
@@ -26,7 +25,11 @@ import { tt } from './panel/helpers.ts'
26
25
  /** Minimal File System Access API surface (not in all lib.dom versions). */
27
26
  interface WindowWithFileSystemAccess {
28
27
  showSaveFilePicker?: (options: { suggestedName?: string }) => Promise<{
29
- createWritable: () => Promise<{ write: (data: Uint8Array) => Promise<void>; close: () => Promise<void> }>
28
+ createWritable: () => Promise<{
29
+ write: (data: Uint8Array) => Promise<void>
30
+ close: () => Promise<void>
31
+ abort?: () => Promise<void>
32
+ }>
30
33
  }>
31
34
  }
32
35
 
@@ -419,28 +422,44 @@ export class SshApi {
419
422
  let finalError: string | undefined
420
423
  let sawResult = false
421
424
  let transferredBytes = 0
422
- for (;;) {
423
- const { done, value } = await reader.read()
424
- if (done) break
425
- buffer += decoder.decode(value, { stream: true })
426
- const lines = buffer.split('\n')
427
- buffer = lines.pop() ?? ''
428
- for (const line of lines) {
429
- if (line.trim() === '') continue
430
- let parsed: TransferStreamLine
431
- try {
432
- parsed = JSON.parse(line) as TransferStreamLine
433
- } catch {
434
- continue
435
- }
436
- if (parsed.type === 'progress') {
437
- onProgress?.(parsed.progress)
438
- } else if (parsed.type === 'result') {
439
- sawResult = true
440
- if (parsed.ok) transferredBytes = parsed.transferredBytes ?? 0
441
- finalError = parsed.ok ? undefined : parsed.error ?? 'upload failed'
425
+ let doneReading = false
426
+ const processLine = (line: string): void => {
427
+ if (line.trim() === '') return
428
+ let parsed: TransferStreamLine
429
+ try {
430
+ parsed = JSON.parse(line) as TransferStreamLine
431
+ } catch {
432
+ return
433
+ }
434
+ if (parsed.type === 'progress') {
435
+ onProgress?.(parsed.progress)
436
+ } else if (parsed.type === 'result') {
437
+ sawResult = true
438
+ if (parsed.ok) transferredBytes = parsed.transferredBytes ?? 0
439
+ finalError = parsed.ok ? undefined : parsed.error ?? 'upload failed'
440
+ }
441
+ }
442
+ try {
443
+ for (;;) {
444
+ const { done, value } = await reader.read()
445
+ if (done) {
446
+ doneReading = true
447
+ break
442
448
  }
449
+ buffer += decoder.decode(value, { stream: true })
450
+ const lines = buffer.split('\n')
451
+ buffer = lines.pop() ?? ''
452
+ for (const line of lines) processLine(line)
443
453
  }
454
+ buffer += decoder.decode()
455
+ if (buffer !== '') {
456
+ for (const line of buffer.split('\n')) processLine(line)
457
+ }
458
+ } finally {
459
+ if (!doneReading) {
460
+ try { await reader.cancel() } catch { /* ignore */ }
461
+ }
462
+ try { reader.releaseLock() } catch { /* ignore */ }
444
463
  }
445
464
  if (finalError !== undefined) throw new SshApiError(finalError)
446
465
  if (!sawResult) throw new SshApiError('upload ended without a result frame — the transfer did not complete')
@@ -472,11 +491,21 @@ export class SshApi {
472
491
  ? (window as WindowWithFileSystemAccess).showSaveFilePicker
473
492
  : undefined
474
493
  let streamed = false
475
- let writable: { write: (data: Uint8Array) => Promise<void>; close: () => Promise<void> } | undefined
494
+ let writable: {
495
+ write: (data: Uint8Array) => Promise<void>
496
+ close: () => Promise<void>
497
+ abort?: () => Promise<void>
498
+ } | undefined
476
499
  const chunks: Uint8Array<ArrayBuffer>[] = []
477
500
  let received = 0
478
- const progress = (): void => {
479
- onProgress?.({
501
+ let lastProgressAt = -Infinity
502
+ const PROGRESS_THROTTLE_MS = 100
503
+ const emitProgress = (force = false): void => {
504
+ if (onProgress === undefined) return
505
+ const now = Date.now()
506
+ if (!force && now - lastProgressAt < PROGRESS_THROTTLE_MS) return
507
+ lastProgressAt = now
508
+ onProgress({
480
509
  phase: 'transferring',
481
510
  file: remotePath,
482
511
  transferred: received,
@@ -484,33 +513,52 @@ export class SshApi {
484
513
  percent: total > 0 ? Math.round((received / total) * 1000) / 10 : 0,
485
514
  })
486
515
  }
516
+ let doneReading = false
517
+ let completed = false
487
518
  try {
488
- if (picker !== undefined) {
489
- const handle = await picker.call(window, { suggestedName: filename })
490
- writable = await handle.createWritable()
491
- streamed = true
519
+ try {
520
+ if (picker !== undefined) {
521
+ const handle = await picker.call(window, { suggestedName: filename })
522
+ writable = await handle.createWritable()
523
+ streamed = true
524
+ }
525
+ } catch {
526
+ // User cancelled the save dialog or the API is unavailable: fall back.
492
527
  }
493
- } catch {
494
- // User cancelled the save dialog or the API is unavailable: fall back.
495
- }
496
- for (;;) {
497
- const { done, value } = await reader.read()
498
- if (done) break
499
- if (writable !== undefined) {
500
- await writable.write(value as Uint8Array)
501
- } else {
502
- chunks.push(value as Uint8Array<ArrayBuffer>)
528
+ for (;;) {
529
+ const { done, value } = await reader.read()
530
+ if (done) {
531
+ doneReading = true
532
+ break
533
+ }
534
+ if (writable !== undefined) {
535
+ await writable.write(value as Uint8Array)
536
+ } else {
537
+ chunks.push(value as Uint8Array<ArrayBuffer>)
538
+ }
539
+ received += value.length
540
+ emitProgress(lastProgressAt < 0)
503
541
  }
504
- received += value.length
505
- progress()
506
- }
507
- if (writable !== undefined) await writable.close()
508
- onProgress?.({ phase: 'done', file: remotePath, transferred: received, total: received > 0 ? received : total, percent: 100 })
509
- return {
510
- blob: streamed ? undefined : new Blob(chunks),
511
- filename,
512
- streamed,
513
- bytes: received,
542
+ if (writable !== undefined) await writable.close()
543
+ completed = true
544
+ onProgress?.({ phase: 'done', file: remotePath, transferred: received, total: received > 0 ? received : total, percent: 100 })
545
+ return {
546
+ blob: streamed ? undefined : new Blob(chunks),
547
+ filename,
548
+ streamed,
549
+ bytes: received,
550
+ }
551
+ } finally {
552
+ if (!completed && writable !== undefined) {
553
+ try {
554
+ if (writable.abort !== undefined) await writable.abort()
555
+ else await writable.close()
556
+ } catch { /* ignore */ }
557
+ }
558
+ if (!doneReading) {
559
+ try { await reader.cancel() } catch { /* ignore */ }
560
+ }
561
+ try { reader.releaseLock() } catch { /* ignore */ }
514
562
  }
515
563
  }
516
564
 
@@ -626,6 +674,12 @@ export class SshApi {
626
674
  // A deliberate detach/close must not surface as a transport error: the
627
675
  // view tears down silently, and only an UNEXPECTED close reports exit.
628
676
  let leaving = false
677
+ let exited = false
678
+ const notifyExit = (code: number | null, error?: string): void => {
679
+ if (exited) return
680
+ exited = true
681
+ connection.onExit?.(code, error)
682
+ }
629
683
  const sendFrame = (frame: TerminalClientFrame): void => {
630
684
  if (socket.readyState === WebSocket.OPEN) socket.send(JSON.stringify(frame))
631
685
  }
@@ -657,11 +711,11 @@ export class SshApi {
657
711
  }
658
712
  if (frame.type === 'ready') connection.onReady?.(frame.sessionId, frame.alias)
659
713
  else if (frame.type === 'output') connection.onOutput?.(frame.data)
660
- else if (frame.type === 'exit') connection.onExit?.(frame.code, frame.error)
714
+ else if (frame.type === 'exit') notifyExit(frame.code, frame.error)
661
715
  else if (frame.type === 'auth_prompt') connection.onAuthPrompt?.(frame.name, frame.instructions, frame.prompts)
662
716
  }
663
- socket.onclose = () => { if (!leaving) connection.onExit?.(null, 'connection closed') }
664
- socket.onerror = () => { if (!leaving) connection.onExit?.(null, 'connection error') }
717
+ socket.onclose = () => { if (!leaving) notifyExit(null, 'connection closed') }
718
+ socket.onerror = () => { if (!leaving) notifyExit(null, 'connection error') }
665
719
  return connection
666
720
  }
667
721
  }
@@ -172,10 +172,12 @@ export function HostFormDialog({ api, editing, onClose, onSaved }: HostFormDialo
172
172
  // form can both enable and clear forwarding (omitting it would keep the
173
173
  // stored value under PATCH semantics).
174
174
  forwardAgent: form.forwardAgent,
175
- description: form.description.trim() === '' ? undefined : form.description.trim(),
176
- environment: form.environment.trim() === '' ? undefined : form.environment.trim(),
175
+ // Always sent (never omitted): an empty string is the explicit PATCH
176
+ // clear, matching store.ts semantics.
177
+ description: form.description.trim(),
178
+ environment: form.environment.trim(),
177
179
  tags: splitList(form.tags),
178
- location: form.location.trim() === '' ? undefined : form.location.trim(),
180
+ location: form.location.trim(),
179
181
  }
180
182
  setSaving(true)
181
183
  setError(null)
@@ -75,7 +75,7 @@ export function HostsTab({ api, onConnect }: HostsTabProps) {
75
75
  const [hosts, setHosts] = useState<SshPanelHostSummary[] | null>(null)
76
76
  const [error, setError] = useState<string | null>(null)
77
77
  const [search, setSearch] = useState('')
78
- const [testingAlias, setTestingAlias] = useState<string | null>(null)
78
+ const [testingAliases, setTestingAliases] = useState<ReadonlySet<string>>(() => new Set())
79
79
  const [testResults, setTestResults] = useState<Record<string, TestResult>>({})
80
80
  const [importing, setImporting] = useState(false)
81
81
  const [notice, setNotice] = useState<string | null>(null)
@@ -93,7 +93,10 @@ export function HostsTab({ api, onConnect }: HostsTabProps) {
93
93
  // sibling tabs (terminal / transfer / tunnels) already guard with a
94
94
  // disposed flag.
95
95
  const mountedRef = useRef(true)
96
- useEffect(() => () => { mountedRef.current = false }, [])
96
+ useEffect(() => {
97
+ mountedRef.current = true
98
+ return () => { mountedRef.current = false }
99
+ }, [])
97
100
 
98
101
  const load = useCallback(async (query?: string): Promise<void> => {
99
102
  const seq = ++seqRef.current
@@ -108,23 +111,37 @@ export function HostsTab({ api, onConnect }: HostsTabProps) {
108
111
  }
109
112
  }, [api])
110
113
 
111
- useEffect(() => { void load() }, [load])
112
-
113
- // Debounced search: every keystroke re-filters through the API.
114
+ // Initial load fires once right away; later search edits debounce through the API.
115
+ const loadedApiRef = useRef<SshApi | null>(null)
114
116
  useEffect(() => {
117
+ const query = search.trim()
118
+ const normalized = query === '' ? undefined : query
119
+ if (loadedApiRef.current !== api) {
120
+ loadedApiRef.current = api
121
+ void load(normalized)
122
+ return
123
+ }
115
124
  const timer = setTimeout(() => {
116
- const query = search.trim()
117
- void load(query === '' ? undefined : query)
125
+ void load(normalized)
118
126
  }, 300)
119
127
  return () => { clearTimeout(timer) }
120
- }, [search, load])
128
+ }, [api, search, load])
129
+
130
+ const reloadCurrent = (): void => {
131
+ const query = search.trim()
132
+ void load(query === '' ? undefined : query)
133
+ }
121
134
 
122
135
  // Every async setState path guards with mountedRef, not just load(): a
123
136
  // promise settling after unmount would setState against the torn-down
124
137
  // environment (window is not defined, main-CI flake).
125
138
  const runTest = async (alias: string): Promise<void> => {
126
139
  if (!mountedRef.current) return
127
- setTestingAlias(alias)
140
+ setTestingAliases(prev => {
141
+ const next = new Set(prev)
142
+ next.add(alias)
143
+ return next
144
+ })
128
145
  try {
129
146
  const result = await api.testHost(alias)
130
147
  if (!mountedRef.current) return
@@ -133,7 +150,14 @@ export function HostsTab({ api, onConnect }: HostsTabProps) {
133
150
  if (!mountedRef.current) return
134
151
  setTestResults(prev => ({ ...prev, [alias]: { ok: false, error: errorMessage(cause) } }))
135
152
  } finally {
136
- if (mountedRef.current) setTestingAlias(null)
153
+ if (mountedRef.current) {
154
+ setTestingAliases(prev => {
155
+ if (!prev.has(alias)) return prev
156
+ const next = new Set(prev)
157
+ next.delete(alias)
158
+ return next
159
+ })
160
+ }
137
161
  }
138
162
  }
139
163
 
@@ -142,7 +166,7 @@ export function HostsTab({ api, onConnect }: HostsTabProps) {
142
166
  try {
143
167
  await api.deleteHost(alias)
144
168
  if (!mountedRef.current) return
145
- void load()
169
+ reloadCurrent()
146
170
  } catch (cause) {
147
171
  if (!mountedRef.current) return
148
172
  setError(errorMessage(cause))
@@ -168,7 +192,7 @@ export function HostsTab({ api, onConnect }: HostsTabProps) {
168
192
  if (!mountedRef.current) return
169
193
  setNotice(tt('hosts.imported', { parsed: result.parsed, added: result.added, skipped: result.skipped }))
170
194
  setImportSkips(result.skippedBlocks)
171
- void load()
195
+ reloadCurrent()
172
196
  } catch (cause) {
173
197
  if (!mountedRef.current) return
174
198
  setError(errorMessage(cause))
@@ -179,6 +203,7 @@ export function HostsTab({ api, onConnect }: HostsTabProps) {
179
203
 
180
204
  const renderHostRow = (host: SshPanelHostSummary): ReactNode => {
181
205
  const test = testResults[host.alias]
206
+ const testing = testingAliases.has(host.alias)
182
207
  return (
183
208
  <tr key={host.alias}>
184
209
  <td className={css.mono}>{host.alias}</td>
@@ -198,10 +223,10 @@ export function HostsTab({ api, onConnect }: HostsTabProps) {
198
223
  <td className={css.cellMuted}>{host.description ?? ''}</td>
199
224
  <td>
200
225
  <div className={css.actions}>
201
- <button type="button" className={css.linkButton} disabled={testingAlias === host.alias} onClick={() => { void runTest(host.alias) }}>
202
- {testingAlias === host.alias ? tt('hosts.testing') : tt('hosts.test')}
226
+ <button type="button" className={css.linkButton} disabled={testing} onClick={() => { void runTest(host.alias) }}>
227
+ {testing ? tt('hosts.testing') : tt('hosts.test')}
203
228
  </button>
204
- {testingAlias === host.alias && <span className={css.spinner} aria-hidden="true" />}
229
+ {testing && <span className={css.spinner} aria-hidden="true" />}
205
230
  {test !== undefined && (
206
231
  <span className={css.inlineTest} data-status={test.ok ? 'ok' : 'fail'}>
207
232
  {test.ok ? tt('hosts.testOk', { latency: test.latencyMs ?? 0 }) : tt('hosts.testFail', { error: test.error ?? '' })}
@@ -320,7 +345,7 @@ export function HostsTab({ api, onConnect }: HostsTabProps) {
320
345
  api={api}
321
346
  editing={dialog.mode === 'edit' ? dialog.host : null}
322
347
  onClose={() => { setDialog(null) }}
323
- onSaved={() => { setDialog(null); void load() }}
348
+ onSaved={() => { setDialog(null); reloadCurrent() }}
324
349
  />
325
350
  )}
326
351
  </div>
@@ -110,6 +110,8 @@ export function TerminalTab({ api, controller, presetAlias, terminalFont }: Term
110
110
  const dataSubRef = useRef<IDisposable | null>(null)
111
111
  /** Tab whose screen the terminal currently holds. */
112
112
  const renderedRef = useRef<string | undefined>(undefined)
113
+ /** Last geometry pushed to the active socket to skip duplicate resizes. */
114
+ const lastSentSizeRef = useRef<{ connection: TerminalConnection; cols: number; rows: number } | null>(null)
113
115
  /** Tabs with a background close in flight, so one click cannot open two. */
114
116
  const closingRef = useRef<Set<string>>(new Set())
115
117
  const fontSource = terminalFont ?? NO_FONT_SOURCE
@@ -129,7 +131,10 @@ export function TerminalTab({ api, controller, presetAlias, terminalFont }: Term
129
131
  term.options.fontFamily = next
130
132
  fitRef.current?.fit()
131
133
  const link = linkRef.current
132
- if (link !== null) link.connection.resize(term.cols, term.rows)
134
+ if (link !== null) {
135
+ link.connection.resize(term.cols, term.rows)
136
+ lastSentSizeRef.current = { connection: link.connection, cols: term.cols, rows: term.rows }
137
+ }
133
138
  }, [fontOverride])
134
139
 
135
140
  // Fetch the host list on tab activation.
@@ -159,17 +164,16 @@ export function TerminalTab({ api, controller, presetAlias, terminalFont }: Term
159
164
  // height and the last line is clipped below the fold). ResizeObserver may
160
165
  // be absent (jsdom tests); the window listener then remains the only path.
161
166
  useEffect(() => {
162
- let lastCols = -1
163
- let lastRows = -1
164
167
  const sync = (): void => {
165
168
  const term = termRef.current
166
169
  const fit = fitRef.current
167
170
  if (term === null || fit === null) return
168
171
  fit.fit()
169
172
  const link = linkRef.current
170
- if (link !== null && (term.cols !== lastCols || term.rows !== lastRows)) {
171
- lastCols = term.cols
172
- lastRows = term.rows
173
+ if (link === null) return
174
+ const last = lastSentSizeRef.current
175
+ if (last === null || last.connection !== link.connection || term.cols !== last.cols || term.rows !== last.rows) {
176
+ lastSentSizeRef.current = { connection: link.connection, cols: term.cols, rows: term.rows }
173
177
  link.connection.resize(term.cols, term.rows)
174
178
  }
175
179
  }
@@ -336,11 +340,12 @@ export function TerminalTab({ api, controller, presetAlias, terminalFont }: Term
336
340
  }
337
341
  if (tab.status === 'connected' && tab.sessionId !== undefined) {
338
342
  const sessionId = tab.sessionId
343
+ // Always clear retained output before attaching: the host replays its
344
+ // full scrollback on attach, including after a panel remount where the
345
+ // local xterm starts fresh (renderedRef.current === undefined).
346
+ controller.clearTerminalOutput(tab.id)
339
347
  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
348
  view.term.reset()
343
- controller.clearTerminalOutput(tab.id)
344
349
  renderedRef.current = tab.id
345
350
  }
346
351
  bindConnection(tab, api.attachTerminal(sessionId, view.term.cols, view.term.rows))