dsh-remote-vs 0.24.0 → 0.26.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 (125) hide show
  1. package/README.en.md +50 -16
  2. package/README.md +40 -15
  3. package/THIRD-PARTY-NOTICES.md +188 -0
  4. package/lib/client.js +6512 -77887
  5. package/lib/index.js +1461 -1024
  6. package/lib/p2-router-fs.js +1 -1
  7. package/lib/types/client/CodeEditor.d.ts +25 -0
  8. package/lib/types/client/EditorPane.d.ts +16 -5
  9. package/lib/types/client/FloatingPlaceholder.d.ts +16 -5
  10. package/lib/types/client/RemoteEditorView.d.ts +13 -10
  11. package/lib/types/client/RemoteExplorer.d.ts +53 -0
  12. package/lib/types/client/RemoteRoot.d.ts +5 -5
  13. package/lib/types/client/TerminalSnippets.d.ts +36 -0
  14. package/lib/types/client/TerminalView.d.ts +1 -1
  15. package/lib/types/client/XTerm.d.ts +33 -0
  16. package/lib/types/client/api.d.ts +37 -2
  17. package/lib/types/client/changes/review-state.d.ts +19 -0
  18. package/lib/types/client/connection.d.ts +16 -0
  19. package/lib/types/client/editor-capability.d.ts +27 -0
  20. package/lib/types/client/i18n.d.ts +1 -1
  21. package/lib/types/client/request-gate.d.ts +110 -0
  22. package/lib/types/client/scm/DiffView.d.ts +45 -7
  23. package/lib/types/client/scm/actions.d.ts +31 -3
  24. package/lib/types/client/store.d.ts +112 -4
  25. package/lib/types/client/terminal-input.d.ts +23 -0
  26. package/lib/types/client/terminal-snippets.d.ts +86 -0
  27. package/lib/types/client/vsc/FindWidget.d.ts +6 -0
  28. package/lib/types/client/vsc/breadcrumb.d.ts +30 -0
  29. package/lib/types/client/vsc/change-marks.d.ts +16 -6
  30. package/lib/types/client/vsc/editor-caret.d.ts +32 -0
  31. package/lib/types/client/vsc/editor-keymap.d.ts +35 -1
  32. package/lib/types/client/vsc/editor-langs.d.ts +9 -0
  33. package/lib/types/client/vsc/editor-settings.d.ts +55 -0
  34. package/lib/types/client/vsc/image-preview.d.ts +36 -0
  35. package/lib/types/client/vsc/kit.d.ts +13 -0
  36. package/lib/types/client/vsc/save-shortcut.d.ts +21 -0
  37. package/lib/types/client/vsc/terminal-clipboard.d.ts +15 -0
  38. package/lib/types/client/vsc/terminal-line.d.ts +25 -0
  39. package/lib/types/client/vsc/terminal-links.d.ts +62 -0
  40. package/lib/types/client/vsc/terminal-theme.d.ts +48 -0
  41. package/lib/types/client/vsc/terminal-writer.d.ts +52 -0
  42. package/lib/types/forward.d.ts +12 -0
  43. package/lib/types/fs-ops.d.ts +42 -0
  44. package/lib/types/http.d.ts +2 -0
  45. package/lib/types/keygen.d.ts +9 -0
  46. package/lib/types/monitor.d.ts +8 -0
  47. package/lib/types/notices.d.ts +16 -1
  48. package/lib/types/p2/helper-rpc.d.ts +45 -0
  49. package/lib/types/pool.d.ts +25 -0
  50. package/lib/types/routes.d.ts +2 -0
  51. package/lib/types/store.d.ts +7 -0
  52. package/lib/types/terminal.d.ts +33 -1
  53. package/lib/types/view-settings.d.ts +5 -0
  54. package/lib/{worlds-B7gEDBzC.js → worlds-RG8K5eom.js} +113 -15
  55. package/package.json +2 -1
  56. package/src/client/CodeEditor.tsx +205 -10
  57. package/src/client/DirectoryFlow.tsx +16 -0
  58. package/src/client/DoctorPanel.tsx +70 -7
  59. package/src/client/EditorPane.tsx +545 -118
  60. package/src/client/FloatingPlaceholder.tsx +34 -5
  61. package/src/client/HostsView.tsx +12 -3
  62. package/src/client/RemoteDirectoryPicker.tsx +12 -0
  63. package/src/client/RemoteEditorView.tsx +14 -11
  64. package/src/client/RemoteExplorer.tsx +929 -40
  65. package/src/client/RemoteRoot.tsx +167 -147
  66. package/src/client/SearchView.tsx +8 -0
  67. package/src/client/TerminalSnippets.tsx +432 -0
  68. package/src/client/TerminalView.tsx +50 -1
  69. package/src/client/XTerm.tsx +228 -58
  70. package/src/client/api.ts +106 -13
  71. package/src/client/auto-open-remote.ts +11 -9
  72. package/src/client/changes/ChangesDock.tsx +188 -6
  73. package/src/client/changes/changes.css +10 -3
  74. package/src/client/changes/review-state.ts +34 -0
  75. package/src/client/connection.ts +29 -0
  76. package/src/client/downloads.ts +49 -4
  77. package/src/client/editor-capability.ts +42 -0
  78. package/src/client/i18n.ts +228 -12
  79. package/src/client/index.tsx +22 -6
  80. package/src/client/request-gate.ts +221 -0
  81. package/src/client/scm/CommitPane.tsx +20 -2
  82. package/src/client/scm/DiffView.tsx +343 -117
  83. package/src/client/scm/HistoryPanel.tsx +23 -2
  84. package/src/client/scm/RepoPicker.tsx +1 -1
  85. package/src/client/scm/ScmPanel.tsx +391 -87
  86. package/src/client/scm/actions.ts +95 -12
  87. package/src/client/store.tsx +537 -22
  88. package/src/client/terminal-input.ts +44 -0
  89. package/src/client/terminal-snippets.ts +216 -0
  90. package/src/client/ui.tsx +4 -0
  91. package/src/client/vsc/FindWidget.tsx +24 -9
  92. package/src/client/vsc/breadcrumb.tsx +339 -0
  93. package/src/client/vsc/change-marks.ts +93 -44
  94. package/src/client/vsc/editor-caret.ts +30 -0
  95. package/src/client/vsc/editor-keymap.ts +59 -1
  96. package/src/client/vsc/editor-langs.ts +20 -0
  97. package/src/client/vsc/editor-settings.ts +146 -0
  98. package/src/client/vsc/editor-theme.ts +4 -5
  99. package/src/client/vsc/file-icons.tsx +17 -3
  100. package/src/client/vsc/image-preview.tsx +110 -0
  101. package/src/client/vsc/kit.tsx +46 -10
  102. package/src/client/vsc/save-shortcut.ts +47 -1
  103. package/src/client/vsc/terminal-clipboard.ts +19 -0
  104. package/src/client/vsc/terminal-line.ts +101 -0
  105. package/src/client/vsc/terminal-links.ts +166 -0
  106. package/src/client/vsc/terminal-theme.ts +97 -0
  107. package/src/client/vsc/terminal-writer.ts +112 -0
  108. package/src/client/vsc/vsc.css +1078 -181
  109. package/src/forward.ts +47 -9
  110. package/src/fs-ops.ts +124 -4
  111. package/src/git-ops.ts +20 -3
  112. package/src/http.ts +35 -4
  113. package/src/keygen.ts +55 -4
  114. package/src/monitor.ts +13 -0
  115. package/src/notices.ts +23 -1
  116. package/src/p2/helper-rpc.ts +113 -7
  117. package/src/p2/worlds.ts +14 -1
  118. package/src/pool.ts +99 -27
  119. package/src/routes.ts +212 -43
  120. package/src/sftp.ts +51 -14
  121. package/src/store.ts +10 -0
  122. package/src/terminal.ts +225 -24
  123. package/src/view-settings.ts +50 -10
  124. package/lib/types/client/Dialog.d.ts +0 -14
  125. package/src/client/Dialog.tsx +0 -76
