dsh-remote-vs 0.13.0 → 0.15.1

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 (128) hide show
  1. package/README.en.md +455 -443
  2. package/README.md +408 -396
  3. package/lib/client.js +8062 -2651
  4. package/lib/index.js +1058 -288
  5. package/lib/p2-router-fs.js +1 -1
  6. package/lib/p2-router-refs.js +89 -10
  7. package/lib/p2-router-spill.js +73 -1
  8. package/lib/p2-router-subprocess.js +18 -6
  9. package/lib/spill-retention-BwKEWrl5.js +115 -0
  10. package/lib/{ssh-proc-arI5lm4W.js → ssh-proc-VKWn_LZC.js} +17 -0
  11. package/lib/types/archive.d.ts +1 -1
  12. package/lib/types/changes/recorder.d.ts +34 -2
  13. package/lib/types/client/CodeEditor.d.ts +12 -0
  14. package/lib/types/client/ConnectionStatus.d.ts +17 -0
  15. package/lib/types/client/DirectoryFlow.d.ts +2 -0
  16. package/lib/types/client/DoctorPanel.d.ts +25 -0
  17. package/lib/types/client/QuickOpen.d.ts +17 -0
  18. package/lib/types/client/RemoteExplorer.d.ts +192 -1
  19. package/lib/types/client/RemoteRoot.d.ts +17 -0
  20. package/lib/types/client/SearchView.d.ts +55 -0
  21. package/lib/types/client/TerminalView.d.ts +38 -0
  22. package/lib/types/client/WorkspaceWizard.d.ts +17 -0
  23. package/lib/types/client/api.d.ts +54 -4
  24. package/lib/types/client/changes/undo-affordance.d.ts +16 -0
  25. package/lib/types/client/changes/undo-context.d.ts +14 -18
  26. package/lib/types/client/changes/undo-target.d.ts +78 -0
  27. package/lib/types/client/connection.d.ts +111 -0
  28. package/lib/types/client/doctor.d.ts +122 -0
  29. package/lib/types/client/download.d.ts +35 -5
  30. package/lib/types/client/downloads.d.ts +18 -1
  31. package/lib/types/client/file-open-probe.d.ts +64 -0
  32. package/lib/types/client/i18n.d.ts +1 -1
  33. package/lib/types/client/quickopen-model.d.ts +332 -0
  34. package/lib/types/client/scm/DiffView.d.ts +34 -0
  35. package/lib/types/client/scm/actions.d.ts +18 -0
  36. package/lib/types/client/scm/diff-model.d.ts +17 -1
  37. package/lib/types/client/scm/git-cache.d.ts +10 -2
  38. package/lib/types/client/scm/read-queue.d.ts +2 -1
  39. package/lib/types/client/scm/stage-queue.d.ts +13 -0
  40. package/lib/types/client/scm/status-map.d.ts +3 -1
  41. package/lib/types/client/store.d.ts +114 -5
  42. package/lib/types/client/vsc/FindWidget.d.ts +7 -0
  43. package/lib/types/client/vsc/save-shortcut.d.ts +57 -0
  44. package/lib/types/deploy.d.ts +44 -2
  45. package/lib/types/git-format.d.ts +15 -0
  46. package/lib/types/http.d.ts +44 -0
  47. package/lib/types/p2/file-refs.d.ts +39 -2
  48. package/lib/types/p2/helper-rpc.d.ts +26 -0
  49. package/lib/types/p2/router-spill.d.ts +19 -0
  50. package/lib/types/p2/router-subprocess.d.ts +2 -0
  51. package/lib/types/p2/spill-retention.d.ts +74 -0
  52. package/lib/types/p2/worlds.d.ts +11 -0
  53. package/lib/types/pool.d.ts +73 -11
  54. package/lib/types/protocol.d.ts +63 -0
  55. package/lib/types/routes.d.ts +18 -0
  56. package/lib/types/sftp.d.ts +114 -8
  57. package/lib/types/store.d.ts +34 -0
  58. package/lib/types/timeouts.d.ts +14 -0
  59. package/lib/{worlds-C6Xha1mQ.js → worlds-Be1YE2Ot.js} +727 -78
  60. package/package.json +1 -1
  61. package/src/archive.ts +41 -9
  62. package/src/changes/recorder.ts +227 -31
  63. package/src/changes/status.ts +37 -1
  64. package/src/client/CodeEditor.tsx +84 -2
  65. package/src/client/ConnectionStatus.tsx +130 -0
  66. package/src/client/DirectoryFlow.tsx +40 -5
  67. package/src/client/DoctorPanel.tsx +202 -0
  68. package/src/client/DownloadDock.tsx +13 -25
  69. package/src/client/EditorPane.tsx +291 -7
  70. package/src/client/HostsView.tsx +17 -8
  71. package/src/client/QuickOpen.tsx +371 -0
  72. package/src/client/RemoteDirectoryPicker.tsx +54 -3
  73. package/src/client/RemoteExplorer.tsx +879 -160
  74. package/src/client/RemoteRoot.tsx +178 -1
  75. package/src/client/SearchView.tsx +180 -6
  76. package/src/client/SettingsHosts.tsx +1 -1
  77. package/src/client/TerminalView.tsx +174 -9
  78. package/src/client/WorkspaceWizard.tsx +110 -16
  79. package/src/client/WorkspacesView.tsx +22 -6
  80. package/src/client/api.ts +197 -11
  81. package/src/client/changes/ChangesDock.tsx +35 -8
  82. package/src/client/changes/undo-affordance.ts +33 -0
  83. package/src/client/changes/undo-context.ts +14 -18
  84. package/src/client/changes/undo-target.ts +139 -0
  85. package/src/client/connection.ts +264 -0
  86. package/src/client/doctor.ts +441 -0
  87. package/src/client/download.ts +148 -12
  88. package/src/client/downloads.ts +43 -2
  89. package/src/client/file-open-probe.ts +83 -0
  90. package/src/client/i18n.ts +244 -0
  91. package/src/client/index.tsx +5 -2
  92. package/src/client/quickopen-model.ts +778 -0
  93. package/src/client/remote-file-open.ts +21 -33
  94. package/src/client/scm/DiffView.tsx +116 -6
  95. package/src/client/scm/ScmPanel.tsx +19 -0
  96. package/src/client/scm/actions.ts +34 -2
  97. package/src/client/scm/diff-model.ts +33 -37
  98. package/src/client/scm/git-cache.ts +61 -4
  99. package/src/client/scm/read-queue.ts +33 -2
  100. package/src/client/scm/stage-queue.ts +72 -1
  101. package/src/client/scm/status-map.ts +22 -1
  102. package/src/client/store.tsx +704 -21
  103. package/src/client/vsc/FindWidget.tsx +20 -0
  104. package/src/client/vsc/kit.tsx +115 -6
  105. package/src/client/vsc/reveal-line.ts +33 -14
  106. package/src/client/vsc/save-shortcut.ts +131 -0
  107. package/src/client/vsc/vsc.css +419 -0
  108. package/src/deploy.ts +185 -33
  109. package/src/git-format.ts +136 -22
  110. package/src/git-ops.ts +14 -6
  111. package/src/http.ts +80 -12
  112. package/src/importers.ts +80 -21
  113. package/src/index.ts +21 -1
  114. package/src/p2/file-refs.ts +112 -10
  115. package/src/p2/helper-rpc.ts +73 -36
  116. package/src/p2/router-spill.ts +96 -1
  117. package/src/p2/router-subprocess.ts +18 -5
  118. package/src/p2/spill-retention.ts +134 -0
  119. package/src/p2/ssh-proc.ts +22 -0
  120. package/src/p2/worlds.ts +24 -0
  121. package/src/pool.ts +329 -47
  122. package/src/protocol.ts +66 -0
  123. package/src/routes.ts +251 -43
  124. package/src/sftp.ts +486 -26
  125. package/src/store.ts +207 -85
  126. package/src/terminal.ts +38 -2
  127. package/src/timeouts.ts +14 -0
  128. package/src/tools.ts +14 -5
