dsh-remote-vs 0.21.1 → 0.23.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 (52) hide show
  1. package/README.en.md +489 -473
  2. package/README.md +434 -424
  3. package/cordis.patch.yml +13 -5
  4. package/lib/client.js +946 -256
  5. package/lib/index.js +187 -15
  6. package/lib/p2-router-fs.js +6 -7
  7. package/lib/types/changes/recorder.d.ts +21 -0
  8. package/lib/types/changes/status.d.ts +41 -1
  9. package/lib/types/changes/text-diff.d.ts +18 -0
  10. package/lib/types/client/changes/ChangesDock.d.ts +9 -2
  11. package/lib/types/client/changes/model.d.ts +3 -1
  12. package/lib/types/client/changes/review-state.d.ts +67 -0
  13. package/lib/types/client/notices.d.ts +35 -0
  14. package/lib/types/client/store.d.ts +51 -0
  15. package/lib/types/client/vsc/change-marks.d.ts +17 -0
  16. package/lib/types/client/vsc/kit.d.ts +9 -0
  17. package/lib/types/deploy.d.ts +28 -2
  18. package/lib/types/notices.d.ts +22 -0
  19. package/lib/types/p2/router-fs.d.ts +4 -5
  20. package/lib/types/p2/worlds.d.ts +10 -0
  21. package/lib/types/protocol.d.ts +37 -1
  22. package/lib/{worlds-DSzyajOB.js → worlds-DXdP4SMn.js} +80 -4
  23. package/package.json +37 -37
  24. package/src/changes/recorder.ts +93 -28
  25. package/src/changes/status.ts +69 -2
  26. package/src/changes/text-diff.ts +42 -0
  27. package/src/client/DirectoryFlow.tsx +65 -5
  28. package/src/client/api.ts +5 -0
  29. package/src/client/changes/ChangesDock.tsx +241 -39
  30. package/src/client/changes/changes.css +122 -9
  31. package/src/client/changes/model.ts +106 -22
  32. package/src/client/changes/review-state.ts +133 -0
  33. package/src/client/i18n.ts +48 -8
  34. package/src/client/index.tsx +24 -5
  35. package/src/client/notices.ts +86 -0
  36. package/src/client/store.tsx +186 -2
  37. package/src/client/vsc/change-marks.ts +39 -6
  38. package/src/client/vsc/kit.tsx +16 -1
  39. package/src/client/vsc/vsc.css +23 -0
  40. package/src/deploy.ts +38 -2
  41. package/src/http.ts +12 -1
  42. package/src/notices.ts +37 -0
  43. package/src/p2/router-fs.ts +5 -6
  44. package/src/p2/worlds.ts +46 -2
  45. package/src/protocol.ts +37 -1
  46. package/vendor/dsh-remote-helpers/dsh-ssh-helper-0.2.2-rc.4-linux-x64.helper.json +19 -0
  47. package/vendor/dsh-remote-helpers/dsh-ssh-helper-0.2.2-rc.4-linux-x64.tar.gz +4 -0
  48. package/vendor/dsh-remote-helpers/dsh-ssh-helper-0.2.2-rc.4-linux-x64.tar.gz.sha256 +1 -0
  49. package/vendor/dsh-remote-helpers/ssh-helper-runtime-deps.patch +14 -0
  50. package/vendor/dsh-remote-helpers/dsh-ssh-helper-0.2.1-alpha.2-linux-x64.helper.json +0 -16
  51. package/vendor/dsh-remote-helpers/dsh-ssh-helper-0.2.1-alpha.2-linux-x64.tar.gz +0 -4
  52. package/vendor/dsh-remote-helpers/dsh-ssh-helper-0.2.1-alpha.2-linux-x64.tar.gz.sha256 +0 -1
