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
4 changed files with 141 additions and 67 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;
});
+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({