dsh-plugin-wsl-env 0.24.0 → 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/CHANGELOG.md +136 -0
  2. package/CODE_OF_CONDUCT.md +85 -0
  3. package/CODE_OF_CONDUCT.zh.md +85 -0
  4. package/CONTRIBUTING.md +19 -3
  5. package/CONTRIBUTING.zh.md +200 -0
  6. package/README.md +18 -6
  7. package/SECURITY.md +12 -0
  8. package/SECURITY.zh.md +108 -0
  9. package/SUPPORT.md +2 -0
  10. package/SUPPORT.zh.md +99 -0
  11. package/client.js +409 -8
  12. package/cordis.patch.yml +17 -0
  13. package/docs/AGENT-PROTOCOL-V7.md +2 -2
  14. package/docs/API.md +2 -0
  15. package/docs/API.zh.md +38 -0
  16. package/docs/ARCHITECTURE.md +30 -9
  17. package/docs/ARCHITECTURE.zh.md +511 -0
  18. package/docs/COMPATIBILITY.md +2 -0
  19. package/docs/COMPATIBILITY.zh.md +117 -0
  20. package/docs/CONFIGURATION.md +45 -2
  21. package/docs/CONFIGURATION.zh.md +39 -3
  22. package/docs/DIAGNOSTICS.md +12 -2
  23. package/docs/DIAGNOSTICS.zh.md +5 -1
  24. package/docs/LIMITATIONS.md +60 -9
  25. package/docs/LIMITATIONS.zh.md +45 -9
  26. package/docs/MIGRATION.md +6 -3
  27. package/docs/MIGRATION.zh.md +91 -0
  28. package/docs/PEER-PARITY.md +63 -51
  29. package/docs/PERFORMANCE.md +2 -0
  30. package/docs/PERFORMANCE.zh.md +59 -0
  31. package/docs/QUICKSTART.md +21 -6
  32. package/docs/QUICKSTART.zh.md +16 -4
  33. package/docs/README.zh.md +28 -19
  34. package/docs/RELEASING.md +19 -14
  35. package/docs/REQUIREMENTS.zh.md +6 -3
  36. package/docs/ROADMAP-1.0.md +1 -1
  37. package/docs/UPSTREAM-FILE-REFERENCE-SEAM.md +1 -1
  38. package/docs/UPSTREAM-FSIO-EXPORT.md +5 -4
  39. package/docs/UPSTREAM-OPEN-IN-APP.md +33 -11
  40. package/docs/UPSTREAM-PROMPT-ADAPTERS.md +85 -0
  41. package/docs/UPSTREAM-SESSION-NOTICE.md +7 -0
  42. package/docs/VALUE.md +146 -0
  43. package/docs/VALUE.zh.md +15 -13
  44. package/docs/root-fs-routing.md +1 -1
  45. package/lib/agent-confined.d.ts +7 -1
  46. package/lib/agent-confined.js +3 -3
  47. package/lib/auto-preset-seam.d.ts +45 -0
  48. package/lib/auto-preset-seam.js +47 -0
  49. package/lib/auto-preset.d.ts +33 -10
  50. package/lib/auto-preset.js +148 -44
  51. package/lib/bwrap.d.ts +14 -0
  52. package/lib/bwrap.js +11 -0
  53. package/lib/cwd-prompt.d.ts +41 -3
  54. package/lib/cwd-prompt.js +125 -8
  55. package/lib/doctor-live.d.ts +30 -0
  56. package/lib/doctor-live.js +37 -0
  57. package/lib/doctor-report.d.ts +50 -0
  58. package/lib/doctor-report.js +172 -0
  59. package/lib/fs-routing.d.ts +1 -1
  60. package/lib/fs-routing.js +1 -1
  61. package/lib/fs.d.ts +1 -1
  62. package/lib/fs.js +1 -1
  63. package/lib/index.d.ts +6 -1464
  64. package/lib/index.js +5 -2120
  65. package/lib/messages.d.ts +20 -1
  66. package/lib/messages.js +31 -3
  67. package/lib/open-in-app.d.ts +206 -0
  68. package/lib/open-in-app.js +300 -0
  69. package/lib/preflight.d.ts +7 -4
  70. package/lib/preflight.js +27 -13
  71. package/lib/preset-choice.d.ts +13 -0
  72. package/lib/preset-choice.js +18 -1
  73. package/lib/provider-common.d.ts +58 -0
  74. package/lib/provider-common.js +123 -0
  75. package/lib/sandbox-core.d.ts +1 -0
  76. package/lib/sandbox-core.js +4 -2
  77. package/lib/session-runtime.d.ts +7 -1
  78. package/lib/session-runtime.js +9 -2
  79. package/lib/shell.d.ts +1 -1
  80. package/lib/shell.js +1 -1
  81. package/lib/status.js +2 -1
  82. package/lib/writable-roots.d.ts +109 -0
  83. package/lib/writable-roots.js +257 -0
  84. package/lib/wsl-doctor-command.js +2 -1
  85. package/lib/wsl-doctor-tool.js +2 -2
  86. package/lib/wsl-filesystem.d.ts +692 -0
  87. package/lib/wsl-filesystem.js +897 -0
  88. package/lib/wsl-shell.d.ts +742 -0
  89. package/lib/wsl-shell.js +965 -0
  90. package/lib/wsl.d.ts +1 -1
  91. package/lib/wsl.js +1 -1
  92. package/package.json +48 -24
  93. package/scripts/doctor.mjs +1 -1
  94. package/scripts/profile-preset.mjs +17 -5
