dsh-plugin-wsl-env 0.23.0 → 0.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client.js CHANGED
@@ -1,16 +1,37 @@
1
1
  /**
2
- * The doctor's GUI button: a pill in the conversation composer dock that opens
3
- * a small menu of wsl_doctor run modes — two depths (quick, full) and the
4
- * six single-section scopes. Picking an entry drops the matching `/wsl-doctor`
5
- * command into the current session's input and submits it; the commands
6
- * registry executes it host-side and the report renders in the UI without a
7
- * model turn.
2
+ * The plugin's web client: the navigation column's status panel and the
3
+ * post-add access-mode prompt.
8
4
  *
9
- * The composer dock's slot components receive the harness's standard props —
10
- * `inputActions` among them. Sending is `setDraft(text)` (replace the whole
11
- * draft with plain text) followed by `submit()` (send the current draft — the
12
- * published face has no submit-with-text verb). When those verbs are missing
13
- * the menu degrades to a draft prefill, never to a broken control.
5
+ * The panel (`WSL 环境`) answers two questions: which distros are installed,
6
+ * and whether one distro's environment is usable. The second answer is the
7
+ * authoritative doctor verdict — the same standalone CLI the `/wsl-doctor`
8
+ * command spawns — fetched from this plugin's own route,
9
+ * `GET /api/wsl-env/status?distro=<name>`. The route lives on the Host
10
+ * connection's authenticated exact-Fetch channel, which is why a browser plugin
11
+ * can reach it without a generated client Remote. Checks run only when asked:
12
+ * probing a stopped distro boots it, so a page load lists without probing.
13
+ *
14
+ * A checked row's second action is a full doctor run with `--fix-owned`
15
+ * (`POST` on the same route). Its label follows what it can do: **修复** when
16
+ * the report carries a finding the plugin can repair (a stale session scope or
17
+ * a broken agent cache), **完整检查** otherwise. It never installs packages or
18
+ * rewrites Windows-owned configuration; every other warning stays manual, and
19
+ * the `fix.*` rows carry the before → after state.
20
+ *
21
+ * The last result is persisted Host-side, so a page reload (or an app restart)
22
+ * still shows the last guidance and when it ran. On load, a stored result for
23
+ * a distro that is currently running is re-checked in the background (never a
24
+ * stopped one: a probe boots it); the result is labeled with its source, and
25
+ * a failed background run overwrites the stored result truthfully.
26
+ *
27
+ * The panel opens no workspace and runs no session: adding a workspace still
28
+ * happens where it always did. The only other surface is the access-mode
29
+ * prompt, which asks once how a newly added distro workspace is opened. Its
30
+ * Windows answer is persisted in this plugin's `auto-preset` row
31
+ * (`windowsWorkspaces`, a volatile Settings field), and that row stops adopting
32
+ * the WSL preset for those directories; the prompt also switches the
33
+ * workspace's blank session back to the host preset so the answer applies
34
+ * before the first turn.
14
35
  *
15
36
  * Loaded by the harness's web client loader through the `dsh.client`
16
37
  * declaration in package.json; the composition's bare-name row
@@ -22,196 +43,984 @@ window.__ModuleLoader__.load({
22
43
  factory(require) {
23
44
  const React = require("react");
24
45
  const h = React.createElement;
25
- const useEffect = React.useEffect;
26
46
  const useState = React.useState;
47
+ const useEffect = React.useEffect;
48
+
49
+ /** The plugin's status route (checks on GET, repair on POST); the row registers this exact path. */
50
+ const STATUS_PATH = "/api/wsl-env/status";
51
+ /** Sidebar panel id and order: below the shipped plugin/schedule entries. */
52
+ const PANEL_ID = "wsl-env";
53
+ const PANEL_ORDER = 25;
54
+ /** Profile entry id of the row whose volatile field carries the access choice. */
55
+ const AUTO_PRESET_ENTRY = "auto-preset";
56
+ const WINDOWS_FIELD = "windowsWorkspaces";
57
+ const UNC_RE = /^\\\\wsl(?:\.localhost|\$)\\([^\\]+)(?:\\([\s\S]*))?$/i;
58
+
59
+ const service = (ctx, name) => {
60
+ try {
61
+ return ctx.get(name);
62
+ } catch (error) {
63
+ return undefined;
64
+ }
65
+ };
66
+
67
+ const messageOf = (error) => (error && typeof error.message === "string" ? error.message : String(error));
68
+
69
+ const isWslUnc = (value) => typeof value === "string" && UNC_RE.test(value);
70
+
71
+ const normalize = (value) => value.trim().replace(/[\\/]+$/, "").replace(/\//g, "\\").toLowerCase();
72
+
73
+ const samePath = (a, b) => typeof a === "string" && typeof b === "string" && normalize(a) === normalize(b);
74
+
75
+ /**
76
+ * Fetch the route and decode its JSON answer.
77
+ * @param query - the query string, including `?`, or empty.
78
+ * @param method - `GET` for a check, `POST` for the repair action.
79
+ * @returns the decoded body.
80
+ * @throws with the route's own error message.
81
+ */
82
+ const statusRequest = async (query, method = "GET") => {
83
+ const answer = await fetch(STATUS_PATH + (query ?? ""), { method });
84
+ const body = await answer.json().catch(() => ({}));
85
+ if (!answer.ok) throw new Error(body.error ?? `状态接口返回 ${answer.status}`);
86
+ return body;
87
+ };
88
+
89
+ // ── Access-mode records ────────────────────────────────────────────────
90
+ // The choice lives in the auto-preset row so the host can honor it without
91
+ // a plugin-specific client Remote (the Client Remote assembly fixes its
92
+ // namespaces at build time). Settings reads/writes go through the shipped
93
+ // namespace.
94
+
95
+ /**
96
+ * Find the auto-preset settings view and its Windows-access paths.
97
+ * @param describe - the `settings.describe` answer.
98
+ * @returns the namespace view and the paths it currently carries.
99
+ */
100
+ const accessViewOf = (describe) => {
101
+ if (!describe || describe.ok !== true) return undefined;
102
+ const value = describe.value;
103
+ if (!value || value.writable !== true || !Array.isArray(value.namespaces)) return undefined;
104
+ // The composed entry id is the patch row id (`auto-preset`); a profile that
105
+ // nests the bundle under an include may qualify it, so accept that shape too.
106
+ const entry = value.namespaces.find((row) => row
107
+ && (row.ns === AUTO_PRESET_ENTRY || row.ns.endsWith("/" + AUTO_PRESET_ENTRY)));
108
+ if (entry === undefined) return undefined;
109
+ const configured = entry.value && Array.isArray(entry.value[WINDOWS_FIELD]) ? entry.value[WINDOWS_FIELD] : [];
110
+ return { entry, paths: configured.filter((path) => typeof path === "string") };
111
+ };
112
+
113
+ /**
114
+ * Read the current Windows-access paths.
115
+ * @param ctx - client root context.
116
+ * @returns `{ ok: true, paths }`, or the reason the record is unavailable.
117
+ */
118
+ const readAccess = async (ctx) => {
119
+ const settings = service(ctx, "remote.settings");
120
+ if (settings === undefined) return { ok: false, message: "设置服务不可用" };
121
+ const describe = await settings.describe();
122
+ const view = accessViewOf(describe);
123
+ if (view === undefined) return { ok: false, message: "auto-preset 配置不可写(或未装配)" };
124
+ return { ok: true, paths: view.paths };
125
+ };
126
+
127
+ /**
128
+ * Persist a complete Windows-access list.
129
+ * @param ctx - client root context.
130
+ * @param paths - the new list.
131
+ * @returns `undefined` on success, or the failure message.
132
+ */
133
+ const writeAccess = async (ctx, paths) => {
134
+ const settings = service(ctx, "remote.settings");
135
+ if (settings === undefined) return "设置服务不可用";
136
+ const describe = await settings.describe();
137
+ const view = accessViewOf(describe);
138
+ if (view === undefined) return "auto-preset 配置不可写(或未装配)";
139
+ const patch = { [WINDOWS_FIELD]: paths };
140
+ const answer = await settings.update(view.entry.ns, patch, view.entry.revision);
141
+ if (answer.ok !== true) return answer.error?.message ?? "设置写入被拒绝";
142
+ return undefined;
143
+ };
144
+
145
+ /**
146
+ * Switch one workspace's still-blank sessions to the host default preset.
147
+ * @param ctx - client root context.
148
+ * @param workspaceId - the workspace whose sessions to revisit.
149
+ * @returns the first failure message, or undefined when every eligible session moved.
150
+ */
151
+ const switchWorkspaceSessions = async (ctx, workspaceId) => {
152
+ const presets = service(ctx, "remote.agentPresets");
153
+ const sessions = service(ctx, "sessions");
154
+ const workspaces = service(ctx, "workspaces");
155
+ if (presets === undefined || sessions === undefined || workspaces === undefined) return "会话服务不可用";
156
+ const roster = await presets.list();
157
+ if (roster.ok !== true) return roster.error?.message ?? "无法读取 preset 清单";
158
+ const entries = Array.isArray(roster.value?.presets) ? roster.value.presets : [];
159
+ const fallback = entries.find((entry) => entry && entry.isDefault === true);
160
+ if (fallback === undefined || typeof fallback.id !== "string") return "找不到宿主默认 preset";
161
+ const workspace = workspaces.list.getSnapshot().items.find((item) => item.workspaceId === workspaceId);
162
+ if (workspace === undefined) return undefined;
163
+ let failure;
164
+ for (const sessionId of workspace.sessionIds) {
165
+ const summary = sessions.list.getSnapshot().byId[sessionId];
166
+ // A blank session still accepts a preset; one that started a turn keeps
167
+ // the history it was produced under, and the host refuses the switch.
168
+ if (summary === undefined || summary.blank !== true) continue;
169
+ const answer = await presets.select(sessionId, fallback.id);
170
+ if (answer.ok !== true && failure === undefined) failure = answer.error?.message ?? "preset 切换失败";
171
+ }
172
+ return failure;
173
+ };
174
+
175
+ // ── Presentation primitives ────────────────────────────────────────────
176
+
177
+ const styles = {
178
+ panel: {
179
+ boxSizing: "border-box",
180
+ height: "100%",
181
+ overflowY: "auto",
182
+ padding: "24px 28px 40px",
183
+ fontSize: 13,
184
+ lineHeight: 1.55,
185
+ },
186
+ inner: {
187
+ maxWidth: 780,
188
+ margin: "0 auto",
189
+ display: "flex",
190
+ flexDirection: "column",
191
+ gap: 18,
192
+ },
193
+ title: { fontSize: 20, fontWeight: 600, letterSpacing: 0.2 },
194
+ subtitle: { fontSize: 12, opacity: 0.6, marginTop: 2 },
195
+ card: {
196
+ border: "1px solid rgba(128, 128, 128, 0.28)",
197
+ borderRadius: 10,
198
+ padding: "14px 16px",
199
+ display: "flex",
200
+ flexDirection: "column",
201
+ gap: 10,
202
+ },
203
+ cardHead: {
204
+ display: "flex",
205
+ alignItems: "center",
206
+ gap: 8,
207
+ justifyContent: "space-between",
208
+ },
209
+ cardTitle: { fontSize: 13, fontWeight: 600 },
210
+ hint: { fontSize: 12, opacity: 0.6 },
211
+ row: {
212
+ display: "flex",
213
+ flexDirection: "column",
214
+ gap: 6,
215
+ padding: "8px 10px",
216
+ borderRadius: 6,
217
+ border: "1px solid rgba(128, 128, 128, 0.16)",
218
+ },
219
+ rowHead: { display: "flex", alignItems: "center", gap: 10 },
220
+ rowName: { flex: 1, minWidth: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" },
221
+ empty: { fontSize: 12, opacity: 0.55, padding: "4px 2px" },
222
+ notice: { fontSize: 12, color: "#ff8f6b" },
223
+ noticeOk: { fontSize: 12, color: "#5ecf86" },
224
+ noticeInfo: { fontSize: 12, opacity: 0.7 },
225
+ detail: { fontSize: 12, opacity: 0.8, display: "flex", flexDirection: "column", gap: 3 },
226
+ repair: { fontSize: 12, wordBreak: "break-word" },
227
+ failure: { fontSize: 12, opacity: 0.85, wordBreak: "break-word" },
228
+ warning: { fontSize: 12, opacity: 0.75, wordBreak: "break-word" },
229
+ code: { fontFamily: "var(--dsh-font-family-code, ui-monospace, monospace)", opacity: 0.9 },
230
+ fixableTag: { fontSize: 11, color: "#5ecf86", marginLeft: 4, marginRight: 4 },
231
+ summary: { display: "flex", flexDirection: "column", gap: 3, fontSize: 12 },
232
+ summaryLine: { display: "flex", flexWrap: "wrap", gap: 10, alignItems: "center" },
233
+ summaryMuted: { opacity: 0.55 },
234
+ refreshTag: { fontSize: 12, color: "#e0b04a" },
235
+ countOk: { color: "#5ecf86" },
236
+ countWarn: { color: "#e0b04a" },
237
+ countFail: { color: "#ff8f6b" },
238
+ sectionChip: { border: "1px solid rgba(128, 128, 128, 0.2)", borderRadius: 4, padding: "0 5px", fontSize: 11.5 },
239
+ checkDetails: { display: "flex", flexDirection: "column", gap: 4, marginTop: 2 },
240
+ detailToggle: {
241
+ alignSelf: "flex-start",
242
+ padding: 0,
243
+ border: "none",
244
+ background: "transparent",
245
+ color: "inherit",
246
+ opacity: 0.65,
247
+ fontSize: 12,
248
+ cursor: "pointer",
249
+ textDecoration: "underline",
250
+ textUnderlineOffset: 2,
251
+ },
252
+ checkBody: {
253
+ display: "flex",
254
+ flexDirection: "column",
255
+ gap: 6,
256
+ borderLeft: "2px solid rgba(128, 128, 128, 0.22)",
257
+ paddingLeft: 8,
258
+ },
259
+ checkGroup: { display: "flex", flexDirection: "column", gap: 2 },
260
+ checkGroupHead: { fontSize: 11, opacity: 0.5, letterSpacing: 0.3 },
261
+ checkRow: { fontSize: 12, opacity: 0.85, wordBreak: "break-word" },
262
+ checkMark: { display: "inline-block", width: 14 },
263
+ checkRemedy: { opacity: 0.6 },
264
+ };
27
265
 
28
- // The command plane, not the model: each entry drops a `/wsl-doctor` line.
29
- // Slash commands execute in the UI command plane against the commands
30
- // registry (`dsh-commands` contract) — the handler spawns the standalone
31
- // doctor CLI and the settled report renders detached from model history,
32
- // adding no tokens. A deployment without the command adapter rejects the
33
- // line at the composer instead of sending a prompt.
34
- const commandFor = (mode) => {
35
- if (mode.kind === "quick") return "/wsl-doctor quick";
36
- if (mode.kind === "full") return "/wsl-doctor full";
37
- return "/wsl-doctor " + mode.section;
266
+ /** Verdict colors: ready / blocked / error / idle. */
267
+ const verdictColors = {
268
+ ready: { fg: "#5ecf86", bg: "rgba(94, 207, 134, 0.14)" },
269
+ blocked: { fg: "#ff8f6b", bg: "rgba(255, 143, 107, 0.14)" },
270
+ error: { fg: "#e0b04a", bg: "rgba(224, 176, 74, 0.14)" },
271
+ idle: { fg: "inherit", bg: "rgba(128, 128, 128, 0.14)" },
38
272
  };
39
273
 
40
- // Menu layout: two depth entries, then the section scopes the wsl_doctor
41
- // tool accepts. Labels mirror the tool's own depth/section vocabulary.
42
- const MENU = [
43
- { header: "诊断深度" },
44
- { label: "快速诊断(推荐)", hint: "仅前置项,约 10 秒", mode: { kind: "quick" } },
45
- { label: "完整诊断", hint: "全部检查项含 agent 冒烟", mode: { kind: "full" } },
46
- { header: "分区诊断" },
47
- { label: "host", mode: { kind: "section", section: "host" } },
48
- { label: "sandbox", mode: { kind: "section", section: "sandbox" } },
49
- { label: "session", mode: { kind: "section", section: "session" } },
50
- { label: "conf", mode: { kind: "section", section: "conf" } },
51
- { label: "net", mode: { kind: "section", section: "net" } },
52
- { label: "agent", mode: { kind: "section", section: "agent" } },
53
- ];
54
-
55
- function DoctorButton(props) {
274
+ /**
275
+ * One status pill.
276
+ * @param props - label, tone, and optional tooltip.
277
+ * @returns the pill element.
278
+ */
279
+ function Pill({ label, tone, title }) {
280
+ const color = verdictColors[tone] ?? verdictColors.idle;
281
+ return h(
282
+ "span",
283
+ {
284
+ title,
285
+ style: {
286
+ padding: "1px 8px",
287
+ borderRadius: 999,
288
+ fontSize: 11.5,
289
+ lineHeight: "18px",
290
+ whiteSpace: "nowrap",
291
+ color: color.fg,
292
+ background: color.bg,
293
+ },
294
+ },
295
+ label,
296
+ );
297
+ }
298
+
299
+ /**
300
+ * One neutral button; the caller supplies emphasis.
301
+ * @param props - label, click handler, and optional emphasis/disabled.
302
+ * @returns the button element.
303
+ */
304
+ function Btn({ label, onClick, primary, disabled, small }) {
305
+ return h(
306
+ "button",
307
+ {
308
+ type: "button",
309
+ onClick,
310
+ disabled: disabled === true,
311
+ style: {
312
+ padding: small === true ? "3px 9px" : "6px 12px",
313
+ borderRadius: 6,
314
+ fontSize: small === true ? 12 : 12.5,
315
+ border: "1px solid rgba(128, 128, 128, 0.35)",
316
+ background: primary === true ? "rgba(86, 132, 255, 0.18)" : "transparent",
317
+ color: "inherit",
318
+ opacity: disabled === true ? 0.5 : 1,
319
+ cursor: disabled === true ? "default" : "pointer",
320
+ whiteSpace: "nowrap",
321
+ },
322
+ },
323
+ label,
324
+ );
325
+ }
326
+
327
+ /**
328
+ * The sidebar glyph: a terminal window.
329
+ * @param props - requested size and selection state.
330
+ * @returns the icon element.
331
+ */
332
+ function WslIcon({ size, active }) {
333
+ const edge = typeof size === "number" ? size : 16;
334
+ return h(
335
+ "svg",
336
+ {
337
+ width: edge,
338
+ height: edge,
339
+ viewBox: "0 0 16 16",
340
+ fill: "none",
341
+ stroke: "currentColor",
342
+ strokeWidth: 1.4,
343
+ strokeLinecap: "round",
344
+ strokeLinejoin: "round",
345
+ opacity: active === true ? 1 : 0.85,
346
+ "aria-hidden": "true",
347
+ },
348
+ h("rect", { x: 1.6, y: 2.4, width: 12.8, height: 11.2, rx: 2 }),
349
+ h("path", { d: "M4.4 6.2l2.1 1.8-2.1 1.8" }),
350
+ h("path", { d: "M8.6 9.8h3.1" }),
351
+ );
352
+ }
353
+
354
+ /**
355
+ * A titled card.
356
+ * @param props - title, optional head actions, and children.
357
+ * @returns the card element.
358
+ */
359
+ function Card({ title, actions, children }) {
360
+ return h(
361
+ "section",
362
+ { style: styles.card },
363
+ h("div", { style: styles.cardHead }, h("div", { style: styles.cardTitle }, title), actions ?? null),
364
+ children,
365
+ );
366
+ }
367
+
368
+ /**
369
+ * The pill for one distro's check state.
370
+ * @param props - the cached check state, if any.
371
+ * @returns the pill element.
372
+ */
373
+ function CheckPill({ state }) {
374
+ if (state === undefined || state.phase === undefined) return h(Pill, { label: "未检查", tone: "idle" });
375
+ if (state.phase === "checking") return h(Pill, { label: "检查中…", tone: "idle" });
376
+ if (state.phase === "repairing") {
377
+ return h(Pill, {
378
+ label: state.mode === "full" ? "检查中…" : "修复中…",
379
+ tone: "idle",
380
+ title: state.mode === "full" ? "正在运行完整检查(无可自动修复项)" : "正在运行完整检查并修复插件自有状态",
381
+ });
382
+ }
383
+ if (state.phase === "refreshing") return h(Pill, { label: "复核中…", tone: "idle", title: "面板正在后台复核上次结果" });
384
+ if (state.phase === "error") return h(Pill, { label: "无法检查", tone: "error" });
385
+ if (state.verdict === "ready") return h(Pill, { label: "正常", tone: "ready" });
386
+ if (state.verdict === "blocked") {
387
+ const count = Array.isArray(state.failures) ? state.failures.length : 0;
388
+ const label = count > 0 ? `异常 · ${count} 项` : state.cached === true ? "异常" : "有告警";
389
+ return h(Pill, { label, tone: "blocked" });
390
+ }
391
+ return h(Pill, { label: "检查失败", tone: "error" });
392
+ }
393
+
394
+ /**
395
+ * A numbered list of doctor findings.
396
+ * @param props - heading, findings, whether they block, and the ids the
397
+ * repair action can act on.
398
+ * @returns the list, or null when there is nothing to show.
399
+ */
400
+ function IssueList({ heading, items, severity, repairable }) {
401
+ if (!Array.isArray(items) || items.length === 0) return null;
402
+ return h(
403
+ "div",
404
+ null,
405
+ h("div", { style: { opacity: 0.7, marginBottom: 2 } }, heading),
406
+ items.map((item, index) => h(
407
+ "div",
408
+ {
409
+ key: `${String(item.id ?? "item")}-${String(index)}`,
410
+ style: severity === "warn" ? styles.warning : styles.failure,
411
+ },
412
+ h("span", { style: { opacity: 0.6, marginRight: 4 } }, `${String(index + 1)}.`),
413
+ h("span", { style: styles.code }, item.id),
414
+ Array.isArray(repairable) && repairable.includes(item.id)
415
+ ? h("span", { style: styles.fixableTag }, "可自动修复")
416
+ : null,
417
+ " — ",
418
+ item.detail ? `${item.detail}${item.remedy ? ";" : ""}` : "",
419
+ item.remedy ?? "",
420
+ )),
421
+ );
422
+ }
423
+
424
+ /**
425
+ * The repair action's own rows: what the doctor did, with its status mark.
426
+ * @param props - the `fix.*` rows the repair answered with.
427
+ * @returns the list, or null when the run has no repair rows.
428
+ */
429
+ function RepairList({ items }) {
430
+ if (!Array.isArray(items) || items.length === 0) return null;
431
+ return h(
432
+ "div",
433
+ null,
434
+ h("div", { style: { opacity: 0.7, marginBottom: 2 } }, `修复动作(${String(items.length)})`),
435
+ items.map((item, index) => h(
436
+ "div",
437
+ {
438
+ key: `${String(item.id ?? "fix")}-${String(index)}`,
439
+ style: styles.detail,
440
+ },
441
+ h(
442
+ "div",
443
+ { style: styles.repair },
444
+ h("span", { style: { opacity: 0.6, marginRight: 4 } }, item.status === "ok" ? "✓" : "!"),
445
+ h("span", { style: styles.code }, String(item.title ?? item.id ?? "")),
446
+ " — ",
447
+ String(item.detail ?? ""),
448
+ ),
449
+ item.remedy === undefined ? null : h("div", { style: styles.warning }, String(item.remedy)),
450
+ )),
451
+ );
452
+ }
453
+
454
+ /**
455
+ * The expandable per-check detail: every check the run executed, grouped
456
+ * by the doctor's section order, with its status and evidence. A green row
457
+ * is an assertion ("normal"), and this list is what backs it; a blocked row
458
+ * shows the same rows the failures came from, so nothing is hidden. The
459
+ * catalog rows a quick run never executed are counted in one line instead
460
+ * of listed as fake "not run" checks.
461
+ * @param props - the cached check state.
462
+ * @returns the toggle and, open, the grouped list.
463
+ */
464
+ function CheckDetails({ state }) {
56
465
  const [open, setOpen] = useState(false);
57
- const [root, setRoot] = useState(null);
466
+ const checks = Array.isArray(state?.checks) ? state.checks : [];
467
+ if (checks.length === 0) return null;
468
+ const order = ["host", "sandbox", "session", "conf", "net", "agent"];
469
+ const groups = order
470
+ .map((section) => ({ section, rows: checks.filter((row) => row.section === section) }))
471
+ .filter((group) => group.rows.length > 0);
472
+ const other = checks.filter((row) => !order.includes(row.section));
473
+ if (other.length > 0) groups.push({ section: "other", rows: other });
474
+ const mark = (status) => status === "ok" ? "✓" : status === "fail" ? "✗" : status === "warn" ? "!" : status === "unknown" ? "?" : status === "skipped" ? "-" : "i";
475
+ const tone = (status) => status === "ok" ? styles.countOk : status === "fail" ? styles.countFail : status === "warn" || status === "unknown" ? styles.countWarn : styles.summaryMuted;
476
+ return h(
477
+ "div",
478
+ { style: styles.checkDetails },
479
+ h("button", {
480
+ type: "button",
481
+ "aria-expanded": open,
482
+ onClick: () => setOpen((previous) => !previous),
483
+ style: styles.detailToggle,
484
+ }, open ? "收起检查详情" : `查看检查详情(${String(checks.length)} 项)`),
485
+ open
486
+ ? h(
487
+ "div",
488
+ { style: styles.checkBody },
489
+ groups.map((group) => h(
490
+ "div",
491
+ { key: group.section, style: styles.checkGroup },
492
+ h("div", { style: styles.checkGroupHead }, `${group.section}(${String(group.rows.length)})`),
493
+ group.rows.map((row) => h(
494
+ "div",
495
+ { key: row.id, style: styles.checkRow },
496
+ h("span", { style: { ...styles.checkMark, ...tone(row.status) } }, mark(row.status)),
497
+ h("span", { style: styles.code }, String(row.id)),
498
+ row.detail ? ` — ${String(row.detail)}` : "",
499
+ row.remedy ? h("span", { style: styles.checkRemedy }, ` 处理:${String(row.remedy)}`) : null,
500
+ )),
501
+ )),
502
+ typeof state.notRun === "number" && state.notRun > 0
503
+ ? h("div", { style: styles.hint }, `本次是快速检查,只覆盖首条命令的前置项;完整检查还会运行 ${String(state.notRun)} 项(agent 链路、工具、网络、配置等)。`)
504
+ : null,
505
+ )
506
+ : null,
507
+ );
508
+ }
58
509
 
59
- // Close on any outside click; the root node ref keeps the listener's
60
- // contains() check exact without querying the DOM.
61
- useEffect(() => {
62
- if (!open || !root) return undefined;
63
- const close = (event) => {
64
- if (root && !root.contains(event.target)) setOpen(false);
65
- };
66
- document.addEventListener("mousedown", close);
67
- return () => document.removeEventListener("mousedown", close);
68
- }, [open, root]);
69
-
70
- const send = (mode) => {
71
- setOpen(false);
72
- const command = commandFor(mode);
73
- const actions = props && props.inputActions;
74
- // The published InputActions face has no submit(text): submit() sends
75
- // the CURRENT draft, and insertText needs a captureInsertion() span.
76
- // setDraft replaces the whole draft with plain text, then submit()
77
- // sends it — one click, no span bookkeeping.
78
- if (actions && typeof actions.setDraft === "function" && typeof actions.submit === "function") {
79
- try {
80
- actions.setDraft(command);
81
- actions.submit();
82
- return;
83
- } catch (error) {
84
- // Fall through to the draft prefill below; the command text is the
85
- // same either way.
86
- }
510
+ /**
511
+ * Format a check timestamp with a relative hint.
512
+ * @param at - epoch milliseconds.
513
+ * @returns the display label.
514
+ */
515
+ const checkedLabel = (at) => {
516
+ const date = new Date(at);
517
+ const now = Date.now();
518
+ const minutes = Math.max(0, Math.floor((now - at) / 60_000));
519
+ const relative = minutes < 1
520
+ ? "刚刚"
521
+ : minutes < 60
522
+ ? `${String(minutes)} 分钟前`
523
+ : minutes < 1440
524
+ ? `${String(Math.floor(minutes / 60))} 小时前`
525
+ : `${String(Math.floor(minutes / 1440))} 天前`;
526
+ const stamp = `${date.toLocaleDateString()} ${date.toLocaleTimeString()}`;
527
+ return `${stamp}(${relative})`;
528
+ };
529
+
530
+ /**
531
+ * The result's structure: when the check ran and how its rows landed.
532
+ * @param props - the cached check state.
533
+ * @returns the summary block.
534
+ */
535
+ function ResultSummary({ state }) {
536
+ const counts = state.counts ?? {};
537
+ const statuses = [
538
+ ["通过", counts.ok, styles.countOk],
539
+ ["告警", counts.warn, styles.countWarn],
540
+ ["失败", counts.fail, styles.countFail],
541
+ ["未知", counts.unknown, styles.countWarn],
542
+ ["信息", counts.info, styles.summaryMuted],
543
+ ["跳过", counts.skipped, styles.summaryMuted],
544
+ ].filter(([, n]) => typeof n === "number" && n > 0);
545
+ const sections = Array.isArray(state.sections) ? state.sections : [];
546
+ return h(
547
+ "div",
548
+ { style: styles.summary },
549
+ h(
550
+ "div",
551
+ { style: styles.summaryLine },
552
+ h("span", { style: styles.summaryMuted }, state.verdict === "error" ? "尝试检查:" : "上次检查:"),
553
+ h("span", null, typeof state.checkedAt === "number" ? checkedLabel(state.checkedAt) : "时间未知"),
554
+ h("span", { style: styles.summaryMuted }, state.repaired === true
555
+ ? (Array.isArray(state.repairs) && state.repairs.length > 0 ? "完整检查 · 已修复" : "完整检查")
556
+ : "快速检查"),
557
+ h("span", { style: styles.summaryMuted }, `来源:${state.source === "background" ? "后台" : "手动"}`),
558
+ state.cached === true ? h("span", { style: styles.summaryMuted }, "缓存结果") : null,
559
+ state.phase === "refreshing" ? h("span", { style: styles.refreshTag }, "后台复核中…") : null,
560
+ ),
561
+ state.verdict === "error" ? null : h(
562
+ "div",
563
+ { style: styles.summaryLine },
564
+ statuses.map(([label, n, color]) => h("span", { key: String(label), style: color }, `${String(label)} ${String(n)}`)),
565
+ statuses.length === 0 ? h("span", { style: styles.summaryMuted }, "没有可汇总的检查项") : null,
566
+ ),
567
+ state.verdict === "error" || sections.length === 0 ? null : h(
568
+ "div",
569
+ { style: styles.summaryLine },
570
+ h("span", { style: styles.summaryMuted }, "分区:"),
571
+ sections.map((section) => {
572
+ const parts = [];
573
+ if (section.ok > 0) parts.push(`通过 ${String(section.ok)}`);
574
+ if (section.warn > 0) parts.push(`告警 ${String(section.warn)}`);
575
+ if (section.fail > 0) parts.push(`失败 ${String(section.fail)}`);
576
+ if (section.unknown > 0) parts.push(`未知 ${String(section.unknown)}`);
577
+ return h(
578
+ "span",
579
+ { key: section.section, style: styles.sectionChip },
580
+ h("span", { style: { opacity: 0.7, marginRight: 4 } }, section.section),
581
+ parts.length > 0 ? parts.join("、") : "无结论",
582
+ );
583
+ }),
584
+ ),
585
+ );
586
+ }
587
+
588
+ // ── The panel ──────────────────────────────────────────────────────────
589
+
590
+ /**
591
+ * The WSL environment page: the installed distros and their quick verdicts.
592
+ * @returns the page element.
593
+ */
594
+ function WslPanel() {
595
+ const [phase, setPhase] = useState("loading");
596
+ const [distros, setDistros] = useState([]);
597
+ const [checks, setChecks] = useState({});
598
+ const [notice, setNotice] = useState(null);
599
+
600
+ /**
601
+ * Re-check one already-running distro without the user asking. The row
602
+ * keeps its previous summary until the answer arrives; a doctor failure
603
+ * comes back as a normal error verdict (and is stored), while a
604
+ * transport failure leaves the row with the reason it has no result.
605
+ * @param distro - the distro to re-check.
606
+ */
607
+ const refreshBackground = async (distro) => {
608
+ setChecks((previous) => {
609
+ const current = previous[distro];
610
+ if (current === undefined || current.phase === "refreshing") return previous;
611
+ return { ...previous, [distro]: { ...current, phase: "refreshing" } };
612
+ });
613
+ try {
614
+ const answer = await statusRequest(`?distro=${encodeURIComponent(distro)}&refresh=1&background=1`);
615
+ setChecks((previous) => ({ ...previous, [distro]: { phase: "done", ...answer } }));
616
+ } catch (error) {
617
+ setChecks((previous) => ({ ...previous, [distro]: { ...previous[distro], phase: "error", error: messageOf(error) } }));
87
618
  }
88
- if (actions && typeof actions.setDraft === "function") {
89
- try {
90
- actions.setDraft(command);
91
- return;
92
- } catch (error) {
93
- // Ignored: the draft stays untouched rather than half-filled.
619
+ };
620
+
621
+ /**
622
+ * Load the distro list and the stored results.
623
+ * @param allowBackground - whether running distros' stored results may be
624
+ * re-checked in the background (the initial load only, not a manual
625
+ * refresh: a refresh is a list read, not a probe).
626
+ */
627
+ const loadDistros = async (allowBackground = false) => {
628
+ setPhase("loading");
629
+ setNotice(null);
630
+ try {
631
+ const answer = await statusRequest("");
632
+ setDistros(Array.isArray(answer.distros) ? answer.distros : []);
633
+ const cached = {};
634
+ for (const entry of Array.isArray(answer.cached) ? answer.cached : []) {
635
+ cached[entry.distro] = { phase: "done", ...entry, cached: true };
94
636
  }
637
+ setChecks(cached);
638
+ setPhase("ready");
639
+ if (allowBackground) {
640
+ const running = new Set(Array.isArray(answer.running) ? answer.running : []);
641
+ for (const entry of Array.isArray(answer.cached) ? answer.cached : []) {
642
+ // A result from the last minute is already current; an error is
643
+ // not retried automatically (the row's check button is the way
644
+ // back), so a persistent failure cannot spin on every load.
645
+ const recent = typeof entry.checkedAt === "number" && Date.now() - entry.checkedAt < 60_000;
646
+ if (running.has(entry.distro) && entry.verdict !== "error" && !recent) void refreshBackground(entry.distro);
647
+ }
648
+ }
649
+ } catch (error) {
650
+ setPhase("error");
651
+ setNotice({ kind: "error", text: messageOf(error) });
95
652
  }
96
653
  };
97
654
 
98
- const menu = open
99
- ? h(
100
- "div",
655
+ useEffect(() => {
656
+ // The first load may refresh stored results for running distros; the
657
+ // manual 刷新 button only re-reads the list.
658
+ void loadDistros(true);
659
+ }, []);
660
+
661
+ const check = async (distro) => {
662
+ setNotice(null);
663
+ setChecks((previous) => ({ ...previous, [distro]: { phase: "checking" } }));
664
+ try {
665
+ const answer = await statusRequest(`?distro=${encodeURIComponent(distro)}&refresh=1`);
666
+ setChecks((previous) => ({ ...previous, [distro]: { phase: "done", ...answer } }));
667
+ } catch (error) {
668
+ setChecks((previous) => ({ ...previous, [distro]: { phase: "error", error: messageOf(error) } }));
669
+ }
670
+ };
671
+
672
+ /**
673
+ * Run the full doctor with `--fix-owned`: the row labels it `修复` when a
674
+ * repairable finding exists and `完整检查` otherwise, but it is the same
675
+ * run. Only the plugin's own state is touched.
676
+ * @param distro - the distro to run against.
677
+ */
678
+ const repair = async (distro, mode = "repair") => {
679
+ setNotice(null);
680
+ setChecks((previous) => ({ ...previous, [distro]: { ...previous[distro], phase: "repairing", mode } }));
681
+ try {
682
+ const answer = await statusRequest(`?distro=${encodeURIComponent(distro)}`, "POST");
683
+ setChecks((previous) => ({ ...previous, [distro]: { phase: "done", ...answer } }));
684
+ const rows = Array.isArray(answer.repairs) ? answer.repairs : [];
685
+ const fixed = rows.filter((row) => row.status === "ok").length;
686
+ const remaining = (Array.isArray(answer.failures) ? answer.failures.length : 0)
687
+ + (Array.isArray(answer.warnings) ? answer.warnings.length : 0);
688
+ setNotice({
689
+ kind: fixed > 0 || remaining === 0 ? "ok" : "info",
690
+ text: fixed > 0 && remaining > 0
691
+ ? `已在 ${distro} 修复 ${String(fixed)} 项;仍有 ${String(remaining)} 项需按下方处理办法手动处理。`
692
+ : fixed > 0
693
+ ? `已在 ${distro} 修复 ${String(fixed)} 项;复检通过。`
694
+ : rows.length > 0
695
+ ? `尝试修复 ${String(rows.length)} 项但未通过复检;请按下方处理办法手动处理。`
696
+ : remaining > 0
697
+ ? `完整检查完成;没有可自动修复项,${String(remaining)} 项需按下方处理办法手动处理。`
698
+ : `已在 ${distro} 完成完整检查,未发现待修项。`,
699
+ });
700
+ } catch (error) {
701
+ setChecks((previous) => ({ ...previous, [distro]: { ...previous[distro], phase: "error", error: messageOf(error) } }));
702
+ }
703
+ };
704
+
705
+ return h(
706
+ "div",
707
+ { style: styles.panel },
708
+ h(
709
+ "div",
710
+ { style: styles.inner },
711
+ h(
712
+ "header",
713
+ null,
714
+ h("div", { style: styles.title }, "WSL 环境"),
715
+ h("div", { style: styles.subtitle }, "诊断与安全修复:已安装的发行版、快速检查,以及插件自有状态的修复。"),
716
+ ),
717
+ notice === null ? null : h("div", { style: notice.kind === "ok" ? styles.noticeOk : notice.kind === "info" ? styles.noticeInfo : styles.notice }, notice.text),
718
+ h(
719
+ Card,
101
720
  {
102
- // Anchored above the pill; the dock sits at the composer's
103
- // bottom edge, so the menu opens upward.
104
- style: {
105
- position: "absolute",
106
- bottom: "calc(100% + 6px)",
107
- right: 0,
108
- minWidth: 220,
109
- padding: "4px 0",
110
- borderRadius: 8,
111
- background: "var(--dsh-bg, #1f1f1f)",
112
- color: "inherit",
113
- boxShadow: "0 4px 16px rgba(0, 0, 0, 0.35)",
114
- border: "1px solid rgba(128, 128, 128, 0.35)",
115
- zIndex: 50,
116
- fontSize: 12,
117
- },
721
+ title: "发行版与环境状态",
722
+ actions: h(Btn, {
723
+ label: "刷新",
724
+ small: true,
725
+ onClick: () => { void loadDistros(false); },
726
+ }),
118
727
  },
119
- MENU.map((entry, index) => {
120
- if (entry.header) {
121
- return h(
122
- "div",
123
- {
124
- key: "header-" + entry.header,
125
- style: {
126
- padding: "5px 12px 3px",
127
- opacity: 0.55,
128
- fontSize: 11,
129
- userSelect: "none",
130
- },
131
- },
132
- entry.header
133
- );
134
- }
135
- return h(
136
- "div",
137
- {
138
- key: "item-" + String(index),
139
- onClick: () => send(entry.mode),
140
- style: {
141
- display: "flex",
142
- justifyContent: "space-between",
143
- gap: 10,
144
- padding: "6px 12px",
145
- cursor: "pointer",
146
- whiteSpace: "nowrap",
147
- },
148
- onMouseEnter: (event) => {
149
- event.currentTarget.style.background = "rgba(128, 128, 128, 0.2)";
150
- },
151
- onMouseLeave: (event) => {
152
- event.currentTarget.style.background = "transparent";
153
- },
154
- },
155
- h("span", null, entry.label),
156
- entry.hint
157
- ? h("span", { style: { opacity: 0.55, fontSize: 11 } }, entry.hint)
158
- : null
159
- );
160
- })
161
- )
162
- : null;
728
+ h(
729
+ "div",
730
+ { style: styles.hint },
731
+ "“检查”运行一次 doctor 的快速检查(与 /wsl-doctor 同源):验证该发行版的 bwrap、systemd 与 Linger 等前置项。右侧按钮按结果切换:存在可自动修复项时显示“修复”,只修复插件自有状态(残留 session scope、损坏的 agent 缓存)并复检、显示 before→after;否则显示“完整检查”,运行完整 doctor 以发现更多项。自动修复不安装软件包、不改写 Windows 配置;其余告警按各自处理办法手动处理。手动检查/修复会让停止的发行版启动,所以只在点击时执行;页面加载的后台复核只针对正在运行的发行版,失败会按实际观测覆盖并标为“后台”来源。",
732
+ ),
733
+ phase === "loading"
734
+ ? h("div", { style: styles.empty }, "加载中…")
735
+ : phase === "error"
736
+ ? h("div", { style: styles.empty }, "状态接口不可用(需要 Web 连接)。")
737
+ : distros.length === 0
738
+ ? h("div", { style: styles.empty }, "没有发现发行版。")
739
+ : distros.map((distro) => {
740
+ const state = checks[distro];
741
+ const done = state !== undefined && state.phase === "done";
742
+ const checking = state !== undefined && state.phase === "checking";
743
+ const repairing = state !== undefined && state.phase === "repairing";
744
+ const refreshing = state !== undefined && state.phase === "refreshing";
745
+ const busy = checking || repairing || refreshing;
746
+ const repairable = Array.isArray(state?.repairable) ? state.repairable : [];
747
+ const canRepair = done && repairable.length > 0;
748
+ const findings = done
749
+ ? (Array.isArray(state.failures) ? state.failures.length : 0)
750
+ + (Array.isArray(state.warnings) ? state.warnings.length : 0)
751
+ : 0;
752
+ return h(
753
+ "div",
754
+ { key: distro, style: styles.row },
755
+ h(
756
+ "div",
757
+ { style: styles.rowHead },
758
+ h("span", { style: styles.rowName, title: distro }, distro),
759
+ h(CheckPill, { state }),
760
+ h(Btn, {
761
+ label: checking ? "检查中…" : refreshing ? "后台检查中…" : done ? "重新检查" : "检查",
762
+ small: true,
763
+ primary: state === undefined,
764
+ disabled: busy,
765
+ onClick: () => { void check(distro); },
766
+ }),
767
+ done || repairing
768
+ ? h(Btn, {
769
+ label: repairing ? (state?.mode === "full" ? "完整检查中…" : "修复中…") : canRepair ? "修复" : "完整检查",
770
+ small: true,
771
+ disabled: busy,
772
+ onClick: () => { void repair(distro, canRepair ? "repair" : "full"); },
773
+ })
774
+ : null,
775
+ ),
776
+ state === undefined
777
+ ? h("div", { style: styles.hint }, "尚未检查:点击“检查”运行快速 doctor(约 10 秒;会启动停止的发行版)。")
778
+ : state.phase === "checking"
779
+ ? h("div", { style: styles.hint }, "正在运行快速检查…(会启动停止的发行版)")
780
+ : state.phase === "repairing"
781
+ ? h("div", { style: styles.hint }, state?.mode === "full"
782
+ ? "正在运行完整检查(按上次结果没有可自动修复项)…"
783
+ : "正在运行完整检查并修复插件自有状态…")
784
+ : state.phase === "error"
785
+ ? h("div", { style: styles.detail }, h("span", { style: styles.failure }, state.error))
786
+ : h(
787
+ "div",
788
+ { style: styles.detail },
789
+ h(ResultSummary, { state }),
790
+ state.verdict === "error"
791
+ ? h("span", { style: styles.failure }, state.error ?? "检查未能完成")
792
+ : null,
793
+ h(RepairList, { items: state.repairs }),
794
+ h(IssueList, {
795
+ heading: `待修项(${String(Array.isArray(state.failures) ? state.failures.length : 0)})`,
796
+ items: state.failures,
797
+ severity: "fail",
798
+ repairable,
799
+ }),
800
+ h(IssueList, {
801
+ heading: `告警(${String(Array.isArray(state.warnings) ? state.warnings.length : 0)})`,
802
+ items: state.warnings,
803
+ severity: "warn",
804
+ repairable,
805
+ }),
806
+ findings > 0
807
+ ? h("div", { style: styles.hint }, canRepair
808
+ ? "标有“可自动修复”的项会由“修复”处理;其余项目需按处理办法手动处理。"
809
+ : "以上项目没有可自动修复项,需按各自处理办法手动处理。自动修复只覆盖残留 session scope 与损坏的 agent 缓存。")
810
+ : null,
811
+ h(CheckDetails, { state }),
812
+ ),
813
+ );
814
+ }),
815
+ ),
816
+ ),
817
+ );
818
+ }
819
+
820
+ // ── The access-mode prompt ─────────────────────────────────────────────
821
+
822
+ /** One pending prompt, shared by the watcher and the overlay occupant. */
823
+ const accessPrompt = {
824
+ value: null,
825
+ listeners: new Set(),
826
+ get() { return accessPrompt.value; },
827
+ set(next) {
828
+ accessPrompt.value = next;
829
+ for (const listener of accessPrompt.listeners) listener();
830
+ },
831
+ subscribe(listener) {
832
+ accessPrompt.listeners.add(listener);
833
+ return () => { accessPrompt.listeners.delete(listener); };
834
+ },
835
+ };
836
+
837
+ /**
838
+ * The modal that asks how a newly added distro workspace is opened.
839
+ * @param props - the client root context.
840
+ * @returns the modal, or null while nothing is pending.
841
+ */
842
+ function AccessPrompt({ ctx }) {
843
+ const [request, setRequest] = useState(accessPrompt.get());
844
+ const [busy, setBusy] = useState(false);
845
+ const [error, setError] = useState(null);
846
+
847
+ useEffect(() => accessPrompt.subscribe(() => {
848
+ setRequest(accessPrompt.get());
849
+ setError(null);
850
+ setBusy(false);
851
+ }), []);
852
+
853
+ // Dismissing the prompt takes the default: Remote WSL. Nothing is written,
854
+ // which is exactly what "keep the default" means for this record.
855
+ useEffect(() => {
856
+ if (request === null) return undefined;
857
+ const onKey = (event) => { if (event.key === "Escape") accessPrompt.set(null); };
858
+ document.addEventListener("keydown", onKey);
859
+ return () => document.removeEventListener("keydown", onKey);
860
+ }, [request]);
861
+
862
+ if (request === null) return null;
863
+
864
+ const close = () => { accessPrompt.set(null); };
865
+
866
+ const chooseWindows = async () => {
867
+ setBusy(true);
868
+ setError(null);
869
+ try {
870
+ const current = await readAccess(ctx);
871
+ const paths = current.ok === true ? current.paths : [];
872
+ if (current.ok !== true) throw new Error(current.message);
873
+ const next = paths.some((entry) => samePath(entry, request.path))
874
+ ? paths
875
+ : [...paths, request.path];
876
+ const failure = await writeAccess(ctx, next);
877
+ if (failure !== undefined) throw new Error(failure);
878
+ const switchFailure = await switchWorkspaceSessions(ctx, request.workspaceId);
879
+ if (switchFailure !== undefined) throw new Error(switchFailure);
880
+ accessPrompt.set(null);
881
+ } catch (reason) {
882
+ setError(messageOf(reason));
883
+ } finally {
884
+ setBusy(false);
885
+ }
886
+ };
163
887
 
164
888
  return h(
165
889
  "div",
166
890
  {
167
- ref: setRoot,
168
- // The dock is a centered flex row; an auto left margin overrides the
169
- // group centering for this item alone and pins the pill to the
170
- // dock's right edge.
171
- style: { position: "relative", marginLeft: "auto" },
891
+ onClick: (event) => { if (event.target === event.currentTarget) close(); },
892
+ style: {
893
+ position: "fixed",
894
+ inset: 0,
895
+ zIndex: 1000,
896
+ pointerEvents: "auto",
897
+ background: "rgba(0, 0, 0, 0.45)",
898
+ display: "flex",
899
+ alignItems: "center",
900
+ justifyContent: "center",
901
+ padding: 24,
902
+ },
172
903
  },
173
- menu,
174
904
  h(
175
- "button",
905
+ "div",
176
906
  {
177
- type: "button",
178
- onClick: () => setOpen(!open),
179
- title: "运行 WSL 环境诊断(doctor):选择诊断模式",
907
+ role: "dialog",
908
+ "aria-modal": "true",
909
+ "aria-label": "选择 WSL 工作区的打开方式",
180
910
  style: {
911
+ width: 480,
912
+ maxWidth: "100%",
181
913
  display: "flex",
182
- alignItems: "center",
183
- gap: 5,
184
- padding: "2px 10px",
185
- borderRadius: 999,
186
- fontSize: 12,
187
- border: "none",
188
- outline: "none",
189
- background: "transparent",
914
+ flexDirection: "column",
915
+ gap: 12,
916
+ padding: "18px 20px 16px",
917
+ borderRadius: 12,
918
+ background: "var(--dsh-bg, #1f1f1f)",
190
919
  color: "inherit",
191
- opacity: 0.75,
192
- cursor: "pointer",
193
- userSelect: "none",
920
+ border: "1px solid rgba(128, 128, 128, 0.35)",
921
+ boxShadow: "0 16px 48px rgba(0, 0, 0, 0.5)",
922
+ fontSize: 13,
194
923
  },
195
924
  },
196
- "WSL 诊断",
197
- h("span", { style: { fontSize: 9, opacity: 0.8 } }, open ? "▲" : "▼")
198
- )
925
+ h("div", { style: { fontSize: 15, fontWeight: 600 } }, "这个文件夹在 WSL 发行版内"),
926
+ h("div", { style: { fontSize: 12, opacity: 0.6, wordBreak: "break-all" } }, request.path),
927
+ h(
928
+ "div",
929
+ { style: { fontSize: 12.5, opacity: 0.85 } },
930
+ "选择打开方式。默认 Remote WSL:命令、文件与终端都在发行版内运行。",
931
+ ),
932
+ error === null ? null : h("div", { style: styles.notice }, error),
933
+ h(
934
+ "div",
935
+ { style: { display: "flex", flexDirection: "column", gap: 8, marginTop: 4 } },
936
+ h(Btn, {
937
+ label: "Remote WSL(推荐)",
938
+ primary: true,
939
+ disabled: busy,
940
+ onClick: close,
941
+ }),
942
+ h(Btn, {
943
+ label: "Windows 访问(经 9p 共享)",
944
+ disabled: busy,
945
+ onClick: () => { void chooseWindows(); },
946
+ }),
947
+ ),
948
+ h(
949
+ "div",
950
+ { style: { fontSize: 11.5, opacity: 0.5 } },
951
+ "Windows 访问把该文件夹当作普通 Windows 共享打开:不启用发行版执行环境,读写经过 9p,较慢,但适合只想用 Windows 工具链的场景。选择会记录到插件配置,之后在该工作区新建的会话同样生效。",
952
+ ),
953
+ ),
199
954
  );
200
955
  }
201
956
 
957
+ /**
958
+ * Watch for newly added WSL workspaces and raise the access-mode prompt.
959
+ * Existing workspaces are the baseline: startup restoration must not ask
960
+ * again for a workspace the operator already opened.
961
+ * @param ctx - client root context.
962
+ * @returns a disposer owned by the plugin fiber.
963
+ */
964
+ const watchWorkspaces = (ctx) => {
965
+ const workspaces = service(ctx, "workspaces");
966
+ if (workspaces === undefined) return undefined;
967
+ let known;
968
+ const consider = () => {
969
+ const snapshot = workspaces.list.getSnapshot();
970
+ if (snapshot.phase !== "ready" || !Array.isArray(snapshot.items)) return;
971
+ const ids = new Set(snapshot.items.map((item) => item.workspaceId));
972
+ if (known === undefined) {
973
+ known = ids;
974
+ return;
975
+ }
976
+ for (const item of snapshot.items) {
977
+ if (known.has(item.workspaceId)) continue;
978
+ if (!isWslUnc(item.path)) continue;
979
+ accessPrompt.set({ workspaceId: item.workspaceId, path: item.path });
980
+ break;
981
+ }
982
+ known = ids;
983
+ };
984
+ consider();
985
+ return workspaces.list.subscribe(consider);
986
+ };
987
+
202
988
  return {
203
989
  inject: ["slots"],
204
990
  apply(ctx) {
205
- ctx.slots.inject("conversation.composer.dock", function* () {
991
+ // Sidebar panel: icon in the navigation column, page in the main seat.
992
+ ctx.slots.inject("sidebar.panellist", function* () {
206
993
  yield ctx.slots.register(
207
994
  {
208
- name: "conversation.composer.dock",
209
- id: "wsl-doctor-button",
210
- order: 9,
995
+ name: "sidebar.panellist",
996
+ id: PANEL_ID,
997
+ order: PANEL_ORDER,
998
+ label: "WSL 环境",
211
999
  },
212
- DoctorButton
1000
+ ({ size, active }) => h(WslIcon, { size, active }),
1001
+ );
1002
+ });
1003
+ ctx.slots.inject("main", function* () {
1004
+ yield ctx.slots.register(
1005
+ { name: "main", key: PANEL_ID },
1006
+ () => h(WslPanel),
213
1007
  );
214
1008
  });
1009
+ // The post-add prompt rides the frame-wide overlay seat.
1010
+ ctx.slots.inject("shell.overlay", function* () {
1011
+ yield ctx.slots.register(
1012
+ { name: "shell.overlay", id: "wsl-access-choice", order: 100 },
1013
+ () => h(AccessPrompt, { ctx }),
1014
+ );
1015
+ });
1016
+ // The workspace catalog activates independently of this module; the
1017
+ // prompt watcher waits for it instead of sampling a missing service.
1018
+ ctx.inject(["workspaces"], (scope) => {
1019
+ scope.effect(() => {
1020
+ const stop = watchWorkspaces(scope);
1021
+ return () => { if (typeof stop === "function") stop(); };
1022
+ }, "wsl-env: workspace access prompt");
1023
+ });
215
1024
  },
216
1025
  };
217
1026
  },