@@ -40,6 +40,7 @@ import type {
40
40
  import type { RemotePool } from '../pool.ts'
41
41
  import type { RemoteWorlds, WorldRoute } from '../p2/worlds.ts'
42
42
  import {
43
+ excludeDirNames,
43
44
  parseReads,
44
45
  parseStatusZ,
45
46
  parseUntrackedZ,
@@ -47,12 +48,13 @@ import {
47
48
  readWorktreeCommand,
48
49
  reposBelowCommand,
49
50
  trackedStatusCommand,
51
+ UNTRACKED_EXCLUDED_DIRECTORIES,
50
52
  untrackedCommand,
51
53
  type ChangeStatus,
52
54
  type ReadResult,
53
55
  type StatusEntry,
54
56
  } from './status.ts'
55
- import { diffText, hunkPatch } from './text-diff.ts'
57
+ import { diffText, filePatch, hunkPatch } from './text-diff.ts'
56
58
 
57
59
  /** The two facts a turn boundary needs from a Session, kept cordis-free. */
58
60
  export interface LedgerTarget {
@@ -78,6 +80,12 @@ export interface SessionChangesDeps {
78
80
  untrackedBudgetMs?: number
79
81
  /** How often the untracked scan may run again (default five seconds). */
80
82
  untrackedRefreshMs?: number
83
+ /**
84
+ * Directory names the untracked scan leaves out (build output, dependency
85
+ * caches). Defaults to {@link UNTRACKED_EXCLUDED_DIRECTORIES}; an explicit
86
+ * empty array turns the exclusion off.
87
+ */
88
+ excludeDirs?: readonly string[]
81
89
  /**
82
90
  * Override the per-exec budget outright.
83
91
  *
@@ -111,18 +119,17 @@ interface FileRecord {
111
119
  binary: boolean
112
120
  truncated: boolean
113
121
  /**
114
- * Whether {@link SessionChanges.diff} may hand out a real reverse patch.
122
+ * Which side the `before` bytes came from.
115
123
  *
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
+ * `baseline` is the content a file already carried when the session started
125
+ * (pre-existing dirt), `head` is git's committed blob. The distinction is
126
+ * load-bearing for big files: a HEAD read can be taken again at a larger cap
127
+ * when the user asks for one file, while the baseline snapshot cannot be
128
+ * retaken — it described the worktree at session start, which has moved on.
129
+ * Re-reading `HEAD` for a baseline-backed record would silently build a
130
+ * revert that discards the user's own pre-session edits.
124
131
  */
125
- undoable: boolean
132
+ beforeFrom: 'baseline' | 'head' | 'none'
126
133
  }
127
134
 
128
135
  /** Grace added to an exec budget before the watchdog gives up on it. */
@@ -130,6 +137,19 @@ const WATCHDOG_GRACE_MS = 5_000
130
137
  /** Sentinel for "the host call never came back". */
131
138
  const WATCHDOG_FIRED = 'watchdog-fired' as const
132
139
 
140
+ /**
141
+ * Per-file budget for the ONE read a click asks for (`diff`).
142
+ *
143
+ * A scan compares hundreds of paths and stays at 256 KiB; a single file the user
144
+ * asked to review is a different trade — 2 MiB is enough for the large sources
145
+ * a monorepo carries while keeping the base64 reply (≈2.7 MB) inside what one
146
+ * exec comfortably returns.
147
+ */
148
+ const DIFF_MAX_FILE_BYTES = 2 * 1024 * 1024
149
+
150
+ /** The single-file read budget, as `readPaths` wants it. */
151
+ const DIFF_LIMITS = { perFile: DIFF_MAX_FILE_BYTES, total: DIFF_MAX_FILE_BYTES } as const
152
+
133
153
  /** One session's bookkeeping. */
134
154
  interface Ledger {
135
155
  sessionId: string
@@ -277,6 +297,10 @@ export class SessionChanges {
277
297
  ?? (ledger.untrackedFailure === undefined
278
298
  ? undefined
279
299
  : `new-file scan unavailable: ${ledger.untrackedFailure} (use the refresh button to retry)`)
300
+ // Which paths the scan was told to skip. Said out loud (not silently
301
+ // filtered) so a file the user expected to see is never "missing" for an
302
+ // unknown reason; the SCM panel is the surface that shows everything.
303
+ const excludedDirs = this.excludedDirs()
280
304
  return {
281
305
  alias: ledger.alias,
282
306
  root: ledger.root,
@@ -285,6 +309,7 @@ export class SessionChanges {
285
309
  added: ledger.added,
286
310
  deleted: ledger.deleted,
287
311
  at: ledger.at,
312
+ ...(excludedDirs.length === 0 ? {} : { excludedDirs }),
288
313
  /*
289
314
  * What "pending" is allowed to mean to the panel.
290
315
  *
@@ -314,6 +339,14 @@ export class SessionChanges {
314
339
  * change the file between scans, and replaying a cached copy against a fresh
315
340
  * buffer is exactly how the painted lines end up at the wrong places.
316
341
  *
342
+ * This is the ONE read a user asks for by clicking a row, so it is allowed a
343
+ * larger per-file budget than a scan (`DIFF_MAX_FILE_BYTES`): a file the list
344
+ * had to withhold as "too large" can still be reviewed and reverted here,
345
+ * while a scan stays cheap. A withheld HEAD side is retaken at that budget
346
+ * (git has the bytes); a withheld BASELINE side is not — that snapshot
347
+ * described the session's own starting point and cannot be reconstructed, so
348
+ * the file stays display-only rather than guessing a wrong reverse.
349
+ *
317
350
  * @param sessionId - live session owning the ledger.
318
351
  * @param path - the file's remote absolute path (as listed in the summary).
319
352
  * @returns hunks for decorations, or null when the session/file is unknown.
@@ -329,7 +362,7 @@ export class SessionChanges {
329
362
  let afterText = record.after
330
363
  let binary = record.binary
331
364
  let truncated = record.truncated
332
- const fresh = await this.readPaths(ledger, [record.display], 'worktree')
365
+ const fresh = await this.readPaths(ledger, [record.display], 'worktree', DIFF_LIMITS)
333
366
  if (ledger.disposed) return null
334
367
  const side = fresh.get(record.display)
335
368
  if (side !== undefined) {
@@ -341,7 +374,24 @@ export class SessionChanges {
341
374
  if (binary) {
342
375
  return { kind: 'binary', path, display: record.display, hunks: [], ...(status === undefined ? {} : { status }) }
343
376
  }
344
- const result = diffText(record.before ?? '', afterText ?? '')
377
+ // A HEAD side the scan had to withhold is worth one more read at the larger
378
+ // budget; the baseline side is not (see the note above).
379
+ let beforeText = record.before
380
+ if (beforeText === null && record.beforeFrom === 'head') {
381
+ const head = await this.readPaths(ledger, [record.display], 'head', DIFF_LIMITS)
382
+ if (ledger.disposed) return null
383
+ beforeText = head.get(record.display)?.text ?? null
384
+ }
385
+ const result = diffText(beforeText ?? '', afterText ?? '')
386
+ /**
387
+ * The reverse patch exists only when the comparison is complete and has an
388
+ * old side. A whole-file creation has no old side: its reverse is "delete the
389
+ * file", which a patch cannot express (the client uses
390
+ * `RemoteChangedFile.revert` for that case instead). Withheld bytes are not
391
+ * evidence either, so a truncated after side gets no patch — the client's
392
+ * undo path then refuses (`changes.undoMissing`) instead of guessing.
393
+ */
394
+ const reverse = beforeText !== null && !truncated ? filePatch(record.display, result.hunks) : ''
345
395
  const hunks: UnifiedHunk[] = result.hunks.map(hunk => ({
346
396
  oldStart: hunk.oldStart,
347
397
  oldCount: hunk.oldLines,
@@ -353,9 +403,8 @@ export class SessionChanges {
353
403
  // change", so it must be a real patch, not a display artifact. Empty
354
404
  // means "display only": the client's undo path refuses an empty patch
355
405
  // (`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) : '',
406
+ // whose reverse would delete a file git has no copy of.
407
+ patch: reverse === '' ? '' : hunkPatch(record.display, hunk),
359
408
  }))
360
409
  if (hunks.length === 0) {
361
410
  return { kind: 'missing', path, display: record.display, hunks: [], ...(status === undefined ? {} : { status }) }
@@ -365,6 +414,7 @@ export class SessionChanges {
365
414
  path,
366
415
  display: record.display,
367
416
  hunks,
417
+ ...(reverse === '' ? {} : { patch: reverse }),
368
418
  ...(status === undefined ? {} : { status }),
369
419
  ...(truncated ? { truncated: true as const } : {}),
370
420
  }
@@ -692,7 +742,9 @@ export class SessionChanges {
692
742
  let added = 0
693
743
  let deleted = 0
694
744
  for (const entry of listed) {
695
- const beforeSide = baseline.get(entry.path) ?? head.get(entry.path)
745
+ const fromBaseline = baseline.get(entry.path)
746
+ const fromHead = head.get(entry.path)
747
+ const beforeSide = fromBaseline ?? fromHead
696
748
  const afterSide = after.get(entry.path)
697
749
  const before = beforeSide?.text ?? null
698
750
  const afterText = afterSide?.text ?? null
@@ -711,14 +763,15 @@ export class SessionChanges {
711
763
  if ((binary || fileTruncated) && sameStat(beforeSide, afterSide)) continue
712
764
  const oversized = fileTruncated && !binary
713
765
  // 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`).
766
+ // deleting the file. That is recoverable when git holds the content — a
767
+ // tracked addition, where the index still has the bytes — and not when it
768
+ // does not: an untracked file exists only in the worktree, so "undo" would
769
+ // destroy its single copy. The summary therefore tells the client which
770
+ // action (if any) it may offer, instead of letting the browser guess.
720
771
  const creation = before === null
721
- const undoable = !binary && !oversized && beforeSide !== undefined && !creation
772
+ const revert: 'patch' | 'delete' | undefined = !binary && !oversized && beforeSide !== undefined && !creation
773
+ ? 'patch'
774
+ : (entry.status === 'A' ? 'delete' : undefined)
722
775
  const diff = binary || oversized ? { added: 0, deleted: 0 } : diffText(before ?? '', afterText ?? '')
723
776
  const status = panelStatus(entry.status)
724
777
  const absolute = posixJoin(ledger.root, entry.path)
@@ -730,7 +783,7 @@ export class SessionChanges {
730
783
  after: afterText,
731
784
  binary,
732
785
  truncated: fileTruncated,
733
- undoable,
786
+ beforeFrom: fromBaseline !== undefined ? 'baseline' : fromHead !== undefined ? 'head' : 'none',
734
787
  })
735
788
  added += diff.added
736
789
  deleted += diff.deleted
@@ -742,6 +795,7 @@ export class SessionChanges {
742
795
  ...(binary ? { binary: true as const } : {}),
743
796
  ...(oversized ? { oversized: true as const } : {}),
744
797
  ...(status === undefined ? {} : { status }),
798
+ ...(revert === undefined ? {} : { revert }),
745
799
  })
746
800
  }
747
801
  files.sort((left, right) => left.display.localeCompare(right.display))
@@ -884,7 +938,7 @@ export class SessionChanges {
884
938
  ledger.untrackedAt = Date.now()
885
939
  const job = (async () => {
886
940
  const started = Date.now()
887
- const scan = await this.run(ledger.alias, untrackedCommand(root), this.untrackedBudget())
941
+ const scan = await this.run(ledger.alias, untrackedCommand(root, this.excludedDirs()), this.untrackedBudget())
888
942
  ledger.untrackedMs = Date.now() - started
889
943
  if (ledger.disposed) return
890
944
  if (ledger.root !== root) return
@@ -993,10 +1047,11 @@ export class SessionChanges {
993
1047
  ledger: Ledger,
994
1048
  paths: readonly string[],
995
1049
  side: 'worktree' | 'head',
1050
+ limits?: { perFile: number; total: number },
996
1051
  ): Promise<Map<string, ReadResult>> {
997
1052
  if (paths.length === 0) return new Map()
998
- const perFile = this.deps.maxFileBytes ?? 256 * 1024
999
- const total = this.deps.maxTotalBytes ?? 8 * 1024 * 1024
1053
+ const perFile = limits?.perFile ?? this.deps.maxFileBytes ?? 256 * 1024
1054
+ const total = limits?.total ?? this.deps.maxTotalBytes ?? 8 * 1024 * 1024
1000
1055
  const command = side === 'worktree'
1001
1056
  ? readWorktreeCommand(ledger.root, paths, perFile, total)
1002
1057
  : readHeadCommand(ledger.root, paths, perFile, total)
@@ -1065,6 +1120,16 @@ export class SessionChanges {
1065
1120
  return this.deps.untrackedBudgetMs ?? this.budget(this.deps.timeouts().gitMs, 10_000, 180_000)
1066
1121
  }
1067
1122
 
1123
+ /**
1124
+ * The exclusions this ledger scans with, normalized once per call.
1125
+ *
1126
+ * `??` and not `||`: an explicit empty array is a caller saying "count
1127
+ * everything", which must stay distinguishable from "not configured".
1128
+ */
1129
+ private excludedDirs(): string[] {
1130
+ return excludeDirNames(this.deps.excludeDirs ?? UNTRACKED_EXCLUDED_DIRECTORIES)
1131
+ }
1132
+
1068
1133
  private budget(configured: number, floor: number, ceiling: number): number {
1069
1134
  const value = Number.isFinite(configured) && configured > 0 ? configured : 30_000
1070
1135
  return Math.max(floor, Math.min(value, ceiling))
@@ -170,14 +170,81 @@ export function trackedStatusCommand(root: string): string {
170
170
  return [cdLine(root), 'git --no-pager status --porcelain -z -uno -- .'].join('\n')
171
171
  }
172
172
 
173
+ /**
174
+ * Directory names the ledger does not count as session changes.
175
+ *
176
+ * Build output and dependency caches are the two things a build leaves behind,
177
+ * and neither is this session's work. `--exclude-standard` only covers what the
178
+ * repository's own ignore rules name, so a checkout whose build directory is NOT
179
+ * ignored pays twice: thousands of paths fill the 500-row list (sorted, and
180
+ * `build/`/`out/` sort BEFORE `src/`, so the real changes get truncated away) and
181
+ * every listed path costs a read out of the 8 MiB transfer budget.
182
+ *
183
+ * The names mirror the three lists the plugin already prunes by elsewhere
184
+ * (`client/quickopen-model.ts` `EXCLUDED_DIRECTORIES`, `p2/file-refs.ts`
185
+ * `REMOTE_FILE_SEARCH_EXCLUDED_DIRECTORIES`, `search-ops.ts` `PRUNE_DIRS`). One
186
+ * vocabulary, four consumers: fold them into a shared module when one of those
187
+ * surfaces is next touched, instead of adding a fifth spelling here.
188
+ */
189
+ export const UNTRACKED_EXCLUDED_DIRECTORIES: readonly string[] = [
190
+ '.git', 'node_modules', 'dist', 'build', 'out', 'coverage', 'target',
191
+ '.next', '.nuxt', '.turbo', '.venv', '__pycache__', '.pytest_cache',
192
+ '.mypy_cache', '.gradle',
193
+ ]
194
+
195
+ /** Ceiling on the pathspecs one command carries (a cap, not a policy). */
196
+ const MAX_EXCLUDE_DIRS = 32
197
+
198
+ /**
199
+ * Keep only directory names a pathspec may name safely.
200
+ *
201
+ * A value that is absolute, carries a separator, walks up or looks like a flag
202
+ * is DROPPED rather than rejected: the list is configuration, and one bad entry
203
+ * must not stop the scan — the scan's job is to say what changed, not to police
204
+ * a setting. Dropping is also the conservative direction: a name that is not
205
+ * excluded is merely visible, while a malformed pathspec would hide paths the
206
+ * user never asked to hide (or turn `--exclude` into another flag).
207
+ *
208
+ * @param dirs - candidate names (undefined = none).
209
+ * @returns the usable names, deduplicated, in the given order.
210
+ */
211
+ export function excludeDirNames(dirs: readonly string[] | undefined): string[] {
212
+ const kept: string[] = []
213
+ for (const raw of dirs ?? []) {
214
+ const name = raw.trim()
215
+ if (name === '' || name === '.' || name === '..') continue
216
+ if (name.includes('/') || name.includes('\\') || name.includes('\0')) continue
217
+ // A pathspec is a PATTERN: `a*b` would exclude far more than the name says,
218
+ // and the panel would report that pattern as if it were a directory.
219
+ if (/[*?[\]]/.test(name)) continue
220
+ // A leading `-` would reach git as a flag, not a pathspec.
221
+ if (name.startsWith('-')) continue
222
+ if (kept.includes(name)) continue
223
+ if (kept.length >= MAX_EXCLUDE_DIRS) break
224
+ kept.push(name)
225
+ }
226
+ return kept
227
+ }
228
+
173
229
  /**
174
230
  * New files git is not tracking yet (the ones a session usually creates).
175
231
  *
232
+ * The exclusions are pushed down as pathspecs (`:(exclude)out`) rather than
233
+ * filtered after the fact, so those paths never cross the wire and never enter
234
+ * the 500-row cap. Measured on a tree with 3000 build outputs + 300 sources:
235
+ * 3300 records / 61.5 KB unfiltered versus 300 records / 6.8 KB with two
236
+ * exclusions — the walk itself costs the same either way (git still descends
237
+ * those directories), so the win is wire bytes, parse time and the read budget,
238
+ * not scan latency.
239
+ *
176
240
  * @param root - remote absolute POSIX directory (the session cwd).
241
+ * @param excludeDirs - directory names to leave out (see {@link excludeDirNames}).
177
242
  * @returns a `sh` script printing NUL-separated paths.
178
243
  */
179
- export function untrackedCommand(root: string): string {
180
- return [cdLine(root), 'git ls-files --others --exclude-standard -z -- .'].join('\n')
244
+ export function untrackedCommand(root: string, excludeDirs: readonly string[] = []): string {
245
+ const excludes = excludeDirNames(excludeDirs).map(name => shq(`:(exclude)${name}`))
246
+ const pathspec = ['--', '.', ...excludes].join(' ')
247
+ return [cdLine(root), `git ls-files --others --exclude-standard -z ${pathspec}`].join('\n')
181
248
  }
182
249
 
183
250
  /**
@@ -375,3 +375,45 @@ function lastLineOfSide(lines: string[], tag: '-' | '+'): number {
375
375
  }
376
376
  return -1
377
377
  }
378
+
379
+ /**
380
+ * Serialize a WHOLE file comparison as ONE patch (one header, every hunk).
381
+ *
382
+ * "Revert everything this session did to this file" is `git apply -R` of the
383
+ * file's complete diff, and that is a single write instead of one write per
384
+ * hunk. Concatenating `hunkPatch` output would also apply (git tolerates the
385
+ * repeated headers and re-anchors each block by offset), but it says the same
386
+ * file begins twice and depends on offset guessing — a real unified diff names
387
+ * the file once and lets git place every hunk against one picture.
388
+ *
389
+ * Verified against git 2.x: the result reverse-applies to a file whose content
390
+ * is `hunks`' new side, and leaves it byte-identical to the old side.
391
+ *
392
+ * @param displayPath - repo-relative path, as the panel shows it.
393
+ * @param hunks - every hunk of the comparison, in ascending order.
394
+ * @returns the patch, or '' when there is nothing to write (no hunks).
395
+ */
396
+ export function filePatch(displayPath: string, hunks: readonly TextHunk[]): string {
397
+ if (hunks.length === 0) return ''
398
+ const out: string[] = [`--- a/${displayPath}`, `+++ b/${displayPath}`]
399
+ for (const hunk of hunks) {
400
+ out.push(`@@ -${hunk.oldStart},${hunk.oldLines} +${hunk.newStart},${hunk.newLines} @@`)
401
+ // The marker follows the last line of the side that lacks a final newline.
402
+ // A per-file comparison has at most one such line per side and it is inside
403
+ // the last hunk, so the same rule as `hunkPatch` applies hunk by hunk.
404
+ const markers = new Set<number>()
405
+ if (hunk.oldNoEol === true) {
406
+ const at = lastLineOfSide(hunk.lines, '-')
407
+ if (at >= 0) markers.add(at)
408
+ }
409
+ if (hunk.newNoEol === true) {
410
+ const at = lastLineOfSide(hunk.lines, '+')
411
+ if (at >= 0) markers.add(at)
412
+ }
413
+ for (let index = 0; index < hunk.lines.length; index += 1) {
414
+ out.push(hunk.lines[index] ?? '')
415
+ if (markers.has(index)) out.push('\')
416
+ }
417
+ }
418
+ return `${out.join('\n')}\n`
419
+ }
@@ -27,6 +27,24 @@ import { WorkspaceWizard } from './WorkspaceWizard.tsx'
27
27
  import { detectLang, makeT } from './i18n.ts'
28
28
  import { Btn, Notice } from './ui.tsx'
29
29
 
30
+ /**
31
+ * Opt-in trace for the directory flow, silent unless the operator sets
32
+ * `localStorage['dsh-remote-vs.debug'] = '1'` and reopens the dialog.
33
+ *
34
+ * The native-chooser interaction crosses three parties — this dialog, the stock
35
+ * owner that adopts the path, and the host-side OS chooser — so "the dialog did
36
+ * not close" needs to say WHICH stage was reached before it can be diagnosed.
37
+ * Without this the only observable is the symptom.
38
+ */
39
+ function traceFlow(...parts: unknown[]): void {
40
+ try {
41
+ if (typeof localStorage === 'undefined' || localStorage.getItem('dsh-remote-vs.debug') !== '1') return
42
+ } catch {
43
+ return
44
+ }
45
+ console.info('[rvs-flow]', ...parts)
46
+ }
47
+
30
48
  /** Injected face: uiWorkspace directory primitives (bound in apply's closure). */
31
49
  export interface DirectoryFlowInjected {
32
50
  listDirectory: (path?: string, signal?: AbortSignal) => Promise<DirectoryListing>
@@ -62,6 +80,8 @@ function LocalLeg(props: {
62
80
  t: (k: string) => string
63
81
  busy: boolean
64
82
  injected: DirectoryFlowInjected
83
+ /** Monotonic id of the open request this leg belongs to (shared across remounts). */
84
+ flowEpoch: { current: number }
65
85
  onPicked: (path: string) => void
66
86
  }): ReactNode {
67
87
  const { t, busy, injected } = props
@@ -88,8 +108,10 @@ function LocalLeg(props: {
88
108
  } catch (e) {
89
109
  if (gen !== generation.current) return
90
110
  if (isUnavailable(e)) {
111
+ traceFlow('browse unavailable -> native')
91
112
  setMode('native')
92
113
  } else {
114
+ traceFlow('browse failed', errText(e))
93
115
  setMode(mode === 'browse' ? 'browse' : 'failed')
94
116
  setError(errText(e))
95
117
  }
@@ -128,12 +150,23 @@ function LocalLeg(props: {
128
150
 
129
151
  const nativePick = (): void => {
130
152
  const gen = ++generation.current
153
+ // The open request this pick belongs to. A REMOUNT (same request) must still
154
+ // deliver its result — the OS chooser can take long enough for an unrelated
155
+ // re-render to replace this instance — while a result from a PREVIOUS open
156
+ // must be dropped. `generation` cannot tell those apart; the flow epoch can.
157
+ const epoch = props.flowEpoch.current
131
158
  setLoading(true)
132
159
  setError(undefined)
133
160
  setNotice(undefined)
161
+ traceFlow('native chooser requested')
134
162
  injected.pickDirectory().then(
135
163
  (picked) => {
136
- if (gen !== generation.current) return
164
+ if (props.flowEpoch.current !== epoch) {
165
+ traceFlow('native chooser result dropped (another open request)', picked)
166
+ return
167
+ }
168
+ if (gen !== generation.current) traceFlow('native chooser result adopted after remount', picked)
169
+ traceFlow('native chooser returned', picked === null ? 'cancelled' : picked)
137
170
  setLoading(false)
138
171
  if (picked === null) {
139
172
  setNotice(t('flow.nativeCancelled'))
@@ -142,7 +175,8 @@ function LocalLeg(props: {
142
175
  }
143
176
  },
144
177
  (e: unknown) => {
145
- if (gen !== generation.current) return
178
+ if (props.flowEpoch.current !== epoch) return
179
+ traceFlow('native chooser failed', errText(e))
146
180
  setLoading(false)
147
181
  setError(errText(e))
148
182
  },
@@ -327,6 +361,7 @@ function RemoteLeg(props: {
327
361
  onCancel={props.onCancel}
328
362
  onSaved={(_workspace, aliasPath) => {
329
363
  setDone(true)
364
+ traceFlow('remote wizard saved', aliasPath)
330
365
  props.onPicked(aliasPath)
331
366
  }}
332
367
  />
@@ -338,13 +373,38 @@ export function RemoteDirectoryFlow(props: DirectoryFlowOwnerProps & DirectoryFl
338
373
  const [t] = useState(() => makeT(detectLang()))
339
374
  const [tab, setTab] = useState<'local' | 'remote'>('local')
340
375
  const [epoch, setEpoch] = useState(0)
376
+ /** Mirrors `epoch` without a render lag; the local leg compares it on resolve. */
377
+ const epochRef = useRef(0)
378
+
379
+ /**
380
+ * Hand the picked path to the owner and close the dialog in one step.
381
+ *
382
+ * The owner adopts a picked path asynchronously (`createWorkspace`), and only
383
+ * then flips `open` back to false. For the in-app browser that round trip is
384
+ * a local listing, but the native chooser makes the operator wait for the OS
385
+ * dialog to return and for the host to create the Workspace — and until the
386
+ * owner's state lands, this dialog sits on screen. Operators reported it as
387
+ * "the dialog only disappears after I click or press a key": that next input
388
+ * is what re-rendered the owner's surface. `onCancel` is the same owner's
389
+ * "withdraw the request / just close the flow" signal, so sending it with the
390
+ * path closes immediately and independently of adoption timing; the owner's
391
+ * own close is then a no-op. Cancel goes first so the dialog closes even if
392
+ * the owner's picked-handler throws.
393
+ */
394
+ const finish = (path: string): void => {
395
+ traceFlow('finish', path)
396
+ props.onCancel()
397
+ props.onPicked(path)
398
+ }
341
399
 
342
400
  const wasOpen = useRef(false)
343
401
  useEffect(() => {
344
402
  if (props.open && !wasOpen.current) {
345
403
  setTab('local')
346
- setEpoch((n) => n + 1)
404
+ epochRef.current += 1
405
+ setEpoch(epochRef.current)
347
406
  }
407
+ traceFlow('open', props.open)
348
408
  wasOpen.current = props.open
349
409
  }, [props.open])
350
410
 
@@ -454,8 +514,8 @@ export function RemoteDirectoryFlow(props: DirectoryFlowOwnerProps & DirectoryFl
454
514
  </div>
455
515
  <div style={{ flex: 1, minHeight: 0, overflowY: 'auto' }}>
456
516
  {tab === 'local'
457
- ? <LocalLeg key={`local-${epoch}`} t={t} busy={props.busy} injected={injected} onPicked={props.onPicked} />
458
- : <RemoteLeg key={`remote-${epoch}`} t={t} busy={props.busy} onPicked={props.onPicked} onCancel={props.onCancel} />}
517
+ ? <LocalLeg key={`local-${epoch}`} t={t} busy={props.busy} injected={injected} flowEpoch={epochRef} onPicked={finish} />
518
+ : <RemoteLeg key={`remote-${epoch}`} t={t} busy={props.busy} onPicked={finish} onCancel={props.onCancel} />}
459
519
  </div>
460
520
  <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 12 }}>
461
521
  <Btn onClick={props.onCancel} disabled={props.busy}>{t('hosts.cancel')}</Btn>
package/src/client/api.ts CHANGED
@@ -33,6 +33,7 @@ import {
33
33
  import { DEFAULT_TIMEOUTS, normalizeTimeouts, timeoutSeconds } from '../timeouts.ts'
34
34
  import { activeConnectionAlias, currentConnection, isConnectionFailure, noteConnectionFailure } from './connection.ts'
35
35
  import { detectLang, makeT } from './i18n.ts'
36
+ import { dispatchHostNotices } from './notices.ts'
36
37
  import { parseSseFrame, takeSseFrames } from './exec-output.ts'
37
38
  import {
38
39
  branchesCommand,
@@ -141,6 +142,10 @@ async function call<T>(path: string, init?: RequestInit): Promise<T> {
141
142
  }
142
143
  throw failure
143
144
  }
145
+ // One-shot Host notices (an automatic helper push that THIS request
146
+ // triggered) ride the response; render them here so the surface that needed
147
+ // the helper reports it without the user opening Settings.
148
+ dispatchHostNotices(data)
144
149
  return data as T
145
150
  }
146
151