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
package/src/routes.ts CHANGED
@@ -10,9 +10,18 @@ import { fileURLToPath } from 'node:url'
10
10
  import { WebSocketServer } from 'ws'
11
11
  import type { Context } from '@deepseek-ai/cordis'
12
12
  import type { WebRoute, WebUpgradeRoute } from '@deepseek-ai/dsh-host-webserver'
13
- import { readJsonBodyResult, writeJson, writeRouteError } from './http.ts'
13
+ import { readJsonBodyResult, scopeHostNotices, writeJson, writeRouteError } from './http.ts'
14
14
  import { isLoopbackRequest } from './loopback.ts'
15
- import { REMOTE_API, MAX_SELECTION_DOWNLOAD, selectionDownloadName, type ExecStreamEvent, type ImportReport, type RemoteTimeouts } from './protocol.ts'
15
+ import {
16
+ REMOTE_API,
17
+ MAX_SELECTION_DOWNLOAD,
18
+ selectionDownloadName,
19
+ type ExecStreamEvent,
20
+ type ImportReport,
21
+ type RemoteProcessesResult,
22
+ type RemoteHostMetrics,
23
+ type RemoteTimeouts,
24
+ } from './protocol.ts'
16
25
  import type { HostPayload, RemoteStore } from './store.ts'
17
26
  import type { RemotePool } from './pool.ts'
18
27
  import type { RemoteWorlds } from './p2/worlds.ts'
@@ -25,21 +34,34 @@ import { TERMINAL_MAX_FRAME_BYTES, TerminalSessionRegistry } from './terminal.ts
25
34
  import { ForwardManager, validateForwardRequest } from './forward.ts'
26
35
  import { LISTEN_PORTS_TIMEOUT_MS, listenPortsCommand, parseListenPorts } from './listen-ports.ts'
27
36
  import { HostMonitor } from './monitor.ts'
37
+ import { PROCESSES_TIMEOUT_MS, assertProcessPid, isKillSignal, killCommand, parseProcesses, processesCommand } from './processes.ts'
28
38
  import type { SessionChanges } from './changes/recorder.ts'
29
39
  import { DEFAULT_TIMEOUTS, clampExecTimeout } from './timeouts.ts'
30
40
  import { RemoteViewSettingsStore } from './view-settings.ts'
31
41
 
32
- /** One noServer WebSocket server for terminal upgrades (RFC 6455). */
33
- // `maxPayload` is the authoritative frame bound: without it ws buffers up to its
34
- // 100 MiB default before the handler ever sees the message, in the process that
35
- // also runs the agent. Terminal frames are small JSON control messages.
36
- const terminalWss = new WebSocketServer({ noServer: true, maxPayload: TERMINAL_MAX_FRAME_BYTES })
37
-
38
42
  function queryParam(url: URL, name: string): string | undefined {
39
43
  const value = url.searchParams.get(name)
40
44
  return value === null ? undefined : value
41
45
  }
42
46
 
