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
@@ -8,6 +8,18 @@
8
8
  * behind). The agent runs with no idle close — its lifetime is the session's —
9
9
  * but an explicit client lease still catches a wedged host.
10
10
  *
11
+ * The session's end is the harness's `agent/disposed`: a provider in the
12
+ * preset's realm hears it (rows there inherit the preset scope's tag, and
13
+ * agent events flow up the scope chain), and calls {@link
14
+ * SessionRuntimes.releaseSession}, which tears the session's runtimes down
15
+ * however many references they carry. Each holder drops its own book for the
16
+ * session on the same event, before it calls — and a holder that finds the
17
+ * registry no longer keeps an entry it cached ({@link SessionRuntimes.holds})
18
+ * acquires afresh rather than reusing a closed agent. The preset's own scope
19
+ * is NOT the session's: upstream disposes it only when the preset definition
20
+ * is unregistered, so a disposer registered by a provider there runs once per
21
+ * process, never once per session.
22
+ *
11
23
  * The confinement here is the agent's own bwrap mount profile, WITHOUT a PID
12
24
  * namespace: commands are the agent's children, so a background process
13
25
  * survives the command, `/tmp` is the distro's real `/tmp` under
@@ -164,7 +176,8 @@ export class SessionRuntimes {
164
176
  * @returns the live entry; the caller holds one reference.
165
177
  */
166
178
  acquire(request) {
167
- const key = SessionRuntimes.key({ ...request, sessionId: request.sessionId || defaultToken() });
179
+ const sessionId = request.sessionId || defaultToken();
180
+ const key = SessionRuntimes.key({ ...request, sessionId });
168
181
  const existing = this.runtimes.get(key);
169
182
  if (existing !== undefined) {
170
183
  existing.refs += 1;
@@ -184,7 +197,7 @@ export class SessionRuntimes {
184
197
  leaseMs: request.leaseMs ?? 0,
185
198
  signalable: true,
186
199
  });
187
- const entry = { key, unit, agent, distro: request.distro, wslPath, refs: 1 };
200
+ const entry = { key, unit, agent, distro: request.distro, wslPath, refs: 1, sessionId };
188
201
  this.runtimes.set(key, entry);
189
202
  return entry;
190
203
  }
@@ -204,6 +217,44 @@ export class SessionRuntimes {
204
217
  if (entry.refs > 0)
205
218
  return;
206
219
  this.runtimes.delete(key);
220
+ await this.teardown(entry);
221
+ }
222
+ /**
223
+ * Whether the registry still keeps THIS entry. A holder caches the entry it
224
+ * acquired; a session end tears the entry down whatever references remain,
225
+ * so a holder that did not drop its cache itself asks here before reusing
226
+ * it — a closed agent must never be handed out as a live runtime.
227
+ *
228
+ * @param entry - the entry the holder cached.
229
+ * @returns true while the registry tracks that exact entry.
230
+ */
231
+ holds(entry) {
232
+ return this.runtimes.get(entry.key) === entry;
233
+ }
234
+ /**
235
+ * End one session. Every runtime it named is torn down regardless of its
236
+ * reference count: the session is over, and a reference nobody will release
237
+ * again is not a reason to keep a scope. Holders drop their own books on the
238
+ * same event; a holder that did not notices through {@link
239
+ * SessionRuntimes.holds}. Idempotent: a second call finds nothing.
240
+ *
241
+ * @param sessionId - the session that ended.
242
+ * @returns resolved once every runtime of the session is torn down.
243
+ */
244
+ async releaseSession(sessionId) {
245
+ for (const [key, entry] of [...this.runtimes]) {
246
+ if (entry.sessionId !== sessionId)
247
+ continue;
248
+ this.runtimes.delete(key);
249
+ await this.teardown(entry);
250
+ }
251
+ }
252
+ /**
253
+ * Tear one runtime down: close the agent, then stop the scope.
254
+ *
255
+ * @param entry - the runtime, already removed from the map.
256
+ */
257
+ async teardown(entry) {
207
258
  try {
208
259
  await entry.agent.close();
209
260
  }
@@ -218,11 +269,10 @@ export class SessionRuntimes {
218
269
  * @returns resolved once every runtime is torn down.
219
270
  */
220
271
  async disposeAll() {
221
- for (const key of [...this.runtimes.keys()]) {
222
- const entry = this.runtimes.get(key);
223
- if (entry !== undefined)
224
- entry.refs = 1;
225
- await this.release(key);
272
+ // Session by session, through the same door a session end takes: the
273
+ // holders are told, so no provider's book names a runtime that is gone.
274
+ for (const sessionId of new Set([...this.runtimes.values()].map((entry) => entry.sessionId))) {
275
+ await this.releaseSession(sessionId);
226
276
  }
227
277
  }
228
278
  }
@@ -19,6 +19,13 @@
19
19
  *
20
20
  * @module dsh-plugin-wsl-env/session-scope
21
21
  */
22
+ /**
23
+ * How long a `dsh-wsl-*.scope` may stay agent-less before the sweep may stop
24
+ * it. `systemd-run --scope` creates the unit before it execs the agent, so a
25
+ * scope that is merely starting has an empty cgroup for a moment; the sweep
26
+ * must not mistake that for a crash leftover.
27
+ */
28
+ export declare const SCOPE_STARTUP_GRACE_SECONDS = 120;
22
29
  /**
23
30
  * Build the systemd user unit name for one session runtime.
24
31
  *
@@ -51,6 +58,13 @@ export declare function sessionScopePrefix(unit: string): string[];
51
58
  * cleanup step that replaces the per-command PID namespace: the cgroup kills
52
59
  * every descendant, including a background dev server a command left behind.
53
60
  *
61
+ * The stop names the `.scope` unit systemd creates: `systemd-run --scope`
62
+ * appends that suffix to {@link sessionScopeUnit}'s bare name, while
63
+ * `systemctl stop` resolves a suffix-less name as a `.service` — never
64
+ * loaded, so the stop exits 5 and the scope outlives the session. (Without a
65
+ * background process the scope dies with its agent anyway, which is why only
66
+ * a session that leaves one shows the difference.)
67
+ *
54
68
  * @param options - the transport path, distro and unit name.
55
69
  * @returns the `wsl.exe --exec systemctl --user stop` argv.
56
70
  */
@@ -59,7 +73,7 @@ export declare function sessionScopeStopArgv({ wslPath, distro, unit }: {
59
73
  wslPath: string;
60
74
  /** The distro name; empty means the default distro. */
61
75
  distro: string;
62
- /** The unit name from {@link sessionScopeUnit}. */
76
+ /** The bare unit name from {@link sessionScopeUnit}, exactly as it was started with. */
63
77
  unit: string;
64
78
  }): string[];
65
79
  /**
@@ -89,6 +103,13 @@ export declare function sessionScopeProbeScript(): string;
89
103
  * can prove stale; if there is no user manager it exits 0 (the session
90
104
  * preflight reports that condition separately).
91
105
  *
106
+ * Two checks keep a scope that is still starting from being swept: an
107
+ * unreadable `cgroup.procs` says nothing (the cgroup may not exist yet), and
108
+ * a unit younger than {@link SCOPE_STARTUP_GRACE_SECONDS} is left alone —
109
+ * `systemd-run --scope` creates the unit before exec'ing the agent, so its
110
+ * `cgroup.procs` is briefly empty. Only a scope older than that with no agent
111
+ * in its cgroup is provably stale.
112
+ *
92
113
  * @returns the shell script.
93
114
  */
94
115
  export declare function sessionScopeSweepScript(): string;
@@ -22,6 +22,13 @@
22
22
  import { t } from "./messages.js";
23
23
  /** The longest piece of a unit name this builder emits, per component. */
24
24
  const MAX_COMPONENT = 64;
25
+ /**
26
+ * How long a `dsh-wsl-*.scope` may stay agent-less before the sweep may stop
27
+ * it. `systemd-run --scope` creates the unit before it execs the agent, so a
28
+ * scope that is merely starting has an empty cgroup for a moment; the sweep
29
+ * must not mistake that for a crash leftover.
30
+ */
31
+ export const SCOPE_STARTUP_GRACE_SECONDS = 120;
25
32
  /**
26
33
  * Characters systemd accepts in a unit name; everything else is folded to `_`.
27
34
  * The allowed set is `[A-Za-z0-9:_.\-]`; `:` is legal in unit names but not
@@ -76,6 +83,13 @@ export function sessionScopePrefix(unit) {
76
83
  * cleanup step that replaces the per-command PID namespace: the cgroup kills
77
84
  * every descendant, including a background dev server a command left behind.
78
85
  *
86
+ * The stop names the `.scope` unit systemd creates: `systemd-run --scope`
87
+ * appends that suffix to {@link sessionScopeUnit}'s bare name, while
88
+ * `systemctl stop` resolves a suffix-less name as a `.service` — never
89
+ * loaded, so the stop exits 5 and the scope outlives the session. (Without a
90
+ * background process the scope dies with its agent anyway, which is why only
91
+ * a session that leaves one shows the difference.)
92
+ *
79
93
  * @param options - the transport path, distro and unit name.
80
94
  * @returns the `wsl.exe --exec systemctl --user stop` argv.
81
95
  */
@@ -87,7 +101,7 @@ export function sessionScopeStopArgv({ wslPath, distro, unit }) {
87
101
  "systemctl",
88
102
  "--user",
89
103
  "stop",
90
- unit,
104
+ `${unit}.scope`,
91
105
  ];
92
106
  }
93
107
  /**
@@ -126,6 +140,13 @@ export function sessionScopeProbeScript() {
126
140
  * can prove stale; if there is no user manager it exits 0 (the session
127
141
  * preflight reports that condition separately).
128
142
  *
143
+ * Two checks keep a scope that is still starting from being swept: an
144
+ * unreadable `cgroup.procs` says nothing (the cgroup may not exist yet), and
145
+ * a unit younger than {@link SCOPE_STARTUP_GRACE_SECONDS} is left alone —
146
+ * `systemd-run --scope` creates the unit before exec'ing the agent, so its
147
+ * `cgroup.procs` is briefly empty. Only a scope older than that with no agent
148
+ * in its cgroup is provably stale.
149
+ *
129
150
  * @returns the shell script.
130
151
  */
131
152
  export function sessionScopeSweepScript() {
@@ -136,13 +157,18 @@ export function sessionScopeSweepScript() {
136
157
  ' [ -n "$unit" ] || continue',
137
158
  ' cg=$(systemctl --user show -p ControlGroup --value "$unit" 2>/dev/null)',
138
159
  ' [ -n "$cg" ] || continue',
160
+ ' [ -r "/sys/fs/cgroup$cg/cgroup.procs" ] || continue',
161
+ ' started=$(systemctl --user show -p ActiveEnterTimestampMonotonic --value "$unit" 2>/dev/null)',
162
+ ' case "$started" in ""|*[!0-9]*) continue;; esac',
163
+ ' [ "$started" -gt 0 ] || continue',
164
+ " now=$(awk '{ printf \"%.0f\", $1 * 1000000 }' /proc/uptime 2>/dev/null) || continue",
165
+ ' [ -n "$now" ] || continue',
166
+ ' [ $((now - started)) -ge ' + String(SCOPE_STARTUP_GRACE_SECONDS * 1_000_000) + ' ] || continue',
139
167
  ' alive=0',
140
- ' if [ -r "/sys/fs/cgroup$cg/cgroup.procs" ]; then',
141
- ' while read -r pid; do',
142
- ' [ -n "$pid" ] || continue',
143
- " if tr '\\0' ' ' < \"/proc/$pid/cmdline\" 2>/dev/null | grep -q -e 'wsl-agent.sh' -e 'dsh-wsl-agent'; then alive=1; break; fi",
144
- ' done < "/sys/fs/cgroup$cg/cgroup.procs"',
145
- ' fi',
168
+ ' while read -r pid; do',
169
+ ' [ -n "$pid" ] || continue',
170
+ " if tr '\\0' ' ' < \"/proc/$pid/cmdline\" 2>/dev/null | grep -q -e 'wsl-agent.sh' -e 'dsh-wsl-agent'; then alive=1; break; fi",
171
+ ' done < "/sys/fs/cgroup$cg/cgroup.procs"',
146
172
  ' [ "$alive" -eq 1 ] || systemctl --user stop "$unit" >/dev/null 2>&1 || true',
147
173
  'done',
148
174
  'exit 0',
package/lib/shell-env.js CHANGED
@@ -30,7 +30,7 @@ import z from "@deepseek-ai/schemastery";
30
30
  import { uncToPosix } from "./paths.js";
31
31
  import { fileURLToPath } from "node:url";
32
32
  import { dirname, join } from "node:path";
33
- import { defaultDistro, defaultShell, linuxHomePath, listDistros } from "./wsl.js";
33
+ import { defaultDistro, defaultShell, linuxHomePath, listDistros, listRunningDistros } from "./wsl.js";
34
34
  import { isDefaultDistro, pinnedDistro } from "./distro-route.js";
35
35
  import { sharedAgent } from "./agent-shared.js";
36
36
  import { scanListeningPorts } from "./ports.js";
@@ -70,7 +70,18 @@ export function doctorFact(execPath, pluginRoot, isWindows = process.platform ==
70
70
  const script = join(pluginRoot, "scripts", "doctor.mjs");
71
71
  const existing = process.env.WSLENV;
72
72
  const wslenv = existing !== undefined && existing.length > 0 ? `ELECTRON_RUN_AS_NODE:${existing}` : "ELECTRON_RUN_AS_NODE";
73
- return `WSLENV="${wslenv}" ELECTRON_RUN_AS_NODE=1 '${windowsToPosix(execPath)}' '${script}'`;
73
+ return `WSLENV="${wslenv}" ELECTRON_RUN_AS_NODE=1 ${posixQuote(windowsToPosix(execPath))} ${posixQuote(script)}`;
74
+ }
75
+ /**
76
+ * Quote one value for a POSIX shell. A lone apostrophe would otherwise end
77
+ * the quoted string early — a path may legally contain one, and the whole
78
+ * command then fails with a syntax error instead of running the doctor.
79
+ *
80
+ * @param value - the raw value.
81
+ * @returns the value in single quotes with embedded apostrophes escaped.
82
+ */
83
+ function posixQuote(value) {
84
+ return `'${value.replace(/'/g, "'\\''")}'`;
74
85
  }
75
86
  export const name = "wsl-shell-env";
76
87
  export const inject = ["shellEnv"];
@@ -119,6 +130,18 @@ export async function apply(ctx, config = {}) {
119
130
  }
120
131
  }
121
132
  const defaultName = distros[0];
133
+ /**
134
+ * The spelling this row uses for one distro: the listed name when WSL knows
135
+ * it, the input otherwise. `facts`, the port timers and the snapshots are
136
+ * keyed by it, so two casings of one distro must not become two entries.
137
+ *
138
+ * @param name - the distro name as a session or the config spelled it.
139
+ * @returns the canonical spelling.
140
+ */
141
+ const canonicalDistro = (name) => {
142
+ const normalized = name.toLowerCase();
143
+ return distros.find((known) => known.toLowerCase() === normalized) ?? name;
144
+ };
122
145
  /** The facts one distro can answer; a failed probe leaves its key absent. */
123
146
  const facts = new Map();
124
147
  const inflight = new Set();
@@ -131,7 +154,13 @@ export async function apply(ctx, config = {}) {
131
154
  defaultShell(distro),
132
155
  linuxHomePath(distro).catch(() => undefined),
133
156
  ]);
134
- facts.set(distro, { shell, home });
157
+ // A probe that failed leaves NO key behind: the comment above promises
158
+ // that, and caching an all-undefined entry made one transient failure
159
+ // permanent for the process (no DSH_WSL_SHELL/DSH_WSL_HOME until a
160
+ // restart). A partial answer is still worth caching.
161
+ if (shell !== undefined || home !== undefined) {
162
+ facts.set(distro, { ...(shell === undefined ? {} : { shell }), ...(home === undefined ? {} : { home }) });
163
+ }
135
164
  }
136
165
  finally {
137
166
  inflight.delete(distro);
@@ -152,7 +181,7 @@ export async function apply(ctx, config = {}) {
152
181
  description: "Home directory of the user model shell calls run as inside that distro.",
153
182
  },
154
183
  DSH_WSL_PORTS: {
155
- description: `Ports with a listener inside that distro (comma-separated, ascending), as of the last snapshot — refreshed every ${Math.round(portsRefreshMs / 1000)}s, so a dev server started moments ago may not be listed yet. Empty means none were listening at the last successful scan (or no scan has succeeded yet); a failed scan keeps the last successful list.`,
184
+ description: `Ports with a listener inside that distro (comma-separated, ascending), as of the last snapshot — refreshed every ${Math.round(portsRefreshMs / 1000)}s while the distro runs and a session works in it, so a dev server started moments ago may not be listed yet. Empty means none were listening at the last successful scan, the distro was not running, or no scan has succeeded yet; a failed scan keeps the last successful list.`,
156
185
  },
157
186
  DSH_WSL_PLUGIN_UPDATE: {
158
187
  description: "A newer release of this plugin (dsh-plugin-wsl-env), as of the last update check — checked against the registry about once a day. Empty means the installed version is current (or the check has not run yet). Upgrade from the sidebar WSL environment panel's version card (one-click upgrade), or from the Plugins page's Versions section; restart DSH or reload the page when the host reports it.",
@@ -163,12 +192,27 @@ export async function apply(ctx, config = {}) {
163
192
  };
164
193
  // The port snapshot refreshes on a timer and is served synchronously: the
165
194
  // registry's resolve is sync by contract, so live reads are impossible —
166
- // the timer bounds staleness instead (see lib/ports.js). A timer starts only
167
- // for a distro a session actually uses, so multi-distro users do not keep
168
- // every distro's resident agent warm.
195
+ // the timer bounds staleness instead (see lib/ports.js). A timer runs only
196
+ // for a distro a live session works in, so multi-distro users do not keep
197
+ // every distro's resident agent warm — and when the last session that used
198
+ // a distro is gone, its timer goes with it, and with it the scans that
199
+ // kept that resident from ever idling out.
169
200
  const ports = new Map();
170
201
  const timers = new Map();
202
+ /** The scans in flight, by distro: a slow one is not overlapped by the next tick. */
203
+ const scanning = new Set();
204
+ /**
205
+ * Distros asked for since the last tick. Each gets one running-checked scan
206
+ * whatever the live-agent list says of it: a session may resolve its
207
+ * environment before the list carries it.
208
+ */
209
+ const requested = new Set();
171
210
  const refreshPorts = async (distro) => {
211
+ // The scan has an 8 s budget and the default interval is 10 s; on a slow
212
+ // distro the next tick used to start a second scan beside the first.
213
+ if (scanning.has(distro))
214
+ return;
215
+ scanning.add(distro);
172
216
  try {
173
217
  const next = await scanListeningPorts(sharedAgent(distro), 8000);
174
218
  if (next === undefined) {
@@ -182,14 +226,82 @@ export async function apply(ctx, config = {}) {
182
226
  catch {
183
227
  // Same posture as a failed scan: keep the last successful list.
184
228
  }
229
+ finally {
230
+ scanning.delete(distro);
231
+ }
232
+ };
233
+ /**
234
+ * The distros live sessions work in, lower-cased; undefined when the agent
235
+ * registry cannot be read, which is taken as "every polled distro is in
236
+ * use" — an unreadable fact must not silence a working poller.
237
+ */
238
+ const sessionDistros = () => {
239
+ const live = ctx.get("agents");
240
+ if (typeof live?.list !== "function")
241
+ return undefined;
242
+ const active = new Set();
243
+ for (const agent of live.list()) {
244
+ const parsed = uncToPosix(String(agent?.session?.header?.cwd ?? ""));
245
+ if (parsed !== undefined)
246
+ active.add(parsed.distro.toLowerCase());
247
+ }
248
+ return active;
249
+ };
250
+ /** Stop polling a distro; its last snapshot stays readable. */
251
+ const stopPorts = (distro) => {
252
+ const timer = timers.get(distro);
253
+ if (timer !== undefined)
254
+ clearInterval(timer);
255
+ timers.delete(distro);
256
+ };
257
+ let ticking = false;
258
+ /**
259
+ * One refresh round for every polled distro. Pollers without a live session
260
+ * are dropped first; then WSL is asked, once, which distros are running —
261
+ * a probe is a `wsl.exe -d <distro>`, which BOOTS a stopped distro, so one
262
+ * the user terminated is left alone and reads as having no listeners.
263
+ */
264
+ const tick = async () => {
265
+ if (ticking)
266
+ return;
267
+ ticking = true;
268
+ try {
269
+ const active = sessionDistros();
270
+ for (const distro of [...timers.keys()]) {
271
+ if (requested.has(distro) || active === undefined || active.has(distro.toLowerCase()))
272
+ continue;
273
+ stopPorts(distro);
274
+ }
275
+ requested.clear();
276
+ if (timers.size === 0)
277
+ return;
278
+ let running;
279
+ try {
280
+ running = new Set((await listRunningDistros()).map((name) => name.toLowerCase()));
281
+ }
282
+ catch {
283
+ // WSL did not answer: probe as before rather than guess a distro stopped.
284
+ }
285
+ for (const distro of [...timers.keys()]) {
286
+ if (running !== undefined && !running.has(distro.toLowerCase())) {
287
+ ports.set(distro, []);
288
+ continue;
289
+ }
290
+ void refreshPorts(distro);
291
+ }
292
+ }
293
+ finally {
294
+ ticking = false;
295
+ }
185
296
  };
186
297
  const ensurePorts = (distro) => {
298
+ requested.add(distro);
187
299
  if (timers.has(distro))
188
300
  return;
189
- void refreshPorts(distro);
190
- const timer = setInterval(() => void refreshPorts(distro), portsRefreshMs);
301
+ const timer = setInterval(() => void tick(), portsRefreshMs);
191
302
  timer.unref?.();
192
303
  timers.set(distro, timer);
304
+ void tick();
193
305
  };
194
306
  const lifecycle = ctx;
195
307
  const consider = (agent) => {
@@ -200,8 +312,9 @@ export async function apply(ctx, config = {}) {
200
312
  return;
201
313
  if (isDefaultDistro(configured) && defaultName !== undefined && parsed.distro.toLowerCase() !== defaultName.toLowerCase())
202
314
  return;
203
- void ensureFacts(parsed.distro);
204
- ensurePorts(parsed.distro);
315
+ const distro = canonicalDistro(parsed.distro);
316
+ void ensureFacts(distro);
317
+ ensurePorts(distro);
205
318
  };
206
319
  const off = lifecycle.on?.("agent/created", (payload) => consider(payload?.agent));
207
320
  // The live-agent sweep is a convenience, not a dependency: `inject` names
@@ -226,7 +339,7 @@ export async function apply(ctx, config = {}) {
226
339
  return {};
227
340
  if (isDefaultDistro(configured) && defaultName !== undefined && named.toLowerCase() !== defaultName.toLowerCase())
228
341
  return {};
229
- const canonical = [...facts.keys()].find((distro) => distro.toLowerCase() === named.toLowerCase()) ?? named;
342
+ const canonical = canonicalDistro(named);
230
343
  const doctorCommand = doctorFactValue ?? doctorFact(process.execPath, dirname(dirname(fileURLToPath(import.meta.url))));
231
344
  doctorFactValue = doctorCommand;
232
345
  const known = facts.get(canonical);
@@ -20,9 +20,9 @@
20
20
  * 3. {@link socketMaskPaths} maps a mode plus facts to the absolute paths
21
21
  * bwrap binds `/dev/null` over.
22
22
  * 4. {@link socketMasksFor} runs the probe once per `(wslPath, distro)` and
23
- * caches the facts; a probe failure is thrown, never read as "nothing to
24
- * mask" — a configured isolation that silently disappears is worse than
25
- * no isolation.
23
+ * keeps the facts for a short TTL; a probe failure is thrown, never read
24
+ * as "nothing to mask" — a configured isolation that silently disappears
25
+ * is worse than no isolation.
26
26
  *
27
27
  * The masks are a narrowing, not a closure. The distro user's other IPC
28
28
  * (`/proc`, a same-user process's sockets, the interop transport) remains;
@@ -84,11 +84,19 @@ export declare function parseSocketIsolationFacts(text: string): SocketIsolation
84
84
  * @returns the masks, deduplicated; empty for `off`.
85
85
  */
86
86
  export declare function socketMaskPaths(mode: SocketIsolation, facts: SocketIsolationFacts): string[];
87
+ /**
88
+ * How long resolved facts stay fresh. A daemon started after the first
89
+ * confined command (docker, podman, the user manager) adds a socket that a
90
+ * process-lifetime cache would never mask; the TTL bounds that window while
91
+ * still keeping a burst of commands to one probe.
92
+ */
93
+ export declare const SOCKET_FACTS_TTL_MS = 60000;
87
94
  /** Test hook: forget the remembered facts. */
88
95
  export declare function resetSocketIsolationCache(): void;
89
96
  /**
90
97
  * Resolve the socket masks for one distro and stance, running the in-distro
91
- * probe once per `(wslPath, distro)`.
98
+ * probe once per `(wslPath, distro)` and re-running it after
99
+ * {@link SOCKET_FACTS_TTL_MS} so a socket that appears later is masked too.
92
100
  *
93
101
  * @param options - the stance, transport, distro and host runner.
94
102
  * @returns the masks; empty for `off`.
@@ -20,9 +20,9 @@
20
20
  * 3. {@link socketMaskPaths} maps a mode plus facts to the absolute paths
21
21
  * bwrap binds `/dev/null` over.
22
22
  * 4. {@link socketMasksFor} runs the probe once per `(wslPath, distro)` and
23
- * caches the facts; a probe failure is thrown, never read as "nothing to
24
- * mask" — a configured isolation that silently disappears is worse than
25
- * no isolation.
23
+ * keeps the facts for a short TTL; a probe failure is thrown, never read
24
+ * as "nothing to mask" — a configured isolation that silently disappears
25
+ * is worse than no isolation.
26
26
  *
27
27
  * The masks are a narrowing, not a closure. The distro user's other IPC
28
28
  * (`/proc`, a same-user process's sockets, the interop transport) remains;
@@ -120,6 +120,13 @@ export function socketMaskPaths(mode, facts) {
120
120
  paths.push(...facts.strictSockets);
121
121
  return [...new Set(paths)];
122
122
  }
123
+ /**
124
+ * How long resolved facts stay fresh. A daemon started after the first
125
+ * confined command (docker, podman, the user manager) adds a socket that a
126
+ * process-lifetime cache would never mask; the TTL bounds that window while
127
+ * still keeping a burst of commands to one probe.
128
+ */
129
+ export const SOCKET_FACTS_TTL_MS = 60_000;
123
130
  /** The successful facts, keyed by the exact transport + distro pair; a failure is not remembered. */
124
131
  const factsCache = new Map();
125
132
  /** Test hook: forget the remembered facts. */
@@ -128,7 +135,8 @@ export function resetSocketIsolationCache() {
128
135
  }
129
136
  /**
130
137
  * Resolve the socket masks for one distro and stance, running the in-distro
131
- * probe once per `(wslPath, distro)`.
138
+ * probe once per `(wslPath, distro)` and re-running it after
139
+ * {@link SOCKET_FACTS_TTL_MS} so a socket that appears later is masked too.
132
140
  *
133
141
  * @param options - the stance, transport, distro and host runner.
134
142
  * @returns the masks; empty for `off`.
@@ -139,8 +147,10 @@ export async function socketMasksFor(options) {
139
147
  return [];
140
148
  options.signal?.throwIfAborted();
141
149
  const key = `${options.wslPath}\u0000${options.distro}`;
142
- let pending = factsCache.get(key);
143
- if (pending === undefined) {
150
+ const now = Date.now();
151
+ const cached = factsCache.get(key);
152
+ let entry;
153
+ if (cached === undefined || now - cached.at >= SOCKET_FACTS_TTL_MS) {
144
154
  const argv = [
145
155
  options.wslPath,
146
156
  ...(options.distro.length > 0 ? ["-d", options.distro] : []),
@@ -149,13 +159,20 @@ export async function socketMasksFor(options) {
149
159
  "-c",
150
160
  socketIsolationProbeScript(),
151
161
  ];
152
- pending = options.run(argv).then(parseSocketIsolationFacts);
153
- factsCache.set(key, pending);
154
- pending.catch(() => factsCache.delete(key));
162
+ const pending = options.run(argv).then(parseSocketIsolationFacts);
163
+ entry = { at: now, pending };
164
+ factsCache.set(key, entry);
165
+ pending.catch(() => {
166
+ if (factsCache.get(key) === entry)
167
+ factsCache.delete(key);
168
+ });
169
+ }
170
+ else {
171
+ entry = cached;
155
172
  }
156
173
  let facts;
157
174
  try {
158
- facts = await pending;
175
+ facts = await entry.pending;
159
176
  }
160
177
  catch (error) {
161
178
  const reason = error instanceof Error ? error.message : String(error);
package/lib/status.js CHANGED
@@ -261,6 +261,13 @@ export function createStatusHandler(options) {
261
261
  const now = options.now ?? (() => Date.now());
262
262
  const statePath = options.statePath ?? defaultStatePath();
263
263
  const verdicts = new Map();
264
+ /**
265
+ * The runs in flight, by distro and mode. A second request for the same
266
+ * run joins it instead of starting another doctor: two concurrent sweeps
267
+ * of one distro saturate `wsl.exe`, and whichever answer landed second
268
+ * used to win the stored result.
269
+ */
270
+ const inflight = new Map();
264
271
  let list;
265
272
  // Restore the last successful results before the first request. The stored
266
273
  // view is the panel's shape; the fields later releases may have added are
@@ -303,8 +310,18 @@ export function createStatusHandler(options) {
303
310
  list = { at: now(), names };
304
311
  return names;
305
312
  };
306
- const check = async (distro, refresh, mode = "quick", source = "user") => {
313
+ /** Run one doctor for one distro; the single-flight wrapper is {@link check}. */
314
+ const run = async (distro, refresh, mode, source) => {
307
315
  const cached = verdicts.get(distro);
316
+ // A background refresh is the page load's courtesy re-check of a QUICK
317
+ // result. A full diagnosis, or a repair with its before → after
318
+ // evidence, is the user's own doing and is never replaced by a quick
319
+ // one: that replaced the repair button and the evidence sixty seconds
320
+ // after the user last opened the panel. (A failed full run is not
321
+ // protected: it has nothing to keep.)
322
+ if (source === "background" && cached !== undefined && cached.view.verdict !== "error" && (cached.view.full === true || cached.view.repaired === true)) {
323
+ return present(cached.view, true);
324
+ }
308
325
  // A failure is a fact of this moment: it is kept for the list and the
309
326
  // store, but a plain GET re-runs instead of serving it as fresh.
310
327
  if (!refresh && cached !== undefined && cached.view.verdict !== "error" && now() - cached.at < options.cacheMs)
@@ -314,11 +331,16 @@ export function createStatusHandler(options) {
314
331
  try {
315
332
  // Repairs require the full scope so every changed condition is re-probed.
316
333
  // The separate full mode is read-only and never passes a fix flag.
334
+ // One stuck probe must settle inside this run's own budget instead of
335
+ // under the outer kill, so the report names the read that hung: the
336
+ // probe deadline plus one flake retry and the settle delay is 2T + 2s
337
+ // (the settle is the doctor's 2 s), kept strictly below the budget.
338
+ const probeTimeout = Math.ceil((options.timeoutMs - 2_000) / 2) - 1;
317
339
  const argv = mode === "repair"
318
- ? ["--json", "--fix", "--fix-owned", "--distro", distro]
340
+ ? ["--json", "--fix", "--fix-owned", "--probe-timeout", String(probeTimeout), "--distro", distro]
319
341
  : mode === "full"
320
- ? ["--json", "--distro", distro]
321
- : ["--json", "--quick", "--distro", distro];
342
+ ? ["--json", "--probe-timeout", String(probeTimeout), "--distro", distro]
343
+ : ["--json", "--quick", "--probe-timeout", String(probeTimeout), "--distro", distro];
322
344
  const raw = await options.runCli(argv, undefined, options.timeoutMs);
323
345
  const report = JSON.parse(raw);
324
346
  const live = mergeTakeoverReport(mergeAutoPresetSeam(report), options.providers?.() ?? []);
@@ -353,6 +375,33 @@ export function createStatusHandler(options) {
353
375
  writeStored(statePath, verdicts);
354
376
  return present(view, false);
355
377
  };
378
+ /**
379
+ * Check one distro, at most once at a time per mode: requests for the same
380
+ * distro and mode that arrive while one runs answer with that run's result.
381
+ * A repair is its own mode and never shares a read-only run.
382
+ *
383
+ * @param distro - the distro to check.
384
+ * @param refresh - whether to bypass the stored result.
385
+ * @param mode - the doctor scope.
386
+ * @param source - who started it.
387
+ * @returns the view to present.
388
+ */
389
+ const check = (distro, refresh, mode = "quick", source = "user") => {
390
+ const key = `${distro}\u0000${mode}`;
391
+ const running = inflight.get(key);
392
+ if (running !== undefined)
393
+ return running;
394
+ const pending = run(distro, refresh, mode, source);
395
+ inflight.set(key, pending);
396
+ // The entry leaves with the run whatever its outcome; the promise stored
397
+ // is the one later callers join, never a derived one.
398
+ const forget = () => {
399
+ if (inflight.get(key) === pending)
400
+ inflight.delete(key);
401
+ };
402
+ void pending.then(forget, forget);
403
+ return pending;
404
+ };
356
405
  /**
357
406
  * Drop stored verdicts and persist the change. Clearing is deliberately
358
407
  * independent of `wsl.exe`: it is local housekeeping, and must still work
package/lib/subprocess.js CHANGED
@@ -308,7 +308,7 @@ export class WslSubprocessRuntime extends LocalSubprocessRuntime {
308
308
  return async () => {
309
309
  try {
310
310
  const probe = terminalActivityProbe(terminalId);
311
- const result = await sharedAgent(distro).exec({
311
+ const result = await sharedAgent(distro, this.config.wslPath).exec({
312
312
  cwd: probe.cwd,
313
313
  argv: probe.argv,
314
314
  maxOutputBytes: 256,
@@ -383,7 +383,7 @@ export class WslSubprocessRuntime extends LocalSubprocessRuntime {
383
383
  const stdoutCap = spec.stdio.stdout?.maxBytes ?? 0;
384
384
  const stderrCap = spec.stdio.stderr?.maxBytes ?? 0;
385
385
  return gitExecutionHandle({
386
- agent: sharedAgent(gitRewrite.distro),
386
+ agent: sharedAgent(gitRewrite.distro, this.config.wslPath),
387
387
  cwd: gitRewrite.linuxCwd,
388
388
  argv: gitRewrite.gitArgv,
389
389
  env: agentEnv,
@@ -402,7 +402,7 @@ export class WslSubprocessRuntime extends LocalSubprocessRuntime {
402
402
  // (`done`, `collected`, `kill`); the seam's full handle surface is the
403
403
  // one-shot fallback's, so the override's declared return is the cast's.
404
404
  return searchExecutionHandle({
405
- agent: sharedAgent(rewrite.distro),
405
+ agent: sharedAgent(rewrite.distro, this.config.wslPath),
406
406
  cwd: rewrite.linuxCwd,
407
407
  argv: rewrite.rgArgv,
408
408
  distro: rewrite.distro,