@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.
@@ -72,6 +72,11 @@ export function TunnelsTab({ api, active = true }: TunnelsTabProps) {
72
72
  // state, and the list is diff-set so an unchanged poll tick keeps the
73
73
  // previous state reference (no wasted re-render).
74
74
  const seqRef = useRef(0)
75
+ const mountedRef = useRef(true)
76
+ useEffect(() => {
77
+ mountedRef.current = true
78
+ return () => { mountedRef.current = false }
79
+ }, [])
75
80
  const automaticRead = useRef<{ running: boolean; resume?: () => void }>({ running: false })
76
81
  useEffect(() => {
77
82
  if (!active) return
@@ -128,24 +133,26 @@ export function TunnelsTab({ api, active = true }: TunnelsTabProps) {
128
133
  }
129
134
  }, [api, active])
130
135
 
131
- const refresh = async (): Promise<void> => {
136
+ const refresh = async (preserveError = false): Promise<void> => {
132
137
  const seq = ++seqRef.current
133
138
  try {
134
139
  const list = await api.listTunnels()
135
- if (seq !== seqRef.current) return
140
+ if (!mountedRef.current || seq !== seqRef.current) return
136
141
  setTunnels(list)
137
- setError(null)
142
+ if (!preserveError) setError(null)
138
143
  } catch (cause) {
139
- if (seq !== seqRef.current) return
140
- setError(errorMessage(cause))
144
+ if (!mountedRef.current || seq !== seqRef.current) return
145
+ if (!preserveError) setError(errorMessage(cause))
141
146
  }
142
147
  }
143
148
 
144
149
  const stopTunnel = async (tunnelId: string): Promise<void> => {
145
150
  try {
146
151
  await api.stopTunnel(tunnelId)
152
+ if (!mountedRef.current) return
147
153
  await refresh()
148
154
  } catch (cause) {
155
+ if (!mountedRef.current) return
149
156
  setError(errorMessage(cause))
150
157
  }
151
158
  }
@@ -155,11 +162,13 @@ export function TunnelsTab({ api, active = true }: TunnelsTabProps) {
155
162
  setBusy(true)
156
163
  try {
157
164
  await api.stopAllTunnels(alias === '' ? undefined : alias)
165
+ if (!mountedRef.current) return
158
166
  await refresh()
159
167
  } catch (cause) {
168
+ if (!mountedRef.current) return
160
169
  setError(errorMessage(cause))
161
170
  } finally {
162
- setBusy(false)
171
+ if (mountedRef.current) setBusy(false)
163
172
  }
164
173
  }
165
174
 
@@ -176,6 +185,7 @@ export function TunnelsTab({ api, active = true }: TunnelsTabProps) {
176
185
  return
177
186
  }
178
187
  setBusy(true)
188
+ setError(null)
179
189
  setNotice(null)
180
190
  try {
181
191
  const tunnel = await api.startTunnel({
@@ -184,15 +194,22 @@ export function TunnelsTab({ api, active = true }: TunnelsTabProps) {
184
194
  remoteHost: remoteHost.trim() === '' ? undefined : remoteHost.trim(),
185
195
  localPort: localPortNumber,
186
196
  })
197
+ if (!mountedRef.current) return
198
+ if (tunnel.state === 'failed') {
199
+ setError(tt('tunnel.failed', { error: tunnel.error ?? 'unknown error' }))
200
+ await refresh(true)
201
+ return
202
+ }
187
203
  setNotice(tt('tunnel.started', { localPort: tunnel.localPort }))
188
204
  setRemotePort('')
189
205
  setRemoteHost('')
190
206
  setLocalPort('')
191
207
  await refresh()
192
208
  } catch (cause) {
209
+ if (!mountedRef.current) return
193
210
  setError(tt('tunnel.failed', { error: errorMessage(cause) }))
194
211
  } finally {
195
- setBusy(false)
212
+ if (mountedRef.current) setBusy(false)
196
213
  }
197
214
  }
198
215
 
@@ -117,13 +117,55 @@ const MAX_RETAINED_BYTES = 256 * 1024
117
117
  */
118
118
  function utf8Bytes(text: string): number {
119
119
  let bytes = 0
120
- for (const char of text) {
121
- const code = char.codePointAt(0) ?? 0
122
- bytes += code < 0x80 ? 1 : code < 0x800 ? 2 : code < 0x10000 ? 3 : 4
120
+ for (let i = 0; i < text.length; i += 1) {
121
+ const code = text.charCodeAt(i)
122
+ if (code >= 0xd800 && code <= 0xdbff && i + 1 < text.length) {
123
+ const low = text.charCodeAt(i + 1)
124
+ if (low >= 0xdc00 && low <= 0xdfff) {
125
+ bytes += 4
126
+ i += 1
127
+ continue
128
+ }
129
+ }
130
+ bytes += code < 0x80 ? 1 : code < 0x800 ? 2 : 3
123
131
  }
124
132
  return bytes
125
133
  }
126
134
 
135
+ /** Trim leading code units from an oversized chunk so its tail fits maxBytes without splitting surrogate pairs. */
136
+ function trimTrailingUtf8(text: string, maxBytes: number): { text: string; bytes: number } {
137
+ let bytes = 0
138
+ let start = text.length
139
+ for (let i = text.length - 1; i >= 0; i -= 1) {
140
+ const code = text.charCodeAt(i)
141
+ let charBytes: number
142
+ let stepStart = i
143
+ if (code >= 0xdc00 && code <= 0xdfff && i > 0) {
144
+ const high = text.charCodeAt(i - 1)
145
+ if (high >= 0xd800 && high <= 0xdbff) {
146
+ charBytes = 4
147
+ stepStart = i - 1
148
+ } else {
149
+ charBytes = 3
150
+ }
151
+ } else {
152
+ charBytes = code < 0x80 ? 1 : code < 0x800 ? 2 : 3
153
+ }
154
+ if (bytes + charBytes > maxBytes) break
155
+ bytes += charBytes
156
+ start = stepStart
157
+ i = stepStart
158
+ }
159
+ return { text: start === 0 ? text : text.slice(start), bytes }
160
+ }
161
+
162
+ interface RetainedScreen {
163
+ chunks: string[]
164
+ chunkBytes: number[]
165
+ head: number
166
+ bytes: number
167
+ }
168
+
127
169
  /** The panel state owner the sidebar row and the view both read. */
128
170
  export class PanelController {
129
171
  private panelOpen = false
@@ -138,7 +180,7 @@ export class PanelController {
138
180
  * not re-render the panel on every chunk, and only the terminal view reads
139
181
  * this (when a tab has no session left to replay from).
140
182
  */
141
- private readonly retainedScreens = new Map<string, { chunks: string[]; bytes: number }>()
183
+ private readonly retainedScreens = new Map<string, RetainedScreen>()
142
184
  /**
143
185
  * Sockets that outlived their view while still connecting. Their session id
144
186
  * is unknown, so they cannot be detached yet; keeping them here is what
@@ -403,19 +445,42 @@ export class PanelController {
403
445
 
404
446
  /** Append one output chunk to the retained screen of a tab. */
405
447
  appendTerminalOutput(id: string, chunk: string): void {
406
- const screen = this.retainedScreens.get(id) ?? { chunks: [], bytes: 0 }
448
+ if (chunk === '') return
449
+ const size = utf8Bytes(chunk)
450
+ if (size > MAX_RETAINED_BYTES) {
451
+ const trimmed = trimTrailingUtf8(chunk, MAX_RETAINED_BYTES)
452
+ this.retainedScreens.set(id, {
453
+ chunks: trimmed.text === '' ? [] : [trimmed.text],
454
+ chunkBytes: trimmed.text === '' ? [] : [trimmed.bytes],
455
+ head: 0,
456
+ bytes: trimmed.bytes,
457
+ })
458
+ return
459
+ }
460
+ let screen = this.retainedScreens.get(id)
461
+ if (screen === undefined) {
462
+ this.retainedScreens.set(id, { chunks: [chunk], chunkBytes: [size], head: 0, bytes: size })
463
+ return
464
+ }
407
465
  screen.chunks.push(chunk)
408
- screen.bytes += utf8Bytes(chunk)
409
- while (screen.bytes > MAX_RETAINED_BYTES && screen.chunks.length > 1) {
410
- const dropped = screen.chunks.shift() ?? ''
411
- screen.bytes -= utf8Bytes(dropped)
466
+ screen.chunkBytes.push(size)
467
+ screen.bytes += size
468
+ while (screen.bytes > MAX_RETAINED_BYTES && screen.chunks.length - screen.head > 1) {
469
+ screen.bytes -= screen.chunkBytes[screen.head]!
470
+ screen.head += 1
471
+ }
472
+ if (screen.head >= 256 && screen.head * 2 >= screen.chunks.length) {
473
+ screen.chunks = screen.chunks.slice(screen.head)
474
+ screen.chunkBytes = screen.chunkBytes.slice(screen.head)
475
+ screen.head = 0
412
476
  }
413
- this.retainedScreens.set(id, screen)
414
477
  }
415
478
 
416
479
  /** The retained screen of a tab, concatenated for a redraw. */
417
480
  readTerminalOutput(id: string): string {
418
- return (this.retainedScreens.get(id)?.chunks ?? []).join('')
481
+ const screen = this.retainedScreens.get(id)
482
+ if (screen === undefined) return ''
483
+ return screen.head === 0 ? screen.chunks.join('') : screen.chunks.slice(screen.head).join('')
419
484
  }
420
485
 
421
486
  /** Forget the retained screen (a fresh replay from the host replaces it). */
@@ -6,11 +6,32 @@
6
6
  import type { ClusterResult } from '../protocol.ts'
7
7
  import { execCommand, type PoolEngine } from './connection-pool.ts'
8
8
 
9
- interface ClusterOptions {
10
- command: string
9
+ /** Target selector fields shared by cluster engine, routes, and agent tool. */
10
+ export interface ClusterSelector {
11
11
  aliases?: string[]
12
12
  environment?: string
13
13
  tags?: string[]
14
+ }
15
+
16
+ function normalizeStringList(values: unknown): string[] | undefined {
17
+ if (!Array.isArray(values)) return undefined
18
+ return values
19
+ .filter((value): value is string => typeof value === 'string')
20
+ .map(value => value.trim())
21
+ .filter(value => value !== '')
22
+ }
23
+
24
+ /** Whether at least one trimmed non-empty cluster target filter is present. */
25
+ export function hasClusterSelector(options: ClusterSelector): boolean {
26
+ const aliases = normalizeStringList(options.aliases)
27
+ if (aliases !== undefined && aliases.length > 0) return true
28
+ if (typeof options.environment === 'string' && options.environment.trim() !== '') return true
29
+ const tags = normalizeStringList(options.tags)
30
+ return tags !== undefined && tags.length > 0
31
+ }
32
+
33
+ interface ClusterOptions extends ClusterSelector {
34
+ command: string
14
35
  timeoutMs?: number
15
36
  maxWorkers?: number
16
37
  /** Caller cancellation, forwarded to every host's command. */
@@ -19,23 +40,25 @@ interface ClusterOptions {
19
40
 
20
41
  /** Run one command against many hosts concurrently. */
21
42
  export async function cluster(engine: PoolEngine, options: ClusterOptions): Promise<ClusterResult[]> {
22
- const hasAliases = Array.isArray(options.aliases) && options.aliases.some(alias => typeof alias === 'string' && alias.trim() !== '')
23
- const hasEnvironment = typeof options.environment === 'string' && options.environment.trim() !== ''
24
- const hasTags = Array.isArray(options.tags) && options.tags.some(tag => typeof tag === 'string' && tag.trim() !== '')
25
- if (!hasAliases && !hasEnvironment && !hasTags) {
43
+ const aliases = normalizeStringList(options.aliases)
44
+ const environment = typeof options.environment === 'string' && options.environment.trim() !== ''
45
+ ? options.environment.trim()
46
+ : undefined
47
+ const tags = normalizeStringList(options.tags)
48
+ if (!hasClusterSelector({ aliases, environment, tags })) {
26
49
  throw new Error('ssh_cluster requires aliases, environment, or tags to limit the target set')
27
50
  }
28
51
 
29
52
  let targets = engine.store.list()
30
- if (options.aliases !== undefined && options.aliases.length > 0) {
31
- targets = targets.filter(entry => options.aliases!.includes(entry.alias))
53
+ if (aliases !== undefined && aliases.length > 0) {
54
+ targets = targets.filter(entry => aliases.includes(entry.alias))
32
55
  }
33
- if (options.environment !== undefined && options.environment !== '') {
34
- targets = targets.filter(entry => entry.environment === options.environment)
56
+ if (environment !== undefined) {
57
+ targets = targets.filter(entry => entry.environment === environment)
35
58
  }
36
- if (options.tags !== undefined && options.tags.length > 0) {
59
+ if (tags !== undefined && tags.length > 0) {
37
60
  // ALL semantics (matches the ssh_cluster tool description).
38
- targets = targets.filter(entry => options.tags!.every(tag => entry.tags.includes(tag)))
61
+ targets = targets.filter(entry => tags.every(tag => entry.tags.includes(tag)))
39
62
  }
40
63
  if (targets.length === 0) return []
41
64
  if (options.maxWorkers !== undefined && (!Number.isInteger(options.maxWorkers) || options.maxWorkers < 1)) {
@@ -49,7 +72,16 @@ export async function cluster(engine: PoolEngine, options: ClusterOptions): Prom
49
72
  const entry = queue.shift()!
50
73
  try {
51
74
  const result = await execCommand(engine, entry.alias, options.command, options.timeoutMs, options.signal)
52
- results.push({ alias: entry.alias, ok: result.success, exitCode: result.exitCode, timedOut: result.timedOut, stdout: result.stdout, stderr: result.stderr, durationMs: result.durationMs })
75
+ results.push({
76
+ alias: entry.alias,
77
+ ok: result.success,
78
+ exitCode: result.exitCode,
79
+ timedOut: result.timedOut,
80
+ stdout: result.stdout,
81
+ stderr: result.stderr,
82
+ durationMs: result.durationMs,
83
+ ...(result.error !== undefined ? { error: result.error } : {}),
84
+ })
53
85
  } catch (error) {
54
86
  results.push({ alias: entry.alias, ok: false, error: error instanceof Error ? error.message : String(error) })
55
87
  }
@@ -5,6 +5,7 @@
5
5
 
6
6
  import { existsSync, readFileSync } from 'node:fs'
7
7
  import type { Duplex } from 'node:stream'
8
+ import { StringDecoder } from 'node:string_decoder'
8
9
  import { Client, type ConnectConfig } from 'ssh2'
9
10
  import type { ExecResult, SshHostEntry } from '../protocol.ts'
10
11
  import { expandHome, normalizeAgentPath, type HostStore } from '../store.ts'
@@ -216,14 +217,21 @@ export function connectClient(config: ConnectConfig, onKeyboardInteractive?: Key
216
217
  const cause = error instanceof Error ? error : new Error(String(error))
217
218
  reject(isReadyTimeout(cause) ? new Error(readyTimeoutMessage(config.readyTimeout, handshakeComplete)) : cause)
218
219
  }
220
+ const onPreReadyClose = (): void => {
221
+ fail(new Error('SSH connection closed before ready'))
222
+ }
219
223
  client.once('handshake', () => {
220
224
  handshakeComplete = true
221
225
  })
222
226
  client.once('ready', () => {
223
227
  if (settled) return
224
228
  settled = true
229
+ client.removeListener?.('close', onPreReadyClose)
225
230
  resolve(client)
226
231
  })
232
+ // ssh2 clears readyTimeout and emits only 'close' (no 'error') when the peer
233
+ // closes cleanly after sending the SSH banner; settle instead of hanging forever.
234
+ client.once('close', onPreReadyClose)
227
235
  client.on('keyboard-interactive', (name, instructions, instructionsLang, prompts, finish) => {
228
236
  if (onKeyboardInteractive !== undefined) {
229
237
  onKeyboardInteractive(name, instructions, instructionsLang, prompts.map(p => ({ prompt: p.prompt, echo: Boolean(p.echo) })), finish)
@@ -250,18 +258,43 @@ export function connectClient(config: ConnectConfig, onKeyboardInteractive?: Key
250
258
  })
251
259
  }
252
260
 
253
- /** Cap captured output at the configured byte budget (marks truncation). */
254
- export function appendOutput(target: { text: string; truncated: boolean }, chunk: Buffer, maxBytes: number): void {
255
- if (target.truncated) return
256
- if (target.text.length + chunk.length > maxBytes) {
257
- let cut = chunk.toString('utf8').slice(0, maxBytes - target.text.length)
258
- // Never split a surrogate pair at the cut boundary.
259
- if (/[\uD800-\uDBFF]$/.test(cut)) cut = cut.slice(0, -1)
261
+ /** Truncate `text` so its UTF-8 encoding fits within `maxBytes` without splitting code points. */
262
+ function sliceUtf8ToBytes(text: string, maxBytes: number): string {
263
+ if (maxBytes <= 0 || text === '') return ''
264
+ if (Buffer.byteLength(text, 'utf8') <= maxBytes) return text
265
+ let bytes = 0
266
+ let end = 0
267
+ for (const char of text) {
268
+ const code = char.codePointAt(0)!
269
+ const charBytes = code < 0x80 ? 1 : code < 0x800 ? 2 : code < 0x10000 ? 3 : 4
270
+ if (bytes + charBytes > maxBytes) break
271
+ bytes += charBytes
272
+ end += char.length
273
+ }
274
+ return text.slice(0, end)
275
+ }
276
+
277
+ /** Append an already-decoded string chunk under a UTF-8 byte budget. */
278
+ function appendDecodedOutput(target: { text: string; truncated: boolean; bytes?: number }, decoded: string, maxBytes: number): void {
279
+ if (target.truncated || decoded === '') return
280
+ const usedBytes = target.bytes ?? Buffer.byteLength(target.text, 'utf8')
281
+ const decodedBytes = Buffer.byteLength(decoded, 'utf8')
282
+ if (usedBytes + decodedBytes > maxBytes) {
283
+ const cut = sliceUtf8ToBytes(decoded, maxBytes - usedBytes)
260
284
  target.text += cut + '…[output truncated]'
285
+ target.bytes = maxBytes
261
286
  target.truncated = true
262
287
  return
263
288
  }
264
- target.text += chunk.toString('utf8')
289
+ target.text += decoded
290
+ target.bytes = usedBytes + decodedBytes
291
+ }
292
+
293
+ /** Cap captured output at the configured UTF-8 byte budget (marks truncation). */
294
+ export function appendOutput(target: { text: string; truncated: boolean; bytes?: number }, chunk: Buffer, maxBytes: number, decoder?: StringDecoder): void {
295
+ if (target.truncated) return
296
+ const decoded = decoder !== undefined ? decoder.write(chunk) : chunk.toString('utf8')
297
+ appendDecodedOutput(target, decoded, maxBytes)
265
298
  }
266
299
 
267
300
  /** The ProxyCommand token source for one entry. */
@@ -431,8 +464,43 @@ export async function connectChain(
431
464
  }
432
465
  }
433
466
 
467
+ interface PoolLifecycle {
468
+ disposed: boolean
469
+ generations: Map<string, number>
470
+ }
471
+
472
+ const poolLifecycles = new WeakMap<PoolEngine, PoolLifecycle>()
473
+
474
+ function lifecycleOf(engine: PoolEngine): PoolLifecycle {
475
+ let state = poolLifecycles.get(engine)
476
+ if (state === undefined) {
477
+ state = { disposed: false, generations: new Map() }
478
+ poolLifecycles.set(engine, state)
479
+ }
480
+ return state
481
+ }
482
+
483
+ /**
484
+ * Invalidate any in-flight acquire for `alias` so a connection still handshaking
485
+ * under stale config or before a delete cannot enter `engine.pool` after completion.
486
+ */
487
+ export function invalidateAlias(engine: PoolEngine, alias: string): void {
488
+ const state = lifecycleOf(engine)
489
+ state.generations.set(alias, (state.generations.get(alias) ?? 0) + 1)
490
+ engine.acquireQueue.delete(alias)
491
+ }
492
+
493
+ /** Mark the pool disposed so in-flight acquires tear down instead of entering the pool. */
494
+ export function markPoolDisposed(engine: PoolEngine): void {
495
+ const state = lifecycleOf(engine)
496
+ state.disposed = true
497
+ engine.acquireQueue.clear()
498
+ }
499
+
434
500
  /** Connect (or reuse) the pooled chain for one alias; pins nothing. */
435
501
  export async function acquire(engine: PoolEngine, alias: string): Promise<PoolRecord> {
502
+ const state = lifecycleOf(engine)
503
+ if (state.disposed) throw new Error('ssh engine has been disposed')
436
504
  const pending = engine.acquireQueue.get(alias)
437
505
  if (pending !== undefined) return pending
438
506
  const task = doAcquire(engine, alias)
@@ -445,12 +513,32 @@ export async function acquire(engine: PoolEngine, alias: string): Promise<PoolRe
445
513
  }
446
514
 
447
515
  async function doAcquire(engine: PoolEngine, alias: string): Promise<PoolRecord> {
516
+ const state = lifecycleOf(engine)
517
+ if (state.disposed) throw new Error('ssh engine has been disposed')
518
+ const gen = state.generations.get(alias) ?? 0
448
519
  const entry = engine.store.find(alias)
449
520
  if (entry === undefined) throw new Error('alias \'' + alias + '\' not found — add it first')
450
521
  const { client, hops } = await connectChain(engine, entry)
451
522
  const record: PoolRecord = { client, hops, idleAt: Date.now(), pinned: false, broken: false, inFlight: 0 }
452
- client.on('error', () => { record.broken = true })
453
- client.on('close', () => { record.broken = true })
523
+ if (state.disposed || (state.generations.get(alias) ?? 0) !== gen) {
524
+ endRecordChain(record)
525
+ throw new Error(state.disposed
526
+ ? 'ssh engine disposed while connecting \'' + alias + '\''
527
+ : 'host \'' + alias + '\' configuration changed while connecting')
528
+ }
529
+ const markBroken = (): void => { record.broken = true }
530
+ const onTargetClosed = (): void => {
531
+ record.broken = true
532
+ for (const hop of record.hops) {
533
+ try { hop.end() } catch { /* already closed */ }
534
+ }
535
+ }
536
+ client.on('error', markBroken)
537
+ client.on('close', onTargetClosed)
538
+ for (const hop of hops) {
539
+ hop.on('error', markBroken)
540
+ hop.on('close', markBroken)
541
+ }
454
542
  engine.pool.set(alias, record)
455
543
  return record
456
544
  }
@@ -491,6 +579,32 @@ function isAborted(signal?: AbortSignal): boolean {
491
579
  return signal?.aborted === true
492
580
  }
493
581
 
582
+ /** Race an in-flight promise against an optional AbortSignal without leaving an unhandled rejection behind. */
583
+ function waitWithSignal<T>(promise: Promise<T>, signal?: AbortSignal): Promise<T> {
584
+ if (signal === undefined) return promise
585
+ if (signal.aborted) {
586
+ promise.catch(() => undefined)
587
+ return Promise.reject(new Error('command cancelled by the caller'))
588
+ }
589
+ return new Promise<T>((resolve, reject) => {
590
+ const onAbort = (): void => {
591
+ promise.catch(() => undefined)
592
+ reject(new Error('command cancelled by the caller'))
593
+ }
594
+ signal.addEventListener('abort', onAbort, { once: true })
595
+ promise.then(
596
+ (value) => {
597
+ signal.removeEventListener('abort', onAbort)
598
+ resolve(value)
599
+ },
600
+ (error) => {
601
+ signal.removeEventListener('abort', onAbort)
602
+ reject(error)
603
+ },
604
+ )
605
+ })
606
+ }
607
+
494
608
  /**
495
609
  * Run `fn` with a live client for `alias`, reconnecting (up to the
496
610
  * attempt budget) when the connection broke mid-flight.
@@ -504,7 +618,7 @@ export async function withClient<T>(engine: PoolEngine, alias: string, fn: (clie
504
618
  let record = engine.pool.get(alias)
505
619
  if (record === undefined || record.broken) {
506
620
  if (record !== undefined) disposeRecord(engine, alias, record)
507
- record = await acquire(engine, alias)
621
+ record = await waitWithSignal(acquire(engine, alias), signal)
508
622
  }
509
623
  record.idleAt = Date.now()
510
624
  record.inFlight += 1
@@ -554,8 +668,16 @@ export async function execCommand(engine: PoolEngine, alias: string, command: st
554
668
  // in a mutable slot because abort may fire before client.exec calls back.
555
669
  let aborted = signal !== undefined && signal.aborted
556
670
  let settled = false
557
- const stdout = { text: '', truncated: false }
558
- const stderr = { text: '', truncated: false }
671
+ const stdout = { text: '', truncated: false, bytes: 0 }
672
+ const stderr = { text: '', truncated: false, bytes: 0 }
673
+ const stdoutDecoder = new StringDecoder('utf8')
674
+ const stderrDecoder = new StringDecoder('utf8')
675
+ const flushDecoders = (): void => {
676
+ const outTail = stdoutDecoder.end()
677
+ if (outTail !== '') appendDecodedOutput(stdout, outTail, engine.opts.maxOutputBytes)
678
+ const errTail = stderrDecoder.end()
679
+ if (errTail !== '') appendDecodedOutput(stderr, errTail, engine.opts.maxOutputBytes)
680
+ }
559
681
  let timer: ReturnType<typeof setTimeout> | undefined
560
682
  let kill = (): void => { /* channel not open yet */ }
561
683
  /** One cancelled outcome: the remote channel was killed on caller request. */
@@ -573,6 +695,7 @@ export async function execCommand(engine: PoolEngine, alias: string, command: st
573
695
  settled = true
574
696
  if (timer !== undefined) clearTimeout(timer)
575
697
  signal?.removeEventListener('abort', onAbort)
698
+ flushDecoders()
576
699
  resolve(cancelledResult())
577
700
  }
578
701
  const onAbort = (): void => {
@@ -613,6 +736,7 @@ export async function execCommand(engine: PoolEngine, alias: string, command: st
613
736
  settled = true
614
737
  if (timer !== undefined) clearTimeout(timer)
615
738
  signal?.removeEventListener('abort', onAbort)
739
+ flushDecoders()
616
740
  resolve({
617
741
  success: false,
618
742
  exitCode: null,
@@ -631,13 +755,14 @@ export async function execCommand(engine: PoolEngine, alias: string, command: st
631
755
  // channel close (the stream 'close' handler is then a no-op).
632
756
  finish()
633
757
  }, budget)
634
- stream.on('data', (chunk: Buffer) => appendOutput(stdout, chunk, engine.opts.maxOutputBytes))
635
- stream.stderr.on('data', (chunk: Buffer) => appendOutput(stderr, chunk, engine.opts.maxOutputBytes))
758
+ stream.on('data', (chunk: Buffer) => appendOutput(stdout, chunk, engine.opts.maxOutputBytes, stdoutDecoder))
759
+ stream.stderr.on('data', (chunk: Buffer) => appendOutput(stderr, chunk, engine.opts.maxOutputBytes, stderrDecoder))
636
760
  stream.on('close', (code: number | null) => {
637
761
  if (settled) return
638
762
  settled = true
639
763
  if (timer !== undefined) clearTimeout(timer)
640
764
  signal?.removeEventListener('abort', onAbort)
765
+ flushDecoders()
641
766
  // A caller cancellation settles as cancelled, never as a broken
642
767
  // connection: the latter would send withClient into a retry that
643
768
  // re-runs a command the caller asked to stop.
@@ -666,6 +791,7 @@ export async function execCommand(engine: PoolEngine, alias: string, command: st
666
791
  settled = true
667
792
  if (timer !== undefined) clearTimeout(timer)
668
793
  signal?.removeEventListener('abort', onAbort)
794
+ flushDecoders()
669
795
  if (aborted) {
670
796
  resolve(cancelledResult())
671
797
  return
@@ -96,8 +96,15 @@ export function startProxyCommand(rawCommand: string, target: ProxyTarget): Prox
96
96
  })
97
97
 
98
98
  let killed = false
99
+ let exited = false
100
+ let escalateTimer: ReturnType<typeof setTimeout> | undefined
101
+ const clearEscalate = (): void => {
102
+ if (escalateTimer === undefined) return
103
+ clearTimeout(escalateTimer)
104
+ escalateTimer = undefined
105
+ }
99
106
  const kill = (): void => {
100
- if (killed) return
107
+ if (killed || exited || child.exitCode !== null || child.signalCode !== null) return
101
108
  killed = true
102
109
  const pid = child.pid
103
110
  const group = process.platform !== 'win32' && pid !== undefined
@@ -105,13 +112,15 @@ export function startProxyCommand(rawCommand: string, target: ProxyTarget): Prox
105
112
  if (group) process.kill(-pid, 'SIGTERM')
106
113
  else child.kill()
107
114
  } catch { /* already gone */ }
108
- const escalate = setTimeout(() => {
115
+ escalateTimer = setTimeout(() => {
116
+ escalateTimer = undefined
117
+ if (exited || child.exitCode !== null || child.signalCode !== null) return
109
118
  try {
110
119
  if (group) process.kill(-pid, 'SIGKILL')
111
120
  else child.kill('SIGKILL')
112
121
  } catch { /* already gone */ }
113
122
  }, KILL_GRACE_MS)
114
- escalate.unref()
123
+ escalateTimer.unref()
115
124
  }
116
125
 
117
126
  function formatExitError(code: number | null, signal: NodeJS.Signals | null, stderrDetail: string): Error {
@@ -199,7 +208,6 @@ export function startProxyCommand(rawCommand: string, target: ProxyTarget): Prox
199
208
  // instead of the generic "connection lost before handshake" ssh2 produces
200
209
  // for a socket that simply closed.
201
210
  let stdoutEnded = false
202
- let exited = false
203
211
  const finishIfClean = (): void => {
204
212
  if (exited && stdoutEnded && !failed && !stream.destroyed) stream.push(null)
205
213
  }
@@ -214,6 +222,7 @@ export function startProxyCommand(rawCommand: string, target: ProxyTarget): Prox
214
222
  child.stdout?.on('error', (error: Error) => {
215
223
  fail(new Error('ProxyCommand stdout error: ' + error.message))
216
224
  })
225
+ let stdinErrorPending = false
217
226
  child.stdin?.on('error', (error: Error) => {
218
227
  // A broken pipe (EPIPE) on stdin occurs naturally when the proxy command
219
228
  // exits early or closes its standard input. Prevent unhandled EventEmitter errors.
@@ -221,22 +230,30 @@ export function startProxyCommand(rawCommand: string, target: ProxyTarget): Prox
221
230
  fail(formatExitError(child.exitCode, child.signalCode, stderr))
222
231
  return
223
232
  }
224
- const timer = setTimeout(() => {
225
- fail(new Error('ProxyCommand transport error: ' + error.message))
226
- }, 200)
227
- timer.unref()
228
- child.once('exit', (code, signal) => {
233
+ if (exited || child.exitCode !== null || stdinErrorPending || failed || stream.destroyed) return
234
+ stdinErrorPending = true
235
+ const onExit = (code: number | null, signal: NodeJS.Signals | null): void => {
236
+ stdinErrorPending = false
229
237
  clearTimeout(timer)
230
238
  if ((code !== null && code !== 0) || signal !== null) {
231
239
  fail(formatExitError(code, signal, stderr))
232
240
  }
233
- })
241
+ }
242
+ const timer = setTimeout(() => {
243
+ stdinErrorPending = false
244
+ child.removeListener('exit', onExit)
245
+ fail(new Error('ProxyCommand transport error: ' + error.message))
246
+ }, 200)
247
+ timer.unref()
248
+ child.once('exit', onExit)
234
249
  })
235
250
  child.on('error', (error: Error) => {
251
+ clearEscalate()
236
252
  fail(new Error('ProxyCommand could not start: ' + error.message))
237
253
  })
238
254
  child.on('exit', (code, signal) => {
239
255
  exited = true
256
+ clearEscalate()
240
257
  if ((code !== null && code !== 0) || signal !== null) {
241
258
  fail(formatExitError(code, signal, stderr))
242
259
  return