Compare commits

..
Author SHA1 Message Date
Cursor Agent b3ce952ec9 fix: use Effect.ignore instead of Effect.asVoid in killDirectChild to prevent SIGKILL phase short-circuit
Effect.asVoid only discards the success value but does not suppress errors.
When child.kill fails (e.g., child already exited), the error propagates
through Effect.all, causing the SIGTERM phase to fail and short-circuiting
the SIGKILL escalation phase. This leaves orphaned serve processes alive.

Effect.ignore both discards the value and suppresses errors, making
killDirectChild infallible and allowing the full kill chain to complete.
Also fix the same issue in the Windows path of killOpenCodeProcessGroup.
2026-05-12 13:47:44 +00:00
Julius Marminge b538723e98 Harden OpenCode probe teardown and cleanup
- keep successful provider refreshes when probe scope teardown fails
- terminate stray matching `opencode serve` processes alongside the child
2026-05-12 06:33:08 -07:00
7 changed files with 254 additions and 176 deletions

No files matched your search

+3 -49
View File
@@ -3,12 +3,8 @@ 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,
@@ -17,22 +13,6 @@ 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* () {
@@ -498,36 +478,13 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
});
it.layer(NodeServices.layer)("launchDetached", (it) => {
it.effect("resolves when command can be spawned through ChildProcessSpawner", () =>
it.effect("resolves when command can be spawned", () =>
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.provide(spawnerLayer), Effect.result);
}).pipe(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)"]);
}),
);
@@ -536,10 +493,7 @@ it.layer(NodeServices.layer)("launchDetached", (it) => {
const result = yield* launchDetached({
command: `t3code-no-such-command-${yield* Random.nextUUIDv4}`,
args: [],
}).pipe(
Effect.provide(Layer.mock(ChildProcessSpawner.ChildProcessSpawner)({})),
Effect.result,
);
}).pipe(Effect.result);
assert.equal(result._tag, "Failure");
}),
);
+32 -31
View File
@@ -1,3 +1,4 @@
// @effect-diagnostics nodeBuiltinImport:off
/**
* Open - Browser/editor launch service interface.
*
@@ -6,12 +7,13 @@
*
* @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
@@ -189,34 +191,38 @@ export const launchDetached = (launch: EditorLaunch) =>
return yield* new OpenError({ message: `Editor command not found: ${launch.command}` });
}
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",
},
),
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,
},
);
yield* Effect.asVoid(child.unref);
}),
).pipe(
Effect.mapError(
(cause) => new OpenError({ message: "failed to spawn detached process", cause }),
),
);
} 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 }))),
);
});
});
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 }),
@@ -228,12 +234,7 @@ 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), (launch) =>
launchDetached(launch).pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
),
),
openInEditor: (input) => Effect.flatMap(resolveEditorLaunch(input), launchDetached),
} satisfies OpenShape;
});
@@ -34,6 +34,7 @@ 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: {} },
@@ -44,6 +45,7 @@ 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: {} },
@@ -64,6 +66,9 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = {
yield* Effect.addFinalizer(() =>
Effect.sync(() => {
runtimeMock.state.closeCalls += 1;
if (runtimeMock.state.closeError) {
throw runtimeMock.state.closeError;
}
}),
);
}
@@ -201,6 +206,41 @@ 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,6 +23,7 @@ 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");
@@ -406,38 +407,34 @@ export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatu
}
const inventoryExit = yield* Effect.exit(
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) }),
),
);
}),
),
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")),
);
if (inventoryExit._tag === "Failure") {
return fallback(Cause.squash(inventoryExit.cause), version);
+118 -3
View File
@@ -273,10 +273,100 @@ 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(
@@ -360,7 +450,7 @@ const makeOpenCodeRuntime = Effect.gen(function* () {
const killOpenCodeProcessGroup = (signal: NodeJS.Signals) =>
process.platform === "win32"
? child.kill({ killSignal: signal, forceKillAfter: "1 second" }).pipe(Effect.asVoid)
? child.kill({ killSignal: signal, forceKillAfter: "1 second" }).pipe(Effect.ignore)
: Effect.sync(() => {
try {
process.kill(-Number(child.pid), signal);
@@ -370,9 +460,34 @@ const makeOpenCodeRuntime = Effect.gen(function* () {
// any serve process left in that group.
}
});
const terminateChild = killOpenCodeProcessGroup("SIGTERM").pipe(
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(
Effect.andThen(Effect.sleep("1 second")),
Effect.andThen(killOpenCodeProcessGroup("SIGKILL")),
Effect.andThen(
Effect.all(
[
killOpenCodeProcessGroup("SIGKILL"),
killDirectChild("SIGKILL"),
killMatchingServeProcesses("SIGKILL"),
],
{ concurrency: "unbounded", discard: true },
),
),
Effect.ignore,
);
yield* Scope.addFinalizer(runtimeScope, terminateChild);
+2 -42
View File
@@ -41,7 +41,8 @@ describe("VcsProjectConfig", () => {
yield* fileSystem.makeDirectory(nested, { recursive: true });
yield* fileSystem.writeFileString(
path.join(configDir, "vcs.json"),
'{"vcs":{"kind":"jj"}}',
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify({ vcs: { kind: "jj" } }),
);
const config = yield* VcsProjectConfig.VcsProjectConfig;
@@ -52,47 +53,6 @@ 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* () {
+30 -19
View File
@@ -2,7 +2,6 @@ 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";
@@ -16,10 +15,16 @@ const ProjectVcsConfig = Schema.Struct({
),
vcsKind: Schema.optional(VcsDriverKind),
});
type ProjectVcsConfigFile = typeof ProjectVcsConfig.Type;
const decodeProjectVcsConfigJson = Schema.decodeUnknownOption(
Schema.fromJsonString(ProjectVcsConfig),
);
const isProjectVcsConfig = Schema.is(ProjectVcsConfig);
interface ProjectVcsConfigFile {
readonly vcs?:
| {
readonly kind?: VcsDriverKindType | undefined;
}
| undefined;
readonly vcsKind?: VcsDriverKindType | undefined;
}
export interface VcsProjectConfigResolveInput {
readonly cwd: string;
@@ -40,8 +45,14 @@ function configuredKind(config: ProjectVcsConfigFile): VcsDriverKindType | "auto
return config.vcs?.kind ?? config.vcsKind ?? "auto";
}
const parseConfig = (raw: string): Option.Option<ProjectVcsConfigFile> =>
decodeProjectVcsConfigJson(raw);
function parseConfig(raw: string): ProjectVcsConfigFile | null {
try {
const parsed = JSON.parse(raw) as unknown;
return isProjectVcsConfig(parsed) ? parsed : null;
} catch {
return null;
}
}
export const make = Effect.fn("makeVcsProjectConfig")(function* () {
const fileSystem = yield* FileSystem.FileSystem;
@@ -52,12 +63,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 Option.some(candidate);
return candidate;
}
const parent = path.dirname(current);
if (parent === current) {
return Option.none();
return null;
}
current = parent;
}
@@ -67,27 +78,26 @@ 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(Option.none())),
}).pipe(Effect.as(null)),
),
);
if (Option.isNone(raw)) {
if (raw === null) {
return "auto" as const;
}
const parsed = parseConfig(raw.value);
if (Option.isNone(parsed)) {
const parsed = parseConfig(raw);
if (parsed === null) {
yield* Effect.logWarning("invalid VCS project config", {
configPath,
});
return "auto" as const;
}
return configuredKind(parsed.value);
return configuredKind(parsed);
});
const resolveKind: VcsProjectConfigShape["resolveKind"] = Effect.fn(
@@ -98,10 +108,11 @@ export const make = Effect.fn("makeVcsProjectConfig")(function* () {
}
const configPath = yield* findConfigPath(input.cwd);
return yield* Option.match(configPath, {
onNone: () => Effect.succeed("auto" as const),
onSome: readConfiguredKind,
});
if (configPath === null) {
return "auto";
}
return yield* readConfiguredKind(configPath);
});
return VcsProjectConfig.of({