47
+ /**
48
+ * Host alias a request URL names (`?alias=`), or `null` when it names none.
49
+ *
50
+ * Only the routes know what a request is about; the response writer needs that
51
+ * in order to attach only THIS host's notices (see `scopeHostNotices`).
52
+ */
53
+ function urlAliasOf(req: IncomingMessage): string | null {
54
+ const alias = new URL(req.url ?? '/', 'http://localhost').searchParams.get('alias')
55
+ return alias === null || alias === '' ? null : alias
56
+ }
57
+
58
+ /** Host alias a parsed JSON body names, or `null` when it names none. */
59
+ function bodyAliasOf(value: unknown): string | null {
60
+ if (typeof value !== 'object' || value === null) return null
61
+ const alias = (value as { alias?: unknown }).alias
62
+ return typeof alias === 'string' && alias !== '' ? alias : null
63
+ }
64
+
43
65
  /**
44
66
  * A caller mistake the route can name: well-formed HTTP, unusable payload.
45
67
  *
@@ -97,6 +119,12 @@ async function readBodyOrError<T>(
97
119
  writeJson(res, 400, { error: 'invalid JSON body' })
98
120
  return { ok: false }
99
121
  }
122
+ // POST routes name their host in the BODY, which the URL cannot tell us: mark
123
+ // the response here so its one-shot notices bind to that host.
124
+ if (result.kind === 'ok') {
125
+ const alias = bodyAliasOf(result.value)
126
+ if (alias !== null) scopeHostNotices(res, alias)
127
+ }
100
128
  return { ok: true, body: result.kind === 'ok' ? (result.value as T) : null }
101
129
  }
102
130
 
@@ -257,7 +285,13 @@ function ownSettingsNs(ctx: Context): string | undefined {
257
285
  return fallback
258
286
  }
259
287
 
260
- export function makeRoutes(deps: RemoteRoutesDeps): { routes: WebRoute[]; upgrade: WebUpgradeRoute; terminalSessions: TerminalSessionRegistry } {
288
+ export function makeRoutes(deps: RemoteRoutesDeps): {
289
+ routes: WebRoute[]
290
+ upgrade: WebUpgradeRoute
291
+ terminalSessions: TerminalSessionRegistry
292
+ /** Close the terminal upgrade server (plugin unload); idempotent. */
293
+ close: () => void
294
+ } {
261
295
  const { store, pool, worlds, ctx } = deps
262
296
  /** Timeouts for this request (a volatile config edit must apply live). */
263
297
  const timeouts = (): RemoteTimeouts => deps.timeouts?.() ?? DEFAULT_TIMEOUTS
@@ -267,9 +301,102 @@ export function makeRoutes(deps: RemoteRoutesDeps): { routes: WebRoute[]; upgrad
267
301
  // costs one extra sample, so it is safe to construct here instead of owning a
268
302
  // fiber-scoped effect like the forward manager.
269
303
  const monitor = new HostMonitor(pool)
304
+ /**
305
+ * Last process snapshot per alias. The kill route validates against this
306
+ * table, so a browser cannot construct a `kill` for an arbitrary PID; a stale
307
+ * entry is refreshed before validation rather than trusted indefinitely.
308
+ */
309
+ const processSnapshots = new Map<string, { at: number; result: RemoteProcessesResult }>()
310
+ /** One probe per alias at a time; a second reader joins the in-flight one. */
311
+ const processInflight = new Map<string, Promise<RemoteProcessesResult>>()
312
+ const forgetProcesses = (alias: string): void => {
313
+ processSnapshots.delete(alias)
314
+ processInflight.delete(alias)
315
+ }
316
+ const readProcesses = async (alias: string, maxAgeMs: number): Promise<RemoteProcessesResult> => {
317
+ const cached = processSnapshots.get(alias)
318
+ if (maxAgeMs > 0 && cached !== undefined && Date.now() - cached.at < maxAgeMs) return cached.result
319
+ const joined = processInflight.get(alias)
320
+ if (joined !== undefined) return joined
321
+ const task = (async (): Promise<RemoteProcessesResult> => {
322
+ const result = await pool.exec(alias, processesCommand(), { timeoutMs: PROCESSES_TIMEOUT_MS })
323
+ let parsed: RemoteProcessesResult
324
+ if (result.error !== undefined) {
325
+ parsed = { tool: 'unknown', processes: [], truncated: false, error: result.error }
326
+ } else if (result.timedOut) {
327
+ parsed = { tool: 'unknown', processes: [], truncated: false, error: `the process probe did not finish within ${PROCESSES_TIMEOUT_MS / 1000}s` }
328
+ } else if (result.exitCode === null) {
329
+ parsed = { tool: 'unknown', processes: [], truncated: false, error: 'the process probe ended without an exit status' }
330
+ } else {
331
+ parsed = parseProcesses(result.stdout, result.exitCode)
332
+ }
333
+ if (parsed.tool === 'gnu' || parsed.tool === 'bsd') {
334
+ processSnapshots.set(alias, { at: Date.now(), result: parsed })
335
+ } else {
336
+ processSnapshots.delete(alias)
337
+ }
338
+ return parsed
339
+ })()
340
+ processInflight.set(alias, task)
341
+ void task.then(
342
+ () => { if (processInflight.get(alias) === task) processInflight.delete(alias) },
343
+ () => { if (processInflight.get(alias) === task) processInflight.delete(alias) },
344
+ )
345
+ return task
346
+ }
270
347
  const forwards = deps.forwards
271
348
  const viewSettings = deps.viewSettings ?? new RemoteViewSettingsStore()
272
349
 
350
+ /**
351
+ * One noServer WebSocket server for terminal upgrades (RFC 6455).
352
+ *
353
+ * `maxPayload` is the authoritative frame bound: without it ws buffers up to
354
+ * its 100 MiB default before the handler ever sees the message, in the
355
+ * process that also runs the agent. Terminal frames are small JSON control
356
+ * messages.
357
+ *
358
+ * It belongs to the route set, not to the module: as a module-level singleton
359
+ * a plugin unload (and every later reload with a fresh module instance) left
360
+ * the old server object alive forever. It must NOT close per route rebuild —
361
+ * live PTYs survive a settings edit, and ws answers an upgrade on a closed
362
+ * server with 503 — so teardown is bound to the fiber (the unload boundary);
363
+ * a later load builds a fresh instance.
364
+ */
365
+ const terminalWss = new WebSocketServer({ noServer: true, maxPayload: TERMINAL_MAX_FRAME_BYTES })
366
+ /** Idempotent teardown of the terminal upgrade server (plugin unload). */
367
+ const close = (): void => {
368
+ try {
369
+ terminalWss.close()
370
+ } catch {
371
+ // Already closed.
372
+ }
373
+ }
374
+ // Route-only probes build `makeRoutes` with a bare ctx (no fiber): they own
375
+ // no server lifetime and their process ends with the probe.
376
+ if (typeof ctx.effect === 'function') {
377
+ ctx.effect(() => close, 'dsh-remote-vs: terminal websocket server')
378
+ }
379
+
380
+ /**
381
+ * A corrupt store is a service-side failure with a path the user can repair.
382
+ *
383
+ * `store.list()`/`listWorkspaces()` re-read the JSON file, and a bad file
384
+ * threw straight out of the route: the host webserver answered a bare 400
385
+ * with no body, so the GUI could only report "request failed" and the path
386
+ * that needs fixing never reached the person who could fix it.
387
+ */
388
+ const writeStoreError = (res: ServerResponse, error: unknown): void => {
389
+ writeJson(res, 503, {
390
+ code: 'store-corrupt',
391
+ error: error instanceof Error ? error.message : String(error),
392
+ path: store.filePath,
393
+ })
394
+ }
395
+
396
+ /** Did the store's own JSON parse/validate fail? (`store.filePath` names it.) */
397
+ const isStoreError = (error: unknown): boolean =>
398
+ error instanceof Error && error.message.includes(store.filePath)
399
+
273
400
  /**
274
401
  * Stream one remote `tar -czf -` command into a `.tar.gz` download response.
275
402
  *
@@ -388,7 +515,11 @@ export function makeRoutes(deps: RemoteRoutesDeps): { routes: WebRoute[]; upgrad
388
515
  const method = req.method ?? 'GET'
389
516
  const url = new URL(req.url ?? '/', 'http://localhost')
390
517
  if (method === 'GET') {
391
- writeJson(res, 200, { hosts: store.list().map(h => store.summarize(h)) })
518
+ try {
519
+ writeJson(res, 200, { hosts: store.list().map(h => store.summarize(h)) })
520
+ } catch (error) {
521
+ writeStoreError(res, error)
522
+ }
392
523
  return
393
524
  }
394
525
  if (method === 'POST') {
@@ -423,6 +554,7 @@ export function makeRoutes(deps: RemoteRoutesDeps): { routes: WebRoute[]; upgrad
423
554
  forwards?.stopAlias(alias)
424
555
  pool.forget(alias)
425
556
  monitor.forget(alias)
557
+ forgetProcesses(alias)
426
558
  void worlds.dropHost(alias).catch(() => undefined)
427
559
  if (!store.remove(alias)) {
428
560
  writeJson(res, 404, { error: `unknown host alias: ${alias}` })
@@ -442,6 +574,7 @@ export function makeRoutes(deps: RemoteRoutesDeps): { routes: WebRoute[]; upgrad
442
574
  try {
443
575
  pool.forget(alias)
444
576
  monitor.forget(alias)
577
+ forgetProcesses(alias)
445
578
  void worlds.dropHost(alias).catch(() => undefined)
446
579
  const entry = store.update(alias, body as Partial<HostPayload>)
447
580
  writeJson(res, 200, { host: store.summarize(entry) })
@@ -549,7 +682,53 @@ export function makeRoutes(deps: RemoteRoutesDeps): { routes: WebRoute[]; upgrad
549
682
  return
550
683
  }
551
684
  const timeoutMs = clampExecTimeout(body.timeoutMs)
552
- writeJson(res, 200, await pool.exec(body.alias, body.command, timeoutMs === undefined ? {} : { timeoutMs }))
685
+ /** The client closed the request: its response is never read. */
686
+ let clientGone = false
687
+ /** The client asked to stop: kill the remote even if the read is still opening. */
688
+ let cancelRequested = false
689
+ /** The cancel handle was invoked (only once). */
690
+ let cancelSent = false
691
+ let cancel: (() => void) | undefined
692
+ /**
693
+ * Stop the remote process group exactly once.
694
+ *
695
+ * Same latch as the streaming route: the disconnect may land while
696
+ * `pool.exec` is still acquiring the channel (slot queue, setsid probe,
697
+ * connect), where no handle exists yet — the request is remembered and
698
+ * fired the moment `onCancel` supplies one. Without this the command kept
699
+ * running to its timeout after a page refresh, holding a channel slot and
700
+ * remote CPU for nobody.
701
+ */
702
+ const abortRemote = (): void => {
703
+ cancelRequested = true
704
+ if (cancel === undefined || cancelSent) return
705
+ cancelSent = true
706
+ cancel()
707
+ }
708
+ res.on('close', () => {
709
+ // Also fires after a normal response; the run is settled by then and the
710
+ // cancel is a no-op.
711
+ clientGone = true
712
+ abortRemote()
713
+ })
714
+ try {
715
+ const result = await pool.exec(body.alias, body.command, {
716
+ ...(timeoutMs === undefined ? {} : { timeoutMs }),
717
+ onCancel: (handle) => {
718
+ cancel = handle
719
+ if (cancelRequested && !cancelSent) {
720
+ cancelSent = true
721
+ handle()
722
+ }
723
+ },
724
+ })
725
+ // Writing onto a closed socket is pointless (and the caller is gone).
726
+ if (!clientGone) writeJson(res, 200, result)
727
+ } catch (error) {
728
+ // The caller may have disconnected while the command was being set up:
729
+ // do not write a 502 onto a closed socket either.
730
+ if (!clientGone) writeJson(res, 502, { error: error instanceof Error ? error.message : String(error) })
731
+ }
553
732
  },
554
733
  },