package/lib/messages.d.ts CHANGED
@@ -92,6 +92,25 @@ declare const en: {
92
92
  workdir: string;
93
93
  distro: string;
94
94
  }) => string;
95
+ /**
96
+ * `auto-preset`: a distro workspace is recorded as Windows access (9p), so
97
+ * the session runs the host preset. The model-facing half of the reminder;
98
+ * the human sees the web client's banner.
99
+ */
100
+ hostModeWindowsAccess: ({ cwd, distro }: {
101
+ cwd: string;
102
+ distro: string;
103
+ }) => string;
104
+ /** `auto-preset`: the session began its first turn before the WSL preset could be selected. */
105
+ hostModeLocked: ({ cwd, distro }: {
106
+ cwd: string;
107
+ distro: string;
108
+ }) => string;
109
+ /** `auto-preset`: the profile composes no WSL preset, so the session keeps the host environment. */
110
+ hostModePresetUnavailable: ({ cwd, distro }: {
111
+ cwd: string;
112
+ distro: string;
113
+ }) => string;
95
114
  /** `wsl_doctor` digest: the verdict line. `verdict` is the report's own `ready`/`blocked`. */
96
115
  doctorDigestVerdict: ({ verdict }: {
97
116
  verdict: string;
@@ -146,7 +165,7 @@ declare const en: {
146
165
  doctorDigestFixPrefix: ({ remedy }: {
147
166
  remedy: string;
148
167
  }) => string;
149
- /** `wsl_doctor` digest: the ready note (how to attach the full report). */
168
+ /** `wsl_doctor` digest: the ready note; the report is not a promise about a call. */
150
169
  doctorDigestNoteReady: () => string;
151
170
  /** `wsl_doctor` digest: the blocked note (the rerun is the re-verification). */
152
171
  doctorDigestNoteBlocked: () => string;
package/lib/messages.js CHANGED
@@ -69,6 +69,25 @@ const en = {
69
69
  workdirAnotherDistro: ({ workdir, distro }) => `"${workdir}" names a workspace in another WSL distro, and this profile pins its commands to "${distro}" — ` +
70
70
  `running them here would act on a different machine's tree. Open a session in that distro, ` +
71
71
  `or point cwd/workdir at this distro.`,
72
+ /**
73
+ * `auto-preset`: a distro workspace is recorded as Windows access (9p), so
74
+ * the session runs the host preset. The model-facing half of the reminder;
75
+ * the human sees the web client's banner.
76
+ */
77
+ hostModeWindowsAccess: ({ cwd, distro }) => `The workspace "${cwd}" is inside WSL distro "${distro}" but is recorded as a Windows-access workspace, ` +
78
+ `so this session runs the host (Windows) environment: commands execute in Windows PowerShell, file access ` +
79
+ `crosses the 9p share, and the distro's Linux toolchain is unavailable. Do not assume Linux commands, paths, ` +
80
+ `or tooling here; using the distro requires opening a new session in this workspace with the WSL preset.`,
81
+ /** `auto-preset`: the session began its first turn before the WSL preset could be selected. */
82
+ hostModeLocked: ({ cwd, distro }) => `The workspace "${cwd}" is inside WSL distro "${distro}", but this session became interactive before the WSL ` +
83
+ `preset could be selected, so it keeps the host (Windows) environment: commands execute in Windows PowerShell, ` +
84
+ `file access crosses the 9p share, and the distro's Linux toolchain is unavailable. Do not assume Linux commands, ` +
85
+ `paths, or tooling here; a new session in this workspace adopts the WSL preset.`,
86
+ /** `auto-preset`: the profile composes no WSL preset, so the session keeps the host environment. */
87
+ hostModePresetUnavailable: ({ cwd, distro }) => `The workspace "${cwd}" is inside WSL distro "${distro}", but this profile composes no WSL preset, so this ` +
88
+ `session runs the host (Windows) environment: commands execute in Windows PowerShell, file access crosses the ` +
89
+ `9p share, and the distro's Linux toolchain is unavailable. Do not assume Linux commands, paths, or tooling ` +
90
+ `here; the operator can run /wsl-doctor to diagnose the profile.`,
72
91
  /** `wsl_doctor` digest: the verdict line. `verdict` is the report's own `ready`/`blocked`. */
73
92
  doctorDigestVerdict: ({ verdict }) => `wsl doctor verdict: ${verdict}`,
74
93
  /** `wsl_doctor` digest: the host-wide group heading. */
@@ -96,8 +115,8 @@ const en = {
96
115
  doctorTallySkipped: ({ n }) => `${n} skipped`,
97
116
  /** `wsl_doctor` digest: the remedy prefix under a failed check. */
98
117
  doctorDigestFixPrefix: ({ remedy }) => ` fix: ${remedy}`,
99
- /** `wsl_doctor` digest: the ready note (how to attach the full report). */
100
- doctorDigestNoteReady: () => "the first command should succeed; run the CLI (pnpm run doctor --bundle <path>) for the attachable file",
118
+ /** `wsl_doctor` digest: the ready note; the report is not a promise about a call. */
119
+ doctorDigestNoteReady: () => "ready covers the checks in this run; it does not promise every command will succeed",
101
120
  /** `wsl_doctor` digest: the blocked note (the rerun is the re-verification). */
102
121
  doctorDigestNoteBlocked: () => "apply each remedy above, then call this tool again — the re-run is the re-verification",
103
122
  /** `wsl_doctor` digest: the blocked summary tail; `noneBlocking` is the fixed clause. */
@@ -127,6 +146,15 @@ const zh = {
127
146
  `请创建该目录,或将 \`cwd\`(或请求的 \`workdir\`)指向一个已存在的目录。`,
128
147
  workdirAnotherDistro: ({ workdir, distro }) => `"${workdir}" 指向另一个 WSL 发行版中的工作区,而本 profile 将命令固定在 "${distro}" —— ` +
129
148
  `在这里运行会作用于另一台机器的目录树。请在该发行版中打开会话,或将 cwd/workdir 指向本发行版。`,
149
+ hostModeWindowsAccess: ({ cwd, distro }) => `工作区 "${cwd}" 位于 WSL 发行版 "${distro}" 内,但被记录为 Windows 访问工作区,` +
150
+ `因此本会话运行在宿主(Windows)环境:命令经 PowerShell 执行,文件访问经过 9p 共享,发行版的 Linux 工具链不可用。` +
151
+ `不要在此假设 Linux 命令、路径或工具;如需在发行版内运行,须由操作者以 WSL preset 在本工作区新开会话。`,
152
+ hostModeLocked: ({ cwd, distro }) => `工作区 "${cwd}" 位于 WSL 发行版 "${distro}" 内,但本会话在选中 WSL preset 之前就已开始交互,` +
153
+ `因此保留宿主(Windows)环境:命令经 PowerShell 执行,文件访问经过 9p 共享,发行版的 Linux 工具链不可用。` +
154
+ `不要在此假设 Linux 命令、路径或工具;在本工作区新开的会话会采用 WSL preset。`,
155
+ hostModePresetUnavailable: ({ cwd, distro }) => `工作区 "${cwd}" 位于 WSL 发行版 "${distro}" 内,但本 profile 未装配 WSL preset,` +
156
+ `因此本会话运行在宿主(Windows)环境:命令经 PowerShell 执行,文件访问经过 9p 共享,发行版的 Linux 工具链不可用。` +
157
+ `不要在此假设 Linux 命令、路径或工具;操作者可运行 /wsl-doctor 诊断该 profile。`,
130
158
  doctorDigestVerdict: ({ verdict }) => `wsl doctor 裁决:${verdict}`,
131
159
  doctorDigestHostLabel: () => "(宿主——Windows 与全局检查)",
132
160
  doctorDigestNotRunLabel: () => "(不在本次范围)",
@@ -143,7 +171,7 @@ const zh = {
143
171
  doctorTallyInfo: ({ n }) => `信息 ${n}`,
144
172
  doctorTallySkipped: ({ n }) => `跳过 ${n}`,
145
173
  doctorDigestFixPrefix: ({ remedy }) => ` 修复: ${remedy}`,
146
- doctorDigestNoteReady: () => "首条命令应能成功;如需可附加的报告文件,运行 CLI(pnpm run doctor --bundle <path>)",
174
+ doctorDigestNoteReady: () => "ready 只覆盖本次检查,不保证每条命令都能成功",
147
175
  doctorDigestNoteBlocked: () => "应用上方每条修复,然后再次调用本工具——重跑即复核",
148
176
  doctorDigestBlockedTail: ({ blockers, warnings, skipped, note }) => `阻断项:${blockers};${warnings} 个警告,${skipped} 个跳过腿——均不阻断;${note}`,
149
177
  };
@@ -0,0 +1,206 @@
1
+ /**
2
+ * Durable replacement for the local `app.asar` patch this repository used to
3
+ * carry around the host's "Open in app" launcher.
4
+ *
5
+ * Two independent defects made that patch necessary. The first is scrubbed from
6
+ * this route's editor child only; the shipped launcher still inherits it. The
7
+ * second is fixed here without touching the installed archive:
8
+ *
9
+ * 1. The Desktop Host runs with `ELECTRON_RUN_AS_NODE=1`; the host
10
+ * launcher (`@deepseek-ai/dsh-host-open-in-app`) copies the parent
11
+ * environment through `scrubbedParentEnv()`, which does not drop that
12
+ * name. An Electron editor therefore starts as plain Node, exits 1 and
13
+ * the route answers `launch-failed`. The row scrubs the name from the
14
+ * **editor child's** environment only. Editing the Host environment would
15
+ * do the same for every later child, including Node-mode helpers such as
16
+ * the Windows Job runner, which legitimately inherit it and then fail to
17
+ * start.
18
+ * 2. An Electron editor launched with a WSL UNC workspace opens the folder
19
+ * through the 9p share (Windows terminal, Windows extensions). The
20
+ * earlier patch rewrote the argument to `--folder-uri` and landed in
21
+ * Remote-WSL. The same conversion is offered here as an authenticated
22
+ * `POST /api/wsl-env/open-in-app` route; the browser's session-header
23
+ * menu calls it. The route refuses anything that is not a WSL UNC path,
24
+ * so it cannot launch an editor for an arbitrary path.
25
+ *
26
+ * The route is registered on the Host connection's authenticated exact-Fetch
27
+ * channel (the same channel as this plugin's status route), so only the owner
28
+ * browser reaches it. A composition without `connection` leaves the route
29
+ * unregistered; the child environment is only built when a launch happens.
30
+ *
31
+ * This is a TypeScript source built to `lib/open-in-app.js`; edit THIS file and
32
+ * run `pnpm run build` — the artifact under `lib/` is generated, and
33
+ * `pnpm test` fails when it drifts.
34
+ *
35
+ * @module dsh-plugin-wsl-env/open-in-app
36
+ */
37
+ import { spawn } from "node:child_process";
38
+ import z from "@deepseek-ai/schemastery";
39
+ /** The composition row's plugin name. */
40
+ export declare const name = "wsl-open-in-app";
41
+ /** The authenticated route the session-header menu posts to. */
42
+ export declare const OPEN_IN_APP_PATH = "/api/wsl-env/open-in-app";
43
+ export declare const Config: z<Schemastery.ObjectS<NoInfer<{
44
+ /**
45
+ * Editor executable to launch. Empty resolves VS Code from its usual
46
+ * Windows install locations, then falls back to `Code.exe` on PATH.
47
+ */
48
+ executable: z<string, string, "defined">;
49
+ /** Early-failure watch window per launch, in milliseconds. */
50
+ watchMs: z<number, number, "defined">;
51
+ }>>, Schemastery.ObjectT<NoInfer<{
52
+ /**
53
+ * Editor executable to launch. Empty resolves VS Code from its usual
54
+ * Windows install locations, then falls back to `Code.exe` on PATH.
55
+ */
56
+ executable: z<string, string, "defined">;
57
+ /** Early-failure watch window per launch, in milliseconds. */
58
+ watchMs: z<number, number, "defined">;
59
+ }>>, "plain">;
60
+ /** The config schema's validated output. */
61
+ export interface OpenInAppConfig {
62
+ /** Editor executable, or empty for the normal Windows lookup. */
63
+ executable?: string;
64
+ /** Early-failure watch window per launch, in milliseconds. */
65
+ watchMs?: number;
66
+ }
67
+ /** How one detached launch ended. */
68
+ export type LaunchOutcome = "launched" | "missing" | "failed";
69
+ /** The environment shape the pure helpers read. */
70
+ type Environment = Readonly<Record<string, string | undefined>>;
71
+ /** Options for one detached launch. */
72
+ export interface LaunchOptions {
73
+ /** Early-failure watch window, in milliseconds. */
74
+ watchMs: number;
75
+ /** Complete child environment; already scrubbed by the caller. */
76
+ env: NodeJS.ProcessEnv;
77
+ }
78
+ /**
79
+ * Convert a WSL UNC workspace to the `vscode-remote` URI Remote-WSL expects.
80
+ *
81
+ * Both share spellings (`\\wsl.localhost\<distro>\...` and
82
+ * `\\wsl$\<distro>\...`) are accepted; every other path is refused rather
83
+ * than guessed at.
84
+ *
85
+ * @param uncPath - candidate workspace path.
86
+ * @returns the editor URI, or undefined when the path is not WSL UNC or
87
+ * cannot be encoded (a path with malformed UTF-16 is not a workspace).
88
+ */
89
+ export declare function editorUri(uncPath: string): string | undefined;
90
+ /**
91
+ * The editor executables this machine is likely to carry, in preference order.
92
+ *
93
+ * @param env - environment carrying the Windows install roots.
94
+ * @returns absolute candidate paths; empty when no root is named.
95
+ */
96
+ export declare function editorCandidates(env: Environment): string[];
97
+ /**
98
+ * Resolve the editor executable: an explicit config value wins; otherwise the
99
+ * first existing install candidate; otherwise the PATH name `Code.exe`.
100
+ *
101
+ * @param config - this row's config.
102
+ * @param env - environment carrying the install roots.
103
+ * @param exists - existence check, injected for tests.
104
+ * @returns the command to spawn.
105
+ */
106
+ export declare function resolveEditor(config: OpenInAppConfig, env: Environment, exists?: (path: string) => boolean): string;
107
+ /**
108
+ * Remove `ELECTRON_RUN_AS_NODE` from an environment object, in place.
109
+ *
110
+ * Callers pass the editor child's environment copy, never the Host process
111
+ * environment: a Host-wide deletion breaks Node-mode helpers that inherit it.
112
+ *
113
+ * @param env - environment to clean, in place.
114
+ * @returns true when the name was present.
115
+ */
116
+ export declare function dropElectronRunAsNode(env: NodeJS.ProcessEnv): boolean;
117
+ /**
118
+ * The child environment for one editor launch: the Host environment with
119
+ * `ELECTRON_RUN_AS_NODE` removed. The deletion is scoped to this child;
120
+ * editing the Host's own environment would break Node-mode helpers (the
121
+ * Windows Job runner, for one) that legitimately inherit the flag.
122
+ *
123
+ * @param env - source environment; defaults to the current process environment.
124
+ * @returns a fresh environment safe to hand to an Electron editor.
125
+ */
126
+ export declare function launchEnvironment(env?: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
127
+ /**
128
+ * Launch one detached editor through a `--folder-uri` argument and classify
129
+ * an early failure.
130
+ *
131
+ * Success is decoupled from process lifetime, mirroring the host launcher: a
132
+ * child still running when the watch window closes counts as launched (an
133
+ * existing editor window may keep the process in the foreground), exit code 0
134
+ * inside the window counts as launched, and a nonzero exit, a spawn error or
135
+ * a synchronous spawn throw is a failure.
136
+ *
137
+ * @param command - executable path or PATH name.
138
+ * @param args - argv, never a shell string.
139
+ * @param options - watch window and complete child environment.
140
+ * @param spawnChild - spawn seam, injected for tests.
141
+ * @returns the classified outcome.
142
+ */
143
+ export declare function launchDetached(command: string, args: readonly string[], options: LaunchOptions, spawnChild?: typeof spawn): Promise<LaunchOutcome>;
144
+ /** The launch seam the handler calls. */
145
+ export interface OpenInAppDeps {
146
+ /** Launch one editor URI and report how the attempt ended. */
147
+ launch: (uri: string) => Promise<LaunchOutcome>;
148
+ }
149
+ /**
150
+ * The route handler: validate one POST body and launch the editor for its WSL
151
+ * workspace. Only a `\\wsl...` UNC path is accepted; the route never launches
152
+ * for a Windows or POSIX path.
153
+ *
154
+ * @param deps - the launch seam.
155
+ * @returns the exact-Fetch handler.
156
+ */
157
+ export declare function createOpenInAppHandler(deps: OpenInAppDeps): (request: Request) => Promise<Response>;
158
+ /** One exact route's registration shape. */
159
+ interface ConnectionRoute {
160
+ readonly path: string;
161
+ readonly methods: readonly string[];
162
+ readonly requestBody: "buffered" | "streaming";
163
+ readonly fetch: (request: Request) => Promise<Response>;
164
+ }
165
+ /** The connection slice this row registers into. */
166
+ interface ConnectionFace {
167
+ /** The exact-Fetch route registry. */
168
+ readonly fetch: {
169
+ /** Register one exact route; the returned disposer withdraws it. */
170
+ register: (route: ConnectionRoute) => () => Promise<void> | void;
171
+ };
172
+ }
173
+ /** The context slice this row consumes; the seams keep it boot-free in tests. */
174
+ interface OpenInAppContext {
175
+ /** Optional cordis-style lookup: how production resolves the connection. */
176
+ get?: (name: string) => unknown;
177
+ /** Wait for a service, then run the callback in its scope. */
178
+ inject?: (deps: readonly string[], callback: (scope: OpenInAppContext) => void) => unknown;
179
+ /** Own one disposer on the calling fiber. */
180
+ effect?: (callback: () => () => void, label?: string) => unknown;
181
+ /** The Host connection whose `/api` channel carries the route. */
182
+ connection?: ConnectionFace;
183
+ }
184
+ /**
185
+ * Build the launch seam for one row: resolve the editor once, scrub the child
186
+ * environment once, and hand every call to {@link launchDetached}.
187
+ *
188
+ * The factory exists so a test can observe the exact argv, the detachment
189
+ * flags and the child environment the row produces without starting an editor.
190
+ *
191
+ * @param config - this row's config.
192
+ * @param env - source environment; defaults to the current process environment.
193
+ * @param spawnChild - spawn seam, injected for tests.
194
+ * @returns the launch seam {@link createOpenInAppHandler} calls.
195
+ */
196
+ export declare function createLauncher(config: OpenInAppConfig, env?: NodeJS.ProcessEnv, spawnChild?: typeof spawn): (uri: string) => Promise<LaunchOutcome>;
197
+ /**
198
+ * Mount the row: register the route once the Host connection is available.
199
+ * The route scrubs `ELECTRON_RUN_AS_NODE` from each editor child's environment
200
+ * without touching the Host process environment.
201
+ *
202
+ * @param ctx - the cordis context.
203
+ * @param config - the schema-validated config.
204
+ */
205
+ export declare function apply(ctx: OpenInAppContext, config?: OpenInAppConfig): void;
206
+ export {};
@@ -0,0 +1,300 @@
1
+ /**
2
+ * Durable replacement for the local `app.asar` patch this repository used to
3
+ * carry around the host's "Open in app" launcher.
4
+ *
5
+ * Two independent defects made that patch necessary. The first is scrubbed from
6
+ * this route's editor child only; the shipped launcher still inherits it. The
7
+ * second is fixed here without touching the installed archive:
8
+ *
9
+ * 1. The Desktop Host runs with `ELECTRON_RUN_AS_NODE=1`; the host
10
+ * launcher (`@deepseek-ai/dsh-host-open-in-app`) copies the parent
11
+ * environment through `scrubbedParentEnv()`, which does not drop that
12
+ * name. An Electron editor therefore starts as plain Node, exits 1 and
13
+ * the route answers `launch-failed`. The row scrubs the name from the
14
+ * **editor child's** environment only. Editing the Host environment would
15
+ * do the same for every later child, including Node-mode helpers such as
16
+ * the Windows Job runner, which legitimately inherit it and then fail to
17
+ * start.
18
+ * 2. An Electron editor launched with a WSL UNC workspace opens the folder
19
+ * through the 9p share (Windows terminal, Windows extensions). The
20
+ * earlier patch rewrote the argument to `--folder-uri` and landed in
21
+ * Remote-WSL. The same conversion is offered here as an authenticated
22
+ * `POST /api/wsl-env/open-in-app` route; the browser's session-header
23
+ * menu calls it. The route refuses anything that is not a WSL UNC path,
24
+ * so it cannot launch an editor for an arbitrary path.
25
+ *
26
+ * The route is registered on the Host connection's authenticated exact-Fetch
27
+ * channel (the same channel as this plugin's status route), so only the owner
28
+ * browser reaches it. A composition without `connection` leaves the route
29
+ * unregistered; the child environment is only built when a launch happens.
30
+ *
31
+ * This is a TypeScript source built to `lib/open-in-app.js`; edit THIS file and
32
+ * run `pnpm run build` — the artifact under `lib/` is generated, and
33
+ * `pnpm test` fails when it drifts.
34
+ *
35
+ * @module dsh-plugin-wsl-env/open-in-app
36
+ */
37
+ import { spawn } from "node:child_process";
38
+ import { existsSync } from "node:fs";
39
+ import { join } from "node:path";
40
+ import z from "@deepseek-ai/schemastery";
41
+ import { uncToPosix } from "./paths.js";
42
+ /** The composition row's plugin name. */
43
+ export const name = "wsl-open-in-app";
44
+ /** The authenticated route the session-header menu posts to. */
45
+ export const OPEN_IN_APP_PATH = "/api/wsl-env/open-in-app";
46
+ export const Config = z.object({
47
+ /**
48
+ * Editor executable to launch. Empty resolves VS Code from its usual
49
+ * Windows install locations, then falls back to `Code.exe` on PATH.
50
+ */
51
+ executable: z.string().default(""),
52
+ /** Early-failure watch window per launch, in milliseconds. */
53
+ watchMs: z.natural().min(1).default(1_500),
54
+ });
55
+ /**
56
+ * Convert a WSL UNC workspace to the `vscode-remote` URI Remote-WSL expects.
57
+ *
58
+ * Both share spellings (`\\wsl.localhost\<distro>\...` and
59
+ * `\\wsl$\<distro>\...`) are accepted; every other path is refused rather
60
+ * than guessed at.
61
+ *
62
+ * @param uncPath - candidate workspace path.
63
+ * @returns the editor URI, or undefined when the path is not WSL UNC or
64
+ * cannot be encoded (a path with malformed UTF-16 is not a workspace).
65
+ */
66
+ export function editorUri(uncPath) {
67
+ const target = uncToPosix(uncPath);
68
+ if (target === undefined)
69
+ return undefined;
70
+ try {
71
+ const encodedPath = target.linuxPath
72
+ .split("/")
73
+ .map((segment) => encodeURIComponent(segment))
74
+ .join("/");
75
+ const path = encodedPath.startsWith("/") ? encodedPath : `/${encodedPath}`;
76
+ return `vscode-remote://wsl%2B${encodeURIComponent(target.distro)}${path}`;
77
+ }
78
+ catch {
79
+ // `encodeURIComponent` throws URIError on a lone surrogate. The route must
80
+ // answer a classified 400, not reject the request, for such a body.
81
+ return undefined;
82
+ }
83
+ }
84
+ /**
85
+ * The editor executables this machine is likely to carry, in preference order.
86
+ *
87
+ * @param env - environment carrying the Windows install roots.
88
+ * @returns absolute candidate paths; empty when no root is named.
89
+ */
90
+ export function editorCandidates(env) {
91
+ const candidates = [];
92
+ const local = env.LOCALAPPDATA;
93
+ const programFiles = env.ProgramFiles;
94
+ const programFilesX86 = env["ProgramFiles(x86)"];
95
+ if (local !== undefined && local.length > 0) {
96
+ candidates.push(join(local, "Programs", "Microsoft VS Code", "Code.exe"));
97
+ candidates.push(join(local, "Programs", "Microsoft VS Code Insiders", "Code - Insiders.exe"));
98
+ candidates.push(join(local, "Programs", "cursor", "Cursor.exe"));
99
+ }
100
+ if (programFiles !== undefined && programFiles.length > 0) {
101
+ candidates.push(join(programFiles, "Microsoft VS Code", "Code.exe"));
102
+ }
103
+ if (programFilesX86 !== undefined && programFilesX86.length > 0) {
104
+ candidates.push(join(programFilesX86, "Microsoft VS Code", "Code.exe"));
105
+ }
106
+ return candidates;
107
+ }
108
+ /**
109
+ * Resolve the editor executable: an explicit config value wins; otherwise the
110
+ * first existing install candidate; otherwise the PATH name `Code.exe`.
111
+ *
112
+ * @param config - this row's config.
113
+ * @param env - environment carrying the install roots.
114
+ * @param exists - existence check, injected for tests.
115
+ * @returns the command to spawn.
116
+ */
117
+ export function resolveEditor(config, env, exists = existsSync) {
118
+ const configured = (config.executable ?? "").trim();
119
+ if (configured.length > 0)
120
+ return configured;
121
+ for (const candidate of editorCandidates(env)) {
122
+ if (exists(candidate))
123
+ return candidate;
124
+ }
125
+ return "Code.exe";
126
+ }
127
+ /**
128
+ * Remove `ELECTRON_RUN_AS_NODE` from an environment object, in place.
129
+ *
130
+ * Callers pass the editor child's environment copy, never the Host process
131
+ * environment: a Host-wide deletion breaks Node-mode helpers that inherit it.
132
+ *
133
+ * @param env - environment to clean, in place.
134
+ * @returns true when the name was present.
135
+ */
136
+ export function dropElectronRunAsNode(env) {
137
+ if (env.ELECTRON_RUN_AS_NODE === undefined)
138
+ return false;
139
+ delete env.ELECTRON_RUN_AS_NODE;
140
+ return true;
141
+ }
142
+ /**
143
+ * The child environment for one editor launch: the Host environment with
144
+ * `ELECTRON_RUN_AS_NODE` removed. The deletion is scoped to this child;
145
+ * editing the Host's own environment would break Node-mode helpers (the
146
+ * Windows Job runner, for one) that legitimately inherit the flag.
147
+ *
148
+ * @param env - source environment; defaults to the current process environment.
149
+ * @returns a fresh environment safe to hand to an Electron editor.
150
+ */
151
+ export function launchEnvironment(env = process.env) {
152
+ const copy = { ...env };
153
+ dropElectronRunAsNode(copy);
154
+ return copy;
155
+ }
156
+ /**
157
+ * Launch one detached editor through a `--folder-uri` argument and classify
158
+ * an early failure.
159
+ *
160
+ * Success is decoupled from process lifetime, mirroring the host launcher: a
161
+ * child still running when the watch window closes counts as launched (an
162
+ * existing editor window may keep the process in the foreground), exit code 0
163
+ * inside the window counts as launched, and a nonzero exit, a spawn error or
164
+ * a synchronous spawn throw is a failure.
165
+ *
166
+ * @param command - executable path or PATH name.
167
+ * @param args - argv, never a shell string.
168
+ * @param options - watch window and complete child environment.
169
+ * @param spawnChild - spawn seam, injected for tests.
170
+ * @returns the classified outcome.
171
+ */
172
+ export function launchDetached(command, args, options, spawnChild = spawn) {
173
+ return new Promise((resolve) => {
174
+ let child;
175
+ try {
176
+ child = spawnChild(command, [...args], {
177
+ detached: true,
178
+ stdio: "ignore",
179
+ windowsHide: false,
180
+ env: options.env,
181
+ });
182
+ }
183
+ catch {
184
+ resolve("failed");
185
+ return;
186
+ }
187
+ let settled = false;
188
+ const settle = (outcome) => {
189
+ if (settled)
190
+ return;
191
+ settled = true;
192
+ clearTimeout(watch);
193
+ child.unref();
194
+ resolve(outcome);
195
+ };
196
+ const watch = setTimeout(() => { settle("launched"); }, options.watchMs);
197
+ child.once("error", (error) => {
198
+ settle(error.code === "ENOENT" ? "missing" : "failed");
199
+ });
200
+ child.once("exit", (code) => { settle(code === 0 ? "launched" : "failed"); });
201
+ });
202
+ }
203
+ /** JSON response with no-store caching. */
204
+ function json(payload, status = 200) {
205
+ return new Response(JSON.stringify(payload), {
206
+ status,
207
+ headers: { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" },
208
+ });
209
+ }
210
+ /**
211
+ * The route handler: validate one POST body and launch the editor for its WSL
212
+ * workspace. Only a `\\wsl...` UNC path is accepted; the route never launches
213
+ * for a Windows or POSIX path.
214
+ *
215
+ * @param deps - the launch seam.
216
+ * @returns the exact-Fetch handler.
217
+ */
218
+ export function createOpenInAppHandler(deps) {
219
+ return async (request) => {
220
+ if (request.method !== "POST")
221
+ return json({ error: "只支持 POST" }, 405);
222
+ const essence = request.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase();
223
+ if (essence !== "application/json")
224
+ return json({ error: "content-type 必须是 application/json" }, 415);
225
+ let body;
226
+ try {
227
+ body = await request.json();
228
+ }
229
+ catch {
230
+ return json({ error: "请求体不是合法 JSON" }, 400);
231
+ }
232
+ if (typeof body !== "object" || body === null)
233
+ return json({ error: "请求体必须是对象" }, 400);
234
+ const path = body.path;
235
+ if (typeof path !== "string")
236
+ return json({ error: "path 必须是字符串" }, 400);
237
+ const uri = editorUri(path);
238
+ if (uri === undefined)
239
+ return json({ error: "不是 WSL 工作区路径" }, 400);
240
+ let outcome;
241
+ try {
242
+ outcome = await deps.launch(uri);
243
+ }
244
+ catch {
245
+ // The launcher is a seam: a rejected promise must become a classified
246
+ // failure, not an unhandled rejection inside the route.
247
+ return json({ error: "VS Code 启动失败" }, 502);
248
+ }
249
+ if (outcome === "launched")
250
+ return json({ ok: true, uri });
251
+ return json({
252
+ error: outcome === "missing"
253
+ ? "找不到 VS Code;可在 wsl-open-in-app 行配置 executable"
254
+ : "VS Code 启动失败",
255
+ }, 502);
256
+ };
257
+ }
258
+ /**
259
+ * Build the launch seam for one row: resolve the editor once, scrub the child
260
+ * environment once, and hand every call to {@link launchDetached}.
261
+ *
262
+ * The factory exists so a test can observe the exact argv, the detachment
263
+ * flags and the child environment the row produces without starting an editor.
264
+ *
265
+ * @param config - this row's config.
266
+ * @param env - source environment; defaults to the current process environment.
267
+ * @param spawnChild - spawn seam, injected for tests.
268
+ * @returns the launch seam {@link createOpenInAppHandler} calls.
269
+ */
270
+ export function createLauncher(config, env = process.env, spawnChild = spawn) {
271
+ const childEnvironment = launchEnvironment(env);
272
+ const executable = resolveEditor(config, childEnvironment);
273
+ const watchMs = config.watchMs ?? 1_500;
274
+ return (uri) => launchDetached(executable, ["--folder-uri", uri], { watchMs, env: childEnvironment }, spawnChild);
275
+ }
276
+ /**
277
+ * Mount the row: register the route once the Host connection is available.
278
+ * The route scrubs `ELECTRON_RUN_AS_NODE` from each editor child's environment
279
+ * without touching the Host process environment.
280
+ *
281
+ * @param ctx - the cordis context.
282
+ * @param config - the schema-validated config.
283
+ */
284
+ export function apply(ctx, config = {}) {
285
+ if (typeof ctx.inject !== "function")
286
+ return;
287
+ ctx.inject(["connection"], (scope) => {
288
+ const connection = scope.connection ?? scope.get?.("connection");
289
+ if (connection === undefined)
290
+ return;
291
+ const handler = createOpenInAppHandler({ launch: createLauncher(config) });
292
+ const dispose = connection.fetch.register({
293
+ path: OPEN_IN_APP_PATH,
294
+ methods: ["POST"],
295
+ requestBody: "buffered",
296
+ fetch: handler,
297
+ });
298
+ scope.effect?.(() => () => { void dispose(); }, `wsl-open-in-app: ${OPEN_IN_APP_PATH}`);
299
+ });
300
+ }
@@ -14,8 +14,9 @@
14
14
  * The same probes also run once at plugin load (`startup`, on by default) so an
15
15
  * install-plus-restart already carries the verdict in the log — the pinned or
16
16
  * WSL-default distro — before the first session opens. A session on that distro
17
- * repeats only the runtime-context entry; other distros keep the session-open
18
- * check unchanged.
17
+ * repeats only a failing verdict as the runtime-context entry; a ready verdict
18
+ * stays in the log, because "the prerequisite is usable" is not an action the
19
+ * model needs to take. Other distros keep the session-open check unchanged.
19
20
  *
20
21
  * Advisory by construction. A preflight that cannot run (no WSL, a wedged
21
22
  * `wsl.exe`) degrades to a log line; it must never fail a session that has not
@@ -55,7 +56,8 @@ export declare const Config: z<Schemastery.ObjectS<NoInfer<{
55
56
  * against the pinned or WSL-default distro, so the verdict is in the log
56
57
  * before any session opens. Sessions on other distros are still checked at
57
58
  * open, and a session announcement for a message the load pass already
58
- * logged skips the duplicate log line but keeps its runtime-context entry.
59
+ * logged skips the duplicate log line; a failing verdict still lands as the
60
+ * session's runtime-context entry.
59
61
  */
60
62
  startup: z<boolean, boolean, "defined">;
61
63
  }>>, Schemastery.ObjectT<NoInfer<{
@@ -81,7 +83,8 @@ export declare const Config: z<Schemastery.ObjectS<NoInfer<{
81
83
  * against the pinned or WSL-default distro, so the verdict is in the log
82
84
  * before any session opens. Sessions on other distros are still checked at
83
85
  * open, and a session announcement for a message the load pass already
84
- * logged skips the duplicate log line but keeps its runtime-context entry.
86
+ * logged skips the duplicate log line; a failing verdict still lands as the
87
+ * session's runtime-context entry.
85
88
  */
86
89
  startup: z<boolean, boolean, "defined">;
87
90
  }>>, "plain">;