dsh-plugin-wsl-env 0.29.0 → 0.29.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 (78) hide show
  1. package/CHANGELOG.md +342 -0
  2. package/CONTRIBUTING.md +68 -12
  3. package/CONTRIBUTING.zh.md +34 -4
  4. package/README.md +1 -1
  5. package/agent/native/linux-aarch64/dsh-wsl-agent +0 -0
  6. package/agent/native/linux-x86_64/dsh-wsl-agent +0 -0
  7. package/agent/wsl-agent.sh +15 -4
  8. package/client.js +454 -110
  9. package/cordis.patch.yml +28 -7
  10. package/docs/AGENT-PROTOCOL-V7.md +4 -2
  11. package/docs/ARCHITECTURE.md +3 -1
  12. package/docs/ARCHITECTURE.zh.md +3 -1
  13. package/docs/COMPATIBILITY.md +1 -1
  14. package/docs/COMPATIBILITY.zh.md +1 -1
  15. package/docs/CONFIGURATION.md +19 -7
  16. package/docs/CONFIGURATION.zh.md +13 -5
  17. package/docs/DIAGNOSTICS.md +31 -5
  18. package/docs/DIAGNOSTICS.zh.md +22 -5
  19. package/docs/LIMITATIONS.md +65 -6
  20. package/docs/LIMITATIONS.zh.md +51 -6
  21. package/docs/PERFORMANCE.md +29 -1
  22. package/docs/PERFORMANCE.zh.md +23 -1
  23. package/docs/QUICKSTART.md +1 -1
  24. package/docs/QUICKSTART.zh.md +1 -1
  25. package/docs/README.zh.md +1 -1
  26. package/docs/RELEASING.md +29 -6
  27. package/docs/RELEASING.zh.md +9 -0
  28. package/docs/adr/0002-native-agent.md +50 -2
  29. package/lib/agent-confined.js +15 -4
  30. package/lib/agent-errors.d.ts +16 -0
  31. package/lib/agent-errors.js +19 -0
  32. package/lib/agent-exec.d.ts +8 -1
  33. package/lib/agent-exec.js +2 -1
  34. package/lib/agent-shared.d.ts +85 -2
  35. package/lib/agent-shared.js +167 -38
  36. package/lib/agent.d.ts +60 -6
  37. package/lib/agent.js +177 -28
  38. package/lib/auto-preset.js +7 -2
  39. package/lib/doctor-live.d.ts +36 -7
  40. package/lib/doctor-live.js +61 -12
  41. package/lib/doctor-process.d.ts +68 -0
  42. package/lib/doctor-process.js +139 -0
  43. package/lib/doctor-report.js +11 -109
  44. package/lib/fs-substrate.js +3 -3
  45. package/lib/fsio-agent.d.ts +57 -6
  46. package/lib/fsio-agent.js +168 -75
  47. package/lib/git-exec.d.ts +7 -1
  48. package/lib/git-exec.js +14 -2
  49. package/lib/native-agent.d.ts +25 -4
  50. package/lib/native-agent.js +52 -9
  51. package/lib/picker.d.ts +2 -1
  52. package/lib/picker.js +30 -13
  53. package/lib/plugin-update.js +18 -14
  54. package/lib/provider-common.d.ts +112 -0
  55. package/lib/provider-common.js +171 -0
  56. package/lib/sandbox-core.js +52 -13
  57. package/lib/search-exec.d.ts +6 -0
  58. package/lib/search-exec.js +10 -2
  59. package/lib/session-runtime.d.ts +46 -1
  60. package/lib/session-runtime.js +57 -7
  61. package/lib/session-scope.d.ts +22 -1
  62. package/lib/session-scope.js +33 -7
  63. package/lib/shell-env.js +125 -12
  64. package/lib/socket-isolation.d.ts +12 -4
  65. package/lib/socket-isolation.js +27 -10
  66. package/lib/status.js +53 -4
  67. package/lib/subprocess.js +3 -3
  68. package/lib/terminal-activity.js +6 -9
  69. package/lib/wsl-doctor-command.js +36 -80
  70. package/lib/wsl-filesystem.d.ts +9 -4
  71. package/lib/wsl-filesystem.js +26 -10
  72. package/lib/wsl-shell.d.ts +27 -17
  73. package/lib/wsl-shell.js +83 -24
  74. package/lib/wsl.d.ts +3 -1
  75. package/lib/wsl.js +82 -7
  76. package/package.json +5 -4
  77. package/scripts/bootstrap.sh +36 -12
  78. package/scripts/doctor.mjs +514 -201
package/lib/fsio-agent.js CHANGED
@@ -30,6 +30,12 @@ const FS_OP_TIMEOUT_MS = 30_000;
30
30
  const FS_OP_TIMEOUT_PER_MIB_MS = 1_000;
31
31
  /** Ceiling on the size-scaled budget; a stuck op must still fail in bounded time. */
32
32
  const FS_OP_TIMEOUT_MAX_MS = 10 * 60_000;
