diff --git a/tests/process-global/setupConfigurationConflicts.test.ts b/tests/process-global/setupConfigurationConflicts.test.ts index 9eb25813ce..b2de5bc908 100644 --- a/tests/process-global/setupConfigurationConflicts.test.ts +++ b/tests/process-global/setupConfigurationConflicts.test.ts @@ -9,9 +9,9 @@ import { symlink, writeFile, } from "node:fs/promises"; -import { join, relative } from "node:path"; +import { join } from "node:path"; import { afterEach, expect, it, vi } from "vitest"; -import { phaseGate } from "../support/lifecycleHarness.js"; +import { phaseArrival, phaseGate } from "../support/lifecycleHarness.js"; const writers = vi.hoisted(() => ({ before: undefined as undefined | ((path: string) => Promise), @@ -65,6 +65,7 @@ vi.mock("../../src/process/BoundedFileBytes.js", async (importOriginal) => { }; }); +import * as transactions from "../../src/application/ClientConfigurationTransaction.js"; import { configureClientConfiguration } from "../../src/application/SetupClientConfiguration.js"; import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js"; import { supportedClientRegistrationProfile } from "../fixtures/clientRegistrationProfile.js"; @@ -173,24 +174,6 @@ it("preserves an unrelated concurrent edit when a matching recovery backup alrea ).toEqual({ status: "unchanged" }); }); -it("does not overwrite a file created by another writer during first-run setup", async () => { - const root = await createTestTempDirectory("rea-config-first-run-conflict-"); - const path = join(root, "config.json"); - const changed = '{"theme":"light"}\n'; - writers.before = (target) => writeFile(target, changed); - - expect( - await configureClientConfiguration({ - name: "cursor", - registrationProfile: supportedClientRegistrationProfile("cursor"), - configPath: path, - format: "json", - }), - ).toMatchObject({ status: "failed", reason: "conflict" }); - expect(await readFile(path, "utf8")).toBe(changed); - expect(await readdir(root)).toEqual(["config.json"]); -}); - it("does not recreate a configuration deleted during setup", async () => { const root = await createTestTempDirectory("rea-config-deleted-"); const path = join(root, "config.json"); @@ -299,37 +282,36 @@ it.skipIf(process.platform === "win32")( }, ); -it.each(["absolute", "relative"])( - "merges queued setup requests using a %s path to the same configuration", - async (pathKind) => { - const root = await createTestTempDirectory("rea-config-queued-"); - const path = join(root, "config.json"); - const client = { - name: "cursor", - registrationProfile: supportedClientRegistrationProfile("cursor"), - configPath: path, - format: "json", - } as const; +it("merges queued setup requests through absolute and relative paths to the same file", async () => { + const root = await createTestTempDirectory("rea-config-queued-"); + const path = join(root, "config.json"); + const client = { + name: "cursor", + registrationProfile: supportedClientRegistrationProfile("cursor"), + configPath: path, + format: "json", + } as const; + const callerDirectory = process.cwd(); + process.chdir(root); + try { const results = await Promise.all([ configureClientConfiguration(client, { FIRST: "1" }), configureClientConfiguration( - { - ...client, - configPath: - pathKind === "relative" ? relative(process.cwd(), path) : path, - }, + { ...client, configPath: "./config.json" }, { SECOND: "2" }, ), ]); - - expect(results.every((result) => result.status === "configured")).toBe( - true, - ); + expect(results.map(({ status }) => status)).toEqual([ + "configured", + "configured", + ]); expect(JSON.parse(await readFile(path, "utf8"))).toMatchObject({ mcpServers: { rea: { env: { FIRST: "1", SECOND: "2" } } }, }); - }, -); + } finally { + process.chdir(callerDirectory); + } +}); it.skipIf(process.platform === "win32")( "serializes setup through a directory symlink and its real directory", @@ -347,13 +329,24 @@ it.skipIf(process.platform === "win32")( if (presence === "existing") await writeFile(realPath, "{}\n"); const entered: string[] = []; + const queued = phaseArrival(); const writer = phaseGate(); - writers.before = async (target) => { - entered.push(target); - if (entered.length === 1) { - await writer.hold(); - } - }; + writers.before = () => writer.hold(); + const withTransaction = transactions.withClientConfigurationTransaction; + let requests = 0; + const observe = vi + .spyOn(transactions, "withClientConfigurationTransaction") + .mockImplementation( + (path: string, operation: () => Promise) => { + const attempt = withTransaction(path, () => { + entered.push(path); + return operation(); + }); + // Receipt from the real owner after the queue lookup. + if (++requests === 2) queued.arrive(path); + return attempt; + }, + ); const first = configureClientConfiguration( { @@ -376,21 +369,9 @@ it.skipIf(process.platform === "win32")( }, { SECOND: "2" }, ); - const secondReachedWriter = await new Promise((resolve) => { - let giveUp: ReturnType | undefined; - const timer = setInterval(() => { - if (entered.length > 1) { - clearInterval(timer); - clearTimeout(giveUp); - resolve(true); - } - }, 15); - giveUp = setTimeout(() => { - clearInterval(timer); - resolve(false); - }, 1_000); - }); - expect(secondReachedWriter).toBe(false); + await expect( + queued.reached(second, "second configuration transaction"), + ).resolves.toBe(realPath); expect(entered).toEqual([realPath]); writer.release(); const [firstResult, secondResult] = await Promise.all([first, second]); @@ -408,6 +389,7 @@ it.skipIf(process.platform === "win32")( writer.release(); writers.before = undefined; await Promise.allSettled([first, second]); + observe.mockRestore(); } } }, diff --git a/tests/process-global/setupConfigurationRollback.test.ts b/tests/process-global/setupConfigurationRollback.test.ts index 74bc081789..0bb5f73e50 100644 --- a/tests/process-global/setupConfigurationRollback.test.ts +++ b/tests/process-global/setupConfigurationRollback.test.ts @@ -1,4 +1,4 @@ -import { open, readFile, type FileHandle } from "node:fs/promises"; +import { open, readFile, writeFile, type FileHandle } from "node:fs/promises"; import { createHash } from "node:crypto"; import { join } from "node:path"; @@ -164,105 +164,68 @@ const ownReadHandle = async (path: string) => { return owner; }; -it("reports a failed config rollback and retains its backup path", async () => { - state.readbackFailed = false; - state.rejectRestore = false; - state.initialCleanupFailure = undefined; - state.readbackCleanupFailure = undefined; - const root = await createTestTempDirectory("rea-config-rollback-"); - const path = join(root, "client.json"); - const original = '{"keep":true}\n'; - await import("node:fs/promises").then(({ writeFile }) => - writeFile(path, original), - ); - state.rejectRestore = true; +it.each([ + { state: "no previous backup", previousBackup: undefined }, + { state: "stale previous backup", previousBackup: '{"keep":"first"}\n' }, +])( + "reports the verified snapshot after failed rollback with $state", + async ({ previousBackup }) => { + const root = await createTestTempDirectory("rea-config-rollback-"); + const path = join(root, "client.json"); + const firstBackup = `${path}.rea.backup`; + const original = '{"keep":"current"}\n'; + await writeFile(path, original); + if (previousBackup !== undefined) + await writeFile(firstBackup, previousBackup); + state.rejectRestore = true; - const result = await configureClientConfiguration( - { - name: "cursor", - registrationProfile: supportedClientRegistrationProfile("cursor"), - configPath: path, - format: "json", - }, - {}, - ["rea", "mcp"], - ); + const result = await configureClientConfiguration( + { + name: "cursor", + registrationProfile: supportedClientRegistrationProfile("cursor"), + configPath: path, + format: "json", + }, + {}, + ["rea", "mcp"], + ); - expect(result).toEqual({ - status: "failed", - reason: "rollback", - backupPath: `${path}.rea.backup`, - failure: { - kind: "restore", - path, - detail: "injected restore write failure", - }, - }); - expect(await readFile(`${path}.rea.backup`, "utf8")).toBe(original); - expect(JSON.parse(await readFile(path, "utf8"))).toMatchObject({ - mcpServers: { rea: { command: "rea", args: ["mcp"] } }, - }); -}); - -it("preserves the first backup and reports a verified backup of the current original", async () => { - state.readbackFailed = false; - state.rejectRestore = false; - state.initialCleanupFailure = undefined; - state.readbackCleanupFailure = undefined; - const root = await createTestTempDirectory("rea-config-stale-backup-"); - const path = join(root, "client.json"); - const firstOriginal = '{"keep":"first"}\n'; - const currentOriginal = '{"keep":"current"}\n'; - await import("node:fs/promises").then(async ({ writeFile }) => { - await writeFile(path, currentOriginal); - await writeFile(`${path}.rea.backup`, firstOriginal); - }); - state.rejectRestore = true; - - const result = await configureClientConfiguration( - { - name: "cursor", - registrationProfile: supportedClientRegistrationProfile("cursor"), - configPath: path, - format: "json", - }, - {}, - ["rea", "mcp"], - ); - state.rejectRestore = false; - - const recoveryPath = `${path}.rea.backup.${createHash("sha256") - .update(currentOriginal, "utf8") - .digest("hex")}.recovery`; - expect(result).toMatchObject({ - status: "failed", - reason: "rollback", - backupPath: recoveryPath, - failure: { - kind: "restore", - path, - detail: "injected restore write failure", - }, - }); - expect(await readFile(`${path}.rea.backup`, "utf8")).toBe(firstOriginal); - expect(await readFile(recoveryPath, "utf8")).toBe(currentOriginal); -}); + const backupPath = + previousBackup === undefined + ? firstBackup + : `${firstBackup}.${createHash("sha256").update(original).digest("hex")}.recovery`; + expect(result).toEqual({ + status: "failed", + reason: "rollback", + backupPath, + failure: { + kind: "restore", + path, + detail: "injected restore write failure", + }, + }); + expect(await readFile(backupPath, "utf8")).toBe(original); + if (previousBackup !== undefined) + expect(await readFile(firstBackup, "utf8")).toBe(previousBackup); + expect(JSON.parse(await readFile(path, "utf8"))).toMatchObject({ + keep: "current", + mcpServers: { rea: { command: "rea", args: ["mcp"] } }, + }); + }, +); it("does not write config when a recovery copy disappears before verification", async () => { - state.readbackFailed = false; - state.rejectRestore = false; - state.removeCopiedRecovery = false; - state.initialCleanupFailure = undefined; - state.readbackCleanupFailure = undefined; const root = await createTestTempDirectory("rea-config-vanished-recovery-"); const path = join(root, "client.json"); const firstOriginal = '{"keep":"first"}\n'; const currentOriginal = '{"keep":"current"}\n'; - await import("node:fs/promises").then(async ({ writeFile }) => { - await writeFile(path, currentOriginal); - await writeFile(`${path}.rea.backup`, firstOriginal); - }); + await writeFile(path, currentOriginal); + await writeFile(`${path}.rea.backup`, firstOriginal); state.removeCopiedRecovery = true; + let published = false; + state.afterPublication = async () => { + published = true; + }; const result = await configureClientConfiguration( { @@ -274,8 +237,7 @@ it("does not write config when a recovery copy disappears before verification", {}, ["rea", "mcp"], ); - state.removeCopiedRecovery = false; - + expect(published).toBe(false); expect(result).toEqual({ status: "failed", reason: "backup" }); expect(await readFile(path, "utf8")).toBe(currentOriginal); expect(await readFile(`${path}.rea.backup`, "utf8")).toBe(firstOriginal); @@ -1387,13 +1349,10 @@ it("first-run setup preserves a destination created during staging", async () => state.beforePublicationOpen = undefined; await fs.writeFile(path, edited); }; - expect((await runConfigurationChange("setup", root, path)).status).toBe( - "failed", - ); + const result = await runConfigurationChange("setup", root, path); expect(await fs.readFile(path, "utf8")).toBe(edited); - expect( - (await fs.readdir(root)).filter((name) => name.startsWith(".rea-config-")), - ).toEqual([]); + expect(result).toMatchObject({ status: "failed", reason: "conflict" }); + expect(await fs.readdir(root)).toEqual(["client.json"]); }); it.each(["setup", "uninstall"] as const)( @@ -1474,7 +1433,7 @@ it.each(["setup", "uninstall"] as const)( }, ); -it("first-run publication exclusively refuses a destination created after its final check", async () => { +it("first-run setup exclusively refuses a destination created after its final check", async () => { const root = await createTestTempDirectory("rea-config-exclusive-link-"); const path = join(root, "client.json"); const fs = @@ -1485,13 +1444,10 @@ it("first-run publication exclusively refuses a destination created after its fi state.beforeFirstPublication = async () => { await fs.writeFile(path, edited); }; - await expect( - ClientConfigurationPublication.write(path, "{}", undefined), - ).rejects.toMatchObject({ code: "EEXIST" }); + const result = await runConfigurationChange("setup", root, path); expect(await fs.readFile(path, "utf8")).toBe(edited); - expect( - (await fs.readdir(root)).filter((name) => name.startsWith(".rea-config-")), - ).toEqual([]); + expect(result).toMatchObject({ status: "failed", reason: "conflict" }); + expect(await fs.readdir(root)).toEqual(["client.json"]); }); it("publication keeps its selected canonical parent when a directory symlink is retargeted", async () => {