# Files changed · PR \#9576 · pingdotgg/t3code

[View on GitCafe](https://git.cafe/pingdotgg/t3code/pull/9576/diffs)

Repository: [pingdotgg/t3code](https://git.cafe/pingdotgg/t3code)

Visibility: public

[test\(server\): make Windows path and async fixtures deterministic](https://git.cafe/pingdotgg/t3code/pull/9576.md)

Version: 3

Head commit: 3bcea0a97064d223537fb84e50f6f67a7c7b8869

Base commit: 2c64068e10a194c8d8732a046147b9f240a4104a

Comparison base: 2c64068e10a194c8d8732a046147b9f240a4104a

Showing up to 20 entries from this revision. If the pull request changes, reopen the first page before continuing.

## apps/server/src/bootstrap.test.ts

Status: modified; +21; −11

```diff
@@ -57,6 +57,22 @@
 
 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 @@
         `${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 @@
       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 @@
     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 @@
       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 @@
 
         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, {
```

## apps/server/src/cli/config.test.ts

Status: modified; +15; −4

```diff
@@ -60,7 +60,16 @@
     yield* fs.writeFileString(filePath, `${encoded}\n`);
     return yield* Effect.acquireRelease(
       Effect.sync(() => NodeFS.openSync(filePath, "r")),
+      // 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;
+          }
+        }),
-      (fd) => Effect.sync(() => NodeFS.closeSync(fd)),
     );
   });
 
@@ -281,13 +290,15 @@
 
   it.effect("uses bootstrap envelope values as fallbacks when flags and env are absent", () =>
     Effect.gen(function* () {
+      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 { join } = yield* Path.Path;
-      const baseDir = "/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,
```

## apps/server/src/cloud/bootService.test.ts

Status: modified; +6; −3

```diff
@@ -529,11 +529,14 @@
   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(
+          path.join("Library", "LaunchAgents", "com.t3tools.t3code.service.plist"),
+        ),
-      expect(plan.unitPath.endsWith("Library/LaunchAgents/com.t3tools.t3code.service.plist")).toBe(
-        true,
-      );
+      ).toBe(true);
       expect(yield* fs.readFileString(plan.unitPath)).toContain(
         `    <key>PATH</key>\n    <string>${macInstallerPath}:/usr/local/bin:/usr/sbin:/sbin</string>`,
       );
```

## apps/server/src/provider/Layers/AntigravityAdapter.test.ts

Status: modified; +2; −1

```diff
@@ -421,7 +421,8 @@
         modelSelection: { instanceId, model: nativeAlternative },
       });
       expect(second.model).toBe(nativeAlternative);
+      // The adapter resolves the cwd it was given through the host Path.
+      expect(second.cwd).toBe((yield* Path.Path).resolve("/tmp"));
-      expect(second.cwd).toBe("/tmp");
       expect(h.launches[1]?.resumeSessionId).toBe(nativeSessionId);
       expect(h.calls).toEqual([
         "start",
```

## apps/server/src/provider/Layers/ProviderInstanceRegistryLive.test.ts

Status: modified; +13; −4

```diff
@@ -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 @@
       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 @@
       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);
```

## apps/server/src/provider/Layers/ProviderRegistry.test.ts

Status: modified; +32; −31

```diff
@@ -3,6 +3,7 @@
 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";
@@ -345,6 +346,21 @@
     } satisfies ServerSettingsModule.ServerSettingsService["Service"];
   });
 }
+
+// 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",
@@ -1752,18 +1768,10 @@
             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 @@
                 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* Fiber.join(failedPersisted);
+              cachedProvider = yield* readProviderStatusCache(filePath);
-                yield* TestClock.adjust("10 millis");
-                yield* Effect.yieldNow;
-                cachedProvider = yield* readProviderStatusCache(filePath);
-              }
 
               assert.deepStrictEqual(cachedProvider?.models, [authoritativeProvider.models[0]!]);
               assert.deepStrictEqual((yield* registry.getProviders)[0]?.models, [
@@ -2715,9 +2715,10 @@
             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),
+            [(yield* Path.Path).resolve(claudeConfigDir)],
-            [claudeConfigDir],
           );
         }).pipe(Effect.provide(recorded.layer));
       });
```

## apps/server/src/server.test.ts

Status: modified; +10; −1

```diff
@@ -1855,12 +1855,18 @@
       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 @@
             ),
         open: (filePath, options) =>
           fileSystem
+            .open(
+              filePath === afterOpenPath && windowsHost ? afterOpenSnapshotPath : filePath,
+              options,
-            .open(filePath, options)
+            )
             .pipe(
               Effect.tap(() => (filePath === afterOpenPath ? replaceOnce(filePath) : Effect.void)),
             ),
```

## apps/server/src/sourceControl/SourceControlRepositoryService.test.ts

Status: modified; +3; −1

```diff
@@ -3,6 +3,7 @@
 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("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* () {
```

## apps/server/src/workspace/WorkspaceFileSystem.test.ts

Status: modified; +23; −19

```diff
@@ -14,6 +14,7 @@
 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 @@
       }),
     );
 
+    // 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;
-    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(),
+          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 })
-        const error = yield* workspaceFileSystem
-          .readFile({ cwd, relativePath: fifoPath })
-          .pipe(Effect.flip);
+            .pipe(Effect.flip);
 
+          expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspacePathNotFileError);
+        }),
-        expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspacePathNotFileError);
-      }),
     );
 
     it.effect("rejects reads outside the workspace root", () =>
```
