dsh-remote-vs 0.25.0 → 0.27.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 (109) hide show
  1. package/README.en.md +12 -15
  2. package/README.md +11 -12
  3. package/THIRD-PARTY-NOTICES.md +193 -0
  4. package/lib/client.js +7313 -79961
  5. package/lib/index.js +1529 -964
  6. package/lib/p2-router-fs.js +1 -1
  7. package/lib/types/client/CodeEditor.d.ts +22 -0
  8. package/lib/types/client/OutlinePanel.d.ts +22 -0
  9. package/lib/types/client/ProcessesSection.d.ts +19 -0
  10. package/lib/types/client/RemoteExplorer.d.ts +53 -0
  11. package/lib/types/client/api.d.ts +42 -3
  12. package/lib/types/client/blame-model.d.ts +77 -0
  13. package/lib/types/client/changes/review-state.d.ts +19 -0
  14. package/lib/types/client/connection.d.ts +16 -0
  15. package/lib/types/client/i18n.d.ts +1 -1
  16. package/lib/types/client/outline-model.d.ts +59 -0
  17. package/lib/types/client/request-gate.d.ts +110 -0
  18. package/lib/types/client/scm/DiffView.d.ts +45 -7
  19. package/lib/types/client/scm/actions.d.ts +43 -4
  20. package/lib/types/client/store.d.ts +71 -0
  21. package/lib/types/client/vsc/FindWidget.d.ts +6 -0
  22. package/lib/types/client/vsc/blame.d.ts +19 -0
  23. package/lib/types/client/vsc/change-marks.d.ts +16 -6
  24. package/lib/types/client/vsc/editor-keymap.d.ts +35 -1
  25. package/lib/types/client/vsc/kit.d.ts +11 -2
  26. package/lib/types/client/vsc/preview-document.d.ts +46 -0
  27. package/lib/types/client/vsc/preview-model.d.ts +31 -0
  28. package/lib/types/client/vsc/preview-services.d.ts +24 -0
  29. package/lib/types/client/vsc/save-shortcut.d.ts +21 -0
  30. package/lib/types/client/vsc/terminal-theme.d.ts +28 -2
  31. package/lib/types/forward.d.ts +12 -0
  32. package/lib/types/fs-ops.d.ts +42 -0
  33. package/lib/types/git-ops.d.ts +18 -0
  34. package/lib/types/http.d.ts +2 -0
  35. package/lib/types/keygen.d.ts +9 -0
  36. package/lib/types/monitor.d.ts +8 -0
  37. package/lib/types/notices.d.ts +16 -1
  38. package/lib/types/p2/helper-rpc.d.ts +45 -0
  39. package/lib/types/processes.d.ts +43 -0
  40. package/lib/types/protocol.d.ts +34 -0
  41. package/lib/types/routes.d.ts +2 -0
  42. package/lib/types/store.d.ts +7 -0
  43. package/lib/types/terminal.d.ts +8 -0
  44. package/lib/types/view-settings.d.ts +5 -0
  45. package/lib/{worlds-B7gEDBzC.js → worlds-RG8K5eom.js} +113 -15
  46. package/package.json +3 -1
  47. package/src/client/CodeEditor.tsx +194 -9
  48. package/src/client/DirectoryFlow.tsx +16 -0
  49. package/src/client/DoctorPanel.tsx +70 -7
  50. package/src/client/EditorPane.tsx +574 -42
  51. package/src/client/HostsView.tsx +12 -3
  52. package/src/client/MonitorView.tsx +16 -5
  53. package/src/client/OutlinePanel.tsx +287 -0
  54. package/src/client/ProcessesSection.tsx +292 -0
  55. package/src/client/RemoteDirectoryPicker.tsx +12 -0
  56. package/src/client/RemoteExplorer.tsx +929 -40
  57. package/src/client/RemoteRoot.tsx +147 -22
  58. package/src/client/SearchView.tsx +8 -0
  59. package/src/client/TerminalSnippets.tsx +83 -8
  60. package/src/client/api.ts +114 -13
  61. package/src/client/blame-model.ts +242 -0
  62. package/src/client/changes/ChangesDock.tsx +188 -6
  63. package/src/client/changes/changes.css +10 -3
  64. package/src/client/changes/review-state.ts +34 -0
  65. package/src/client/connection.ts +29 -0
  66. package/src/client/downloads.ts +49 -4
  67. package/src/client/i18n.ts +276 -8
  68. package/src/client/index.tsx +4 -0
  69. package/src/client/outline-model.ts +775 -0
  70. package/src/client/request-gate.ts +221 -0
  71. package/src/client/scm/CommitPane.tsx +20 -2
  72. package/src/client/scm/DiffView.tsx +343 -117
  73. package/src/client/scm/HistoryPanel.tsx +61 -3
  74. package/src/client/scm/RepoPicker.tsx +1 -1
  75. package/src/client/scm/ScmPanel.tsx +391 -87
  76. package/src/client/scm/actions.ts +150 -14
  77. package/src/client/store.tsx +426 -14
  78. package/src/client/ui.tsx +4 -0
  79. package/src/client/vsc/FindWidget.tsx +24 -9
  80. package/src/client/vsc/blame.ts +147 -0
  81. package/src/client/vsc/breadcrumb.tsx +91 -3
  82. package/src/client/vsc/change-marks.ts +93 -44
  83. package/src/client/vsc/editor-keymap.ts +59 -1
  84. package/src/client/vsc/file-icons.tsx +17 -3
  85. package/src/client/vsc/kit.tsx +29 -20
  86. package/src/client/vsc/preview-document.tsx +323 -0
  87. package/src/client/vsc/preview-model.ts +216 -0
  88. package/src/client/vsc/preview-services.ts +118 -0
  89. package/src/client/vsc/save-shortcut.ts +47 -1
  90. package/src/client/vsc/terminal-theme.ts +44 -18
  91. package/src/client/vsc/vsc.css +6509 -5458
  92. package/src/forward.ts +47 -9
  93. package/src/fs-ops.ts +124 -4
  94. package/src/git-ops.ts +54 -3
  95. package/src/http.ts +35 -4
  96. package/src/keygen.ts +55 -4
  97. package/src/monitor.ts +13 -0
  98. package/src/notices.ts +23 -1
  99. package/src/p2/helper-rpc.ts +113 -7
  100. package/src/p2/worlds.ts +14 -1
  101. package/src/processes.ts +177 -0
  102. package/src/protocol.ts +37 -0
  103. package/src/routes.ts +330 -43
  104. package/src/sftp.ts +51 -14
  105. package/src/store.ts +10 -0
  106. package/src/terminal.ts +73 -26
  107. package/src/view-settings.ts +50 -10
  108. package/lib/types/client/Dialog.d.ts +0 -14
  109. package/src/client/Dialog.tsx +0 -76
