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/sftp.ts CHANGED
@@ -7,7 +7,8 @@ import type { ServerResponse } from 'node:http'
7
7
  import { posix } from 'node:path'
8
8
  import type { OpenMode, SFTPWrapper, Stats } from 'ssh2'
9
9
  import type { RemotePool } from './pool.ts'
10
- import type { RemoteFileEntry, RemoteRead } from './protocol.ts'
10
+ import type { RemoteFileEntry, RemoteRead, RemoteWriteConflict, RemoteWriteResult } from './protocol.ts'
11
+ import { DeadlineError } from './timeouts.ts'
11
12
 
12
13
  /** Single-read cap (matches the fs-ssh 8 MiB window). */
13
14
  export const READ_CAP = 8 * 1024 * 1024
@@ -25,6 +26,35 @@ export const LIST_ENTRY_CAP = 20000
25
26
  /** Largest single upload accepted (matches the client-side planner cap). */
26
27
  export const UPLOAD_MAX_BYTES = 2 * 1024 * 1024 * 1024
27
28
 
29
+ /**
30
+ * The remote file changed after the bytes the caller saved against were read.
31
+ *
32
+ * Carries what is there NOW so the route can answer 409 with the current
33
+ * version instead of a bare message — the client shows "changed at …, N bytes"
34
+ * and offers overwrite / reload / see-the-difference without a second round
35
+ * trip. A missing target is a conflict too (`mtime`/`size` null): the file this
36
+ * buffer was loaded from is gone, so writing would recreate something a person
37
+ * or another tool deliberately removed.
38
+ *
39
+ * The mtime comparison is SFTP's own (second granularity), so this narrows the
40
+ * window rather than closing it: two writes to the same inode inside one second
41
+ * share an mtime. `expectSize` covers the common "same second, different
42
+ * length" case and nothing more. It is a guard against silent loss, not a
43
+ * strong consistency protocol — the docs say so.
44
+ */
45
+ export class WriteConflictError extends Error {
46
+ readonly conflict: RemoteWriteConflict
47
+ constructor(
48
+ readonly path: string,
49
+ mtime: number | null,
50
+ size: number | null,
51
+ ) {
52
+ super(`remote file changed since it was opened: ${path}`)
53
+ this.name = 'WriteConflictError'
54
+ this.conflict = { mtime, size }
55
+ }
56
+ }
57
+
28
58
  /**
29
59
  * How long one download stream may make no progress before it is failed.
30
60
  *
@@ -115,6 +145,22 @@ export const MULTI_CHANNEL_MIN_BYTES = 4 * 1024 * 1024
115
145
  */
116
146
  const MEMO_CAP = 512
117
147
 
148
+ /**
149
+ * Fixed segment every side file this plugin creates carries.
150
+ *
151
+ * A sweep must never be able to name a file the user owns. Without a reserved
152
+ * segment, the old shape (`.part-<8 hex>`) also matched a user's own
153
+ * `foo.part-deadbeef`, and the age bound was the only thing between that file
154
+ * and an irreversible delete. The segment makes "this name is shaped like ours"
155
+ * checkable, and the per-process ownership registry below makes the delete
156
+ * provable instead of guessed.
157
+ */
158
+ const PART_MARKER = '.dsh-rvs.part-'
159
+ /** Side files one sweep removes at most, so a burst cannot become a long list. */
160
+ const PART_SWEEP_MAX_PER_DIR = 50
161
+ /** Side-file name shape shared by `write` and `upload` (marker + 8 hex). */
162
+ const PART_NAME_RE = /\.dsh-rvs\.part-[0-9a-f]{8}$/
163
+
118
164
  /** SFTP status code for "no such file or directory" (ssh2 sets `error.code`). */
119
165
  const SFTP_NO_SUCH_FILE = 2
120
166
  /** Generic SFTP failure — what OpenSSH returns for most non-ENOENT errors. */
@@ -137,11 +183,13 @@ export function remotePath(path: string): string {
137
183
  *
138
184
  * The download's one-shot calls (`lstat`, `open`, `fstat`, an extra channel's
139
185
  * handle) have no progress signal, so this is the only thing between a stalled
140
- * server and a response — and two SFTP channels — pinned forever.
186
+ * server and a response — and two SFTP channels — pinned forever. The rejection
187
+ * is a `DeadlineError`, not a plain error: a budget that ran out must not be
188
+ * reported to the status chip as a dead link (see `pool.noteOpFailure`).
141
189
  */
