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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-remote-vs",
3
3
  "description": "VSCode-style remote development for DSH: SSH host manager (key/password), helper deploy pipeline with version check, remote file explorer + editor + terminal in dsh-better-sidebar.",
4
- "version": "0.13.0",
4
+ "version": "0.15.1",
5
5
  "icon": "icon.svg",
6
6
  "keywords": [
7
7
  "dsh",
package/src/archive.ts CHANGED
@@ -11,14 +11,50 @@ import { posix } from 'node:path'
11
11
  import { shQuote } from './git-format.ts'
12
12
  import { MAX_SELECTION_DOWNLOAD } from './protocol.ts'
13
13
 
14
- /** Download file name for one archived directory. */
14
+ /**
15
+ * Best-effort normal form of one remote path, shared by the guard, the command
16
+ * and the download NAME.
17
+ *
18
+ * The name used to take its basename from the RAW string while the command
19
+ * normalized: `/a/b/..` archived `/a` but was saved as `...tar.gz`. One
20
+ * normalization for both is the only way the file name can be trusted to name
21
+ * what is inside.
22
+ */
23
+ function normalizeArchivePath(raw: string): string {
24
+ return posix.normalize(String(raw).replace(/\\/g, '/')).replace(/\/+$/, '')
25
+ }
26
+
27
+ /** Download file name for one archived directory (normalized like the command). */
15
28
  export function directoryArchiveName(dir: string): string {
16
- const trimmed = String(dir).replace(/[\\/]+$/, '')
17
- const at = Math.max(trimmed.lastIndexOf('/'), trimmed.lastIndexOf('\\'))
29
+ const trimmed = normalizeArchivePath(dir)
30
+ const at = trimmed.lastIndexOf('/')
18
31
  const base = at < 0 ? trimmed : trimmed.slice(at + 1)
19
32
  return `${base === '' ? 'root' : base}.tar.gz`
20
33
  }
21
34
 
35
+ /**
36
+ * Normalize one remote path into the exact string the tar command will use.
37
+ *
38
+ * The normalization has to live HERE, not only in the caller: `files.stat()`
39
+ * normalizes internally (`remotePath()`), so a raw `/..` passed the "is it a
40
+ * directory" check and still reached the builder un-normalized — `-C '/' './..'`
41
+ * then archived the whole remote root, which is exactly what the guard is
42
+ * supposed to refuse. Guard and command therefore have to be derived from the
43
+ * SAME value; a character-class check on the raw string cannot do it.
44
+ *
45
+ * `/a/b/..` → `/a`: climbing down to a real directory is a legitimate target,
46
+ * only the root itself (and anything relative) is refused.
47
+ */
48
+ function archivePath(raw: string): string {
49
+ const path = normalizeArchivePath(raw)
50
+ if (path === '' || path === '/') throw new Error('refusing to archive the remote root')
51
+ if (!path.startsWith('/')) throw new Error('remote path must be absolute')
52
+ // Defense in depth: normalize() resolves every `..` in an absolute path, so
53
+ // this only fires on a shape it did not understand — never accept such a path.
54
+ if (path.split('/').includes('..')) throw new Error('path must not contain ..')
55
+ return path
56
+ }
57
+
22
58
  /**
23
59
  * One POSIX shell command that writes the directory's gzip tar to stdout.
24
60
  *
@@ -28,9 +64,7 @@ export function directoryArchiveName(dir: string): string {
28
64
  * quotes and `$()` in a real path cannot escape into the command.
29
65
  */
30
66
  export function directoryArchiveCommand(dir: string): string {
31
- const path = String(dir).replace(/\\/g, '/').replace(/\/+$/, '')
32
- if (path === '' || path === '/') throw new Error('refusing to archive the remote root')
33
- if (!path.startsWith('/')) throw new Error('remote path must be absolute')
67
+ const path = archivePath(dir)
34
68
  const parent = posix.dirname(path)
35
69
  const name = posix.basename(path)
36
70
  return `tar -czf - -C ${shQuote(parent)} ${shQuote(`./${name}`)}`
@@ -51,9 +85,7 @@ export function selectionArchiveCommand(paths: readonly string[]): string {
51
85
  if (paths.length > MAX_SELECTION_DOWNLOAD) throw new Error(`too many entries: ${paths.length} (max ${MAX_SELECTION_DOWNLOAD})`)
52
86
  let command = 'tar -czf -'
53
87
  for (const raw of paths) {
54
- const path = String(raw).replace(/\\/g, '/').replace(/\/+$/, '')
55
- if (path === '' || path === '/') throw new Error('refusing to archive the remote root')
56
- if (!path.startsWith('/')) throw new Error('remote path must be absolute')
88
+ const path = archivePath(raw)
57
89
  command += ` -C ${shQuote(posix.dirname(path))} ${shQuote(`./${posix.basename(path)}`)}`
58
90
  }
59
91
  return command
@@ -110,6 +110,19 @@ interface FileRecord {
110
110
  after: string | null
111
111
  binary: boolean
112
112
  truncated: boolean
113
+ /**
114
+ * Whether {@link SessionChanges.diff} may hand out a real reverse patch.
115
+ *
116
+ * A record with no old side is a whole-file creation, and the only reverse of
117
+ * its patch is deleting the file. That is recoverable when git holds the
118
+ * content (a tracked addition — the index still has it) and unrecoverable when
119
+ * it does not: an untracked file exists only in the worktree, so a revert
120
+ * would destroy its single copy. A missing old side (a failed read) is not
121
+ * evidence either, and a creation patch built from missing evidence is a
122
+ * guess. Both cases are still served for display; only the patch is withheld,
123
+ * which makes the client's undo path fail closed instead of deleting.
124
+ */
125
+ undoable: boolean
113
126
  }
114
127
 
115
128
  /** Grace added to an exec budget before the watchdog gives up on it. */
@@ -120,20 +133,39 @@ const WATCHDOG_FIRED = 'watchdog-fired' as const
120
133
  /** One session's bookkeeping. */
121
134
  interface Ledger {
122
135
  sessionId: string
136
+ /** Session working directory this ledger is CURRENTLY bound to (see `ensure`). */
137
+ cwd: string
138
+ /** Remote route (binding) id the ledger is bound to; a different one = rebind. */
139
+ routeId: string
123
140
  alias: string
124
141
  root: string
125
142
  /** Content of every path that was ALREADY dirty when the session began. */
126
143
  baseline: Map<string, ReadResult> | undefined
127
144
  baselineTaken: boolean
128
- /** Set once the untracked scan proves unusable on this host; stops retrying it. */
145
+ /** Set once the untracked scan proves unusable for THIS root; stops retrying it. */
129
146
  untrackedGivenUp: boolean
130
- /** Wall-clock ms this ledger appeared: the session's own start for mtime tests. */
147
+ /**
148
+ * Why the untracked scan was written off, kept so the panel can SAY so.
149
+ *
150
+ * Capability loss without a reason reads as "this session changed nothing new",
151
+ * which is the opposite of the truth: the walk that finds new files is off. This
152
+ * is sticky (a later successful tracked scan must not hide it) and only cleared
153
+ * by a successful walk or by moving the root (`resetObservation`).
154
+ */
155
+ untrackedFailure: string | undefined
156
+ /**
157
+ * Wall-clock ms when observation of the CURRENT root started.
158
+ *
159
+ * The baseline's "was this file here before?" test compares file mtimes against
160
+ * it, so it must move with the root (`resetObservation`) — a file that appeared
161
+ * before we started looking at this tree is pre-existing by definition.
162
+ */
131
163
  startedAt: number
132
164
  /** True once the first untracked result has been folded into the baseline. */
133
165
  absorbed: boolean
134
166
  /** True once a repository below the session root has been looked for. */
135
167
  adoptedSubdir: boolean
136
- /** The session root as first resolved;
168
+ /** The session root as first resolved; root may be this plus subdir. */
137
169
  baseRoot: string
138
170
  /** Explicit repository directory inside the root ('' = the root itself). */
139
171
  subdir: string
@@ -160,6 +192,17 @@ interface Ledger {
160
192
  /** Serialized background work; a second schedule coalesces into one run. */
161
193
  queue: Promise<void>
162
194
  dirty: boolean
195
+ /**
196
+ * Monotonic publish ledger: only the LATEST started publish may write.
197
+ *
198
+ * Two publishes can be in flight at once by design (the queued `refresh` and the
199
+ * background untracked job, which runs outside the queue), each holding a
200
+ * snapshot taken before its own awaits. Without this, the one that finishes last
201
+ * wins with the OLDER data — rows vanish/reappear and counts flop for a scan.
202
+ * Deliberately NOT reset by `resetObservation`: it orders writes, it is not an
203
+ * observation of a root (the root guard already covers identity).
204
+ */
205
+ publishSeq: number
163
206
  disposed: boolean
164
207
  }
165
208
 
@@ -219,6 +262,21 @@ export class SessionChanges {
219
262
  summary(sessionId: string): RemoteChangesSummary | null {
220
263
  const ledger = this.ledgers.get(sessionId)
221
264
  if (ledger === undefined) return null
265
+ /*
266
+ * Why "unavailable" has two sources.
267
+ *
268
+ * The tracked scan explains itself through `ledger.unavailable`. A written-off
269
+ * untracked walk has no such channel — it permanently removes the "new files"
270
+ * column, and silence there reads as "this session changed nothing new". So the
271
+ * sticky `untrackedFailure` is folded in here, with the one action that can
272
+ * recover it. The explicit reason wins: a successful tracked scan clears
273
+ * `ledger.unavailable` every turn, while `untrackedFailure` survives until a
274
+ * walk succeeds or the root moves.
275
+ */
276
+ const unavailable = ledger.unavailable
277
+ ?? (ledger.untrackedFailure === undefined
278
+ ? undefined
279
+ : `new-file scan unavailable: ${ledger.untrackedFailure} (use the refresh button to retry)`)
222
280
  return {
223
281
  alias: ledger.alias,
224
282
  root: ledger.root,
@@ -243,7 +301,7 @@ export class SessionChanges {
243
301
  */
244
302
  pending: ledger.untrackedJob !== undefined || (ledger.pending && ledger.files.length > 0),
245
303
  ...(ledger.truncated === true ? { truncated: true as const } : {}),
246
- ...(ledger.unavailable === undefined ? {} : { unavailable: ledger.unavailable }),
304
+ ...(unavailable === undefined ? {} : { unavailable }),
247
305
  }
248
306
  }
249
307
 
@@ -292,8 +350,12 @@ export class SessionChanges {
292
350
  heading: '',
293
351
  lines: hunk.lines,
294
352
  // The client hands this straight to `git apply -R` for "revert this
295
- // change", so it must be a real patch, not a display artifact.
296
- patch: hunkPatch(record.display, hunk),
353
+ // change", so it must be a real patch, not a display artifact. Empty
354
+ // means "display only": the client's undo path refuses an empty patch
355
+ // (`changes.undoMissing`), which is the fail-closed answer for a record
356
+ // whose reverse would delete a file git has no copy of (see
357
+ // `FileRecord.undoable`).
358
+ patch: record.undoable ? hunkPatch(record.display, hunk) : '',
297
359
  }))
298
360
  if (hunks.length === 0) {
299
361
  return { kind: 'missing', path, display: record.display, hunks: [], ...(status === undefined ? {} : { status }) }
@@ -348,7 +410,16 @@ export class SessionChanges {
348
410
  rescan(sessionId: string): void {
349
411
  const ledger = this.ledgers.get(sessionId)
350
412
  if (ledger === undefined || ledger.disposed) return
413
+ // An explicit refresh means "try again": the write-off verdict describes the
414
+ // previous attempt, not the session, so the button must be able to clear it.
415
+ // Automatic polls (`touch`) deliberately keep it — retrying a minute-long
416
+ // walk on every 30s self-heal is exactly what the write-off prevents.
417
+ if (ledger.untrackedGivenUp) {
418
+ ledger.untrackedGivenUp = false
419
+ this.warn('manual refresh re-arms the untracked scan for this session')
420
+ }
351
421
  ledger.untrackedAt = 0
422
+ ledger.untrackedMs = undefined
352
423
  this.schedule(ledger)
353
424
  }
354
425
 
@@ -389,48 +460,115 @@ export class SessionChanges {
389
460
  if (clean === ledger.subdir) return
390
461
  ledger.subdir = clean
391
462
  ledger.root = clean === '' ? ledger.baseRoot : `${ledger.baseRoot}/${clean}`
392
- // The baseline describes the previous root; it means nothing for this one.
463
+ this.resetObservation(ledger)
464
+ this.schedule(ledger)
465
+ }
466
+
467
+ /**
468
+ * Forget everything observed against the ledger's previous root.
469
+ *
470
+ * The root is the subject of every fact this ledger holds: the baseline
471
+ * describes that tree, both scans name paths relative to it, and the flags
472
+ * that gate them (`absorbed`, `untrackedGivenUp`) are verdicts about that
473
+ * repository. Moving the root therefore makes the whole observation set
474
+ * meaningless at once — resetting only the ones a caller happened to remember
475
+ * is how the first cut of `useRepoSubdir` forgot `untracked` and `absorbed`,
476
+ * which announced the newly selected repository's PRE-EXISTING untracked
477
+ * files as this session's work (full-file additions, revertible — and a
478
+ * revert of an untracked file destroys a copy git never had).
479
+ *
480
+ * One entry point on purpose: a field added later belongs here by default,
481
+ * instead of needing every root-move path to be found again.
482
+ */
483
+ private resetObservation(ledger: Ledger): void {
393
484
  ledger.baseline = undefined
394
485
  ledger.baselineTaken = false
486
+ ledger.absorbed = false
395
487
  ledger.adoptedSubdir = false
488
+ ledger.tracked = []
489
+ ledger.untracked = undefined
490
+ ledger.untrackedAt = 0
491
+ ledger.untrackedMs = undefined
492
+ ledger.untrackedGivenUp = false
493
+ ledger.untrackedFailure = undefined
396
494
  ledger.files = []
397
495
  ledger.records = new Map()
398
496
  ledger.added = 0
399
497
  ledger.deleted = 0
498
+ ledger.truncated = undefined
400
499
  ledger.at = 0
401
- this.schedule(ledger)
500
+ ledger.unavailable = undefined
501
+ // The mtime test in `absorbPreExisting` asks "did this file predate the
502
+ // observation of THIS tree?"; the previous root's clock would call files that
503
+ // appeared in the new one before the move "session work" (and list them with
504
+ // whole-file counts). Restart it with the rest of the observation.
505
+ ledger.startedAt = Date.now()
402
506
  }
403
507
 
404
508
  // ------------------------------------------------------------- internals
405
509
 
406
- /** Resolve the routing target once per session, caching the ledger. */
510
+ /**
511
+ * Resolve (or rebind) the ledger for one session from its CURRENT cwd.
512
+ *
513
+ * The cwd is re-resolved on every turn boundary instead of once per session: a
514
+ * session can change its working directory mid-conversation (a workspace
515
+ * switch, `working-directory.set`), and a ledger pinned to the first binding
516
+ * then keeps answering "what did this session change" about a tree the session
517
+ * is no longer working in — and points file-open and undo at it.
518
+ *
519
+ * Rebinding happens IN PLACE rather than forget+create: the panel keeps its
520
+ * identity and `turn` counter (no null-summary flicker) and one
521
+ * `resetObservation()` drops every fact that belonged to the previous root, so
522
+ * the field list stays in that one method. C1's root-snapshot guards in
523
+ * `refresh`/`publish`/`kickUntracked`/`absorbPreExisting` are exactly what makes
524
+ * this safe while a scan of the old root is still in flight.
525
+ */
407
526
  private ensure(target: LedgerTarget): Ledger | undefined {
408
527
  if (target.cwd.trim() === '') return undefined
409
- const existing = this.ledgers.get(target.sessionId)
410
- if (existing !== undefined && !existing.disposed && existing.root !== '') return existing
411
528
  let route: WorldRoute
412
529
  try {
413
530
  route = this.deps.worlds.routeDir(target.cwd)
414
531
  } catch {
532
+ // Tombstoned spelling (a removed mapping): fail closed AND stop serving a
533
+ // list for a workspace that no longer exists. Keeping the old ledger was
534
+ // the old behaviour and it kept a dead session looking alive.
535
+ this.forget(target.sessionId)
415
536
  return undefined
416
537
  }
417
538
  if (route.kind !== 'remote') {
418
539
  // Local sessions are already covered by DSH's own recorder, and this
419
540
  // panel is a remote-workspace feature: keeping no ledger is what makes it
420
541
  // stay hidden there instead of showing a permanently empty box.
421
- this.ledgers.delete(target.sessionId)
542
+ this.forget(target.sessionId)
422
543
  return undefined
423
544
  }
424
545
  const root = route.remotePath.length > 1 && route.remotePath.endsWith('/')
425
546
  ? route.remotePath.replace(/\/+$/, '')
426
547
  : route.remotePath
548
+ const existing = this.ledgers.get(target.sessionId)
549
+ if (existing !== undefined && !existing.disposed && existing.root !== '') {
550
+ existing.cwd = target.cwd
551
+ if (existing.routeId === route.id) return existing
552
+ // Same session, different binding: rebind in place.
553
+ this.warn(`session working directory moved to ${route.alias}:${root}; re-observing the new binding`)
554
+ existing.routeId = route.id
555
+ existing.alias = route.alias
556
+ existing.baseRoot = root
557
+ existing.subdir = ''
558
+ existing.root = root
559
+ this.resetObservation(existing)
560
+ return existing
561
+ }
427
562
  const ledger: Ledger = {
428
563
  sessionId: target.sessionId,
564
+ cwd: target.cwd,
565
+ routeId: route.id,
429
566
  alias: route.alias,
430
567
  root,
431
568
  baseline: undefined,
432
569
  baselineTaken: false,
433
570
  untrackedGivenUp: false,
571
+ untrackedFailure: undefined,
434
572
  startedAt: Date.now(),
435
573
  absorbed: false,
436
574
  adoptedSubdir: false,
@@ -452,6 +590,7 @@ export class SessionChanges {
452
590
  pending: false,
453
591
  queue: Promise.resolve(),
454
592
  dirty: false,
593
+ publishSeq: 0,
455
594
  disposed: false,
456
595
  }
457
596
  this.ledgers.set(target.sessionId, ledger)
@@ -489,9 +628,14 @@ export class SessionChanges {
489
628
  */
490
629
  private async refresh(ledger: Ledger): Promise<void> {
491
630
  if (ledger.disposed || ledger.root === '') return
492
- const tracked = await this.scanTracked(ledger)
493
- if (ledger.disposed || tracked === undefined) return
494
- ledger.tracked = tracked
631
+ const scanned = await this.scanTracked(ledger)
632
+ if (ledger.disposed || scanned === undefined) return
633
+ // The root may have moved while the scan was in flight (the user picked
634
+ // another repository directory). `scanTracked` reports the root its entries
635
+ // belong to, so a mismatch means someone else owns the observation now —
636
+ // publish nothing and let that caller's own refresh land.
637
+ if (ledger.root !== scanned.root) return
638
+ ledger.tracked = scanned.entries
495
639
  await this.publish(ledger)
496
640
  void this.kickUntracked(ledger)
497
641
  }
@@ -499,6 +643,13 @@ export class SessionChanges {
499
643
  /** Recompute the panel's list from the scans currently known. */
500
644
  private async publish(ledger: Ledger): Promise<void> {
501
645
  if (ledger.disposed) return
646
+ // Ordering ticket: see Ledger.publishSeq. Taken before the first await.
647
+ const seq = ++ledger.publishSeq
648
+ // The reads below are relative to the root at THIS moment. A root move while
649
+ // they are in flight (the user picked another repository directory) makes
650
+ // the answer mixed-root, so it must not reach the panel; the caller that
651
+ // moved the root has already queued its own refresh.
652
+ const root = ledger.root
502
653
  const merged = new Map<string, StatusEntry>()
503
654
  for (const entry of ledger.tracked) merged.set(entry.path, entry)
504
655
  for (const entry of ledger.untracked ?? []) {
@@ -512,8 +663,11 @@ export class SessionChanges {
512
663
  if (!ledger.baselineTaken) {
513
664
  // First observation: everything dirty RIGHT NOW predates this ledger, so
514
665
  // it becomes the baseline rather than a change to report.
515
- ledger.baseline = await this.readPaths(ledger, listed.map(entry => entry.path), 'worktree')
516
- if (ledger.disposed) return
666
+ const first = await this.readPaths(ledger, listed.map(entry => entry.path), 'worktree')
667
+ if (ledger.disposed || ledger.root !== root) return
668
+ // A newer publish already started: it owns the baseline now.
669
+ if (ledger.publishSeq !== seq) return
670
+ ledger.baseline = first
517
671
  ledger.baselineTaken = true
518
672
  ledger.files = []
519
673
  ledger.records = new Map()
@@ -531,7 +685,7 @@ export class SessionChanges {
531
685
  const fromHead = listed.filter(entry => !baseline.has(entry.path)).map(entry => entry.path)
532
686
  const head = fromHead.length === 0 ? new Map<string, ReadResult>() : await this.readPaths(ledger, fromHead, 'head')
533
687
  const after = await this.readPaths(ledger, listed.map(entry => entry.path), 'worktree')
534
- if (ledger.disposed) return
688
+ if (ledger.disposed || ledger.root !== root) return
535
689
 
536
690
  const records = new Map<string, FileRecord>()
537
691
  const files: RemoteChangedFile[] = []
@@ -556,6 +710,15 @@ export class SessionChanges {
556
710
  // sides means the session never wrote to it.
557
711
  if ((binary || fileTruncated) && sameStat(beforeSide, afterSide)) continue
558
712
  const oversized = fileTruncated && !binary
713
+ // No old side = whole-file creation, and the only reverse of its patch is
714
+ // deleting the file. git holds the content only for a TRACKED addition (the
715
+ // index has it); an untracked one exists nowhere else, and a "before side"
716
+ // that a failed read could not see is not evidence either. A reverse patch
717
+ // cannot express "un-add" anyway, so no creation is offered one — the hunk
718
+ // is still served for display (the client's undo path refuses an empty
719
+ // patch: `changes.undoMissing`).
720
+ const creation = before === null
721
+ const undoable = !binary && !oversized && beforeSide !== undefined && !creation
559
722
  const diff = binary || oversized ? { added: 0, deleted: 0 } : diffText(before ?? '', afterText ?? '')
560
723
  const status = panelStatus(entry.status)
561
724
  const absolute = posixJoin(ledger.root, entry.path)
@@ -567,6 +730,7 @@ export class SessionChanges {
567
730
  after: afterText,
568
731
  binary,
569
732
  truncated: fileTruncated,
733
+ undoable,
570
734
  })
571
735
  added += diff.added
572
736
  deleted += diff.deleted
@@ -581,6 +745,11 @@ export class SessionChanges {
581
745
  })
582
746
  }
583
747
  files.sort((left, right) => left.display.localeCompare(right.display))
748
+ // Last gates before the panel sees anything: `root` covers IDENTITY (the tree
749
+ // moved while we read), `publishSeq` covers ORDER (a later publish already
750
+ // wrote a newer list, and this older snapshot must not overwrite it).
751
+ if (ledger.root !== root) return
752
+ if (ledger.publishSeq !== seq) return
584
753
  ledger.records = records
585
754
  ledger.files = files
586
755
  ledger.added = added
@@ -606,14 +775,18 @@ export class SessionChanges {
606
775
  * ledger looks one level down once and adopts the repository it finds, which
607
776
  * is the same idea the SCM panel's `repoSubdir` expresses by hand.
608
777
  *
609
- * @returns entries relative to the ledger's root, or undefined when no
778
+ * @returns the entries and the root they are relative to, or undefined when no
610
779
  * repository could be found (the ledger then reports why).
611
780
  */
612
- private async scanTracked(ledger: Ledger): Promise<StatusEntry[] | undefined> {
613
- const tracked = await this.run(ledger.alias, trackedStatusCommand(ledger.root))
781
+ private async scanTracked(ledger: Ledger): Promise<{ root: string; entries: StatusEntry[] } | undefined> {
782
+ let root = ledger.root
783
+ const tracked = await this.run(ledger.alias, trackedStatusCommand(root))
784
+ // A concurrent root move makes this answer describe a tree nobody is
785
+ // looking at any more; hand back nothing instead of mixing two roots.
786
+ if (ledger.root !== root) return undefined
614
787
  if (tracked.ok) {
615
788
  ledger.unavailable = undefined
616
- return parseStatusZ(tracked.stdout)
789
+ return { root, entries: parseStatusZ(tracked.stdout) }
617
790
  }
618
791
  // The configured repository directory may belong to a DIFFERENT workspace
619
792
  // (the panel reads it from whatever the explorer has selected), or the
@@ -623,12 +796,14 @@ export class SessionChanges {
623
796
  this.warn(`repository directory "${ledger.subdir}" is missing on the host; falling back to the session root`)
624
797
  ledger.subdir = ''
625
798
  ledger.root = ledger.baseRoot
626
- ledger.baseline = undefined
627
- ledger.baselineTaken = false
628
- const retry = await this.run(ledger.alias, trackedStatusCommand(ledger.root))
799
+ // Same rule as `useRepoSubdir`: the previous root's observations (and its
800
+ // untracked verdicts) say nothing about this one.
801
+ this.resetObservation(ledger)
802
+ root = ledger.root
803
+ const retry = await this.run(ledger.alias, trackedStatusCommand(root))
629
804
  if (retry.ok) {
630
805
  ledger.unavailable = undefined
631
- return parseStatusZ(retry.stdout)
806
+ return { root, entries: parseStatusZ(retry.stdout) }
632
807
  }
633
808
  ledger.unavailable = retry.reason
634
809
  return undefined
@@ -636,10 +811,11 @@ export class SessionChanges {
636
811
  if (!ledger.adoptedSubdir) {
637
812
  const found = await this.adoptRepositoryBelow(ledger)
638
813
  if (found !== undefined) {
639
- const retry = await this.run(ledger.alias, trackedStatusCommand(ledger.root))
814
+ root = ledger.root
815
+ const retry = await this.run(ledger.alias, trackedStatusCommand(root))
640
816
  if (retry.ok) {
641
817
  ledger.unavailable = undefined
642
- return parseStatusZ(retry.stdout)
818
+ return { root, entries: parseStatusZ(retry.stdout) }
643
819
  }
644
820
  ledger.unavailable = retry.reason
645
821
  return undefined
@@ -675,7 +851,15 @@ export class SessionChanges {
675
851
  + ' — set the repository directory in Source Control'
676
852
  return undefined
677
853
  }
678
- ledger.root = `${ledger.root}/${found[0]}`
854
+ const adopted = `${ledger.root}/${found[0]}`
855
+ // Adopting a repository one level down is a root move like any other: what
856
+ // was observed against the container root (and what git said about the
857
+ // untracked walk there) describes a different tree.
858
+ this.resetObservation(ledger)
859
+ ledger.root = adopted
860
+ // `resetObservation` cleared it; the probe above already ran for this root,
861
+ // and re-probing on every refresh would turn one transient miss into a loop.
862
+ ledger.adoptedSubdir = true
679
863
  this.warn(`no repository at the session root; using ${ledger.root}`)
680
864
  return ledger.root
681
865
  }
@@ -693,17 +877,26 @@ export class SessionChanges {
693
877
  private async kickUntracked(ledger: Ledger): Promise<void> {
694
878
  if (ledger.disposed || ledger.untrackedGivenUp || ledger.untrackedJob !== undefined) return
695
879
  if (ledger.untracked !== undefined && Date.now() - ledger.untrackedAt < this.untrackedCadence(ledger)) return
880
+ // The paths this walk produces are relative to the root it runs in; capture
881
+ // it so a root move that happens mid-walk (seconds to minutes here) cannot
882
+ // merge the previous tree's names into the new one.
883
+ const root = ledger.root
696
884
  ledger.untrackedAt = Date.now()
697
885
  const job = (async () => {
698
886
  const started = Date.now()
699
- const scan = await this.run(ledger.alias, untrackedCommand(ledger.root), this.untrackedBudget())
887
+ const scan = await this.run(ledger.alias, untrackedCommand(root), this.untrackedBudget())
700
888
  ledger.untrackedMs = Date.now() - started
701
889
  if (ledger.disposed) return
890
+ if (ledger.root !== root) return
702
891
  if (!scan.ok) {
703
892
  ledger.untrackedGivenUp = true
893
+ // Keep WHY: the panel can show it, and its absence would make a dead
894
+ // capability look like "this session created no files".
895
+ ledger.untrackedFailure = scan.reason
704
896
  this.warn(`untracked scan unusable (${scan.reason}); new files will not be listed`)
705
897
  return
706
898
  }
899
+ ledger.untrackedFailure = undefined
707
900
  ledger.untracked = parseUntrackedZ(scan.stdout)
708
901
  await this.absorbPreExisting(ledger)
709
902
  // A completed scan is worth one more publish: it is the only source of
@@ -749,6 +942,7 @@ export class SessionChanges {
749
942
  private async absorbPreExisting(ledger: Ledger): Promise<void> {
750
943
  if (ledger.untracked === undefined || ledger.absorbed) return
751
944
  ledger.absorbed = true
945
+ const root = ledger.root
752
946
  const baseline = ledger.baseline ?? new Map<string, ReadResult>()
753
947
  ledger.baseline = baseline
754
948
  const unknown = ledger.untracked
@@ -756,7 +950,9 @@ export class SessionChanges {
756
950
  .filter(path => !baseline.has(path))
757
951
  if (unknown.length === 0) return
758
952
  const reads = await this.readPaths(ledger, unknown, 'worktree')
759
- if (ledger.disposed) return
953
+ // A root move during the read makes the mtimes describe another tree; the
954
+ // move itself reset `absorbed`, so dropping the batch is enough.
955
+ if (ledger.disposed || ledger.root !== root) return
760
956
  for (const [path, read] of reads) {
761
957
  if (read.mtime === undefined) continue
762
958
  if (read.mtime * 1000 < ledger.startedAt) baseline.set(path, read)
@@ -105,6 +105,34 @@ export const READ_EXIT = {
105
105
  /** Marker that starts one file block in a read reply. */
106
106
  const FILE_MARKER = '@@RVS-FILE '
107
107
 
108
+ /**
109
+ * Strict UTF-8 decoder — one instance, reused.
110
+ *
111
+ * A file's bytes are only "text" if they decode as UTF-8; anything else used to be
112
+ * decoded lossily into U+FFFD, which made the panel show mojibake with counts that
113
+ * were pure fiction AND made every revert fail (the patch's context lines could
114
+ * never match the real bytes). "Not decodable" is reported as binary instead — the
115
+ * one honest answer, and the one the undo path already refuses to touch.
116
+ *
117
+ * `ignoreBOM: true` is required, despite the confusing name: with the default
118
+ * (false) the decoder CONSUMES a leading UTF-8 BOM, while the editor's read path
119
+ * (`sftp.ts` → `Buffer.toString('utf8')`) keeps it. Stripping it here would make
120
+ * the ledger's text one code point shorter than the file on disk; the patch the
121
+ * undo path builds from that text then lacks the BOM on the first line and
122
+ * `git apply -R` rejects it (fail-closed, but the revert is unusable), and the
123
+ * first-line inline marks shift by one column.
124
+ */
125
+ const strictUtf8 = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true })
126
+
127
+ /** Decode strict UTF-8, or undefined when the bytes are not valid UTF-8. */
128
+ function decodeUtf8Strict(bytes: Buffer): string | undefined {
129
+ try {
130
+ return strictUtf8.decode(bytes)
131
+ } catch {
132
+ return undefined
133
+ }
134
+ }
135
+
108
136
  /** POSIX single-quote one shell word. Throws on NUL, which no shell can carry. */
109
137
  function shq(word: string): string {
110
138
  if (word.includes('\0')) throw new Error('NUL byte in shell word')
@@ -442,7 +470,15 @@ export function parseReads(stdout: string): Map<string, ReadResult> {
442
470
  results.set(path, { text: null, truncated: false, binary: true, absent: false, ...stats })
443
471
  continue
444
472
  }
445
- results.set(path, { text: bytes.toString('utf8'), truncated: false, binary: false, absent: false, ...stats })
473
+ // Not valid UTF-8 (a legacy-encoded source, a truncated multibyte char, a
474
+ // non-text payload): report it as binary rather than pretending the lossy
475
+ // decode is the file's text. See `strictUtf8`.
476
+ const text = decodeUtf8Strict(bytes)
477
+ if (text === undefined) {
478
+ results.set(path, { text: null, truncated: false, binary: true, absent: false, ...stats })
479
+ continue
480
+ }
481
+ results.set(path, { text, truncated: false, binary: false, absent: false, ...stats })
446
482
  }
447
483
  return results
448
484
  }