From e5cea81fea229722125b3390e29bfdcce28840e0 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 5 Mar 2026 14:50:56 -0800 Subject: [PATCH] Harden server tests for Windows and WSL interop - make fake codex test launcher cross-platform (`.cmd` + Node script, PATH delimiter aware) - stabilize git/integration temp repo behavior (`core.autocrlf=false`, retrying `rmSync` cleanup) - remove OS-fragile assertions in CLI, keybindings, and terminal manager tests --- .../OrchestrationEngineHarness.integration.ts | 3 +- .../git/Layers/CodexTextGeneration.test.ts | 110 +++++++++++------- apps/server/src/git/Layers/GitCore.test.ts | 63 ++++------ apps/server/src/keybindings.test.ts | 65 +++++++---- apps/server/src/main.test.ts | 6 +- .../Layers/CheckpointReactor.test.ts | 3 +- .../src/terminal/Layers/Manager.test.ts | 4 +- 7 files changed, 147 insertions(+), 107 deletions(-) diff --git a/apps/server/integration/OrchestrationEngineHarness.integration.ts b/apps/server/integration/OrchestrationEngineHarness.integration.ts index 45eb883c6e..9c7fae9d51 100644 --- a/apps/server/integration/OrchestrationEngineHarness.integration.ts +++ b/apps/server/integration/OrchestrationEngineHarness.integration.ts @@ -70,6 +70,7 @@ function initializeGitWorkspace(cwd: string) { runGit(cwd, ["init", "--initial-branch=main"]); runGit(cwd, ["config", "user.email", "test@example.com"]); runGit(cwd, ["config", "user.name", "Test User"]); + runGit(cwd, ["config", "core.autocrlf", "false"]); fs.writeFileSync(path.join(cwd, "README.md"), "v1\n", "utf8"); runGit(cwd, ["add", "."]); runGit(cwd, ["commit", "-m", "Initial"]); @@ -388,7 +389,7 @@ export const makeOrchestrationIntegrationHarness = Effect.gen(function* () { yield* shutdown.pipe( Effect.ensuring( Effect.sync(() => { - fs.rmSync(rootDir, { recursive: true, force: true }); + fs.rmSync(rootDir, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 }); }), ), ); diff --git a/apps/server/src/git/Layers/CodexTextGeneration.test.ts b/apps/server/src/git/Layers/CodexTextGeneration.test.ts index 9642f0b06a..494fbe26de 100644 --- a/apps/server/src/git/Layers/CodexTextGeneration.test.ts +++ b/apps/server/src/git/Layers/CodexTextGeneration.test.ts @@ -19,56 +19,78 @@ function makeFakeCodexBinary(dir: string) { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const binDir = path.join(dir, "bin"); - const codexPath = path.join(binDir, "codex"); + const launcherPath = path.join(binDir, process.platform === "win32" ? "codex.cmd" : "codex"); + const scriptPath = path.join(binDir, "codex.cjs"); yield* fs.makeDirectory(binDir, { recursive: true }); yield* fs.writeFileString( - codexPath, + scriptPath, [ - "#!/bin/sh", - 'output_path=""', - "while [ $# -gt 0 ]; do", - ' if [ "$1" = "--image" ]; then', - " shift", - ' if [ -n "$1" ]; then', - ' seen_image="1"', - " fi", - " continue", - " fi", - ' if [ "$1" = "--output-last-message" ]; then', - " shift", - ' output_path="$1"', - " fi", - " shift", - "done", - 'stdin_content="$(cat)"', - 'if [ "$T3_FAKE_CODEX_REQUIRE_IMAGE" = "1" ] && [ "$seen_image" != "1" ]; then', - ' printf "%s\\n" "missing --image input" >&2', - " exit 2", - "fi", - 'if [ -n "$T3_FAKE_CODEX_STDIN_MUST_CONTAIN" ]; then', - ' printf "%s" "$stdin_content" | grep -F -- "$T3_FAKE_CODEX_STDIN_MUST_CONTAIN" >/dev/null || {', - ' printf "%s\\n" "stdin missing expected content" >&2', - " exit 3", + 'const fs = require("node:fs");', + "", + "async function readStdin() {", + " const chunks = [];", + " for await (const chunk of process.stdin) {", + " chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));", " }", - "fi", - 'if [ -n "$T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN" ]; then', - ' if printf "%s" "$stdin_content" | grep -F -- "$T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN" >/dev/null; then', - ' printf "%s\\n" "stdin contained forbidden content" >&2', - " exit 4", - " fi", - "fi", - 'if [ -n "$T3_FAKE_CODEX_STDERR" ]; then', - ' printf "%s\\n" "$T3_FAKE_CODEX_STDERR" >&2', - "fi", - 'if [ -n "$output_path" ]; then', - ' node -e \'const fs=require("node:fs"); const value=process.argv[2] ?? ""; fs.writeFileSync(process.argv[1], Buffer.from(value, "base64"));\' "$output_path" "${T3_FAKE_CODEX_OUTPUT_B64:-e30=}"', - "fi", - 'exit "${T3_FAKE_CODEX_EXIT_CODE:-0}"', + ' return Buffer.concat(chunks).toString("utf8");', + "}", + "", + "(async () => {", + ' let outputPath = "";', + " let seenImage = false;", + " for (let index = 2; index < process.argv.length; index += 1) {", + " const arg = process.argv[index];", + ' if (arg === "--image") {', + " const imagePath = process.argv[index + 1];", + " if (imagePath) {", + " seenImage = true;", + " index += 1;", + " }", + " continue;", + " }", + ' if (arg === "--output-last-message") {', + ' outputPath = process.argv[index + 1] ?? "";', + " index += 1;", + " }", + " }", + " const stdinContent = await readStdin();", + ' if (process.env.T3_FAKE_CODEX_REQUIRE_IMAGE === "1" && !seenImage) {', + ' process.stderr.write("missing --image input\\n");', + " process.exit(2);", + " }", + " const mustContain = process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN;", + ' if (mustContain && !stdinContent.includes(mustContain)) {', + ' process.stderr.write("stdin missing expected content\\n");', + " process.exit(3);", + " }", + " const mustNotContain = process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN;", + ' if (mustNotContain && stdinContent.includes(mustNotContain)) {', + ' process.stderr.write("stdin contained forbidden content\\n");', + " process.exit(4);", + " }", + " if (process.env.T3_FAKE_CODEX_STDERR) {", + ' process.stderr.write(`${process.env.T3_FAKE_CODEX_STDERR}\\n`);', + " }", + " if (outputPath) {", + ' fs.writeFileSync(outputPath, Buffer.from(process.env.T3_FAKE_CODEX_OUTPUT_B64 ?? "e30=", "base64"));', + " }", + ' process.exit(Number(process.env.T3_FAKE_CODEX_EXIT_CODE ?? "0"));', + "})().catch((error) => {", + ' process.stderr.write(`${error instanceof Error ? error.message : String(error)}\\n`);', + " process.exit(1);", + "});", "", ].join("\n"), ); - yield* fs.chmod(codexPath, 0o755); + + yield* fs.writeFileString( + launcherPath, + process.platform === "win32" + ? `@echo off\r\n"${process.execPath}" "${scriptPath}" %*\r\n` + : `#!/bin/sh\nexec "${process.execPath}" "${scriptPath}" "$@"\n`, + ); + yield* fs.chmod(launcherPath, 0o755); return binDir; }); } @@ -96,9 +118,11 @@ function withFakeCodexEnv( const previousRequireImage = process.env.T3_FAKE_CODEX_REQUIRE_IMAGE; const previousStdinMustContain = process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN; const previousStdinMustNotContain = process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN; + const pathDelimiter = process.platform === "win32" ? ";" : ":"; yield* Effect.sync(() => { - process.env.PATH = `${binDir}:${previousPath ?? ""}`; + process.env.PATH = + previousPath && previousPath.length > 0 ? `${binDir}${pathDelimiter}${previousPath}` : binDir; process.env.T3_FAKE_CODEX_OUTPUT_B64 = Buffer.from(input.output, "utf8").toString("base64"); if (input.exitCode !== undefined) { diff --git a/apps/server/src/git/Layers/GitCore.test.ts b/apps/server/src/git/Layers/GitCore.test.ts index 0c0e914032..900d3218ff 100644 --- a/apps/server/src/git/Layers/GitCore.test.ts +++ b/apps/server/src/git/Layers/GitCore.test.ts @@ -1,17 +1,18 @@ -import { existsSync } from "node:fs"; +import { existsSync, mkdtempSync, rmSync } from "node:fs"; +import os from "node:os"; import path from "node:path"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { it } from "@effect/vitest"; -import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect"; -import { describe, expect, vi } from "vitest"; +import { Effect, FileSystem, Layer, PlatformError } from "effect"; +import { afterEach, describe, expect, vi } from "vitest"; import { GitServiceLive } from "./GitService.ts"; import { GitService, type GitServiceShape } from "../Services/GitService.ts"; import { GitCoreLive } from "./GitCore.ts"; import { GitCore, type GitCoreShape } from "../Services/GitCore.ts"; import { GitCommandError } from "../Errors.ts"; -import { type ProcessRunResult, runProcess } from "../../processRunner.ts"; +import { runProcess } from "../../processRunner.ts"; // ── Helpers ── @@ -21,13 +22,20 @@ const GitCoreTestLayer = GitCoreLive.pipe( Layer.provide(NodeServices.layer), ); const TestLayer = Layer.mergeAll(NodeServices.layer, GitServiceTestLayer, GitCoreTestLayer); +const tempDirs = new Set(); -function makeTmpDir( - prefix = "git-test-", -): Effect.Effect { - return Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - return yield* fileSystem.makeTempDirectoryScoped({ prefix }); +afterEach(() => { + for (const dir of tempDirs) { + rmSync(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 }); + } + tempDirs.clear(); +}); + +function makeTmpDir(prefix = "git-test-"): Effect.Effect { + return Effect.sync(() => { + const dir = mkdtempSync(path.join(os.tmpdir(), prefix)); + tempDirs.add(dir); + return dir; }); } @@ -60,31 +68,6 @@ function git( }); } -function runShellCommand(input: { - command: string; - cwd: string; - timeoutMs?: number; - maxOutputBytes?: number; -}): Effect.Effect { - return Effect.promise(() => { - const shellPath = - process.platform === "win32" - ? (process.env.ComSpec ?? "cmd.exe") - : (process.env.SHELL ?? "/bin/sh"); - - const args = - process.platform === "win32" ? ["/d", "/s", "/c", input.command] : ["-lc", input.command]; - - return runProcess(shellPath, args, { - cwd: input.cwd, - timeoutMs: input.timeoutMs ?? 30_000, - allowNonZeroExit: true, - maxBufferBytes: input.maxOutputBytes ?? 1_000_000, - outputMode: "truncate", - }); - }); -} - const makeIsolatedGitCore = (gitService: GitServiceShape) => Effect.promise(async () => { const gitServiceLayer = Layer.succeed(GitService, gitService); @@ -182,6 +165,7 @@ function initRepoWithCommit( yield* initGitRepo({ cwd }); yield* git(cwd, ["config", "user.email", "test@test.com"]); yield* git(cwd, ["config", "user.name", "Test"]); + yield* git(cwd, ["config", "core.autocrlf", "false"]); yield* writeTextFile(path.join(cwd, "README.md"), "# test\n"); yield* git(cwd, ["add", "."]); yield* git(cwd, ["commit", "-m", "initial commit"]); @@ -215,12 +199,13 @@ function commitWithDate( it.layer(TestLayer)("git integration", (it) => { describe("shell process execution", () => { it.effect("caps captured output when maxOutputBytes is exceeded", () => - Effect.gen(function* () { - const result = yield* runShellCommand({ - command: `node -e "process.stdout.write('x'.repeat(2000))"`, + Effect.promise(async () => { + const result = await runProcess(process.execPath, ["-e", "process.stdout.write('x'.repeat(2000))"], { cwd: process.cwd(), timeoutMs: 10_000, - maxOutputBytes: 128, + allowNonZeroExit: true, + maxBufferBytes: 128, + outputMode: "truncate", }); expect(result.code).toBe(0); diff --git a/apps/server/src/keybindings.test.ts b/apps/server/src/keybindings.test.ts index 4a10d5816b..53f04fa844 100644 --- a/apps/server/src/keybindings.test.ts +++ b/apps/server/src/keybindings.test.ts @@ -17,22 +17,46 @@ import { } from "./keybindings"; const KeybindingsConfigJson = Schema.fromJsonString(KeybindingsConfig); -const makeKeybindingsLayer = () => - KeybindingsLive.pipe( - Layer.provideMerge( - Layer.effect( - ServerConfig, - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const { join } = yield* Path.Path; - const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-server-config-test-" }); - const configPath = join(dir, "keybindings.json"); - return { keybindingsConfigPath: configPath } as ServerConfigShape; - }), - ), - ), +const makeKeybindingsLayer = (options?: { + readonly fileSystemLayer?: Layer.Layer; +}) => { + const serverConfigLayer = Layer.effect( + ServerConfig, + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const { join } = yield* Path.Path; + const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-server-config-test-" }); + const configPath = join(dir, "keybindings.json"); + return { keybindingsConfigPath: configPath } as ServerConfigShape; + }), ); + return options?.fileSystemLayer + ? KeybindingsLive.pipe( + Layer.provideMerge(options.fileSystemLayer), + Layer.provideMerge(serverConfigLayer), + ) + : KeybindingsLive.pipe(Layer.provideMerge(serverConfigLayer)); +}; + +const makeTempWriteFailingFileSystemLayer = () => + Layer.effect( + FileSystem.FileSystem, + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + return { + ...fs, + writeFileString: ((filePath: string, ...args: [string, ...unknown[]]) => + filePath.endsWith(".tmp") + ? Effect.fail(new Error("simulated temp write failure")) + : (fs.writeFileString as (...allArgs: [string, ...unknown[]]) => ReturnType)( + filePath, + ...args, + )) as typeof fs.writeFileString, + } satisfies typeof fs; + }), + ).pipe(Layer.provide(NodeServices.layer)); + const toDetailResult = (effect: Effect.Effect) => effect.pipe( Effect.mapError((error) => error.detail), @@ -392,13 +416,10 @@ it.layer(NodeServices.layer)("keybindings", (it) => { it.effect("fails when config directory is not writable", () => Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; const { keybindingsConfigPath } = yield* ServerConfig; - const { dirname } = yield* Path.Path; yield* writeKeybindingsConfig(keybindingsConfigPath, [ { key: "mod+j", command: "terminal.toggle" }, ]); - yield* fs.chmod(dirname(keybindingsConfigPath), 0o500); const result = yield* Effect.gen(function* () { const keybindings = yield* Keybindings; @@ -409,12 +430,16 @@ it.layer(NodeServices.layer)("keybindings", (it) => { }).pipe(toDetailResult); assertFailure(result, "failed to write keybindings config"); - yield* fs.chmod(dirname(keybindingsConfigPath), 0o700); - const persisted = yield* readKeybindingsConfig(keybindingsConfigPath); const persistedView = persisted.map(({ key, command }) => ({ key, command })); assert.deepEqual(persistedView, [{ key: "mod+j", command: "terminal.toggle" }]); - }).pipe(Effect.provide(makeKeybindingsLayer())), + }).pipe( + Effect.provide( + makeKeybindingsLayer({ + fileSystemLayer: makeTempWriteFailingFileSystemLayer(), + }), + ), + ), ); it.effect("caches loaded resolved config across repeated reads", () => diff --git a/apps/server/src/main.test.ts b/apps/server/src/main.test.ts index e0d794aee6..716acf13f0 100644 --- a/apps/server/src/main.test.ts +++ b/apps/server/src/main.test.ts @@ -1,4 +1,5 @@ import * as Http from "node:http"; +import path from "node:path"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it, vi } from "@effect/vitest"; import * as ConfigProvider from "effect/ConfigProvider"; @@ -25,6 +26,7 @@ const serverStart = Effect.acquireRelease( () => Effect.sync(() => stop()), ); const findAvailablePort = vi.fn((preferred: number) => Effect.succeed(preferred)); +const resolveExpectedStateDir = (value: string) => path.resolve(value); // Shared service layer used by this CLI test suite. const testLayer = Layer.mergeAll( @@ -100,7 +102,7 @@ it.layer(testLayer)("server cli", (it) => { assert.equal(resolvedConfig?.mode, "desktop"); assert.equal(resolvedConfig?.port, 4010); assert.equal(resolvedConfig?.host, "0.0.0.0"); - assert.equal(resolvedConfig?.stateDir, "/tmp/t3-cli-state"); + assert.equal(resolvedConfig?.stateDir, resolveExpectedStateDir("/tmp/t3-cli-state")); assert.equal(resolvedConfig?.devUrl?.toString(), "http://127.0.0.1:5173/"); assert.equal(resolvedConfig?.noBrowser, true); assert.equal(resolvedConfig?.authToken, "auth-secret"); @@ -135,7 +137,7 @@ it.layer(testLayer)("server cli", (it) => { assert.equal(resolvedConfig?.mode, "desktop"); assert.equal(resolvedConfig?.port, 4999); assert.equal(resolvedConfig?.host, "100.88.10.4"); - assert.equal(resolvedConfig?.stateDir, "/tmp/t3-env-state"); + assert.equal(resolvedConfig?.stateDir, resolveExpectedStateDir("/tmp/t3-env-state")); assert.equal(resolvedConfig?.devUrl?.toString(), "http://localhost:5173/"); assert.equal(resolvedConfig?.noBrowser, true); assert.equal(resolvedConfig?.authToken, "env-token"); diff --git a/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts b/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts index 25ca97b804..dbee690da6 100644 --- a/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts +++ b/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts @@ -155,6 +155,7 @@ function createGitRepository() { runGit(cwd, ["init", "--initial-branch=main"]); runGit(cwd, ["config", "user.email", "test@example.com"]); runGit(cwd, ["config", "user.name", "Test User"]); + runGit(cwd, ["config", "core.autocrlf", "false"]); fs.writeFileSync(path.join(cwd, "README.md"), "v1\n", "utf8"); runGit(cwd, ["add", "."]); runGit(cwd, ["commit", "-m", "Initial"]); @@ -209,7 +210,7 @@ describe("CheckpointReactor", () => { while (tempDirs.length > 0) { const dir = tempDirs.pop(); if (dir) { - fs.rmSync(dir, { recursive: true, force: true }); + fs.rmSync(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 }); } } }); diff --git a/apps/server/src/terminal/Layers/Manager.test.ts b/apps/server/src/terminal/Layers/Manager.test.ts index 79c09f1727..92bc452339 100644 --- a/apps/server/src/terminal/Layers/Manager.test.ts +++ b/apps/server/src/terminal/Layers/Manager.test.ts @@ -575,7 +575,9 @@ describe("TerminalManager", () => { expect(snapshot.status).toBe("running"); expect(ptyAdapter.spawnInputs.length).toBeGreaterThanOrEqual(2); - expect(ptyAdapter.spawnInputs[0]?.shell).toBe("/definitely/missing-shell"); + expect(ptyAdapter.spawnInputs[0]?.shell).toBe( + process.platform === "win32" ? "/definitely/missing-shell -l" : "/definitely/missing-shell", + ); if (process.platform === "win32") { expect(