Files
t3code/apps/server/src/process/externalLauncher.test.ts
T

1536 lines
58 KiB
TypeScript

// @effect-diagnostics nodeBuiltinImport:off - the Windows reveal smoke test drives a real PowerShell through Node process and filesystem APIs.
import * as NodeChildProcess from "node:child_process";
import * as NodeFS from "node:fs";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import * as ConfigProvider from "effect/ConfigProvider";
import * as Deferred from "effect/Deferred";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import * as TestClock from "effect/testing/TestClock";
import { ChildProcess, ChildProcessSpawner } from "effect/process";
import * as HostProcess from "@t3tools/shared/HostProcess";
import { SpawnExecutableResolution } from "@t3tools/shared/shell";
import * as ExternalLauncher from "./externalLauncher.ts";
// Tests below write `#!/bin/sh` stubs into a real temp dir and hand that
// directory to a posix-mocked resolver as PATH. On a Windows host the temp
// path carries a drive letter, so the posix `:` split shatters it; there is
// no posix executable to find there anyway.
const windowsHost = HostProcess.Platform.defaultValue() === "win32";
interface MockSpawnResult {
readonly exitCode?: number;
readonly stdout?: string;
/** Never deliver an exit code, like a child wedged on a broken desktop session. */
readonly stall?: boolean;
}
function makeMockDetachedHandle(input: MockSpawnResult & { readonly onUnref?: () => void } = {}) {
return ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(1),
exitCode: input.stall
? Effect.never
: Effect.succeed(ChildProcessSpawner.ExitCode(input.exitCode ?? 0)),
isRunning: Effect.succeed(true),
kill: () => Effect.void,
unref: Effect.sync(() => {
input.onUnref?.();
return Effect.void;
}),
stdin: Sink.drain,
stdout:
input.stdout === undefined
? Stream.empty
: Stream.make(new TextEncoder().encode(input.stdout)),
stderr: Stream.empty,
all: Stream.empty,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
});
}
const layerTest = (input: {
readonly platform: NodeJS.Platform;
readonly env?: Record<string, string>;
readonly resolveExecutable?: (command: string) => string | undefined;
readonly onSpawn?: (command: ChildProcess.StandardCommand) => void;
readonly onUnref?: () => void;
readonly spawnResult?: (command: ChildProcess.StandardCommand) => MockSpawnResult | undefined;
}) => {
const layerSpawner = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make((command) =>
Effect.sync(() => {
assert.equal(ChildProcess.isStandardCommand(command), true);
if (!ChildProcess.isStandardCommand(command)) {
throw new Error("Expected a standard command");
}
input.onSpawn?.(command);
return makeMockDetachedHandle({
...(input.onUnref === undefined ? {} : { onUnref: input.onUnref }),
...input.spawnResult?.(command),
});
}),
),
);
return Layer.mergeAll(
ExternalLauncher.layer.pipe(Layer.provide(Layer.merge(NodeServices.layer, layerSpawner))),
Layer.succeed(HostProcess.Platform, input.platform),
Layer.succeed(
SpawnExecutableResolution,
(command) => input.resolveExecutable?.(command) ?? command,
),
ConfigProvider.layer(ConfigProvider.fromEnv({ env: input.env ?? {} })),
);
};
it.effect("launches the default browser through the platform command", () => {
let spawned: ChildProcess.StandardCommand | undefined;
let didUnref = false;
return Effect.gen(function* () {
const launcher = yield* ExternalLauncher.ExternalLauncher;
yield* launcher.launchBrowser("https://example.com/some path");
assert.ok(spawned);
assert.equal(spawned.command, "xdg-open");
assert.deepEqual(spawned.args, ["https://example.com/some path"]);
assert.equal(spawned.options.detached, true);
assert.equal(didUnref, true);
}).pipe(
Effect.provide(
layerTest({
platform: "linux",
onSpawn: (command) => {
spawned = command;
},
onUnref: () => {
didUnref = true;
},
}),
),
);
});
it.effect("launches an installed editor with platform-safe arguments", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
yield* fileSystem.writeFileString(path.join(binDir, "code.CMD"), "@echo off\r\n");
let spawned: ChildProcess.StandardCommand | undefined;
yield* Effect.gen(function* () {
const launcher = yield* ExternalLauncher.ExternalLauncher;
yield* launcher.launchEditor({
editor: "vscode",
cwd: "C:\\workspace with spaces\\src\\index.ts:12:4",
});
}).pipe(
Effect.provide(
layerTest({
platform: "win32",
env: { PATH: binDir, PATHEXT: ".COM;.EXE;.BAT;.CMD" },
resolveExecutable: (command) =>
command === "code" ? "C:\\Program Files\\Microsoft VS Code\\bin\\code.CMD" : command,
onSpawn: (command) => {
spawned = command;
},
}),
),
);
assert.ok(spawned);
assert.equal(
spawned.command,
[
'^"C:\\Program^ Files\\Microsoft^ VS^ Code\\bin\\code.CMD^"',
'^"--goto^"',
'^"C:\\workspace^ with^ spaces\\src\\index.ts:12:4^"',
].join(" "),
);
assert.deepEqual(spawned.args, []);
assert.equal(spawned.options.shell, true);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
for (const platform of ["darwin", "linux"] as const) {
it.effect.skipIf(windowsHost)(`launches Cursor in classic IDE mode on ${platform}`, () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
const cursorPath = path.join(binDir, "cursor");
yield* fileSystem.writeFileString(cursorPath, "#!/bin/sh\n");
yield* fileSystem.chmod(cursorPath, 0o755);
const spawned: ChildProcess.StandardCommand[] = [];
yield* Effect.gen(function* () {
const launcher = yield* ExternalLauncher.ExternalLauncher;
for (const cwd of [
"/workspace with spaces",
"/workspace with spaces/src/index.ts",
"/workspace with spaces/src/index.ts:12",
"/workspace with spaces/src/index.ts:12:4",
]) {
yield* launcher.launchEditor({ editor: "cursor", cwd });
}
}).pipe(
Effect.provide(
layerTest({
platform,
env: { PATH: binDir },
onSpawn: (command) => spawned.push(command),
}),
),
);
assert.deepEqual(
spawned.map((command) => ({ command: command.command, args: command.args })),
[
{ command: "cursor", args: ["--classic", "/workspace with spaces"] },
{ command: "cursor", args: ["--classic", "/workspace with spaces/src/index.ts"] },
{
command: "cursor",
args: ["--classic", "--goto", "/workspace with spaces/src/index.ts:12"],
},
{
command: "cursor",
args: ["--classic", "--goto", "/workspace with spaces/src/index.ts:12:4"],
},
],
);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
}
it.effect("launches Cursor in classic IDE mode through the Windows command shim", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
yield* fileSystem.writeFileString(path.join(binDir, "cursor.CMD"), "@echo off\r\n");
let spawned: ChildProcess.StandardCommand | undefined;
yield* Effect.gen(function* () {
const launcher = yield* ExternalLauncher.ExternalLauncher;
yield* launcher.launchEditor({
editor: "cursor",
cwd: "C:\\workspace with spaces\\src\\index.ts:12:4",
});
}).pipe(
Effect.provide(
layerTest({
platform: "win32",
env: { PATH: binDir, PATHEXT: ".COM;.EXE;.BAT;.CMD" },
resolveExecutable: (command) =>
command === "cursor" ? "C:\\Program Files\\Cursor\\bin\\cursor.CMD" : command,
onSpawn: (command) => {
spawned = command;
},
}),
),
);
assert.ok(spawned);
assert.equal(
spawned.command,
[
'^"C:\\Program^ Files\\Cursor\\bin\\cursor.CMD^"',
'^"--classic^"',
'^"--goto^"',
'^"C:\\workspace^ with^ spaces\\src\\index.ts:12:4^"',
].join(" "),
);
assert.deepEqual(spawned.args, []);
assert.equal(spawned.options.shell, true);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect.skipIf(windowsHost)("reveals a file in Finder with open -R on macOS", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
const openPath = path.join(binDir, "open");
yield* fileSystem.writeFileString(openPath, "#!/bin/sh\n");
yield* fileSystem.chmod(openPath, 0o755);
let spawned: ChildProcess.StandardCommand | undefined;
yield* Effect.gen(function* () {
const launcher = yield* ExternalLauncher.ExternalLauncher;
yield* launcher.launchEditor({
editor: "file-manager",
cwd: "/workspace/media/linux-mini-v2.mp4",
reveal: true,
});
}).pipe(
Effect.provide(
layerTest({
platform: "darwin",
env: { PATH: binDir },
onSpawn: (command) => {
spawned = command;
},
}),
),
);
assert.ok(spawned);
assert.equal(spawned.command, "open");
assert.deepEqual(spawned.args, ["-R", "/workspace/media/linux-mini-v2.mp4"]);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect("reveals a file in File Explorer through PowerShell on Windows", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
yield* fileSystem.writeFileString(path.join(binDir, "explorer.CMD"), "@echo off\r\n");
// resolvePowerShellPath builds `${SYSTEMROOT}\System32\...` with Windows
// separators, which on the posix test filesystem is one file name.
const systemRoot = path.join(binDir, "system-root");
const powerShellPath = `${systemRoot}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;
yield* fileSystem.makeDirectory(path.dirname(powerShellPath), { recursive: true });
yield* fileSystem.writeFileString(powerShellPath, "");
let spawned: ChildProcess.StandardCommand | undefined;
const kind = yield* Effect.gen(function* () {
const launcher = yield* ExternalLauncher.ExternalLauncher;
yield* launcher.launchEditor({
editor: "file-manager",
// Web file links normalize separators even when the server runs on
// Windows. Explorer's `/select` switch requires Windows separators.
cwd: "C:/workspace with spaces/media/author's clip.mp4",
reveal: true,
});
return yield* launcher.resolveFileManagerRevealKind();
}).pipe(
Effect.provide(
layerTest({
platform: "win32",
env: { PATH: binDir, PATHEXT: ".COM;.EXE;.BAT;.CMD", SYSTEMROOT: systemRoot },
onSpawn: (command) => {
spawned = command;
},
}),
),
);
assert.equal(kind, "file-explorer");
assert.ok(spawned);
assert.equal(spawned.command, powerShellPath);
assert.deepEqual(spawned.args.slice(0, -1), [
"-NoProfile",
"-NonInteractive",
"-ExecutionPolicy",
"Bypass",
"-EncodedCommand",
]);
const encodedCommand = spawned.args[spawned.args.length - 1] ?? "";
const decodedCommand = Buffer.from(encodedCommand, "base64").toString("utf16le");
// explorer.exe expects `/select,"<path>"` with only the path quoted;
// PowerShell 5.1's Start-Process passes the argument string verbatim.
assert.equal(
decodedCommand,
"$ProgressPreference = 'SilentlyContinue'; Start-Process 'explorer.exe' -ArgumentList ('/select,\"' + 'C:\\workspace with spaces\\media\\author''s clip.mp4' + '\"')",
);
assert.equal(spawned.options.shell, false);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
// Real-chain smoke check for the Explorer selection contract: runs the exact
// PowerShell source the reveal launch encodes, against a stub that records
// the raw argument tail it receives, and asserts a spaced path arrives as the
// single `/select,"<path>"` switch. Mock argv assertions cannot prove this —
// only Windows' own PowerShell -> CreateProcess quoting chain can, so the
// test runs only where that chain exists.
// oxlint-disable-next-line t3code/no-global-process-runtime -- the skip decision needs the real host platform, outside any Effect runtime.
it.skipIf(process.platform !== "win32")(
"delivers the raw /select switch for spaced paths through real PowerShell",
{ timeout: 60_000 },
async () => {
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-reveal-smoke-"));
try {
const recorderPath = NodePath.join(tempDir, "recorder.cmd");
const outputPath = NodePath.join(tempDir, "argv.txt");
NodeFS.writeFileSync(recorderPath, `@echo off\r\n>"${outputPath}" echo(%*\r\n`);
const target = "C:/workspace with spaces/media/author's clip.mp4";
const explorerTarget = target.replaceAll("/", "\\");
const source = ExternalLauncher.buildFileExplorerRevealPowerShellSource(
recorderPath,
explorerTarget,
);
const powerShellPath = `${process.env.SYSTEMROOT ?? "C:\\Windows"}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;
NodeChildProcess.execFileSync(
powerShellPath,
[
"-NoProfile",
"-NonInteractive",
"-ExecutionPolicy",
"Bypass",
"-EncodedCommand",
Buffer.from(source, "utf16le").toString("base64"),
],
{ timeout: 30_000 },
);
// Start-Process returns before the recorder runs; wait for its output.
// The waits run outside the Effect runtime on purpose: the test
// exercises the real Windows process chain in real time.
// @effect-diagnostics-next-line globalTimers:off
const sleep = (millis: number) => new Promise((resolve) => setTimeout(resolve, millis));
// @effect-diagnostics-next-line globalDate:off
const deadline = Date.now() + 20_000;
// @effect-diagnostics-next-line globalDate:off
while (!NodeFS.existsSync(outputPath) && Date.now() < deadline) {
await sleep(100);
}
await sleep(200);
const recorded = NodeFS.readFileSync(outputPath, "utf8").trim();
assert.equal(recorded, `/select,"${explorerTarget}"`);
} finally {
NodeFS.rmSync(tempDir, { recursive: true, force: true });
}
},
);
it.effect("does not advertise reveal on Windows when PowerShell is missing", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
yield* fileSystem.writeFileString(path.join(binDir, "explorer.CMD"), "@echo off\r\n");
const result = yield* Effect.gen(function* () {
const launcher = yield* ExternalLauncher.ExternalLauncher;
return {
kind: yield* launcher.resolveFileManagerRevealKind(),
editors: yield* launcher.resolveAvailableEditors(),
};
}).pipe(
Effect.provide(
layerTest({
platform: "win32",
env: {
PATH: binDir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
SYSTEMROOT: path.join(binDir, "missing-system-root"),
},
}),
),
);
// Plain "open in file manager" still works through explorer; only the
// reveal capability, which launches PowerShell, must stay hidden.
assert.equal(result.editors.includes("file-manager"), true);
assert.isUndefined(result.kind);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect.skipIf(windowsHost)(
"reveals a WSL file in Windows File Explorer through its UNC path",
() =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
for (const name of ["explorer.exe", "powershell.exe", "xdg-open"]) {
const filePath = path.join(binDir, name);
yield* fileSystem.writeFileString(filePath, "#!/bin/sh\n");
yield* fileSystem.chmod(filePath, 0o755);
}
let spawned: ChildProcess.StandardCommand | undefined;
const result = yield* Effect.gen(function* () {
const launcher = yield* ExternalLauncher.ExternalLauncher;
const kind = yield* launcher.resolveFileManagerRevealKind();
const editors = yield* launcher.resolveAvailableEditors();
yield* launcher.launchEditor({
editor: "file-manager",
cwd: "/home/t3/workspace/media/clip.mp4",
reveal: true,
});
return { kind, editors };
}).pipe(
Effect.provide(
layerTest({
platform: "linux",
env: {
PATH: binDir,
WSL_DISTRO_NAME: "Ubuntu-24.04",
WSL_INTEROP: "/run/WSL/1_interop",
},
onSpawn: (command) => {
spawned = command;
},
}),
),
);
assert.equal(result.kind, "file-explorer");
assert.equal(result.editors.includes("file-manager"), true);
assert.ok(spawned);
// The reveal routes through interop PowerShell so Explorer receives its
// raw `/select,"<path>"` switch even for spaced paths.
assert.equal(spawned.command, "powershell.exe");
const encodedCommand = spawned.args[spawned.args.length - 1] ?? "";
const decodedCommand = Buffer.from(encodedCommand, "base64").toString("utf16le");
assert.equal(
decodedCommand,
"$ProgressPreference = 'SilentlyContinue'; Start-Process 'explorer.exe' -ArgumentList ('/select,\"' + '\\\\wsl.localhost\\Ubuntu-24.04\\home\\t3\\workspace\\media\\clip.mp4' + '\"')",
);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect.skipIf(windowsHost)(
"does not advertise reveal from WSL when interop PowerShell is missing",
() =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
const explorerPath = path.join(binDir, "explorer.exe");
yield* fileSystem.writeFileString(explorerPath, "");
yield* fileSystem.chmod(explorerPath, 0o755);
const result = yield* Effect.gen(function* () {
const launcher = yield* ExternalLauncher.ExternalLauncher;
return {
kind: yield* launcher.resolveFileManagerRevealKind(),
editors: yield* launcher.resolveAvailableEditors(),
};
}).pipe(
Effect.provide(
layerTest({
platform: "linux",
env: {
PATH: binDir,
WSL_DISTRO_NAME: "Ubuntu-24.04",
WSL_INTEROP: "/run/WSL/1_interop",
},
}),
),
);
assert.equal(result.editors.includes("file-manager"), true);
assert.isUndefined(result.kind);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
// When interop PowerShell is missing the capability advertises the Linux
// "files" kind (or nothing), so the reveal must open the Linux file manager
// the label promised even though plain open still prefers File Explorer.
it.effect.skipIf(windowsHost)(
"reveals through the Linux file manager when WSL lacks interop PowerShell",
() =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
for (const name of ["explorer.exe", "xdg-open", "xdg-mime"]) {
const filePath = path.join(binDir, name);
yield* fileSystem.writeFileString(filePath, "#!/bin/sh\n");
yield* fileSystem.chmod(filePath, 0o755);
}
const spawnedCommands: ChildProcess.StandardCommand[] = [];
const kind = yield* Effect.gen(function* () {
const launcher = yield* ExternalLauncher.ExternalLauncher;
const revealKind = yield* launcher.resolveFileManagerRevealKind();
yield* launcher.launchEditor({
editor: "file-manager",
cwd: "/home/t3/workspace/media/clip.mp4",
reveal: true,
});
return revealKind;
}).pipe(
Effect.provide(
layerTest({
platform: "linux",
env: {
PATH: binDir,
WSL_DISTRO_NAME: "Ubuntu-24.04",
WSL_INTEROP: "/run/WSL/1_interop",
DISPLAY: ":0",
},
onSpawn: (command) => {
spawnedCommands.push(command);
},
spawnResult: (command) =>
command.command === "xdg-mime"
? { stdout: "org.gnome.Nautilus.desktop\n" }
: undefined,
}),
),
);
assert.equal(kind, "files");
const launch = spawnedCommands.find((command) => command.command === "xdg-open");
assert.ok(launch);
assert.deepEqual(launch.args, ["/home/t3/workspace/media"]);
assert.isUndefined(spawnedCommands.find((command) => command.command === "explorer.exe"));
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
// Interop can exist without `explorer.exe` on PATH (appendWindowsPath=false)
// while WSLg still provides a working Linux file manager; the host must keep
// the Linux open/reveal path instead of losing the editor entirely.
it.effect.skipIf(windowsHost)(
"falls back to the Linux file manager when WSL lacks the Explorer bridge",
() =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
for (const name of ["xdg-open", "xdg-mime"]) {
const filePath = path.join(binDir, name);
yield* fileSystem.writeFileString(filePath, "#!/bin/sh\n");
yield* fileSystem.chmod(filePath, 0o755);
}
const spawnedCommands: ChildProcess.StandardCommand[] = [];
const result = yield* Effect.gen(function* () {
const launcher = yield* ExternalLauncher.ExternalLauncher;
const editors = yield* launcher.resolveAvailableEditors();
const kind = yield* launcher.resolveFileManagerRevealKind();
yield* launcher.launchEditor({
editor: "file-manager",
cwd: "/home/t3/workspace/media/clip.mp4",
reveal: true,
});
return { editors, kind };
}).pipe(
Effect.provide(
layerTest({
platform: "linux",
env: {
PATH: binDir,
WSL_DISTRO_NAME: "Ubuntu-24.04",
WSL_INTEROP: "/run/WSL/1_interop",
DISPLAY: ":0",
},
onSpawn: (command) => {
spawnedCommands.push(command);
},
spawnResult: (command) =>
command.command === "xdg-mime"
? { stdout: "org.gnome.Nautilus.desktop\n" }
: undefined,
}),
),
);
assert.equal(result.editors.includes("file-manager"), true);
assert.equal(result.kind, "files");
const launch = spawnedCommands.find((command) => command.command === "xdg-open");
assert.ok(launch);
assert.deepEqual(launch.args, ["/home/t3/workspace/media"]);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect.skipIf(windowsHost)(
"falls back to opening the containing directory for WSL paths Explorer cannot select",
() =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
for (const name of ["explorer.exe", "powershell.exe"]) {
const filePath = path.join(binDir, name);
yield* fileSystem.writeFileString(filePath, "#!/bin/sh\n");
yield* fileSystem.chmod(filePath, 0o755);
}
let spawned: ChildProcess.StandardCommand | undefined;
yield* Effect.gen(function* () {
const launcher = yield* ExternalLauncher.ExternalLauncher;
yield* launcher.launchEditor({
editor: "file-manager",
cwd: '/home/t3/work "quoted"/clip.mp4',
reveal: true,
});
}).pipe(
Effect.provide(
layerTest({
platform: "linux",
env: {
PATH: binDir,
WSL_DISTRO_NAME: "Ubuntu-24.04",
WSL_INTEROP: "/run/WSL/1_interop",
},
onSpawn: (command) => {
spawned = command;
},
}),
),
);
// Explorer's raw switch cannot express a double quote, so the launch
// opens the parent directory instead of misparsing a /select argument.
assert.ok(spawned);
assert.equal(spawned.command, "explorer.exe");
assert.deepEqual(spawned.args, ['\\\\wsl.localhost\\Ubuntu-24.04\\home\\t3\\work "quoted"']);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect.skipIf(windowsHost)("reveals by opening the containing directory on Linux", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
for (const name of ["xdg-open", "xdg-mime"]) {
const filePath = path.join(binDir, name);
yield* fileSystem.writeFileString(filePath, "#!/bin/sh\n");
yield* fileSystem.chmod(filePath, 0o755);
}
const spawnedCommands: ChildProcess.StandardCommand[] = [];
yield* Effect.gen(function* () {
const launcher = yield* ExternalLauncher.ExternalLauncher;
yield* launcher.launchEditor({
editor: "file-manager",
cwd: "/workspace/media/linux-mini-v2.mp4",
reveal: true,
});
}).pipe(
Effect.provide(
layerTest({
platform: "linux",
env: { PATH: binDir, DISPLAY: ":0" },
onSpawn: (command) => {
spawnedCommands.push(command);
},
spawnResult: (command) =>
command.command === "xdg-mime" ? { stdout: "org.gnome.Nautilus.desktop\n" } : undefined,
}),
),
);
const spawned = spawnedCommands.find((command) => command.command === "xdg-open");
assert.ok(spawned);
assert.deepEqual(spawned.args, ["/workspace/media"]);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect.skipIf(windowsHost)(
"does not advertise a Linux file manager without a graphical session",
() =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
const xdgOpenPath = path.join(binDir, "xdg-open");
yield* fileSystem.writeFileString(xdgOpenPath, "#!/bin/sh\n");
yield* fileSystem.chmod(xdgOpenPath, 0o755);
const editors = yield* Effect.gen(function* () {
const launcher = yield* ExternalLauncher.ExternalLauncher;
return yield* launcher.resolveAvailableEditors();
}).pipe(Effect.provide(layerTest({ platform: "linux", env: { PATH: binDir } })));
assert.equal(editors.includes("file-manager"), false);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect.skipIf(windowsHost)(
"advertises a Linux file manager when a directory handler is installed",
() =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
for (const name of ["xdg-open", "xdg-mime"]) {
const filePath = path.join(binDir, name);
yield* fileSystem.writeFileString(filePath, "#!/bin/sh\n");
yield* fileSystem.chmod(filePath, 0o755);
}
let probe: ChildProcess.StandardCommand | undefined;
const editors = yield* Effect.gen(function* () {
const launcher = yield* ExternalLauncher.ExternalLauncher;
return yield* launcher.resolveAvailableEditors();
}).pipe(
Effect.provide(
layerTest({
platform: "linux",
env: { PATH: binDir, DISPLAY: ":0" },
onSpawn: (command) => {
probe = command;
},
spawnResult: (command) =>
command.command === "xdg-mime"
? { stdout: "org.gnome.Nautilus.desktop\n" }
: undefined,
}),
),
);
assert.equal(editors.includes("file-manager"), true);
assert.ok(probe);
assert.equal(probe.command, "xdg-mime");
assert.deepEqual(probe.args, ["query", "default", "inode/directory"]);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
// `xdg-open` with a display variable but no `inode/directory` handler exits
// nonzero after the launch has already detached: without this gate the server
// advertises a reveal that is a silent no-op.
it.effect.skipIf(windowsHost)(
"does not advertise a Linux file manager without a directory handler",
() =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
for (const name of ["xdg-open", "xdg-mime"]) {
const filePath = path.join(binDir, name);
yield* fileSystem.writeFileString(filePath, "#!/bin/sh\n");
yield* fileSystem.chmod(filePath, 0o755);
}
const editors = yield* Effect.gen(function* () {
const launcher = yield* ExternalLauncher.ExternalLauncher;
return yield* launcher.resolveAvailableEditors();
}).pipe(
Effect.provide(
layerTest({
platform: "linux",
env: { PATH: binDir, DISPLAY: ":0" },
spawnResult: (command) => (command.command === "xdg-mime" ? { stdout: "" } : undefined),
}),
),
);
assert.equal(editors.includes("file-manager"), false);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect.skipIf(windowsHost)(
"does not advertise a Linux file manager when the handler query fails",
() =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
for (const name of ["xdg-open", "xdg-mime"]) {
const filePath = path.join(binDir, name);
yield* fileSystem.writeFileString(filePath, "#!/bin/sh\n");
yield* fileSystem.chmod(filePath, 0o755);
}
const editors = yield* Effect.gen(function* () {
const launcher = yield* ExternalLauncher.ExternalLauncher;
return yield* launcher.resolveAvailableEditors();
}).pipe(
Effect.provide(
layerTest({
platform: "linux",
env: { PATH: binDir, DISPLAY: ":0" },
spawnResult: (command) =>
command.command === "xdg-mime"
? { exitCode: 47, stdout: "org.gnome.Nautilus.desktop\n" }
: undefined,
}),
),
);
assert.equal(editors.includes("file-manager"), false);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
// The handler probe carries its own timeout because the editor scan's outer
// timeout in server.getConfig degrades to an EMPTY editor list: a wedged
// xdg-mime must cost only the file manager, never the other editors. Runs on
// the live clock so the probe's real timeout fires.
it.live.skipIf(windowsHost)("a stalled handler probe drops only the file manager", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
for (const name of ["xdg-open", "xdg-mime", "code"]) {
const filePath = path.join(binDir, name);
yield* fileSystem.writeFileString(filePath, "#!/bin/sh\n");
yield* fileSystem.chmod(filePath, 0o755);
}
const editors = yield* Effect.gen(function* () {
const launcher = yield* ExternalLauncher.ExternalLauncher;
return yield* launcher.resolveAvailableEditors();
}).pipe(
Effect.provide(
layerTest({
platform: "linux",
env: { PATH: binDir, DISPLAY: ":0" },
spawnResult: (command) => (command.command === "xdg-mime" ? { stall: true } : undefined),
}),
),
);
assert.equal(editors.includes("vscode"), true);
assert.equal(editors.includes("file-manager"), false);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect.skipIf(windowsHost)(
"does not advertise a Linux file manager when xdg-mime is missing",
() =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
const xdgOpenPath = path.join(binDir, "xdg-open");
yield* fileSystem.writeFileString(xdgOpenPath, "#!/bin/sh\n");
yield* fileSystem.chmod(xdgOpenPath, 0o755);
const editors = yield* Effect.gen(function* () {
const launcher = yield* ExternalLauncher.ExternalLauncher;
return yield* launcher.resolveAvailableEditors();
}).pipe(
Effect.provide(layerTest({ platform: "linux", env: { PATH: binDir, DISPLAY: ":0" } })),
);
assert.equal(editors.includes("file-manager"), false);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect("discovers editors through the service API", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
yield* fileSystem.writeFileString(path.join(binDir, "code.CMD"), "@echo off\r\n");
yield* fileSystem.writeFileString(path.join(binDir, "explorer.CMD"), "@echo off\r\n");
const editors = yield* Effect.gen(function* () {
const launcher = yield* ExternalLauncher.ExternalLauncher;
return yield* launcher.resolveAvailableEditors();
}).pipe(
Effect.provide(
layerTest({
platform: "win32",
env: { PATH: binDir, PATHEXT: ".COM;.EXE;.BAT;.CMD" },
}),
),
);
assert.equal(editors.includes("vscode"), true);
assert.equal(editors.includes("file-manager"), true);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
for (const { platform, installPath, editor, args } of [
{
platform: "darwin",
installPath: "Applications/Antigravity IDE.app/Contents/Resources/app/bin/antigravity-ide",
editor: "antigravity",
args: ["--goto", "/workspace with spaces/file.ts:12:4"],
},
{
platform: "linux",
installPath: ".local/bin/antigravity-ide",
editor: "antigravity",
args: ["--goto", "/workspace with spaces/file.ts:12:4"],
},
{
platform: "darwin",
installPath: "Applications/Cursor.app/Contents/Resources/app/bin/code",
editor: "cursor",
args: ["--classic", "--goto", "/workspace with spaces/file.ts:12:4"],
},
{
platform: "darwin",
installPath: "Applications/Kiro.app/Contents/Resources/app/bin/code",
editor: "kiro",
args: ["--goto", "/workspace with spaces/file.ts:12:4"],
},
{
platform: "darwin",
installPath: "Applications/WebStorm.app/Contents/MacOS/webstorm",
editor: "webstorm",
args: ["--line", "12", "--column", "4", "/workspace with spaces/file.ts"],
},
{
platform: "darwin",
installPath: "Applications/Zed.app/Contents/MacOS/cli",
editor: "zed",
args: ["/workspace with spaces/file.ts:12:4"],
},
{
platform: "win32",
installPath: "Programs/Cursor/resources/app/bin/cursor.cmd",
editor: "cursor",
args: ['^"--classic^"', '^"--goto^"', '^"/workspace^ with^ spaces/file.ts:12:4^"'],
},
{
platform: "win32",
installPath: "Programs/Microsoft VS Code/bin/code.cmd",
editor: "vscode",
args: ['^"--goto^"', '^"/workspace^ with^ spaces/file.ts:12:4^"'],
},
{
platform: "win32",
installPath: "Programs/JetBrains/WebStorm 2026.2/bin/webstorm64.exe",
editor: "webstorm",
args: ["--line", "12", "--column", "4", "/workspace with spaces/file.ts"],
},
{
platform: "win32",
installPath: "Programs/WebStorm/bin/webstorm64.exe",
editor: "webstorm",
args: ["--line", "12", "--column", "4", "/workspace with spaces/file.ts"],
},
{
platform: "win32",
installPath: "Programs/Zed/bin/zed.exe",
editor: "zed",
args: ["/workspace with spaces/file.ts:12:4"],
},
{
platform: "linux",
installPath: ".local/share/JetBrains/Toolbox/scripts/idea",
editor: "idea",
args: ["--line", "12", "--column", "4", "/workspace with spaces/file.ts"],
},
{
platform: "linux",
installPath: ".local/bin/zed",
editor: "zed",
args: ["/workspace with spaces/file.ts:12:4"],
},
] as const) {
it.effect.skipIf(windowsHost && platform !== "win32")(
`discovers and launches ${editor} outside PATH on ${platform}`,
() =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editor installs-" });
const executable = path.join(home, installPath);
yield* fs.makeDirectory(path.dirname(executable), { recursive: true });
yield* fs.writeFileString(executable, "#!/bin/sh\n");
yield* fs.chmod(executable, 0o755);
let spawned: ChildProcess.StandardCommand | undefined;
yield* Effect.gen(function* () {
const launcher = yield* ExternalLauncher.ExternalLauncher;
assert.include(yield* launcher.resolveAvailableEditors(), editor);
yield* launcher.launchEditor({ editor, cwd: "/workspace with spaces/file.ts:12:4" });
}).pipe(
Effect.provide(
layerTest({
platform,
env: { HOME: home, LOCALAPPDATA: home, PATH: path.join(home, "empty") },
onSpawn: (command) => {
spawned = command;
},
}),
),
);
assert.ok(spawned);
const shim = executable.endsWith(".cmd");
assert.equal(
spawned.command,
shim ? [`^"${executable.replaceAll(" ", "^ ")}^"`, ...args].join(" ") : executable,
);
assert.deepEqual(spawned.args, shim ? [] : args);
assert.equal(spawned.options.shell, shim);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
}
for (const cwd of ["/workspace with spaces/", "/workspace with spaces/file.ts:12:4"]) {
it.effect.skipIf(windowsHost)(
`opens ${cwd} with the macOS Zed bundle when another zed is on PATH`,
() =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-zed-collision-" });
const executable = path.join(home, "Applications/Zed.app/Contents/MacOS/cli");
const binDir = path.join(home, "zfs/bin");
yield* fs.makeDirectory(path.dirname(executable), { recursive: true });
yield* fs.makeDirectory(binDir, { recursive: true });
for (const command of [executable, path.join(binDir, "zed")]) {
yield* fs.writeFileString(command, "#!/bin/sh\n");
yield* fs.chmod(command, 0o755);
}
let spawned: ChildProcess.StandardCommand | undefined;
yield* Effect.gen(function* () {
const launcher = yield* ExternalLauncher.ExternalLauncher;
assert.include(yield* launcher.resolveAvailableEditors(), "zed");
yield* launcher.launchEditor({ editor: "zed", cwd });
}).pipe(
Effect.provide(
layerTest({
platform: "darwin",
env: { HOME: home, PATH: binDir },
onSpawn: (command) => {
spawned = command;
},
}),
),
);
assert.ok(spawned);
assert.equal(spawned.command, executable);
assert.deepEqual(spawned.args, [cwd]);
assert.equal(spawned.options.shell, false);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
}
// JetBrains Toolbox names its bundles after the app and the installed version
// (`IntelliJ IDEA 2026.1.4.app`), so the darwin branch has to list the
// Applications directories the way the win32 branch does instead of probing
// exact `<name>.app` paths. The fixtures only use the mocked platform and a
// temp directory, so this runs on a Windows host too.
it.effect.each([
{ editor: "webstorm", installPath: "Applications/WebStorm 2026.2.app/Contents/MacOS/webstorm" },
{ editor: "idea", installPath: "Applications/IntelliJ IDEA 2026.1.4.app/Contents/MacOS/idea" },
] as const)(
"discovers and launches $editor from a versioned macOS bundle",
({ editor, installPath }) =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editor-versioned-" });
const executable = path.join(home, installPath);
yield* fs.makeDirectory(path.dirname(executable), { recursive: true });
yield* fs.writeFileString(executable, "#!/bin/sh\n");
yield* fs.chmod(executable, 0o755);
let spawned: ChildProcess.StandardCommand | undefined;
yield* Effect.gen(function* () {
const launcher = yield* ExternalLauncher.ExternalLauncher;
assert.include(yield* launcher.resolveAvailableEditors(), editor);
yield* launcher.launchEditor({ editor, cwd: "/workspace with spaces/file.ts:12:4" });
}).pipe(
Effect.provide(
layerTest({
platform: "darwin",
env: { HOME: home, PATH: path.join(home, "empty") },
onSpawn: (command) => {
spawned = command;
},
}),
),
);
assert.ok(spawned);
assert.equal(spawned.command, executable);
assert.deepEqual(spawned.args, [
"--line",
"12",
"--column",
"4",
"/workspace with spaces/file.ts",
]);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
// An app whose name merely starts with the same letters is a different IDE, and
// an exact `<name>.app` bundle keeps resolving the way it did before.
it.effect("matches macOS bundles on the name boundary only", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const unrelatedHome = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editor-unrelated-" });
const unrelated = path.join(
unrelatedHome,
"Applications/WebStormHelper.app/Contents/MacOS/webstorm",
);
yield* fs.makeDirectory(path.dirname(unrelated), { recursive: true });
yield* fs.writeFileString(unrelated, "#!/bin/sh\n");
yield* fs.chmod(unrelated, 0o755);
const editorsFor = (home: string) =>
Effect.gen(function* () {
const launcher = yield* ExternalLauncher.ExternalLauncher;
return yield* launcher.resolveAvailableEditors();
}).pipe(
Effect.provide(
layerTest({ platform: "darwin", env: { HOME: home, PATH: path.join(home, "bin") } }),
),
);
assert.notInclude(yield* editorsFor(unrelatedHome), "webstorm");
const exactHome = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editor-exact-" });
const exact = path.join(exactHome, "Applications/WebStorm.app/Contents/MacOS/webstorm");
yield* fs.makeDirectory(path.dirname(exact), { recursive: true });
yield* fs.writeFileString(exact, "#!/bin/sh\n");
yield* fs.chmod(exact, 0o755);
assert.include(yield* editorsFor(exactHome), "webstorm");
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
// `Visual Studio Code - Insiders.app` starts with the stable VS Code install
// name, so a plain prefix match let the stable editor resolve to the Insiders
// bundle. Insiders has to stay reachable under its own name, stable VS Code has
// to stay unresolved.
it.effect("keeps the macOS VS Code Insiders bundle out of stable VS Code", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editor-insiders-" });
// The real Insiders bundle ships both `code-insiders` and `code`.
const bin = path.join(
home,
"Applications/Visual Studio Code - Insiders.app/Contents/Resources/app/bin",
);
yield* fs.makeDirectory(bin, { recursive: true });
for (const name of ["code", "code-insiders"]) {
yield* fs.writeFileString(path.join(bin, name), "#!/bin/sh\n");
yield* fs.chmod(path.join(bin, name), 0o755);
}
let spawned: ChildProcess.StandardCommand | undefined;
const editors = yield* Effect.gen(function* () {
const launcher = yield* ExternalLauncher.ExternalLauncher;
const available = yield* launcher.resolveAvailableEditors();
yield* launcher.launchEditor({ editor: "vscode-insiders", cwd: "/workspace/file.ts" });
return available;
}).pipe(
Effect.provide(
layerTest({
platform: "darwin",
env: { HOME: home, PATH: path.join(home, "empty") },
onSpawn: (command) => {
spawned = command;
},
}),
),
);
assert.notInclude(editors, "vscode");
assert.include(editors, "vscode-insiders");
assert.equal(spawned?.command, path.join(bin, "code-insiders"));
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
// `agy` is the standalone Antigravity CLI, which installs to ~/.local/bin on
// macOS and Linux and to its own bin folder on Windows. It is not the IDE.
for (const { platform, installPath, onPath } of [
{ platform: "darwin", installPath: ".local/bin/agy", onPath: true },
{ platform: "linux", installPath: ".local/bin/agy", onPath: false },
{ platform: "win32", installPath: "agy/bin/agy.cmd", onPath: true },
] as const) {
it.effect.skipIf(windowsHost && platform !== "win32")(
`does not report the agy CLI as the Antigravity IDE on ${platform}`,
() =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-cli-" });
const executable = path.join(home, installPath);
yield* fs.makeDirectory(path.dirname(executable), { recursive: true });
yield* fs.writeFileString(executable, "#!/bin/sh\n");
yield* fs.chmod(executable, 0o755);
const editors = yield* Effect.gen(function* () {
const launcher = yield* ExternalLauncher.ExternalLauncher;
return yield* launcher.resolveAvailableEditors();
}).pipe(
Effect.provide(
layerTest({
platform,
env: {
HOME: home,
LOCALAPPDATA: home,
PATH: onPath ? path.dirname(executable) : path.join(home, "empty"),
PATHEXT: ".COM;.EXE;.BAT;.CMD",
},
}),
),
);
assert.notInclude(editors, "antigravity");
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
}
it.effect.skipIf(windowsHost)("ignores unusable app bundles and keeps PATH launchers first", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editor-priority-" });
const executable = path.join(home, "Applications/Cursor.app/Contents/Resources/app/bin/code");
const env = { HOME: home, PATH: path.join(home, "bin") };
const discover = Effect.gen(function* () {
const launcher = yield* ExternalLauncher.ExternalLauncher;
return yield* launcher.resolveAvailableEditors();
});
const before = yield* discover.pipe(Effect.provide(layerTest({ platform: "darwin", env })));
yield* fs.makeDirectory(executable, { recursive: true });
assert.deepEqual(
yield* discover.pipe(Effect.provide(layerTest({ platform: "darwin", env }))),
before,
);
yield* fs.remove(executable, { recursive: true });
yield* fs.writeFileString(executable, "#!/bin/sh\n");
yield* fs.chmod(executable, 0o644);
assert.deepEqual(
yield* discover.pipe(Effect.provide(layerTest({ platform: "darwin", env }))),
before,
);
yield* fs.chmod(executable, 0o755);
yield* fs.makeDirectory(env.PATH);
yield* fs.writeFileString(path.join(env.PATH, "cursor"), "#!/bin/sh\n");
yield* fs.chmod(path.join(env.PATH, "cursor"), 0o755);
let spawned: ChildProcess.StandardCommand | undefined;
yield* Effect.gen(function* () {
const launcher = yield* ExternalLauncher.ExternalLauncher;
yield* launcher.launchEditor({ editor: "cursor", cwd: "/workspace" });
}).pipe(
Effect.provide(
layerTest({
platform: "darwin",
env: { ...env, PATH: `${env.PATH}:/usr/bin` },
onSpawn: (command) => {
spawned = command;
},
}),
),
);
assert.equal(spawned?.command, "cursor");
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect("memoizes editor discovery and refreshes after the cache window", () => {
let statCalls = 0;
const fileInfo = { type: "File" } as FileSystem.File.Info;
const layerLauncher = ExternalLauncher.layer.pipe(
Layer.provide(
Layer.mergeAll(
FileSystem.layerNoop({
stat: () =>
Effect.sync(() => {
statCalls += 1;
return fileInfo;
}),
}),
Path.layer,
Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() => Effect.sync(() => makeMockDetachedHandle())),
),
),
),
);
return Effect.gen(function* () {
const launcher = yield* ExternalLauncher.ExternalLauncher;
const first = yield* launcher.resolveAvailableEditors();
assert.equal(first.includes("vscode"), true);
const statCallsAfterFirstScan = statCalls;
assert.isAbove(statCallsAfterFirstScan, 0);
// Past the shared command-resolution cache TTL (30s) but within the
// discovery cache window: the memoized set is reused without any scan.
yield* TestClock.adjust("31 seconds");
const second = yield* launcher.resolveAvailableEditors();
assert.deepEqual([...second], [...first]);
assert.equal(statCalls, statCallsAfterFirstScan);
// Past the discovery cache window the next call rescans.
yield* TestClock.adjust("30 seconds");
yield* launcher.resolveAvailableEditors();
assert.isAbove(statCalls, statCallsAfterFirstScan);
}).pipe(
Effect.provide(
Layer.mergeAll(
layerLauncher,
Layer.succeed(HostProcess.Platform, "win32"),
ConfigProvider.layer(
ConfigProvider.fromEnv({
env: {
PATH: "C:\\t3-editor-discovery-cache-test",
PATHEXT: ".COM;.EXE;.BAT;.CMD",
},
}),
),
TestClock.layer(),
),
),
);
});
// Connects run discovery under a timeout and may disconnect mid-scan. Neither
// may cancel the scan: on a busy host every connect would time out partway
// through, cache nothing, and leave every client without editors.
it.effect("keeps scanning after the caller is interrupted and shares that scan", () => {
const fileInfo = { type: "File" } as FileSystem.File.Info;
const release = Deferred.makeUnsafe<void>();
let parkedStats = 0;
const layerLauncher = ExternalLauncher.layer.pipe(
Layer.provide(
Layer.mergeAll(
FileSystem.layerNoop({
// Scans park inside `stat` until released, so the interrupt lands
// while discovery is in flight.
stat: () =>
Effect.gen(function* () {
if (!Deferred.isDoneUnsafe(release)) {
parkedStats += 1;
yield* Deferred.await(release);
}
return fileInfo;
}),
}),
Path.layer,
Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() => Effect.sync(() => makeMockDetachedHandle())),
),
),
),
);
return Effect.gen(function* () {
const launcher = yield* ExternalLauncher.ExternalLauncher;
const interrupted = yield* Effect.forkChild(launcher.resolveAvailableEditors());
yield* Effect.yieldNow;
yield* Fiber.interrupt(interrupted);
// The next connect joins the running scan instead of starting its own.
const next = yield* Effect.forkChild(launcher.resolveAvailableEditors());
yield* Effect.yieldNow;
assert.equal(parkedStats, 1);
yield* Deferred.succeed(release, undefined);
const editors = yield* Fiber.join(next);
assert.equal(editors.includes("vscode"), true);
}).pipe(
Effect.provide(
Layer.mergeAll(
layerLauncher,
Layer.succeed(HostProcess.Platform, "win32"),
ConfigProvider.layer(
ConfigProvider.fromEnv({
env: {
PATH: "C:\\t3-editor-discovery-interrupt-test",
PATHEXT: ".COM;.EXE;.BAT;.CMD",
},
}),
),
),
),
);
});
const launchWindowsShimEditor = (cwd: string) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
yield* fileSystem.writeFileString(path.join(binDir, "code.CMD"), "@echo off\r\n");
let spawned: ChildProcess.StandardCommand | undefined;
const exit = yield* Effect.gen(function* () {
const launcher = yield* ExternalLauncher.ExternalLauncher;
return yield* launcher.launchEditor({ editor: "vscode", cwd }).pipe(Effect.exit);
}).pipe(
Effect.provide(
layerTest({
platform: "win32",
env: { PATH: binDir, PATHEXT: ".COM;.EXE;.BAT;.CMD" },
resolveExecutable: (command) =>
command === "code" ? "C:\\Program Files\\Microsoft VS Code\\bin\\code.CMD" : command,
onSpawn: (command) => {
spawned = command;
},
}),
),
);
return { exit, spawned };
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer));
it.effect.each([
["CRLF", "C:\\workspace\\file.ts\r\ncalc.exe"],
["LF", "C:\\workspace\\file.ts\ncalc.exe"],
["double quote", 'C:\\workspace\\file.ts" & calc.exe & "'],
] as const)("does not start a Windows command shim for a path with a $0", ([, cwd]) =>
Effect.gen(function* () {
const { exit, spawned } = yield* launchWindowsShimEditor(cwd);
assert.equal(spawned, undefined);
assert.isTrue(Exit.isFailure(exit));
if (Exit.isFailure(exit)) {
assert.instanceOf(
Cause.squash(exit.cause),
ExternalLauncher.ExternalLauncherUnsupportedTargetError,
);
}
}),
);
it.effect("starts a Windows command shim for unicode paths with cmd metacharacters", () =>
Effect.gen(function* () {
const { exit, spawned } = yield* launchWindowsShimEditor(
"C:\\Users\\jö\\R&D (100%)\\naïve ^file!.ts:3:7",
);
assert.isTrue(Exit.isSuccess(exit));
assert.ok(spawned);
assert.equal(spawned.options.shell, true);
assert.deepEqual(spawned.args, []);
assert.isTrue(
spawned.command.endsWith(
' ^"--goto^" ^"C:\\Users\\jö\\R^&D^ ^(100^%^)\\naïve^ ^^file^!.ts:3:7^"',
),
);
}),
);
it.effect.skipIf(windowsHost)("passes line breaks through to editors started without a shell", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" });
const zed = path.join(binDir, "zed");
yield* fileSystem.writeFileString(zed, "#!/bin/sh\n");
yield* fileSystem.chmod(zed, 0o755);
let spawned: ChildProcess.StandardCommand | undefined;
yield* Effect.gen(function* () {
const launcher = yield* ExternalLauncher.ExternalLauncher;
yield* launcher.launchEditor({ editor: "zed", cwd: "/workspace/odd\nname.ts" });
}).pipe(
Effect.provide(
layerTest({
platform: "linux",
env: { PATH: binDir, HOME: binDir },
onSpawn: (command) => {
spawned = command;
},
}),
),
);
assert.ok(spawned);
assert.deepEqual(spawned.args, ["/workspace/odd\nname.ts"]);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect("rejects unknown editors through the service API", () =>
Effect.gen(function* () {
const launcher = yield* ExternalLauncher.ExternalLauncher;
const error = yield* launcher
.launchEditor({ editor: "missing-editor" as never, cwd: "/tmp/workspace" })
.pipe(Effect.flip);
assert.instanceOf(error, ExternalLauncher.ExternalLauncherUnknownEditorError);
assert.equal(error.editor, "missing-editor");
assert.equal(error.message, "Unknown editor: missing-editor");
}).pipe(Effect.provide(layerTest({ platform: "linux", env: { PATH: "" } }))),
);