package/src/pool.ts CHANGED
@@ -11,7 +11,14 @@ import { readFileSync } from 'node:fs'
11
11
  import { StringDecoder } from 'node:string_decoder'
12
12
  import { Client, type ClientChannel, type SFTPWrapper } from 'ssh2'
13
13
  import type { RemoteStore } from './store.ts'
14
- import type { RemoteExecResult, RemoteHostEntry } from './protocol.ts'
14
+ import { DeadlineError } from './timeouts.ts'
15
+ import type { RemoteConnectionStatus, RemoteExecResult, RemoteHostEntry } from './protocol.ts'
16
+
17
+ /**
18
+ * The budget-out type lives in `timeouts.ts` (both halves need it); re-exported
19
+ * here because existing callers and the browse gate import it from the pool.
20
+ */
21
+ export { DeadlineError }
15
22
 
16
23
  /** Idle time after which a pooled connection is closed. */
17
24
  const IDLE_MS = 30 * 60 * 1000
@@ -32,17 +39,39 @@ const READY_TIMEOUT_MS = (() => {
32
39
  return Number.isFinite(raw) && raw >= 1_000 ? raw : 45_000
33
40
  })()
34
41
 
42
+ /**
43
+ * Extra wall clock on top of `READY_TIMEOUT_MS` for the dial's own watchdog.
44
+ *
45
+ * `readyTimeout` only covers "the socket stays open and the handshake stalls":
46
+ * ssh2 clears it as soon as the socket closes, and it only re-reports a close as
47
+ * an `error` when the SSH banner never arrived (client.js `onDone`). The shape
48
+ * left over is "no event at all", which used to leave the dial promise pending
49
+ * forever and the caller holding a channel slot. Override with
50
+ * DSH_REMOTE_VS_DIAL_GUARD_MS (milliseconds, >= 0); the dial gate keeps its case
51
+ * fast that way.
52
+ */
53
+ const DIAL_GUARD_MARGIN_MS = (() => {
54
+ const raw = Number(process.env.DSH_REMOTE_VS_DIAL_GUARD_MS)
55
+ return Number.isFinite(raw) && raw >= 0 ? raw : 5_000
56
+ })()
57
+
35
58
  /** Per-stream output cap (stdout/stderr each); overflow truncates with a marker. */