33
+ /**
34
+ * How many of a listing's symlink children ride one batched frame, each with
35
+ * its stat and its realpath. Bounded so one frame stays a reasonable size
36
+ * however link-heavy the directory is (`node_modules/.bin`, `/usr/bin`).
37
+ */
38
+ const LINKS_PER_BATCH = 256;
33
39
  /**
34
40
  * The in-distro budget for an op whose cost scales with `bytes`: a fixed 30 s
35
41
  * was a false `FS_IO_ERROR` for a multi-GB `move` (the agent copies with
@@ -114,6 +120,41 @@ export function reasonToCode(reason) {
114
120
  * model sees the escalation offer instead of an unexplained I/O failure.
115
121
  */
116
122
  const DENIAL_SIGNATURES = ["read-only file system"];
123
+ /**
124
+ * Fill one listing row in from its symlink target's stat and canonical path:
125
+ * the type the tree shows, the version (and size, for a file) the target
126
+ * carries, and the identity the harness keys on.
127
+ *
128
+ * @param row - the link's row, seeded with the dangling shape.
129
+ * @param followed - the target's stat.
130
+ * @param canonical - the target's canonical path.
131
+ * @param distro - the distro the path lives in, for the UNC identity.
132
+ */
133
+ function applyFollowed(row, followed, canonical, distro) {
134
+ if (row === undefined)
135
+ return;
136
+ row.type = followed.type === "f" ? "file" : followed.type === "d" ? "directory" : "other";
137
+ row.version = followed.version;
138
+ if (followed.type === "f")
139
+ row.size = followed.size;
140
+ row.target = { displayPath: row.target.displayPath, targetKey: posixToUnc(distro, canonical) };
141
+ }
142
+ /**
143
+ * Parse a batched stat record for a symlink's target, reading a malformed one
144
+ * as "not followed" — the batched twin of the serial road, where a stat that
145
+ * fails for any reason is caught and reads as a dangling link.
146
+ *
147
+ * @param payload - the record's payload.
148
+ * @returns the stat row, or null when it will not parse.
149
+ */
150
+ function followedOrNull(payload) {
151
+ try {
152
+ return parseStatRecord(payload);
153
+ }
154
+ catch {
155
+ return null;
156
+ }
157
+ }
117
158
  /**
118
159
  * One distro's filesystem face. Owns the agent round trips and the host-side
119
160
  * validation; the provider layers the fence on top.
@@ -238,7 +279,11 @@ export class DistroFs {
238
279
  * The wire type is the entry's own (lstat): a symlink child then gets one
239
280
  * follow-up stat (its target's version and size) plus a realpath (its
240
281
  * identity), and a dangling symlink degrades to the peer's `other` with no
241
- * version — exactly what the peer's null follow-probe produces.
282
+ * version — exactly what the peer's null follow-probe produces. Those
283
+ * follow-ups are collected first and sent together, one batched frame per
284
+ * {@link LINKS_PER_BATCH} links: one at a time, a directory of 200 links
285
+ * cost 400 sequential round trips and about half a second to expand in the
286
+ * GUI file tree, where the same 400 operations in one frame took 5 ms.
242
287
  *
243
288
  * @param target - the resolved directory to list.
244
289
  * @param signal - aborts between children.
@@ -286,6 +331,8 @@ export class DistroFs {
286
331
  const parentCanonical = linuxDir;
287
332
  const records = listPayload.toString("utf8").split("\0").filter((record) => record.length > 0);
288
333
  const entries = [];
334
+ /** The symlink children, each with the index of its row in `entries`. */
335
+ const links = [];
289
336
  for (const record of records) {
290
337
  throwIfAborted(signal, "list");
291
338
  const fields = record.split("\t");
@@ -302,35 +349,71 @@ export class DistroFs {
302
349
  const directory = parentCanonical === "/" ? "" : parentCanonical;
303
350
  const name = path.slice(parentCanonical.length).replace(/^\/+/, "");
304
351
  const displayPath = `${directory}/${name}`;
305
- // Non-link entries: the record's own stat IS the follow stat. A link
306
- // costs one stat plus one realpath, where the symlink actually lives.
307
- let { type, version, size } = { type: wireType, version: undefined, size: undefined };
308
- let childCanonical = `${directory}/${name}`;
352
+ const childPath = `${directory}/${name}`;
309
353
  if (wireType === "l") {
310
- const followed = await this.stat(childCanonical, { signal }).catch(() => null);
311
- if (followed) {
312
- type = followed.type;
313
- version = followed.version;
314
- if (followed.type === "f")
315
- size = followed.size;
316
- childCanonical = await this.canonicalPath(childCanonical, signal);
317
- }
318
- }
319
- else {
320
- version = versionOf({ dev, ino, size: sizeField, mtimeNs: nanoseconds(mtime), ctimeNs: nanoseconds(ctime) });
321
- if (type === "f")
322
- size = Number(sizeField);
354
+ // A link costs one stat plus one realpath, where the symlink actually
355
+ // lives. Its row starts as the dangling shape and is filled in by
356
+ // `followLinks` once every child has been read.
357
+ links.push({ row: entries.length, path: childPath });
358
+ entries.push({ name, type: "other", target: { displayPath, targetKey: posixToUnc(this.distro, childPath) } });
359
+ continue;
323
360
  }
361
+ // Every other entry: the record's own stat IS the follow stat.
324
362
  entries.push({
325
363
  name,
326
- type: type === "f" ? "file" : type === "d" ? "directory" : "other",
327
- target: { displayPath, targetKey: posixToUnc(this.distro, childCanonical) },
328
- ...(version !== undefined ? { version } : {}),
329
- ...(size !== undefined ? { size } : {}),
364
+ type: wireType === "f" ? "file" : wireType === "d" ? "directory" : "other",
365
+ target: { displayPath, targetKey: posixToUnc(this.distro, childPath) },
366
+ version: versionOf({ dev, ino, size: sizeField, mtimeNs: nanoseconds(mtime), ctimeNs: nanoseconds(ctime) }),
367
+ ...(wireType === "f" ? { size: Number(sizeField) } : {}),
330
368
  });
331
369
  }
370
+ await this.followLinks(links, entries, signal);
332
371
  return entries.sort((left, right) => left.name.localeCompare(right.name));
333
372
  }
