The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | // @effect-diagnostics nodeBuiltinImport:off - the executed suite runs the generated install script through a real POSIX shell. |
| 2 | import * as NodeServices from "@effect/platform-node/NodeServices"; |
| 3 | import { assert, describe, it } from "@effect/vitest"; |
| 4 | import * as Effect from "effect/Effect"; |
| 5 | import * as FileSystem from "effect/FileSystem"; |
| 6 | import * as Layer from "effect/Layer"; |
| 7 | import * as Option from "effect/Option"; |
| 8 | import * as Path from "effect/Path"; |
| 9 | import * as Redacted from "effect/Redacted"; |
| 10 | import * as Sink from "effect/Sink"; |
| 11 | import * as Stream from "effect/Stream"; |
| 12 | import { ChildProcess, ChildProcessSpawner } from "effect/process"; |
| 13 | import { afterAll, expect } from "vite-plus/test"; |
| 14 | import * as NodeChildProcess from "node:child_process"; |
| 15 | |
| 16 | import { ManagedPolicyFileError } from "@t3tools/shared/managedPolicyFile"; |
| 17 | |
| 18 | import * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; |
| 19 | import * as DesktopManagedPolicy from "../app/DesktopManagedPolicy.ts"; |
| 20 | import { |
| 21 | DesktopWslEnvironment, |
| 22 | layer as layerDesktopWslEnvironment, |
| 23 | buildWslRuntimeInstallScript, |
| 24 | makeIsAvailable, |
| 25 | buildWslRuntimePruneScript, |
| 26 | buildWslRuntimeProbeScript, |
| 27 | parseResolvedPath, |
| 28 | parseT3Home, |
| 29 | parseWslRuntimeRoot, |
| 30 | windowsToWslPathImpl, |
| 31 | } from "./DesktopWslEnvironment.ts"; |
| 32 | |
| 33 | // The install script only fails the way this file cares about when a real shell |
| 34 | // runs it, so find one that has the tools it needs: bash directly on Linux, and |
| 35 | // the WSL distro on a Windows dev box, where Git Bash ships no flock. Anywhere |
| 36 | // else the executed suite skips and the generated-text assertions stand alone. |
| 37 | const REQUIRED_SHELL_TOOLS = ["flock", "sha256sum", "tar", "mktemp"] as const; |
| 38 | |
| 39 | const posixShellRunner = (() => { |
| 40 | const candidates = [ |
| 41 | { file: "bash", args: [] as ReadonlyArray<string> }, |
| 42 | { file: "wsl.exe", args: ["-e", "bash"] as ReadonlyArray<string> }, |
| 43 | ]; |
| 44 | const probe = [ |
| 45 | "[ -d /proc/1 ] || exit 1", |
| 46 | ...REQUIRED_SHELL_TOOLS.map((tool) => `command -v ${tool} >/dev/null || exit 1`), |
| 47 | ].join("\n"); |
| 48 | return ( |
| 49 | candidates.find((candidate) => { |
| 50 | const result = NodeChildProcess.spawnSync(candidate.file, [...candidate.args, "-c", probe], { |
| 51 | encoding: "utf8", |
| 52 | }); |
| 53 | return result.status === 0; |
| 54 | }) ?? null |
| 55 | ); |
| 56 | })(); |
| 57 | |
| 58 | const runShell = (script: string) => { |
| 59 | if (posixShellRunner === null) throw new Error("no POSIX shell runner available"); |
| 60 | // Pass the script on stdin, as production does, to avoid matching its own /proc scan. |
| 61 | const result = NodeChildProcess.spawnSync( |
| 62 | posixShellRunner.file, |
| 63 | [...posixShellRunner.args, "-s"], |
| 64 | { input: script, encoding: "utf8" }, |
| 65 | ); |
| 66 | return { status: result.status, stdout: result.stdout ?? "", stderr: result.stderr ?? "" }; |
| 67 | }; |
| 68 | |
| 69 | const sh = (value: string) => `'${value.replaceAll("'", "'\\''")}'`; |
| 70 | |
| 71 | const awaitHolder = (condition: string) => |
| 72 | `i=0; until ${condition}; do i=$((i + 1)); [ "$i" -lt 500 ] || exit 1; sleep 0.01; done`; |
| 73 | |
| 74 | // Use runtime-entry argv[0] for /proc detection; an open pipe keeps it alive only while this script runs. |
| 75 | const holdRuntimeBusy = (entry: string) => |
| 76 | [ |
| 77 | `exec 7> >(exec -a ${entry} cat >/dev/null 2>&1)`, |
| 78 | awaitHolder(`grep -qF -- ${entry} /proc/[0-9]*/cmdline 2>/dev/null`), |
| 79 | ].join("\n"); |
| 80 | |
| 81 | const holdInstallLock = (lock: string) => |
| 82 | [ |
| 83 | `exec 6> >(exec 9> ${lock}; flock -x 9; cat >/dev/null 2>&1)`, |
| 84 | awaitHolder(`! flock -n ${lock} true`), |
| 85 | ].join("\n"); |
| 86 | |
| 87 | const readField = (stdout: string, field: string) => { |
| 88 | const line = stdout.split("\n").find((candidate) => candidate.startsWith(`${field}:`)); |
| 89 | if (line === undefined) throw new Error(`missing ${field} in fixture output: ${stdout}`); |
| 90 | return line.slice(field.length + 1).trim(); |
| 91 | }; |
| 92 | |
| 93 | const SERVER_ENTRY_SOURCE = '#!/bin/sh\necho "t3code wsl runtime test server 0.0.0"\n'; |
| 94 | |
| 95 | describe("WSL runtime cache", () => { |
| 96 | it.each([ |
| 97 | [ |
| 98 | "install", |
| 99 | (id: string) => buildWslRuntimeInstallScript("/runtime.tar.gz", id, "b".repeat(64), null), |
| 100 | ], |
| 101 | ["prune", (id: string) => buildWslRuntimePruneScript(id, null)], |
| 102 | ] as const)("sanitizes cache ids in the %s script", (_, buildScript) => { |
| 103 | const runtimeId = "1.2.3/x64; touch /tmp/nope"; |
| 104 | const script = buildScript(runtimeId); |
| 105 | expect(script).toContain("/1.2.3_x64__touch__tmp_nope"); |
| 106 | expect(script).not.toContain(runtimeId); |
| 107 | }); |
| 108 | }); |
| 109 | |
| 110 | describe.skipIf(posixShellRunner === null)("WSL runtime install script (executed)", () => { |
| 111 | const fixtures: Array<string> = []; |
| 112 | |
| 113 | afterAll(() => { |
| 114 | for (const work of fixtures) runShell(`set -eu\nrm -rf ${sh(work)}`); |
| 115 | fixtures.length = 0; |
| 116 | }); |
| 117 | |
| 118 | const createFixture = (serverEntry = SERVER_ENTRY_SOURCE) => { |
| 119 | const result = runShell( |
| 120 | [ |
| 121 | "set -eu", |
| 122 | "work=$(mktemp -d)", |
| 123 | 'stage="$work/stage/t3-0.0.0-linux-x64"', |
| 124 | 'mkdir -p "$stage/node_modules/node-pty/build/Release" "$work/home"', |
| 125 | `printf '%s' ${sh(serverEntry)} > "$stage/t3"`, |
| 126 | 'chmod +x "$stage/t3"', |
| 127 | `printf '%s' 'pty-native-payload' > "$stage/node_modules/node-pty/build/Release/pty.node"`, |
| 128 | `tar -czf "$work/wsl-runtime.tar.gz" -C "$work/stage" t3-0.0.0-linux-x64`, |
| 129 | `printf 'work:%s\\n' "$work"`, |
| 130 | `printf 'archiveSha:%s\\n' "$(sha256sum "$work/wsl-runtime.tar.gz" | cut -d ' ' -f 1)"`, |
| 131 | ].join("\n"), |
| 132 | ); |
| 133 | expect(result.status, result.stderr).toBe(0); |
| 134 | |
| 135 | const work = readField(result.stdout, "work"); |
| 136 | fixtures.push(work); |
| 137 | const archivePath = `${work}/wsl-runtime.tar.gz`; |
| 138 | const archiveSha = readField(result.stdout, "archiveSha"); |
| 139 | const runtimeId = `sha256-${archiveSha}`; |
| 140 | // WSL does not inherit HOME; embed the fixture's override in the script. |
| 141 | const installScript = (archive = archivePath, sha = archiveSha, t3Home: string | null = null) => |
| 142 | [ |
| 143 | `HOME=${sh(`${work}/home`)}`, |
| 144 | "export HOME", |
| 145 | buildWslRuntimeInstallScript(archive, runtimeId, sha, t3Home), |
| 146 | ].join("\n"); |
| 147 | return { |
| 148 | work, |
| 149 | archivePath, |
| 150 | archiveSha, |
| 151 | runtimeId, |
| 152 | runtimeParent: `${work}/home/.t3/wsl-runtime`, |
| 153 | runtimeRoot: `${work}/home/.t3/wsl-runtime/${runtimeId}`, |
| 154 | serverEntry: `${work}/home/.t3/wsl-runtime/${runtimeId}/t3`, |
| 155 | installScript, |
| 156 | install: (archive?: string, sha?: string, t3Home?: string | null) => |
| 157 | runShell(installScript(archive, sha, t3Home)), |
| 158 | }; |
| 159 | }; |
| 160 | |
| 161 | const probeFixture = (fixture: ReturnType<typeof createFixture>) => |
| 162 | runShell( |
| 163 | [ |
| 164 | `export HOME=${sh(`${fixture.work}/home`)}`, |
| 165 | 'export NVM_DIR="$HOME/.nvm" FNM_DIR="$HOME/.fnm" VOLTA_HOME="$HOME/.volta"', |
| 166 | "bash() { (", |
| 167 | " command() {", |
| 168 | ' case "$*" in', |
| 169 | ' "-v node"|"-v mise"|"-v fnm"|"-v nodenv") return 1 ;;', |
| 170 | ' *) builtin command "$@" ;;', |
| 171 | " esac", |
| 172 | " }", |
| 173 | ' eval "$2"', |
| 174 | "); }", |
| 175 | buildWslRuntimeProbeScript(), |
| 176 | ].join("\n"), |
| 177 | ); |
| 178 | |
| 179 | it("discovers version-managed Node for providers with a standalone runtime", () => { |
| 180 | const fixture = createFixture(); |
| 181 | expect(fixture.install().status).toBe(0); |
| 182 | const nodeBin = `${fixture.work}/home/.nvm/versions/node/v24.15.0/bin`; |
| 183 | const setup = runShell( |
| 184 | [ |
| 185 | "set -eu", |
| 186 | `mkdir -p ${sh(nodeBin)}`, |
| 187 | `printf '%s' ${sh('#!/bin/sh\nprintf "linux-node-provider\\n"\n')} > ${sh(`${nodeBin}/node`)}`, |
| 188 | `chmod +x ${sh(`${nodeBin}/node`)}`, |
| 189 | ].join("\n"), |
| 190 | ); |
| 191 | expect(setup.status, setup.stderr).toBe(0); |
| 192 | |
| 193 | const probe = probeFixture(fixture); |
| 194 | |
| 195 | expect(probe.status, probe.stderr).toBe(0); |
| 196 | const resolvedPath = parseResolvedPath(probe.stdout); |
| 197 | expect(resolvedPath?.split(":")).toContain(nodeBin); |
| 198 | const provider = runShell(`export PATH=${sh(resolvedPath ?? "")}\nnode provider.js`); |
| 199 | expect(provider.status, provider.stderr).toBe(0); |
| 200 | expect(provider.stdout).toBe("linux-node-provider\n"); |
| 201 | }); |
| 202 | |
| 203 | it("stages the runtime under the login shell's T3CODE_HOME and reports it to the launcher", () => { |
| 204 | const fixture = createFixture(); |
| 205 | const t3Home = `${fixture.work}/home/.config/t3 home`; |
| 206 | const install = fixture.install(undefined, undefined, t3Home); |
| 207 | expect(install.status, install.stderr).toBe(0); |
| 208 | expect(parseWslRuntimeRoot(install.stdout)).toBe(`${t3Home}/wsl-runtime/${fixture.runtimeId}`); |
| 209 | expect(runShell(`test ! -e ${sh(`${fixture.work}/home/.t3`)}`).status).toBe(0); |
| 210 | |
| 211 | const probe = runShell( |
| 212 | [ |
| 213 | `bash() { ( export T3CODE_HOME=${sh(t3Home)}; eval "$2" ); }`, |
| 214 | buildWslRuntimeProbeScript(), |
| 215 | ].join("\n"), |
| 216 | ); |
| 217 | expect(probe.status, probe.stderr).toBe(0); |
| 218 | expect(parseT3Home(probe.stdout)).toBe(t3Home); |
| 219 | }); |
| 220 | |
| 221 | it("keeps the inherited PATH when bash is unavailable", () => { |
| 222 | const fixture = createFixture(); |
| 223 | expect(fixture.install().status).toBe(0); |
| 224 | const probe = runShell( |
| 225 | [ |
| 226 | "bash() { return 127; }", |
| 227 | 'export PATH="/fixture/bin:/usr/bin:/bin"', |
| 228 | buildWslRuntimeProbeScript(), |
| 229 | ].join("\n"), |
| 230 | ); |
| 231 | |
| 232 | expect(probe.status, probe.stderr).toBe(0); |
| 233 | expect(parseResolvedPath(probe.stdout)).toBe("/fixture/bin:/usr/bin:/bin"); |
| 234 | }); |
| 235 | |
| 236 | it("reuses a warm cache without touching the archive", () => { |
| 237 | const fixture = createFixture(); |
| 238 | expect(fixture.install().status).toBe(0); |
| 239 | expect(runShell(`set -eu\nrm ${sh(fixture.archivePath)}`).status).toBe(0); |
| 240 | |
| 241 | const warm = fixture.install(); |
| 242 | |
| 243 | expect(warm.status, warm.stderr).toBe(0); |
| 244 | expect(parseWslRuntimeRoot(warm.stdout)).toBe(fixture.runtimeRoot); |
| 245 | }); |
| 246 | |
| 247 | it("retains the loader error when a bundled executable needs a missing system library", () => { |
| 248 | const fixture = createFixture( |
| 249 | '#!/bin/sh\nprintf "error while loading shared libraries: libatomic.so.1: cannot open shared object file\\n" >&2\nexit 127\n', |
| 250 | ); |
| 251 | |
| 252 | const result = fixture.install(); |
| 253 | |
| 254 | expect(result.status).not.toBe(0); |
| 255 | expect(result.stderr).toContain("libatomic.so.1"); |
| 256 | expect(parseWslRuntimeRoot(result.stdout)).toBeNull(); |
| 257 | }); |
| 258 | |
| 259 | it("reinstalls a cache whose executable was truncated", () => { |
| 260 | const fixture = createFixture(); |
| 261 | expect(fixture.install().status).toBe(0); |
| 262 | expect(runShell(`set -eu\n: > ${sh(fixture.serverEntry)}`).status).toBe(0); |
| 263 | |
| 264 | const repaired = fixture.install(); |
| 265 | |
| 266 | expect(repaired.status, repaired.stderr).toBe(0); |
| 267 | expect(parseWslRuntimeRoot(repaired.stdout)).toBe(fixture.runtimeRoot); |
| 268 | const restored = runShell(`set -eu\ncat ${sh(fixture.serverEntry)}`); |
| 269 | expect(restored.stdout).toBe(SERVER_ENTRY_SOURCE); |
| 270 | }); |
| 271 | |
| 272 | it("reinstalls an executable that fails --version despite a matching recorded digest", () => { |
| 273 | const fixture = createFixture(); |
| 274 | expect(fixture.install().status).toBe(0); |
| 275 | const brokenEntry = "#!/bin/sh\nexit 42\n"; |
| 276 | const corrupt = runShell( |
| 277 | [ |
| 278 | "set -eu", |
| 279 | `printf '%s' ${sh(brokenEntry)} > ${sh(fixture.serverEntry)}`, |
| 280 | `chmod +x ${sh(fixture.serverEntry)}`, |
| 281 | `sha256sum ${sh(fixture.serverEntry)} | cut -d ' ' -f 1 > ${sh(`${fixture.runtimeRoot}/.t3code-wsl-runtime-ready`)}`, |
| 282 | ].join("\n"), |
| 283 | ); |
| 284 | expect(corrupt.status, corrupt.stderr).toBe(0); |
| 285 | expect(runShell(`${sh(fixture.serverEntry)} --version`).status).toBe(42); |
| 286 | |
| 287 | const repaired = fixture.install(); |
| 288 | expect(repaired.status, repaired.stderr).toBe(0); |
| 289 | expect(parseWslRuntimeRoot(repaired.stdout)).toBe(fixture.runtimeRoot); |
| 290 | expect(runShell(`cat ${sh(fixture.serverEntry)}`).stdout).toBe(SERVER_ENTRY_SOURCE); |
| 291 | expect(runShell(`${sh(fixture.serverEntry)} --version`).status).toBe(0); |
| 292 | }); |
| 293 | |
| 294 | it("falls back instead of launching a corrupted cache it cannot reinstall", () => { |
| 295 | const fixture = createFixture(); |
| 296 | expect(fixture.install().status).toBe(0); |
| 297 | expect(runShell(`set -eu\n: > ${sh(fixture.serverEntry)}`).status).toBe(0); |
| 298 | expect(runShell(`set -eu\nrm ${sh(fixture.archivePath)}`).status).toBe(0); |
| 299 | |
| 300 | const broken = fixture.install(); |
| 301 | |
| 302 | expect(broken.status).not.toBe(0); |
| 303 | expect(parseWslRuntimeRoot(broken.stdout)).toBeNull(); |
| 304 | }); |
| 305 | |
| 306 | it("extracts once when two installs race for the same cache", () => { |
| 307 | const fixture = createFixture(); |
| 308 | const raced = runShell( |
| 309 | [ |
| 310 | "set -eu", |
| 311 | `work=${sh(fixture.work)}`, |
| 312 | 'mkdir -p "$work/bin"', |
| 313 | "real_tar=$(command -v tar)", |
| 314 | `printf '#!/bin/sh\\nprintf x >> "%s/tar-calls"\\nsleep 1\\nexec %s "$@"\\n' "$work" "$real_tar" > "$work/bin/tar"`, |
| 315 | 'chmod +x "$work/bin/tar"', |
| 316 | ': > "$work/tar-calls"', |
| 317 | 'PATH="$work/bin:$PATH"', |
| 318 | "export PATH", |
| 319 | `cat > "$work/install.sh" <<'T3CODE_INSTALL_SCRIPT'`, |
| 320 | fixture.installScript(), |
| 321 | "T3CODE_INSTALL_SCRIPT", |
| 322 | // Keep runtime roots out of both racers' argv so their /proc scans cannot match themselves. |
| 323 | 'sh "$work/install.sh" > "$work/first.out" 2>&1 &', |
| 324 | "first=$!", |
| 325 | 'sh "$work/install.sh" > "$work/second.out" 2>&1 &', |
| 326 | "second=$!", |
| 327 | "if wait $first; then first_status=0; else first_status=$?; fi", |
| 328 | "if wait $second; then second_status=0; else second_status=$?; fi", |
| 329 | `printf 'firstStatus:%s\\n' "$first_status"`, |
| 330 | `printf 'secondStatus:%s\\n' "$second_status"`, |
| 331 | `printf 'extractions:%s\\n' "$(wc -c < "$work/tar-calls" | tr -d ' ')"`, |
| 332 | `printf 'firstRoot:%s\\n' "$(sed -n 's/^runtimeRoot://p' "$work/first.out")"`, |
| 333 | `printf 'secondRoot:%s\\n' "$(sed -n 's/^runtimeRoot://p' "$work/second.out")"`, |
| 334 | ].join("\n"), |
| 335 | ); |
| 336 | |
| 337 | expect(raced.status, raced.stderr).toBe(0); |
| 338 | expect(readField(raced.stdout, "firstStatus")).toBe("0"); |
| 339 | expect(readField(raced.stdout, "secondStatus")).toBe("0"); |
| 340 | expect(readField(raced.stdout, "extractions")).toBe("1"); |
| 341 | expect(readField(raced.stdout, "firstRoot")).toBe(fixture.runtimeRoot); |
| 342 | expect(readField(raced.stdout, "secondRoot")).toBe(fixture.runtimeRoot); |
| 343 | }); |
| 344 | |
| 345 | it("leaves no half-built cache when extraction fails", () => { |
| 346 | const fixture = createFixture(); |
| 347 | const truncated = runShell( |
| 348 | [ |
| 349 | "set -eu", |
| 350 | `work=${sh(fixture.work)}`, |
| 351 | 'size=$(wc -c < "$work/wsl-runtime.tar.gz")', |
| 352 | 'head -c $((size / 2)) "$work/wsl-runtime.tar.gz" > "$work/truncated.tar.gz"', |
| 353 | `printf 'sha:%s\\n' "$(sha256sum "$work/truncated.tar.gz" | cut -d ' ' -f 1)"`, |
| 354 | ].join("\n"), |
| 355 | ); |
| 356 | expect(truncated.status, truncated.stderr).toBe(0); |
| 357 | |
| 358 | const failed = fixture.install( |
| 359 | `${fixture.work}/truncated.tar.gz`, |
| 360 | readField(truncated.stdout, "sha"), |
| 361 | ); |
| 362 | |
| 363 | expect(failed.status).not.toBe(0); |
| 364 | expect(parseWslRuntimeRoot(failed.stdout)).toBeNull(); |
| 365 | const leftovers = runShell( |
| 366 | `set -eu\nfind ${sh(fixture.runtimeParent)} -mindepth 1 -maxdepth 1 -type d`, |
| 367 | ); |
| 368 | expect(leftovers.stdout.trim()).toBe(""); |
| 369 | }); |
| 370 | |
| 371 | it("refuses an archive whose bytes do not match the digest recorded for it", () => { |
| 372 | const fixture = createFixture(); |
| 373 | |
| 374 | const refused = fixture.install(fixture.archivePath, "e".repeat(64)); |
| 375 | |
| 376 | expect(refused.status).not.toBe(0); |
| 377 | expect(refused.stderr).toContain("does not match its recorded SHA-256"); |
| 378 | expect(parseWslRuntimeRoot(refused.stdout)).toBeNull(); |
| 379 | const leftovers = runShell( |
| 380 | `set -eu\nfind ${sh(fixture.runtimeParent)} -mindepth 1 -maxdepth 1 -type d`, |
| 381 | ); |
| 382 | expect(leftovers.stdout.trim()).toBe(""); |
| 383 | }); |
| 384 | |
| 385 | it("leases a warm cache across the prepare-to-spawn handoff", () => { |
| 386 | const fixture = createFixture(); |
| 387 | expect(fixture.install().status).toBe(0); |
| 388 | const selected = runShell( |
| 389 | [ |
| 390 | "set -eu", |
| 391 | `runtime_parent=${sh(fixture.runtimeParent)}`, |
| 392 | 'mkdir -p "$runtime_parent/sha256-current" "$runtime_parent/sha256-previous"', |
| 393 | 'printf ready > "$runtime_parent/sha256-current/.t3code-wsl-runtime-ready"', |
| 394 | 'printf ready > "$runtime_parent/sha256-previous/.t3code-wsl-runtime-ready"', |
| 395 | `touch -d "10 minutes ago" ${sh(fixture.runtimeRoot)}`, |
| 396 | 'touch -d "1 minute ago" "$runtime_parent/sha256-previous"', |
| 397 | `cat > ${sh(`${fixture.work}/select.sh`)} <<'T3CODE_SELECT_SCRIPT'`, |
| 398 | fixture.installScript(), |
| 399 | "T3CODE_SELECT_SCRIPT", |
| 400 | `sh ${sh(`${fixture.work}/select.sh`)}`, |
| 401 | `HOME=${sh(`${fixture.work}/home`)}`, |
| 402 | "export HOME", |
| 403 | buildWslRuntimePruneScript("sha256-current", null), |
| 404 | `test -d ${sh(fixture.runtimeRoot)}`, |
| 405 | ].join("\n"), |
| 406 | ); |
| 407 | |
| 408 | expect(selected.status, `${selected.stdout}\n${selected.stderr}`).toBe(0); |
| 409 | }); |
| 410 | |
| 411 | // Runs the distro side on the local bash, so a Windows dev box using the wsl.exe runner skips it. |
| 412 | describe.skipIf(posixShellRunner?.file !== "bash")("prepareRuntime through wsl.exe", () => { |
| 413 | // Emulates `wsl.exe [-d <distro>] [--cd <dir>] [--|--exec] <argv>` in a distro with automount off. |
| 414 | const layerFakeWslExe = (home: string) => |
| 415 | Layer.effect( |
| 416 | ChildProcessSpawner.ChildProcessSpawner, |
| 417 | Effect.map(ChildProcessSpawner.ChildProcessSpawner, (local) => |
| 418 | ChildProcessSpawner.make((command) => { |
| 419 | if (!ChildProcess.isStandardCommand(command) || command.command !== "wsl.exe") { |
| 420 | return local.spawn(command); |
| 421 | } |
| 422 | const args = command.args.map((word) => |
| 423 | Redacted.isRedacted(word) ? Redacted.value(word) : word, |
| 424 | ); |
| 425 | while (args.length > 0) { |
| 426 | const flag = args[0]; |
| 427 | if (flag === "-d" || flag === "--distribution" || flag === "--cd") { |
| 428 | args.splice(0, 2); |
| 429 | } else if (flag === "--" || flag === "--exec" || flag === "-e") { |
| 430 | args.shift(); |
| 431 | break; |
| 432 | } else { |
| 433 | break; |
| 434 | } |
| 435 | } |
| 436 | const [file = "sh", ...rest] = |
| 437 | args[0] === "wslpath" |
| 438 | ? [ |
| 439 | "sh", |
| 440 | "-c", |
| 441 | 'printf "wslpath: %s\\n" "$1" >&2; exit 1', |
| 442 | "wslpath", |
| 443 | args.at(-1) ?? "", |
| 444 | ] |
| 445 | : args; |
| 446 | return local.spawn( |
| 447 | ChildProcess.make(file, rest, { |
| 448 | ...command.options, |
| 449 | env: { ...command.options.env, HOME: home }, |
| 450 | extendEnv: true, |
| 451 | }), |
| 452 | ); |
| 453 | }), |
| 454 | ), |
| 455 | ); |
| 456 | |
| 457 | const layerWslEnvironment = (home: string) => |
| 458 | layerDesktopWslEnvironment.pipe( |
| 459 | Layer.provide( |
| 460 | Layer.mergeAll( |
| 461 | layerFakeWslExe(home), |
| 462 | DesktopManagedPolicy.layerTest(), |
| 463 | Layer.effect( |
| 464 | DesktopEnvironment.DesktopEnvironment, |
| 465 | Effect.map( |
| 466 | Path.Path, |
| 467 | (path) => |
| 468 | ({ platform: "win32", path }) as DesktopEnvironment.DesktopEnvironment["Service"], |
| 469 | ), |
| 470 | ), |
| 471 | ), |
| 472 | ), |
| 473 | Layer.provide(NodeServices.layer), |
| 474 | ); |
| 475 | |
| 476 | it.live("installs the runtime when wslpath cannot translate the archive's Windows path", () => { |
| 477 | const fixture = createFixture(); |
| 478 | return Effect.gen(function* () { |
| 479 | const wsl = yield* DesktopWslEnvironment; |
| 480 | // The archive's Windows path; with no drives mounted, wslpath cannot map it into the distro. |
| 481 | const translated = yield* wsl.windowsToWslPath("Ubuntu", fixture.archivePath); |
| 482 | expect(translated._tag).toBe("None"); |
| 483 | |
| 484 | const prepared = yield* wsl.prepareRuntime( |
| 485 | "Ubuntu", |
| 486 | { |
| 487 | windowsPath: fixture.archivePath, |
| 488 | runtimeId: fixture.runtimeId, |
| 489 | sha256: fixture.archiveSha, |
| 490 | }, |
| 491 | null, |
| 492 | ); |
| 493 | |
| 494 | expect(prepared).toEqual({ ok: true, linuxAppRoot: fixture.runtimeRoot }); |
| 495 | const version = runShell(`${sh(fixture.serverEntry)} --version`); |
| 496 | expect(version.status, version.stderr).toBe(0); |
| 497 | expect(version.stdout).toBe("t3code wsl runtime test server 0.0.0\n"); |
| 498 | }).pipe(Effect.provide(layerWslEnvironment(`${fixture.work}/home`))); |
| 499 | }); |
| 500 | }); |
| 501 | |
| 502 | it("prunes old and markerless caches without touching retained, active, locked, or unrelated roots", () => { |
| 503 | const result = runShell( |
| 504 | [ |
| 505 | "set -eu", |
| 506 | "work=$(mktemp -d)", |
| 507 | 'home="$work/home"', |
| 508 | 'runtime_parent="$home/.t3/wsl-runtime"', |
| 509 | 'mkdir -p "$runtime_parent"', |
| 510 | 'make_ready() { mkdir -p "$runtime_parent/$1"; printf ready > "$runtime_parent/$1/.t3code-wsl-runtime-ready"; }', |
| 511 | "make_ready sha256-current", |
| 512 | "make_ready sha256-previous", |
| 513 | "make_ready sha256-active", |
| 514 | "make_ready sha256-old", |
| 515 | "make_ready sha256-locked", |
| 516 | 'mkdir -p "$runtime_parent/sha256-markerless" "$runtime_parent/versions"', |
| 517 | 'touch -d "1 minute ago" "$runtime_parent/sha256-previous"', |
| 518 | 'touch -d "4 minutes ago" "$runtime_parent/sha256-active"', |
| 519 | 'touch -d "3 minutes ago" "$runtime_parent/sha256-old"', |
| 520 | 'touch -d "2 minutes ago" "$runtime_parent/sha256-locked"', |
| 521 | holdRuntimeBusy('"$runtime_parent/sha256-active/t3"'), |
| 522 | holdInstallLock('"$runtime_parent/.sha256-locked.install.lock"'), |
| 523 | `HOME="$home"`, |
| 524 | "export HOME", |
| 525 | buildWslRuntimePruneScript("sha256-current", null), |
| 526 | 'test -d "$runtime_parent/sha256-current"', |
| 527 | 'test -d "$runtime_parent/sha256-previous"', |
| 528 | 'test -d "$runtime_parent/sha256-active"', |
| 529 | 'test -d "$runtime_parent/sha256-locked"', |
| 530 | 'test -d "$runtime_parent/versions"', |
| 531 | 'test ! -e "$runtime_parent/sha256-old"', |
| 532 | 'test ! -e "$runtime_parent/sha256-markerless"', |
| 533 | 'rm -rf "$work"', |
| 534 | ].join("\n"), |
| 535 | ); |
| 536 | |
| 537 | expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(0); |
| 538 | }); |
| 539 | }); |
| 540 | |
| 541 | describe("parseResolvedPath", () => { |
| 542 | it("preserves spaces and apostrophes in the resolved login-shell PATH", () => { |
| 543 | const resolvedPath = "/home/test user/bin:/opt/test's tools/bin:/usr/bin:/bin"; |
| 544 | expect(parseResolvedPath(`nodePath:/usr/bin/node\nresolvedPath:${resolvedPath}\n`)).toBe( |
| 545 | resolvedPath, |
| 546 | ); |
| 547 | }); |
| 548 | |
| 549 | it("accepts CRLF output without retaining the carriage return", () => { |
| 550 | expect(parseResolvedPath("resolvedPath:/usr/local/bin:/usr/bin\r\n")).toBe( |
| 551 | "/usr/local/bin:/usr/bin", |
| 552 | ); |
| 553 | }); |
| 554 | }); |
| 555 | |
| 556 | // Path.layer joins with POSIX separators here, so the test windir is a POSIX path. |
| 557 | const WSL_EXE = "/windows/System32/wsl.exe"; |
| 558 | |
| 559 | const isAvailable = (policy?: Parameters<typeof DesktopManagedPolicy.layerTest>[0]) => |
| 560 | makeIsAvailable("win32", "/windows").pipe( |
| 561 | Effect.provide( |
| 562 | Layer.mergeAll( |
| 563 | FileSystem.layerNoop({ exists: (path) => Effect.succeed(path === WSL_EXE) }), |
| 564 | Path.layer, |
| 565 | DesktopManagedPolicy.layerTest(policy), |
| 566 | ), |
| 567 | ), |
| 568 | ); |
| 569 | |
| 570 | describe("makeIsAvailable", () => { |
| 571 | it.effect("turns WSL off on a machine with a managed policy, even an invalid one", () => |
| 572 | Effect.gen(function* () { |
| 573 | assert.isTrue(yield* isAvailable()); |
| 574 | assert.isFalse(yield* isAvailable({ schemaVersion: 1, organization: "Example Corp" })); |
| 575 | assert.isFalse( |
| 576 | yield* isAvailable(new ManagedPolicyFileError({ path: "/test", reason: "bad JSON" })), |
| 577 | ); |
| 578 | }), |
| 579 | ); |
| 580 | }); |
| 581 | |
| 582 | describe("windowsToWslPathImpl", () => { |
| 583 | it.effect("runs wslpath without a shell so folder names stay one literal argument", () => |
| 584 | Effect.gen(function* () { |
| 585 | const spawned: Array<ChildProcess.Command> = []; |
| 586 | const stdout = Stream.make(new TextEncoder().encode("/mnt/c/a$b & c;(d)\n")); |
| 587 | const spawner = ChildProcessSpawner.make((command) => { |
| 588 | spawned.push(command); |
| 589 | return Effect.succeed( |
| 590 | ChildProcessSpawner.makeHandle({ |
| 591 | pid: ChildProcessSpawner.ProcessId(1), |
| 592 | stdout, |
| 593 | stderr: Stream.empty, |
| 594 | all: stdout, |
| 595 | exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)), |
| 596 | isRunning: Effect.succeed(false), |
| 597 | kill: () => Effect.void, |
| 598 | stdin: Sink.drain, |
| 599 | getInputFd: () => Sink.drain, |
| 600 | getOutputFd: () => Stream.empty, |
| 601 | unref: Effect.succeed(Effect.void), |
| 602 | }), |
| 603 | ); |
| 604 | }); |
| 605 | |
| 606 | const converted = yield* windowsToWslPathImpl("Ubuntu", "C:\\a$b & c;(d)").pipe( |
| 607 | Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), |
| 608 | ); |
| 609 | |
| 610 | assert.deepStrictEqual(converted, Option.some("/mnt/c/a$b & c;(d)")); |
| 611 | assert.lengthOf(spawned, 1); |
| 612 | const [command] = spawned; |
| 613 | assert(command?._tag === "StandardCommand"); |
| 614 | assert.strictEqual(command.command, "wsl.exe"); |
| 615 | assert.deepStrictEqual(command.args, [ |
| 616 | "-d", |
| 617 | "Ubuntu", |
| 618 | "--exec", |
| 619 | "wslpath", |
| 620 | "-u", |
| 621 | "C:/a$b & c;(d)", |
| 622 | ]); |
| 623 | }), |
| 624 | ); |
| 625 | }); |