555
734
  // ----------------------------------------------------- exec (streaming)
@@ -1001,24 +1180,28 @@ export function makeRoutes(deps: RemoteRoutesDeps): { routes: WebRoute[]; upgrad
1001
1180
  const method = req.method ?? 'GET'
1002
1181
  const url = new URL(req.url ?? '/', 'http://localhost')
1003
1182
  if (method === 'GET') {
1004
- const bindings = store.listWorkspaces()
1005
- const aliasPaths: Record<string, string> = {}
1006
- for (const b of bindings) aliasPaths[b.id] = worlds.aliasPathFor(b.id)
1007
- // Lazy registry ensure: a boot-time sync may have run before the
1008
- // workspace registry was ready (soft-skipped); the GUI always GETs
1009
- // on load, long after readiness, so re-sync here best-effort.
1010
- void worlds.syncWorkspaces().catch(() => undefined)
1011
- writeJson(res, 200, {
1012
- workspaces: bindings,
1013
- mode: worlds.mode,
1014
- aliasPaths,
1015
- tombstones: store.listTombstones(),
1016
- version: pluginVersion(),
1017
- // The client's own deadlines must match what this Host would allow,
1018
- // otherwise a raised `gitTimeoutMs` still died at the client's 45 s
1019
- // deadline (2026-10-19: large-repo `git status` looked like a hang).
1020
- timeouts: timeouts(),
1021
- })
1183
+ try {
1184
+ const bindings = store.listWorkspaces()
1185
+ const aliasPaths: Record<string, string> = {}
1186
+ for (const b of bindings) aliasPaths[b.id] = worlds.aliasPathFor(b.id)
1187
+ // Lazy registry ensure: a boot-time sync may have run before the
1188
+ // workspace registry was ready (soft-skipped); the GUI always GETs
1189
+ // on load, long after readiness, so re-sync here best-effort.
1190
+ void worlds.syncWorkspaces().catch(() => undefined)
1191
+ writeJson(res, 200, {
1192
+ workspaces: bindings,
1193
+ mode: worlds.mode,
1194
+ aliasPaths,
1195
+ tombstones: store.listTombstones(),
1196
+ version: pluginVersion(),
1197
+ // The client's own deadlines must match what this Host would allow,
1198
+ // otherwise a raised `gitTimeoutMs` still died at the client's 45 s
1199
+ // deadline (2026-10-19: large-repo `git status` looked like a hang).
1200
+ timeouts: timeouts(),
1201
+ })
1202
+ } catch (error) {
1203
+ writeStoreError(res, error)
1204
+ }
1022
1205
  return
1023
1206
  }
1024
1207
  if (method === 'POST') {
@@ -1282,7 +1465,10 @@ export function makeRoutes(deps: RemoteRoutesDeps): { routes: WebRoute[]; upgrad
1282
1465
  const entry = store.require(alias)
1283
1466
  writeJson(res, 200, { deploy: entry.deploy ?? { status: 'not-deployed' }, helpers: helperAvailability() })
1284
1467
  } catch (error) {
1285
- writeJson(res, 404, { error: error instanceof Error ? error.message : String(error) })
1468
+ // An unreadable store is NOT "unknown alias": report it as the
1469
+ // service failure it is, with the path the user can repair.
1470
+ if (isStoreError(error)) writeStoreError(res, error)
1471
+ else writeJson(res, 404, { error: error instanceof Error ? error.message : String(error) })
1286
1472
  }
1287
1473
  return
1288
1474
  }
@@ -1486,7 +1672,81 @@ export function makeRoutes(deps: RemoteRoutesDeps): { routes: WebRoute[]; upgrad
1486
1672
  }
1487
1673
  writeJson(res, 200, parseListenPorts(result.stdout, result.exitCode))
1488
1674
  } catch (error) {
1489
- writeJson(res, 502, { error: error instanceof Error ? error.message : String(error) })
1675
+ // A corrupt store during `alias` lookup is a 503 with the path, not a
1676
+ // 502 "remote host failed".
1677
+ if (isStoreError(error)) writeStoreError(res, error)
1678
+ else writeJson(res, 502, { error: error instanceof Error ? error.message : String(error) })
1679
+ }
1680
+ },
1681
+ },
1682
+ // -------------------------------------------------- remote processes
1683
+ {
1684
+ kind: 'exact',
1685
+ path: REMOTE_API.processes,
1686
+ handler: async (req, res) => {
1687
+ if (!isLoopbackRequest(req)) {
1688
+ writeJson(res, 403, { error: 'forbidden: loopback-only' })
1689
+ return
1690
+ }
1691
+ const method = req.method ?? 'GET'
1692
+ if (method !== 'GET' && method !== 'POST') {
1693
+ writeJson(res, 405, { error: `method not allowed: ${method}` })
1694
+ return
1695
+ }
1696
+ try {
1697
+ if (method === 'GET') {
1698
+ const url = new URL(req.url ?? '/', 'http://localhost')
1699
+ const alias = queryParam(url, 'alias')
1700
+ if (alias === undefined || alias === '') {
1701
+ writeJson(res, 400, { error: 'alias query parameter is required' })
1702
+ return
1703
+ }
1704
+ if (store.get(alias) === undefined) {
1705
+ writeJson(res, 404, { error: `unknown host alias: ${alias}` })
1706
+ return
1707
+ }
1708
+ writeJson(res, 200, await readProcesses(alias, queryParam(url, 'refresh') === '1' ? 0 : 3_000))
1709
+ return
1710
+ }
1711
+ const read = await readBodyOrError<{ alias?: unknown; pid?: unknown; signal?: unknown }>(req, res, { objectOnly: true })
1712
+ if (!read.ok) return
1713
+ const body = read.body ?? {}
1714
+ const alias = typeof body.alias === 'string' ? body.alias : ''
1715
+ if (alias === '') {
1716
+ writeJson(res, 400, { error: 'alias is required' })
1717
+ return
1718
+ }
1719
+ let pid: number
1720
+ try {
1721
+ pid = assertProcessPid(body.pid)
1722
+ } catch (error) {
1723
+ writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) })
1724
+ return
1725
+ }
1726
+ if (!isKillSignal(body.signal)) {
1727
+ writeJson(res, 400, { error: 'signal must be TERM or KILL' })
1728
+ return
1729
+ }
1730
+ // The snapshot is the authorization list: a PID that is not in the
1731
+ // current remote table cannot be signalled, even if it is numeric.
1732
+ const snapshot = await readProcesses(alias, 0)
1733
+ const target = snapshot.processes.find(process => process.pid === pid)
1734
+ if (target === undefined) {
1735
+ writeJson(res, 400, { error: `process ${pid} is not in the current remote snapshot` })
1736
+ return
1737
+ }
1738
+ const result = await pool.exec(alias, killCommand(pid, body.signal), { timeoutMs: 10_000 })
1739
+ if (result.error !== undefined || result.exitCode !== 0) {
1740
+ const message = result.error ?? result.stderr.trim() ?? ''
1741
+ writeJson(res, 502, { error: message === '' ? `kill failed [exit code: ${result.exitCode ?? '?'}]` : message })
1742
+ return
1743
+ }
1744
+ // The next GET must not serve the pre-kill snapshot.
1745
+ processSnapshots.delete(alias)
1746
+ writeJson(res, 200, { ok: true, pid, signal: body.signal })
1747
+ } catch (error) {
1748
+ if (isStoreError(error)) writeStoreError(res, error)
1749
+ else writeJson(res, 502, { error: error instanceof Error ? error.message : String(error) })
1490
1750
  }