373
+ /**
374
+ * Give the listing's symlink children their targets' identity: the row's
375
+ * type, version and size from a following stat, and its target key from the
376
+ * realpath. A link whose target cannot be stat'ed — dangling, or a record
377
+ * that will not parse — keeps the dangling shape the caller seeded.
378
+ *
379
+ * A batch-capable resident gets every follow-up in one frame per
380
+ * {@link LINKS_PER_BATCH} links; anything else keeps the serial road of one
381
+ * stat and one realpath per link, which is the only one it can serve.
382
+ *
383
+ * @param links - the symlink children, each with the index of its row.
384
+ * @param entries - the rows, updated in place.
385
+ * @param signal - aborts between frames.
386
+ */
387
+ async followLinks(links, entries, signal) {
388
+ if (!this.supportsBatch()) {
389
+ for (const link of links) {
390
+ throwIfAborted(signal, "list");
391
+ const followed = await this.stat(link.path, { signal }).catch(() => null);
392
+ // The realpath is asked only of a link that could be followed, and its
393
+ // failure is the listing's failure, exactly as before.
394
+ if (followed)
395
+ applyFollowed(entries[link.row], followed, await this.canonicalPath(link.path, signal), this.distro);
396
+ }
397
+ return;
398
+ }
399
+ for (let start = 0; start < links.length; start += LINKS_PER_BATCH) {
400
+ throwIfAborted(signal, "list");
401
+ const slice = links.slice(start, start + LINKS_PER_BATCH);
402
+ const records = await this.batch(slice.flatMap((link) => [{ op: "stat", args: [link.path] }, { op: "realpath", args: [link.path] }]), signal);
403
+ for (const [index, link] of slice.entries()) {
404
+ const statRecord = records[2 * index];
405
+ const realpathRecord = records[2 * index + 1];
406
+ const followed = statRecord?.ok ? followedOrNull(statRecord.payload) : null;
407
+ if (followed === null)
408
+ continue;
409
+ if (realpathRecord === undefined)
410
+ throw new FsCodedError(`cannot resolve "${link.path}": distro I/O failure`, "FS_IO_ERROR");
411
+ if (!realpathRecord.ok)
412
+ throw new FsCodedError(realpathRecord.message, reasonToCode(realpathRecord.reason));
413
+ applyFollowed(entries[link.row], followed, realpathRecord.payload.toString("utf8"), this.distro);
414
+ }
415
+ }
416
+ }
334
417
  /**
335
418
  * Stat the target as a regular file or refuse, mirroring the peer's
336
419
  * `statRegularFile` messages.
@@ -352,21 +435,35 @@ export class DistroFs {
352
435
  /**
353
436
  * Read the whole file's bytes through windowed frames.
354
437
  *
438
+ * A window is never wider than one frame should be, cap or no cap: with a
439
+ * finite cap the first request used to ask for `maxBytes + 1` bytes at
440
+ * once, which cancelled the windowing — an edit's diff basis, bounded at
441
+ * 10 MiB, arrived as one multi-megabyte frame however the unbounded read
442
+ * was chunked.
443
+ *
355
444
  * @param target - the resolved file.
356
445
  * @param signal - the caller's cancellation.
357
446
  * @param maxBytes - inclusive byte cap on the complete content.
447
+ * @param first - the first window, already read by a caller that sent it
448
+ * ahead of the stat's answer ({@link readWholePipelined}); the loop then
449
+ * continues from its end.
358
450
  * @returns the file's bytes.
359
451
  */
