test(server): make Windows path and async fixtures deterministic (#9576)

Co-authored-by: Claude Code <[email protected]>
This commit is contained in:
Julius MarmingeandClaude Code authored and GitHub committed 2026-09-04 20:33:23 +00:00
1 parent 5f4c7161fa
commit b123cbb317
9 files changed
+125 -75

No files matched your search

+21 -11
View File
@@ -57,6 +57,22 @@ vi.mock("node:fs", async (importOriginal) => {
const windowsHost = HostProcessPlatform.defaultValue() === "win32";
const nullDevice = windowsHost ? "\\\\.\\NUL" : "/dev/null";
const closeIfOpen = (fd: number) => {
try {
NodeFS.closeSync(fd);
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "EBADF") throw error;
}
};
// A successful Windows read streams the inherited fd with autoClose. POSIX
// reopens the fd through /proc or /dev, so the test still owns the original.
const openBootstrapInputFd = (filePath: string) =>
Effect.acquireRelease(
Effect.sync(() => NodeFS.openSync(filePath, "r")),
(fd) => (windowsHost ? Effect.void : Effect.sync(() => closeIfOpen(fd))),
);
const TestEnvelopeSchema = Schema.Struct({ mode: Schema.String });
const encodeTestEnvelopeSchema = Schema.encodeEffect(Schema.fromJsonString(TestEnvelopeSchema));
@@ -71,10 +87,7 @@ it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
`${yield* encodeTestEnvelopeSchema({ mode: "desktop" })}\n`,
);
const fd = yield* Effect.acquireRelease(
Effect.sync(() => NodeFS.openSync(filePath, "r")),
(fd) => Effect.sync(() => NodeFS.closeSync(fd)),
);
const fd = yield* openBootstrapInputFd(filePath);
const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, { timeoutMs: 100 });
assertSome(payload, {
@@ -119,7 +132,7 @@ it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" });
const fd = yield* Effect.acquireRelease(
Effect.sync(() => NodeFS.openSync(filePath, "r")),
(fd) => Effect.sync(() => NodeFS.closeSync(fd)),
(fd) => Effect.sync(() => closeIfOpen(fd)),
);
const fdPath = `/proc/self/fd/${fd}`;
@@ -160,7 +173,7 @@ it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
Effect.gen(function* () {
const fd = yield* Effect.acquireRelease(
Effect.sync(() => NodeFS.openSync(nullDevice, "r")),
(fd) => Effect.sync(() => NodeFS.closeSync(fd)),
(fd) => Effect.sync(() => closeIfOpen(fd)),
);
fstatSyncInterceptor.failFd = fd;
@@ -185,10 +198,7 @@ it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" });
yield* fs.writeFileString(filePath, '{"mode":42}\n');
const fd = yield* Effect.acquireRelease(
Effect.sync(() => NodeFS.openSync(filePath, "r")),
(fd) => Effect.sync(() => NodeFS.closeSync(fd)),
);
const fd = yield* openBootstrapInputFd(filePath);
const error = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, {
timeoutMs: 100,
}).pipe(Effect.flip);
@@ -228,7 +238,7 @@ it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
const fd = yield* Effect.acquireRelease(
Effect.sync(() => NodeFS.openSync(fifoPath, "r")),
(fd) => Effect.sync(() => NodeFS.closeSync(fd)),
(fd) => Effect.sync(() => closeIfOpen(fd)),
);
const fiber = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, {
+15 -4
View File
@@ -60,7 +60,16 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
yield* fs.writeFileString(filePath, `${encoded}\n`);
return yield* Effect.acquireRelease(
Effect.sync(() => NodeFS.openSync(filePath, "r")),
(fd) => Effect.sync(() => NodeFS.closeSync(fd)),
// Without a /proc or /dev/fd path to reopen, the reader consumes the fd
// itself (autoClose), so on Windows it is already closed here.
(fd) =>
Effect.sync(() => {
try {
NodeFS.closeSync(fd);
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "EBADF") throw error;
}
}),
);
});
@@ -281,13 +290,15 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
it.effect("uses bootstrap envelope values as fallbacks when flags and env are absent", () =>
Effect.gen(function* () {
const { join } = yield* Path.Path;
const baseDir = "/tmp/t3-bootstrap-home";
const { join, resolve } = yield* Path.Path;
// The resolver absolutises the configured home, so the expectation must
// carry the host's drive on Windows.
const baseDir = resolve("/tmp/t3-bootstrap-home");
const fd = yield* openBootstrapFd(
makeDesktopBootstrap({
port: 4888,
host: "127.0.0.2",
t3Home: baseDir,
t3Home: "/tmp/t3-bootstrap-home",
noBrowser: true,
desktopBootstrapToken: "desktop-token",
desktopTelemetryFd: 4,
+6 -3
View File
@@ -529,11 +529,14 @@ it.layer(NodeServices.layer)("boot service install", (it) => {
it.effect("installs, reports current state, and uninstalls on macOS", () =>
Effect.gen(function* () {
const { service, fs, statePath, commands, timeouts } = yield* makeHarness("darwin");
const path = yield* Path.Path;
const plan = yield* service.install();
expect(plan.unitPath.endsWith("Library/LaunchAgents/com.t3tools.t3code.service.plist")).toBe(
true,
);
expect(
plan.unitPath.endsWith(
path.join("Library", "LaunchAgents", "com.t3tools.t3code.service.plist"),
),
).toBe(true);
expect(yield* fs.readFileString(plan.unitPath)).toContain(
` <key>PATH</key>\n <string>${macInstallerPath}:/usr/local/bin:/usr/sbin:/sbin</string>`,
);
@@ -421,7 +421,8 @@ it.layer(layer)("AntigravityAdapter", (it) => {
modelSelection: { instanceId, model: nativeAlternative },
});
expect(second.model).toBe(nativeAlternative);
expect(second.cwd).toBe("/tmp");
// The adapter resolves the cwd it was given through the host Path.
expect(second.cwd).toBe((yield* Path.Path).resolve("/tmp"));
expect(h.launches[1]?.resumeSessionId).toBe(nativeSessionId);
expect(h.calls).toEqual([
"start",
@@ -24,6 +24,7 @@
*/
import { describe, expect, it } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Path from "effect/Path";
import {
type ClaudeSettings,
type CodexSettings,
@@ -214,15 +215,19 @@ describe("ProviderInstanceRegistryLive — multi-instance codex slice", () => {
expect(personalSnapshot.instanceId).toBe(personalId);
expect(personalSnapshot.driver).toBe(codexDriverKind);
expect(personalSnapshot.enabled).toBe(false);
// The layout resolves the configured home through the host Path.
const path = yield* Path.Path;
expect(personalSnapshot.continuation?.groupKey).toBe(
"codex:home:/home/julius/.codex_personal",
`codex:home:${path.resolve("/home/julius/.codex_personal")}`,
);
const workSnapshot = yield* work!.snapshot.getSnapshot;
expect(workSnapshot.instanceId).toBe(workId);
expect(workSnapshot.driver).toBe(codexDriverKind);
expect(workSnapshot.enabled).toBe(false);
expect(workSnapshot.continuation?.groupKey).toBe("codex:home:/home/julius/.codex");
expect(workSnapshot.continuation?.groupKey).toBe(
`codex:home:${path.resolve("/home/julius/.codex")}`,
);
// Nothing goes to the unavailable bucket — both drivers are registered.
const unavailable = yield* registry.listUnavailable;
@@ -451,13 +456,17 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => {
expect(codexSnapshot.instanceId).toBe(codexId);
expect(codexSnapshot.driver).toBe(codexDriverKind);
expect(codexSnapshot.enabled).toBe(false);
expect(codexSnapshot.continuation?.groupKey).toBe("codex:home:/home/julius/.codex");
expect(codexSnapshot.continuation?.groupKey).toBe(
`codex:home:${(yield* Path.Path).resolve("/home/julius/.codex")}`,
);
const claudeSnapshot = yield* claude!.snapshot.getSnapshot;
expect(claudeSnapshot.instanceId).toBe(claudeId);
expect(claudeSnapshot.driver).toBe(claudeDriverKind);
expect(claudeSnapshot.enabled).toBe(false);
expect(claudeSnapshot.continuation?.groupKey).toBe("claude:home:/home/julius/.claude-work");
expect(claudeSnapshot.continuation?.groupKey).toBe(
`claude:home:${(yield* Path.Path).resolve("/home/julius/.claude-work")}`,
);
const cursorSnapshot = yield* cursor!.snapshot.getSnapshot;
expect(cursorSnapshot.instanceId).toBe(cursorId);
@@ -3,6 +3,7 @@ import { describe, it, assert } from "@effect/vitest";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Path from "effect/Path";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
@@ -346,6 +347,21 @@ function makeMutableServerSettingsService(
});
}
// The registry writes the status cache and only then publishes the change, so
// a subscriber that sees `checkedAt` on the stream knows the file is on disk.
// Subscribed before the publish that triggers it; a spin on the file would
// race the write and lose on a slow host.
const awaitPersistedProvider = (
registry: ProviderRegistry.ProviderRegistry["Service"],
checkedAt: string,
) =>
registry.streamChanges.pipe(
Stream.filter((providers) => providers.some((provider) => provider.checkedAt === checkedAt)),
Stream.take(1),
Stream.runDrain,
Effect.forkScoped,
);
it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), TestHttpClientLive))(
"ProviderRegistry",
(it) => {
@@ -1752,18 +1768,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
assert.deepStrictEqual((yield* registry.getProviders)[0]?.models, [
...initialProvider.models,
]);
const persisted = yield* awaitPersistedProvider(registry, refreshedProvider.checkedAt);
yield* PubSub.publish(changes, refreshedProvider);
let cachedProvider = yield* readProviderStatusCache(filePath);
for (
let attempt = 0;
attempt < 50 && cachedProvider?.checkedAt !== refreshedProvider.checkedAt;
attempt += 1
) {
yield* TestClock.adjust("10 millis");
yield* Effect.yieldNow;
cachedProvider = yield* readProviderStatusCache(filePath);
}
yield* Fiber.join(persisted);
const cachedProvider = yield* readProviderStatusCache(filePath);
assert.deepStrictEqual(cachedProvider, {
...refreshedProvider,
@@ -1878,31 +1886,23 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
instanceId: openCodeInstanceId,
});
const authoritativePersisted = yield* awaitPersistedProvider(
registry,
authoritativeProvider.checkedAt,
);
yield* PubSub.publish(changes, authoritativeProvider);
yield* Fiber.join(authoritativePersisted);
let cachedProvider = yield* readProviderStatusCache(filePath);
for (
let attempt = 0;
attempt < 50 && cachedProvider?.checkedAt !== authoritativeProvider.checkedAt;
attempt += 1
) {
yield* TestClock.adjust("10 millis");
yield* Effect.yieldNow;
cachedProvider = yield* readProviderStatusCache(filePath);
}
assert.deepStrictEqual(cachedProvider?.models, [authoritativeProvider.models[0]!]);
const failedPersisted = yield* awaitPersistedProvider(
registry,
failedProvider.checkedAt,
);
yield* PubSub.publish(changes, failedProvider);
for (
let attempt = 0;
attempt < 50 && cachedProvider?.checkedAt !== failedProvider.checkedAt;
attempt += 1
) {
yield* TestClock.adjust("10 millis");
yield* Effect.yieldNow;
cachedProvider = yield* readProviderStatusCache(filePath);
}
yield* Fiber.join(failedPersisted);
cachedProvider = yield* readProviderStatusCache(filePath);
assert.deepStrictEqual(cachedProvider?.models, [authoritativeProvider.models[0]!]);
assert.deepStrictEqual((yield* registry.getProviders)[0]?.models, [
@@ -2715,9 +2715,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
claudeCapabilities(),
);
assert.strictEqual(status.status, "ready");
// The home is resolved through the host Path before it reaches the env.
assert.deepStrictEqual(
recorded.commands.map((command) => command.env?.CLAUDE_CONFIG_DIR),
[claudeConfigDir],
[(yield* Path.Path).resolve(claudeConfigDir)],
);
}).pipe(Effect.provide(recorded.layer));
});
+10 -1
View File
@@ -1855,12 +1855,18 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
const staticDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-static-replace-" });
const beforeOpenPath = path.join(staticDir, "before-open.txt");
const afterOpenPath = path.join(staticDir, "after-open.txt");
const afterOpenSnapshotPath = path.join(staticDir, "after-open-snapshot.txt");
const windowsHost = HostProcessPlatform.defaultValue() === "win32";
const original = "original bytes";
const replacement = "replacement bytes with a different size";
for (const filePath of [beforeOpenPath, afterOpenPath]) {
yield* fileSystem.writeFileString(filePath, original);
yield* fileSystem.writeFileString(`${filePath}.next`, replacement);
}
if (windowsHost) {
// Windows cannot replace an open destination, so model the race with its original handle.
yield* fileSystem.writeFileString(afterOpenSnapshotPath, original);
}
const replaced = new Set<string>();
const replaceOnce = Effect.fnUntraced(function* (filePath: string) {
if (replaced.has(filePath)) return;
@@ -1877,7 +1883,10 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
),
open: (filePath, options) =>
fileSystem
.open(filePath, options)
.open(
filePath === afterOpenPath && windowsHost ? afterOpenSnapshotPath : filePath,
options,
)
.pipe(
Effect.tap(() => (filePath === afterOpenPath ? replaceOnce(filePath) : Effect.void)),
),
@@ -3,6 +3,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as Layer from "effect/Layer";
import * as PlatformError from "effect/PlatformError";
import { ChildProcessSpawner } from "effect/unstable/process";
@@ -153,10 +154,11 @@ it.effect("preserves provider failures without deriving the repository message f
it.effect("clones a looked-up repository into the requested destination", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const parent = yield* fs.makeTempDirectoryScoped({
prefix: "t3-source-control-clone-parent-",
});
const destinationPath = `${parent}/t3code`;
const destinationPath = path.join(parent, "t3code");
const cloneCalls: Array<{ cwd: string; args: ReadonlyArray<string> }> = [];
yield* Effect.gen(function* () {
@@ -14,6 +14,7 @@ import * as VcsProcess from "../vcs/VcsProcess.ts";
import * as WorkspaceEntries from "./WorkspaceEntries.ts";
import * as WorkspaceFileSystem from "./WorkspaceFileSystem.ts";
import * as WorkspacePaths from "./WorkspacePaths.ts";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
const ProjectLayer = WorkspaceFileSystem.layer.pipe(
@@ -100,28 +101,31 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
}),
);
it.effect("rejects a FIFO without blocking on open", () =>
Effect.gen(function* () {
const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
const path = yield* Path.Path;
const cwd = yield* makeTempDir;
const outsideDir = yield* makeTempDir;
const fifoPath = path.join(outsideDir, "pipe");
yield* Effect.promise(
() =>
new Promise<void>((resolve, reject) =>
NodeChildProcess.execFile("mkfifo", [fifoPath], (error) =>
error ? reject(error) : resolve(),
// Needs mkfifo; Windows has no FIFOs to reject.
it.effect.skipIf(HostProcessPlatform.defaultValue() === "win32")(
"rejects a FIFO without blocking on open",
() =>
Effect.gen(function* () {
const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
const path = yield* Path.Path;
const cwd = yield* makeTempDir;
const outsideDir = yield* makeTempDir;
const fifoPath = path.join(outsideDir, "pipe");
yield* Effect.promise(
() =>
new Promise<void>((resolve, reject) =>
NodeChildProcess.execFile("mkfifo", [fifoPath], (error) =>
error ? reject(error) : resolve(),
),
),
),
);
);
const error = yield* workspaceFileSystem
.readFile({ cwd, relativePath: fifoPath })
.pipe(Effect.flip);
const error = yield* workspaceFileSystem
.readFile({ cwd, relativePath: fifoPath })
.pipe(Effect.flip);
expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspacePathNotFileError);
}),
expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspacePathNotFileError);
}),
);
it.effect("rejects reads outside the workspace root", () =>