36
59
  const OUTPUT_CAP = 2 * 1024 * 1024
37
60
 
38
61
  /**
39
- * Wall-clock cap for one SFTP callback body. SSH gives no request timeout of
40
- * its own, so a server that never answers would hold the session (and the
41
- * pooled connection's hold count) open forever — the leak that eventually
42
- * exhausts the server's channel budget. The timeout rejects so the caller's
43
- * `finally` still ends the session and releases the connection.
62
+ * Wall-clock cap for one SFTP callback body (and for opening the session). SSH
63
+ * gives no request timeout of its own, so a server that never answers would hold
64
+ * the session (and the pooled connection's hold count) open forever — the leak
65
+ * that eventually exhausts the server's channel budget. The timeout rejects so
66
+ * the caller's `finally` still ends the session and releases the connection.
67
+ *
68
+ * Override with DSH_REMOTE_VS_SFTP_TIMEOUT_MS (milliseconds, >= 100) so the
69
+ * session-lifecycle gate can exercise the deadline without waiting a minute.
44
70
  */
45
- const SFTP_OP_TIMEOUT_MS = 60_000
71
+ const SFTP_OP_TIMEOUT_MS = (() => {
72
+ const raw = Number(process.env.DSH_REMOTE_VS_SFTP_TIMEOUT_MS)
73
+ return Number.isFinite(raw) && raw >= 100 ? raw : 60_000
74
+ })()
46
75
 