package/src/routes.ts CHANGED
@@ -10,9 +10,17 @@ 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 RemoteHostMetrics,
22
+ type RemoteTimeouts,
23
+ } from './protocol.ts'
16
24
  import type { HostPayload, RemoteStore } from './store.ts'
17
25
  import type { RemotePool } from './pool.ts'
18
26
  import type { RemoteWorlds } from './p2/worlds.ts'
@@ -29,17 +37,29 @@ import type { SessionChanges } from './changes/recorder.ts'
29
37
  import { DEFAULT_TIMEOUTS, clampExecTimeout } from './timeouts.ts'
30
38
  import { RemoteViewSettingsStore } from './view-settings.ts'
31
39
 
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
40
  function queryParam(url: URL, name: string): string | undefined {
39
41
  const value = url.searchParams.get(name)
40
42
  return value === null ? undefined : value
41
43
  }
42
44
 
45
+ /**
46
+ * Host alias a request URL names (`?alias=`), or `null` when it names none.
47
+ *
48
+ * Only the routes know what a request is about; the response writer needs that
49
+ * in order to attach only THIS host's notices (see `scopeHostNotices`).
50
+ */
51
+ function urlAliasOf(req: IncomingMessage): string | null {
52
+ const alias = new URL(req.url ?? '/', 'http://localhost').searchParams.get('alias')
53
+ return alias === null || alias === '' ? null : alias
54
+ }
55
+
56
+ /** Host alias a parsed JSON body names, or `null` when it names none. */
57
+ function bodyAliasOf(value: unknown): string | null {
58
+ if (typeof value !== 'object' || value === null) return null
59
+ const alias = (value as { alias?: unknown }).alias
60
+ return typeof alias === 'string' && alias !== '' ? alias : null
61
+ }
62
+
43
63
  /**
44
64
  * A caller mistake the route can name: well-formed HTTP, unusable payload.
45
65
  *
@@ -97,6 +117,12 @@ async function readBodyOrError<T>(
97
117
  writeJson(res, 400, { error: 'invalid JSON body' })
98
118
  return { ok: false }
99
119
  }
120
+ // POST routes name their host in the BODY, which the URL cannot tell us: mark
121
+ // the response here so its one-shot notices bind to that host.
122
+ if (result.kind === 'ok') {
123
+ const alias = bodyAliasOf(result.value)
124
+ if (alias !== null) scopeHostNotices(res, alias)
125
+ }
100
126
  return { ok: true, body: result.kind === 'ok' ? (result.value as T) : null }
101
127
  }
102
128
 
@@ -257,7 +283,13 @@ function ownSettingsNs(ctx: Context): string | undefined {
257
283
  return fallback
258
284
  }
259
285
 
260
- export function makeRoutes(deps: RemoteRoutesDeps): { routes: WebRoute[]; upgrade: WebUpgradeRoute; terminalSessions: TerminalSessionRegistry } {
286
+ export function makeRoutes(deps: RemoteRoutesDeps): {
287
+ routes: WebRoute[]
288
+ upgrade: WebUpgradeRoute
289
+ terminalSessions: TerminalSessionRegistry
290
+ /** Close the terminal upgrade server (plugin unload); idempotent. */
291
+ close: () => void
292
+ } {
261
293
  const { store, pool, worlds, ctx } = deps
262
294
  /** Timeouts for this request (a volatile config edit must apply live). */
263
295
  const timeouts = (): RemoteTimeouts => deps.timeouts?.() ?? DEFAULT_TIMEOUTS
@@ -270,6 +302,56 @@ export function makeRoutes(deps: RemoteRoutesDeps): { routes: WebRoute[]; upgrad
270
302
  const forwards = deps.forwards
271
303
  const viewSettings = deps.viewSettings ?? new RemoteViewSettingsStore()
272
304
 
305
+ /**
306
+ * One noServer WebSocket server for terminal upgrades (RFC 6455).
307
+ *
308
+ * `maxPayload` is the authoritative frame bound: without it ws buffers up to
309
+ * its 100 MiB default before the handler ever sees the message, in the
310
+ * process that also runs the agent. Terminal frames are small JSON control
311
+ * messages.
312
+ *
313
+ * It belongs to the route set, not to the module: as a module-level singleton
314
+ * a plugin unload (and every later reload with a fresh module instance) left
315
+ * the old server object alive forever. It must NOT close per route rebuild —
316
+ * live PTYs survive a settings edit, and ws answers an upgrade on a closed
317
+ * server with 503 — so teardown is bound to the fiber (the unload boundary);
318
+ * a later load builds a fresh instance.
319
+ */
320
+ const terminalWss = new WebSocketServer({ noServer: true, maxPayload: TERMINAL_MAX_FRAME_BYTES })
321
+ /** Idempotent teardown of the terminal upgrade server (plugin unload). */
322
+ const close = (): void => {
323
+ try {
324
+ terminalWss.close()
325
+ } catch {
326
+ // Already closed.
327
+ }
328
+ }
329
+ // Route-only probes build `makeRoutes` with a bare ctx (no fiber): they own
330
+ // no server lifetime and their process ends with the probe.
331
+ if (typeof ctx.effect === 'function') {
332
+ ctx.effect(() => close, 'dsh-remote-vs: terminal websocket server')
333
+ }
334
+
335
+ /**
336
+ * A corrupt store is a service-side failure with a path the user can repair.
337
+ *
338
+ * `store.list()`/`listWorkspaces()` re-read the JSON file, and a bad file
339
+ * threw straight out of the route: the host webserver answered a bare 400
340
+ * with no body, so the GUI could only report "request failed" and the path
341
+ * that needs fixing never reached the person who could fix it.
342
+ */
343
+ const writeStoreError = (res: ServerResponse, error: unknown): void => {
344
+ writeJson(res, 503, {
345
+ code: 'store-corrupt',
346
+ error: error instanceof Error ? error.message : String(error),
347
+ path: store.filePath,
348
+ })
349
+ }
350
+
351
+ /** Did the store's own JSON parse/validate fail? (`store.filePath` names it.) */
352
+ const isStoreError = (error: unknown): boolean =>
353
+ error instanceof Error && error.message.includes(store.filePath)
354
+
273
355
  /**
274
356
  * Stream one remote `tar -czf -` command into a `.tar.gz` download response.
275
357
  *
@@ -388,7 +470,11 @@ export function makeRoutes(deps: RemoteRoutesDeps): { routes: WebRoute[]; upgrad
388
470
  const method = req.method ?? 'GET'
389
471
  const url = new URL(req.url ?? '/', 'http://localhost')
390
472
  if (method === 'GET') {
391
- writeJson(res, 200, { hosts: store.list().map(h => store.summarize(h)) })
473
+ try {
474
+ writeJson(res, 200, { hosts: store.list().map(h => store.summarize(h)) })
475
+ } catch (error) {
476
+ writeStoreError(res, error)
477
+ }
392
478
  return
393
479
  }
394
480
  if (method === 'POST') {
@@ -549,7 +635,53 @@ export function makeRoutes(deps: RemoteRoutesDeps): { routes: WebRoute[]; upgrad
549
635
  return
550
636
  }
551
637
  const timeoutMs = clampExecTimeout(body.timeoutMs)
552
- writeJson(res, 200, await pool.exec(body.alias, body.command, timeoutMs === undefined ? {} : { timeoutMs }))
638
+ /** The client closed the request: its response is never read. */
639
+ let clientGone = false
640
+ /** The client asked to stop: kill the remote even if the read is still opening. */
641
+ let cancelRequested = false
642
+ /** The cancel handle was invoked (only once). */
643
+ let cancelSent = false
644
+ let cancel: (() => void) | undefined
645
+ /**
646
+ * Stop the remote process group exactly once.
647
+ *
648
+ * Same latch as the streaming route: the disconnect may land while
649
+ * `pool.exec` is still acquiring the channel (slot queue, setsid probe,
650
+ * connect), where no handle exists yet — the request is remembered and
651
+ * fired the moment `onCancel` supplies one. Without this the command kept
652
+ * running to its timeout after a page refresh, holding a channel slot and
653
+ * remote CPU for nobody.
654
+ */
655
+ const abortRemote = (): void => {
656
+ cancelRequested = true
657
+ if (cancel === undefined || cancelSent) return
658
+ cancelSent = true
659
+ cancel()
660
+ }
661
+ res.on('close', () => {
662
+ // Also fires after a normal response; the run is settled by then and the
663
+ // cancel is a no-op.
664
+ clientGone = true
665
+ abortRemote()
666
+ })
667
+ try {
668
+ const result = await pool.exec(body.alias, body.command, {
669
+ ...(timeoutMs === undefined ? {} : { timeoutMs }),
670
+ onCancel: (handle) => {
671
+ cancel = handle
672
+ if (cancelRequested && !cancelSent) {
673
+ cancelSent = true
674
+ handle()
675
+ }
676
+ },
677
+ })
678
+ // Writing onto a closed socket is pointless (and the caller is gone).
679
+ if (!clientGone) writeJson(res, 200, result)
680
+ } catch (error) {
681
+ // The caller may have disconnected while the command was being set up:
682
+ // do not write a 502 onto a closed socket either.
683
+ if (!clientGone) writeJson(res, 502, { error: error instanceof Error ? error.message : String(error) })
684
+ }
553
685
  },
554
686
  },
