dsh-plugin-wsl-env 0.28.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 (81) hide show
  1. package/CHANGELOG.md +368 -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 +540 -160
  9. package/cordis.patch.yml +28 -7
  10. package/docs/AGENT-PROTOCOL-V7.md +4 -2
  11. package/docs/API.md +1 -1
  12. package/docs/API.zh.md +1 -1
  13. package/docs/ARCHITECTURE.md +7 -4
  14. package/docs/ARCHITECTURE.zh.md +6 -4
  15. package/docs/COMPATIBILITY.md +1 -1
  16. package/docs/COMPATIBILITY.zh.md +1 -1
  17. package/docs/CONFIGURATION.md +28 -15
  18. package/docs/CONFIGURATION.zh.md +20 -11
  19. package/docs/DIAGNOSTICS.md +45 -19
  20. package/docs/DIAGNOSTICS.zh.md +33 -15
  21. package/docs/LIMITATIONS.md +70 -10
  22. package/docs/LIMITATIONS.zh.md +53 -8
  23. package/docs/PERFORMANCE.md +29 -1
  24. package/docs/PERFORMANCE.zh.md +23 -1
  25. package/docs/QUICKSTART.md +21 -15
  26. package/docs/QUICKSTART.zh.md +13 -11
  27. package/docs/README.zh.md +1 -1
  28. package/docs/RELEASING.md +29 -6
  29. package/docs/RELEASING.zh.md +9 -0
  30. package/docs/adr/0002-native-agent.md +50 -2
  31. package/lib/agent-confined.js +15 -4
  32. package/lib/agent-errors.d.ts +16 -0
  33. package/lib/agent-errors.js +19 -0
  34. package/lib/agent-exec.d.ts +8 -1
  35. package/lib/agent-exec.js +2 -1
  36. package/lib/agent-shared.d.ts +85 -2
  37. package/lib/agent-shared.js +167 -38
  38. package/lib/agent.d.ts +60 -6
  39. package/lib/agent.js +177 -28
  40. package/lib/auto-preset.js +7 -2
  41. package/lib/doctor-live.d.ts +36 -7
  42. package/lib/doctor-live.js +61 -12
  43. package/lib/doctor-process.d.ts +68 -0
  44. package/lib/doctor-process.js +139 -0
  45. package/lib/doctor-report.js +11 -109
  46. package/lib/fs-substrate.js +3 -3
  47. package/lib/fsio-agent.d.ts +57 -6
  48. package/lib/fsio-agent.js +168 -75
  49. package/lib/git-exec.d.ts +7 -1
  50. package/lib/git-exec.js +14 -2
  51. package/lib/native-agent.d.ts +25 -4
  52. package/lib/native-agent.js +52 -9
  53. package/lib/picker.d.ts +2 -1
  54. package/lib/picker.js +30 -13
  55. package/lib/plugin-update.js +18 -14
  56. package/lib/provider-common.d.ts +112 -0
  57. package/lib/provider-common.js +171 -0
  58. package/lib/sandbox-core.js +52 -13
  59. package/lib/search-exec.d.ts +6 -0
  60. package/lib/search-exec.js +10 -2
  61. package/lib/session-runtime.d.ts +46 -1
  62. package/lib/session-runtime.js +57 -7
  63. package/lib/session-scope.d.ts +22 -1
  64. package/lib/session-scope.js +33 -7
  65. package/lib/shell-env.js +125 -12
  66. package/lib/socket-isolation.d.ts +12 -4
  67. package/lib/socket-isolation.js +27 -10
  68. package/lib/status.d.ts +7 -4
  69. package/lib/status.js +72 -16
  70. package/lib/subprocess.js +3 -3
  71. package/lib/terminal-activity.js +6 -9
  72. package/lib/wsl-doctor-command.js +36 -80
  73. package/lib/wsl-filesystem.d.ts +9 -4
  74. package/lib/wsl-filesystem.js +26 -10
  75. package/lib/wsl-shell.d.ts +27 -17
  76. package/lib/wsl-shell.js +83 -24
  77. package/lib/wsl.d.ts +3 -1
  78. package/lib/wsl.js +82 -7
  79. package/package.json +5 -4
  80. package/scripts/bootstrap.sh +36 -12
  81. package/scripts/doctor.mjs +514 -201
package/client.js CHANGED
@@ -19,13 +19,11 @@
19
19
  * `updateBundle` only for that explicit click and the card reports the host's
20
20
  * applied/restart-required/rollback outcome.
21
21
  *
22
- * Every distro row offers two check actions: **快速检查** (the scoped quick
23
- * doctor, `GET` on the status route) and **完整检查** (the full doctor with
24
- * `--fix-owned`, `POST` on the same route). Both run again on every click —
25
- * there is no persistent "recheck" label. The full run also repairs plugin-owned
26
- * state (a stale session scope or a broken agent cache) and answers with its
27
- * `fix.*` before → after rows; it never installs packages or rewrites
28
- * Windows-owned configuration. Every other warning stays manual.
22
+ * Every distro row offers **快速检查** (the quick doctor) and **完整诊断**
23
+ * (the full doctor, read-only). When a full report identifies plugin-owned
24
+ * state it can repair, the row separately offers **修复插件状态**; that action
25
+ * uses `--fix-owned` and answers with its `fix.*` before → after rows. It never
26
+ * installs packages or rewrites Windows-owned configuration.
29
27
  *
30
28
  * The last result is persisted Host-side, so a page reload (or an app restart)
31
29
  * still shows the last guidance and when it ran. On load, a stored result for
@@ -53,15 +51,250 @@
53
51
  * (`wsl-env-client-host`, mounting the no-op root export) is what puts this
54
52
  * package on the web bundle list.
55
53
  */