47
76
  /**
48
77
  * No-progress budget for a bulk upload. Deliberately an *idle* timeout rather
@@ -130,6 +159,38 @@ interface BrowseChannel {
130
159
  idle: ReturnType<typeof setTimeout> | undefined
131
160
  }
132
161
 
162
+ /**
163
+ * Connection-level failures the status indicator must show.
164
+ *
165
+ * Deliberately about the TRANSPORT, not about the remote's answer: a missing
166
+ * file, a rejected password prompt or a non-zero git exit are all business
167
+ * outcomes and must not paint the host as disconnected. `timed out` is in here
168
+ * because a handshake/channel deadline means the link (or the server behind it)
169
+ * is not answering, which is exactly what the indicator is for.
170
+ */
171
+ const CONNECTION_ERROR_RE = /not connected|no response from server|connection lost|connection closed|connection refused|socket hang up|channel open fail(?:ed|ure)|stalled|host .* was disconnected|timed out|ECONNRESET|ECONNREFUSED|ETIMEDOUT|EHOSTUNREACH|ENETUNREACH|EHOSTDOWN|EPIPE/i
172
+
173
+ /** Whether `error` is a transport-level failure worth showing as a link problem. */
174
+ export function isConnectionFailure(error: unknown): boolean {
175
+ const message = error instanceof Error ? error.message : String(error ?? '')
176
+ return message !== '' && CONNECTION_ERROR_RE.test(message)
177
+ }
178
+
179
+ /**
180
+ * Per-alias connection health, kept OUTSIDE the pooled entry on purpose: a
181
+ * failed dial deletes the entry, and the indicator still has to say why.
182
+ *
183
+ * `idle` is the initial/normal-closed state — the pool is lazy and closes a
184
+ * connection after 30 idle minutes; the next operation dials again, so calling
185
+ * that "disconnected" would make the indicator cry wolf.
186
+ */
187
+ interface Health {
188
+ state: 'ok' | 'error' | 'idle'
189
+ okAt?: number
190
+ errorAt?: number
191
+ error?: string
192
+ }
193
+
133
194
  export interface ExecOptions {
134
195
  timeoutMs?: number
135
196
  /**
@@ -192,6 +253,8 @@ export class RemotePool {
192
253
  private readonly slots = new Map<string, Slots>()
193
254
  /** Per-alias BROWSE SFTP session (see withBrowseSftp). */
194
255
  private readonly browsed = new Map<string, BrowseChannel>()
256
+ /** Per-alias connection health for the browser's status chip (see status). */
257
+ private readonly health = new Map<string, Health>()
195
258
 
196
259
  constructor(private readonly store: RemoteStore) {}
197
260
 
@@ -219,17 +282,121 @@ export class RemotePool {
219
282
  for (const alias of [...this.conns.keys()]) this.drop(alias)
220
283
  }
221
284
 
222
- /** Test a connection without disturbing the pool. */
285
+ /**
286
+ * Forget one alias's connection HEALTH (host edited/removed), not just its
287
+ * connection.
288
+ *
289
+ * `drop` is also the idle eviction path, so it must keep the health record
290
+ * (idle-closed is not an error). Only a host mutation discards what the pool
291
+ * learned about that alias.
292
+ */
293
+ forget(alias: string): void {
294
+ this.drop(alias)
295
+ this.health.delete(alias)
296
+ }
297
+
298
+ /**
299
+ * Per-alias connection health for the browser's status indicator.
300
+ *
301
+ * Read-only and dial-free: it reports what the pool already knows, so the
302
+ * indicator's poll never creates a connection as a side effect.
303
+ */
304
+ status(): RemoteConnectionStatus[] {
305
+ const aliases = new Set<string>([...this.conns.keys(), ...this.health.keys()])
306
+ try {
307
+ for (const host of this.store.list()) aliases.add(host.alias)
308
+ } catch {
309
+ // Unreadable store: answer what the pool knows rather than failing the route.
310
+ }
311
+ return [...aliases].sort().map((alias) => {
312
+ const entry = this.health.get(alias)
313
+ const pooled = this.conns.get(alias)
314
+ return {
315
+ alias,
316
+ state: entry?.state ?? 'idle',
317
+ // connecting means a DIAL is in flight (the pooled entry exists before
318
+ // the Client does), so that is not an open connection yet.
319
+ open: pooled !== undefined && pooled.connecting === undefined,
320
+ ...(entry?.okAt === undefined ? {} : { okAt: entry.okAt }),
321
+ ...(entry?.errorAt === undefined ? {} : { errorAt: entry.errorAt }),
322
+ ...(entry?.error === undefined ? {} : { error: entry.error }),
323
+ }
324
+ })
325
+ }
326
+
327
+ /** Record a successful dial or transport-level operation. */
328
+ private markOk(alias: string): void {
329
+ this.health.set(alias, { state: 'ok', okAt: Date.now() })
330
+ }
331
+
332
+ /** Record a connection-level failure the status chip should show. */
333
+ private markError(alias: string, error: unknown): void {
334
+ const message = error instanceof Error ? error.message : String(error ?? '')
335
+ this.health.set(alias, { state: 'error', errorAt: Date.now(), error: message })
336
+ }
337
+
338
+ /**
339
+ * Record one operation's failure, EXCEPT when the budget simply ran out.
340
+ *
341
+ * A deadline means "this request did not answer in time", not "the link is
342
+ * down": the connection can be perfectly healthy and merely slow (a huge
343
+ * directory, an 8 MiB read on a thin link, a cold filesystem). Painting the
344
+ * chip red used to flip the editor to read-only and block saving — a false
345
+ * alarm with a real cost. Real transport failures still arrive as transport
346
+ * errors (`close`, `No response from server`, a channel open failure), and
347
+ * those keep marking; the operation itself still fails either way.
348
+ */
349
+ private noteOpFailure(alias: string, error: unknown): void {
350
+ if (error instanceof DeadlineError) return
351
+ if (isConnectionFailure(error)) this.markError(alias, error)
352
+ }
353
+
354
+ /**
355
+ * Probe one connection and record the outcome for the status indicator.
356
+ *
357
+ * "Test" must PROVE the link, not report that a pooled Client object exists:
358
+ * the old version answered ok without any traffic, so a retry against a
359
+ * half-open link painted the host green until the next real request failed.
360
+ *
361
+ * It must also NOT disturb the pool: this is what host settings' "test" and
362
+ * the chip's retry run, and the host being tested is often the one the user is
363
+ * working on (a terminal open, a transfer running). So a live connection gets
364
+ * a real round trip on itself (a trivial bare command under the control
365
+ * deadline), and only a COLD alias dials. Tearing the connection down instead
366
+ * would end every channel on it, including the terminal that the user opened
367
+ * to debug the flaky host.
368
+ */
223
369
  async test(alias: string): Promise<{ ok: boolean; banner?: string; error?: string; durationMs: number }> {
224
370
  const started = Date.now()
371
+ const finish = (ok: boolean, error?: string): { ok: boolean; banner?: string; error?: string; durationMs: number } => ({
372
+ ok,
373
+ ...(error === undefined ? {} : { error }),
374
+ durationMs: Date.now() - started,
375
+ })
376
+ if (this.conns.has(alias)) {
377
+ try {
378
+ const probe = await this.exec(alias, 'true', { timeoutMs: CONTROL_TIMEOUT_MS, bare: true })
379
+ // A non-zero exit still proves the transport; only an error field means
380
+ // the link itself failed (same rule as exec's own marking).
381
+ if (probe.success || probe.exitCode !== null) {
382
+ this.markOk(alias)
383
+ return finish(true)
384
+ }
385
+ if (probe.error !== undefined && isConnectionFailure(probe.error)) this.markError(alias, probe.error)
386
+ return finish(false, probe.error ?? 'the probe command did not complete')
387
+ } catch (error) {
388
+ const message = error instanceof Error ? error.message : String(error)
389
+ if (isConnectionFailure(error)) this.markError(alias, error)
390
+ return finish(false, message)
391
+ }
392
+ }
225
393
  try {
226
- const conn = await this.acquire(alias)
227
- this.hold(alias)
228
- this.release(alias)
229
- void conn
230
- return { ok: true, durationMs: Date.now() - started }
394
+ await this.acquire(alias)
395
+ this.markOk(alias)
396
+ return finish(true)
231
397
  } catch (error) {
232
- return { ok: false, error: error instanceof Error ? error.message : String(error), durationMs: Date.now() - started }
398
+ if (isConnectionFailure(error)) this.markError(alias, error)
399
+ return finish(false, error instanceof Error ? error.message : String(error))
233
400
  }
234
401
  }
235
402
 
@@ -254,7 +421,17 @@ export class RemotePool {
254
421
  }
255
422
  }