555
687
  // ----------------------------------------------------- exec (streaming)
@@ -1001,24 +1133,28 @@ export function makeRoutes(deps: RemoteRoutesDeps): { routes: WebRoute[]; upgrad
1001
1133
  const method = req.method ?? 'GET'
1002
1134
  const url = new URL(req.url ?? '/', 'http://localhost')
1003
1135
  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
- })
1136
+ try {
1137
+ const bindings = store.listWorkspaces()
1138
+ const aliasPaths: Record<string, string> = {}
1139
+ for (const b of bindings) aliasPaths[b.id] = worlds.aliasPathFor(b.id)
1140
+ // Lazy registry ensure: a boot-time sync may have run before the
1141
+ // workspace registry was ready (soft-skipped); the GUI always GETs
1142
+ // on load, long after readiness, so re-sync here best-effort.
1143
+ void worlds.syncWorkspaces().catch(() => undefined)
1144
+ writeJson(res, 200, {
1145
+ workspaces: bindings,
1146
+ mode: worlds.mode,
1147
+ aliasPaths,
1148
+ tombstones: store.listTombstones(),
1149
+ version: pluginVersion(),
1150
+ // The client's own deadlines must match what this Host would allow,
1151
+ // otherwise a raised `gitTimeoutMs` still died at the client's 45 s
1152
+ // deadline (2026-10-19: large-repo `git status` looked like a hang).
1153
+ timeouts: timeouts(),
1154
+ })
1155
+ } catch (error) {
1156
+ writeStoreError(res, error)
1157
+ }
1022
1158
  return