360
- async readWhole(target, signal, maxBytes = Number.MAX_SAFE_INTEGER) {
452
+ async readWhole(target, signal, maxBytes = Number.MAX_SAFE_INTEGER, first) {
361
453
  const linuxPath = uncToPosix(target.targetKey)?.linuxPath ?? target.displayPath;
362
454
  const chunks = [];
363
455
  let offset = 0;
456
+ let chunk = first?.chunk;
457
+ let window = first?.window ?? 0;
364
458
  for (;;) {
365
- throwIfAborted(signal, "read");
366
- const result = await this.request("read", [linuxPath, String(offset), String(maxBytes === Number.MAX_SAFE_INTEGER ? FS_READ_CHUNK_BYTES : maxBytes - offset + 1)], signal);
367
- if (result.exitCode !== 0)
368
- throw this.fail("read", result, target.displayPath);
369
- const chunk = result.stdout;
459
+ if (chunk === undefined) {
460
+ throwIfAborted(signal, "read");
461
+ window = Math.min(FS_READ_CHUNK_BYTES, maxBytes - offset + 1);
462
+ const result = await this.request("read", [linuxPath, String(offset), String(window)], signal);
463
+ if (result.exitCode !== 0)
464
+ throw this.fail("read", result, target.displayPath);
465
+ chunk = result.stdout;
466
+ }
370
467
  if (chunk.length === 0)
371
468
  break;
372
469
  chunks.push(chunk);
@@ -374,8 +471,10 @@ export class DistroFs {
374
471
  if (offset > maxBytes) {
375
472
  throw new FsCodedError(`cannot read "${target.displayPath}": content exceeds the ${maxBytes}-byte limit`, "FS_TOO_LARGE");
376
473
  }
377
- if (chunk.length < FS_READ_CHUNK_BYTES)
474
+ // A short window is the end of the file.
475
+ if (chunk.length < window)
378
476
  break;
477
+ chunk = undefined;
379
478
  }
380
479
  return Buffer.concat(chunks, offset);
381
480
  }
@@ -387,7 +486,7 @@ export class DistroFs {
387
486
  * @returns the full decoded text, byte-for-byte.
388
487
  */
389
488
  async readWholeText(target, signal) {
390
- const raw = this.supportsBatch() ? await this.readWholeBatched(target, signal) : await this.statThenReadWhole(target, signal);
489
+ const raw = this.supportsBatch() ? await this.readWholePipelined(target, signal) : await this.statThenReadWhole(target, signal);
391
490
  if (raw.subarray(0, BINARY_SAMPLE_BYTES).includes(0)) {
392
491
  throw new FsCodedError(`cannot read "${target.displayPath}": binary file`, "FS_NOT_TEXT");
393
492
  }
@@ -406,55 +505,39 @@ export class DistroFs {
406
505
  return this.readWhole(target, signal);
407
506
  }
408
507
  /**
409
- * The protocol-7 batch path for {@link readWholeText}: the stat and the
410
- * first read window ride ONE FSB frame — the GUI preview's dominant
411
- * shape — and further windows stay single reads.
508
+ * The protocol-7 road for {@link readWholeText}: the stat and the first
509
+ * read window go out together, each in its own frame, and neither answer
510
+ * is awaited until both are written.
511
+ *
512
+ * They used to share one batched frame. That put the window's bytes
513
+ * through base64 twice — once inside the batch's record and once around
514
+ * the whole record stream — for a read of 1 MiB: 40 ms against 25 ms for
515
+ * a plain read frame. Sending the two frames back to back keeps the one
516
+ * host round trip without it: a resident that serves requests concurrently
517
+ * runs them side by side, and a serial one already finds the second frame
518
+ * in its pipe when it finishes the first.
519
+ *
520
+ * The stat is still judged first. A target that is missing or not a regular
521
+ * file refuses through the stat's own failure, whatever the read answers —
522
+ * including a read that never answers, as one of a FIFO would not.
412
523
  *
413
524
  * @param target - the resolved file.
414
525
  * @param signal - aborts the read.
415
526
  * @returns the file's bytes.
416
527
  */
417
- async readWholeBatched(target, signal) {
528
+ async readWholePipelined(target, signal) {
418
529
  const linuxPath = uncToPosix(target.targetKey)?.linuxPath ?? target.displayPath;
419
- const records = await this.batch([
420
- { op: "stat", args: [linuxPath] },
421
- { op: "read", args: [linuxPath, "0", String(FS_READ_CHUNK_BYTES)] },
422
- ], signal);
423
- const statRecord = records[0];
424
- if (statRecord === undefined || !statRecord.ok) {
425
- if (statRecord !== undefined && !statRecord.ok) {
426
- if (statRecord.reason === "notfound")
427
- throw new FsCodedError(`cannot read "${target.displayPath}": not found`, "FS_NOT_FOUND");
428
- throw new FsCodedError(statRecord.message, reasonToCode(statRecord.reason));
429
- }
430
- throw new FsCodedError(`cannot read "${target.displayPath}": distro I/O failure`, "FS_IO_ERROR");
431
- }
432
- const info = parseStatRecord(statRecord.payload);
433
- if (info.type !== "f")
434
- throw new FsCodedError(`cannot read "${target.displayPath}": not a regular file`, "FS_NOT_REGULAR_FILE");
435
- const first = records[1];
436
- if (first === undefined || !first.ok) {
437
- if (first !== undefined && !first.ok)
438
- throw new FsCodedError(first.message, reasonToCode(first.reason));
439
- throw new FsCodedError(`cannot read "${target.displayPath}": distro I/O failure`, "FS_IO_ERROR");
440
- }
441
- const chunks = [];
442
- let offset = 0;
443
- let chunk = first.payload;
444
- for (;;) {
445
- if (chunk.length === 0)
446
- break;
447
- chunks.push(chunk);
448
- offset += chunk.length;
449
- if (chunk.length < FS_READ_CHUNK_BYTES)
450
- break;
451
- throwIfAborted(signal, "read");
452
- const result = await this.request("read", [linuxPath, String(offset), String(FS_READ_CHUNK_BYTES)], signal);
453
- if (result.exitCode !== 0)
454
- throw this.fail("read", result, target.displayPath);
455
- chunk = result.stdout;
456
- }
457
- return Buffer.concat(chunks, offset);
530
+ throwIfAborted(signal, "read");
531
+ const info = this.statRegularFile(target, "read", signal);
532
+ const read = this.request("read", [linuxPath, "0", String(FS_READ_CHUNK_BYTES)], signal);
533
+ // The read's rejection must not go unhandled when the stat's refusal is
534
+ // the one reported; `await read` below still sees it when it is not.
535
+ read.catch(() => { });
536
+ await info;
537
+ const first = await read;
538
+ if (first.exitCode !== 0)
539
+ throw this.fail("read", first, target.displayPath);
540
+ return this.readWhole(target, signal, Number.MAX_SAFE_INTEGER, { chunk: first.stdout, window: FS_READ_CHUNK_BYTES });
458
541
  }
459
542
  /**
460
543
  * Read a whole regular file as raw bytes, bounded by `maxBytes`.
@@ -693,15 +776,25 @@ export class DistroFs {
693
776
  * one (binary, at/above the bound, vanished), so the write still succeeds
694
777
  * and presentation falls back to a whole-file diff.
695
778
  *
779
+ * `known` is the stat the caller already made for its own guard: the write
780
+ * paths read the target once for type, mode and version, and this basis
781
+ * used to stat it a second time on every overwrite. The basis is best
782
+ * effort, so judging the bound from that earlier row (and letting a raced
783
+ * read degrade to null) is within its contract.
784
+ *
696
785
  * @param target - the resolved file.
697
786
  * @param maxBytes - exclusive upper bound for the held basis.
698
787
  * @param signal - cancellation propagates, unlike I/O failure.
788
+ * @param known - the caller's already-fetched stat row, or null when the
789
+ * target was known absent.
699
790
  * @returns the LF-normalized text, or null.
700
791
  */
701
- async readTextForDiff(target, maxBytes, signal) {
792
+ async readTextForDiff(target, maxBytes, signal, known) {
702
793
  throwIfAborted(signal, "read");
703
794
  try {
704
- const info = await this.stat(uncToPosix(target.targetKey)?.linuxPath ?? target.displayPath, { signal });
795
+ const info = known === undefined
796
+ ? await this.stat(uncToPosix(target.targetKey)?.linuxPath ?? target.displayPath, { signal })
797
+ : known;
705
798
  if (!info || info.type !== "f" || info.size >= maxBytes)
706
799
  return null;
707
800
  const raw = await this.readWhole(target, signal, maxBytes - 1);
package/lib/git-exec.d.ts CHANGED
@@ -15,7 +15,13 @@
15
15
  * The caps map onto the agent's single per-request capture ceiling as the
16
16
  * larger of the two stream budgets; the reader then slices each stream to its
17
17
  * own budget and reports `lossy` from that slice, so the caller's contract
18
- * (per-stream cut flags) holds even though the wire carries one cap.
18
+ * (per-stream cut flags) holds even though the wire carries one cap. A stream
19
+ * is lossy when the agent cut it at the wire cap OR when it runs past its own
20
+ * budget, and a cut keeps the TAIL — what the one-shot handle's own reader
21
+ * keeps (an in-memory tail window), so the last line of a failure survives
22
+ * on both transports. What the agent discarded is gone: the wire carries one
23
+ * cap, so a stream with the smaller budget can be cut beyond recovery before
24
+ * this reader sees it.
19
25
  *
20
26
  * Environment rides the agent's per-request `env` (an `env --` argv prefix —
21
27
  * no `SETENV` global pollution), holding only the translated `GIT_*` names:
package/lib/git-exec.js CHANGED
@@ -15,7 +15,13 @@
15
15
  * The caps map onto the agent's single per-request capture ceiling as the
16
16
  * larger of the two stream budgets; the reader then slices each stream to its
17
17
  * own budget and reports `lossy` from that slice, so the caller's contract
18
- * (per-stream cut flags) holds even though the wire carries one cap.
18
+ * (per-stream cut flags) holds even though the wire carries one cap. A stream
19
+ * is lossy when the agent cut it at the wire cap OR when it runs past its own
20
+ * budget, and a cut keeps the TAIL — what the one-shot handle's own reader
21
+ * keeps (an in-memory tail window), so the last line of a failure survives
22
+ * on both transports. What the agent discarded is gone: the wire carries one
23
+ * cap, so a stream with the smaller budget can be cut beyond recovery before
24
+ * this reader sees it.
19
25
  *
20
26
  * Environment rides the agent's per-request `env` (an `env --` argv prefix —
21
27
  * no `SETENV` global pollution), holding only the translated `GIT_*` names:
@@ -114,7 +120,9 @@ export function gitExecutionHandle({ agent, cwd, argv, env, stdin, caps, distro,
114
120
  readFrom(from) {
115
121
  const buffer = state[slot] ?? Buffer.alloc(0);
116
122
  const lossy = state.lossy[slot] || buffer.length > cap;
117
- const visible = lossy ? buffer.subarray(0, cap) : buffer;
123
+ // The tail, not the head: the one-shot delegate's reader is a tail
124
+ // window, and a git failure's cause is its LAST line.
125
+ const visible = lossy ? buffer.subarray(Math.max(0, buffer.length - cap)) : buffer;
118
126
  const start = Math.min(from, visible.length);
119
127
  return { text: visible.subarray(start).toString("utf8"), lossy, nextOffset: visible.length };
120
128
  },
@@ -205,6 +213,10 @@ export function gitExecutionHandle({ agent, cwd, argv, env, stdin, caps, distro,
205
213
  result = await agent.exec({ cwd, argv, env, stdin, maxOutputBytes: wireCap, signal: controller.signal });
206
214
  state.stdout = discovery ? translateDiscoveryOutput(distro, result.stdout) : result.stdout;
207
215
  state.stderr = result.stderr;
216
+ // The agent cut a stream at the wire cap. Its length then EQUALS the
217
+ // cap, so the length test in the reader cannot see it: a diff read as
218
+ // whole was missing every change past the cap.
219
+ state.lossy = { stdout: result.truncated?.stdout === true, stderr: result.truncated?.stderr === true };
208
220
  }
209
221
  catch (error) {
210
222
  if (controller.signal.aborted) {
@@ -15,6 +15,14 @@
15
15
  * failed copy falls back to the shell agent — this module never throws to the
16
16
  * command path.
17
17
  *
18
+ * A prepared backend is remembered; a failed preparation is not. It describes
19
+ * the machine as it is at that moment (a distro still starting, a cache
20
+ * directory not executable yet), and remembering it would keep the shell
21
+ * agent on a distro whose native binary works the moment the user fixes it —
22
+ * without the app restart nothing tells them to take. The reason of the last
23
+ * failure is kept for {@link nativeBackendFailure}, so a diagnosis can say
24
+ * why the reads run on the shell agent.
25
+ *
18
26
  * This is a TypeScript source built to `lib/native-agent.js`; edit THIS file
19
27
  * and run `pnpm run build` — the artifact under `lib/` is generated, and
20
28
  * `pnpm test` fails when it drifts.
@@ -60,16 +68,29 @@ interface NativeBackendResult {
60
68
  digest: string;
61
69
  }
62
70
  /**
63
- * Copy the binary into the distro and verify it. The result is cached per
64
- * `(wslPath, distro, source)`; a failure is cached as `undefined` for this
65
- * process (the caller falls back to the shell agent).
71
+ * Copy the binary into the distro and verify it. A success is cached per
72
+ * `(wslPath, distro, source, packageRoot)` for the process, and callers that
73
+ * arrive while one is in flight share it. A failure answers `undefined` to
74
+ * its callers and is then forgotten — the next call tries again — but its
75
+ * reason is kept for {@link nativeBackendFailure}.
66
76
  *
67
77
  * @param options - the transport, distro, source and injectables.
68
78
  * @returns the Linux binary path and digest, or undefined when unusable.
69
79
  */
70
80
  export declare function ensureNativeBackend({ wslPath, distro, source, packageRoot, readSource, run, copy, }: NativeBackendOptions): Promise<NativeBackendResult | undefined>;
71
81
  /**
72
- * Forget the cache; tests only.
82
+ * Why the native agent could not be prepared for a distro, for a diagnosis.
83
+ * The reads fall back to the shell agent either way; this says why they did.
84
+ *
85
+ * @param distro - the distro.
86
+ * @param wslPath - the `wsl.exe` the preparation used.
87
+ * @param source - the host-path override the preparation used.
88
+ * @returns the last failure's reason, or undefined while none is recorded
89
+ * (never attempted, or the last attempt succeeded).
90
+ */
91
+ export declare function nativeBackendFailure(distro: string, wslPath?: string, source?: string): string | undefined;
92
+ /**
93
+ * Forget the cache and the recorded failures; tests only.
73
94
  */
74
95
  export declare function clearNativeBackendCache(): void;
75
96
  /**
@@ -15,6 +15,14 @@
15
15
  * failed copy falls back to the shell agent — this module never throws to the
16
16
  * command path.
17
17
  *
18
+ * A prepared backend is remembered; a failed preparation is not. It describes
19
+ * the machine as it is at that moment (a distro still starting, a cache
20
+ * directory not executable yet), and remembering it would keep the shell
21
+ * agent on a distro whose native binary works the moment the user fixes it —
22
+ * without the app restart nothing tells them to take. The reason of the last
23
+ * failure is kept for {@link nativeBackendFailure}, so a diagnosis can say
24
+ * why the reads run on the shell agent.
25
+ *
18
26
  * This is a TypeScript source built to `lib/native-agent.js`; edit THIS file
19
27
  * and run `pnpm run build` — the artifact under `lib/` is generated, and
20
28
  * `pnpm test` fails when it drifts.
@@ -66,40 +74,75 @@ export function nativeCacheScript(digest) {
66
74
  ].join("\n");
67
75
  }
68
76
  /**
69
- * Copy the binary into the distro and verify it. The result is cached per
70
- * `(wslPath, distro, source)`; a failure is cached as `undefined` for this
71
- * process (the caller falls back to the shell agent).
77
+ * Copy the binary into the distro and verify it. A success is cached per
78
+ * `(wslPath, distro, source, packageRoot)` for the process, and callers that
79
+ * arrive while one is in flight share it. A failure answers `undefined` to
80
+ * its callers and is then forgotten — the next call tries again — but its
81
+ * reason is kept for {@link nativeBackendFailure}.
72
82
  *
73
83
  * @param options - the transport, distro, source and injectables.
74
84
  * @returns the Linux binary path and digest, or undefined when unusable.
75
85
  */
76
86
  export async function ensureNativeBackend({ wslPath, distro, source, packageRoot = PACKAGE_ROOT, readSource = readFile, run = (argv) => runCapture(argv), copy, }) {
77
- const key = `${wslPath}\u0000${distro}\u0000${source}\u0000${packageRoot}`;
87
+ const key = nativeCacheKey(wslPath, distro, source, packageRoot);
78
88
  const cached = NATIVE_CACHE.get(key);
79
89
  if (cached !== undefined)
80
90
  return cached;
81
91
  const pending = (async () => {
82
92
  const arch = (await run([wslPath, "-d", distro, "--exec", "uname", "-m"])).trim();
83
93
  const normalized = ARCHS.get(arch);
84
- if (normalized === undefined)
94
+ if (normalized === undefined) {
95
+ // Deterministic for the distro, so it stays cached — and it is the one
96
+ // failure the user cannot fix, which is why its reason says so.
97
+ NATIVE_FAILURES.set(key, `the distro reports the architecture "${arch}", for which no native agent is packaged (x86_64 and aarch64 are)`);
85
98
  return undefined;
99
+ }
86
100
  const hostPath = source.length > 0 ? source : join(packageRoot, "agent", "native", `linux-${normalized}`, "dsh-wsl-agent");
87
101
  const binary = await readSource(hostPath);
88
102
  const digest = createHash("sha256").update(binary).digest("hex");
89
103
  const install = copy ?? ((script, bytes) => copyBinary(wslPath, distro, script, bytes));
90
104
  const path = await install(nativeCacheScript(digest), binary);
91
- return path.length > 0 ? { path, digest } : undefined;
92
- })().catch(() => undefined);
105
+ if (path.length === 0) {
106
+ NATIVE_FAILURES.set(key, "the copy/verify script printed no cache path");
107
+ return undefined;
108
+ }
109
+ NATIVE_FAILURES.delete(key);
110
+ return { path, digest };
111
+ })().catch((error) => {
112
+ // Not a verdict: the entry leaves the cache, so the next start tries
113
+ // again. Only the reason stays.
114
+ NATIVE_FAILURES.set(key, error instanceof Error ? error.message : String(error));
115
+ NATIVE_CACHE.delete(key);
116
+ return undefined;
117
+ });
93
118
  NATIVE_CACHE.set(key, pending);
94
119
  return pending;
95
120
  }
96
- /** The per-process cache; a failure is remembered as undefined. */
121
+ /** The per-process cache: a preparation in flight, or one that succeeded. */
97
122
  const NATIVE_CACHE = new Map();
123
+ /** Why the last preparation of a cache key failed, until one succeeds. */
124
+ const NATIVE_FAILURES = new Map();
125
+ /** The cache key of one `(wslPath, distro, source, packageRoot)`. */
126
+ const nativeCacheKey = (wslPath, distro, source, packageRoot = PACKAGE_ROOT) => `${wslPath}\u0000${distro}\u0000${source}\u0000${packageRoot}`;
127
+ /**
128
+ * Why the native agent could not be prepared for a distro, for a diagnosis.
129
+ * The reads fall back to the shell agent either way; this says why they did.
130
+ *
131
+ * @param distro - the distro.
132
+ * @param wslPath - the `wsl.exe` the preparation used.
133
+ * @param source - the host-path override the preparation used.
134
+ * @returns the last failure's reason, or undefined while none is recorded
135
+ * (never attempted, or the last attempt succeeded).
136
+ */
137
+ export function nativeBackendFailure(distro, wslPath = "wsl.exe", source = process.env[NATIVE_AGENT_ENV] ?? "") {
138
+ return NATIVE_FAILURES.get(nativeCacheKey(wslPath, distro, source));
139
+ }
98
140
  /**
99
- * Forget the cache; tests only.
141
+ * Forget the cache and the recorded failures; tests only.
100
142
  */
101
143
  export function clearNativeBackendCache() {
102
144
  NATIVE_CACHE.clear();
145
+ NATIVE_FAILURES.clear();
103
146
  }
104
147
  /**
105
148
  * Stream the binary to the distro on stdin, run the copy/verify script and
package/lib/picker.d.ts CHANGED
@@ -182,7 +182,8 @@ export declare class WslDirectoryPicker extends DirectoryPicker {
182
182
  /**
183
183
  * A distro's Linux home directory as a UNC path, best effort: a distro that
184
184
  * cannot be queried (stopped, and unable to start) falls back to its root so
185
- * the dialog still opens somewhere real.
185
+ * the dialog still opens somewhere real. Only a real answer is cached; the
186
+ * fallback is retried on the next call.
186
187
  *
187
188
  * @param distro - distro name.
188
189
  * @param signal - optional cancellation.
package/lib/picker.js CHANGED
@@ -247,7 +247,8 @@ export class WslDirectoryPicker extends DirectoryPicker {
247
247
  /**
248
248
  * A distro's Linux home directory as a UNC path, best effort: a distro that
249
249
  * cannot be queried (stopped, and unable to start) falls back to its root so
250
- * the dialog still opens somewhere real.
250
+ * the dialog still opens somewhere real. Only a real answer is cached; the
251
+ * fallback is retried on the next call.
251
252
  *
252
253
  * @param distro - distro name.
253
254
  * @param signal - optional cancellation.
@@ -262,7 +263,10 @@ export class WslDirectoryPicker extends DirectoryPicker {
262
263
  home = await linuxHome(distro, { wslPath: this.config.wslPath, signal });
263
264
  }
264
265
  catch {
265
- home = distroRoot(distro);
266
+ // A failed probe is not an answer: caching the root fallback made a
267
+ // distro that was briefly unavailable look home-less for the rest of the
268
+ // process. Return the fallback this once and probe again next time.
269
+ return distroRoot(distro);
266
270
  }
267
271
  this.homeCache.set(distro, home);
268
272
  return home;
@@ -388,21 +392,34 @@ export class WslDirectoryPicker extends DirectoryPicker {
388
392
  throw new DirectoryPickerError("directory-unreadable", path, `cannot list "${path}": not a fully qualified path`);
389
393
  }
390
394
  const target = resolve(path);
391
- // A host directory must list even when WSL itself is unusable (not
392
- // installed, or `wsl.exe` failing): the preferred distro is only the
393
- // dialog's Home affordance here. A cancelled call still cancels.
394
- let preferred = "";
395
+ // The listing and the Home affordance are independent: the distro query
396
+ // (and the home probe behind it) only feeds `home`, and awaiting it first
397
+ // made every level wait for the distro enumeration before the walk even
398
+ // started. A broken WSL still must not stop a host directory from
399
+ // listing, so the preferred-distro failure is swallowed here; a cancelled
400
+ // call still cancels.
401
+ const levelPromise = isWslUnc(target) ? this.listDistroLevel(target, signal) : this.listHostLevel(target, signal);
402
+ const preferredPromise = this.preferredDistro(signal).catch((error) => {
403
+ if (signal?.aborted)
404
+ throw error;
405
+ return "";
406
+ });
407
+ const homePromise = preferredPromise.then((preferred) => (preferred.length > 0 ? this.homeOf(preferred, signal) : homedir()));
408
+ // The listing can fail first; the background Home lookup must not become
409
+ // an unhandled rejection when nobody awaits it.
410
+ homePromise.catch(() => { });
411
+ let level;
395
412
  try {
396
- preferred = await this.preferredDistro(signal);
413
+ level = await levelPromise;
397
414
  }
398
415
  catch (error) {
399
- if (signal?.aborted)
400
- throw error;
416
+ preferredPromise.catch(() => { });
417
+ throw error;
401
418
  }
402
- const level = isWslUnc(target) ? await this.listDistroLevel(target, signal) : await this.listHostLevel(target, signal);
419
+ const home = await homePromise;
403
420
  return {
404
421
  path: target,
405
- home: preferred.length > 0 ? await this.homeOf(preferred, signal) : homedir(),
422
+ home,
406
423
  crumbs: this.crumbsFor(target),
407
424
  entries: level.rows,
408
425
  truncated: level.truncated,
@@ -428,7 +445,7 @@ export class WslDirectoryPicker extends DirectoryPicker {
428
445
  const linuxDir = parsed.linuxPath.length > 0 ? parsed.linuxPath : "/";
429
446
  let stdout;
430
447
  try {
431
- const result = await sharedAgent(parsed.distro).exec({
448
+ const result = await sharedAgent(parsed.distro, this.config.wslPath).exec({
432
449
  cwd: linuxDir,
433
450
  argv: dirListingArgv(linuxDir),
434
451
  timeoutMs: 15_000,
@@ -564,7 +581,7 @@ export class WslDirectoryPicker extends DirectoryPicker {
564
581
  const parsed = uncToPosix(parent);
565
582
  const linuxParent = parsed.linuxPath.length > 0 ? parsed.linuxPath : "/";
566
583
  try {
567
- const result = await sharedAgent(parsed.distro).exec({
584
+ const result = await sharedAgent(parsed.distro, this.config.wslPath).exec({
568
585
  cwd: linuxParent,
569
586
  argv: distroMkdirArgv(linuxParent, name),
570
587
  timeoutMs: 10_000,