256
423
  try {
257
- return await this.runExec(alias, command, opts)
424
+ const result = await this.runExec(alias, command, opts)
425
+ // `runExec` answers a command failure as a RESULT, so an `error` field
426
+ // here means the transport itself broke; a non-zero exit still proves the
427
+ // link works. `timedOut` is a command budget, not a connection problem.
428
+ // AMBIGUOUS results (channel closed with neither exit status nor error —
429
+ // what a dropped link looks like) must NOT mark ok: the connection-level
430
+ // close already recorded the failure, and overwriting it here would leave
431
+ // the chip green for exactly the disconnect users notice most.
432
+ if (result.error !== undefined && isConnectionFailure(result.error)) this.markError(alias, result.error)
433
+ else if (result.success || result.exitCode !== null) this.markOk(alias)
434
+ return result
258
435
  } finally {
259
436
  this.releaseSlot(alias)
260
437
  }
@@ -479,9 +656,11 @@ export class RemotePool {
479
656
  })
480
657
  })
481
658
  channel.once('close', () => this.release(alias))
659
+ this.markOk(alias)
482
660
  return channel
483
661
  } catch (error) {
484
662
  this.release(alias)
663
+ if (isConnectionFailure(error)) this.markError(alias, error)
485
664
  throw error
486
665
  }
487
666
  }
@@ -498,9 +677,11 @@ export class RemotePool {
498
677
  })
499
678
  })
500
679
  channel.once('close', () => this.release(alias))
680
+ this.markOk(alias)
501
681
  return channel
502
682
  } catch (error) {
503
683
  this.release(alias)
684
+ if (isConnectionFailure(error)) this.markError(alias, error)
504
685
  throw error
505
686
  }
506
687
  }