1023
1159
  }
1024
1160
  if (method === 'POST') {
@@ -1282,7 +1418,10 @@ export function makeRoutes(deps: RemoteRoutesDeps): { routes: WebRoute[]; upgrad
1282
1418
  const entry = store.require(alias)
1283
1419
  writeJson(res, 200, { deploy: entry.deploy ?? { status: 'not-deployed' }, helpers: helperAvailability() })
1284
1420
  } catch (error) {
1285
- writeJson(res, 404, { error: error instanceof Error ? error.message : String(error) })
1421
+ // An unreadable store is NOT "unknown alias": report it as the
1422
+ // service failure it is, with the path the user can repair.
1423
+ if (isStoreError(error)) writeStoreError(res, error)
1424
+ else writeJson(res, 404, { error: error instanceof Error ? error.message : String(error) })
1286
1425
  }
1287
1426
  return
1288
1427
  }
@@ -1486,7 +1625,10 @@ export function makeRoutes(deps: RemoteRoutesDeps): { routes: WebRoute[]; upgrad
1486
1625
  }
1487
1626
  writeJson(res, 200, parseListenPorts(result.stdout, result.exitCode))
1488
1627
  } catch (error) {
1489
- writeJson(res, 502, { error: error instanceof Error ? error.message : String(error) })
1628
+ // A corrupt store during `alias` lookup is a 503 with the path, not a
1629
+ // 502 "remote host failed".
1630
+ if (isStoreError(error)) writeStoreError(res, error)
1631
+ else writeJson(res, 502, { error: error instanceof Error ? error.message : String(error) })
1490
1632
  }