56
- window.__ModuleLoader__.load({
54
+
55
+ // The browser surface the client program touches, declared here rather than
56
+ // via a DOM lib: the shared type gate runs with Node's globals, and a global
57
+ // `window`/`document` there would let Node-side typos pass. One `globalThis`
58
+ // sample, cast once, mirrors the harness loader's own delivery: both a browser
59
+ // and the VM the client tests load this file in expose `window` and `document`
60
+ // as properties of that same object.
61
+ /** @typedef {object} ClientStorage
62
+ * @property {(key: string) => string | null} getItem
63
+ * @property {(key: string, value: string) => void} setItem
64
+ */
65
+ /** @typedef {{ key?: string, shiftKey?: boolean, preventDefault?: () => void }} ClientKeyEvent */
66
+ /** @typedef {{ target?: unknown, currentTarget?: unknown }} ClientMouseEvent */
67
+ /** @typedef {{ focus?: () => void, querySelector?: (selector: string) => ClientElement | null, querySelectorAll?: (selector: string) => ArrayLike<ClientElement> }} ClientElement */
68
+ /** @typedef {{ load: (module: { id: string, factory: (require: (name: string) => unknown) => unknown }) => void }} ClientModuleLoader */
69
+ /**
70
+ * @typedef {object} ClientWindow
71
+ * @property {ClientModuleLoader} __ModuleLoader__
72
+ * @property {ClientStorage} sessionStorage
73
+ */
74
+ /**
75
+ * @typedef {object} ClientDocument
76
+ * @property {ClientElement | null} [activeElement]
77
+ * @property {(type: string, listener: (event: ClientKeyEvent) => void) => void} addEventListener
78
+ * @property {(type: string, listener: (event: ClientKeyEvent) => void) => void} removeEventListener
79
+ */
80
+ /**
81
+ * @typedef {object} ClientPlatform
82
+ * @property {ClientWindow} window
83
+ * @property {ClientDocument} document
84
+ */
85
+ /**
86
+ * The slice of React's API the panel uses. The harness hands the real React
87
+ * through the loader's `require`; no typings ship for it, so this is the
88
+ * contract the client is written against.
89
+ * @typedef {object} ReactApi
90
+ * @property {(type: unknown, props?: Record<string, unknown> | null, ...children: unknown[]) => unknown} createElement
91
+ * @property {<T>(initial: T | (() => T)) => [T, (next: T | ((prev: T) => T)) => void]} useState
92
+ * @property {(effect: () => void | (() => void), deps?: readonly unknown[]) => void} useEffect
93
+ * @property {<T>(initial: T) => { current: T }} useRef
94
+ */
95
+ const platform = /** @type {ClientPlatform} */ (/** @type {unknown} */ (globalThis));
96
+
97
+ // ── The plugin's wire and state shapes ─────────────────────────────────────
98
+ // The routes' answers mirror the built modules, so the types come from them;
99
+ // the panel's own state shapes are spelled out where the client adds to them.
100
+
101
+ /** @typedef {import("./lib/status.js").DistroStatusView} DistroStatusView */
102
+ /** @typedef {import("./lib/status.js").StatusCheck} StatusCheck */
103
+ /** @typedef {import("./lib/status.js").StatusRepair} StatusRepair */
104
+ /** @typedef {import("./lib/status.js").StatusWarning} StatusWarning */
105
+ /** @typedef {import("./lib/plugin-update.js").PluginVersionView} PluginVersionView */
106
+ /** @typedef {import("./lib/plugin-update.js").PluginUpdateReply} PluginUpdateReply */
107
+ /** @typedef {import("./lib/plugin-update.js").ChangeApplication} ChangeApplication */
108
+ /** @typedef {import("./lib/update-check.js").ListedVersion} ListedVersion */
109
+
110
+ /**
111
+ * The status route's answers. The `GET` list answer carries the stored rows
112
+ * under `cached`, while a single-check answer carries a boolean there, so the
113
+ * field is the union of both shapes.
114
+ * @typedef {object} ClientStatusReply
115
+ * @property {string[]} [distros]
116
+ * @property {string[]} [running]
117
+ * @property {DistroStatusView[] | boolean} [cached]
118
+ * @property {number} [cleared]
119
+ * @property {string} [distro]
120
+ * @property {DistroStatusView["verdict"]} [verdict]
121
+ * @property {boolean} [full]
122
+ * @property {boolean} [repaired]
123
+ * @property {StatusRepair[]} [repairs]
124
+ * @property {string[]} [repairable]
125
+ * @property {number} [checkedAt]
126
+ * @property {DistroStatusView["failures"]} [failures]
127
+ * @property {StatusWarning[]} [warnings]
128
+ * @property {DistroStatusView["counts"]} [counts]
129
+ * @property {DistroStatusView["sections"]} [sections]
130
+ * @property {StatusCheck[]} [checks]
131
+ * @property {number} [notRun]
132
+ * @property {string[]} [blockers]
133
+ * @property {DistroStatusView["source"]} [source]
134
+ * @property {string} [error]
135
+ */
136
+ /**
137
+ * One distro row as the panel keeps it: the last answer plus the panel's own
138
+ * phase. Every verdict field is optional because a row exists before any
139
+ * answer arrives (`{ phase: "checking" }`).
140
+ * @typedef {object} ClientCheckRow
141
+ * @property {string} [phase]
142
+ * @property {string} [distro]
143
+ * @property {DistroStatusView["verdict"]} [verdict]
144
+ * @property {boolean} [full]
145
+ * @property {boolean} [repaired]
146
+ * @property {StatusRepair[]} [repairs]
147
+ * @property {string[]} [repairable]
148
+ * @property {number} [checkedAt]
149
+ * @property {DistroStatusView["failures"]} [failures]
150
+ * @property {StatusWarning[]} [warnings]
151
+ * @property {Partial<DistroStatusView["counts"]>} [counts]
152
+ * @property {DistroStatusView["sections"]} [sections]
153
+ * @property {StatusCheck[]} [checks]
154
+ * @property {number} [notRun]
155
+ * @property {string[]} [blockers]
156
+ * @property {DistroStatusView["source"]} [source]
157
+ * @property {DistroStatusView[] | boolean} [cached]
158
+ * @property {string} [error]
159
+ */
160
+ /** The panel's row table, keyed by distro name. @typedef {Record<string, ClientCheckRow | undefined>} ClientCheckTable */
161
+ /** One finding row: a failing check or a warning. @typedef {{ id: string, detail?: string, remedy?: string }} ClientFinding */
162
+ /** One transient panel notice. @typedef {{ kind: "ok" | "info" | "warn" | "error", text: string }} ClientNotice */
163
+ /** The access record the reminder reads. @typedef {{ target: string, paths: string[] }} ClientAccess */
164
+ /** The access read's answer: the record, or why it is unavailable. @typedef {{ ok: true, paths: string[], preset: string } | { ok: false, message?: string }} ClientAccessRead */
165
+
166
+ /**
167
+ * The plugin route's answers: the version view on `GET`, the host's upgrade
168
+ * outcome on `POST`.
169
+ * @typedef {object} ClientPluginReply
170
+ * @property {string} [installed]
171
+ * @property {string} [running]
172
+ * @property {PluginVersionView["status"]} [status]
173
+ * @property {number} [checkedAt]
174
+ * @property {boolean} [cached]
175
+ * @property {boolean} [updateSupported]
176
+ * @property {boolean} [canUpdate]
177
+ * @property {string | null} [registry]
178
+ * @property {ListedVersion} [latest]
179
+ * @property {string} [problem]
180
+ * @property {string} [reason]
181
+ * @property {boolean} [updated]
182
+ * @property {ChangeApplication} [application]
183
+ * @property {string} [from]
184
+ * @property {string} [to]
185
+ * @property {PluginUpdateReply["step"]} [step]
186
+ * @property {string} [restartReason]
187
+ * @property {boolean} [restored]
188
+ * @property {{ code?: string, diagnostic?: string }} [error]
189
+ * @property {readonly string[]} [pendingBuilds]
190
+ * @property {{ code?: string, diagnostic?: string }} [restoreError]
191
+ */
192
+ /**
193
+ * The version card's state: the last answer plus the panel's own phase. The
194
+ * panel's `error` is the display string a failed request stores, which is why
195
+ * the route's structured `error` is also allowed here.
196
+ * @typedef {object} ClientPluginState
197
+ * @property {string} [phase]
198
+ * @property {string} [installed]
199
+ * @property {string} [running]
200
+ * @property {PluginVersionView["status"]} [status]
201
+ * @property {number} [checkedAt]
202
+ * @property {boolean} [cached]
203
+ * @property {boolean} [updateSupported]
204
+ * @property {boolean} [canUpdate]
205
+ * @property {string | null} [registry]
206
+ * @property {ListedVersion | null} [latest]
207
+ * @property {string} [problem]
208
+ * @property {string} [reason]
209
+ * @property {string | { code?: string, diagnostic?: string }} [error]
210
+ * @property {ClientPluginReply} [upgrade]
211
+ */
212
+
213
+ // ── The client services the panel consumes ────────────────────────────────
214
+ // The harness's browser services have no declarations visible here, so each
215
+ // slice is spelled structurally for exactly what the client reads.
216
+
217
+ /** @typedef {{ get: (name: string) => unknown }} ClientServiceHost */
218
+ /** @typedef {{ message?: string }} ClientServiceError */
219
+ /**
220
+ * @typedef {object} ClientSettingsNamespace
221
+ * @property {string} ns
222
+ * @property {number} revision
223
+ * @property {Record<string, unknown>} [value]
224
+ */
225
+ /**
226
+ * @typedef {object} ClientSettingsReply
227
+ * @property {boolean} [ok]
228
+ * @property {{ writable?: boolean, namespaces?: ClientSettingsNamespace[] }} [value]
229
+ * @property {ClientServiceError} [error]
230
+ */
231
+ /**
232
+ * @typedef {object} ClientSettingsService
233
+ * @property {() => Promise<ClientSettingsReply>} describe
234
+ * @property {(ns: string, patch: Record<string, unknown>, revision: number) => Promise<{ ok?: boolean, error?: ClientServiceError }>} update
235
+ */
236
+ /** A preset row from the agent-preset roster. @typedef {{ id?: string, isDefault?: boolean }} ClientPresetEntry */
237
+ /**
238
+ * @typedef {object} ClientPresetService
239
+ * @property {(sessionId: string, presetId: string) => Promise<{ ok?: boolean, error?: ClientServiceError }>} select
240
+ * @property {() => Promise<{ ok?: boolean, error?: ClientServiceError, value?: { presets?: ClientPresetEntry[] } }>} list
241
+ */
242
+ /** One session summary as the list hook exposes it. @typedef {{ cwd?: string, parentId?: string, origin?: string, blank?: boolean }} ClientSessionSummary */
243
+ /** @typedef {{ byId: Record<string, ClientSessionSummary> }} ClientSessionSnapshot */
244
+ /** @typedef {{ list: { getSnapshot: () => ClientSessionSnapshot } }} ClientSessionsService */
245
+ /** One workspace catalog entry. @typedef {{ workspaceId: string, path: string, sessionIds: string[] }} ClientWorkspaceEntry */
246
+ /** @typedef {{ phase?: string, items: ClientWorkspaceEntry[] }} ClientWorkspaceSnapshot */
247
+ /**
248
+ * @typedef {object} ClientWorkspacesService
249
+ * @property {{ getSnapshot: () => ClientWorkspaceSnapshot, subscribe: (listener: () => void) => (() => void) }} list
250
+ */
251
+ /** The slot's session-list and projection hooks. @typedef {<T>(selector: (state: ClientSessionSnapshot) => T) => T} UseSessions */
252
+ /** @typedef {(name: string) => unknown} UseProjection */
253
+ /** The props every component this client registers receives. @typedef {{ ctx: ClientContext }} ClientPanelProps */
254
+ /** The composer/header reminder components' props. @typedef {{ ctx: ClientContext, sessionId: string, useSessions: UseSessions, useProjection: UseProjection }} ClientReminderProps */
255
+ /** Props of one slot's renderer. @typedef {{ size?: number, active?: boolean, sessionId?: string, useSessions?: UseSessions, useProjection?: UseProjection }} ClientSlotProps */
256
+ /** @typedef {{ label: string, tone: "ready" | "blocked" | "error" | "idle", title?: string }} ClientPillProps */
257
+ /** @typedef {{ label: string, onClick?: () => void, primary?: boolean, disabled?: boolean, small?: boolean }} ClientBtnProps */
258
+ /** @typedef {{ title?: unknown, actions?: unknown, children?: unknown }} ClientCardProps */
259
+ /**
260
+ * @typedef {object} ClientSlots
261
+ * @property {(name: string, install: () => Generator<unknown, void, unknown>) => void} inject
262
+ * @property {(spec: Record<string, unknown>, render: (props: ClientSlotProps) => unknown) => unknown} register
263
+ */
264
+ /** One session-header menu item the client offers. @typedef {{ id: string, label: string, failureLabel: string, run: () => Promise<void> }} ClientMenuItem */
265
+ /**
266
+ * @typedef {object} ClientMenuDefinition
267
+ * @property {string} id
268
+ * @property {string} target
269
+ * @property {number} order
270
+ * @property {() => unknown[]} observe
271
+ * @property {(context: { sessionId: string }) => ClientMenuItem[]} resolve
272
+ */
273
+ /** @typedef {{ register: (definition: ClientMenuDefinition) => unknown }} ClientContextMenuRegistry */
274
+ /** The scope a service injection hands its callback. @typedef {{ get: (name: string) => unknown, effect: (callback: () => unknown, label?: string) => unknown, contextMenus: ClientContextMenuRegistry, sessions: ClientSessionsService }} ClientScope */
275
+ /** @typedef {ClientServiceHost & { slots: ClientSlots, inject: (dependencies: readonly string[], callback: (scope: ClientScope) => void) => unknown }} ClientContext */
276
+ /** One pending access-mode prompt. @typedef {{ workspaceId: string, path: string }} ClientPromptRequest */
277
+ /**
278
+ * The prompt slot shared by the watcher and the overlay occupant.
279
+ * @typedef {object} ClientAccessPrompt
280
+ * @property {ClientPromptRequest | null} value
281
+ * @property {Set<() => void>} listeners
282
+ * @property {() => ClientPromptRequest | null} get
283
+ * @property {(next: ClientPromptRequest | null) => void} set
284
+ * @property {(listener: () => void) => () => void} subscribe
285
+ */
286
+ /** The browser services this client reads, keyed by their registered names. @typedef {{ "remote.settings": ClientSettingsService, "remote.agentPresets": ClientPresetService, sessions: ClientSessionsService, workspaces: ClientWorkspacesService }} ClientServiceMap */
287
+
288
+ platform.window.__ModuleLoader__.load({
57
289
  id: "dsh-plugin-wsl-env",
58
290
  factory(require) {
59
- const React = require("react");
291
+ const React = /** @type {ReactApi} */ (require("react"));
60
292
  const h = React.createElement;
61
293
  const useState = React.useState;
62
294
  const useEffect = React.useEffect;
295
+ const useRef = React.useRef;
63
296
 
64
- /** The plugin's status route (checks on GET, the full check on POST, clear on DELETE); the row registers this exact path. */
297
+ /** The plugin's status route (checks on GET, repair on POST, clear on DELETE); the row registers this exact path. */
65
298
  const STATUS_PATH = "/api/wsl-env/status";
66
299
  /** The plugin version/upgrade route: GET reads, POST performs the confirmed upgrade. */
67
300
  const PLUGIN_UPDATE_PATH = "/api/wsl-env/plugin-update";
@@ -75,53 +308,79 @@ window.__ModuleLoader__.load({
75
308
  const WINDOWS_FIELD = "windowsWorkspaces";
76
309
  const UNC_RE = /^\\\\wsl(?:\.localhost|\$)\\([^\\]+)(?:\\([\s\S]*))?$/i;
77
310
 
311
+ /**
312
+ * Resolve one browser service by its registered name.
313
+ * @template {keyof ClientServiceMap} Name
314
+ * @param {ClientServiceHost} ctx - client root context.
315
+ * @param {Name} name - the service's registered name.
316
+ * @returns {ClientServiceMap[Name] | undefined} the service, or undefined when the host provides none.
317
+ */
78
318
  const service = (ctx, name) => {
79
319
  try {
80
- return ctx.get(name);
320
+ return /** @type {ClientServiceMap[Name] | undefined} */ (ctx.get(name));
81
321
  } catch (error) {
82
322
  return undefined;
83
323
  }
84
324
  };
85
325
 
86
- const messageOf = (error) => (error && typeof error.message === "string" ? error.message : String(error));
326
+ /**
327
+ * One error's message, whatever value was thrown.
328
+ * @param {unknown} error - the thrown value.
329
+ * @returns {string} its message, or the value stringified.
330
+ */
331
+ const messageOf = (error) => (error && typeof (/** @type {ClientServiceError} */ (error)).message === "string"
332
+ ? /** @type {{ message: string }} */ (error).message
333
+ : String(error));
87
334
 
335
+ /** @type {(value: unknown) => value is string} */
88
336
  const isWslUnc = (value) => typeof value === "string" && UNC_RE.test(value);
89
337
 
338
+ /**
339
+ * @param {string} value - a workspace path.
340
+ * @returns {string} the comparable form: separators unified, trailing ones dropped, lowercased.
341
+ */
90
342
  const normalize = (value) => value.trim().replace(/[\\/]+$/, "").replace(/\//g, "\\").toLowerCase();
91
343
 
344
+ /**
345
+ * @param {unknown} a - one path.
346
+ * @param {unknown} b - the other path.
347
+ * @returns {boolean} whether both are strings naming the same path.
348
+ */
92
349
  const samePath = (a, b) => typeof a === "string" && typeof b === "string" && normalize(a) === normalize(b);
93
350
 
94
351
  /**
95
352
  * Fetch one exact route and decode its JSON answer.
96
- * @param path - the route's absolute path.
97
- * @param query - the query string, including `?`, or empty.
98
- * @param method - `GET` to read, `POST` to act, `DELETE` to clear.
99
- * @returns the decoded body.
100
- * @throws with the route's own error message.
353
+ * @template Reply
354
+ * @param {string} path - the route's absolute path.
355
+ * @param {string} query - the query string, including `?`, or empty.
356
+ * @param {string} [method] - `GET` to read, `POST` to act, `DELETE` to clear.
357
+ * @returns {Promise<Reply>} the decoded body.
358
+ * @throws with the route's own error message. The status routes answer a
359
+ * string `error`; the plugin route answers a structured one, which this
360
+ * transport has never rendered as anything but its string form.
101
361
  */
102
362
  const jsonRequest = async (path, query, method = "GET") => {
103
363
  const answer = await fetch(path + (query ?? ""), { method });
104
- const body = await answer.json().catch(() => ({}));
105
- if (!answer.ok) throw new Error(body.error ?? `接口返回 ${answer.status}`);
364
+ const body = /** @type {Reply} */ (await answer.json().catch(() => ({})));
365
+ if (!answer.ok) throw new Error(/** @type {{ error?: string }} */ (body).error ?? `接口返回 ${answer.status}`);
106
366
  return body;
107
367
  };
108
368
 
109
369
  /**
110
- * The doctor route: list/quick check on GET, the full check (which also
111
- * repairs plugin-owned state) on POST, and clearing stored results on
112
- * DELETE.
113
- * @param query - the query string, including `?`, or empty.
114
- * @param method - `GET` for a check, `POST` for the full-check action,
370
+ * The doctor route: list/quick/full read-only checks on GET, the explicit
371
+ * plugin-owned repair on POST, and clearing stored results on DELETE.
372
+ * @param {string} query - the query string, including `?`, or empty.
373
+ * @param {string} [method] - `GET` for a check, `POST` for repair,
115
374
  * `DELETE` to clear one distro's result (named by `distro`) or all.
116
- * @returns the decoded body.
375
+ * @returns {Promise<ClientStatusReply>} the decoded body.
117
376
  */
118
377
  const statusRequest = (query, method = "GET") => jsonRequest(STATUS_PATH, query, method);
119
378
 
120
379
  /**
121
380
  * The plugin version route: read on GET, confirmed one-click upgrade on POST.
122
- * @param query - the query string, including `?`, or empty.
123
- * @param method - `GET` for a check, `POST` for the upgrade.
124
- * @returns the decoded body.
381
+ * @param {string} query - the query string, including `?`, or empty.
382
+ * @param {string} [method] - `GET` for a check, `POST` for the upgrade.
383
+ * @returns {Promise<ClientPluginReply>} the decoded body.
125
384
  */
126
385
  const pluginRequest = (query, method = "GET") => jsonRequest(PLUGIN_UPDATE_PATH, query, method);
127
386
 
@@ -133,8 +392,8 @@ window.__ModuleLoader__.load({
133
392
 
134
393
  /**
135
394
  * Find the auto-preset settings view and its Windows-access paths.
136
- * @param describe - the `settings.describe` answer.
137
- * @returns the namespace view and the paths it currently carries.
395
+ * @param {ClientSettingsReply} describe - the `settings.describe` answer.
396
+ * @returns {{ entry: ClientSettingsNamespace, paths: string[], preset: string } | undefined} the namespace view and the paths it currently carries.
138
397
  */
139
398
  const accessViewOf = (describe) => {
140
399
  if (!describe || describe.ok !== true) return undefined;
@@ -145,17 +404,17 @@ window.__ModuleLoader__.load({
145
404
  const entry = value.namespaces.find((row) => row
146
405
  && (row.ns === AUTO_PRESET_ENTRY || row.ns.endsWith("/" + AUTO_PRESET_ENTRY)));
147
406
  if (entry === undefined) return undefined;
148
- const configured = entry.value && Array.isArray(entry.value[WINDOWS_FIELD]) ? entry.value[WINDOWS_FIELD] : [];
407
+ const configured = /** @type {unknown[]} */ (entry.value && Array.isArray(entry.value[WINDOWS_FIELD]) ? entry.value[WINDOWS_FIELD] : []);
149
408
  // The row's `preset` field is the preset auto-preset adopts for distro
150
409
  // workspaces; the reminder compares the session's projection against it.
151
410
  const preset = entry.value && typeof entry.value.preset === "string" ? entry.value.preset : "";
152
- return { entry, paths: configured.filter((path) => typeof path === "string"), preset };
411
+ return { entry, paths: /** @type {string[]} */ (configured.filter((path) => typeof path === "string")), preset };
153
412
  };
154
413
 
155
414
  /**
156
415
  * Read the current Windows-access paths and the target preset.
157
- * @param ctx - client root context.
158
- * @returns `{ ok: true, paths, preset }`, or the reason the record is unavailable.
416
+ * @param {ClientServiceHost} ctx - client root context.
417
+ * @returns {Promise<ClientAccessRead>} `{ ok: true, paths, preset }`, or the reason the record is unavailable.
159
418
  */
160
419
  const readAccess = async (ctx) => {
161
420
  const settings = service(ctx, "remote.settings");
@@ -168,9 +427,9 @@ window.__ModuleLoader__.load({
168
427
 
169
428
  /**
170
429
  * Persist a complete Windows-access list.
171
- * @param ctx - client root context.
172
- * @param paths - the new list.
173
- * @returns `undefined` on success, or the failure message.
430
+ * @param {ClientServiceHost} ctx - client root context.
431
+ * @param {string[]} paths - the new list.
432
+ * @returns {Promise<string | undefined>} `undefined` on success, or the failure message.
174
433
  */
175
434
  const writeAccess = async (ctx, paths) => {
176
435
  const settings = service(ctx, "remote.settings");
@@ -199,9 +458,9 @@ window.__ModuleLoader__.load({
199
458
  /**
200
459
  * Whether a workspace is one of the recorded Windows-access directories or
201
460
  * below one (whole-segment, case-insensitive, like the host's comparison).
202
- * @param cwd - the session workspace.
203
- * @param paths - the configured directories.
204
- * @returns true when the workspace opted out of the distro environment.
461
+ * @param {string} cwd - the session workspace.
462
+ * @param {readonly string[]} paths - the configured directories.
463
+ * @returns {boolean} true when the workspace opted out of the distro environment.
205
464
  */
206
465
  const isWindowsAccessPath = (cwd, paths) => {
207
466
  const target = normalize(cwd);
@@ -214,8 +473,8 @@ window.__ModuleLoader__.load({
214
473
 
215
474
  /**
216
475
  * The distro a UNC workspace names.
217
- * @param cwd - the session workspace.
218
- * @returns the distro name, or undefined for a non-UNC path.
476
+ * @param {unknown} cwd - the session workspace.
477
+ * @returns {string | undefined} the distro name, or undefined for a non-UNC path.
219
478
  */
220
479
  const distroOf = (cwd) => {
221
480
  const match = typeof cwd === "string" ? UNC_RE.exec(cwd) : null;
@@ -226,9 +485,8 @@ window.__ModuleLoader__.load({
226
485
  * The reminder state for one session, or null when its environment is right.
227
486
  * A missing projection and a matching preset both mean "nothing to say": the
228
487
  * banner never guesses an environment.
229
- * @param input - the session workspace, its projected preset, the configured
230
- * target preset, the Windows-access list, and subagent membership.
231
- * @returns `{ target, windowsAccess }` for a distro workspace on a non-WSL preset.
488
+ * @param {{ cwd?: string, preset?: unknown, target: string, paths?: string[], subagent?: boolean }} input - the session workspace, its projected preset, the configured target preset, the Windows-access list, and subagent membership.
489
+ * @returns {{ target: string, windowsAccess: boolean } | null} `{ target, windowsAccess }` for a distro workspace on a non-WSL preset.
232
490
  */
233
491
  const hostModeOf = ({ cwd, preset, target, paths, subagent }) => {
234
492
  if (subagent === true || !isWslUnc(cwd)) return null;
@@ -236,10 +494,14 @@ window.__ModuleLoader__.load({
236
494
  return { target, windowsAccess: isWindowsAccessPath(cwd, paths ?? []) };
237
495
  };
238
496
 
239
- /** The sessionStorage key that collapses the warning for one session. */
497
+ /**
498
+ * The sessionStorage key that collapses the warning for one session.
499
+ * @param {string} sessionId - the session the warning belongs to.
500
+ * @returns {string} the storage key.
501
+ */
240
502
  const dismissedKey = (sessionId) => "wsl-env.access-mode.dismissed:" + String(sessionId);
241
503
 
242
- /** Reminder components that must re-read the collapse fact when it changes. */
504
+ /** Reminder components that must re-read the collapse fact when it changes. @type {Set<() => void>} */
243
505
  const dismissedListeners = new Set();
244
506
 
245
507
  /**
@@ -255,12 +517,12 @@ window.__ModuleLoader__.load({
255
517
 
256
518
  /**
257
519
  * Whether the operator collapsed the reminder for this session.
258
- * @param sessionId - the session to ask about.
259
- * @returns true when the warning was dismissed in this browser session.
520
+ * @param {string} sessionId - the session to ask about.
521
+ * @returns {boolean} true when the warning was dismissed in this browser session.
260
522
  */
261
523
  const readDismissed = (sessionId) => {
262
524
  try {
263
- return window.sessionStorage.getItem(dismissedKey(sessionId)) === "1";
525
+ return platform.window.sessionStorage.getItem(dismissedKey(sessionId)) === "1";
264
526
  } catch {
265
527
  return false;
266
528
  }
@@ -268,11 +530,11 @@ window.__ModuleLoader__.load({
268
530
 
269
531
  /**
270
532
  * Collapse the reminder for this session only; a new session asks again.
271
- * @param sessionId - the session to collapse.
533
+ * @param {string} sessionId - the session to collapse.
272
534
  */
273
535
  const rememberDismissed = (sessionId) => {
274
536
  try {
275
- window.sessionStorage.setItem(dismissedKey(sessionId), "1");
537
+ platform.window.sessionStorage.setItem(dismissedKey(sessionId), "1");
276
538
  } catch {
277
539
  /* a browser without storage keeps the reminder visible */
278
540
  }
@@ -281,17 +543,17 @@ window.__ModuleLoader__.load({
281
543
 
282
544
  /**
283
545
  * Follow one session's host-mode state.
284
- * @param ctx - client root context.
285
- * @param sessionId - the active session.
286
- * @param useSessions - the slot's session-list hook.
287
- * @param useProjection - the slot's projection hook.
288
- * @returns the session summary and the reminder state (null while loading or correct).
546
+ * @param {ClientServiceHost} ctx - client root context.
547
+ * @param {string} sessionId - the active session.
548
+ * @param {UseSessions} useSessions - the slot's session-list hook.
549
+ * @param {UseProjection} useProjection - the slot's projection hook.
550
+ * @returns {{ summary: ClientSessionSummary | undefined, state: { target: string, windowsAccess: boolean } | null }} the session summary and the reminder state (null while loading or correct).
289
551
  */
290
552
  const useHostMode = (ctx, sessionId, useSessions, useProjection) => {
291
553
  const summary = useSessions((state) => state.byId[sessionId]);
292
554
  const preset = useProjection("agentPreset");
293
555
  const cwd = summary?.cwd;
294
- const [access, setAccess] = useState(null);
556
+ const [access, setAccess] = useState(/** @type {ClientAccess | null} */ (null));
295
557
 
296
558
  useEffect(() => {
297
559
  let live = true;
@@ -302,6 +564,7 @@ window.__ModuleLoader__.load({
302
564
  return () => { live = false; };
303
565
  }
304
566
  void (async () => {
567
+ /** @type {ClientAccessRead} */
305
568
  let answer;
306
569
  try {
307
570
  answer = await readAccess(ctx);
@@ -336,15 +599,15 @@ window.__ModuleLoader__.load({
336
599
  * host environment. The primary action is the one that works for this
337
600
  * session: a blank session can be switched in place; a session that already
338
601
  * started a turn keeps its history, so the durable fix is the access record.
339
- * @param props - slot standard props plus the client root context.
340
- * @returns the warning bar, or null when the environment is right or collapsed.
602
+ * @param {ClientReminderProps} props - slot standard props plus the client root context.
603
+ * @returns {unknown} the warning bar, or null when the environment is right or collapsed.
341
604
  */
342
605
  function AccessModeBanner({ ctx, sessionId, useSessions, useProjection }) {
343
606
  const { summary, state } = useHostMode(ctx, sessionId, useSessions, useProjection);
344
607
  const [dismissed, setDismissed] = useState(() => readDismissed(sessionId));
345
608
  const [removed, setRemoved] = useState(false);
346
609
  const [busy, setBusy] = useState(false);
347
- const [notice, setNotice] = useState(null);
610
+ const [notice, setNotice] = useState(/** @type {ClientNotice | null} */ (null));
348
611
 
349
612
  useEffect(() => {
350
613
  const sync = () => { setDismissed(readDismissed(sessionId)); };
@@ -442,8 +705,8 @@ window.__ModuleLoader__.load({
442
705
 
443
706
  /**
444
707
  * The quiet session-header marker that survives collapsing the banner.
445
- * @param props - slot standard props plus the client root context.
446
- * @returns the badge, or null when the environment is right or the banner shows.
708
+ * @param {ClientReminderProps} props - slot standard props plus the client root context.
709
+ * @returns {unknown} the badge, or null when the environment is right or the banner shows.
447
710
  */
448
711
  function AccessModeBadge({ ctx, sessionId, useSessions, useProjection }) {
449
712
  const { summary, state } = useHostMode(ctx, sessionId, useSessions, useProjection);
@@ -466,9 +729,9 @@ window.__ModuleLoader__.load({
466
729
 
467
730
  /**
468
731
  * Switch one workspace's still-blank sessions to the host default preset.
469
- * @param ctx - client root context.
470
- * @param workspaceId - the workspace whose sessions to revisit.
471
- * @returns the first failure message, or undefined when every eligible session moved.
732
+ * @param {ClientServiceHost} ctx - client root context.
733
+ * @param {string} workspaceId - the workspace whose sessions to revisit.
734
+ * @returns {Promise<string | undefined>} the first failure message, or undefined when every eligible session moved.
472
735
  */
473
736
  const switchWorkspaceSessions = async (ctx, workspaceId) => {
474
737
  const presets = service(ctx, "remote.agentPresets");
@@ -482,6 +745,7 @@ window.__ModuleLoader__.load({
482
745
  if (fallback === undefined || typeof fallback.id !== "string") return "找不到宿主默认 preset";
483
746
  const workspace = workspaces.list.getSnapshot().items.find((item) => item.workspaceId === workspaceId);
484
747
  if (workspace === undefined) return undefined;
748
+ /** @type {string | undefined} */
485
749
  let failure;
486
750
  for (const sessionId of workspace.sessionIds) {
487
751
  const summary = sessions.list.getSnapshot().byId[sessionId];
@@ -545,7 +809,7 @@ window.__ModuleLoader__.load({
545
809
  justifyContent: "space-between",
546
810
  },
547
811
  cardTitle: { fontSize: 13, fontWeight: 600 },
548
- hint: { fontSize: 12, opacity: 0.6 },
812
+ hint: { fontSize: 12, opacity: 0.7 },
549
813
  row: {
550
814
  display: "flex",
551
815
  flexDirection: "column",
@@ -599,7 +863,7 @@ window.__ModuleLoader__.load({
599
863
  fixableTag: { fontSize: 11, color: "#5ecf86", marginLeft: 4, marginRight: 4 },
600
864
  summary: { display: "flex", flexDirection: "column", gap: 3, fontSize: 12 },
601
865
  summaryLine: { display: "flex", flexWrap: "wrap", gap: 10, alignItems: "center" },
602
- summaryMuted: { opacity: 0.55 },
866
+ summaryMuted: { opacity: 0.7 },
603
867
  refreshTag: { fontSize: 12, color: "#e0b04a" },
604
868
  countOk: { color: "#5ecf86" },
605
869
  countWarn: { color: "#e0b04a" },
@@ -632,7 +896,7 @@ window.__ModuleLoader__.load({
632
896
  checkRemedy: { opacity: 0.6 },
633
897
  };
634
898
 
635
- /** Verdict colors: ready / blocked / error / idle. */
899
+ /** Verdict colors: ready / blocked / error / idle. @type {Record<"ready" | "blocked" | "error" | "idle", { fg: string, bg: string }>} */
636
900
  const verdictColors = {
637
901
  ready: { fg: "#5ecf86", bg: "rgba(94, 207, 134, 0.14)" },
638
902
  blocked: { fg: "#ff8f6b", bg: "rgba(255, 143, 107, 0.14)" },
@@ -642,8 +906,8 @@ window.__ModuleLoader__.load({
642
906
 
643
907
  /**
644
908
  * One status pill.
645
- * @param props - label, tone, and optional tooltip.
646
- * @returns the pill element.
909
+ * @param {ClientPillProps} props - label, tone, and optional tooltip.
910
+ * @returns {unknown} the pill element.
647
911
  */
648
912
  function Pill({ label, tone, title }) {
649
913
  const color = verdictColors[tone] ?? verdictColors.idle;
@@ -667,8 +931,8 @@ window.__ModuleLoader__.load({
667
931
 
668
932
  /**
669
933
  * One neutral button; the caller supplies emphasis.
670
- * @param props - label, click handler, and optional emphasis/disabled.
671
- * @returns the button element.
934
+ * @param {ClientBtnProps} props - label, click handler, and optional emphasis/disabled.
935
+ * @returns {unknown} the button element.
672
936
  */
673
937
  function Btn({ label, onClick, primary, disabled, small }) {
674
938
  return h(
@@ -695,8 +959,8 @@ window.__ModuleLoader__.load({
695
959
 
696
960
  /**
697
961
  * The sidebar glyph: a terminal window.
698
- * @param props - requested size and selection state.
699
- * @returns the icon element.
962
+ * @param {{ size?: number, active?: boolean }} props - requested size and selection state.
963
+ * @returns {unknown} the icon element.
700
964
  */
701
965
  function WslIcon({ size, active }) {
702
966
  const edge = typeof size === "number" ? size : 16;
@@ -722,33 +986,34 @@ window.__ModuleLoader__.load({
722
986
 
723
987
  /**
724
988
  * A titled card.
725
- * @param props - title, optional head actions, and children.
726
- * @returns the card element.
989
+ * @param {ClientCardProps} props - title, optional head actions, and children.
990
+ * @returns {unknown} the card element.
727
991
  */
728
992
  function Card({ title, actions, children }) {
729
993
  return h(
730
994
  "section",
731
995
  { style: styles.card },
732
- h("div", { style: styles.cardHead }, h("div", { style: styles.cardTitle }, title), actions ?? null),
996
+ h("div", { style: styles.cardHead }, h("h2", { style: { ...styles.cardTitle, margin: 0 } }, title), actions ?? null),
733
997
  children,
734
998
  );
735
999
  }
736
1000
 
737
1001
  /**
738
1002
  * The pill for one distro's check state.
739
- * @param props - the cached check state, if any.
740
- * @returns the pill element.
1003
+ * @param {{ state?: ClientCheckRow }} props - the cached check state, if any.
1004
+ * @returns {unknown} the pill element.
741
1005
  */
742
1006
  function CheckPill({ state }) {
743
1007
  if (state === undefined || state.phase === undefined) return h(Pill, { label: "未检查", tone: "idle" });
744
1008
  if (state.phase === "checking") return h(Pill, { label: "快速检查中…", tone: "idle" });
745
1009
  if (state.phase === "fullChecking") {
746
1010
  return h(Pill, {
747
- label: "完整检查中…",
1011
+ label: "完整诊断中…",
748
1012
  tone: "idle",
749
- title: "正在运行完整检查并修复插件自有状态",
1013
+ title: "正在运行只读的完整诊断",
750
1014
  });
751
1015
  }
1016
+ if (state.phase === "repairing") return h(Pill, { label: "修复中…", tone: "idle", title: "正在修复插件自有状态并复检" });
752
1017
  if (state.phase === "refreshing") return h(Pill, { label: "复核中…", tone: "idle", title: "面板正在后台复核上次结果" });
753
1018
  if (state.phase === "error") return h(Pill, { label: "无法检查", tone: "error" });
754
1019
  if (state.verdict === "ready") return h(Pill, { label: "正常", tone: "ready" });
@@ -762,9 +1027,8 @@ window.__ModuleLoader__.load({
762
1027
 
763
1028
  /**
764
1029
  * A numbered list of doctor findings.
765
- * @param props - heading, findings, whether they block, and the ids the
766
- * full check can repair.
767
- * @returns the list, or null when there is nothing to show.
1030
+ * @param {{ heading: string, items?: ClientFinding[], severity?: string, repairable?: string[] }} props - heading, findings, whether they block, and the ids the explicit repair can repair.
1031
+ * @returns {unknown} the list, or null when there is nothing to show.
768
1032
  */
769
1033
  function IssueList({ heading, items, severity, repairable }) {
770
1034
  if (!Array.isArray(items) || items.length === 0) return null;
@@ -791,9 +1055,9 @@ window.__ModuleLoader__.load({
791
1055
  }
792
1056
 
793
1057
  /**
794
- * The full check's repair rows: what the doctor did, with its status mark.
795
- * @param props - the `fix.*` rows the full run answered with.
796
- * @returns the list, or null when the run has no repair rows.
1058
+ * The repair action's rows: what the doctor did, with its status mark.
1059
+ * @param {{ items?: StatusRepair[] }} props - the `fix.*` rows the repair answered with.
1060
+ * @returns {unknown} the list, or null when the run has no repair rows.
797
1061
  */
798
1062
  function RepairList({ items }) {
799
1063
  if (!Array.isArray(items) || items.length === 0) return null;
@@ -827,8 +1091,8 @@ window.__ModuleLoader__.load({
827
1091
  * shows the same rows the failures came from, so nothing is hidden. The
828
1092
  * catalog rows a quick run never executed are counted in one line instead
829
1093
  * of listed as fake "not run" checks.
830
- * @param props - the cached check state.
831
- * @returns the toggle and, open, the grouped list.
1094
+ * @param {{ state: ClientCheckRow }} props - the cached check state.
1095
+ * @returns {unknown} the toggle and, open, the grouped list.
832
1096
  */
833
1097
  function CheckDetails({ state }) {
834
1098
  const [open, setOpen] = useState(false);
@@ -840,7 +1104,15 @@ window.__ModuleLoader__.load({
840
1104
  .filter((group) => group.rows.length > 0);
841
1105
  const other = checks.filter((row) => !order.includes(row.section));
842
1106
  if (other.length > 0) groups.push({ section: "other", rows: other });
1107
+ /**
1108
+ * @param {string} status - the doctor's check status.
1109
+ * @returns {string} the status mark.
1110
+ */
843
1111
  const mark = (status) => status === "ok" ? "✓" : status === "fail" ? "✗" : status === "warn" ? "!" : status === "unknown" ? "?" : status === "skipped" ? "-" : "i";
1112
+ /**
1113
+ * @param {string} status - the doctor's check status.
1114
+ * @returns {Record<string, unknown>} the mark's color for that status.
1115
+ */
844
1116
  const tone = (status) => status === "ok" ? styles.countOk : status === "fail" ? styles.countFail : status === "warn" || status === "unknown" ? styles.countWarn : styles.summaryMuted;
845
1117
  return h(
846
1118
  "div",
@@ -869,7 +1141,7 @@ window.__ModuleLoader__.load({
869
1141
  )),
870
1142
  )),
871
1143
  typeof state.notRun === "number" && state.notRun > 0
872
- ? h("div", { style: styles.hint }, `本次是快速检查,只覆盖首条命令的前置项;完整检查还会运行 ${String(state.notRun)} 项(agent 链路、工具、网络、配置等)。`)
1144
+ ? h("div", { style: styles.hint }, `本次是快速检查,只覆盖首条命令的前置项;完整诊断还会运行 ${String(state.notRun)} 项(agent 链路、工具、网络、配置等)。`)
873
1145
  : null,
874
1146
  )
875
1147
  : null,
@@ -878,8 +1150,8 @@ window.__ModuleLoader__.load({
878
1150
 
879
1151
  /**
880
1152
  * Format a check timestamp with a relative hint.
881
- * @param at - epoch milliseconds.
882
- * @returns the display label.
1153
+ * @param {number} at - epoch milliseconds.
1154
+ * @returns {string} the display label.
883
1155
  */
884
1156
  const checkedLabel = (at) => {
885
1157
  const date = new Date(at);
@@ -898,8 +1170,8 @@ window.__ModuleLoader__.load({
898
1170
 
899
1171
  /**
900
1172
  * The result's structure: when the check ran and how its rows landed.
901
- * @param props - the cached check state.
902
- * @returns the summary block.
1173
+ * @param {{ state: ClientCheckRow }} props - the cached check state.
1174
+ * @returns {unknown} the summary block.
903
1175
  */
904
1176
  function ResultSummary({ state }) {
905
1177
  const counts = state.counts ?? {};
@@ -920,8 +1192,8 @@ window.__ModuleLoader__.load({
920
1192
  { style: styles.summaryLine },
921
1193
  h("span", { style: styles.summaryMuted }, state.verdict === "error" ? "尝试检查:" : "上次检查:"),
922
1194
  h("span", null, typeof state.checkedAt === "number" ? checkedLabel(state.checkedAt) : "时间未知"),
923
- h("span", { style: styles.summaryMuted }, state.repaired === true
924
- ? (Array.isArray(state.repairs) && state.repairs.length > 0 ? "完整检查 · 已修复" : "完整检查")
1195
+ h("span", { style: styles.summaryMuted }, state.full === true
1196
+ ? (state.repaired === true ? "完整诊断 · 已修复" : "完整诊断")
925
1197
  : "快速检查"),
926
1198
  h("span", { style: styles.summaryMuted }, `来源:${state.source === "background" ? "后台" : "手动"}`),
927
1199
  state.cached === true ? h("span", { style: styles.summaryMuted }, "缓存结果") : null,
@@ -956,19 +1228,26 @@ window.__ModuleLoader__.load({
956
1228
 
957
1229
  // ── The panel ──────────────────────────────────────────────────────────
958
1230
 
1231
+ /**
1232
+ * The row phases in which a request is still in flight: a list read must
1233
+ * leave such a row alone (see `loadDistros`).
1234
+ * @type {Set<string | undefined>}
1235
+ */
1236
+ const IN_FLIGHT = new Set(["checking", "fullChecking", "repairing", "refreshing"]);
1237
+
959
1238
  /**
960
1239
  * The WSL environment page: the installed distros, their quick verdicts, and
961
1240
  * the directories recorded for Windows access.
962
- * @param props - the client root context.
963
- * @returns the page element.
1241
+ * @param {ClientPanelProps} props - the client root context.
1242
+ * @returns {unknown} the page element.
964
1243
  */
965
1244
  function WslPanel({ ctx }) {
966
1245
  const [phase, setPhase] = useState("loading");
967
- const [distros, setDistros] = useState([]);
968
- const [checks, setChecks] = useState({});
969
- const [notice, setNotice] = useState(null);
970
- const [accessPaths, setAccessPaths] = useState(null);
971
- const [plugin, setPlugin] = useState({ phase: "loading" });
1246
+ const [distros, setDistros] = useState(/** @type {string[]} */ ([]));
1247
+ const [checks, setChecks] = useState(/** @type {ClientCheckTable} */ ({}));
1248
+ const [notice, setNotice] = useState(/** @type {ClientNotice | null} */ (null));
1249
+ const [accessPaths, setAccessPaths] = useState(/** @type {string[] | null} */ (null));
1250
+ const [plugin, setPlugin] = useState(/** @type {ClientPluginState} */ ({ phase: "loading" }));
972
1251
 
973
1252
  /** Re-read the Windows-access record (best effort; the panel still works without it). */
974
1253
  const loadAccessPaths = async () => {
@@ -985,7 +1264,7 @@ window.__ModuleLoader__.load({
985
1264
  * host's cache TTL ask the host's plugin-manager for a fresh answer; a
986
1265
  * click forces one. The installed version stays visible while a later
987
1266
  * check fails, so the card never turns into a bare error.
988
- * @param refresh - whether to bypass the host's version cache.
1267
+ * @param {boolean} [refresh] - whether to bypass the host's version cache.
989
1268
  */
990
1269
  const loadPlugin = async (refresh = false) => {
991
1270
  setPlugin((previous) => ({
@@ -1064,7 +1343,7 @@ window.__ModuleLoader__.load({
1064
1343
  * keeps its previous summary until the answer arrives; a doctor failure
1065
1344
  * comes back as a normal error verdict (and is stored), while a
1066
1345
  * transport failure leaves the row with the reason it has no result.
1067
- * @param distro - the distro to re-check.
1346
+ * @param {string} distro - the distro to re-check.
1068
1347
  */
1069
1348
  const refreshBackground = async (distro) => {
1070
1349
  setChecks((previous) => {
@@ -1082,7 +1361,7 @@ window.__ModuleLoader__.load({
1082
1361
 
1083
1362
  /**
1084
1363
  * Load the distro list and the stored results.
1085
- * @param allowBackground - whether running distros' stored results may be
1364
+ * @param {boolean} [allowBackground] - whether running distros' stored results may be
1086
1365
  * re-checked in the background (the initial load only, not a manual
1087
1366
  * refresh: a refresh is a list read, not a probe).
1088
1367
  */
@@ -1092,20 +1371,39 @@ window.__ModuleLoader__.load({
1092
1371
  try {
1093
1372
  const answer = await statusRequest("");
1094
1373
  setDistros(Array.isArray(answer.distros) ? answer.distros : []);
1095
- const cached = {};
1096
- for (const entry of Array.isArray(answer.cached) ? answer.cached : []) {
1097
- cached[entry.distro] = { phase: "done", ...entry, cached: true };
1098
- }
1099
- setChecks(cached);
1374
+ const stored = Array.isArray(answer.cached) ? answer.cached : [];
1375
+ // The list read MERGES into the rows: one whose check is still in
1376
+ // flight keeps its state. Replacing the whole table reset such a
1377
+ // row to its stored result, which re-enabled the row's buttons (a
1378
+ // second doctor could start beside the first) and let the first
1379
+ // check's late answer land over whatever had replaced it.
1380
+ setChecks((previous) => {
1381
+ /** @type {ClientCheckTable} */
1382
+ const next = {};
1383
+ for (const [distro, state] of Object.entries(previous)) {
1384
+ if (state !== undefined && IN_FLIGHT.has(state.phase)) next[distro] = state;
1385
+ }
1386
+ for (const entry of stored) {
1387
+ if (next[entry.distro] === undefined) next[entry.distro] = { phase: "done", ...entry, cached: true };
1388
+ }
1389
+ return next;
1390
+ });
1100
1391
  setPhase("ready");
1101
1392
  if (allowBackground) {
1102
1393
  const running = new Set(Array.isArray(answer.running) ? answer.running : []);
1103
- for (const entry of Array.isArray(answer.cached) ? answer.cached : []) {
1394
+ for (const entry of stored) {
1104
1395
  // A result from the last minute is already current; an error is
1105
1396
  // not retried automatically (the row's check button is the way
1106
1397
  // back), so a persistent failure cannot spin on every load.
1107
1398
  const recent = typeof entry.checkedAt === "number" && Date.now() - entry.checkedAt < 60_000;
1108
- if (running.has(entry.distro) && entry.verdict !== "error" && !recent) void refreshBackground(entry.distro);
1399
+ // A full diagnosis or a repair is the user's own result. A
1400
+ // background re-check is a QUICK one: it would drop the repair
1401
+ // button and the repair's before → after evidence, sixty
1402
+ // seconds after the user last opened the panel. (The route
1403
+ // answers such a stored result as it is, for a client that
1404
+ // asks anyway.)
1405
+ const userOwn = entry.full === true || entry.repaired === true;
1406
+ if (running.has(entry.distro) && entry.verdict !== "error" && !recent && !userOwn) void refreshBackground(entry.distro);
1109
1407
  }
1110
1408
  }
1111
1409
  } catch (error) {
@@ -1124,6 +1422,10 @@ window.__ModuleLoader__.load({
1124
1422
  void loadPlugin();
1125
1423
  }, []);
1126
1424
 
1425
+ /**
1426
+ * Run the quick check against one distro.
1427
+ * @param {string} distro - the distro to check.
1428
+ */
1127
1429
  const check = async (distro) => {
1128
1430
  setNotice(null);
1129
1431
  setChecks((previous) => ({ ...previous, [distro]: { phase: "checking" } }));
@@ -1136,15 +1438,39 @@ window.__ModuleLoader__.load({
1136
1438
  };
1137
1439
 
1138
1440
  /**
1139
- * Run the full doctor with `--fix-owned`. The button is always
1140
- * **完整检查**: the run may repair plugin-owned state on the way, but the
1141
- * row does not relabel itself as a separate repair action. Only the
1142
- * plugin's own state is touched.
1143
- * @param distro - the distro to run against.
1441
+ * Run a full, read-only doctor report.
1442
+ * @param {string} distro - the distro to run against.
1144
1443
  */
1145
1444
  const fullCheck = async (distro) => {
1146
1445
  setNotice(null);
1147
1446
  setChecks((previous) => ({ ...previous, [distro]: { ...previous[distro], phase: "fullChecking" } }));
1447
+ try {
1448
+ const answer = await statusRequest(`?distro=${encodeURIComponent(distro)}&full=1`);
1449
+ setChecks((previous) => ({ ...previous, [distro]: { phase: "done", ...answer } }));
1450
+ const repairable = Array.isArray(answer.repairable) ? answer.repairable.length : 0;
1451
+ const remaining = (Array.isArray(answer.failures) ? answer.failures.length : 0)
1452
+ + (Array.isArray(answer.warnings) ? answer.warnings.length : 0);
1453
+ setNotice({
1454
+ kind: remaining === 0 ? "ok" : "info",
1455
+ text: repairable > 0
1456
+ ? `完整诊断完成:发现 ${String(repairable)} 项插件状态可修复;点击“修复插件状态”可单独执行,其他 ${String(Math.max(0, remaining - repairable))} 项按处理办法手动处理。`
1457
+ : remaining > 0
1458
+ ? `完整诊断完成:发现 ${String(remaining)} 项需按下方处理办法处理;没有可自动修复的插件状态。`
1459
+ : `已在 ${distro} 完成完整诊断,未发现待处理项。`,
1460
+ });
1461
+ } catch (error) {
1462
+ setChecks((previous) => ({ ...previous, [distro]: { ...previous[distro], phase: "error", error: messageOf(error) } }));
1463
+ }
1464
+ };
1465
+
1466
+ /**
1467
+ * Run the explicit plugin-owned repair after a full report identifies
1468
+ * repairable findings.
1469
+ * @param {string} distro - the distro to repair.
1470
+ */
1471
+ const repair = async (distro) => {
1472
+ setNotice(null);
1473
+ setChecks((previous) => ({ ...previous, [distro]: { ...previous[distro], phase: "repairing" } }));
1148
1474
  try {
1149
1475
  const answer = await statusRequest(`?distro=${encodeURIComponent(distro)}`, "POST");
1150
1476
  setChecks((previous) => ({ ...previous, [distro]: { phase: "done", ...answer } }));
@@ -1155,17 +1481,18 @@ window.__ModuleLoader__.load({
1155
1481
  setNotice({
1156
1482
  kind: fixed > 0 || remaining === 0 ? "ok" : "info",
1157
1483
  text: fixed > 0 && remaining > 0
1158
- ? `完整检查完成:已在 ${distro} 修复 ${String(fixed)} 项;仍有 ${String(remaining)} 项需按下方处理办法手动处理。`
1484
+ ? `插件状态修复完成:已在 ${distro} 修复 ${String(fixed)} 项;仍有 ${String(remaining)} 项需按下方处理办法手动处理。`
1159
1485
  : fixed > 0
1160
- ? `完整检查完成:已在 ${distro} 修复 ${String(fixed)} 项;复检通过。`
1486
+ ? `插件状态修复完成:已在 ${distro} 修复 ${String(fixed)} 项;复检通过。`
1161
1487
  : rows.length > 0
1162
- ? `完整检查完成:尝试修复 ${String(rows.length)} 项但未通过复检;请按下方处理办法手动处理。`
1488
+ ? `已尝试修复 ${String(rows.length)} 项,但复检未通过;请按下方处理办法继续处理。`
1163
1489
  : remaining > 0
1164
- ? `完整检查完成;没有可自动修复项,${String(remaining)} 项需按下方处理办法手动处理。`
1165
- : `已在 ${distro} 完成完整检查,未发现待修项。`,
1490
+ ? `未发现可自动修复的插件状态;${String(remaining)} 项需按下方处理办法手动处理。`
1491
+ : `已在 ${distro} 完成插件状态修复与复检。`,
1166
1492
  });
1167
1493
  } catch (error) {
1168
- setChecks((previous) => ({ ...previous, [distro]: { ...previous[distro], phase: "error", error: messageOf(error) } }));
1494
+ setChecks((previous) => ({ ...previous, [distro]: { ...previous[distro], phase: "done" } }));
1495
+ setNotice({ kind: "error", text: `插件状态修复失败:${messageOf(error)}` });
1169
1496
  }
1170
1497
  };
1171
1498
 
@@ -1175,7 +1502,7 @@ window.__ModuleLoader__.load({
1175
1502
  * when `wsl.exe` or the doctor is unavailable. The rows are removed only
1176
1503
  * after the route confirms, so a failed request leaves the last result
1177
1504
  * visible with the reason.
1178
- * @param distro - the distro whose result is cleared, or null for all.
1505
+ * @param {string | null} distro - the distro whose result is cleared, or null for all.
1179
1506
  */
1180
1507
  const clearResults = async (distro) => {
1181
1508
  setNotice(null);
@@ -1215,6 +1542,7 @@ window.__ModuleLoader__.load({
1215
1542
  && !Number.isNaN(new Date(latest.publishedAt).getTime())
1216
1543
  ? new Date(latest.publishedAt).toLocaleDateString()
1217
1544
  : undefined;
1545
+ /** @type {string} */
1218
1546
  let pluginStatusLine;
1219
1547
  if (plugin.phase === "loading") {
1220
1548
  pluginStatusLine = "正在读取版本信息…";
@@ -1253,7 +1581,7 @@ window.__ModuleLoader__.load({
1253
1581
  const busyAny = distros.some((distro) => {
1254
1582
  const state = checks[distro];
1255
1583
  return state !== undefined
1256
- && (state.phase === "checking" || state.phase === "fullChecking" || state.phase === "refreshing");
1584
+ && (state.phase === "checking" || state.phase === "fullChecking" || state.phase === "repairing" || state.phase === "refreshing");
1257
1585
  });
1258
1586
  const hasAnyResult = distros.some((distro) => checks[distro] !== undefined);
1259
1587
 
@@ -1273,7 +1601,7 @@ window.__ModuleLoader__.load({
1273
1601
  typeof plugin.installed === "string" ? h(Pill, { label: `v${plugin.installed}`, tone: "idle", title: "已安装的插件版本" }) : null,
1274
1602
  pluginAvailable ? h(Pill, { label: `可升级 ${latest.version}`, tone: "blocked", title: "发现新的插件版本" }) : null,
1275
1603
  ),
1276
- h("div", { style: styles.subtitle }, "诊断、版本与安全修复:已安装的发行版、快速检查、插件升级,以及插件自有状态的修复。"),
1604
+ h("div", { style: styles.subtitle }, "查看 WSL 发行版状态并管理插件版本。"),
1277
1605
  ),
1278
1606
  pluginAvailable ? h(
1279
1607
  "div",
@@ -1293,7 +1621,11 @@ window.__ModuleLoader__.load({
1293
1621
  })
1294
1622
  : null,
1295
1623
  ) : null,
1296
- notice === null ? null : h("div", { style: notice.kind === "ok" ? styles.noticeOk : notice.kind === "info" ? styles.noticeInfo : styles.notice }, notice.text),
1624
+ notice === null ? null : h("div", {
1625
+ role: notice.kind === "error" ? "alert" : "status",
1626
+ "aria-live": notice.kind === "error" ? "assertive" : "polite",
1627
+ style: notice.kind === "ok" ? styles.noticeOk : notice.kind === "info" ? styles.noticeInfo : styles.notice,
1628
+ }, notice.text),
1297
1629
  h(
1298
1630
  Card,
1299
1631
  {
@@ -1325,10 +1657,9 @@ window.__ModuleLoader__.load({
1325
1657
  : pluginAvailable && plugin.updateSupported !== true
1326
1658
  ? h("div", { style: styles.hint }, "当前宿主的插件管理器不支持一键升级;请在 Plugins 页升级。")
1327
1659
  : null,
1328
- h(
1329
- "div",
1330
- { style: styles.hint },
1331
- "版本检查委托给宿主的插件管理器(与 Plugins 页同源):读取 registry、弃用标记与 DSH/peer 兼容性。一键升级只在点击后执行,不会自动安装;完成后按提示刷新页面或重启 DSH。无法自动升级时,请在 Plugins 页手动安装新版本。",
1660
+ h("details", null,
1661
+ h("summary", { style: { ...styles.hint, cursor: "pointer" } }, "版本检查与升级说明"),
1662
+ h("div", { style: styles.hint }, "版本检查委托给宿主的插件管理器(与 Plugins 页同源):读取 registry、弃用标记与 DSH/peer 兼容性。一键升级只在点击后执行,不会自动安装;完成后按提示刷新页面或重启 DSH。无法自动升级时,请在 Plugins 页手动安装新版本。"),
1332
1663
  ),
1333
1664
  ),
1334
1665
  h(
@@ -1345,16 +1676,18 @@ window.__ModuleLoader__.load({
1345
1676
  onClick: () => { void clearResults(null); },
1346
1677
  }),
1347
1678
  h(Btn, {
1348
- label: "刷新",
1679
+ label: phase === "loading" ? "刷新中…" : "刷新",
1349
1680
  small: true,
1681
+ // A list read while a row's check is in flight would show
1682
+ // that row's stale stored result under re-enabled buttons.
1683
+ disabled: phase !== "ready" || busyAny,
1350
1684
  onClick: () => { void loadDistros(false); void loadAccessPaths(); },
1351
1685
  }),
1352
1686
  ),
1353
1687
  },
1354
- h(
1355
- "div",
1356
- { style: styles.hint },
1357
- "“快速检查”运行一次 doctor 的快速检查(与 /wsl-doctor 同源):验证该发行版的 bwrap、systemd 与 Linger 等前置项。“完整检查”运行完整 doctor,并只修复插件自有状态(残留 session scope、损坏的 agent 缓存)后复检、显示 before→after。两个按钮都可在结果出现后再次点击,每次都重新执行。自动修复不安装软件包、不改写 Windows 配置;其余告警按各自处理办法手动处理。检查会让停止的发行版启动,所以只在点击时执行;页面加载的后台复核只针对正在运行的发行版,失败会按实际观测覆盖并标为“后台”来源。“清除”删除该发行版本机保存的检测结果,“清除全部”清空所有结果;两者都不探测、不修改发行版,但清除后需再次检查。",
1688
+ h("details", null,
1689
+ h("summary", { style: { ...styles.hint, cursor: "pointer" } }, "检查与修复说明"),
1690
+ h("div", { style: styles.hint }, "“快速检查”验证首条命令的前置项;“完整诊断”运行完整 doctor,二者均只读。完整诊断发现可修复的插件自有状态(残留 session scope、损坏的 agent 缓存)后,才显示独立的“修复插件状态”按钮;修复后复检并显示 before→after。修复不安装软件包、不改写 Windows 配置;其余告警按各自处理办法手动处理。检查会启动已停止的发行版,所以只在点击时执行;页面加载的后台复核只针对正在运行的发行版,不会覆盖“完整诊断”和“修复”的结果,失败会按实际观测覆盖并标为“后台”来源。“清除”删除该发行版本机保存的检测结果,“清除全部”清空所有结果;两者都不探测、不修改发行版,但清除后需再次检查。"),
1358
1691
  ),
1359
1692
  phase === "loading"
1360
1693
  ? h("div", { style: styles.empty }, "加载中…")
@@ -1368,17 +1701,18 @@ window.__ModuleLoader__.load({
1368
1701
  const checking = state !== undefined && state.phase === "checking";
1369
1702
  const fullChecking = state !== undefined && state.phase === "fullChecking";
1370
1703
  const refreshing = state !== undefined && state.phase === "refreshing";
1371
- const busy = checking || fullChecking || refreshing;
1704
+ const repairing = state !== undefined && state.phase === "repairing";
1705
+ const busy = checking || fullChecking || repairing || refreshing;
1372
1706
  const hasResult = state !== undefined && (state.phase === "done" || state.phase === "error");
1373
1707
  const repairable = Array.isArray(state?.repairable) ? state.repairable : [];
1374
- const canRepair = done && repairable.length > 0;
1708
+ const canRepair = done && state.full === true && repairable.length > 0;
1375
1709
  const findings = done
1376
1710
  ? (Array.isArray(state.failures) ? state.failures.length : 0)
1377
1711
  + (Array.isArray(state.warnings) ? state.warnings.length : 0)
1378
1712
  : 0;
1379
1713
  return h(
1380
1714
  "div",
1381
- { key: distro, style: styles.row },
1715
+ { key: distro, style: styles.row, "aria-busy": busy },
1382
1716
  h(
1383
1717
  "div",
1384
1718
  { style: styles.rowHead },
@@ -1392,11 +1726,19 @@ window.__ModuleLoader__.load({
1392
1726
  onClick: () => { void check(distro); },
1393
1727
  }),
1394
1728
  h(Btn, {
1395
- label: fullChecking ? "完整检查中…" : "完整检查",
1729
+ label: fullChecking ? "完整诊断中…" : "完整诊断",
1396
1730
  small: true,
1397
1731
  disabled: busy,
1398
1732
  onClick: () => { void fullCheck(distro); },
1399
1733
  }),
1734
+ canRepair
1735
+ ? h(Btn, {
1736
+ label: repairing ? "修复中…" : `修复插件状态(${String(repairable.length)})`,
1737
+ small: true,
1738
+ disabled: busy,
1739
+ onClick: () => { void repair(distro); },
1740
+ })
1741
+ : null,
1400
1742
  hasResult
1401
1743
  ? h(Btn, {
1402
1744
  label: "清除",
@@ -1407,13 +1749,15 @@ window.__ModuleLoader__.load({
1407
1749
  : null,
1408
1750
  ),
1409
1751
  state === undefined
1410
- ? h("div", { style: styles.hint }, "尚未检查:点击“快速检查”(约 10 秒)或“完整检查”;两者都会启动停止的发行版。")
1752
+ ? h("div", { style: styles.hint }, "尚未检查:选择快速检查或完整诊断。检查可能启动已停止的发行版。")
1411
1753
  : state.phase === "checking"
1412
- ? h("div", { style: styles.hint }, "正在运行快速检查…(会启动停止的发行版)")
1754
+ ? h("div", { role: "status", "aria-live": "polite", "aria-atomic": "true", style: styles.hint }, "正在启动发行版(若已停止)并运行快速检查…")
1413
1755
  : state.phase === "fullChecking"
1414
- ? h("div", { style: styles.hint }, "正在运行完整检查,并修复插件自有状态(残留 session scope、损坏的 agent 缓存)…")
1756
+ ? h("div", { role: "status", "aria-live": "polite", "aria-atomic": "true", style: styles.hint }, "正在启动发行版(若已停止)并运行只读的完整诊断…")
1757
+ : state.phase === "repairing"
1758
+ ? h("div", { role: "status", "aria-live": "polite", "aria-atomic": "true", style: styles.hint }, "正在启动发行版(若已停止),修复插件自有状态并复检…")
1415
1759
  : state.phase === "error"
1416
- ? h("div", { style: styles.detail }, h("span", { style: styles.failure }, state.error))
1760
+ ? h("div", { role: "alert", "aria-live": "assertive", style: styles.detail }, h("span", { style: styles.failure }, state.error))
1417
1761
  : h(
1418
1762
  "div",
1419
1763
  { style: styles.detail },
@@ -1426,17 +1770,17 @@ window.__ModuleLoader__.load({
1426
1770
  heading: `待修项(${String(Array.isArray(state.failures) ? state.failures.length : 0)})`,
1427
1771
  items: state.failures,
1428
1772
  severity: "fail",
1429
- repairable,
1773
+ repairable: canRepair ? repairable : [],
1430
1774
  }),
1431
1775
  h(IssueList, {
1432
1776
  heading: `告警(${String(Array.isArray(state.warnings) ? state.warnings.length : 0)})`,
1433
1777
  items: state.warnings,
1434
1778
  severity: "warn",
1435
- repairable,
1779
+ repairable: canRepair ? repairable : [],
1436
1780
  }),
1437
1781
  findings > 0
1438
1782
  ? h("div", { style: styles.hint }, canRepair
1439
- ? "标有“可自动修复”的项会由“完整检查”处理;其余项目需按处理办法手动处理。"
1783
+ ? "标有“可自动修复”的项可由“修复插件状态”处理;其余项目需按处理办法手动处理。"
1440
1784
  : "以上项目没有可自动修复项,需按各自处理办法手动处理。自动修复只覆盖残留 session scope 与损坏的 agent 缓存。")
1441
1785
  : null,
1442
1786
  h(CheckDetails, { state }),
@@ -1475,7 +1819,7 @@ window.__ModuleLoader__.load({
1475
1819
 
1476
1820
  // ── The access-mode prompt ─────────────────────────────────────────────
1477
1821
 
1478
- /** One pending prompt, shared by the watcher and the overlay occupant. */
1822
+ /** One pending prompt, shared by the watcher and the overlay occupant. @type {ClientAccessPrompt} */
1479
1823
  const accessPrompt = {
1480
1824
  value: null,
1481
1825
  listeners: new Set(),
@@ -1492,13 +1836,14 @@ window.__ModuleLoader__.load({
1492
1836
 
1493
1837
  /**
1494
1838
  * The modal that asks how a newly added distro workspace is opened.
1495
- * @param props - the client root context.
1496
- * @returns the modal, or null while nothing is pending.
1839
+ * @param {ClientPanelProps} props - the client root context.
1840
+ * @returns {unknown} the modal, or null while nothing is pending.
1497
1841
  */
1498
1842
  function AccessPrompt({ ctx }) {
1499
1843
  const [request, setRequest] = useState(accessPrompt.get());
1500
1844
  const [busy, setBusy] = useState(false);
1501
- const [error, setError] = useState(null);
1845
+ const [error, setError] = useState(/** @type {string | null} */ (null));
1846
+ const dialogRef = useRef(/** @type {ClientElement | null} */ (null));
1502
1847
 
1503
1848
  useEffect(() => accessPrompt.subscribe(() => {
1504
1849
  setRequest(accessPrompt.get());
@@ -1506,13 +1851,44 @@ window.__ModuleLoader__.load({
1506
1851
  setBusy(false);
1507
1852
  }), []);
1508
1853
 
1509
- // Dismissing the prompt takes the default: Remote WSL. Nothing is written,
1854
+ // A modal that owns the keyboard: focus moves to the recommended choice
1855
+ // when it opens, Tab/Shift+Tab cycle its buttons instead of walking into
1856
+ // the page behind it, and closing returns focus where it was. Escape and
1857
+ // the backdrop keep taking the default: Remote WSL. Nothing is written,
1510
1858
  // which is exactly what "keep the default" means for this record.
1511
1859
  useEffect(() => {
1512
1860
  if (request === null) return undefined;
1513
- const onKey = (event) => { if (event.key === "Escape") accessPrompt.set(null); };
1514
- document.addEventListener("keydown", onKey);
1515
- return () => document.removeEventListener("keydown", onKey);
1861
+ const previous = platform.document.activeElement ?? null;
1862
+ const dialog = dialogRef.current;
1863
+ /** @returns {ClientElement[]} the dialog's enabled buttons, in DOM order. */
1864
+ const focusables = () => Array.from(dialog?.querySelectorAll?.("button:not([disabled])") ?? []);
1865
+ const first = focusables()[0];
1866
+ first?.focus?.();
1867
+ /** @param {ClientKeyEvent} event - the key event on the document. */
1868
+ const onKey = (event) => {
1869
+ if (event.key === "Escape") {
1870
+ accessPrompt.set(null);
1871
+ return;
1872
+ }
1873
+ if (event.key !== "Tab") return;
1874
+ const items = focusables();
1875
+ if (items.length === 0) return;
1876
+ const active = platform.document.activeElement ?? null;
1877
+ const index = active === null ? -1 : items.indexOf(active);
1878
+ const backwards = event.shiftKey === true;
1879
+ const next = index < 0
1880
+ ? items[backwards ? items.length - 1 : 0]
1881
+ : items[(index + (backwards ? -1 : 1) + items.length) % items.length];
1882
+ if (next !== undefined) {
1883
+ event.preventDefault?.();
1884
+ next.focus?.();
1885
+ }
1886
+ };
1887
+ platform.document.addEventListener("keydown", onKey);
1888
+ return () => {
1889
+ platform.document.removeEventListener("keydown", onKey);
1890
+ previous?.focus?.();
1891
+ };
1516
1892
  }, [request]);
1517
1893
 
1518
1894
  if (request === null) return null;
@@ -1544,6 +1920,7 @@ window.__ModuleLoader__.load({
1544
1920
  return h(
1545
1921
  "div",
1546
1922
  {
1923
+ /** @param {ClientMouseEvent} event - the click on the backdrop. */
1547
1924
  onClick: (event) => { if (event.target === event.currentTarget) close(); },
1548
1925
  style: {
1549
1926
  position: "fixed",
@@ -1560,6 +1937,7 @@ window.__ModuleLoader__.load({
1560
1937
  h(
1561
1938
  "div",
1562
1939
  {
1940
+ ref: dialogRef,
1563
1941
  role: "dialog",
1564
1942
  "aria-modal": "true",
1565
1943
  "aria-label": "选择 WSL 工作区的打开方式",
@@ -1614,12 +1992,13 @@ window.__ModuleLoader__.load({
1614
1992
  * Watch for newly added WSL workspaces and raise the access-mode prompt.
1615
1993
  * Existing workspaces are the baseline: startup restoration must not ask
1616
1994
  * again for a workspace the operator already opened.
1617
- * @param ctx - client root context.
1618
- * @returns a disposer owned by the plugin fiber.
1995
+ * @param {ClientServiceHost} ctx - client root context.
1996
+ * @returns {(() => void) | undefined} a disposer owned by the plugin fiber.
1619
1997
  */
1620
1998
  const watchWorkspaces = (ctx) => {
1621
1999
  const workspaces = service(ctx, "workspaces");
1622
2000
  if (workspaces === undefined) return undefined;
2001
+ /** @type {Set<string> | undefined} */
1623
2002
  let known;
1624
2003
  const consider = () => {
1625
2004
  const snapshot = workspaces.list.getSnapshot();
@@ -1643,6 +2022,7 @@ window.__ModuleLoader__.load({
1643
2022
 
1644
2023
  return {
1645
2024
  inject: ["slots"],
2025
+ /** @param {ClientContext} ctx - the client root context. */
1646
2026
  apply(ctx) {
1647
2027
  // Sidebar panel: icon in the navigation column, page in the main seat.
1648
2028
  ctx.slots.inject("sidebar.panellist", function* () {
@@ -1710,7 +2090,7 @@ window.__ModuleLoader__.load({
1710
2090
  headers: { "content-type": "application/json" },
1711
2091
  body: JSON.stringify({ path: cwd }),
1712
2092
  });
1713
- const body = await answer.json().catch(() => ({}));
2093
+ const body = /** @type {{ error?: string }} */ (await answer.json().catch(() => ({})));
1714
2094
  if (!answer.ok) throw new Error(body.error ?? ("打开失败(HTTP " + answer.status + ")"));
1715
2095
  },
1716
2096
  }];