@@ -525,8 +706,11 @@ export class RemotePool {
525
706
  const sftp = await this.openSession(conn)
526
707
  try {
527
708
  const limit = opts.timeoutMs ?? SFTP_OP_TIMEOUT_MS
528
- if (limit <= 0) return await fn(sftp)
529
- return await withDeadline(fn(sftp), limit, `SFTP operation timed out after ${limit / 1000}s`)
709
+ const result = limit <= 0
710
+ ? await fn(sftp)
711
+ : await withDeadline(fn(sftp), limit, `SFTP operation timed out after ${limit / 1000}s`)
712
+ this.markOk(alias)
713
+ return result
530
714
  } finally {
531
715
  try {
532
716
  sftp.end()
@@ -534,6 +718,9 @@ export class RemotePool {
534
718
  // Ignore close errors.
535
719
  }
536
720
  }
721
+ } catch (error) {
722
+ this.noteOpFailure(alias, error)
723
+ throw error
537
724
  } finally {
538
725
  this.release(alias)
539
726
  this.releaseSlot(alias)
@@ -615,7 +802,12 @@ export class RemotePool {
615
802
  return undefined
616
803
  }
617
804
  }
618
- return await fn(sessions[0] as SFTPWrapper, addChannel)
805
+ const result = await fn(sessions[0] as SFTPWrapper, addChannel)
806
+ this.markOk(alias)
807
+ return result
808
+ } catch (error) {
809
+ this.noteOpFailure(alias, error)
810
+ throw error
619
811
  } finally {
620
812
  closed = true
621
813
  for (const session of sessions) {
@@ -653,18 +845,34 @@ export class RemotePool {
653
845
  * bulk transfer asks for use `tryAcquireSlot`, so they never wait on it.
654
846
  */
655
847
  async withBrowseSftp<T>(alias: string, fn: (sftp: SFTPWrapper) => Promise<T>, opts: SftpOptions = {}): Promise<T> {
656
- const lease = await this.leaseBrowse(alias)
848
+ let lease: { state: BrowseChannel; sftp: SFTPWrapper }
849
+ try {
850
+ lease = await this.leaseBrowse(alias)
851
+ } catch (error) {
852
+ // A channel/subsystem OPEN failure used to happen before this method's own
853
+ // catch (the lease sat outside the try), so the chip stayed healthy while
854
+ // every listing failed — exactly what MaxSessions exhaustion looks like.
855
+ // A budget that ran out while OPENING is still a budget, not a dead link.
856
+ this.noteOpFailure(alias, error)
857
+ throw error
858
+ }
657
859
  const limit = opts.timeoutMs ?? SFTP_OP_TIMEOUT_MS
658
860
  try {
659
- if (limit <= 0) return await fn(lease.sftp)
660
- return await withDeadline(fn(lease.sftp), limit, `SFTP operation on ${alias} timed out after ${limit / 1000}s`)
861
+ const result = limit <= 0
862
+ ? await fn(lease.sftp)
863
+ : await withDeadline(fn(lease.sftp), limit, `SFTP operation on ${alias} timed out after ${limit / 1000}s`)
864
+ this.markOk(alias)
865
+ return result
661
866
  } catch (error) {
662
867
  // A request that never answered stays queued inside ssh2, and this session
663
868
  // was already handed to other browse operations. Mark it stale: the next
664
869
  // lease retires it (leaseBrowse), and operations sharing it fail fast
665
- // instead of waiting out their own deadlines.
870
+ // instead of waiting out their own deadlines. Retiring the session is
871
+ // orthogonal to the link's health: a slow listing is not a dead link.
666
872
  if (error instanceof DeadlineError) {
667
873
  lease.state.stale = true
874
+ } else {
875
+ this.noteOpFailure(alias, error)
668
876
  }
669
877
  throw error
670
878
  } finally {
@@ -729,18 +937,44 @@ export class RemotePool {
729
937
  * ssh2 has no channel-open timeout: a server that never answers leaves this
730
938
  * promise pending forever, which pins the connection's hold count and blocks
731
939
  * idle re-arming (the "SSH looks dead" symptom) while the HTTP request hangs.
940
+ *
941
+ * The deadline is spelled out here instead of wrapped around the promise
942
+ * because the ANSWER can arrive after it: `conn.sftp`'s callback is the only
943
+ * place that can still see the session, and a late one would otherwise leak a
944
+ * server-side channel that no slot or hold accounts for (the caller has long
945
+ * returned its own and moved on).
732
946
  */
733
947
  private openSession(conn: Client): Promise<SFTPWrapper> {
734
- return withDeadline(
735
- new Promise<SFTPWrapper>((resolve, reject) => {
736
- conn.sftp((error, session) => {
737
- if (error !== undefined && error !== null) reject(error)
738
- else resolve(session)
739
- })
740
- }),
741
- SFTP_OP_TIMEOUT_MS,
742
- `SFTP session open timed out after ${SFTP_OP_TIMEOUT_MS / 1000}s`,
743
- )
948
+ return new Promise<SFTPWrapper>((resolve, reject) => {
949
+ let settled = false
950
+ const timer = setTimeout(() => {
951
+ if (settled) return
952
+ settled = true
953
+ reject(new DeadlineError(`SFTP session open timed out after ${SFTP_OP_TIMEOUT_MS / 1000}s`))
954
+ }, SFTP_OP_TIMEOUT_MS)
955
+ timer.unref?.()
956
+ const finish = (error: unknown, session?: SFTPWrapper): void => {
957
+ if (settled) {
958
+ // Deadline first, answer later: the session is ours alone, so close it.
959
+ try {
960
+ session?.end()
961
+ } catch {
962
+ // Already gone.
963
+ }
964
+ return
965
+ }
966
+ settled = true
967
+ clearTimeout(timer)
968
+ if (error !== undefined && error !== null) reject(error)
969
+ else resolve(session as SFTPWrapper)
970
+ }
971
+ try {
972
+ conn.sftp((error, session) => finish(error, session))
973
+ } catch (error) {
974
+ // ssh2 can throw synchronously (e.g. on a dead connection).
975
+ finish(error)
976
+ }
977
+ })
744
978
  }
745
979
 
746
980
  /**
@@ -1032,36 +1266,77 @@ export class RemotePool {
1032
1266
  }
1033
1267
  const entry: Pooled = { conn: undefined as unknown as Client, timer: undefined, lastUse: Date.now(), connecting: undefined, held: 0 }
1034
1268
  this.conns.set(alias, entry)
1269
+ /**
1270
+ * The entry object IS the ownership token: `drop()` deletes it and a later
1271
+ * `acquire()` creates a NEW one, so comparing identity answers "does this
1272
+ * dial still own the alias?" without any extra field.
1273
+ *
1274
+ * Both halves matter. Without the success check, a dial that finishes after
1275
+ * `drop()` (host edited/deleted while connecting) leaves a live connection
1276
+ * nobody can ever close: the entry is out of the map, `release()` is a no-op
1277
+ * so no idle timer arms, and `dispose()` only walks the map. Without the
1278
+ * failure check, a failed OLD dial deletes the NEW entry by alias.
1279
+ */
1035
1280
  entry.connecting = this.dial(alias).then(
1036
1281
  (conn) => {
1282
+ if (this.conns.get(alias) !== entry) {
1283
+ try {
1284
+ conn.end()
1285
+ } catch {
1286
+ // Already gone.
1287
+ }
1288
+ throw new Error(`host ${alias} was disconnected while connecting`)
1289
+ }
1037
1290
  entry.conn = conn
1038
1291
  entry.connecting = undefined
1292
+ this.markOk(alias)
1039
1293
  conn.on('close', () => {
1040
- // The server went away: evict so the next op redials.
1041
- if (this.conns.get(alias) === entry) this.drop(alias)
1294
+ // The server went away: record it for the status chip, then evict so
1295
+ // the next op redials. Our OWN drop() deleted the entry first, so a
1296
+ // normal close (idle eviction, host removal) never lands here.
1297
+ if (this.conns.get(alias) !== entry) return
1298
+ this.markError(alias, new Error('connection closed'))
1299
+ this.drop(alias)
1042
1300
  })
1043
- conn.on('error', () => {
1044
- if (this.conns.get(alias) === entry) this.drop(alias)
1301
+ conn.on('error', (error: Error) => {
1302
+ if (this.conns.get(alias) !== entry) return
1303
+ this.markError(alias, error)
1304
+ this.drop(alias)
1045
1305
  })
1046
1306
  this.release(alias)
1047
1307
  return conn
1048
1308
  },
1049
1309
  (error) => {
1050
- this.conns.delete(alias)
1310
+ if (this.conns.get(alias) === entry) this.conns.delete(alias)
1311
+ this.markError(alias, error)
1051
1312
  throw error
1052
1313
  },
1053
1314
  )
1054
1315
  return entry.connecting
1055
1316
  }
1056
1317
 
1318
+ /**
1319
+ * The ssh2 client factory.
1320
+ *
1321
+ * A seam, not a preference: `dial` is the only place that has to react to
1322
+ * "connect emitted close but never error", and a fake client is the only way a
1323
+ * self-check can produce that shape without a real server. Production never
1324
+ * overrides it.
1325
+ */
1326
+ private makeClient(): Client {
1327
+ return new Client()
1328
+ }
1329
+
1057
1330
  private dial(alias: string): Promise<Client> {
1058
1331
  const host: RemoteHostEntry = this.store.require(alias)
1059
1332
  return new Promise<Client>((resolve, reject) => {
1060
- const conn = new Client()
1333
+ const conn = this.makeClient()
1061
1334
  let settled = false
1335
+ let guard: ReturnType<typeof setTimeout> | undefined
1062
1336
  const fail = (error: Error): void => {
1063
1337
  if (settled) return
1064
1338
  settled = true
1339
+ if (guard !== undefined) clearTimeout(guard)
1065
1340
  try {
1066
1341
  conn.end()
1067
1342
  } catch {
@@ -1072,9 +1347,25 @@ export class RemotePool {
1072
1347
  conn.on('ready', () => {
1073
1348
  if (settled) return
1074
1349
  settled = true
1350
+ if (guard !== undefined) clearTimeout(guard)
1075
1351
  resolve(conn)
1076
1352
  })
1077
1353
  conn.on('error', (error: Error) => fail(error))
1354
+ /**
1355
+ * ssh2 turns a socket close into an `error` only when the SSH banner never
1356
+ * arrived (client.js `onDone`: `wasConnected && !sawHeader`). A clean FIN
1357
+ * after the banner — a server restart or a middlebox dropping the flow
1358
+ * during KEX/auth — emits `end`/`close` and nothing else, which used to
1359
+ * leave this promise pending forever while the caller held a channel slot.
1360
+ */
1361
+ conn.on('close', () => fail(new Error('connection closed during SSH handshake')))
1362
+ // Last resort: the library reports nothing at all (neither ready, nor
1363
+ // error, nor close). `readyTimeout` cannot cover it because ssh2 clears
1364
+ // that timer as soon as the socket closes without emitting an error.
1365
+ guard = setTimeout(() => {
1366
+ fail(new Error(`SSH handshake did not settle within ${(READY_TIMEOUT_MS + DIAL_GUARD_MARGIN_MS) / 1000}s`))
1367
+ }, READY_TIMEOUT_MS + DIAL_GUARD_MARGIN_MS)
1368
+ guard.unref?.()
1078
1369
  conn.on('keyboard-interactive', (_name, _instructions, _lang, prompts, finish) => {
1079
1370
  // Password entries answer a single hidden prompt (the standard
1080
1371
  // password challenge shape) with the stored password — many servers
@@ -1220,15 +1511,6 @@ function warnDetached(alias: string): void {
1220
1511
  console.warn(`[dsh-remote-vs] exec timed out on ${alias}: the channel is closed but the remote command may still be running (no killable process group)`)
1221
1512
  }
1222
1513
 
1223
- /**
1224
- * An operation that ran out of its wall-clock budget.
1225
- *
1226
- * Tagged on purpose: callers have to tell "the remote never answered" from a real
1227
- * remote failure (a missing path must not cost the session), and matching on the
1228
- * message text would silently stop working the moment the template changed.
1229
- */
1230
- export class DeadlineError extends Error {}
1231
-
1232
1514
  /**
1233
1515
  * Reject when `promise` has not settled within `ms`, so a stalled remote
1234
1516
  * callback cannot keep a session (and its pooled connection) alive forever.
package/src/protocol.ts CHANGED
@@ -8,6 +8,8 @@
8
8
  export const REMOTE_API = {
9
9
  hosts: '/api/dsh-remote/hosts',
10
10
  test: '/api/dsh-remote/test',
11
+ /** Per-alias SSH connection health for the client's status indicator. */
12
+ status: '/api/dsh-remote/status',
11
13
  keygen: '/api/dsh-remote/keygen',
12
14
  exec: '/api/dsh-remote/exec',
13
15
  /** Streaming exec (server-sent events) for the long network verbs. */
@@ -140,6 +142,28 @@ export interface RemoteTimeouts {
140
142
  readMs: number
141
143
  }
142
144
 
145
+ /**
146
+ * Connection health for one host alias, as the Host's pool sees it.
147
+ *
148
+ * The browser never talks SSH itself, so it cannot know whether the link is up;
149
+ * this is the Host's answer. `idle` is NOT an error: a pooled connection is
150
+ * closed after 30 idle minutes, and the next operation dials again. `error`
151
+ * means the last connection-level event failed (dial error, unexpected close,
152
+ * or a transport-class operation failure) — the next operation will retry.
153
+ */
154
+ export interface RemoteConnectionStatus {
155
+ alias: string
156
+ state: 'ok' | 'error' | 'idle'
157
+ /** A pooled SSH connection is open right now (not a health promise on its own). */
158
+ open: boolean
159
+ /** Last successful dial / transport-level operation, epoch ms. */
160
+ okAt?: number
161
+ /** Last connection-level failure, epoch ms. */
162
+ errorAt?: number
163
+ /** Human-readable failure the client can show in the status chip. */
164
+ error?: string
165
+ }
166
+
143
167
  /** Remote OS probe outcome. */
144
168
  export interface RemoteProbe {
145
169
  alias: string
@@ -214,6 +238,17 @@ export interface RemoteFileEntry {
214
238
  export interface RemoteRead {
215
239
  /** File size in bytes. */
216
240
  size: number
241
+ /**
242
+ * Modification time in ms — the optimistic-lock baseline for a save.
243
+ *
244
+ * Read with the bytes in the same SFTP round trip, so the pair describes ONE
245
+ * version of the file. The editor stores it and sends it back on save; the
246
+ * Host refuses the write when the remote file has a different mtime, because
247
+ * that means someone else (an agent through the transparent route, a
248
+ * terminal, another editor) wrote it after this buffer was loaded and
249
+ * accepting the save would destroy their work without a word.
250
+ */
251
+ mtime: number
217
252
  /** True when the content is not UTF-8 text (base64 holds the bytes). */
218
253
  binary: boolean
219
254
  text?: string | undefined
@@ -222,6 +257,37 @@ export interface RemoteRead {
222
257
  truncated: boolean
223
258
  }
224
259
 
260
+ /** Result of one remote file write, including the version it left behind. */
261
+ export interface RemoteWriteResult {
262
+ /** Bytes written. */
263
+ size: number
264
+ /**
265
+ * mtime of the NEW content in ms: the baseline for the next save.
266
+ *
267
+ * `null` when the post-write stat could not be read. The save still SUCCEEDED
268
+ * (the bytes are in place), so this is not an error — it only means the next
269
+ * save has no baseline to check and must go through unguarded. Saying so is
270
+ * the whole point: a fabricated timestamp would make every later save of that
271
+ * tab conflict with itself.
272
+ */
273
+ mtime: number | null
274
+ }
275
+
276
+ /**
277
+ * The remote file changed since the baseline the caller saved against.
278
+ *
279
+ * Deliberately its own shape (not a generic failure): the client has to offer
280
+ * "overwrite / reload / see the difference" instead of showing a red toast and
281
+ * dropping the user's edit. `mtime` and `size` describe what is there NOW, so
282
+ * the client can say "the file changed at … and is N bytes" without another
283
+ * round trip; both are null when the file is gone (an external delete is a
284
+ * conflict too — saving towards it would recreate a file someone removed).
285
+ */
286
+ export interface RemoteWriteConflict {
287
+ mtime: number | null
288
+ size: number | null
289
+ }
290
+
225
291
  /** Result of one non-interactive command execution. */
226
292
  export interface RemoteExecResult {
227
293
  success: boolean