1491
1633
  },
1492
1634
  },
@@ -1497,9 +1639,12 @@ export function makeRoutes(deps: RemoteRoutesDeps): { routes: WebRoute[]; upgrad
1497
1639
  // poll storm costs one channel and the first sample honestly says "unknown"
1498
1640
  // for the two deltas instead of inventing numbers.
1499
1641
  //
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.
1642
+ // `alias` selects one host and is the ONLY shape that samples: a GET must
1643
+ // not have a dial side effect, and a bare `GET /metrics` used to sample
1644
+ // every configured host (waking sleeping machines for a listing nobody
1645
+ // asked to probe). Without `alias` it answers the cached samples only;
1646
+ // `all=1` asks for the real batch sample explicitly. Loopback-fenced like
1647
+ // every other route.
1503
1648
  {
1504
1649
  kind: 'exact',
1505
1650
  path: REMOTE_API.metrics,
@@ -1515,15 +1660,22 @@ export function makeRoutes(deps: RemoteRoutesDeps): { routes: WebRoute[]; upgrad
1515
1660
  const url = new URL(req.url ?? '/', 'http://localhost')
1516
1661
  const alias = queryParam(url, 'alias')
1517
1662
  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]
1663
+ /** Explicit opt-in to sampling every configured host (tooling/debug). */
1664
+ const all = queryParam(url, 'all') === '1'
1525
1665
  try {
1526
- const hosts = await Promise.all(aliases.map(host => monitor.sample(host, refresh)))
1666
+ let hosts: RemoteHostMetrics[]
1667
+ if (alias !== undefined && alias !== '') {
1668
+ if (store.get(alias) === undefined) {
1669
+ writeJson(res, 404, { error: `unknown host alias: ${alias}` })
1670
+ return
1671
+ }
1672
+ hosts = [await monitor.sample(alias, refresh)]
1673
+ } else if (all) {
1674
+ const aliases = store.list().map(host => host.alias)
1675
+ hosts = await Promise.all(aliases.map(host => monitor.sample(host, refresh)))
1676
+ } else {
1677
+ hosts = monitor.cached()
1678
+ }
1527
1679
  writeJson(res, 200, { hosts })
1528
1680
  } catch (error) {
1529
1681
  writeJson(res, 502, { error: error instanceof Error ? error.message : String(error) })
@@ -1578,5 +1730,22 @@ export function makeRoutes(deps: RemoteRoutesDeps): { routes: WebRoute[]; upgrad
1578
1730
  },
1579
1731
  }
1580
1732
 
1581
- return { routes, upgrade, terminalSessions }
1733
+ /**
1734
+ * Mark every response with the host it is about before the handler runs.
1735
+ *
1736
+ * `writeJson` attaches notices only for the alias recorded here (or, for a
1737
+ * POST, the one its parsed body names): one window may then never display —
1738
+ * and consume — another host's one-shot helper-push notice. A request that
1739
+ * names no host (the hosts/workspaces listings) marks `null` and leaves the
1740
+ * queue alone.
1741
+ */
1742
+ const scopedRoutes: WebRoute[] = routes.map(route => ({
1743
+ ...route,
1744
+ handler: (req, res) => {
1745
+ scopeHostNotices(res, urlAliasOf(req))
1746
+ return route.handler(req, res)
1747
+ },
1748
+ }))
1749
+
1750
+ return { routes: scopedRoutes, upgrade, terminalSessions, close }
1582
1751
  }
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
  *