dsh-remote-vs 0.24.0 → 0.25.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 (61) hide show
  1. package/README.en.md +40 -10
  2. package/README.md +31 -9
  3. package/lib/client.js +2616 -542
  4. package/lib/index.js +186 -40
  5. package/lib/types/client/CodeEditor.d.ts +17 -0
  6. package/lib/types/client/EditorPane.d.ts +16 -5
  7. package/lib/types/client/FloatingPlaceholder.d.ts +16 -5
  8. package/lib/types/client/RemoteEditorView.d.ts +13 -10
  9. package/lib/types/client/RemoteRoot.d.ts +5 -5
  10. package/lib/types/client/TerminalSnippets.d.ts +36 -0
  11. package/lib/types/client/TerminalView.d.ts +1 -1
  12. package/lib/types/client/XTerm.d.ts +33 -0
  13. package/lib/types/client/editor-capability.d.ts +27 -0
  14. package/lib/types/client/i18n.d.ts +1 -1
  15. package/lib/types/client/store.d.ts +59 -4
  16. package/lib/types/client/terminal-input.d.ts +23 -0
  17. package/lib/types/client/terminal-snippets.d.ts +86 -0
  18. package/lib/types/client/vsc/breadcrumb.d.ts +30 -0
  19. package/lib/types/client/vsc/editor-caret.d.ts +32 -0
  20. package/lib/types/client/vsc/editor-langs.d.ts +9 -0
  21. package/lib/types/client/vsc/editor-settings.d.ts +55 -0
  22. package/lib/types/client/vsc/image-preview.d.ts +36 -0
  23. package/lib/types/client/vsc/kit.d.ts +2 -0
  24. package/lib/types/client/vsc/terminal-clipboard.d.ts +15 -0
  25. package/lib/types/client/vsc/terminal-line.d.ts +25 -0
  26. package/lib/types/client/vsc/terminal-links.d.ts +62 -0
  27. package/lib/types/client/vsc/terminal-theme.d.ts +22 -0
  28. package/lib/types/client/vsc/terminal-writer.d.ts +52 -0
  29. package/lib/types/pool.d.ts +25 -0
  30. package/lib/types/terminal.d.ts +25 -1
  31. package/package.json +1 -1
  32. package/src/client/CodeEditor.tsx +54 -2
  33. package/src/client/EditorPane.tsx +485 -107
  34. package/src/client/FloatingPlaceholder.tsx +34 -5
  35. package/src/client/RemoteEditorView.tsx +14 -11
  36. package/src/client/RemoteRoot.tsx +20 -125
  37. package/src/client/TerminalSnippets.tsx +357 -0
  38. package/src/client/TerminalView.tsx +50 -1
  39. package/src/client/XTerm.tsx +228 -58
  40. package/src/client/auto-open-remote.ts +11 -9
  41. package/src/client/editor-capability.ts +42 -0
  42. package/src/client/i18n.ts +148 -6
  43. package/src/client/index.tsx +22 -6
  44. package/src/client/store.tsx +165 -13
  45. package/src/client/terminal-input.ts +44 -0
  46. package/src/client/terminal-snippets.ts +216 -0
  47. package/src/client/vsc/breadcrumb.tsx +251 -0
  48. package/src/client/vsc/editor-caret.ts +30 -0
  49. package/src/client/vsc/editor-langs.ts +20 -0
  50. package/src/client/vsc/editor-settings.ts +146 -0
  51. package/src/client/vsc/editor-theme.ts +4 -5
  52. package/src/client/vsc/image-preview.tsx +110 -0
  53. package/src/client/vsc/kit.tsx +20 -1
  54. package/src/client/vsc/terminal-clipboard.ts +19 -0
  55. package/src/client/vsc/terminal-line.ts +101 -0
  56. package/src/client/vsc/terminal-links.ts +166 -0
  57. package/src/client/vsc/terminal-theme.ts +71 -0
  58. package/src/client/vsc/terminal-writer.ts +112 -0
  59. package/src/client/vsc/vsc.css +687 -48
  60. package/src/pool.ts +99 -27
  61. package/src/terminal.ts +160 -6