142
190
  function bounded<T>(promise: Promise<T>, ms: number, message: string): Promise<T> {
143
191
  return new Promise<T>((resolve, reject) => {
144
- const timer = setTimeout(() => reject(new Error(message)), ms)
192
+ const timer = setTimeout(() => reject(new DeadlineError(message)), ms)
145
193
  timer.unref?.()
146
194
  promise.then(
147
195
  (value) => {
@@ -180,6 +228,24 @@ export class RemoteFiles {
180
228
  private readonly knownDirs = new Set<string>()
181
229
  /** Listings already reported as truncated; the log line stays one per path. */
182
230
  private readonly capWarned = new Set<string>()
231
+ /**
232
+ * Side files this process is still writing (`alias\0path`). A sweep skips them
233
+ * regardless of age — they are not orphans.
234
+ */
235
+ private readonly activePartials = new Set<string>()
236
+ /**
237
+ * Side files this process CREATED and could not remove (`alias\0path`).
238
+ *
239
+ * This is the ONLY set a sweep may delete from. Deleting a name that merely
240
+ * LOOKS like a side file is a guess, and guessing wrong destroys the user's
241
+ * data (the audit's P2-N1: `foo.part-deadbeef` in a directory that once
242
+ * recorded an orphan, older than the age bound, was irreversibly removed).
243
+ * A leftover from a previous Host process is therefore never swept either:
244
+ * junk that stays is recoverable, a deleted user file is not.
245
+ */
246
+ private readonly ownedPartials = new Set<string>()
247
+ /** alias -> directories that may hold an owned side file (sweep on next write). */
248
+ private readonly orphanDirs = new Map<string, Set<string>>()
183
249
 
184
250
  constructor(private readonly pool: RemotePool) {}
185
251
 
@@ -225,17 +291,29 @@ export class RemoteFiles {
225
291
  async read(alias: string, file: string): Promise<RemoteRead> {
226
292
  const path = remotePath(file)
227
293
  return this.pool.withBrowseSftp(alias, async (sftp) => {
228
- const attrs = await lstatAsync(sftp, path).catch(async (error: unknown) => {
294
+ /**
295
+ * Resolve to the REAL file first, exactly the way `write` does.
296
+ *
297
+ * A bare `lstat` describes a SYMBOLIC LINK (its own mtime, and the link
298
+ * target string's length as the size) while the bytes read through the path
299
+ * come from the target — so the mtime/size pair the editor stores as its
300
+ * save baseline described a different thing than the save would compare,
301
+ * and the first save of every symlinked file conflicted with itself
302
+ * forever (reloading re-read the link's mtime again). Resolving here makes
303
+ * read and write agree on which version they are talking about; the link
304
+ * itself is untouched, which is what "writes through symlinks" means.
305
+ */
306
+ const target = await resolveWriteTarget(sftp, path).catch(async (error: unknown) => {
229
307
  // The stat fails first for a path that is not there, so without this the
230
308
  // caller got a bare "No such file" naming no path, while `list` and
231
309
  // `write` already said which one.
232
310
  throw (await explainSftpFailure(sftp, path, 'file', error)) ?? error
233
311
  })
234
- // Checked from the stat that was already needed, rather than after a
235
- // failed read: asking the server to read a directory yields nothing but
236
- // "Failure", and this pre-check costs no extra round trip.
237
- if (isDir(attrs.mode)) throw new Error(`not a file: ${path} is a directory`)
238
- const size = attrs.size
312
+ // A dangling link resolves to a name with no version: nothing to read.
313
+ if (target.size === undefined || target.mtime === undefined) {
314
+ throw new Error(`no such file: ${path}`)
315
+ }
316
+ const size = target.size
239
317
  // A zero-byte file has no window to read, and asking SFTP for zero bytes
240
318
  // is NOT a no-op: ssh2's `read()` rejects `off >= buf.length` with a
241
319
  // SYNC throw ("offset is out of bounds"), which escapes the promise
@@ -243,13 +321,15 @@ export class RemoteFiles {
243
321
  // SFTP session open — repeating it exhausts the server's MaxSessions and
244
322
  // makes SSH look dead. Empty is answered from the stat alone.
245
323
  if (size <= 0) {
246
- return { size: 0, binary: false, text: '', truncated: false }
324
+ return { size: 0, mtime: target.mtime, binary: false, text: '', truncated: false }
247
325
  }
248
326
  const window = Math.min(size, READ_CAP)
249
- const buffer = await readWindow(sftp, path, 0, window)
327
+ const buffer = await readWindow(sftp, target.realPath, 0, window)
250
328
  const binary = buffer.includes(0)
251
329
  return {
252
330
  size,
331
+ // From the SAME stat as `size`, so the two describe one version.
332
+ mtime: target.mtime,
253
333
  binary,
254
334
  ...(binary ? { base64: buffer.toString('base64') } : { text: buffer.toString('utf8') }),
255
335
  truncated: size > READ_CAP,
@@ -257,26 +337,122 @@ export class RemoteFiles {
257
337
  })
258
338
  }
259
339
 
260
- async write(alias: string, file: string, content: string, encoding: 'utf8' | 'base64' = 'utf8'): Promise<{ size: number }> {
340
+ /**
341
+ * Write one file whole (the remote editor's save / `remote_write`), atomically.
342
+ *
343
+ * Not `writeFile` on the target: that truncates it first, so an interrupted
344
+ * save (a dropped link, a Host restart, a full disk mid-write) left the
345
+ * previous content gone AND the new one half written. The bytes go to a SIDE
346
+ * file next to the target (`.dsh-rvs.part-<8 hex>`, see `PART_MARKER`) and are
347
+ * only moved into place once the body is complete.
348
+ *
349
+ * "Moved into place" must not delete the target first: the old unlink-then-
350
+ * rename pair had a window where a failed rename left NEITHER the old file nor
351
+ * the new one, and reported it as `no such file`. `replaceFile` therefore uses
352
+ * OpenSSH's atomic `posix-rename` when the server advertises it, and otherwise
353
+ * swaps the target aside with a rollback, so the previous bytes survive every
354
+ * failure with the real error attached.
355
+ *
356
+ * Two things a fresh inode would otherwise lose:
357
+ * - a symbolic link target: the side file lives next to the link's REAL
358
+ * target and the link itself is left alone (the old in-place write punched
359
+ * through it; replacing it with a plain file silently changed what the path
360
+ * means);
361
+ * - the permission bits: they are copied back with `setstat` after the swap.
362
+ * Owner/group cannot be preserved without a privileged chown, so a save
363
+ * keeps the bytes and the mode but takes the SSH user's ownership.
364
+ */
365
+ async write(
366
+ alias: string,
367
+ file: string,
368
+ content: string,
369
+ encoding: 'utf8' | 'base64' = 'utf8',
370
+ guard?: { expectMtime?: number | undefined; expectSize?: number | undefined },
371
+ ): Promise<RemoteWriteResult> {
261
372
  const path = remotePath(file)
262
- const dir = posix.dirname(path)
263
373
  const data = encoding === 'base64' ? Buffer.from(content, 'base64') : Buffer.from(content, 'utf8')
264
374
  return this.pool.withSftp(alias, async (sftp) => {
375
+ /** Set once the target may be mid-swap: such failures are never reworded. */
376
+ let replacing = false
377
+ let partial: string | undefined
378
+ /** The new version's mtime; null when it could not be read back. */
379
+ let mtime: number | null = null
380
+ /** The new version's size, from the same stat as `mtime` when possible. */
381
+ let writtenSize = data.length
265
382
  try {
383
+ // Resolve the link BEFORE naming the side file: the side file has to sit
384
+ // in the same directory as the file it will be renamed onto.
385
+ const target = await resolveWriteTarget(sftp, path)
386
+ /**
387
+ * The optimistic lock, checked against the SAME stat that resolved the
388
+ * target — before a side file is even named, so a refused save touches
389
+ * nothing at all.
390
+ *
391
+ * A missing target conflicts when the caller HAD a baseline: the file
392
+ * these bytes were loaded from is gone (a terminal `rm`, an agent's
393
+ * rename), and writing would silently resurrect it. Without a baseline
394
+ * the caller is creating the file and has nothing to compare.
395
+ */
396
+ if (guard !== undefined && guard.expectMtime !== undefined) {
397
+ const changed = target.mtime === undefined
398
+ || target.mtime !== guard.expectMtime
399
+ || (guard.expectSize !== undefined && target.size !== guard.expectSize)
400
+ if (changed) throw new WriteConflictError(target.realPath, target.mtime ?? null, target.size ?? null)
401
+ }
402
+ const dir = posix.dirname(target.realPath)
403
+ partial = partialPathOf(target.realPath)
404
+ this.trackPartial(alias, partial)
266
405
  await this.withDirRetry(alias, dir, async () => {
267
406
  await this.ensureDir(sftp, alias, dir)
268
407
  // A zero-length SFTP WRITE packet is not universally accepted (SFTPv3
269
408
  // leaves it undefined); an empty file is created by opening for
270
409
  // truncation and closing again.
271
- if (data.length === 0) await touchFile(sftp, path)
272
- else await writeFileAsync(sftp, path, data)
410
+ if (data.length === 0) await touchFile(sftp, partial as string)
411
+ else await writeFileAsync(sftp, partial as string, data)
273
412
  })
413
+ replacing = true
414
+ await replaceFile(sftp, partial, target.realPath)
415
+ // The side file is now the target: it must never be swept by name again.
416
+ this.forgetPartial(alias, partial)
417
+ if (target.mode !== undefined) {
418
+ // Best effort: the content is already in place, so a refused setstat
419
+ // must not turn a successful save into a reported failure.
420
+ await setstatAsync(sftp, target.realPath, { mode: target.mode }).catch(() => {
421
+ console.warn(`[dsh-remote-vs] saved ${target.realPath} but could not restore its mode`)
422
+ })
423
+ }
424
+ // Read the version back: the caller stores it as the NEXT save's
425
+ // baseline. A failure here is not a save failure (the bytes landed), so
426
+ // it downgrades to `null` — an unguarded next save — rather than
427
+ // pretending a timestamp. `size` comes from the SAME stat as `mtime`:
428
+ // reporting `data.length` next to a stat-derived mtime would let the two
429
+ // halves of one baseline describe two different moments.
430
+ const after = await lstatAsync(sftp, target.realPath).catch(() => undefined)
431
+ if (after !== undefined) {
432
+ mtime = after.mtime * 1000
433
+ writtenSize = after.size
434
+ }
435
+ this.remember(this.knownDirs, dirKey(alias, posix.dirname(path)))
436
+ await this.sweepOrphanDirs(sftp, alias, dir)
274
437
  } catch (error) {
438
+ // The conflict must reach the route with its own fields: neither the
439
+ // partial-sweep path nor `explainSftpFailure` may relabel it (the
440
+ // target may legitimately be absent, which that helper words as
441
+ // "no such file").
442
+ if (error instanceof WriteConflictError) throw error
443
+ if (partial !== undefined) await this.discardPartial(sftp, alias, partial)
444
+ // A failure after the swap started carries the real reason (a rename
445
+ // status, a permission error). `explainSftpFailure` would relabel it "no
446
+ // such file" because the target can legitimately be absent mid-swap —
447
+ // exactly the misleading message this path used to produce.
448
+ if (replacing) throw error
275
449
  // Wrapped OUTSIDE the retry: withDirRetry keys off `error.code`, so
276
450
  // translating any earlier would break its re-create-the-directory path.
277
451
  throw (await explainSftpFailure(sftp, path, 'file', error)) ?? error
452
+ } finally {
453
+ if (partial !== undefined) this.activePartials.delete(dirKey(alias, partial))
278
454
  }
279
- return { size: data.length }
455
+ return { size: writtenSize, mtime }
280
456
  })
281
457
  }
282
458
 
@@ -289,12 +465,13 @@ export class RemoteFiles {
289
465
  * first — a drop can name a path several levels below the target — and the
290
466
  * source is piped straight into the SFTP write stream.
291
467
  *
292
- * The bytes go to a SIDE file (`.part-<id>` next to the target) and are
293
- * renamed into place only once the body ended cleanly. Writing the real path
468
+ * The bytes go to a SIDE file (`.dsh-rvs.part-<8 hex>` next to the target) and
469
+ * are renamed into place only once the body ended cleanly. Writing the real path
294
470
  * directly left a half file behind whenever the upload was cancelled, which
295
471
  * then looked like a complete file in the explorer (2026-10-20 user report).
296
- * On any failure the side file is removed, so a cancelled upload leaves the
297
- * remote folder exactly as it was.
472
+ * A cancelled upload removes its side file; when the CONNECTION is what failed
473
+ * the unlink cannot run, so the directory is recorded and the next successful
474
+ * write into it sweeps the orphan (see `sweepOrphanDirs`).
298
475
  *
299
476
  * @param alias - host alias.
300
477
  * @param file - absolute remote destination path.
@@ -312,7 +489,7 @@ export class RemoteFiles {
312
489
  ): Promise<{ size: number }> {
313
490
  const path = remotePath(file)
314
491
  const dir = posix.dirname(path)
315
- const partial = `${path}.part-${randomBytes(4).toString('hex')}`
492
+ const partial = partialPathOf(path)
316
493
  // No wall-clock deadline: a large body on a slow upload link is healthy for
317
494
  // minutes; `streamIntoFile` bounds a dead transfer by progress instead
318
495
  // (the old 60 s wrapper turned a healthy 64 MiB upload into a timeout).
@@ -321,17 +498,23 @@ export class RemoteFiles {
321
498
  await this.withDirRetry(alias, dir, async () => {
322
499
  await this.ensureDir(sftp, alias, dir)
323
500
  })
501
+ this.trackPartial(alias, partial)
324
502
  const size = await streamIntoFile(sftp, partial, source, maxBytes)
325
503
  // Move into place. SFTP v3 `rename` refuses to clobber, so an overwrite
326
504
  // removes the old file first — the same window a normal editor save has.
327
505
  if (overwrite) await unlinkAsync(sftp, path).catch(() => undefined)
328
506
  await renameAsync(sftp, partial, path)
507
+ this.forgetPartial(alias, partial)
329
508
  this.remember(this.knownDirs, dirKey(alias, dir))
509
+ await this.sweepOrphanDirs(sftp, alias, dir)
330
510
  return { size }
331
511
  } catch (error) {
332
- // Never leave the side file: a cancelled upload must be invisible.
333
- await unlinkAsync(sftp, partial).catch(() => undefined)
512
+ // Never leave the side file (and when the connection is what failed,
513
+ // record its directory so the next write there sweeps it).
514
+ await this.discardPartial(sftp, alias, partial)
334
515
  throw (await explainSftpFailure(sftp, path, 'file', error)) ?? error
516
+ } finally {
517
+ this.activePartials.delete(dirKey(alias, partial))
335
518
  }
336
519
  }, { timeoutMs: 0 })
337
520
  }
@@ -550,6 +733,110 @@ export class RemoteFiles {
550
733
  }
551
734
  }
552
735
 
736
+ /**
737
+ * Remove a side file, remembering its directory when that is impossible.
738
+ *
739
+ * The only failure that leaves a side file behind is the failure it was
740
+ * cleaning up after: with the connection dead, `unlink` cannot run either.
741
+ * Recording the directory lets the NEXT successful write into it sweep the
742
+ * orphan — otherwise it stays in the remote directory forever, looking like a
743
+ * file the user created.
744
+ */
745
+ private async discardPartial(sftp: SFTPWrapper, alias: string, partial: string): Promise<void> {
746
+ try {
747
+ await unlinkAsync(sftp, partial)
748
+ this.forgetPartial(alias, partial)
749
+ } catch {
750
+ // Still ours, still unremovable: keep the exact name on the owned list so
751
+ // the next sweep in this directory may retry it — and only it.
752
+ this.rememberOwned(dirKey(alias, partial))
753
+ this.markOrphanDir(alias, posix.dirname(partial))
754
+ }
755
+ }
756
+
757
+ /** Register one side file as ours: in flight now, and sweepable after it fails. */
758
+ private trackPartial(alias: string, partial: string): void {
759
+ this.activePartials.add(dirKey(alias, partial))
760
+ this.rememberOwned(dirKey(alias, partial))
761
+ }
762
+
763
+ /** Add one owned side-file key, evicting the oldest when the set is full. */
764
+ private rememberOwned(key: string): void {
765
+ if (!this.ownedPartials.has(key) && this.ownedPartials.size >= MEMO_CAP) {
766
+ const oldest = this.ownedPartials.values().next().value
767
+ if (oldest !== undefined) this.ownedPartials.delete(oldest)
768
+ }
769
+ this.ownedPartials.add(key)
770
+ }
771
+
772
+ /** The side file reached its target (or was removed): no longer ours to sweep. */
773
+ private forgetPartial(alias: string, partial: string): void {
774
+ this.ownedPartials.delete(dirKey(alias, partial))
775
+ }
776
+
777
+ private markOrphanDir(alias: string, dir: string): void {
778
+ const dirs = this.orphanDirs.get(alias) ?? new Set<string>()
779
+ if (dirs.size >= MEMO_CAP) return
780
+ dirs.add(dir)
781
+ this.orphanDirs.set(alias, dirs)
782
+ }
783
+
784
+ /**
785
+ * Remove the side files THIS process left behind in `dir`.
786
+ *
787
+ * Runs after a SUCCESSFUL write/upload into a directory that recorded an
788
+ * orphan, so the healthy path pays nothing. Two independent locks keep it off
789
+ * anything the user owns:
790
+ *
791
+ * 1. the name must match the plugin's reserved shape (`.dsh-rvs.part-<8 hex>`);
792
+ * 2. the exact path must be in `ownedPartials` — a set only `trackPartial`
793
+ * writes, i.e. a file this process itself created.
794
+ *
795
+ * The shape alone would still be a guess (the audit's P2-N1: a user file
796
+ * `foo.part-deadbeef` was deleted after the age bound), so the ownership check
797
+ * is the load-bearing one. A leftover from a PREVIOUS Host process carries the
798
+ * shape but is not owned, and is therefore never deleted either — including a
799
+ * side file left by a pre-marker release (`.part-<8 hex>`, which does not even
800
+ * match the current shape). Junk that stays is recoverable; a deleted user
801
+ * file is not.
802
+ *
803
+ * A sweep failure is never the caller's problem: the record simply survives
804
+ * for the next write.
805
+ */
806
+ private async sweepOrphanDirs(sftp: SFTPWrapper, alias: string, dir: string): Promise<void> {
807
+ const dirs = this.orphanDirs.get(alias)
808
+ if (dirs === undefined || !dirs.has(dir)) return
809
+ let rows: ReaddirRow[]
810
+ try {
811
+ rows = await readdirAsync(sftp, dir)
812
+ } catch {
813
+ return
814
+ }
815
+ let swept = 0
816
+ let failed = false
817
+ for (const row of rows) {
818
+ if (!PART_NAME_RE.test(row.filename)) continue
819
+ const path = posix.join(dir, row.filename)
820
+ const key = dirKey(alias, path)
821
+ // The ONLY names a sweep may delete are ones this process created.
822
+ if (!this.ownedPartials.has(key)) continue
823
+ if (this.activePartials.has(key)) continue
824
+ if (swept >= PART_SWEEP_MAX_PER_DIR) {
825
+ failed = true
826
+ break
827
+ }
828
+ try {
829
+ await unlinkAsync(sftp, path)
830
+ this.ownedPartials.delete(key)
831
+ swept += 1
832
+ } catch {
833
+ failed = true
834
+ }
835
+ }
836
+ if (!failed) dirs.delete(dir)
837
+ if (dirs.size === 0) this.orphanDirs.delete(alias)
838
+ }
839
+
553
840
  /** Add one key to a bounded set, evicting the oldest entry when full. */
554
841
  private remember(memo: Set<string>, key: string): void {
555
842
  if (memo.size >= MEMO_CAP) {
@@ -581,6 +868,17 @@ function dirKey(alias: string, path: string): string {
581
868
  return `${alias}\u0000${path}`
582
869
  }
583
870
 
871
+ /**
872
+ * Name of the side file a save/upload of `path` writes through.
873
+ *
874
+ * The reserved segment is what makes the name recognisably the plugin's (see
875
+ * `PART_MARKER`); the 4 random bytes keep two concurrent operations on one
876
+ * target apart.
877
+ */
878
+ function partialPathOf(path: string): string {
879
+ return `${path}${PART_MARKER}${randomBytes(4).toString('hex')}`
880
+ }
881
+
584
882
  function isSymlink(mode: number): boolean {
585
883
  return (mode & S_IFMT) === S_IFLNK
586
884
  }
@@ -745,7 +1043,10 @@ async function readHandleFully(sftp: SFTPWrapper, handle: Buffer, buffer: Buffer
745
1043
  * (`index % channels.length`) so the in-flight bytes are spread across the SSH
746
1044
  * channel windows instead of queueing behind one 2 MiB window. A closed response
747
1045
  * (user cancel) resolves quietly — the route treats that as a cancellation, not
748
- * an error — and a no-progress watchdog fails a silently dead transfer.
1046
+ * an error — and a no-progress watchdog fails a silently dead transfer. Every
1047
+ * suspension point (slot, chunk, and the writer's `drain` wait) is released by
1048
+ * that close as well, so the caller's `finally` — handles, sessions, slots —
1049
+ * always runs.
749
1050
  */
750
1051
  async function pipeChannelsToResponse(
751
1052
  channels: Array<{ sftp: SFTPWrapper; handle: Buffer }>,
@@ -758,6 +1059,7 @@ async function pipeChannelsToResponse(
758
1059
  const ready = new Map<number, Buffer>()
759
1060
  const chunkWaiters = new Map<number, () => void>()
760
1061
  const slotWaiters: Array<() => void> = []
1062
+ const drainWaiters: Array<() => void> = []
761
1063
  let slots = windowChunks
762
1064
  let nextRead = 0
763
1065
  let cancelled = false
@@ -771,6 +1073,18 @@ async function pipeChannelsToResponse(
771
1073
  for (const wake of chunkWaiters.values()) wake()
772
1074
  chunkWaiters.clear()
773
1075
  }
1076
+ /**
1077
+ * Wake the ordered writer when the response ends underneath it.
1078
+ *
1079
+ * A destroyed response never emits `drain` again, so a `waitDrain()` that only
1080
+ * listens for `drain` would park the writer forever — and with it the
1081
+ * `finally` that closes the handles, the sessions and the pool's channel slots
1082
+ * (a cancelled download used to leak both channels until the Host restarted).
1083
+ * `close` and a transfer-level failure therefore have to release the same wait.
1084
+ */
1085
+ const wakeDrain = (): void => {
1086
+ for (const wake of drainWaiters.splice(0)) wake()
1087
+ }
774
1088
  const signalChunk = (index: number): void => {
775
1089
  const wake = chunkWaiters.get(index)
776
1090
  if (wake !== undefined) {
@@ -783,6 +1097,7 @@ async function pipeChannelsToResponse(
783
1097
  failure = error instanceof Error ? error : new Error(String(error))
784
1098
  wakeSlots()
785
1099
  wakeChunks()
1100
+ wakeDrain()
786
1101
  }
787
1102
  const acquire = async (): Promise<void> => {
788
1103
  while (slots <= 0) await new Promise<void>(resolve => slotWaiters.push(resolve))
@@ -852,17 +1167,29 @@ async function pipeChannelsToResponse(
852
1167
  })
853
1168
  const waitDrain = (): Promise<void> =>
854
1169
  new Promise<void>((resolve) => {
855
- if (cancelled || failure !== undefined) {
1170
+ if (cancelled || failure !== undefined || res.destroyed) {
856
1171
  resolve()
857
1172
  return
858
1173
  }
859
- res.once('drain', resolve)
1174
+ const done = (): void => {
1175
+ const at = drainWaiters.indexOf(done)
1176
+ if (at >= 0) drainWaiters.splice(at, 1)
1177
+ res.removeListener('drain', done)
1178
+ res.removeListener('close', done)
1179
+ resolve()
1180
+ }
1181
+ // `drain` is the normal release; `close` is what a cancelled download
1182
+ // looks like, because a destroyed response never drains.
1183
+ drainWaiters.push(done)
1184
+ res.once('drain', done)
1185
+ res.once('close', done)
860
1186
  })
861
1187
  const onResponseClose = (): void => {
862
1188
  if (res.writableEnded) return
863
1189
  cancelled = true
864
1190
  wakeSlots()
865
1191
  wakeChunks()
1192
+ wakeDrain()
866
1193
  }
867
1194
  res.on('close', onResponseClose)
868
1195
  const idle = setInterval(() => {
@@ -903,6 +1230,7 @@ async function pipeChannelsToResponse(
903
1230
  cancelled = true
904
1231
  wakeSlots()
905
1232
  wakeChunks()
1233
+ wakeDrain()
906
1234
  await Promise.race([drained, new Promise<void>((resolve) => setTimeout(resolve, 250))])
907
1235
  } else {
908
1236
  await drained
@@ -1282,3 +1610,135 @@ async function removeTree(sftp: SFTPWrapper, dir: string): Promise<void> {
1282
1610
  }
1283
1611
  await rmdirAsync(sftp, dir)
1284
1612
  }
1613
+
1614
+ // ------------------------------------------------------ atomic save internals
1615
+
1616
+ /** Symlink hops a save is willing to follow before giving up. */
1617
+ const MAX_LINK_HOPS = 8
1618
+
1619
+ function readlinkAsync(sftp: SFTPWrapper, path: string): Promise<string> {
1620
+ return new Promise((resolve, reject) => {
1621
+ sftp.readlink(path, (error, linkPath) => {
1622
+ if (error !== undefined && error !== null) reject(error)
1623
+ else resolve(linkPath)
1624
+ })
1625
+ })
1626
+ }
1627
+
1628
+ function setstatAsync(sftp: SFTPWrapper, path: string, attrs: { mode: number }): Promise<void> {
1629
+ return new Promise((resolve, reject) => {
1630
+ sftp.setstat(path, attrs, (error) => {
1631
+ if (error !== undefined && error !== null) reject(error)
1632
+ else resolve()
1633
+ })
1634
+ })
1635
+ }
1636
+
1637
+ /**
1638
+ * Resolve what a save must really write, following symbolic links.
1639
+ *
1640
+ * Writing a fresh inode over the path would replace the LINK with a regular file;
1641
+ * the base implementation wrote through the link (`writeFile` follows it), so
1642
+ * following it here keeps that meaning. The returned path is also where the side
1643
+ * file has to live: `rename` only stays inside one directory.
1644
+ *
1645
+ * A missing final target is not an error — saving through a dangling link (or
1646
+ * creating a new file) writes the target, exactly like `open('w')` did.
1647
+ */
1648
+ async function resolveWriteTarget(
1649
+ sftp: SFTPWrapper,
1650
+ path: string,
1651
+ ): Promise<{ realPath: string; mode: number | undefined; size: number | undefined; mtime: number | undefined }> {
1652
+ let current = path
1653
+ for (let hop = 0; hop <= MAX_LINK_HOPS; hop += 1) {
1654
+ let attrs: Stats
1655
+ try {
1656
+ attrs = await lstatAsync(sftp, current)
1657
+ } catch (error) {
1658
+ // A missing final target is not an error by itself (the save may be
1659
+ // creating the file); the VERSION is simply unknown, which is what the
1660
+ // save-conflict guard reads as "there was nothing to be based on".
1661
+ if ((error as { code?: number }).code === SFTP_NO_SUCH_FILE) {
1662
+ return { realPath: current, mode: undefined, size: undefined, mtime: undefined }
1663
+ }
1664
+ throw error
1665
+ }
1666
+ if (isSymlink(attrs.mode)) {
1667
+ // A relative link is relative to the LINK's own directory, not to the path
1668
+ // the caller used.
1669
+ current = posix.resolve(posix.dirname(current), await readlinkAsync(sftp, current))
1670
+ continue
1671
+ }
1672
+ if (isDir(attrs.mode)) throw new Error(`not a file: ${current} is a directory`)
1673
+ // mtime/size are the save guard's baseline: they must come from the SAME
1674
+ // stat that decides whether this path is writable, or the guard would check
1675
+ // a version that this call never looked at.
1676
+ return { realPath: current, mode: attrs.mode & 0o777, size: attrs.size, mtime: attrs.mtime * 1000 }
1677
+ }
1678
+ throw new Error(`too many symbolic links: ${path}`)
1679
+ }
1680
+
1681
+ /**
1682
+ * One atomic replace through OpenSSH's `posix-rename@openssh.com` extension.
1683
+ *
1684
+ * @returns true when the server swapped the names in one step, false when it did
1685
+ * not advertise the extension — the only case the caller has to fall back for.
1686
+ */
1687
+ function posixRename(sftp: SFTPWrapper, from: string, to: string): Promise<boolean> {
1688
+ return new Promise<boolean>((resolve, reject) => {
1689
+ if (typeof sftp.ext_openssh_rename !== 'function') {
1690
+ resolve(false)
1691
+ return
1692
+ }
1693
+ try {
1694
+ sftp.ext_openssh_rename(from, to, (error) => {
1695
+ if (error === undefined || error === null) resolve(true)
1696
+ // The server advertised the extension and still refused: a real failure,
1697
+ // not a reason to fall back (the fallback is not more likely to work).
1698
+ else reject(error)
1699
+ })
1700
+ } catch (error) {
1701
+ // ssh2 throws synchronously when the server did not advertise the
1702
+ // extension; that message is the documented "fall back" signal.
1703
+ if (/does not support this extended request/i.test(error instanceof Error ? error.message : String(error))) {
1704
+ resolve(false)
1705
+ return
1706
+ }
1707
+ reject(error instanceof Error ? error : new Error(String(error)))
1708
+ }
1709
+ })
1710
+ }
1711
+
1712
+ /**
1713
+ * Move a finished side file onto its target without ever deleting the target
1714
+ * before the replacement is in place.
1715
+ *
1716
+ * Atomic path: `posix-rename` (server-side name swap, no window at all).
1717
+ * Fallback: move the target aside, move the side file in, and swap the backup
1718
+ * back if that second rename fails — so the previous bytes exist at every moment
1719
+ * of the sequence. The failure keeps the REAL error: the old unlink-first code
1720
+ * reported `no such file` because it had already deleted the target by the time
1721
+ * the rename failed.
1722
+ *
1723
+ * The backup name carries 4 random bytes, so a leftover from a crash can never
1724
+ * collide with the next save's backup.
1725
+ */
1726
+ async function replaceFile(sftp: SFTPWrapper, partial: string, target: string): Promise<void> {
1727
+ if (await posixRename(sftp, partial, target)) return
1728
+ const backup = `${target}.bak-${randomBytes(4).toString('hex')}`
1729
+ let hasBackup = false
1730
+ try {
1731
+ await renameAsync(sftp, target, backup)
1732
+ hasBackup = true
1733
+ } catch (error) {
1734
+ // No target yet (a new file): nothing to preserve.
1735
+ if ((error as { code?: number }).code !== SFTP_NO_SUCH_FILE) throw error
1736
+ }
1737
+ try {
1738
+ await renameAsync(sftp, partial, target)
1739
+ } catch (error) {
1740
+ if (hasBackup) await renameAsync(sftp, backup, target).catch(() => undefined)
1741
+ throw error
1742
+ }
1743
+ if (hasBackup) await unlinkAsync(sftp, backup).catch(() => undefined)
1744
+ }