Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge cfd7af1464 Handle child process unref result
Co-authored-by: Julius Marminge <[email protected]>
2026-05-09 16:10:53 +00:00
Cursor AgentandJulius Marminge 91263ff1bf Fix Effect test and catch helpers
Co-authored-by: Julius Marminge <[email protected]>
2026-05-09 16:08:22 +00:00
Cursor AgentandJulius Marminge cff8c10d13 Use Effect services for open and VCS config
Co-authored-by: Julius Marminge <[email protected]>
2026-05-09 16:07:39 +00:00
7 changed files with 176 additions and 254 deletions

No files matched your search

+49 -3
View File
@@ -3,8 +3,12 @@ import { assert, it } from "@effect/vitest";
import { assertSuccess } from "@effect/vitest/utils";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Random from "effect/Random";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import {
isCommandAvailable,
@@ -13,6 +17,22 @@ import {
resolveEditorLaunch,
} from "./open.ts";
function makeOpenProcessHandle(onUnref: Effect.Effect<void> = Effect.void) {
return ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(123),
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
isRunning: Effect.succeed(false),
kill: () => Effect.void,
stdin: Sink.drain,
stdout: Stream.empty,
stderr: Stream.empty,
all: Stream.empty,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
unref: Effect.as(onUnref, Effect.void),
});
}
it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
it.effect("returns commands for command-based editors", () =>
Effect.gen(function* () {
@@ -478,13 +498,36 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
});
it.layer(NodeServices.layer)("launchDetached", (it) => {
it.effect("resolves when command can be spawned", () =>
it.effect("resolves when command can be spawned through ChildProcessSpawner", () =>
Effect.gen(function* () {
const commands: Array<ChildProcess.Command> = [];
let unrefCount = 0;
const spawnerLayer = Layer.mock(ChildProcessSpawner.ChildProcessSpawner)({
spawn: (command) =>
Effect.sync(() => {
commands.push(command);
return makeOpenProcessHandle(
Effect.sync(() => {
unrefCount += 1;
}),
);
}),
});
const result = yield* launchDetached({
command: process.execPath,
args: ["-e", "process.exit(0)"],
}).pipe(Effect.result);
}).pipe(Effect.provide(spawnerLayer), Effect.result);
assertSuccess(result, undefined);
assert.equal(unrefCount, 1);
assert.lengthOf(commands, 1);
const command = commands[0] as unknown as {
readonly command: string;
readonly args: ReadonlyArray<string>;
};
assert.equal(command.command, process.execPath);
assert.deepEqual(command.args, ["-e", "process.exit(0)"]);
}),
);
@@ -493,7 +536,10 @@ it.layer(NodeServices.layer)("launchDetached", (it) => {
const result = yield* launchDetached({
command: `t3code-no-such-command-${yield* Random.nextUUIDv4}`,
args: [],
}).pipe(Effect.result);
}).pipe(
Effect.provide(Layer.mock(ChildProcessSpawner.ChildProcessSpawner)({})),
Effect.result,
);
assert.equal(result._tag, "Failure");
}),
);
+31 -32
View File
@@ -1,4 +1,3 @@
// @effect-diagnostics nodeBuiltinImport:off
/**
* Open - Browser/editor launch service interface.
*
@@ -7,13 +6,12 @@
*
* @module Open
*/
import { spawn } from "node:child_process";
import { EDITORS, OpenError, type EditorId } from "@t3tools/contracts";
import { isCommandAvailable, type CommandAvailabilityOptions } from "@t3tools/shared/shell";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
// ==============================
// Definitions
@@ -191,38 +189,34 @@ export const launchDetached = (launch: EditorLaunch) =>
return yield* new OpenError({ message: `Editor command not found: ${launch.command}` });
}
yield* Effect.callback<void, OpenError>((resume) => {
let child;
try {
const isWin32 = process.platform === "win32";
child = spawn(
launch.command,
isWin32 ? launch.args.map((a) => `"${a}"`) : [...launch.args],
{
detached: true,
stdio: "ignore",
shell: isWin32,
},
const isWin32 = process.platform === "win32";
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
yield* Effect.scoped(
Effect.gen(function* () {
const child = yield* spawner.spawn(
ChildProcess.make(
launch.command,
isWin32 ? launch.args.map((a) => `"${a}"`) : [...launch.args],
{
detached: true,
shell: isWin32,
stdin: "ignore",
stdout: "ignore",
stderr: "ignore",
},
),
);
} catch (error) {
return resume(
Effect.fail(new OpenError({ message: "failed to spawn detached process", cause: error })),
);
}
const handleSpawn = () => {
child.unref();
resume(Effect.void);
};
child.once("spawn", handleSpawn);
child.once("error", (cause) =>
resume(Effect.fail(new OpenError({ message: "failed to spawn detached process", cause }))),
);
});
yield* Effect.asVoid(child.unref);
}),
).pipe(
Effect.mapError(
(cause) => new OpenError({ message: "failed to spawn detached process", cause }),
),
);
});
const make = Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const open = yield* Effect.tryPromise({
try: () => import("open"),
catch: (cause) => new OpenError({ message: "failed to load browser opener", cause }),
@@ -234,7 +228,12 @@ const make = Effect.gen(function* () {
try: () => open.default(target),
catch: (cause) => new OpenError({ message: "Browser auto-open failed", cause }),
}),
openInEditor: (input) => Effect.flatMap(resolveEditorLaunch(input), launchDetached),
openInEditor: (input) =>
Effect.flatMap(resolveEditorLaunch(input), (launch) =>
launchDetached(launch).pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
),
),
} satisfies OpenShape;
});
@@ -34,7 +34,6 @@ const runtimeMock = {
runVersionError: null as Error | null,
versionStdout: DEFAULT_VERSION_STDOUT,
inventoryError: null as Error | null,
closeError: null as Error | null,
closeCalls: 0,
inventory: {
providerList: { connected: [] as string[], all: [] as unknown[], default: {} },
@@ -45,7 +44,6 @@ const runtimeMock = {
this.state.runVersionError = null;
this.state.versionStdout = DEFAULT_VERSION_STDOUT;
this.state.inventoryError = null;
this.state.closeError = null;
this.state.closeCalls = 0;
this.state.inventory = {
providerList: { connected: [], all: [] as unknown[], default: {} },
@@ -66,9 +64,6 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = {
yield* Effect.addFinalizer(() =>
Effect.sync(() => {
runtimeMock.state.closeCalls += 1;
if (runtimeMock.state.closeError) {
throw runtimeMock.state.closeError;
}
}),
);
}
@@ -206,41 +201,6 @@ it.layer(testLayer)("checkOpenCodeProviderStatus", (it) => {
assert.equal(runtimeMock.state.closeCalls, 1);
}),
);
it.effect("preserves a successful provider refresh when probe teardown throws", () =>
Effect.gen(function* () {
runtimeMock.state.inventory = {
providerList: {
connected: ["openai"],
all: [
{
id: "openai",
name: "OpenAI",
models: {
"gpt-5": {
id: "gpt-5",
name: "GPT-5",
variants: {},
},
},
},
],
default: {},
},
agents: [],
};
runtimeMock.state.closeError = new Error("close failed");
const snapshot = yield* checkOpenCodeProviderStatus(makeOpenCodeSettings(), process.cwd());
assert.equal(runtimeMock.state.closeCalls, 1);
assert.equal(snapshot.status, "ready");
assert.equal(
snapshot.models.some((model) => model.slug === "openai/gpt-5"),
true,
);
}),
);
});
it.layer(testLayer)("checkOpenCodeProviderStatus with configured server URL", (it) => {
@@ -23,7 +23,6 @@ import {
openCodeRuntimeErrorDetail,
type OpenCodeInventory,
} from "../opencodeRuntime.ts";
import { scopedSafeTeardown } from "./scopedSafeTeardown.ts";
import type { Agent, ProviderListResponse } from "@opencode-ai/sdk/v2";
const PROVIDER = ProviderDriverKind.make("opencode");
@@ -407,34 +406,38 @@ export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatu
}
const inventoryExit = yield* Effect.exit(
Effect.gen(function* () {
const server = yield* openCodeRuntime
.connectToOpenCodeServer({
binaryPath: openCodeSettings.binaryPath,
serverUrl: openCodeSettings.serverUrl,
environment,
})
.pipe(
Effect.mapError(
(cause) => new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),
),
);
return yield* openCodeRuntime
.loadOpenCodeInventory(
openCodeRuntime.createOpenCodeSdkClient({
baseUrl: server.url,
directory: cwd,
...(isExternalServer && openCodeSettings.serverPassword
? { serverPassword: openCodeSettings.serverPassword }
: {}),
}),
)
.pipe(
Effect.mapError(
(cause) => new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),
),
);
}).pipe(scopedSafeTeardown("opencode-provider-probe")),
Effect.scoped(
Effect.gen(function* () {
const server = yield* openCodeRuntime
.connectToOpenCodeServer({
binaryPath: openCodeSettings.binaryPath,
serverUrl: openCodeSettings.serverUrl,
environment,
})
.pipe(
Effect.mapError(
(cause) =>
new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),
),
);
return yield* openCodeRuntime
.loadOpenCodeInventory(
openCodeRuntime.createOpenCodeSdkClient({
baseUrl: server.url,
directory: cwd,
...(isExternalServer && openCodeSettings.serverPassword
? { serverPassword: openCodeSettings.serverPassword }
: {}),
}),
)
.pipe(
Effect.mapError(
(cause) =>
new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),
),
);
}),
),
);
if (inventoryExit._tag === "Failure") {
return fallback(Cause.squash(inventoryExit.cause), version);
+3 -118
View File
@@ -273,100 +273,10 @@ function ensureRuntimeError(
: new OpenCodeRuntimeError({ operation, detail, cause });
}
function commandBasename(commandPath: string): string {
return commandPath.split(/[\\/]/).at(-1) ?? commandPath;
}
function isMatchingOpenCodeServeCommand(input: {
readonly command: string;
readonly binaryPath: string;
readonly hostname: string;
readonly port: number;
}): boolean {
const executable = commandBasename(input.binaryPath);
const command = input.command;
return (
command.includes(executable) &&
/\bserve\b/.test(command) &&
command.includes(`--hostname=${input.hostname}`) &&
command.includes(`--port=${input.port}`)
);
}
const makeOpenCodeRuntime = Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const netService = yield* NetService.NetService;
const listProcessCommands: Effect.Effect<
ReadonlyArray<{ readonly pid: number; readonly command: string }>
> = Effect.gen(function* () {
const child = yield* spawner.spawn(ChildProcess.make("ps", ["-axo", "pid=,command="]));
const [stdout, code] = yield* Effect.all(
[collectStreamAsString(child.stdout), child.exitCode],
{
concurrency: "unbounded",
},
);
if (Number(code) !== 0) {
return [];
}
return stdout
.split("\n")
.flatMap((line) => {
const match = line.trim().match(/^(\d+)\s+(.+)$/);
const command = match?.[2];
if (!match || command === undefined) {
return [];
}
return [{ pid: Number(match[1]), command }];
})
.filter((entry) => Number.isInteger(entry.pid) && entry.pid > 0);
}).pipe(
Effect.scoped,
Effect.catch(() => Effect.succeed([])),
);
const terminateMatchingOpenCodeServeProcesses = (input: {
readonly binaryPath: string;
readonly hostname: string;
readonly port: number;
readonly signal: NodeJS.Signals;
}): Effect.Effect<void> => {
if (process.platform === "win32") {
return Effect.void;
}
return listProcessCommands.pipe(
Effect.flatMap((processes) =>
Effect.forEach(
processes,
(entry) => {
if (
entry.pid === process.pid ||
!isMatchingOpenCodeServeCommand({
command: entry.command,
binaryPath: input.binaryPath,
hostname: input.hostname,
port: input.port,
})
) {
return Effect.void;
}
return Effect.sync(() => {
try {
process.kill(entry.pid, input.signal);
} catch {
// The process may have exited between `ps` and `kill`.
}
});
},
{ discard: true },
),
),
Effect.ignore,
);
};
const runOpenCodeCommand: OpenCodeRuntimeShape["runOpenCodeCommand"] = (input) =>
Effect.gen(function* () {
const child = yield* spawner.spawn(
@@ -450,7 +360,7 @@ const makeOpenCodeRuntime = Effect.gen(function* () {
const killOpenCodeProcessGroup = (signal: NodeJS.Signals) =>
process.platform === "win32"
? child.kill({ killSignal: signal, forceKillAfter: "1 second" }).pipe(Effect.ignore)
? child.kill({ killSignal: signal, forceKillAfter: "1 second" }).pipe(Effect.asVoid)
: Effect.sync(() => {
try {
process.kill(-Number(child.pid), signal);
@@ -460,34 +370,9 @@ const makeOpenCodeRuntime = Effect.gen(function* () {
// any serve process left in that group.
}
});
const killDirectChild = (signal: NodeJS.Signals) =>
child.kill({ killSignal: signal, forceKillAfter: "1 second" }).pipe(Effect.ignore);
const killMatchingServeProcesses = (signal: NodeJS.Signals) =>
terminateMatchingOpenCodeServeProcesses({
binaryPath: input.binaryPath,
hostname,
port,
signal,
});
const terminateChild = Effect.all(
[
killOpenCodeProcessGroup("SIGTERM"),
killDirectChild("SIGTERM"),
killMatchingServeProcesses("SIGTERM"),
],
{ concurrency: "unbounded", discard: true },
).pipe(
const terminateChild = killOpenCodeProcessGroup("SIGTERM").pipe(
Effect.andThen(Effect.sleep("1 second")),
Effect.andThen(
Effect.all(
[
killOpenCodeProcessGroup("SIGKILL"),
killDirectChild("SIGKILL"),
killMatchingServeProcesses("SIGKILL"),
],
{ concurrency: "unbounded", discard: true },
),
),
Effect.andThen(killOpenCodeProcessGroup("SIGKILL")),
Effect.ignore,
);
yield* Scope.addFinalizer(runtimeScope, terminateChild);
+42 -2
View File
@@ -41,8 +41,7 @@ describe("VcsProjectConfig", () => {
yield* fileSystem.makeDirectory(nested, { recursive: true });
yield* fileSystem.writeFileString(
path.join(configDir, "vcs.json"),
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify({ vcs: { kind: "jj" } }),
'{"vcs":{"kind":"jj"}}',
);
const config = yield* VcsProjectConfig.VcsProjectConfig;
@@ -53,6 +52,47 @@ describe("VcsProjectConfig", () => {
);
});
it.layer(TestLayer)("ignores malformed .t3code/vcs.json files", (it) => {
it.effect("returns auto for invalid JSON", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-vcs-config-test-",
});
const configDir = path.join(root, ".t3code");
yield* fileSystem.makeDirectory(configDir, { recursive: true });
yield* fileSystem.writeFileString(path.join(configDir, "vcs.json"), "{not json");
const config = yield* VcsProjectConfig.VcsProjectConfig;
const kind = yield* config.resolveKind({ cwd: root });
assert.equal(kind, "auto");
}),
);
it.effect("returns auto for schema-invalid JSON", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-vcs-config-test-",
});
const configDir = path.join(root, ".t3code");
yield* fileSystem.makeDirectory(configDir, { recursive: true });
yield* fileSystem.writeFileString(
path.join(configDir, "vcs.json"),
'{"vcs":{"kind":"svn"}}',
);
const config = yield* VcsProjectConfig.VcsProjectConfig;
const kind = yield* config.resolveKind({ cwd: root });
assert.equal(kind, "auto");
}),
);
});
it.layer(TestLayer)("falls back to auto when no config exists", (it) => {
it.effect("returns auto", () =>
Effect.gen(function* () {
+19 -30
View File
@@ -2,6 +2,7 @@ import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
@@ -15,16 +16,10 @@ const ProjectVcsConfig = Schema.Struct({
),
vcsKind: Schema.optional(VcsDriverKind),
});
const isProjectVcsConfig = Schema.is(ProjectVcsConfig);
interface ProjectVcsConfigFile {
readonly vcs?:
| {
readonly kind?: VcsDriverKindType | undefined;
}
| undefined;
readonly vcsKind?: VcsDriverKindType | undefined;
}
type ProjectVcsConfigFile = typeof ProjectVcsConfig.Type;
const decodeProjectVcsConfigJson = Schema.decodeUnknownOption(
Schema.fromJsonString(ProjectVcsConfig),
);
export interface VcsProjectConfigResolveInput {
readonly cwd: string;
@@ -45,14 +40,8 @@ function configuredKind(config: ProjectVcsConfigFile): VcsDriverKindType | "auto
return config.vcs?.kind ?? config.vcsKind ?? "auto";
}
function parseConfig(raw: string): ProjectVcsConfigFile | null {
try {
const parsed = JSON.parse(raw) as unknown;
return isProjectVcsConfig(parsed) ? parsed : null;
} catch {
return null;
}
}
const parseConfig = (raw: string): Option.Option<ProjectVcsConfigFile> =>
decodeProjectVcsConfigJson(raw);
export const make = Effect.fn("makeVcsProjectConfig")(function* () {
const fileSystem = yield* FileSystem.FileSystem;
@@ -63,12 +52,12 @@ export const make = Effect.fn("makeVcsProjectConfig")(function* () {
while (true) {
const candidate = path.join(current, ".t3code", "vcs.json");
if (yield* fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false))) {
return candidate;
return Option.some(candidate);
}
const parent = path.dirname(current);
if (parent === current) {
return null;
return Option.none();
}
current = parent;
}
@@ -78,26 +67,27 @@ export const make = Effect.fn("makeVcsProjectConfig")(function* () {
configPath: string,
) {
const raw = yield* fileSystem.readFileString(configPath).pipe(
Effect.map(Option.some),
Effect.catch((error) =>
Effect.logWarning("failed to read VCS project config", {
configPath,
error,
}).pipe(Effect.as(null)),
}).pipe(Effect.as(Option.none())),
),
);
if (raw === null) {
if (Option.isNone(raw)) {
return "auto" as const;
}
const parsed = parseConfig(raw);
if (parsed === null) {
const parsed = parseConfig(raw.value);
if (Option.isNone(parsed)) {
yield* Effect.logWarning("invalid VCS project config", {
configPath,
});
return "auto" as const;
}
return configuredKind(parsed);
return configuredKind(parsed.value);
});
const resolveKind: VcsProjectConfigShape["resolveKind"] = Effect.fn(
@@ -108,11 +98,10 @@ export const make = Effect.fn("makeVcsProjectConfig")(function* () {
}
const configPath = yield* findConfigPath(input.cwd);
if (configPath === null) {
return "auto";
}
return yield* readConfiguredKind(configPath);
return yield* Option.match(configPath, {
onNone: () => Effect.succeed("auto" as const),
onSome: readConfiguredKind,
});
});
return VcsProjectConfig.of({