package/src/pool.ts CHANGED
@@ -245,6 +245,24 @@ interface Slots {
245
245
 
246
246
  export class RemotePool {
247
247
  private readonly conns = new Map<string, Pooled>()
248
+ /**
249
+ * Dedicated connections for PTY shells (one per alias).
250
+ *
251
+ * Why a SECOND connection instead of a channel on the shared one: ssh2
252
+ * multiplexes channels over ONE TCP connection, and SSH has no per-channel
253
+ * priority or flow control. A large SFTP transfer / git output on that
254
+ * connection therefore delays everything else on it — including the echo of a
255
+ * keystroke — which is exactly the "typing stutters when something else is
256
+ * moving data" report. A terminal gets its own connection, so its bytes never
257
+ * queue behind browse/exec traffic, and shells stop consuming the shared
258
+ * connection's channel budget as well.
259
+ *
260
+ * Cost: one extra SSH handshake per alias the first time a terminal opens,
261
+ * plus one held TCP connection per host with a terminal. `shell()` falls back
262
+ * to the shared connection if this one cannot be established at all, so a host
263
+ * that refuses extra connections still gets a working terminal.
264
+ */
265
+ private readonly shellConns = new Map<string, Pooled>()
248
266
  /** TOFU fingerprints observed this process (alias -> sha256). */
249
267
  private readonly hostKeys = new Map<string, string>()
250
268
  /** Per-alias `setsid --wait` capability, probed once (see supportsSetsid). */
@@ -263,23 +281,19 @@ export class RemotePool {
263
281
  // Order matters: the open browse channel must give its slot and hold back
264
282
  // while the pooled entry still exists, or the release would be a no-op.
265
283
  this.evictBrowse(alias)
266
- const pooled = this.conns.get(alias)
267
284
  // The host entry can change under an alias, so the capability answer goes
268
285
  // with the connection; the next exec probes again.
269
286
  this.setsidProbes.delete(alias)
270
- if (pooled === undefined) return
271
- this.conns.delete(alias)
272
- if (pooled.timer !== undefined) clearTimeout(pooled.timer)
273
- try {
274
- pooled.conn.end()
275
- } catch {
276
- // Already gone.
277
- }
287
+ // Both connections belong to the host: an edit/removal must end both.
288
+ // (A transient error on ONE of them uses `evictFrom` for that map only, so
289
+ // a shared-connection blip does not take live terminals down with it.)
290
+ this.evictFrom(this.conns, alias)
291
+ this.evictFrom(this.shellConns, alias)
278
292
  }
279
293
 
280
294
  /** Close every pooled connection. */
281
295
  dispose(): void {
282
- for (const alias of [...this.conns.keys()]) this.drop(alias)
296
+ for (const alias of new Set([...this.conns.keys(), ...this.shellConns.keys()])) this.drop(alias)
283
297
  }
284
298
 
285
299
  /**
@@ -316,7 +330,8 @@ export class RemotePool {
316
330
  state: entry?.state ?? 'idle',
317
331
  // connecting means a DIAL is in flight (the pooled entry exists before
318
332
  // the Client does), so that is not an open connection yet.
319
- open: pooled !== undefined && pooled.connecting === undefined,
333
+ open: (pooled !== undefined && pooled.connecting === undefined)
334
+ || (this.shellConns.get(alias)?.connecting === undefined && this.shellConns.has(alias)),
320
335
  ...(entry?.okAt === undefined ? {} : { okAt: entry.okAt }),
321
336
  ...(entry?.errorAt === undefined ? {} : { errorAt: entry.errorAt }),
322
337
  ...(entry?.error === undefined ? {} : { error: entry.error }),
@@ -646,8 +661,29 @@ export class RemotePool {
646
661
 
647
662
  /** Open an interactive PTY shell. The caller owns the channel lifecycle. */
648
663
  async shell(alias: string, opts: ShellOptions = {}): Promise<ClientChannel> {
649
- const conn = await this.acquire(alias)
650
- this.hold(alias)
664
+ /**
665
+ * Prefer the DEDICATED PTY connection so terminal bytes never queue behind
666
+ * SFTP/git/exec traffic on the shared one (SSH has no channel priority).
667
+ * A host that refuses the extra connection still gets a terminal: the fallback
668
+ * is the shared connection, exactly the old behaviour.
669
+ */
670
+ let conn: Client
671
+ let dedicated = true
672
+ try {
673
+ conn = await this.acquireShell(alias)
674
+ this.holdIn(this.shellConns, alias)
675
+ } catch (error) {
676
+ dedicated = false
677
+ // The shared path reports its own failures; a dedicated-dial failure that
678
+ // the shared one survives is not the link's problem (e.g. a MaxStartups
679
+ // refusal of just this connection).
680
+ conn = await this.acquire(alias)
681
+ this.hold(alias)
682
+ if (!(error instanceof Error) || !isConnectionFailure(error)) {
683
+ // eslint-disable-next-line no-console
684
+ console.warn('[dsh-remote-vs] dedicated PTY connection failed; using the shared one:', error)
685
+ }
686
+ }
651
687
  try {
652
688
  const channel = await new Promise<ClientChannel>((resolve, reject) => {
653
689
  conn.shell({ cols: opts.cols ?? 80, rows: opts.rows ?? 24, term: 'xterm-256color' }, (error, stream) => {
@@ -655,11 +691,15 @@ export class RemotePool {
655
691
  else resolve(stream)
656
692
  })
657
693
  })
658
- channel.once('close', () => this.release(alias))
694
+ channel.once('close', () => {
695
+ if (dedicated) this.releaseIn(this.shellConns, alias)
696
+ else this.release(alias)
697
+ })
659
698
  this.markOk(alias)
660
699
  return channel
661
700
  } catch (error) {
662
- this.release(alias)
701
+ if (dedicated) this.releaseIn(this.shellConns, alias)
702
+ else this.release(alias)
663
703
  if (isConnectionFailure(error)) this.markError(alias, error)
664
704
  throw error
665
705
  }
@@ -1299,7 +1339,11 @@ export class RemotePool {
1299
1339
 
1300
1340
  /** Hold the connection against idle eviction (balanced by release). */
1301
1341
  private hold(alias: string): void {
1302
- const pooled = this.conns.get(alias)
1342
+ this.holdIn(this.conns, alias)
1343
+ }
1344
+
1345
+ private holdIn(map: Map<string, Pooled>, alias: string): void {
1346
+ const pooled = map.get(alias)
1303
1347
  if (pooled === undefined) return
1304
1348
  pooled.held += 1
1305
1349
  pooled.lastUse = Date.now()
@@ -1310,25 +1354,40 @@ export class RemotePool {
1310
1354
  }
1311
1355
 
1312
1356
  private release(alias: string): void {
1313
- const pooled = this.conns.get(alias)
1357
+ this.releaseIn(this.conns, alias)
1358
+ }
1359
+
1360
+ private releaseIn(map: Map<string, Pooled>, alias: string): void {
1361
+ const pooled = map.get(alias)
1314
1362
  if (pooled === undefined) return
1315
1363
  if (pooled.held > 0) pooled.held -= 1
1316
1364
  pooled.lastUse = Date.now()
1317
1365
  if (pooled.held > 0) return
1318
1366
  if (pooled.timer !== undefined) clearTimeout(pooled.timer)
1319
- pooled.timer = setTimeout(() => this.drop(alias), IDLE_MS)
1367
+ // Evict ONLY this map: the idle timer of the shell connection must not close
1368
+ // the shared connection (and vice versa) — they serve different consumers.
1369
+ pooled.timer = setTimeout(() => this.evictFrom(map, alias), IDLE_MS)
1320
1370
  if (typeof pooled.timer === 'object' && 'unref' in pooled.timer) pooled.timer.unref()
1321
1371
  }
1322
1372
 
1323
1373
  private async acquire(alias: string): Promise<Client> {
1324
- const pooled = this.conns.get(alias)
1374
+ return this.acquireIn(this.conns, alias)
1375
+ }
1376
+
1377
+ /** `acquire` for the dedicated PTY connection map. */
1378
+ private async acquireShell(alias: string): Promise<Client> {
1379
+ return this.acquireIn(this.shellConns, alias)
1380
+ }
1381
+
1382
+ private async acquireIn(map: Map<string, Pooled>, alias: string): Promise<Client> {
1383
+ const pooled = map.get(alias)
1325
1384
  if (pooled !== undefined && pooled.connecting !== undefined) return pooled.connecting
1326
1385
  if (pooled !== undefined) {
1327
1386
  pooled.lastUse = Date.now()
1328
1387
  return pooled.conn
1329
1388
  }
1330
1389
  const entry: Pooled = { conn: undefined as unknown as Client, timer: undefined, lastUse: Date.now(), connecting: undefined, held: 0 }
1331
- this.conns.set(alias, entry)
1390
+ map.set(alias, entry)
1332
1391
  /**
1333
1392
  * The entry object IS the ownership token: `drop()` deletes it and a later
1334
1393
  * `acquire()` creates a NEW one, so comparing identity answers "does this
@@ -1342,7 +1401,7 @@ export class RemotePool {
1342
1401
  */
1343
1402
  entry.connecting = this.dial(alias).then(
1344
1403
  (conn) => {
1345
- if (this.conns.get(alias) !== entry) {
1404
+ if (map.get(alias) !== entry) {
1346
1405
  try {
1347
1406
  conn.end()
1348
1407
  } catch {
@@ -1357,20 +1416,20 @@ export class RemotePool {
1357
1416
  // The server went away: record it for the status chip, then evict so
1358
1417
  // the next op redials. Our OWN drop() deleted the entry first, so a
1359
1418
  // normal close (idle eviction, host removal) never lands here.
1360
- if (this.conns.get(alias) !== entry) return
1419
+ if (map.get(alias) !== entry) return
1361
1420
  this.markError(alias, new Error('connection closed'))
1362
- this.drop(alias)
1421
+ this.evictFrom(map, alias)
1363
1422
  })
1364
1423
  conn.on('error', (error: Error) => {
1365
- if (this.conns.get(alias) !== entry) return
1424
+ if (map.get(alias) !== entry) return
1366
1425
  this.markError(alias, error)
1367
- this.drop(alias)
1426
+ this.evictFrom(map, alias)
1368
1427
  })
1369
- this.release(alias)
1428
+ this.releaseIn(map, alias)
1370
1429
  return conn
1371
1430
  },
1372
1431
  (error) => {
1373
- if (this.conns.get(alias) === entry) this.conns.delete(alias)
1432
+ if (map.get(alias) === entry) map.delete(alias)
1374
1433
  this.markError(alias, error)
1375
1434
  throw error
1376
1435
  },
@@ -1378,6 +1437,19 @@ export class RemotePool {
1378
1437
  return entry.connecting
1379
1438
  }
1380
1439
 
1440
+ /** Evict ONE alias from ONE map (host removal drops both maps explicitly). */
1441
+ private evictFrom(map: Map<string, Pooled>, alias: string): void {
1442
+ const pooled = map.get(alias)
1443
+ if (pooled === undefined) return
1444
+ map.delete(alias)
1445
+ if (pooled.timer !== undefined) clearTimeout(pooled.timer)
1446
+ try {
1447
+ pooled.conn.end()
1448
+ } catch {
1449
+ // Already gone.
1450
+ }
1451
+ }
1452
+
1381
1453
  /**
1382
1454
  * The ssh2 client factory.
1383
1455
  *
package/src/terminal.ts CHANGED
@@ -20,6 +20,34 @@ interface Session {
20
20
  pending: number
21
21
  /** True while the channel is paused because a socket fell behind. */
22
22
  paused: boolean
23
+ /**
24
+ * Output text waiting for the next coalesced frame, and its flush timer.
25
+ *
26
+ * A burst (a log tail, `cat` of a large file) delivers one ssh2 chunk at a
27
+ * time; sending each chunk as its own JSON frame made the host stringify, the
28
+ * socket frame and the browser parse once per chunk. Coalescing into one frame
29
+ * per short window keeps the byte flow identical while cutting that overhead
30
+ * by roughly an order of magnitude for exactly the commands that felt busy.
31
+ */
32
+ outBuffer: string
33
+ outTimer: ReturnType<typeof setTimeout> | undefined
34
+ /**
35
+ * When the last `out` frame went out.
36
+ *
37
+ * Used to tell an interactive ECHO from a burst: output that starts after a
38
+ * quiet period is handed over immediately (a keystroke should not wait for the
39
+ * coalescing window), while a continuous stream keeps coalescing.
40
+ */
41
+ lastFlushAt: number
42
+ /**
43
+ * Bytes handed to each socket that have not settled yet.
44
+ *
45
+ * `pending` alone cannot be released when a socket closes with frames still in
46
+ * flight: ws never calls their send callbacks, so the missing bytes kept the
47
+ * channel paused for the rest of the session (no echo at all until a reload).
48
+ * Per-socket bookkeeping lets `detach` return exactly those bytes.
49
+ */
50
+ outstanding: Map<WebSocket, number>
23
51
  /** Fires once the last socket has been gone for EMPTY_SOCKET_TTL_MS. */
24
52
  reap: ReturnType<typeof setTimeout> | undefined
25
53
  /**
@@ -55,12 +83,57 @@ const EMPTY_SOCKET_TTL_MS = 10 * 60_000
55
83
  * The retained ceiling is therefore this mark plus ssh2's window (2 MiB) plus
56
84
  * whatever is in flight — bounded, but not exactly 4 MiB.
57
85
  *
86
+ * The mark is RESPONSIVENESS, not just memory: everything already handed to a
87
+ * socket has to be parsed and painted by the browser before a later keystroke's
88
+ * echo can appear, so a large mark means "type during a huge dump and wait
89
+ * seconds". 2 MiB still absorbs a burst comfortably (a keystroke is bytes) while
90
+ * keeping the worst-case echo delay down; ssh2's own 2 MiB window is the part we
91
+ * cannot shrink from here.
92
+ *
58
93
  * The counter is per session, not per socket: one lagging socket pauses the
59
94
  * channel for every socket attached to that shell. That is deliberate — the
60
95
  * alternative is letting the slowest consumer grow the host process.
61
96
  */
62
- const OUT_HIGH_WATER = 4 * 1024 * 1024
63
- const OUT_LOW_WATER = 1 * 1024 * 1024
97
+ const OUT_HIGH_WATER = 2 * 1024 * 1024
98
+ const OUT_LOW_WATER = 512 * 1024
99
+
100
+ /** Default window for coalescing output frames (0 = one frame per chunk). */
101
+ const OUT_COALESCE_MS = 8
102
+ /**
103
+ * Flush immediately past this much buffered text (measured in UTF-16 code
104
+ * units, i.e. `String.length`): a producer faster than the window must not turn
105
+ * into an unbounded string copy (the channel backpressure bounds the bytes
106
+ * handed to the SOCKETS, not this buffer).
107
+ *
108
+ * Code units rather than bytes on purpose: converting to a byte count would
109
+ * copy the whole buffer on every chunk just to compare a threshold. CJK/emoji
110
+ * output therefore flushes at up to ~3x this many bytes, which is still far
111
+ * below the 1 MiB client-frame cap this path never approaches (it is the
112
+ * client→host direction).
113
+ */
114
+ const OUT_COALESCE_CHARS = 64 * 1024
115
+
116
+ /**
117
+ * How long the output must have been quiet for the NEXT chunk to be sent at once.
118
+ *
119
+ * A terminal echoes what the user types. Holding that echo for the coalescing
120
+ * window is invisible at 8 ms — but under load the window itself is a timer in
121
+ * an event loop shared with the agent, and the delay adds up. After a quiet
122
+ * period the chunk is therefore flushed synchronously; only a running stream
123
+ * (where `lastFlushAt` is fresh) is batched.
124
+ */
125
+ const OUT_ECHO_IDLE_MS = 24
126
+
127
+ /** Construction options (the terminal gate drives the registry directly). */
128
+ export interface TerminalRegistryOptions {
129
+ /**
130
+ * Output coalescing window in ms; `0` sends every chunk as its own frame.
131
+ *
132
+ * The existing checks use `0` so their assertions stay synchronous; one
133
+ * dedicated check drives a non-zero window to pin the coalescing itself.
134
+ */
135
+ coalesceMs?: number
136
+ }
64
137
 
65
138
  /**
66
139
  * The largest client frame accepted, in bytes.
@@ -85,7 +158,15 @@ const WS_OPEN = 1
85
158
  export class TerminalSessionRegistry {
86
159
  private readonly sessions = new Map<string, Session>()
87
160
 
88
- constructor(private readonly pool: RemotePool) {}
161
+ constructor(
162
+ private readonly pool: RemotePool,
163
+ private readonly options: TerminalRegistryOptions = {},
164
+ ) {}
165
+
166
+ /** The window this registry coalesces within (`0` = every chunk is a frame). */
167
+ private get coalesceMs(): number {
168
+ return this.options.coalesceMs ?? OUT_COALESCE_MS
169
+ }
89
170
 
90
171
  /** Open a shell and attach the first socket. */
91
172
  async open(ws: WebSocket, alias: string, cols: number, rows: number): Promise<string> {
@@ -111,6 +192,10 @@ export class TerminalSessionRegistry {
111
192
  sockets: new Set(),
112
193
  pending: 0,
113
194
  paused: false,
195
+ outBuffer: '',
196
+ outTimer: undefined,
197
+ lastFlushAt: 0,
198
+ outstanding: new Map(),
114
199
  reap: undefined,
115
200
  outDecoder: new StringDecoder('utf8'),
116
201
  errDecoder: new StringDecoder('utf8'),
@@ -118,11 +203,11 @@ export class TerminalSessionRegistry {
118
203
  this.sessions.set(id, session)
119
204
  channel.on('data', (chunk: Buffer) => {
120
205
  const text = session.outDecoder.write(chunk)
121
- if (text !== '') this.broadcast(session, { t: 'out', d: text })
206
+ if (text !== '') this.queueOut(session, text)
122
207
  })
123
208
  channel.stderr.on('data', (chunk: Buffer) => {
124
209
  const text = session.errDecoder.write(chunk)
125
- if (text !== '') this.broadcast(session, { t: 'out', d: text })
210
+ if (text !== '') this.queueOut(session, text)
126
211
  })
127
212
  channel.on('close', (code: number | null) => {
128
213
  session.alive = false
@@ -130,8 +215,11 @@ export class TerminalSessionRegistry {
130
215
  // Flush the decoder-held tail BEFORE the exit frame: a command's last
131
216
  // character may still be sitting in the decoder when the channel closes.
132
217
  for (const tail of [session.outDecoder.end(), session.errDecoder.end()]) {
133
- if (tail !== '') this.broadcast(session, { t: 'out', d: tail })
218
+ if (tail !== '') this.queueOut(session, tail)
134
219
  }
220
+ // …and flush anything the coalescing window is still holding, so the exit
221
+ // frame can never overtake the last line the user was meant to see.
222
+ this.flushOut(session)
135
223
  this.broadcast(session, { t: 'exit', code })
136
224
  for (const socket of session.sockets) {
137
225
  try {
@@ -164,6 +252,9 @@ export class TerminalSessionRegistry {
164
252
  const session = this.sessions.get(id)
165
253
  if (session === undefined || !session.alive) return false
166
254
  this.hookSocket(session, ws)
255
+ // Deliver anything the coalescing window still holds to the newcomer too,
256
+ // before its `ready`: it is output the shell already produced.
257
+ this.flushOut(session)
167
258
  this.send(ws, { t: 'ready', id })
168
259
  return true
169
260
  }
@@ -174,6 +265,7 @@ export class TerminalSessionRegistry {
174
265
  if (session === undefined) return false
175
266
  this.sessions.delete(id)
176
267
  this.cancelReap(session)
268
+ this.flushOut(session)
177
269
  try {
178
270
  session.channel.close()
179
271
  } catch {
@@ -187,6 +279,9 @@ export class TerminalSessionRegistry {
187
279
  }
188
280
  }
189
281
  session.sockets.clear()
282
+ // The sockets are gone; their unsettled frames will never settle.
283
+ session.outstanding.clear()
284
+ session.pending = 0
190
285
  return true
191
286
  }
192
287
 
@@ -237,12 +332,25 @@ export class TerminalSessionRegistry {
237
332
  }
238
333
  })
239
334
  const detach = (): void => {
335
+ // Whatever the window is holding was produced while this socket was still
336
+ // attached: hand it over before the socket leaves the set.
337
+ this.flushOut(session)
338
+ // Release the frames this socket never settled. `ws` does not call their
339
+ // send callbacks after a close, and the leaked `pending` bytes used to keep
340
+ // the channel paused for the rest of the session.
341
+ const unsettled = session.outstanding.get(ws)
342
+ if (unsettled !== undefined) {
343
+ session.outstanding.delete(ws)
344
+ session.pending = Math.max(0, session.pending - unsettled)
345
+ if (session.pending <= OUT_LOW_WATER) this.setPaused(session, false)
346
+ }
240
347
  session.sockets.delete(ws)
241
348
  if (session.sockets.size > 0) return
242
349
  // Nobody is watching any more. Release the brake first — a paused channel
243
350
  // would otherwise stay paused with no socket left to resume it — then
244
351
  // start the clock that ends the session (and with it the remote shell).
245
352
  session.pending = 0
353
+ session.outstanding.clear()
246
354
  this.setPaused(session, false)
247
355
  this.armReap(session)
248
356
  }
@@ -280,6 +388,44 @@ export class TerminalSessionRegistry {
280
388
  session.reap = undefined
281
389
  }
282
390
 
391
+ /**
392
+ * Queue one output chunk and schedule the coalesced frame.
393
+ *
394
+ * `coalesceMs === 0` broadcasts immediately (the checks rely on that
395
+ * synchrony). A chunk that arrives after an idle gap is also sent at once —
396
+ * that is the interactive echo path (a keystroke must not wait for the
397
+ * window) — while a stream that keeps producing coalesces.
398
+ */
399
+ private queueOut(session: Session, text: string): void {
400
+ if (text === '') return
401
+ const idle = Date.now() - session.lastFlushAt >= OUT_ECHO_IDLE_MS
402
+ session.outBuffer += text
403
+ if (session.outBuffer.length >= OUT_COALESCE_CHARS || this.coalesceMs <= 0 || idle) {
404
+ this.flushOut(session)
405
+ return
406
+ }
407
+ if (session.outTimer !== undefined) return
408
+ const timer = setTimeout(() => {
409
+ session.outTimer = undefined
410
+ this.flushOut(session)
411
+ }, this.coalesceMs)
412
+ timer.unref?.()
413
+ session.outTimer = timer
414
+ }
415
+
416
+ /** Send the buffered output as ONE `out` frame (no-op when empty). */
417
+ private flushOut(session: Session): void {
418
+ if (session.outTimer !== undefined) {
419
+ clearTimeout(session.outTimer)
420
+ session.outTimer = undefined
421
+ }
422
+ if (session.outBuffer === '') return
423
+ const text = session.outBuffer
424
+ session.outBuffer = ''
425
+ session.lastFlushAt = Date.now()
426
+ this.broadcast(session, { t: 'out', d: text })
427
+ }
428
+
283
429
  private setPaused(session: Session, paused: boolean): void {
284
430
  if (session.paused === paused) return
285
431
  session.paused = paused
@@ -312,10 +458,18 @@ export class TerminalSessionRegistry {
312
458
  const done = (): void => {
313
459
  if (settled) return
314
460
  settled = true
461
+ // A socket that detached already had its outstanding bytes released
462
+ // (its late callback must not decrement them a second time).
463
+ const left = session.outstanding.get(socket)
464
+ if (left === undefined) return
465
+ const remaining = Math.max(0, left - size)
466
+ if (remaining === 0) session.outstanding.delete(socket)
467
+ else session.outstanding.set(socket, remaining)
315
468
  session.pending = Math.max(0, session.pending - size)
316
469
  if (session.pending <= OUT_LOW_WATER) this.setPaused(session, false)
317
470
  }
318
471
  session.pending += size
472
+ session.outstanding.set(socket, (session.outstanding.get(socket) ?? 0) + size)
319
473
  try {
320
474
  socket.send(text, done)
321
475
  } catch {