1491
1751
  },
1492
1752
  },
@@ -1497,9 +1757,12 @@ export function makeRoutes(deps: RemoteRoutesDeps): { routes: WebRoute[]; upgrad
1497
1757
  // poll storm costs one channel and the first sample honestly says "unknown"
1498
1758
  // for the two deltas instead of inventing numbers.
1499
1759
  //
1500
- // `alias` selects one host; omitting it samples every configured host (the
1501
- // panel asks per host, so this is a convenience/tooling shape, not a
1502
- // browser fan-out). Loopback-fenced like every other route.
1760
+ // `alias` selects one host and is the ONLY shape that samples: a GET must
1761
+ // not have a dial side effect, and a bare `GET /metrics` used to sample
1762
+ // every configured host (waking sleeping machines for a listing nobody
1763
+ // asked to probe). Without `alias` it answers the cached samples only;
1764
+ // `all=1` asks for the real batch sample explicitly. Loopback-fenced like
1765
+ // every other route.
1503
1766
  {
1504
1767
  kind: 'exact',
1505
1768
  path: REMOTE_API.metrics,
@@ -1515,15 +1778,22 @@ export function makeRoutes(deps: RemoteRoutesDeps): { routes: WebRoute[]; upgrad
1515
1778
  const url = new URL(req.url ?? '/', 'http://localhost')
1516
1779
  const alias = queryParam(url, 'alias')
1517
1780
  const refresh = queryParam(url, 'refresh') === '1'
1518
- if (alias !== undefined && alias !== '' && store.get(alias) === undefined) {
1519
- writeJson(res, 404, { error: `unknown host alias: ${alias}` })
1520
- return
1521
- }
1522
- const aliases = alias === undefined || alias === ''
1523
- ? store.list().map(host => host.alias)
1524
- : [alias]
1781
+ /** Explicit opt-in to sampling every configured host (tooling/debug). */
1782
+ const all = queryParam(url, 'all') === '1'
1525
1783
  try {
1526
- const hosts = await Promise.all(aliases.map(host => monitor.sample(host, refresh)))
1784
+ let hosts: RemoteHostMetrics[]
1785
+ if (alias !== undefined && alias !== '') {
1786
+ if (store.get(alias) === undefined) {
1787
+ writeJson(res, 404, { error: `unknown host alias: ${alias}` })
1788
+ return
1789
+ }
1790
+ hosts = [await monitor.sample(alias, refresh)]
1791
+ } else if (all) {
1792
+ const aliases = store.list().map(host => host.alias)
1793
+ hosts = await Promise.all(aliases.map(host => monitor.sample(host, refresh)))
1794
+ } else {
1795
+ hosts = monitor.cached()
1796
+ }
1527
1797
  writeJson(res, 200, { hosts })
1528
1798
  } catch (error) {
1529
1799
  writeJson(res, 502, { error: error instanceof Error ? error.message : String(error) })
@@ -1578,5 +1848,22 @@ export function makeRoutes(deps: RemoteRoutesDeps): { routes: WebRoute[]; upgrad
1578
1848
  },
1579
1849
  }
1580
1850
 
1581
- return { routes, upgrade, terminalSessions }
1851
+ /**
1852
+ * Mark every response with the host it is about before the handler runs.
1853
+ *
1854
+ * `writeJson` attaches notices only for the alias recorded here (or, for a
1855
+ * POST, the one its parsed body names): one window may then never display —
1856
+ * and consume — another host's one-shot helper-push notice. A request that
1857
+ * names no host (the hosts/workspaces listings) marks `null` and leaves the
1858
+ * queue alone.
1859
+ */
1860
+ const scopedRoutes: WebRoute[] = routes.map(route => ({
1861
+ ...route,
1862
+ handler: (req, res) => {
1863
+ scopeHostNotices(res, urlAliasOf(req))
1864
+ return route.handler(req, res)
1865
+ },
1866
+ }))
1867
+
1868
+ return { routes: scopedRoutes, upgrade, terminalSessions, close }
1582
1869
  }
package/src/sftp.ts CHANGED
@@ -500,10 +500,37 @@ export class RemoteFiles {
500
500
  })
501
501
  this.trackPartial(alias, partial)
502
502
  const size = await streamIntoFile(sftp, partial, source, maxBytes)
503
- // Move into place. SFTP v3 `rename` refuses to clobber, so an overwrite
504
- // removes the old file first — the same window a normal editor save has.
505
- if (overwrite) await unlinkAsync(sftp, path).catch(() => undefined)
506
- await renameAsync(sftp, partial, path)
503
+ // Move into place the same way a save does: an overwrite must never
504
+ // delete the target first. The old unlink→rename pair left the directory
505
+ // empty when the rename failed, and the catch below then removed the new
506
+ // bytes too — the upload reported a failure and the user's file was gone.
507
+ // `replaceFile` swaps the names (posix-rename, or target-aside with a
508
+ // rollback), so the previous bytes survive every failure with the real
509
+ // error attached.
510
+ if (overwrite) {
511
+ // A write target must be a regular file (or absent). On servers without
512
+ // `posix-rename@openssh.com` the fallback renames the target aside — and
513
+ // SFTP v3 `rename` happily renames a DIRECTORY that way, so a file
514
+ // dropped onto a same-named folder would move the folder to `*.bak-*`
515
+ // (never swept) and report success. Fail before anything moves.
516
+ const targetStat = await lstatAsync(sftp, path).catch((error: unknown) => {
517
+ if ((error as { code?: number }).code === SFTP_NO_SUCH_FILE) return undefined
518
+ throw error
519
+ })
520
+ // `Stats.isDirectory()` is the real ssh2 shape; accept the raw mode for
521
+ // fake SFTPs (and any future backend) that only carry attributes.
522
+ const targetIsDirectory = targetStat !== undefined && (
523
+ typeof (targetStat as { isDirectory?: () => boolean }).isDirectory === 'function'
524
+ ? (targetStat as { isDirectory: () => boolean }).isDirectory()
525
+ : (targetStat.mode & 0o170000) === 0o040000
526
+ )
527
+ if (targetIsDirectory) throw new Error(`not a file: ${path} is a directory`)
528
+ await replaceFile(sftp, partial, path)
529
+ } else {
530
+ // No consent to replace: SFTP v3 `rename` refuses to clobber, so a file
531
+ // that appeared after the route's 409 check is kept.
532
+ await renameAsync(sftp, partial, path)
533
+ }
507
534
  this.forgetPartial(alias, partial)
508
535
  this.remember(this.knownDirs, dirKey(alias, dir))
509
536
  await this.sweepOrphanDirs(sftp, alias, dir)
@@ -701,16 +728,18 @@ export class RemoteFiles {
701
728
  try {
702
729
  await mkdirAsync(sftp, path)
703
730
  } catch (error) {
704
- // EEXIST (code 4, "Failure") means the level is already there.
705
731
  const code = (error as { code?: number }).code
706
- if (code !== 4 && code !== undefined) throw error
707
- if (code === undefined) {
708
- // Unknown failure: verify by stat before ignoring.
709
- try {
710
- await lstatAsync(sftp, path)
711
- } catch {
712
- throw error
713
- }
732
+ // OpenSSH's sftp-server answers EEXIST, EACCES, EROFS and ENOSPC with the
733
+ // same opaque `SSH_FX_FAILURE(4)`, so 4 cannot mean "already there" on its
734
+ // own: swallowing it hid a permission or disk-space refusal until it
735
+ // surfaced later as a misleading "no such file" (S3). Verify the path
736
+ // instead — an existing level is the case this walk must tolerate, any
737
+ // other failure rethrows the original status.
738
+ if (code !== SFTP_FAILURE && code !== undefined) throw error
739
+ try {
740
+ await lstatAsync(sftp, path)
741
+ } catch {
742
+ throw error
714
743
  }
715
744
  }
716
745
  }
@@ -955,7 +984,15 @@ async function explainSftpFailure(
955
984
  if (code !== SFTP_NO_SUCH_FILE && code !== SFTP_FAILURE) return undefined
956
985
  const kind = await pathKind(sftp, path)
957
986
  if (kind.kind === 'missing') {
958
- return new Error(wanted === 'directory' ? `no such directory: ${path}` : `no such file: ${path}`)
987
+ // A status 4 with nothing at the path usually is not "it never existed":
988
+ // OpenSSH reports EACCES/EROFS/ENOSPC with that same code, and the path may
989
+ // be unreadable rather than absent. Name the alternative instead of guessing
990
+ // one cause — EACCES in particular keeps its own status (3), so hard-coding
991
+ // "permission denied" here would be wrong for this code path.
992
+ const hint = code === SFTP_FAILURE
993
+ ? ' (the server reported only status 4: this can also be a permission or disk-space problem)'
994
+ : ''
995
+ return new Error(wanted === 'directory' ? `no such directory: ${path}${hint}` : `no such file: ${path}${hint}`)
959
996
  }
960
997
  if (wanted === 'directory' && kind.kind !== 'dir') {
961
998
  return new Error(`not a directory: ${path} is ${describeKind(kind)}`)
package/src/store.ts CHANGED
@@ -98,6 +98,16 @@ export class RemoteStore {
98
98
  this.reload()
99
99
  }
100
100
 
101
+ /**
102
+ * Absolute path of the JSON document.
103
+ *
104
+ * Diagnostics only: a corrupt file must name itself in the error a surface
105
+ * shows, otherwise the user only sees "the request failed".
106
+ */
107
+ get filePath(): string {
108
+ return this.file
109
+ }
110
+
101
111
  /**
102
112
  * Reload from disk (picks up external edits).
103
113
  *