Compare commits

...
Author SHA1 Message Date
Cursor Agent 7ec01e28bd Remove unused runtime parameter from plan helper functions 2026-03-31 07:44:40 +00:00
Julius Marminge 2ade03788b Refactor open service onto Effect-backed process spawning
- Add external opener support alongside browser/editor launches
- Remove the `open` dependency and cover platform behavior in tests
2026-03-31 00:31:41 -07:00
7 changed files with 1125 additions and 437 deletions

No files matched your search

-1
View File
@@ -29,7 +29,6 @@
"@pierre/diffs": "^1.1.0-beta.16",
"effect": "catalog:",
"node-pty": "^1.1.0",
"open": "^10.1.0",
"ws": "^8.18.0"
},
"devDependencies": {
+2
View File
@@ -51,6 +51,8 @@ const testLayer = Layer.mergeAll(
stopSignal: Effect.void,
} satisfies ServerShape),
Layer.succeed(Open, {
getAvailableEditors: Effect.succeed([]),
openExternal: () => Effect.void,
openBrowser: (_target: string) => Effect.void,
openInEditor: () => Effect.void,
} satisfies OpenShape),
+536 -247
View File
@@ -1,269 +1,558 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem";
import * as NodePath from "@effect/platform-node/NodePath";
import { assert, it } from "@effect/vitest";
import { assertSuccess } from "@effect/vitest/utils";
import { FileSystem, Path, Effect } from "effect";
import {
isCommandAvailable,
launchDetached,
resolveAvailableEditors,
resolveEditorLaunch,
} from "./open";
Deferred,
Effect,
Exit,
FileSystem,
Layer,
PlatformError,
Scope,
Sink,
Stream,
} from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
it.effect("returns commands for command-based editors", () =>
Effect.gen(function* () {
const antigravityLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "antigravity" },
"darwin",
);
assert.deepEqual(antigravityLaunch, {
command: "agy",
args: ["/tmp/workspace"],
});
import { makeOpenLayer, Open } from "./open";
const cursorLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "cursor" },
"darwin",
);
assert.deepEqual(cursorLaunch, {
command: "cursor",
args: ["/tmp/workspace"],
});
const encoder = new TextEncoder();
const vscodeLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "vscode" },
"darwin",
);
assert.deepEqual(vscodeLaunch, {
command: "code",
args: ["/tmp/workspace"],
});
interface SpawnCall {
readonly command: string;
readonly args: ReadonlyArray<string>;
readonly detached?: boolean | undefined;
readonly shell?: boolean | string | undefined;
readonly stdin?: unknown;
readonly stdout?: unknown;
readonly stderr?: unknown;
}
const vscodeInsidersLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "vscode-insiders" },
"darwin",
);
assert.deepEqual(vscodeInsidersLaunch, {
command: "code-insiders",
args: ["/tmp/workspace"],
});
function decodePowerShellCommand(encoded: string): string {
return Buffer.from(encoded, "base64").toString("utf16le");
}
const vscodiumLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "vscodium" },
"darwin",
);
assert.deepEqual(vscodiumLaunch, {
command: "codium",
args: ["/tmp/workspace"],
});
function platformSpawnError(message: string) {
return PlatformError.systemError({
_tag: "Unknown",
module: "ChildProcess",
method: "spawn",
description: message,
});
}
const zedLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "zed" },
"darwin",
function spawnerLayer(
calls: Array<SpawnCall>,
handler: (call: SpawnCall) => {
readonly code?: number;
readonly fail?: string;
readonly awaitExit?: Deferred.Deferred<void>;
readonly onKill?: () => void;
} = () => ({
code: 0,
}),
) {
return Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make((command) => {
const standardCommand = command as unknown as {
readonly command: string;
readonly args: ReadonlyArray<string>;
readonly options: {
readonly detached?: boolean;
readonly shell?: boolean | string;
readonly stdin?: unknown;
readonly stdout?: unknown;
readonly stderr?: unknown;
};
};
const call: SpawnCall = {
command: standardCommand.command,
args: [...standardCommand.args],
detached: standardCommand.options.detached,
shell: standardCommand.options.shell,
stdin: standardCommand.options.stdin,
stdout: standardCommand.options.stdout,
stderr: standardCommand.options.stderr,
};
calls.push(call);
const result = handler(call);
if (result.fail) {
return Effect.fail(platformSpawnError(result.fail));
}
let exited = false;
const exitCode = result.awaitExit
? Deferred.await(result.awaitExit).pipe(
Effect.tap(() =>
Effect.sync(() => {
exited = true;
}),
),
Effect.andThen(Effect.succeed(ChildProcessSpawner.ExitCode(result.code ?? 0))),
)
: Effect.sync(() => {
exited = true;
return ChildProcessSpawner.ExitCode(result.code ?? 0);
});
return Effect.succeed(
ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(calls.length),
exitCode,
isRunning: Effect.succeed(false),
kill: () =>
Effect.sync(() => {
if (!exited) {
result.onKill?.();
}
}),
stdin: Sink.drain,
stdout: Stream.make(encoder.encode("")),
stderr: Stream.make(encoder.encode("")),
all: Stream.empty,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
}),
);
assert.deepEqual(zedLaunch, {
command: "zed",
args: ["/tmp/workspace"],
});
}),
);
}
it.effect("uses --goto when editor supports line/column suffixes", () =>
Effect.gen(function* () {
const lineOnly = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/AGENTS.md:48", editor: "cursor" },
"darwin",
);
assert.deepEqual(lineOnly, {
command: "cursor",
args: ["--goto", "/tmp/workspace/AGENTS.md:48"],
});
const lineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "cursor" },
"darwin",
);
assert.deepEqual(lineAndColumn, {
command: "cursor",
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
});
const vscodeLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode" },
"darwin",
);
assert.deepEqual(vscodeLineAndColumn, {
command: "code",
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
});
const vscodeInsidersLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode-insiders" },
"darwin",
);
assert.deepEqual(vscodeInsidersLineAndColumn, {
command: "code-insiders",
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
});
const vscodiumLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscodium" },
"darwin",
);
assert.deepEqual(vscodiumLineAndColumn, {
command: "codium",
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
});
const zedLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "zed" },
"darwin",
);
assert.deepEqual(zedLineAndColumn, {
command: "zed",
args: ["/tmp/workspace/src/open.ts:71:5"],
});
}),
const provideOpen = (
options: Parameters<typeof makeOpenLayer>[0],
spawnLayer: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>,
) =>
makeOpenLayer(options).pipe(
Layer.provide(Layer.mergeAll(NodeFileSystem.layer, NodePath.layer, spawnLayer)),
);
it.effect("maps file-manager editor to OS open commands", () =>
Effect.gen(function* () {
const launch1 = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "file-manager" },
"darwin",
);
assert.deepEqual(launch1, {
command: "open",
args: ["/tmp/workspace"],
});
const runOpen = <A>(
options: Parameters<typeof makeOpenLayer>[0],
spawnLayer: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>,
effect: Effect.Effect<A, Error, Open>,
) => effect.pipe(Effect.provide(provideOpen(options, spawnLayer)));
const launch2 = yield* resolveEditorLaunch(
{ cwd: "C:\\workspace", editor: "file-manager" },
"win32",
);
assert.deepEqual(launch2, {
command: "explorer",
args: ["C:\\workspace"],
});
const readOpen = Effect.service(Open);
const launch3 = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "file-manager" },
"linux",
);
assert.deepEqual(launch3, {
command: "xdg-open",
args: ["/tmp/workspace"],
});
}),
);
});
it.layer(NodeServices.layer)("launchDetached", (it) => {
it.effect("resolves when command can be spawned", () =>
Effect.gen(function* () {
const result = yield* launchDetached({
command: process.execPath,
args: ["-e", "process.exit(0)"],
}).pipe(Effect.result);
assertSuccess(result, undefined);
}),
);
it.effect("rejects when command does not exist", () =>
Effect.gen(function* () {
const result = yield* launchDetached({
command: `t3code-no-such-command-${Date.now()}`,
args: [],
}).pipe(Effect.result);
assert.equal(result._tag, "Failure");
}),
);
});
it.layer(NodeServices.layer)("isCommandAvailable", (it) => {
it.effect("resolves win32 commands with PATHEXT", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
yield* fs.writeFileString(path.join(dir, "code.CMD"), "@echo off\r\n");
const env = {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
} satisfies NodeJS.ProcessEnv;
assert.equal(isCommandAvailable("code", { platform: "win32", env }), true);
}),
);
it("returns false when a command is not on PATH", () => {
const env = {
PATH: "",
PATHEXT: ".COM;.EXE;.BAT;.CMD",
} satisfies NodeJS.ProcessEnv;
assert.equal(isCommandAvailable("definitely-not-installed", { platform: "win32", env }), false);
const writeExecutable = (filePath: string) =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
yield* fs.writeFileString(filePath, "#!/bin/sh\nexit 0\n");
yield* fs.chmod(filePath, 0o755);
});
it.effect("does not treat bare files without executable extension as available on win32", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
yield* fs.writeFileString(path.join(dir, "npm"), "echo nope\r\n");
const env = {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
} satisfies NodeJS.ProcessEnv;
assert.equal(isCommandAvailable("npm", { platform: "win32", env }), false);
}),
);
it.effect("getAvailableEditors detects installed editors through the service", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-editors-" });
yield* fs.writeFileString(`${dir}/code-insiders.CMD`, "@echo off\r\n");
yield* fs.writeFileString(`${dir}/codium.CMD`, "@echo off\r\n");
yield* fs.writeFileString(`${dir}/explorer.CMD`, "@echo off\r\n");
it.effect("appends PATHEXT for commands with non-executable extensions on win32", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
yield* fs.writeFileString(path.join(dir, "my.tool.CMD"), "@echo off\r\n");
const env = {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
} satisfies NodeJS.ProcessEnv;
assert.equal(isCommandAvailable("my.tool", { platform: "win32", env }), true);
}),
);
const calls: Array<SpawnCall> = [];
const open = yield* runOpen(
{
platform: "win32",
env: {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
},
},
spawnerLayer(calls),
readOpen,
);
it.effect("uses platform-specific PATH delimiter for platform overrides", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const firstDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
const secondDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
yield* fs.writeFileString(path.join(firstDir, "code.CMD"), "@echo off\r\n");
yield* fs.writeFileString(path.join(secondDir, "code.CMD"), "MZ");
const env = {
PATH: `${firstDir};${secondDir}`,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
} satisfies NodeJS.ProcessEnv;
assert.equal(isCommandAvailable("code", { platform: "win32", env }), true);
}),
);
});
const editors = yield* open.getAvailableEditors;
assert.deepEqual(editors, ["vscode-insiders", "vscodium", "file-manager"]);
assert.deepEqual(calls, []);
}).pipe(Effect.provide(NodeFileSystem.layer)),
);
it.layer(NodeServices.layer)("resolveAvailableEditors", (it) => {
it.effect("returns installed editors for command launches", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editors-" });
it.effect("getAvailableEditors does not advertise WSL file-manager from PowerShell alone", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-wsl-editors-" });
yield* fs.makeDirectory(`${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0`, {
recursive: true,
});
yield* writeExecutable(`${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`);
yield* fs.writeFileString(path.join(dir, "code-insiders.CMD"), "@echo off\r\n");
yield* fs.writeFileString(path.join(dir, "codium.CMD"), "@echo off\r\n");
yield* fs.writeFileString(path.join(dir, "explorer.CMD"), "MZ");
const editors = resolveAvailableEditors("win32", {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
});
assert.deepEqual(editors, ["vscode-insiders", "vscodium", "file-manager"]);
}),
);
});
const calls: Array<SpawnCall> = [];
const open = yield* runOpen(
{
platform: "linux",
env: {
PATH: `${dir}:${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0`,
WSL_DISTRO_NAME: "Ubuntu",
},
isWsl: true,
isInsideContainer: false,
powerShellCommand: `${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,
},
spawnerLayer(calls),
readOpen,
);
const editors = yield* open.getAvailableEditors;
assert.equal(editors.includes("file-manager"), false);
assert.deepEqual(calls, []);
}).pipe(Effect.provide(NodeFileSystem.layer)),
);
it.effect("openInEditor uses --goto for editors that support it", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-cursor-" });
yield* writeExecutable(`${dir}/cursor`);
const calls: Array<SpawnCall> = [];
const open = yield* runOpen(
{
platform: "darwin",
env: { PATH: dir },
},
spawnerLayer(calls),
readOpen,
);
yield* open.openInEditor({
cwd: "/tmp/workspace/src/open.ts:71:5",
editor: "cursor",
});
assert.deepEqual(calls, [
{
command: `${dir}/cursor`,
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
detached: true,
shell: false,
stdin: "ignore",
stdout: "ignore",
stderr: "ignore",
},
]);
}).pipe(Effect.provide(NodeFileSystem.layer)),
);
it.effect("openInEditor launches Windows batch shims through cmd.exe without shell mode", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-vscode-win32-" });
yield* fs.writeFileString(`${dir}/code.cmd`, "@echo off\r\n");
const calls: Array<SpawnCall> = [];
const open = yield* runOpen(
{
platform: "win32",
env: {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
},
},
spawnerLayer(calls),
readOpen,
);
yield* open.openInEditor({
cwd: "C:\\work\\100% real\\file.ts:12:4",
editor: "vscode",
});
assert.equal(calls.length, 1);
assert.equal(calls[0]?.command, "cmd.exe");
assert.deepEqual(calls[0]?.args.slice(0, 4), ["/d", "/v:off", "/s", "/c"]);
assert.equal(calls[0]?.args[4]?.toLowerCase().includes(`${dir}/code.cmd`.toLowerCase()), true);
assert.equal(calls[0]?.args[4]?.includes('"--goto"'), true);
assert.equal(calls[0]?.args[4]?.includes("100%% real"), true);
assert.equal(calls[0]?.detached, true);
assert.equal(calls[0]?.shell, false);
assert.equal(calls[0]?.stdin, "ignore");
assert.equal(calls[0]?.stdout, "ignore");
assert.equal(calls[0]?.stderr, "ignore");
}).pipe(Effect.provide(NodeFileSystem.layer)),
);
it.effect("openInEditor detached launches survive service scope shutdown", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-zed-detached-" });
yield* writeExecutable(`${dir}/zed`);
const calls: Array<SpawnCall> = [];
const exitDeferred = yield* Deferred.make<void>();
let killCount = 0;
yield* Effect.acquireUseRelease(
Scope.make("sequential"),
(scope) =>
Effect.gen(function* () {
const runtimeServices = yield* Layer.build(
provideOpen(
{
platform: "darwin",
env: { PATH: dir },
},
spawnerLayer(calls, () => ({
awaitExit: exitDeferred,
onKill: () => {
killCount += 1;
},
})),
),
).pipe(Scope.provide(scope));
const open = yield* readOpen.pipe(Effect.provide(runtimeServices), Scope.provide(scope));
yield* open.openInEditor({
cwd: "/tmp/workspace",
editor: "zed",
});
}),
(scope) => Scope.close(scope, Exit.void),
);
assert.equal(killCount, 0);
assert.deepEqual(calls, [
{
command: `${dir}/zed`,
args: ["/tmp/workspace"],
detached: true,
shell: false,
stdin: "ignore",
stdout: "ignore",
stderr: "ignore",
},
]);
yield* Deferred.succeed(exitDeferred, void 0);
yield* Effect.yieldNow;
assert.equal(killCount, 0);
}).pipe(Effect.provide(NodeFileSystem.layer)),
);
it.effect("openInEditor uses the default opener for file-manager on macOS", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-macos-" });
yield* writeExecutable(`${dir}/open`);
const calls: Array<SpawnCall> = [];
const open = yield* runOpen(
{
platform: "darwin",
env: { PATH: dir },
},
spawnerLayer(calls),
readOpen,
);
yield* open.openInEditor({
cwd: "/tmp/workspace",
editor: "file-manager",
});
assert.deepEqual(calls, [
{
command: `${dir}/open`,
args: ["/tmp/workspace"],
detached: undefined,
shell: false,
stdin: undefined,
stdout: undefined,
stderr: undefined,
},
]);
}).pipe(Effect.provide(NodeFileSystem.layer)),
);
it.effect("openBrowser uses macOS open flags and app arguments", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-browser-macos-" });
yield* writeExecutable(`${dir}/open`);
const calls: Array<SpawnCall> = [];
const open = yield* runOpen(
{
platform: "darwin",
env: { PATH: dir },
},
spawnerLayer(calls),
readOpen,
);
yield* open.openBrowser("https://example.com", {
wait: true,
background: true,
newInstance: true,
app: {
name: "google chrome",
arguments: ["--profile-directory=Work"],
},
});
assert.deepEqual(calls, [
{
command: `${dir}/open`,
args: [
"--wait-apps",
"--background",
"--new",
"-a",
"google chrome",
"https://example.com",
"--args",
"--profile-directory=Work",
],
detached: undefined,
shell: false,
stdin: undefined,
stdout: undefined,
stderr: undefined,
},
]);
}).pipe(Effect.provide(NodeFileSystem.layer)),
);
it.effect("openBrowser uses PowerShell on win32", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-browser-win32-" });
yield* fs.writeFileString(`${dir}/powershell.exe`, "MZ");
const calls: Array<SpawnCall> = [];
const open = yield* runOpen(
{
platform: "win32",
env: {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
},
},
spawnerLayer(calls),
readOpen,
);
yield* open.openBrowser("https://example.com");
assert.equal(calls.length, 1);
assert.equal(calls[0]?.command, `${dir}/powershell.exe`);
assert.equal(calls[0]?.args.at(-2), "-EncodedCommand");
assert.equal(
decodePowerShellCommand(calls[0]?.args.at(-1) ?? ""),
"Start 'https://example.com'",
);
}).pipe(Effect.provide(NodeFileSystem.layer)),
);
it.effect("openBrowser falls back from WSL PowerShell to xdg-open", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-browser-wsl-" });
yield* fs.makeDirectory(`${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0`, {
recursive: true,
});
yield* writeExecutable(`${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`);
yield* writeExecutable(`${dir}/xdg-open`);
const calls: Array<SpawnCall> = [];
const open = yield* runOpen(
{
platform: "linux",
env: {
PATH: `${dir}:${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0`,
WSL_DISTRO_NAME: "Ubuntu",
},
isWsl: true,
isInsideContainer: false,
powerShellCommand: `${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,
},
spawnerLayer(calls, (call) =>
call.command.includes("powershell")
? { fail: "powershell unavailable" }
: {
code: 0,
},
),
readOpen,
);
yield* open.openBrowser("https://example.com");
assert.equal(calls[0]?.command.includes("powershell"), true);
assert.equal(calls[1]?.command, `${dir}/xdg-open`);
assert.deepEqual(calls[1]?.args, ["https://example.com"]);
}).pipe(Effect.provide(NodeFileSystem.layer)),
);
it.effect("openInEditor uses xdg-open first for WSL file-manager paths", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-wsl-file-manager-" });
yield* fs.makeDirectory(`${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0`, {
recursive: true,
});
yield* writeExecutable(`${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`);
yield* writeExecutable(`${dir}/xdg-open`);
const calls: Array<SpawnCall> = [];
const open = yield* runOpen(
{
platform: "linux",
env: {
PATH: `${dir}:${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0`,
WSL_DISTRO_NAME: "Ubuntu",
},
isWsl: true,
isInsideContainer: false,
powerShellCommand: `${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,
},
spawnerLayer(calls),
readOpen,
);
yield* open.openInEditor({
cwd: "/home/julius/workspace",
editor: "file-manager",
});
assert.deepEqual(calls, [
{
command: `${dir}/xdg-open`,
args: ["/home/julius/workspace"],
detached: true,
shell: false,
stdin: "ignore",
stdout: "ignore",
stderr: "ignore",
},
]);
}).pipe(Effect.provide(NodeFileSystem.layer)),
);
it.effect("openInEditor fails when the editor command is unavailable", () =>
Effect.gen(function* () {
const calls: Array<SpawnCall> = [];
const open = yield* runOpen(
{
platform: "darwin",
env: { PATH: "" },
},
spawnerLayer(calls),
readOpen,
);
const error = yield* open
.openInEditor({
cwd: "/tmp/workspace",
editor: "cursor",
})
.pipe(Effect.flip);
assert.equal(error._tag, "OpenError");
assert.equal(error.message, "Command not found: cursor");
assert.deepEqual(calls, []);
}),
);
+575 -171
View File
@@ -1,21 +1,17 @@
/**
* Open - Browser/editor launch service interface.
*
* Owns process launch helpers for opening URLs in a browser and workspace
* paths in a configured editor.
* Owns process launch helpers for opening URLs in a browser, workspace paths in
* a configured editor, and generic external targets through the platform's
* default opener.
*
* @module Open
*/
import { spawn } from "node:child_process";
import { accessSync, constants, statSync } from "node:fs";
import { extname, join } from "node:path";
import os from "node:os";
import { EDITORS, type EditorId } from "@t3tools/contracts";
import { ServiceMap, Schema, Effect, Layer } from "effect";
// ==============================
// Definitions
// ==============================
import { Effect, Exit, FileSystem, Layer, Option, Path, Schema, Scope, ServiceMap } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
export class OpenError extends Schema.TaggedErrorClass<OpenError>()("OpenError", {
message: Schema.String,
@@ -27,33 +23,66 @@ export interface OpenInEditorInput {
readonly editor: EditorId;
}
interface EditorLaunch {
readonly command: string;
readonly args: ReadonlyArray<string>;
export interface OpenApplicationInput {
readonly name: string | ReadonlyArray<string>;
readonly arguments?: ReadonlyArray<string>;
}
interface CommandAvailabilityOptions {
export interface OpenExternalInput {
readonly target: string;
readonly wait?: boolean;
readonly background?: boolean;
readonly newInstance?: boolean;
readonly allowNonzeroExitCode?: boolean;
readonly app?: OpenApplicationInput | ReadonlyArray<OpenApplicationInput>;
}
export interface OpenRuntimeOptions {
readonly platform?: NodeJS.Platform;
readonly env?: NodeJS.ProcessEnv;
readonly isWsl?: boolean;
readonly isInsideContainer?: boolean;
readonly powerShellCommand?: string;
}
interface OpenRuntime {
readonly platform: NodeJS.Platform;
readonly env: NodeJS.ProcessEnv;
readonly isWsl: boolean;
readonly isInsideContainer: boolean;
readonly powerShellCandidates: ReadonlyArray<string>;
readonly windowsPathExtensions: ReadonlyArray<string>;
}
interface LaunchPlan {
readonly command: string;
readonly args: ReadonlyArray<string>;
readonly wait: boolean;
readonly allowNonzeroExitCode: boolean;
readonly detached?: boolean;
readonly shell?: boolean;
readonly stdio?: "ignore";
}
interface ResolvedCommand {
readonly path: string;
readonly usesCmdWrapper: boolean;
}
const LINE_COLUMN_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
const WINDOWS_POWERSHELL_CANDIDATES = ["powershell.exe", "powershell", "pwsh.exe", "pwsh"] as const;
const WSL_POWERSHELL_CANDIDATES = [
"/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe",
"/mnt/c/Program Files/PowerShell/7/pwsh.exe",
"powershell.exe",
"pwsh.exe",
] as const;
const WINDOWS_BATCH_EXTENSIONS = [".CMD", ".BAT"] as const;
function shouldUseGotoFlag(editor: (typeof EDITORS)[number], target: string): boolean {
return editor.supportsGoto && LINE_COLUMN_SUFFIX_PATTERN.test(target);
}
function fileManagerCommandForPlatform(platform: NodeJS.Platform): string {
switch (platform) {
case "darwin":
return "open";
case "win32":
return "explorer";
default:
return "xdg-open";
}
}
function stripWrappingQuotes(value: string): string {
return value.replace(/^"+|"+$/g, "");
}
@@ -72,19 +101,24 @@ function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray<str
.map((entry) => entry.trim())
.filter((entry) => entry.length > 0)
.map((entry) => (entry.startsWith(".") ? entry.toUpperCase() : `.${entry.toUpperCase()}`));
return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback;
}
function resolveWindowsCommandShell(env: NodeJS.ProcessEnv): string {
return env.ComSpec ?? env.COMSPEC ?? "cmd.exe";
}
function resolveCommandCandidates(
command: string,
platform: NodeJS.Platform,
windowsPathExtensions: ReadonlyArray<string>,
runtime: OpenRuntime,
pathService: Path.Path,
): ReadonlyArray<string> {
if (platform !== "win32") return [command];
const extension = extname(command);
if (runtime.platform !== "win32") return [command];
const extension = pathService.extname(command);
const normalizedExtension = extension.toUpperCase();
if (extension.length > 0 && windowsPathExtensions.includes(normalizedExtension)) {
if (extension.length > 0 && runtime.windowsPathExtensions.includes(normalizedExtension)) {
const commandWithoutExtension = command.slice(0, -extension.length);
return Array.from(
new Set([
@@ -96,179 +130,549 @@ function resolveCommandCandidates(
}
const candidates: string[] = [];
for (const extension of windowsPathExtensions) {
candidates.push(`${command}${extension}`);
candidates.push(`${command}${extension.toLowerCase()}`);
for (const extensionName of runtime.windowsPathExtensions) {
candidates.push(`${command}${extensionName}`);
candidates.push(`${command}${extensionName.toLowerCase()}`);
}
return Array.from(new Set(candidates));
}
function isExecutableFile(
filePath: string,
platform: NodeJS.Platform,
windowsPathExtensions: ReadonlyArray<string>,
): boolean {
try {
const stat = statSync(filePath);
if (!stat.isFile()) return false;
if (platform === "win32") {
const extension = extname(filePath);
if (extension.length === 0) return false;
return windowsPathExtensions.includes(extension.toUpperCase());
}
accessSync(filePath, constants.X_OK);
return true;
} catch {
return false;
}
}
function resolvePathDelimiter(platform: NodeJS.Platform): string {
return platform === "win32" ? ";" : ":";
}
export function isCommandAvailable(
command: string,
options: CommandAvailabilityOptions = {},
): boolean {
const platform = options.platform ?? process.platform;
const env = options.env ?? process.env;
const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
const commandCandidates = resolveCommandCandidates(command, platform, windowsPathExtensions);
function detectWsl(platform: NodeJS.Platform, env: NodeJS.ProcessEnv): boolean {
if (platform !== "linux") return false;
if (typeof env.WSL_DISTRO_NAME === "string" || typeof env.WSL_INTEROP === "string") {
return true;
}
return os.release().toLowerCase().includes("microsoft");
}
if (command.includes("/") || command.includes("\\")) {
return commandCandidates.some((candidate) =>
isExecutableFile(candidate, platform, windowsPathExtensions),
);
function quotePowerShellValue(value: string): string {
return `'${value.replaceAll("'", "''")}'`;
}
function encodePowerShellCommand(command: string): string {
return Buffer.from(command, "utf16le").toString("base64");
}
function normalizeAppCandidates(
app: OpenExternalInput["app"],
): ReadonlyArray<{ readonly name: string; readonly arguments: ReadonlyArray<string> } | undefined> {
if (!app) return [undefined];
const apps = Array.isArray(app) ? app : [app];
const candidates: Array<{ readonly name: string; readonly arguments: ReadonlyArray<string> }> =
[];
for (const appDef of apps) {
const names = Array.isArray(appDef.name) ? appDef.name : [appDef.name];
for (const name of names) {
candidates.push({ name, arguments: appDef.arguments ?? [] });
}
}
const pathValue = resolvePathEnvironmentVariable(env);
if (pathValue.length === 0) return false;
const pathEntries = pathValue
.split(resolvePathDelimiter(platform))
.map((entry) => stripWrappingQuotes(entry.trim()))
.filter((entry) => entry.length > 0);
return candidates;
}
for (const pathEntry of pathEntries) {
for (const candidate of commandCandidates) {
if (isExecutableFile(join(pathEntry, candidate), platform, windowsPathExtensions)) {
return true;
function isUriLikeTarget(target: string): boolean {
return /^[A-Za-z][A-Za-z\d+.-]*:/.test(target);
}
function shouldPreferWindowsOpenerOnWsl(input: OpenExternalInput, runtime: OpenRuntime): boolean {
return runtime.isWsl && !runtime.isInsideContainer && isUriLikeTarget(input.target);
}
function makeLaunchPlan(
command: string,
args: ReadonlyArray<string>,
options: {
readonly wait: boolean;
readonly allowNonzeroExitCode: boolean;
readonly detached?: boolean;
readonly shell?: boolean;
readonly stdio?: "ignore";
},
): LaunchPlan {
return {
command,
args,
wait: options.wait,
allowNonzeroExitCode: options.allowNonzeroExitCode,
shell: options.shell ?? false,
...(options.detached !== undefined ? { detached: options.detached } : {}),
...(options.stdio !== undefined ? { stdio: options.stdio } : {}),
};
}
function makeDarwinDefaultPlan(input: OpenExternalInput): LaunchPlan {
const args: string[] = [];
const wait = input.wait ?? false;
if (wait) args.push("--wait-apps");
if (input.background) args.push("--background");
if (input.newInstance) args.push("--new");
args.push(input.target);
return makeLaunchPlan("open", args, {
wait,
allowNonzeroExitCode: input.allowNonzeroExitCode ?? false,
shell: false,
});
}
function makeDarwinApplicationPlan(
input: OpenExternalInput,
app: { readonly name: string; readonly arguments: ReadonlyArray<string> },
): LaunchPlan {
const args: string[] = [];
const wait = input.wait ?? false;
if (wait) args.push("--wait-apps");
if (input.background) args.push("--background");
if (input.newInstance) args.push("--new");
args.push("-a", app.name);
args.push(input.target);
if (app.arguments.length > 0) {
args.push("--args", ...app.arguments);
}
return makeLaunchPlan("open", args, {
wait,
allowNonzeroExitCode: input.allowNonzeroExitCode ?? false,
shell: false,
});
}
function makePowerShellPlan(input: OpenExternalInput, powerShellCommand: string): LaunchPlan {
const encodedParts = ["Start"];
const wait = input.wait ?? false;
if (wait) encodedParts.push("-Wait");
encodedParts.push(quotePowerShellValue(input.target));
return makeLaunchPlan(
powerShellCommand,
[
"-NoProfile",
"-NonInteractive",
"-ExecutionPolicy",
"Bypass",
"-EncodedCommand",
encodePowerShellCommand(encodedParts.join(" ")),
],
{
wait,
allowNonzeroExitCode: input.allowNonzeroExitCode ?? false,
shell: false,
},
);
}
function makeLinuxDefaultPlan(input: OpenExternalInput): LaunchPlan {
const wait = input.wait ?? false;
return makeLaunchPlan("xdg-open", [input.target], {
wait,
allowNonzeroExitCode: input.allowNonzeroExitCode ?? false,
detached: !wait,
...(wait ? {} : { stdio: "ignore" as const }),
shell: false,
});
}
function makeWindowsExplorerPlan(input: OpenExternalInput): LaunchPlan {
return makeLaunchPlan("explorer", [input.target], {
wait: false,
allowNonzeroExitCode: false,
shell: false,
});
}
function makeDirectApplicationPlan(
input: OpenExternalInput,
app: { readonly name: string; readonly arguments: ReadonlyArray<string> },
): LaunchPlan {
return makeLaunchPlan(app.name, [...app.arguments, input.target], {
wait: input.wait ?? false,
allowNonzeroExitCode: input.allowNonzeroExitCode ?? false,
shell: false,
});
}
function resolveExternalPlans(
input: OpenExternalInput,
runtime: OpenRuntime,
): ReadonlyArray<LaunchPlan> {
const appCandidates = normalizeAppCandidates(input.app);
const plans: LaunchPlan[] = [];
const preferWindowsOpenerOnWsl = shouldPreferWindowsOpenerOnWsl(input, runtime);
for (const app of appCandidates) {
if (app) {
if (runtime.platform === "darwin") {
plans.push(makeDarwinApplicationPlan(input, app));
} else {
plans.push(makeDirectApplicationPlan(input, app));
}
continue;
}
if (runtime.platform === "darwin") {
plans.push(makeDarwinDefaultPlan(input));
continue;
}
if (runtime.platform === "win32" || preferWindowsOpenerOnWsl) {
for (const powerShellCommand of runtime.powerShellCandidates) {
plans.push(makePowerShellPlan(input, powerShellCommand));
}
}
}
return false;
}
export function resolveAvailableEditors(
platform: NodeJS.Platform = process.platform,
env: NodeJS.ProcessEnv = process.env,
): ReadonlyArray<EditorId> {
const available: EditorId[] = [];
for (const editor of EDITORS) {
const command = editor.command ?? fileManagerCommandForPlatform(platform);
if (isCommandAvailable(command, { platform, env })) {
available.push(editor.id);
if (runtime.platform === "win32") {
if (!(input.wait ?? false)) {
plans.push(makeWindowsExplorerPlan(input));
}
continue;
}
plans.push(makeLinuxDefaultPlan(input));
}
return available;
return plans;
}
/**
* OpenShape - Service API for browser and editor launch actions.
*/
export interface OpenShape {
/**
* Open a URL target in the default browser.
*/
readonly openBrowser: (target: string) => Effect.Effect<void, OpenError>;
function toOpenError(message: string, cause: unknown): OpenError {
return new OpenError({ message, cause });
}
/**
* Open a workspace path in a selected editor integration.
*
* Launches the editor as a detached process so server startup is not blocked.
*/
function isWindowsBatchShim(pathService: Path.Path, filePath: string): boolean {
return WINDOWS_BATCH_EXTENSIONS.includes(pathService.extname(filePath).toUpperCase() as never);
}
function quoteForWindowsCmd(value: string): string {
return `"${value.replaceAll("%", "%%").replaceAll('"', '""')}"`;
}
function makeWindowsCmdCommandLine(commandPath: string, args: ReadonlyArray<string>): string {
return `"${[commandPath, ...args].map(quoteForWindowsCmd).join(" ")}"`;
}
export interface OpenShape {
readonly getAvailableEditors: Effect.Effect<ReadonlyArray<EditorId>, OpenError>;
readonly openExternal: (input: OpenExternalInput) => Effect.Effect<void, OpenError>;
readonly openBrowser: (
target: string,
options?: Omit<OpenExternalInput, "target">,
) => Effect.Effect<void, OpenError>;
readonly openInEditor: (input: OpenInEditorInput) => Effect.Effect<void, OpenError>;
}
/**
* Open - Service tag for browser/editor launch operations.
*/
export class Open extends ServiceMap.Service<Open, OpenShape>()("t3/open") {}
// ==============================
// Implementations
// ==============================
export const resolveEditorLaunch = Effect.fnUntraced(function* (
input: OpenInEditorInput,
platform: NodeJS.Platform = process.platform,
): Effect.fn.Return<EditorLaunch, OpenError> {
const editorDef = EDITORS.find((editor) => editor.id === input.editor);
if (!editorDef) {
return yield* new OpenError({ message: `Unknown editor: ${input.editor}` });
}
if (editorDef.command) {
return shouldUseGotoFlag(editorDef, input.cwd)
? { command: editorDef.command, args: ["--goto", input.cwd] }
: { command: editorDef.command, args: [input.cwd] };
}
if (editorDef.id !== "file-manager") {
return yield* new OpenError({ message: `Unsupported editor: ${input.editor}` });
}
return { command: fileManagerCommandForPlatform(platform), args: [input.cwd] };
});
export const launchDetached = (launch: EditorLaunch) =>
const makeOpen = (options: OpenRuntimeOptions = {}) =>
Effect.gen(function* () {
if (!isCommandAvailable(launch.command)) {
return yield* new OpenError({ message: `Editor command not found: ${launch.command}` });
}
const fileSystem = yield* FileSystem.FileSystem;
const pathService = yield* Path.Path;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
yield* Effect.callback<void, OpenError>((resume) => {
let child;
try {
child = spawn(launch.command, [...launch.args], {
detached: true,
stdio: "ignore",
shell: process.platform === "win32",
});
} catch (error) {
return resume(
Effect.fail(new OpenError({ message: "failed to spawn detached process", cause: error })),
const isInsideContainer =
options.isInsideContainer ??
(typeof options.env?.CONTAINER === "string" ||
typeof options.env?.container === "string" ||
typeof options.env?.KUBERNETES_SERVICE_HOST === "string"
? true
: yield* fileSystem.exists("/.dockerenv").pipe(Effect.catch(() => Effect.succeed(false))));
const runtime: OpenRuntime = {
platform: options.platform ?? process.platform,
env: options.env ?? process.env,
isWsl:
options.isWsl ??
detectWsl(options.platform ?? process.platform, options.env ?? process.env),
isInsideContainer,
powerShellCandidates:
options.powerShellCommand !== undefined
? [options.powerShellCommand]
: (options.isWsl ??
detectWsl(options.platform ?? process.platform, options.env ?? process.env))
? WSL_POWERSHELL_CANDIDATES
: WINDOWS_POWERSHELL_CANDIDATES,
windowsPathExtensions: resolveWindowsPathExtensions(options.env ?? process.env),
};
const resolveCommand = Effect.fn(function* (
command: string,
): Effect.fn.Return<Option.Option<ResolvedCommand>, never> {
const candidates = resolveCommandCandidates(command, runtime, pathService);
const resolveExecutableFile = Effect.fn(function* (
filePath: string,
): Effect.fn.Return<Option.Option<ResolvedCommand>, never> {
const info = yield* fileSystem.stat(filePath).pipe(Effect.option);
if (Option.isNone(info) || info.value.type !== "File") return Option.none();
if (runtime.platform === "win32") {
const extension = pathService.extname(filePath);
if (
extension.length === 0 ||
!runtime.windowsPathExtensions.includes(extension.toUpperCase())
) {
return Option.none();
}
return Option.some({
path: filePath,
usesCmdWrapper: isWindowsBatchShim(pathService, filePath),
} satisfies ResolvedCommand);
}
return (info.value.mode & 0o111) !== 0
? Option.some({
path: filePath,
usesCmdWrapper: false,
} satisfies ResolvedCommand)
: Option.none();
});
if (command.includes("/") || command.includes("\\")) {
for (const candidate of candidates) {
const resolved = yield* resolveExecutableFile(candidate);
if (Option.isSome(resolved)) return resolved;
}
return Option.none();
}
const pathValue = resolvePathEnvironmentVariable(runtime.env);
if (pathValue.length === 0) return Option.none();
const pathEntries = pathValue
.split(resolvePathDelimiter(runtime.platform))
.map((entry) => stripWrappingQuotes(entry.trim()))
.filter((entry) => entry.length > 0);
for (const pathEntry of pathEntries) {
for (const candidate of candidates) {
const resolved = yield* resolveExecutableFile(pathService.join(pathEntry, candidate));
if (Option.isSome(resolved)) {
return resolved;
}
}
}
return Option.none();
});
const commandAvailable = (command: string) =>
resolveCommand(command).pipe(Effect.map(Option.isSome));
const fileManagerAvailable = Effect.gen(function* () {
const candidates =
runtime.platform === "darwin"
? ["open"]
: runtime.platform === "win32"
? [...runtime.powerShellCandidates, "explorer"]
: ["xdg-open"];
for (const candidate of candidates) {
if (yield* commandAvailable(candidate)) {
return true;
}
}
return false;
});
const getAvailableEditors = Effect.gen(function* () {
const available: EditorId[] = [];
for (const editor of EDITORS) {
if (editor.id === "file-manager") {
if (yield* fileManagerAvailable) {
available.push(editor.id);
}
continue;
}
if (editor.command && (yield* commandAvailable(editor.command))) {
available.push(editor.id);
}
}
return available as ReadonlyArray<EditorId>;
}).pipe(Effect.mapError((cause) => toOpenError("Failed to resolve available editors", cause)));
const spawnPlan = (
plan: LaunchPlan,
resolvedCommand: ResolvedCommand,
failureMessage: string,
) =>
spawner
.spawn(
ChildProcess.make(
resolvedCommand.usesCmdWrapper
? resolveWindowsCommandShell(runtime.env)
: resolvedCommand.path,
resolvedCommand.usesCmdWrapper
? [
"/d",
"/v:off",
"/s",
"/c",
makeWindowsCmdCommandLine(resolvedCommand.path, plan.args),
]
: [...plan.args],
{
detached: plan.detached,
shell: plan.shell,
...(plan.stdio === "ignore"
? {
stdin: "ignore",
stdout: "ignore",
stderr: "ignore",
}
: {}),
},
),
)
.pipe(Effect.mapError((cause) => toOpenError(failureMessage, cause)));
const waitForExit = (
plan: LaunchPlan,
failureMessage: string,
handle: ChildProcessSpawner.ChildProcessHandle,
) =>
handle.exitCode.pipe(
Effect.flatMap((exitCode) =>
!plan.allowNonzeroExitCode && (exitCode as number) !== 0
? Effect.fail(
new OpenError({
message: `${failureMessage} (code=${exitCode as number})`,
}),
)
: Effect.void,
),
Effect.mapError((cause) => toOpenError(failureMessage, cause)),
);
const runWaitedPlan = (
plan: LaunchPlan,
resolvedCommand: ResolvedCommand,
failureMessage: string,
) =>
Effect.acquireUseRelease(
Scope.make("sequential"),
(scope) =>
Effect.gen(function* () {
const handle = yield* spawnPlan(plan, resolvedCommand, failureMessage).pipe(
Scope.provide(scope),
);
yield* waitForExit(plan, failureMessage, handle);
}),
(scope) => Scope.close(scope, Exit.void),
);
const runDetachedPlan = (
plan: LaunchPlan,
resolvedCommand: ResolvedCommand,
failureMessage: string,
) =>
Effect.gen(function* () {
const childScope = yield* Scope.make("sequential");
const handle = yield* spawnPlan(plan, resolvedCommand, failureMessage).pipe(
Scope.provide(childScope),
Effect.catch((error) =>
Scope.close(childScope, Exit.void).pipe(Effect.andThen(Effect.fail(error))),
),
);
const releaseOnExit: Effect.Effect<void, never> = handle.exitCode.pipe(
Effect.ignoreCause,
Effect.ensuring(Scope.close(childScope, Exit.void)),
);
yield* Effect.forkDetach(releaseOnExit);
});
const runPlan = (plan: LaunchPlan, resolvedCommand: ResolvedCommand, failureMessage: string) =>
plan.wait
? runWaitedPlan(plan, resolvedCommand, failureMessage)
: runDetachedPlan(plan, resolvedCommand, failureMessage);
const runFirstAvailablePlan = (
plans: ReadonlyArray<LaunchPlan>,
failureMessage: string,
): Effect.Effect<void, OpenError> => {
const [first, ...rest] = plans;
if (!first) {
return Effect.fail(new OpenError({ message: failureMessage }));
}
return resolveCommand(first.command).pipe(
Effect.flatMap((resolvedCommand) => {
if (Option.isNone(resolvedCommand)) {
return rest.length === 0
? Effect.fail(new OpenError({ message: `Command not found: ${first.command}` }))
: runFirstAvailablePlan(rest, failureMessage);
}
return runPlan(first, resolvedCommand.value, failureMessage).pipe(
Effect.catch((error) =>
rest.length === 0 ? Effect.fail(error) : runFirstAvailablePlan(rest, failureMessage),
),
);
}),
);
};
const openExternal = (input: OpenExternalInput) => {
if (input.target.trim().length === 0) {
return Effect.fail(new OpenError({ message: "Open target must not be empty" }));
}
return runFirstAvailablePlan(
resolveExternalPlans(input, runtime),
`Failed to open ${input.target}`,
);
};
const openInEditor = (input: OpenInEditorInput) => {
const editor = EDITORS.find((candidate) => candidate.id === input.editor);
if (!editor) {
return Effect.fail(new OpenError({ message: `Unknown editor: ${input.editor}` }));
}
if (editor.command) {
return runFirstAvailablePlan(
[
makeLaunchPlan(
editor.command,
shouldUseGotoFlag(editor, input.cwd) ? ["--goto", input.cwd] : [input.cwd],
{
wait: false,
allowNonzeroExitCode: false,
detached: true,
stdio: "ignore",
shell: false,
},
),
],
`Failed to open ${input.cwd} in ${input.editor}`,
);
}
const handleSpawn = () => {
child.unref();
resume(Effect.void);
};
return openExternal({ target: input.cwd });
};
child.once("spawn", handleSpawn);
child.once("error", (cause) =>
resume(Effect.fail(new OpenError({ message: "failed to spawn detached process", cause }))),
);
});
return {
getAvailableEditors,
openExternal,
openBrowser: (target, openOptions = {}) => openExternal({ ...openOptions, target }),
openInEditor,
} satisfies OpenShape;
});
const make = Effect.gen(function* () {
const open = yield* Effect.tryPromise({
try: () => import("open"),
catch: (cause) => new OpenError({ message: "failed to load browser opener", cause }),
});
export const makeOpenLayer = (options: OpenRuntimeOptions = {}) =>
Layer.effect(Open, makeOpen(options));
return {
openBrowser: (target) =>
Effect.tryPromise({
try: () => open.default(target),
catch: (cause) => new OpenError({ message: "Browser auto-open failed", cause }),
}),
openInEditor: (input) => Effect.flatMap(resolveEditorLaunch(input), launchDetached),
} satisfies OpenShape;
});
export const OpenLive = Layer.effect(Open, make);
export const OpenLive = makeOpenLayer();
+6
View File
@@ -63,6 +63,8 @@ const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
const defaultOpenService: OpenShape = {
getAvailableEditors: Effect.succeed([]),
openExternal: () => Effect.void,
openBrowser: () => Effect.void,
openInEditor: () => Effect.void,
};
@@ -1030,6 +1032,8 @@ describe("WebSocket Server", () => {
it("routes shell.openInEditor through the injected open service", async () => {
const openCalls: Array<{ cwd: string; editor: string }> = [];
const openService: OpenShape = {
getAvailableEditors: Effect.succeed([]),
openExternal: () => Effect.void,
openBrowser: () => Effect.void,
openInEditor: (input) => {
openCalls.push({ cwd: input.cwd, editor: input.editor });
@@ -1531,6 +1535,8 @@ describe("WebSocket Server", () => {
process.on("unhandledRejection", onUnhandledRejection);
const brokenOpenService: OpenShape = {
getAvailableEditors: Effect.succeed([]),
openExternal: () => Effect.void,
openBrowser: () => Effect.void,
openInEditor: () =>
Effect.sync(() => BigInt(1)).pipe(Effect.map((result) => result as unknown as void)),
+6 -3
View File
@@ -58,7 +58,7 @@ import { ProviderService } from "./provider/Services/ProviderService";
import { ProviderRegistry } from "./provider/Services/ProviderRegistry";
import { CheckpointDiffQuery } from "./checkpointing/Services/CheckpointDiffQuery";
import { clamp } from "effect/Number";
import { Open, resolveAvailableEditors } from "./open";
import { Open } from "./open";
import { ServerConfig } from "./config";
import { GitCore } from "./git/Services/GitCore.ts";
import { tryHandleProjectFaviconRequest } from "./projectFaviconRoute";
@@ -250,7 +250,10 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
logWebSocketEvents,
autoBootstrapProjectFromCwd,
} = serverConfig;
const availableEditors = resolveAvailableEditors();
const open = yield* Open;
const availableEditors = yield* open.getAvailableEditors.pipe(
Effect.mapError((cause) => new ServerLifecycleError({ operation: "availableEditors", cause })),
);
const runtimeServices = yield* Effect.services<
ServerRuntimeServices | ServerConfig | FileSystem.FileSystem | Path.Path
@@ -615,7 +618,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
const projectionReadModelQuery = yield* ProjectionSnapshotQuery;
const checkpointDiffQuery = yield* CheckpointDiffQuery;
const orchestrationReactor = yield* OrchestrationReactor;
const { openInEditor } = yield* Open;
const { openInEditor } = open;
const subscriptionsScope = yield* Scope.make("sequential");
yield* Effect.addFinalizer(() => Scope.close(subscriptionsScope, Exit.void));
-15
View File
@@ -54,7 +54,6 @@
"@pierre/diffs": "^1.1.0-beta.16",
"effect": "catalog:",
"node-pty": "^1.1.0",
"open": "^10.1.0",
"ws": "^8.18.0",
},
"devDependencies": {
@@ -896,8 +895,6 @@
"bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-tcpfCCl6XWo6nCVnpcVrxQ+9AYN1iqMIzgrSKYMB/fjLtV2eyAVEg7AxQJuCq/26R6HpKWykQXuSOq/21RYcbg=="],
"bundle-name": ["[email protected]", "", { "dependencies": { "run-applescript": "^7.0.0" } }, "sha512-tjwM5exMg6BGRI+kNmTntNsvdZS1X8BFYS6tnJ2hdH0kVxM6/eVZ2xy+FqStSWvYmtfFMDLIxurorHwDKfDz5Q=="],
"cac": ["[email protected]", "", {}, "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ=="],
"cacheable-lookup": ["[email protected]", "", {}, "sha512-2/kNscPhpcxrOigMZzbiWF7dz8ilhb/nIHU3EyZiXWXpeq/au8qJ8VhdftMkty3n7Gj6HIGalQG8oiBNB3AJgA=="],
@@ -972,16 +969,10 @@
"decompress-response": ["[email protected]", "", { "dependencies": { "mimic-response": "^3.1.0" } }, "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ=="],
"default-browser": ["[email protected]", "", { "dependencies": { "bundle-name": "^4.1.0", "default-browser-id": "^5.0.0" } }, "sha512-H9LMLr5zwIbSxrmvikGuI/5KGhZ8E2zH3stkMgM5LpOWDutGM2JZaj460Udnf1a+946zc7YBgrqEWwbk7zHvGw=="],
"default-browser-id": ["[email protected]", "", {}, "sha512-x1VCxdX4t+8wVfd1so/9w+vQ4vx7lKd2Qp5tDRutErwmR85OgmfX7RlLRMWafRMY7hbEiXIbudNrjOAPa/hL8Q=="],
"defer-to-connect": ["[email protected]", "", {}, "sha512-4tvttepXG1VaYGrRibk5EwJd1t4udunSOVMdLSAL6mId1ix438oPwPZMALY41FCijukO1L0twNcGsdzS7dHgDg=="],
"define-data-property": ["[email protected]", "", { "dependencies": { "es-define-property": "^1.0.0", "es-errors": "^1.3.0", "gopd": "^1.0.1" } }, "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A=="],
"define-lazy-prop": ["[email protected]", "", {}, "sha512-N+MeXYoqr3pOgn8xfyRPREN7gHakLYjhsHhWGT3fWAiL4IkAt0iDw14QiiEm2bE30c5XX5q0FtAA3CK5f9/BUg=="],
"define-properties": ["[email protected]", "", { "dependencies": { "define-data-property": "^1.0.1", "has-property-descriptors": "^1.0.0", "object-keys": "^1.1.1" } }, "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg=="],
"defu": ["[email protected]", "", {}, "sha512-mEQCMmwJu317oSz8CwdIOdwf3xMif1ttiM8LTufzc3g6kR+9Pe236twL8j3IYT1F7GfRgGcW6MWxzZjLIkuHIg=="],
@@ -1462,8 +1453,6 @@
"oniguruma-to-es": ["[email protected]", "", { "dependencies": { "oniguruma-parser": "^0.12.1", "regex": "^6.1.0", "regex-recursion": "^6.0.2" } }, "sha512-Zjygswjpsewa0NLTsiizVuMQZbp0MDyM6lIt66OxsF21npUDlzpHi1Mgb/qhQdkb+dWFTzJmFbEWdvZgRho8eQ=="],
"open": ["[email protected]", "", { "dependencies": { "default-browser": "^5.2.1", "define-lazy-prop": "^3.0.0", "is-inside-container": "^1.0.0", "wsl-utils": "^0.1.0" } }, "sha512-YgBpdJHPyQ2UE5x+hlSXcnejzAvD0b22U2OuAP+8OnlJT+PjWPxtgmGqKKc+RgTM63U9gN0YzrYc71R2WT/hTA=="],
"outvariant": ["[email protected]", "", {}, "sha512-+Sl2UErvtsoajRDKCE5/dBz4DIvHXQQnAxtQTF04OJxY0+DyZXSo5P5Bb7XYWOh81syohlYL24hbDwxedPUJCA=="],
"oxfmt": ["[email protected]", "", { "dependencies": { "tinypool": "2.1.0" }, "optionalDependencies": { "@oxfmt/binding-android-arm-eabi": "0.40.0", "@oxfmt/binding-android-arm64": "0.40.0", "@oxfmt/binding-darwin-arm64": "0.40.0", "@oxfmt/binding-darwin-x64": "0.40.0", "@oxfmt/binding-freebsd-x64": "0.40.0", "@oxfmt/binding-linux-arm-gnueabihf": "0.40.0", "@oxfmt/binding-linux-arm-musleabihf": "0.40.0", "@oxfmt/binding-linux-arm64-gnu": "0.40.0", "@oxfmt/binding-linux-arm64-musl": "0.40.0", "@oxfmt/binding-linux-ppc64-gnu": "0.40.0", "@oxfmt/binding-linux-riscv64-gnu": "0.40.0", "@oxfmt/binding-linux-riscv64-musl": "0.40.0", "@oxfmt/binding-linux-s390x-gnu": "0.40.0", "@oxfmt/binding-linux-x64-gnu": "0.40.0", "@oxfmt/binding-linux-x64-musl": "0.40.0", "@oxfmt/binding-openharmony-arm64": "0.40.0", "@oxfmt/binding-win32-arm64-msvc": "0.40.0", "@oxfmt/binding-win32-ia32-msvc": "0.40.0", "@oxfmt/binding-win32-x64-msvc": "0.40.0" }, "bin": { "oxfmt": "bin/oxfmt" } }, "sha512-g0C3I7xUj4b4DcagevM9kgH6+pUHytikxUcn3/VUkvzTNaaXBeyZqb7IBsHwojeXm4mTBEC/aBjBTMVUkZwWUQ=="],
@@ -1598,8 +1587,6 @@
"rolldown-plugin-dts": ["[email protected]", "", { "dependencies": { "@babel/generator": "8.0.0-rc.2", "@babel/helper-validator-identifier": "8.0.0-rc.2", "@babel/parser": "8.0.0-rc.2", "@babel/types": "8.0.0-rc.2", "ast-kit": "^3.0.0-beta.1", "birpc": "^4.0.0", "dts-resolver": "^2.1.3", "get-tsconfig": "^4.13.6", "obug": "^2.1.1" }, "peerDependencies": { "@ts-macro/tsc": "^0.3.6", "@typescript/native-preview": ">=7.0.0-dev.20250601.1", "rolldown": "^1.0.0-rc.3", "typescript": "^5.0.0 || ^6.0.0-beta", "vue-tsc": "~3.2.0" }, "optionalPeers": ["@ts-macro/tsc", "@typescript/native-preview", "typescript", "vue-tsc"] }, "sha512-M/HXfM4cboo+jONx9Z0X+CUf3B5tCi7ni+kR5fUW50Fp9AlZk0oVLesibGWgCXDKFp5lpgQ9yhKoImUFjl3VZw=="],
"run-applescript": ["[email protected]", "", {}, "sha512-DPe5pVFaAsinSaV6QjQ6gdiedWDcRCbUuiQfQa2wmWV7+xC9bGulGI8+TdRmoFkAPaBXk8CrAbnlY2ISniJ47Q=="],
"rxjs": ["[email protected]", "", { "dependencies": { "tslib": "^2.1.0" } }, "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA=="],
"sax": ["[email protected]", "", {}, "sha512-21IYA3Q5cQf089Z6tgaUTr7lDAyzoTPx5HRtbhsME8Udispad8dC/+sziTNugOEx54ilvatQ9YCzl4KQLPcRHA=="],
@@ -1856,8 +1843,6 @@
"ws": ["[email protected]", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-blAT2mjOEIi0ZzruJfIhb3nps74PRWTCz1IjglWEEpQl5XS/UNama6u2/rjFkDDouqr4L67ry+1aGIALViWjDg=="],
"wsl-utils": ["[email protected]", "", { "dependencies": { "is-wsl": "^3.1.0" } }, "sha512-h3Fbisa2nKGPxCpm89Hk33lBLsnaGBvctQopaBSOW/uIs6FTe1ATyAnKFJrzVs9vpGdsTe73WF3V4lIsk4Gacw=="],
"xxhash-wasm": ["[email protected]", "", {}, "sha512-147y/6YNh+tlp6nd/2pWq38i9h6mz/EuQ6njIrmW8D1BS5nCqs0P6DG+m6zTGnNz5I+uhZ0SHxBs9BsPrwcKDA=="],
"y18n": ["[email protected]", "", {}, "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA=="],