@@ -149,6 +149,21 @@ export class RpcConnection {
149
149
  private heartbeat: ReturnType<typeof setTimeout> | undefined
150
150
  private dead: Error | undefined
151
151
  private disposed = false
152
+ /**
153
+ * Transport generation, bumped by every teardown.
154
+ *
155
+ * ssh2 does not close synchronously: `Channel.close()` is a PROTOCOL message
156
+ * and `Client.end()`'s socket 'close' arrives later. Those late
157
+ * 'close'/'error' events used to call `invalidate()` after `reconnect()` had
158
+ * already cleared `dead`, marking the BRAND-NEW dial dead: `open()` then
159
+ * released the fresh transport and the retry rejected with the OLD
160
+ * transport's error (probe T6 measured exactly this — a close 5 ms late, a
161
+ * new dial 20 ms). Every transport callback therefore captures the generation
162
+ * it was created under and compares it before acting; a teardown invalidates
163
+ * every callback of the transport it releases, without removing listeners
164
+ * (ssh2 offers no per-callback unsubscribe that would survive a destroy).
165
+ */
166
+ private generation = 0
152
167
  /**
153
168
  * The helper's own error output, kept so its reason survives.
154
169
  *
@@ -185,6 +200,9 @@ export class RpcConnection {
185
200
  let attempt = 0
186
201
  for (;;) {
187
202
  const peer = await this.peerReady()
203
+ // The link this attempt is queued against: a timeout that fires after a
204
+ // concurrent caller already reconnected must not invalidate the NEW dial.
205
+ const generation = this.generation
188
206
  // Queue rather than let the shared connection reject the call: every agent
189
207
  // on this host funnels through here, and "pending request limit reached"
190
208
  // used to fail a turn for work that only needed to wait its turn.
@@ -194,6 +212,10 @@ export class RpcConnection {
194
212
  } catch (error) {
195
213
  // A caller abort is the caller's decision — never retry it.
196
214
  if (!(error instanceof HelperTimeoutError)) throw error
215
+ // The transport this request rode was already replaced while it was in
216
+ // flight: its timeout describes the OLD link, so leave the current one
217
+ // alone (the reconnect its owner is running will report its own outcome).
218
+ if (generation !== this.generation) throw error
197
219
  // Mark the connection dead so the cached fs view is dropped and the next
198
220
  // caller dials cleanly instead of queueing behind a stuck channel.
199
221
  this.invalidate(error)
@@ -231,6 +253,14 @@ export class RpcConnection {
231
253
  if (this.disposed) throw new Error('helper RPC was disposed')
232
254
  // One teardown for every field: the old transport is fully gone before a new
233
255
  // attempt starts (a half-closed one would keep the ssh session alive).
256
+ //
257
+ // The generation bump inside that teardown is also what makes the window
258
+ // below safe: `dead` is cleared while the OLD transport's asynchronous
259
+ // close/error events may still be in flight, and those callbacks are bound
260
+ // to the generation the teardown just invalidated (see `generation`) — they
261
+ // cannot re-set `dead` under the new dial. Without the guard this method
262
+ // would reject with the previous transport's error and the "fresh channel"
263
+ // retry would never get to run.
234
264
  this.teardownTransport()
235
265
  this.dead = undefined
236
266
  this.readyPromise = this.open()
@@ -249,6 +279,13 @@ export class RpcConnection {
249
279
  async dispose(): Promise<void> {
250
280
  if (this.disposed) return
251
281
  this.disposed = true
282
+ // A dial in flight has no peer/channel yet: the ssh2 `Client` belongs to the
283
+ // handshake, and ending it here would strand that promise — ssh2 clears its
284
+ // own ready timer on close and emits 'close' WITHOUT an 'error', so the
285
+ // awaiting `dialAndHello` would never settle (and a concurrent `dial()` that
286
+ // disposes a reconnect would hang the retry forever). `open()` sees
287
+ // `disposed` when the attempt settles and releases it there.
288
+ if (this.peer === undefined && this.channel === undefined && this.conn !== undefined) return
252
289
  this.teardownTransport()
253
290
  }
254
291
 
@@ -270,8 +307,13 @@ export class RpcConnection {
270
307
  * `stderrTail` is cleared too: it describes the connection being torn down, and
271
308
  * keeping it would attribute the NEXT failure to the previous transport's error
272
309
  * output.
310
+ *
311
+ * The generation bump comes FIRST: the close calls below can emit their events
312
+ * synchronously, and anything this transport has queued must already count as
313
+ * stale by then.
273
314
  */
274
315
  private teardownTransport(): void {
316
+ this.generation += 1
275
317
  if (this.heartbeat !== undefined) {
276
318
  clearTimeout(this.heartbeat)
277
319
  this.heartbeat = undefined
@@ -291,7 +333,19 @@ export class RpcConnection {
291
333
  const conn = new Client()
292
334
  this.conn = conn
293
335
  try {
294
- return await this.dialAndHello(conn)
336
+ const hello = await this.dialAndHello(conn)
337
+ // `invalidate()` may have fired WHILE this attempt was dialing: a genuine
338
+ // error/close on THIS socket after 'ready' but before the hello answer sets
339
+ // `dead` without touching the dialing Client; a `dispose()` that arrived
340
+ // meanwhile set `disposed` and deliberately left the dial alone (ending it
341
+ // would strand the handshake). Either way the attempt has now succeeded, so
342
+ // the transport it produced is useless to everyone — release it here rather
343
+ // than leaving a live socket with no owner (the leak this path prevents).
344
+ if (this.dead !== undefined || this.disposed) {
345
+ this.teardownTransport()
346
+ throw this.dead ?? new Error('helper RPC was disposed')
347
+ }
348
+ return hello
295
349
  } catch (error) {
296
350
  // Anything that fails after the socket is up must not leave it behind: the
297
351
  // caller only sees the reject, and the next attempt would open a second
@@ -304,6 +358,10 @@ export class RpcConnection {
304
358
  /** The part of {@link open} that runs once the socket object exists. */
305
359
  private async dialAndHello(conn: Client): Promise<RpcHello> {
306
360
  const { entry } = this.opts
361
+ // The transport this attempt belongs to. Anything ssh2 reports after a
362
+ // teardown is about a link nobody owns any more; the callbacks below compare
363
+ // against the live value before touching `dead`/`stderrTail`.
364
+ const generation = this.generation
307
365
  await new Promise<void>((resolve, reject) => {
308
366
  let settled = false
309
367
  conn.on('ready', () => {
@@ -316,12 +374,20 @@ export class RpcConnection {
316
374
  if (!settled) {
317
375
  settled = true
318
376
  reject(error)
319
- } else {
377
+ } else if (generation === this.generation) {
320
378
  this.invalidate(error)
321
379
  }
322
380
  })
323
381
  conn.on('close', () => {
324
- this.invalidate(new Error('ssh connection closed'))
382
+ // Settle a handshake that never became ready: ssh2 reports a socket that
383
+ // closes before 'ready' as 'close' only (no 'error'), which used to leave
384
+ // `dialAndHello` pending forever.
385
+ if (!settled) {
386
+ settled = true
387
+ reject(new Error('ssh connection closed before it became ready'))
388
+ }
389
+ // A stale close describes the transport `reconnect()` already replaced.
390
+ if (generation === this.generation) this.invalidate(new Error('ssh connection closed'))
325
391
  })
326
392
  try {
327
393
  if (entry.auth.kind === 'key') {
@@ -359,13 +425,16 @@ export class RpcConnection {
359
425
  })
360
426
  this.channel = channel
361
427
  channel.stderr.on('data', (chunk: Buffer) => {
428
+ // A late chunk describes the previous transport's reason; attributing it
429
+ // to the new one would print the wrong helper error on the next failure.
430
+ if (generation !== this.generation) return
362
431
  this.stderrTail = (this.stderrTail + chunk.toString('utf8')).slice(-STDERR_TAIL_MAX)
363
432
  })
364
433
  channel.on('close', () => {
365
- this.invalidate(new Error('helper channel closed'))
434
+ if (generation === this.generation) this.invalidate(new Error('helper channel closed'))
366
435
  })
367
436
  channel.on('error', (error: Error) => {
368
- this.invalidate(error)
437
+ if (generation === this.generation) this.invalidate(error)
369
438
  })
370
439
  const leaseMs = this.opts.leaseMs ?? 30000
371
440
  const peer = new SshRpcPeer(channel, channel, MAX_FRAME, MAX_PENDING)
@@ -398,10 +467,15 @@ export class RpcConnection {
398
467
  // Arming the next beat only after the previous one settles makes overlap
399
468
  // impossible.
400
469
  const beat = (): void => {
401
- if (this.disposed || this.dead !== undefined) return
470
+ // A stale generation means this transport is gone: its teardown cleared the
471
+ // timer, and a beat already in flight must not resurrect it.
472
+ if (this.disposed || generation !== this.generation || this.dead !== undefined) return
402
473
  this.heartbeat = setTimeout(() => {
403
474
  peer.request('heartbeat', {}, z.null(), AbortSignal.timeout(Math.floor(leaseMs / 2)))
404
475
  .catch((error: unknown) => {
476
+ // The teardown closes the peer, so a beat that was in flight rejects
477
+ // with the TEARDOWN's error. That is not a fact about the new link.
478
+ if (generation !== this.generation) return
405
479
  this.invalidate(error instanceof Error ? error : new Error(String(error)))
406
480
  })
407
481
  .finally(beat)
@@ -418,14 +492,46 @@ export class RpcConnection {
418
492
  }
419
493
  }
420
494
 
495
+ /**
496
+ * Mark the connection dead AND release its transport.
497
+ *
498
+ * Closing the peer alone was not enough: `SshRpcPeer.close()` destroys the
499
+ * exec streams, and ssh2's `Channel.destroy()` does not end the `Client` that
500
+ * carries them — so the session stayed open (30s keepalive and all) while its
501
+ * owner had already written it off as dead. One leaked socket per invalidation,
502
+ * until the process exits. `teardownTransport()` is the only path that ends the
503
+ * Client, so an invalidated connection goes through it too; that is safe to
504
+ * repeat because each field is cleared as it is closed and `closeQuietly`
505
+ * ignores a second close — a later `dispose()`, `reconnect()` or failed
506
+ * `open()` teardown therefore finds nothing left to release.
507
+ *
508
+ * Ordering is deliberate: the peer is closed FIRST so in-flight requests reject
509
+ * with THIS error (the teardown's own close would raise a generic
510
+ * "channel closed" instead), and `stderrTail` is captured BEFORE the teardown,
511
+ * which clears it — otherwise `diagnostics` in the dial path would always
512
+ * report "the helper wrote nothing to stderr".
513
+ *
514
+ * Only an ESTABLISHED transport is released here. While `open()` is still
515
+ * dialing, `conn` is alive and `channel`/`peer` are not, and ending that Client
516
+ * would strand the handshake: ssh2 clears its own ready timer when the socket
517
+ * closes and emits 'close' without an 'error', so the promise `open()` awaits
518
+ * would never settle. `open()` itself releases the attempt instead, once it has
519
+ * a definitive outcome.
520
+ */
421
521
  private invalidate(error: Error): void {
422
522
  if (this.dead !== undefined || this.disposed) return
423
523
  this.dead = error
424
- if (this.heartbeat !== undefined) clearTimeout(this.heartbeat)
524
+ if (this.heartbeat !== undefined) {
525
+ clearTimeout(this.heartbeat)
526
+ this.heartbeat = undefined
527
+ }
528
+ const tail = this.stderrTail
425
529
  try {
426
530
  this.peer?.close(error)
427
531
  } catch {
428
532
  // Ignore.
429
533
  }
534
+ if (this.peer !== undefined || this.channel !== undefined) this.teardownTransport()
535
+ this.stderrTail = tail
430
536
  }
431
537
  }
package/src/p2/worlds.ts CHANGED
@@ -658,9 +658,22 @@ export class RemoteWorlds {
658
658
  // cooldown engage, which is what keeps a PERMANENT condition from
659
659
  // storming — the guard belongs on the persistent case, not the first
660
660
  // hiccup.
661
+ //
662
+ // Discarding the connection must RELEASE its transport first. `alive` goes
663
+ // false as soon as the helper channel dies, but the ssh2 `Client` under it
664
+ // is still an open socket: an invalidated connection closes only its RPC
665
+ // peer, and `Channel.destroy()` does not end the session — so dropping the
666
+ // cache entry alone left one Client (with its 30s keepalive) alive per
667
+ // failed dial, accumulating until the plugin unloaded. `dispose()` is the
668
+ // one path that reaches `teardownTransport()` (peer → channel → Client).
669
+ // `diagnostics` is read first because that teardown clears `stderrTail`,
670
+ // and the failure message below must keep the helper's own words. The
671
+ // dispose is not awaited — it completes synchronously (no transport I/O)
672
+ // and retry pacing must not change.
673
+ const detail = conn.diagnostics
674
+ void conn.dispose().catch(() => undefined)
661
675
  this.rpcs.delete(alias)
662
676
  if (attempt < DIAL_IMMEDIATE_RETRIES) return this.dial(alias, attempt + 1)
663
- const detail = conn.diagnostics
664
677
  const reason = 'helper connection closed right after dialing'
665
678
  + (detail === '' ? ' (the helper wrote nothing to stderr)' : ` — helper stderr: ${detail}`)
666
679
  // Recorded so the NEXT call backs off, and thrown here rather than
@@ -0,0 +1,177 @@
1
+ /**
2
+ * Remote process snapshots for the monitor page.
3
+ *
4
+ * Same model as `listen-ports.ts`: one bounded POSIX probe (GNU `ps`, a BSD
5
+ * `ps` fallback, then an explicit `none`), with all parsing done host-side so
6
+ * the browser only receives a bounded table. A process is never killed by a
7
+ * command assembled in the browser: the route validates the PID against the
8
+ * latest snapshot and builds the one signal command here.
9
+ */
10
+ import type { RemoteProcess, RemoteProcessesResult } from './protocol.ts'
11
+ import { shQuote } from './git-format.ts'
12
+
13
+ /** Marker proving which probe branch actually ran. */
14
+ export const PROCESSES_MARK = '@@RVS-PROCS'
15
+
16
+ /** Budget for the whole probe; a stuck process table must not pin a channel. */
17
+ export const PROCESSES_TIMEOUT_MS = 15_000
18
+
19
+ /** Hard cap on rows per snapshot (a container host can have thousands). */
20
+ export const PROCESSES_MAX = 500
21
+
22
+ /** Longest command string sent to the browser per row. */
23
+ export const PROCESS_COMMAND_MAX = 300
24
+
25
+ /**
26
+ * One bounded probe.
27
+ *
28
+ * GNU first (`--sort` + `etimes`), then the portable `ps aux` table for BSD /
29
+ * old systems (`ppid` and elapsed time are unknown there). The marker
30
+ * line is printed BEFORE the table so an interrupted probe is distinguishable
31
+ * from a genuinely empty one; the final marker lets the parser reject a
32
+ * truncated run.
33
+ */
34
+ export function processesCommand(max: number = PROCESSES_MAX): string {
35
+ const cap = Math.max(1, Math.min(PROCESSES_MAX, Math.floor(max)))
36
+ // Cap + 1: the parser needs one extra row to tell "exactly at the cap" from
37
+ // "there were more rows, we cut them". The GNU branch is sorted by ps; the
38
+ // aux fallback is sorted here (ps aux on BSD has no --sort) on the %CPU column.
39
+ // `user:20` avoids procps' default 8-character user truncation (the panel's
40
+ // user filter would otherwise silently miss the rest of the name).
41
+ const gnu = `ps -eo pid=,ppid=,user:20=,pcpu=,pmem=,etimes=,args= --sort=-pcpu 2>/dev/null`
42
+ return [
43
+ // EXPORTED: a plain LC_ALL assignment does not reach `ps` itself.
44
+ 'export LC_ALL=C',
45
+ `if ${gnu} >/dev/null 2>&1; then`,
46
+ ` echo "${PROCESSES_MARK} gnu"`,
47
+ ` ${gnu} | head -n ${cap + 1}`,
48
+ 'elif ps aux >/dev/null 2>&1; then',
49
+ ` echo "${PROCESSES_MARK} bsd"`,
50
+ ` ps aux | tail -n +2 | sort -k3 -rn | head -n ${cap + 1}`,
51
+ 'else',
52
+ ` echo "${PROCESSES_MARK} none"`,
53
+ 'fi',
54
+ `echo "${PROCESSES_MARK} end"`,
55
+ ].join('\n')
56
+ }
57
+
58
+ /** A kill signal the route accepts; never an arbitrary string from the client. */
59
+ export type KillSignal = 'TERM' | 'KILL'
60
+
61
+ export function isKillSignal(value: unknown): value is KillSignal {
62
+ return value === 'TERM' || value === 'KILL'
63
+ }
64
+
65
+ /** Assert a PID a process snapshot may contain (1 is the remote init). */
66
+ export function assertProcessPid(value: unknown): number {
67
+ const pid = typeof value === 'number' ? value : Number(value)
68
+ if (!Number.isInteger(pid) || pid <= 1 || pid > 2_147_483_647) throw new Error('invalid process id')
69
+ return pid
70
+ }
71
+
72
+ /**
73
+ * Build the one kill command. The PID has already passed the snapshot check;
74
+ * single-quoting it keeps the command shape uniform with every other builder.
75
+ */
76
+ export function killCommand(pid: number, signal: KillSignal): string {
77
+ return `kill -s ${signal} ${shQuote(String(assertProcessPid(pid)))}`
78
+ }
79
+
80
+ function numberOr(value: string): number | null {
81
+ if (!/^[0-9]+(?:\.[0-9]+)?$/.test(value)) return null
82
+ const number = Number(value)
83
+ return Number.isFinite(number) ? number : null
84
+ }
85
+
86
+ /** Bound one argv line before it is serialized into the JSON response. */
87
+ function trimCommand(command: string): string {
88
+ return command.length <= PROCESS_COMMAND_MAX
89
+ ? command
90
+ : `${command.slice(0, PROCESS_COMMAND_MAX - 1)}…`
91
+ }
92
+
93
+ /** GNU row: pid ppid user pcpu pmem etimes args. */
94
+ function parseGnuRow(line: string): RemoteProcess | undefined {
95
+ const match = /^\s*(\d+)\s+(\d+)\s+(\S+)\s+([0-9.]+)\s+([0-9.]+)\s+(\d+)\s+(.*)$/.exec(line)
96
+ if (match === null) return undefined
97
+ const pid = match[1] as string
98
+ const ppid = match[2] as string
99
+ const user = match[3] as string
100
+ const cpu = match[4] as string
101
+ const mem = match[5] as string
102
+ const elapsed = match[6] as string
103
+ const command = match[7] as string
104
+ return {
105
+ pid: Number(pid),
106
+ ppid: Number(ppid),
107
+ user,
108
+ cpuPercent: numberOr(cpu) ?? 0,
109
+ memPercent: numberOr(mem) ?? 0,
110
+ elapsedSeconds: numberOr(elapsed) ?? null,
111
+ command: trimCommand(command.trim()),
112
+ }
113
+ }
114
+
115
+ /** BSD `ps aux` row: user pid %cpu %mem vsz rss tt stat started time command. */
116
+ function parseBsdRow(line: string): RemoteProcess | undefined {
117
+ const match = /^\s*(\S+)\s+(\d+)\s+([0-9.]+)\s+([0-9.]+)\s+\S+\s+\S+\s+\S+\s+\S+\s+(\S+)\s+\S+\s+(.*)$/.exec(line)
118
+ if (match === null) return undefined
119
+ const user = match[1] as string
120
+ const pid = match[2] as string
121
+ const cpu = match[3] as string
122
+ const mem = match[4] as string
123
+ const command = match[6] as string
124
+ return {
125
+ pid: Number(pid),
126
+ ppid: 0,
127
+ user,
128
+ cpuPercent: numberOr(cpu) ?? 0,
129
+ memPercent: numberOr(mem) ?? 0,
130
+ elapsedSeconds: null,
131
+ command: trimCommand(command.trim()),
132
+ }
133
+ }
134
+
135
+ /**
136
+ * Parse one probe. `exitCode === null` (channel died) or a missing end marker
137
+ * means `unknown`, never an empty process table.
138
+ */
139
+ export function parseProcesses(stdout: string, exitCode: number | null): RemoteProcessesResult {
140
+ const lines = stdout.split('\n').map(line => line.endsWith('\r') ? line.slice(0, -1) : line)
141
+ const markerAt = lines.findIndex(line => line.trim() === `${PROCESSES_MARK} gnu` || line.trim() === `${PROCESSES_MARK} bsd` || line.trim() === `${PROCESSES_MARK} none`)
142
+ if (exitCode === null || markerAt < 0) {
143
+ return { tool: 'unknown', processes: [], truncated: false, error: 'the remote process probe ended without a complete answer' }
144
+ }
145
+ const marker = lines[markerAt]?.trim() ?? ''
146
+ // The real terminator is the LAST marker line: a process argv containing a
147
+ // literal `@@RVS-PROCS end` must not truncate the table early.
148
+ let endAt = -1
149
+ for (let index = lines.length - 1; index > markerAt; index -= 1) {
150
+ if ((lines[index] as string).trim() === `${PROCESSES_MARK} end`) {
151
+ endAt = index
152
+ break
153
+ }
154
+ }
155
+ if (endAt < 0) {
156
+ return { tool: 'unknown', processes: [], truncated: false, error: 'the remote process probe was interrupted' }
157
+ }
158
+ if (marker.endsWith('none')) return { tool: 'none', processes: [], truncated: false }
159
+ const gnu = marker.endsWith('gnu')
160
+ const parsedProcesses: RemoteProcess[] = []
161
+ for (const line of lines.slice(markerAt + 1, endAt)) {
162
+ if (line.trim() === '') continue
163
+ const row = gnu ? parseGnuRow(line) : parseBsdRow(line)
164
+ // The probe's own shell/head/ps wrappers contain the marker in their argv;
165
+ // they are not user processes and must not be offered for a kill.
166
+ if (row !== undefined && !row.command.includes(PROCESSES_MARK)) parsedProcesses.push(row)
167
+ }
168
+ if (parsedProcesses.length === 0) {
169
+ return { tool: 'unknown', processes: [], truncated: false, error: 'the remote ps output could not be parsed' }
170
+ }
171
+ const truncated = parsedProcesses.length > PROCESSES_MAX
172
+ return {
173
+ tool: gnu ? 'gnu' : 'bsd',
174
+ processes: parsedProcesses.slice(0, PROCESSES_MAX),
175
+ truncated,
176
+ }
177
+ }
package/src/protocol.ts CHANGED
@@ -42,6 +42,8 @@ export const REMOTE_API = {
42
42
  listenPorts: '/api/dsh-remote/listen-ports',
43
43
  /** Live system metrics for the monitor panel (one bounded probe per host). */
44
44
  metrics: '/api/dsh-remote/metrics',
45
+ /** One bounded process table for the monitor page, plus TERM/KILL actions. */
46
+ processes: '/api/dsh-remote/processes',
45
47
  } as const
46
48
 
47
49
  /**
@@ -716,6 +718,41 @@ export interface RemoteListenPortsResult {
716
718
  error?: string
717
719
  }
718
720
 
721
+ /** One row of the remote process table. */
722
+ export interface RemoteProcess {
723
+ pid: number
724
+ /** Parent PID; 0 on a BSD `ps aux` table that does not print it. */
725
+ ppid: number
726
+ user: string
727
+ cpuPercent: number
728
+ memPercent: number
729
+ /** Elapsed seconds when the probe can provide them; null on BSD `ps aux`. */
730
+ elapsedSeconds: number | null
731
+ command: string
732
+ }
733
+
734
+ /**
735
+ * The remote process probe's answer.
736
+ *
737
+ * `tool: 'none' | 'unknown'` means "cannot enumerate", never "no processes";
738
+ * the monitor page must explain that instead of rendering an empty table.
739
+ */
740
+ export interface RemoteProcessesResult {
741
+ tool: 'gnu' | 'bsd' | 'none' | 'unknown'
742
+ processes: RemoteProcess[]
743
+ truncated: boolean
744
+ error?: string
745
+ }
746
+
747
+ /** Result of one TERM/KILL request (the route validates the PID first). */
748
+ export interface RemoteProcessKillResult {
749
+ ok: boolean
750
+ pid: number
751
+ signal: 'TERM' | 'KILL'
752
+ /** Remote error text when the signal was refused. */
753
+ error?: string
754
+ }
755
+
719
756
  /**
720
757
  * How one host metrics sample ended.
721
758
  *