The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Tests remove their temp folders, also on Windows
Adarsh904acf535a11
diff --git a/tests/account-finish-limits.test.ts b/tests/account-finish-limits.test.tsindex f665872d..292aa7b1 100644--- a/tests/account-finish-limits.test.ts+++ b/tests/account-finish-limits.test.ts@@ -1,10 +1,9 @@-import fs from "node:fs";-import os from "node:os";import path from "node:path";import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";+import { tempDir } from "./helpers/temp-dir";vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-finish-limits-"));+const dir = tempDir("fuobe-finish-limits-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.FUOBE_PUBLIC_SIGNUP = "1";@@ -37,9 +36,6 @@ afterEach(() => {});afterAll(() => {globalThis.__fuobeTestDiskFree = undefined;- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}});const PNG = Buffer.concat([Buffer.from("89504e470d0a1a0a0000000d49484452", "hex"), Buffer.alloc(64)]);diff --git a/tests/account-gpu.test.ts b/tests/account-gpu.test.tsindex bd7cc373..b79ac993 100644--- a/tests/account-gpu.test.ts+++ b/tests/account-gpu.test.ts@@ -1,9 +1,9 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { tempDir } from "./helpers/temp-dir";-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-account-gpu-"));+const dir = tempDir("fuobe-account-gpu-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://owner-comfy.test:8188";delete process.env.FUOBE_PASSWORD;@@ -25,10 +25,6 @@ const { accountRun, OWN_GPU_ONLY } = await import("@/server/generations");const { getSetting } = await import("@/server/settings");afterAll(() => {globalThis.fetch = realFetch;- // The database stays open until the worker exits (Windows won't delete it before).- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}});const publicDns = async () => ["93.184.216.34"];diff --git a/tests/account-idol.test.ts b/tests/account-idol.test.tsindex e98867fd..da1908c5 100644--- a/tests/account-idol.test.ts+++ b/tests/account-idol.test.ts@@ -1,8 +1,6 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";import { afterAll, beforeAll, describe, expect, it } from "vitest";import { startFakeComfy, TINY_PNG, type FakeComfy } from "./helpers/fake-comfy-runner";+import { tempDir } from "./helpers/temp-dir";/*** Idol 3D under public sign-up: 3D models are closed to accounts, so an account's Idol run answers 403@@ -10,7 +8,7 @@ import { startFakeComfy, TINY_PNG, type FakeComfy } from "./helpers/fake-comfy-r* nothing reaches its GPU or fal.*/-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-account-idol-"));+const dir = tempDir("fuobe-account-idol-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://owner-comfy.test:8188";process.env.FUOBE_PUBLIC_SIGNUP = "1";@@ -49,7 +47,6 @@ afterAll(async () => {globalThis.__fuobeTestGpuPort = undefined;globalThis.__fuobeTestDiskFree = undefined;await fake.close();- fs.rmSync(dir, { recursive: true, force: true });});const post = (body: unknown) => {diff --git a/tests/account-inputs.test.ts b/tests/account-inputs.test.tsindex 4d68fc39..d8ac17a7 100644--- a/tests/account-inputs.test.ts+++ b/tests/account-inputs.test.ts@@ -1,10 +1,8 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";import { startFakeComfy, TINY_PNG, type FakeComfy } from "./helpers/fake-comfy-runner";+import { tempDir } from "./helpers/temp-dir";-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-account-inputs-"));+const dir = tempDir("fuobe-account-inputs-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://owner-comfy.test:8188";process.env.FUOBE_PUBLIC_SIGNUP = "1";@@ -41,9 +39,6 @@ afterAll(async () => {globalThis.__fuobeTestGpuPort = undefined;globalThis.__fuobeTestDiskFree = undefined;await fake.close();- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}});beforeEach(() => {resetRates();diff --git a/tests/account-keys-isolation.test.ts b/tests/account-keys-isolation.test.tsindex 79ee6c6d..e0474150 100644--- a/tests/account-keys-isolation.test.ts+++ b/tests/account-keys-isolation.test.ts@@ -1,10 +1,10 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";import { NextRequest } from "next/server";import { keysSeen, startFakeFal, startFakeReplicate, type FakeCloud } from "./helpers/fake-cloud";import { TINY_PNG } from "./helpers/fake-comfy-runner";+import { tempDir } from "./helpers/temp-dir";vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));vi.mock("next/headers", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/headers")>()), cookies: async () => ({ delete: () => {}, get: () => undefined }) }));@@ -15,7 +15,7 @@ vi.mock("next/headers", async (importOriginal) => ({ ...(await importOriginal<ty* The owner's keys are set in Settings and in the environment all along, and the stand-ins accept them, so any leak* would succeed and show in their logs. An account without a key, or whose key can't be opened, sends nothing.*/-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-keys-isolation-"));+const dir = tempDir("fuobe-keys-isolation-");process.env.FUOBE_DATA_DIR = dir;process.env.FUOBE_PUBLIC_SIGNUP = "1";process.env.COMFYUI_URL = "http://owner-comfy.test:8188";@@ -81,9 +81,6 @@ afterAll(async () => {globalThis.__fuobeTestDiskFree = undefined;await fal.close();await rep.close();- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}});beforeEach(async () => {resetRates();diff --git a/tests/account-keys-limits.test.ts b/tests/account-keys-limits.test.tsindex 9b173d9d..e63260c7 100644--- a/tests/account-keys-limits.test.ts+++ b/tests/account-keys-limits.test.ts@@ -1,8 +1,6 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";import { startFakeFal, type FakeCloud } from "./helpers/fake-cloud";+import { tempDir } from "./helpers/temp-dir";/*** Your keys: every account limit applies to runs on its own key too, before anything reaches the provider: runs at@@ -10,7 +8,7 @@ import { startFakeFal, type FakeCloud } from "./helpers/fake-cloud";*/vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-keys-limits-"));+const dir = tempDir("fuobe-keys-limits-");process.env.FUOBE_DATA_DIR = dir;process.env.FUOBE_PUBLIC_SIGNUP = "1";delete process.env.FUOBE_PASSWORD;@@ -41,9 +39,6 @@ afterAll(async () => {globalThis.__fuobeTestFalUrl = undefined;globalThis.__fuobeTestDiskFree = undefined;await fal.close();- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}});beforeEach(async () => {resetRates();diff --git a/tests/account-keys-providers.test.ts b/tests/account-keys-providers.test.tsindex ec100f29..a8535a06 100644--- a/tests/account-keys-providers.test.ts+++ b/tests/account-keys-providers.test.ts@@ -1,9 +1,7 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";import type { ModelDef, ModelRoute } from "@/lib/catalog/types";import { keysSeen, startFakeFal, startFakeReplicate, type FakeCloud } from "./helpers/fake-cloud";+import { tempDir } from "./helpers/temp-dir";/*** Your keys, at every provider call site: inside an account's work fal.ai and Replicate get that account's own key, and@@ -11,7 +9,7 @@ import { keysSeen, startFakeFal, startFakeReplicate, type FakeCloud } from "./he* account without a key send nothing at all. The owner's calls still send the owner's key. Against stand-in servers* (tests/helpers/fake-cloud.ts): no real key, no paid call.*/-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-keys-providers-"));+const dir = tempDir("fuobe-keys-providers-");process.env.FUOBE_DATA_DIR = dir;delete process.env.FUOBE_PASSWORD;// The owner's keys everywhere they can be: the environment (the fal client's own defaults too) and Settings.@@ -56,9 +54,6 @@ afterAll(async () => {globalThis.__fuobeTestReplicateUrl = undefined;await fal.close();await rep.close();- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}});beforeEach(() => {fal.log.length = 0;diff --git a/tests/account-keys-redaction.test.ts b/tests/account-keys-redaction.test.tsindex e8326c3d..2f3f7ecb 100644--- a/tests/account-keys-redaction.test.ts+++ b/tests/account-keys-redaction.test.ts@@ -1,16 +1,14 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";import { afterAll, beforeAll, describe, expect, it } from "vitest";import type { ModelDef, ModelRoute } from "@/lib/catalog/types";import { startFakeFal, startFakeReplicate, type FakeCloud } from "./helpers/fake-cloud";+import { tempDir } from "./helpers/temp-dir";/*** Your keys: a key never shows up in an error. The stand-ins here refuse with a body that repeats the request's* Authorization header (as some proxies do): the message Fuobe keeps holds neither the key nor either half of a fal.ai* key_id:key_secret. An account's refused key, or empty balance, is said the way to fix it.*/-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-keys-redaction-"));+const dir = tempDir("fuobe-keys-redaction-");process.env.FUOBE_DATA_DIR = dir;delete process.env.FUOBE_PASSWORD;@@ -46,9 +44,6 @@ afterAll(async () => {globalThis.__fuobeTestReplicateUrl = undefined;await fal.close();await rep.close();- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}});const model = { id: "m", name: "M", kind: "image", engine: "cloud", routes: [] } as unknown as ModelDef;diff --git a/tests/account-keys-routes.test.ts b/tests/account-keys-routes.test.tsindex 79499c88..9d8f895d 100644--- a/tests/account-keys-routes.test.ts+++ b/tests/account-keys-routes.test.ts@@ -1,9 +1,9 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";import { NextRequest } from "next/server";import { keysSeen, startFakeFal, startFakeReplicate, type FakeCloud } from "./helpers/fake-cloud";+import { tempDir } from "./helpers/temp-dir";/*** Settings → Your keys, the routes: an account adds, checks, replaces and removes its own fal.ai key or Replicate token.@@ -14,7 +14,7 @@ import { keysSeen, startFakeFal, startFakeReplicate, type FakeCloud } from "./hevi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));vi.mock("next/headers", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/headers")>()), cookies: async () => ({ delete: () => {}, get: () => undefined }) }));-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-keys-routes-"));+const dir = tempDir("fuobe-keys-routes-");process.env.FUOBE_DATA_DIR = dir;process.env.FUOBE_PUBLIC_SIGNUP = "1";delete process.env.FUOBE_PASSWORD;@@ -66,9 +66,6 @@ afterAll(async () => {globalThis.__fuobeTestDiskFree = undefined;await fal.close();await rep.close();- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}});beforeEach(() => {resetRates();diff --git a/tests/account-keys.test.ts b/tests/account-keys.test.tsindex d3e10407..d039e78f 100644--- a/tests/account-keys.test.ts+++ b/tests/account-keys.test.ts@@ -1,13 +1,13 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { beforeAll, describe, expect, it } from "vitest";+import { tempDir } from "./helpers/temp-dir";/*** Your keys: where an account's own fal.ai key or Replicate token is kept. Sealed on its record in auth.json, never in* plain text in any file of the data folder, shown only by its last 4 characters, gone with the account.*/-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-account-keys-"));+const dir = tempDir("fuobe-account-keys-");process.env.FUOBE_DATA_DIR = dir;delete process.env.FUOBE_PASSWORD;delete process.env.FUOBE_ENGINE_MODE;@@ -40,11 +40,6 @@ beforeAll(() => {a = auth.createAccount("[email protected]", "long enough").id;b = auth.createAccount("[email protected]", "long enough").id;});-afterAll(() => {- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}-});describe("an account's own keys, at rest", () => {it("are sealed on its record: auth.json holds the sealed value and the last 4 characters, never the key", () => {diff --git a/tests/account-kling-clips.test.ts b/tests/account-kling-clips.test.tsindex c631374b..a3b6b0e5 100644--- a/tests/account-kling-clips.test.ts+++ b/tests/account-kling-clips.test.ts@@ -1,7 +1,5 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { beforeAll, describe, expect, it } from "vitest";+import { tempDir } from "./helpers/temp-dir";/*** Kling 4.0's reference clips and clip elements (nm10-kling-4): the server reads each clip's header to price it (input@@ -9,7 +7,7 @@ import { afterAll, beforeAll, describe, expect, it } from "vitest";* check (account-inputs.ts) and storage's guard on the read (readRef) both refuse another's clip, and an account's* @mentions never pull the owner's Elements (their photos or clips) into its run.*/-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-account-kling-"));+const dir = tempDir("fuobe-account-kling-");process.env.FUOBE_DATA_DIR = dir;process.env.FUOBE_PUBLIC_SIGNUP = "1";delete process.env.FUOBE_PASSWORD;@@ -31,11 +29,6 @@ beforeAll(() => {a = auth.createAccount("[email protected]", "long enough").id;b = auth.createAccount("[email protected]", "long enough").id;});-afterAll(() => {- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}-});const CLIP = Buffer.from("not really an mp4, but a stored file");const asA = <T>(fn: () => T) => runAsTenant({ kind: "account", id: a }, fn);diff --git a/tests/account-retention.test.ts b/tests/account-retention.test.tsindex 33c6f9cf..076eeec4 100644--- a/tests/account-retention.test.ts+++ b/tests/account-retention.test.ts@@ -1,10 +1,10 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { beforeAll, describe, expect, it } from "vitest";import { TINY_PNG } from "./helpers/fake-comfy-runner";+import { tempDir } from "./helpers/temp-dir";-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-account-retention-"));+const dir = tempDir("fuobe-account-retention-");process.env.FUOBE_DATA_DIR = dir;process.env.FUOBE_PUBLIC_SIGNUP = "1";delete process.env.FUOBE_PASSWORD;@@ -15,11 +15,6 @@ const { saveFile, getAsset, absolutePath, scratchDir } = await import("@/server/const { sweepAccountFiles, purgeAccount } = await import("@/server/account-sweep");const { onAccountDeleted } = await import("@/server/account-files");const { DELETE } = await import("@/app/api/generations/[id]/route");-afterAll(() => {- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}-});const DAY = 24 * 60 * 60_000;let a = "";diff --git a/tests/account-review-fixes.test.ts b/tests/account-review-fixes.test.tsindex 50c27a0f..1c2e4ab9 100644--- a/tests/account-review-fixes.test.ts+++ b/tests/account-review-fixes.test.ts@@ -1,16 +1,16 @@import fs from "node:fs";import http from "node:http";-import os from "node:os";import path from "node:path";import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";import { startFakeComfy, TINY_PNG, type FakeComfy } from "./helpers/fake-comfy-runner";+import { tempDir } from "./helpers/temp-dir";/*** The review of "Your GPU" tools (public sign-up): each test here shows one problem the review found, and stays as the* guard against it coming back.*/-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-account-review-"));+const dir = tempDir("fuobe-account-review-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://owner-comfy.test:8188";process.env.FUOBE_PUBLIC_SIGNUP = "1";@@ -66,9 +66,6 @@ afterAll(async () => {globalThis.__fuobeTestDiskFree = undefined;globalThis.__fuobeTestDiskSize = undefined;await fake.close();- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}});beforeEach(() => {resetRates();diff --git a/tests/account-run-fairness.test.ts b/tests/account-run-fairness.test.tsindex 88793223..93b72693 100644--- a/tests/account-run-fairness.test.ts+++ b/tests/account-run-fairness.test.ts@@ -1,10 +1,8 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";import { startFakeComfy, TINY_PNG, type FakeComfy } from "./helpers/fake-comfy-runner";+import { tempDir } from "./helpers/temp-dir";-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-run-fairness-"));+const dir = tempDir("fuobe-run-fairness-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://owner-comfy.test:8188";process.env.FUOBE_PUBLIC_SIGNUP = "1";@@ -42,9 +40,6 @@ afterAll(async () => {globalThis.__fuobeTestGpuPort = undefined;globalThis.__fuobeTestDiskFree = undefined;await fake.close();- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}});const run = (image: string) => {diff --git a/tests/account-runs-admin.test.ts b/tests/account-runs-admin.test.tsindex 590f819c..b6fb7cd2 100644--- a/tests/account-runs-admin.test.ts+++ b/tests/account-runs-admin.test.ts@@ -1,17 +1,17 @@import { createHmac } from "node:crypto";import fs from "node:fs";-import os from "node:os";import path from "node:path";import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";import { NextRequest } from "next/server";import type { AccountListing, AccountRun, AccountTotals } from "@/server/account-admin";import type { ListOptions } from "@/server/generations";import { TINY_PNG } from "./helpers/fake-comfy-runner";+import { tempDir } from "./helpers/temp-dir";// Route handlers are called directly, outside a Next request: connection() has nothing to wait for.vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-account-runs-"));+const dir = tempDir("fuobe-account-runs-");process.env.FUOBE_DATA_DIR = dir;process.env.FUOBE_PUBLIC_SIGNUP = "1";process.env.COMFYUI_URL = "http://127.0.0.1:9";@@ -33,9 +33,6 @@ const filesRoute = await import("@/app/api/files/[...path]/route");const generationsRoute = await import("@/app/api/generations/route");afterAll(() => {delete process.env.FUOBE_PUBLIC_SIGNUP;- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}});const A = auth.createAccount("[email protected]", "long enough").id;diff --git a/tests/account-space-limits.test.ts b/tests/account-space-limits.test.tsindex 4e2d3a30..a70189fe 100644--- a/tests/account-space-limits.test.ts+++ b/tests/account-space-limits.test.ts@@ -1,12 +1,12 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";+import { tempDir } from "./helpers/temp-dir";const jar = { set: vi.fn(), delete: vi.fn(), get: vi.fn() };vi.mock("next/headers", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/headers")>()), cookies: async () => jar }));vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-space-limits-"));+const dir = tempDir("fuobe-space-limits-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.FUOBE_PUBLIC_SIGNUP = "1";@@ -49,9 +49,6 @@ afterEach(() => {});afterAll(() => {globalThis.__fuobeTestDiskFree = undefined;- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}});/** A result of `account` that weighs `bytes` (only its row says so). */diff --git a/tests/account-tenant.test.ts b/tests/account-tenant.test.tsindex 687d0915..bcbc42d7 100644--- a/tests/account-tenant.test.ts+++ b/tests/account-tenant.test.ts@@ -1,10 +1,8 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";import { afterAll, beforeAll, describe, expect, it } from "vitest";import { startFakeComfy, TINY_PNG, type FakeComfy } from "./helpers/fake-comfy-runner";+import { tempDir } from "./helpers/temp-dir";-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-account-tenant-"));+const dir = tempDir("fuobe-account-tenant-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://owner-comfy.test:8188";process.env.FUOBE_PUBLIC_SIGNUP = "1";@@ -44,9 +42,6 @@ afterAll(async () => {globalThis.fetch = realFetch;globalThis.__fuobeTestGpuPort = undefined;await fake.close();- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}});const asA = <T,>(fn: () => T) => runAsTenant({ kind: "account", id: a }, fn);diff --git a/tests/account-tools.test.ts b/tests/account-tools.test.tsindex 774f9318..0c0b51b2 100644--- a/tests/account-tools.test.ts+++ b/tests/account-tools.test.ts@@ -1,11 +1,10 @@import fs from "node:fs";-import os from "node:os";-import path from "node:path";import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";import { NextRequest } from "next/server";import { startFakeComfy, TINY_PNG, type FakeComfy } from "./helpers/fake-comfy-runner";+import { tempDir } from "./helpers/temp-dir";-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-account-tools-"));+const dir = tempDir("fuobe-account-tools-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://owner-comfy.test:8188";process.env.FUOBE_PUBLIC_SIGNUP = "1";@@ -58,9 +57,6 @@ afterAll(async () => {globalThis.__fuobeTestGpuPort = undefined;globalThis.__fuobeTestDiskFree = undefined;await fake.close();- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}});beforeEach(() => {resetRates();diff --git a/tests/account-uploads.test.ts b/tests/account-uploads.test.tsindex db55082f..99ae24c1 100644--- a/tests/account-uploads.test.ts+++ b/tests/account-uploads.test.ts@@ -1,11 +1,11 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";import { NextRequest } from "next/server";import { TINY_PNG } from "./helpers/fake-comfy-runner";+import { tempDir } from "./helpers/temp-dir";-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-account-uploads-"));+const dir = tempDir("fuobe-account-uploads-");process.env.FUOBE_DATA_DIR = dir;process.env.FUOBE_PUBLIC_SIGNUP = "1";delete process.env.FUOBE_PASSWORD;@@ -20,9 +20,6 @@ const { db } = await import("@/server/db");const { hit, resetRates } = await import("@/server/rate");afterAll(() => {globalThis.__fuobeTestDiskFree = undefined;- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}});let a = "";diff --git a/tests/account-voice-design.test.ts b/tests/account-voice-design.test.tsindex 198bc6ba..8e96e153 100644--- a/tests/account-voice-design.test.ts+++ b/tests/account-voice-design.test.ts@@ -1,13 +1,11 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";import { startFakeComfy, type FakeComfy } from "./helpers/fake-comfy-runner";+import { tempDir } from "./helpers/temp-dir";// Design a voice under public sign-up: an account designs and clones voices on its own GPU with its own samples. The// owner's saved voices (their take, its line, the kept fal embedding) never reach an account's run, and nothing is// fetched or stored on the owner's elements for it.-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-account-voice-"));+const dir = tempDir("fuobe-account-voice-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://owner-comfy.test:8188";process.env.FUOBE_PUBLIC_SIGNUP = "1";@@ -52,9 +50,6 @@ afterAll(async () => {globalThis.__fuobeTestGpuPort = undefined;globalThis.__fuobeTestDiskFree = undefined;await fake.close();- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}});beforeEach(() => {resetRates();diff --git a/tests/accounts-admin.test.ts b/tests/accounts-admin.test.tsindex e9137876..6b2ba1b9 100644--- a/tests/accounts-admin.test.ts+++ b/tests/accounts-admin.test.ts@@ -1,10 +1,8 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";import { afterAll, beforeAll, describe, expect, it } from "vitest";import { NextRequest } from "next/server";+import { tempDir } from "./helpers/temp-dir";-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-accounts-admin-"));+const dir = tempDir("fuobe-accounts-admin-");process.env.FUOBE_DATA_DIR = dir;process.env.FUOBE_PUBLIC_SIGNUP = "1";delete process.env.FUOBE_PASSWORD;@@ -12,9 +10,6 @@ const auth = await import("@/server/auth");const { proxy } = await import("@/proxy");afterAll(() => {delete process.env.FUOBE_PUBLIC_SIGNUP;- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}});const req = (url: string, method = "GET", cookie?: string) =>diff --git a/tests/admin-tokens.test.ts b/tests/admin-tokens.test.tsindex 0154de2f..a491a57e 100644--- a/tests/admin-tokens.test.ts+++ b/tests/admin-tokens.test.ts@@ -1,15 +1,15 @@import crypto from "node:crypto";import fs from "node:fs";-import os from "node:os";import path from "node:path";import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";import { NextRequest } from "next/server";import { TINY_PNG } from "./helpers/fake-comfy-runner";+import { tempDir } from "./helpers/temp-dir";// Route handlers are called directly, outside a Next request: connection() has nothing to wait for.vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-admin-tokens-"));+const dir = tempDir("fuobe-admin-tokens-");process.env.FUOBE_DATA_DIR = dir;process.env.FUOBE_PUBLIC_SIGNUP = "1";process.env.COMFYUI_URL = "http://127.0.0.1:9";@@ -41,9 +41,6 @@ const routes = {};afterAll(() => {delete process.env.FUOBE_PUBLIC_SIGNUP;- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}});type Scope = (typeof admin.SCOPES)[number];diff --git a/tests/any-angle-route.test.ts b/tests/any-angle-route.test.tsindex 8ddbbcfb..e48d1053 100644--- a/tests/any-angle-route.test.ts+++ b/tests/any-angle-route.test.ts@@ -1,14 +1,12 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";import { afterAll, beforeAll, describe, expect, it } from "vitest";import { TINY_PNG } from "./helpers/fake-comfy-runner";+import { tempDir } from "./helpers/temp-dir";// Any Angle through POST /api/generations: a second build of the same photo answers with the first one (running or// done) and gives the run back to the hourly count; one account never gets another's; an account may build the 3D view// on its own GPU (other 3D models wait for the server's finish).-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-any-angle-route-"));+const dir = tempDir("fuobe-any-angle-route-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.FUOBE_PUBLIC_SIGNUP = "1";@@ -38,9 +36,6 @@ beforeAll(() => {});afterAll(() => {globalThis.__fuobeTestDiskFree = undefined;- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}});const headers = (who: string, extra: Record<string, string> = {}) => ({ cookie: cookies[who], host: "localhost:3000", ...extra });diff --git a/tests/any-angle-server.test.ts b/tests/any-angle-server.test.tsindex 3db0c2dc..6c78834a 100644--- a/tests/any-angle-server.test.ts+++ b/tests/any-angle-server.test.ts@@ -1,16 +1,14 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";import sharp from "sharp";import { afterAll, describe, expect, it, vi } from "vitest";import { ANY_ANGLE, SWEEP, viewOf, wrapYaw } from "@/lib/catalog/any-angle";+import { tempDir } from "./helpers/temp-dir";// Any Angle on the server (src/server/any-angle.ts): when a 3D view's build succeeds, its front view is measured on the// turntable it rendered and kept on the splat (an angle's camera starts there); a photo's view is found again by the// photo's content for the same owner or account, never for someone else, and a build that failed is built again.vi.setConfig({ testTimeout: 60_000 });-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-any-angle-"));+const dir = tempDir("fuobe-any-angle-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";@@ -20,12 +18,6 @@ const { provider } = await import("@/server/providers");const { saveFile } = await import("@/server/storage");const { findView, viewKeyOf, requestViewKey, NO_SUBJECT_MESSAGE } = await import("@/server/any-angle");-afterAll(() => {- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}-});-/** A figure on a turntable (as in tests/any-angle.test.ts): its body's width, colour and side stripe follow the turn. */function figure(size: number, yaw: number): { rgb: Buffer; mask: Buffer } {const rgb = Buffer.alloc(size * size * 3);diff --git a/tests/assist-connectors.test.ts b/tests/assist-connectors.test.tsindex a61b243d..b91277ea 100644--- a/tests/assist-connectors.test.ts+++ b/tests/assist-connectors.test.ts@@ -1,13 +1,11 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, describe, expect, it, vi } from "vitest";+import { describe, expect, it, vi } from "vitest";import type Anthropic from "@anthropic-ai/sdk";import { claudeStream } from "./fixtures/claude-sse";+import { tempDir } from "./helpers/temp-dir";vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));vi.setConfig({ testTimeout: 60_000 });-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-assist-conn-"));+const dir = tempDir("fuobe-assist-conn-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.OLLAMA_URL = "http://127.0.0.1:9";@@ -20,7 +18,6 @@ const lib = await import("@/lib/assist-connectors");const listRoute = await import("@/app/api/assist/connectors/route");const oneRoute = await import("@/app/api/assist/connectors/[connectorId]/route");-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));const TOKEN = "sk-live-0123456789abcdef";diff --git a/tests/assist-context.test.ts b/tests/assist-context.test.tsindex 11abbdb3..e3219761 100644--- a/tests/assist-context.test.ts+++ b/tests/assist-context.test.ts@@ -1,13 +1,11 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { beforeAll, describe, expect, it, vi } from "vitest";import { claudeStream } from "./fixtures/claude-sse";import type Anthropic from "@anthropic-ai/sdk";import type { AssistItem } from "@/lib/assist";+import { tempDir } from "./helpers/temp-dir";vi.setConfig({ testTimeout: 60_000 });-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-assist-ctx-"));+const dir = tempDir("fuobe-assist-ctx-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.OLLAMA_URL = "http://127.0.0.1:9";@@ -45,7 +43,6 @@ const history = (id: string) => JSON.parse((db().prepare("SELECT messages_json Fconst sysText = (m: Param) => (typeof m.content === "string" ? m.content : m.content.map((b) => ("text" in b ? b.text : "")).join(""));beforeAll(() => setSetting("demoMode", "auto"));-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));describe("a chat's context", () => {it("freezes the system prompt at the first call and appends changes as one Context update", async () => {diff --git a/tests/assist-polish.test.ts b/tests/assist-polish.test.tsindex 170b8a79..fa7b72fe 100644--- a/tests/assist-polish.test.ts+++ b/tests/assist-polish.test.ts@@ -1,15 +1,15 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";import { NextRequest } from "next/server";import { describe, expect, it } from "vitest";import { HUB_MODES } from "@/lib/hubs";// Plain .mjs helper shared with the Playwright scripts.import { dynamicSamples, hubModePaths, querySamples, studioRoutes } from "./e2e/_routes.mjs";+import { tempDir } from "./helpers/temp-dir";const root = process.cwd();// The proxy reads the sign-in settings from the data folder: use an empty one (no password).-process.env.FUOBE_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-polish-"));+process.env.FUOBE_DATA_DIR = tempDir("fuobe-polish-");describe("/apps/<unknown> is a real 404", () => {it("the proxy rewrites unknown app ids to the not-found page with status 404", async () => {@@ -44,7 +44,7 @@ describe("the 390 px sweep visits dynamic routes", () => {});it("gives a route added later (another branch's /faceless/[id]/[episode]) a not-found sample by itself", () => {- const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-routes-"));+ const tmp = tempDir("fuobe-routes-");const page = (rel: string) => {fs.mkdirSync(path.join(tmp, "src/app/(studio)", rel), { recursive: true });fs.writeFileSync(path.join(tmp, "src/app/(studio)", rel, "page.tsx"), "export default function P() { return null; }\n");diff --git a/tests/assist-providers.test.ts b/tests/assist-providers.test.tsindex 506658c1..7eb29c38 100644--- a/tests/assist-providers.test.ts+++ b/tests/assist-providers.test.ts@@ -1,9 +1,7 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";import { afterAll, beforeEach, describe, expect, it, vi } from "vitest";import { claudeStream } from "./fixtures/claude-sse";import { fakeLlm, type FakeLlm, type Mode } from "./helpers/fake-llm";+import { tempDir } from "./helpers/temp-dir";/** Assist end to end on hosted providers, against fakes that enforce each provider's rules: Smart on an@@ -16,7 +14,7 @@ import { fakeLlm, type FakeLlm, type Mode } from "./helpers/fake-llm";vi.setConfig({ testTimeout: 60_000 });vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-assist-providers-"));+const dir = tempDir("fuobe-assist-providers-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.OLLAMA_URL = "http://127.0.0.1:9";@@ -52,9 +50,6 @@ beforeEach(disconnect);afterAll(async () => {await Promise.all(fakes.map((f) => f.close()));delete process.env.FUOBE_LLM_TEST_BASE;- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}});const job = { model_id: "nano-banana-pro", prompt: "a red fox in snow, golden hour" };diff --git a/tests/assist-runtime.test.ts b/tests/assist-runtime.test.tsindex 5488449d..107c6e6b 100644--- a/tests/assist-runtime.test.ts+++ b/tests/assist-runtime.test.ts@@ -1,12 +1,10 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { beforeAll, describe, expect, it, vi } from "vitest";import { z } from "zod";import type Anthropic from "@anthropic-ai/sdk";+import { tempDir } from "./helpers/temp-dir";vi.setConfig({ testTimeout: 60_000 });-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-assist-rt-"));+const dir = tempDir("fuobe-assist-rt-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.OLLAMA_URL = "http://127.0.0.1:9";@@ -35,7 +33,6 @@ function scripted(...turns: Msg[]) {}beforeAll(() => setSetting("demoMode", "auto"));-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));const dependsOn = (id: string) => (db().prepare("SELECT depends_on FROM generations WHERE id = ?").get(id) as { depends_on: string | null }).depends_on;diff --git a/tests/assist-schedules.test.ts b/tests/assist-schedules.test.tsindex 04ff9c2a..79e17549 100644--- a/tests/assist-schedules.test.ts+++ b/tests/assist-schedules.test.ts@@ -1,12 +1,10 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";+import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";import type Anthropic from "@anthropic-ai/sdk";+import { tempDir } from "./helpers/temp-dir";vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));vi.setConfig({ testTimeout: 60_000 });-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-assist-sched-"));+const dir = tempDir("fuobe-assist-sched-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.OLLAMA_URL = "http://127.0.0.1:9";@@ -57,7 +55,6 @@ afterEach(() => {setSetting("falKey", "");db().prepare("DELETE FROM assist_schedules").run();});-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));describe("scheduled tasks", () => {it("show a task saved with the old Ollama agent as a local-model task", () => {diff --git a/tests/assist-skill-tools.test.ts b/tests/assist-skill-tools.test.tsindex b61a523c..3d0bae27 100644--- a/tests/assist-skill-tools.test.ts+++ b/tests/assist-skill-tools.test.ts@@ -1,8 +1,8 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";import type Anthropic from "@anthropic-ai/sdk";-import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { beforeAll, describe, expect, it, vi } from "vitest";+import { tempDir } from "./helpers/temp-dir";// Route handlers call connection() (no request scope in a test).vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));@@ -13,7 +13,7 @@ vi.setConfig({ testTimeout: 120_000 });* and the offline planner through run_skill, priced on one card.*/-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-assist-skill-tools-"));+const dir = tempDir("fuobe-assist-skill-tools-");process.env.FUOBE_DATA_DIR = dir;// Nothing listens: open models run on the demo provider, and there's no LLM.process.env.COMFYUI_URL = "http://127.0.0.1:9";@@ -37,7 +37,6 @@ const { zip } = await import("@/server/zip");const { NESTED_SKILL } = await import("@/lib/recipe");const { DECLINED } = await import("@/lib/assist");-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));let photo = "";let clip = "";diff --git a/tests/assist-skills.test.ts b/tests/assist-skills.test.tsindex 8ccafcd3..e6d6f9df 100644--- a/tests/assist-skills.test.ts+++ b/tests/assist-skills.test.ts@@ -1,9 +1,9 @@import fs from "node:fs";import http from "node:http";-import os from "node:os";import path from "node:path";import zlib from "node:zlib";import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { tempDir } from "./helpers/temp-dir";import {contextUpdate,factMap,@@ -24,7 +24,7 @@ import {// Route handlers call connection() (no request scope in a test).vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-assist-skills-"));+const dir = tempDir("fuobe-assist-skills-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.OLLAMA_URL = "http://127.0.0.1:9";@@ -40,7 +40,6 @@ const { db } = await import("@/server/db");const tools = await import("@/server/assist/tools");const downloadRoute = await import("@/app/api/assist/skills/[name]/download/route");-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));const md = (fm: string, body = "# Do it\n\n1. Step one.") => `---\n${fm}\n---\n\n${body}\n`;diff --git a/tests/assist-studio-routes.test.ts b/tests/assist-studio-routes.test.tsindex a9b62f4d..72feb999 100644--- a/tests/assist-studio-routes.test.ts+++ b/tests/assist-studio-routes.test.ts@@ -1,11 +1,11 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { beforeAll, describe, expect, it, vi } from "vitest";import type Anthropic from "@anthropic-ai/sdk";+import { tempDir } from "./helpers/temp-dir";vi.setConfig({ testTimeout: 120_000 });-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-assist-studios-"));+const dir = tempDir("fuobe-assist-studios-");process.env.FUOBE_DATA_DIR = dir;// Nothing listens: open models run on the demo provider, and there's no LLM (offline writers run).process.env.COMFYUI_URL = "http://127.0.0.1:9";@@ -82,7 +82,6 @@ beforeAll(() => {clip = saveFile({ data: fs.readFileSync(fixture), contentType: "video/mp4", source: "upload", name: "beach day.mp4" }).url;notAnImage = saveFile({ data: Buffer.from("not a picture at all"), contentType: "image/png", source: "upload", name: "broken.png" }).url;});-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));const scenes = [{ narration: "Tea began as medicine in the mountains of China.", visual: "A misty mountain tea garden at dawn" },diff --git a/tests/assist-suggestions.test.ts b/tests/assist-suggestions.test.tsindex 05dce81f..7dcb2ba5 100644--- a/tests/assist-suggestions.test.ts+++ b/tests/assist-suggestions.test.ts@@ -1,10 +1,8 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { beforeAll, describe, expect, it, vi } from "vitest";+import { tempDir } from "./helpers/temp-dir";vi.setConfig({ testTimeout: 60_000 });-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-assist-sugg-"));+const dir = tempDir("fuobe-assist-sugg-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.OLLAMA_URL = "http://127.0.0.1:9";@@ -16,7 +14,6 @@ const { db } = await import("@/server/db");const { ASSIST_SUGGESTIONS } = await import("@/lib/assist");beforeAll(() => setSetting("demoMode", "auto"));-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));type Job = Record<string, unknown>;const jobsOf = (p: ReturnType<typeof agent.offlinePlan>) => ((p?.input as { jobs?: Job[] }).jobs ?? []) as Job[];diff --git a/tests/assist.test.ts b/tests/assist.test.tsindex 8d2b7749..553945d9 100644--- a/tests/assist.test.ts+++ b/tests/assist.test.ts@@ -1,11 +1,9 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { beforeAll, describe, expect, it } from "vitest";import { claudeStream } from "./fixtures/claude-sse";import type Anthropic from "@anthropic-ai/sdk";+import { tempDir } from "./helpers/temp-dir";-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-assist-"));+const dir = tempDir("fuobe-assist-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";@@ -18,7 +16,6 @@ type Msg = Anthropic.Beta.BetaMessage;type Block = Anthropic.Beta.BetaContentBlock;beforeAll(() => setSetting("demoMode", "auto"));-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));const text = (t: string) => ({ type: "text", text: t, citations: null }) as Block;const use = (id: string, name: string, input: unknown) => ({ type: "tool_use", id, name, input }) as unknown as Block;diff --git a/tests/audio-tools.test.ts b/tests/audio-tools.test.tsindex d04cc8b9..a60a6d73 100644--- a/tests/audio-tools.test.ts+++ b/tests/audio-tools.test.ts@@ -1,7 +1,5 @@import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { beforeAll, describe, expect, it } from "vitest";import { clock, planJoin, planLoop } from "@/lib/av/audio-tools";import { cloudLoopPasses } from "@/lib/av/crossfade";import { getModel } from "@/lib/catalog";@@ -9,8 +7,9 @@ import { buildPayload } from "@/lib/catalog/payload";import type { Generation } from "@/lib/catalog/types";import { HUB_MODES, modeHref } from "@/lib/hubs";import { outputActions } from "@/lib/output-actions";+import { tempDir } from "./helpers/temp-dir";-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-audio-tools-"));+const dir = tempDir("fuobe-audio-tools-");process.env.FUOBE_DATA_DIR = dir;// Nothing listens: the open models run on the demo provider.process.env.COMFYUI_URL = "http://127.0.0.1:9";@@ -21,7 +20,6 @@ const gens = await import("@/server/generations");const route = await import("@/app/api/audio-tools/route");beforeAll(() => setSetting("demoMode", "auto"));-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));/** A mono 16-bit WAV of a tone, saved as an upload. */function upload(seconds: number, name = "clip.wav"): string {diff --git a/tests/auth.test.ts b/tests/auth.test.tsindex 13c39f13..5fb9a64c 100644--- a/tests/auth.test.ts+++ b/tests/auth.test.ts@@ -1,13 +1,12 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, describe, expect, it } from "vitest";+import { describe, expect, it } from "vitest";+import { tempDir } from "./helpers/temp-dir";-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-auth-"));+const dir = tempDir("fuobe-auth-");process.env.FUOBE_DATA_DIR = dir;delete process.env.FUOBE_PASSWORD;const auth = await import("@/server/auth");-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));describe("auth", () => {it("is off until a password is set", () => {diff --git a/tests/av-dub.test.ts b/tests/av-dub.test.tsindex feb32150..d1475bb2 100644--- a/tests/av-dub.test.ts+++ b/tests/av-dub.test.ts@@ -1,7 +1,6 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { beforeAll, describe, expect, it, vi } from "vitest";import type { Generation } from "@/lib/catalog/types";import { cueReducer, cueProblems, formatCueTime, normalizeCues, parseCueTime } from "@/lib/av/cue-edit";import {@@ -34,10 +33,11 @@ import { timelineFor, timelineTracks } from "@/lib/av/timeline";import { DUB_LANGUAGES, supportsTarget } from "@/lib/av/languages";import { getModel } from "@/lib/catalog";import { buildPayload } from "@/lib/catalog/payload";+import { tempDir } from "./helpers/temp-dir";vi.setConfig({ testTimeout: 120_000 });-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-av-dub-"));+const dir = tempDir("fuobe-av-dub-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.OLLAMA_URL = "http://127.0.0.1:9";@@ -51,7 +51,6 @@ const { loadIndex } = await import("@/server/gpu/index-file");const { saveFile } = await import("@/server/storage");beforeAll(() => setSetting("demoMode", "auto"));-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));async function settle(id: string, ms = 100_000): Promise<Generation> {const end = Date.now() + ms;diff --git a/tests/av-katana.test.ts b/tests/av-katana.test.tsindex 3d8c003d..50870a23 100644--- a/tests/av-katana.test.ts+++ b/tests/av-katana.test.ts@@ -1,14 +1,14 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { beforeAll, describe, expect, it, vi } from "vitest";import type { Generation } from "@/lib/catalog/types";import { detectCuts, finalKey, KEYFRAME_OFFSET, katanaStage, katanaSteps, nearestAspect, OPEN_KEYFRAME_PHOTOS, planSegments, refineCut, refineTimes, stepsToRedo } from "@/lib/av/katana";import { frameParams, frameRequest } from "@/lib/av/frames";+import { tempDir } from "./helpers/temp-dir";vi.setConfig({ testTimeout: 150_000 });-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-av-katana-"));+const dir = tempDir("fuobe-av-katana-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.OLLAMA_URL = "http://127.0.0.1:9";@@ -20,7 +20,6 @@ const { getTool } = await import("@/server/assist/tools");const { saveFile } = await import("@/server/storage");beforeAll(() => setSetting("demoMode", "auto"));-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));async function settle(id: string, ms = 140_000): Promise<Generation> {const end = Date.now() + ms;diff --git a/tests/av-workflows.test.ts b/tests/av-workflows.test.tsindex f354feb4..666591de 100644--- a/tests/av-workflows.test.ts+++ b/tests/av-workflows.test.ts@@ -1,12 +1,10 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, describe, expect, it } from "vitest";+import { describe, expect, it } from "vitest";import type { GenInput, Operation } from "@/lib/catalog/types";import type { MediaInfo } from "@/lib/media-probe";+import { tempDir } from "./helpers/temp-dir";// The av-tools ComfyUI workflows (Extract frame, video-synced Foley, Product shot), bound for real.-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-av-workflows-"));+const dir = tempDir("fuobe-av-workflows-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://comfy.test:8188";@@ -15,7 +13,6 @@ const { getModel } = await import("@/lib/catalog");const { computeFrames } = await import("@/lib/comfy");const { frameParams } = await import("@/lib/av/frames");-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));const clip: MediaInfo = { container: "mp4", hasVideo: true, hasAudio: true, duration: 6, videoDuration: 6, width: 640, height: 360, fps: 30, frames: 180 };diff --git a/tests/billing-hook.test.ts b/tests/billing-hook.test.tsindex 091adec0..e48f4847 100644--- a/tests/billing-hook.test.ts+++ b/tests/billing-hook.test.ts@@ -1,14 +1,13 @@-import fs from "node:fs";import http from "node:http";-import os from "node:os";import path from "node:path";import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";import { listenInRange, startFakeBilling, type FakeBilling } from "./helpers/fake-billing";import { startFakeComfy, type FakeComfy } from "./helpers/fake-comfy-runner";+import { tempDir } from "./helpers/temp-dir";// The billing hook (docs/billing-hook.md) and hosted runs, against a stand-in billing service and a stand-in ComfyUI// as this install's GPUs. Numbers are arbitrary ("7 units").-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-billing-hook-"));+const dir = tempDir("fuobe-billing-hook-");process.env.FUOBE_DATA_DIR = dir;process.env.FUOBE_PUBLIC_SIGNUP = "1";delete process.env.FUOBE_PASSWORD;@@ -57,9 +56,6 @@ afterAll(async () => {delete process.env.FUOBE_BILLING_TOKEN;await fake.close();await comfy.close();- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}});const on = () => {diff --git a/tests/billing-release.test.ts b/tests/billing-release.test.tsindex c01ec61a..54dca4fc 100644--- a/tests/billing-release.test.ts+++ b/tests/billing-release.test.ts@@ -1,10 +1,8 @@-import fs from "node:fs";import http from "node:http";-import os from "node:os";-import path from "node:path";import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";import { listenInRange, startFakeBilling, type FakeBilling } from "./helpers/fake-billing";import { startFakeComfy, type FakeComfy } from "./helpers/fake-comfy-runner";+import { tempDir } from "./helpers/temp-dir";// A run whose rows can't be made after its price was set aside: the hold is released once (docs/billing-hook.md).vi.mock("@/server/generations", async (importOriginal) => {@@ -17,7 +15,7 @@ vi.mock("@/server/generations", async (importOriginal) => {};});-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-billing-release-"));+const dir = tempDir("fuobe-billing-release-");process.env.FUOBE_DATA_DIR = dir;process.env.FUOBE_PUBLIC_SIGNUP = "1";process.env.FUOBE_HOSTED_RUNS = "1";@@ -48,9 +46,6 @@ afterAll(async () => {for (const k of ["FUOBE_HOSTED_RUNS", "FUOBE_BILLING_URL", "FUOBE_BILLING_TOKEN"]) delete process.env[k];await fake.close();await comfy.close();- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}});describe("a run that can't be made after its reserve", () => {diff --git a/tests/blockout.test.ts b/tests/blockout.test.tsindex e7512cf0..8fcae9d6 100644--- a/tests/blockout.test.ts+++ b/tests/blockout.test.ts@@ -1,13 +1,13 @@import { execFileSync } from "node:child_process";import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { beforeAll, describe, expect, it } from "vitest";import type { CinemaGenerateInput } from "@/lib/catalog/cinema";+import { tempDir } from "./helpers/temp-dir";/** Blockout to film (package blockout-film): the scene maths, beats, prompts, shots, windows, plans, payloads and the API. */-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-blockout-"));+const dir = tempDir("fuobe-blockout-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.OLLAMA_URL = "http://127.0.0.1:9";@@ -29,7 +29,6 @@ beforeAll(() => {setSetting("demoMode", "auto");setSetting("enhanceProvider", "none");});-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));const VIDEO = "/api/files/uploads/blockout.webm";const DEPTH = "/api/files/uploads/blockout-depth.webm";diff --git a/tests/canvas-api.test.ts b/tests/canvas-api.test.tsindex d6aff5e2..c46bf91b 100644--- a/tests/canvas-api.test.ts+++ b/tests/canvas-api.test.ts@@ -1,14 +1,12 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { beforeAll, describe, expect, it, vi } from "vitest";import type { Canvas, CanvasGraph, CanvasSummary } from "@/lib/catalog/canvas";import type { Generation } from "@/lib/catalog/types";+import { tempDir } from "./helpers/temp-dir";// Route handlers are called directly, outside a Next request: connection() has nothing to wait for.vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-canvas-"));+const dir = tempDir("fuobe-canvas-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";@@ -22,7 +20,6 @@ const dup = await import("@/app/api/canvases/[id]/duplicate/route");const run = await import("@/app/api/canvases/[id]/run/route");beforeAll(() => setSetting("demoMode", "auto"));-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));// eslint-disable-next-line @typescript-eslint/no-explicit-anyconst ctx = (id: string) => ({ params: Promise.resolve({ id }) }) as any;diff --git a/tests/canvas-comfy.test.ts b/tests/canvas-comfy.test.tsindex a8ec14b9..1215e339 100644--- a/tests/canvas-comfy.test.ts+++ b/tests/canvas-comfy.test.ts@@ -1,14 +1,12 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, describe, expect, it } from "vitest";+import { describe, expect, it } from "vitest";import type { GenInput, Operation } from "@/lib/catalog/types";import type { ComfyWorkflow, ManifestWorkflow } from "@/lib/comfy";import type { MediaInfo } from "@/lib/media-probe";+import { tempDir } from "./helpers/temp-dir";// The canvas Video concatenator on the open engine (r4/canvas-plus): each clip's fit pass (video-fit-clip: cut,// frame, 30 fps, its sound or silence) and the packet-copy join, as the provider binds them.-const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-canvas-comfy-"));+const tmp = tempDir("fuobe-canvas-comfy-");process.env.FUOBE_DATA_DIR = tmp;process.env.COMFYUI_URL = "http://comfy.test:8188";const { prepareWorkflow } = await import("@/server/providers/comfyui");@@ -16,7 +14,6 @@ const { getModel } = await import("@/lib/catalog");const { describeNode } = await import("@/lib/catalog/canvas");const { planGeneration } = await import("@/lib/catalog/plan");const { getPreset } = await import("@/lib/catalog");-afterAll(() => fs.rmSync(tmp, { recursive: true, force: true }));async function prepare(id: string, input: GenInput, op: Operation, media: Record<string, MediaInfo> = {}) {return prepareWorkflow(id, { seed: 7, ...input }, {diff --git a/tests/canvas-plus.test.ts b/tests/canvas-plus.test.tsindex 38b759a2..ecb70e9d 100644--- a/tests/canvas-plus.test.ts+++ b/tests/canvas-plus.test.ts@@ -1,14 +1,14 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { beforeAll, describe, expect, it, vi } from "vitest";import type { Canvas, CanvasGraph, CanvasNode } from "@/lib/catalog/canvas";import type { Generation } from "@/lib/catalog/types";+import { tempDir } from "./helpers/temp-dir";// Route handlers are called directly, outside a Next request: connection() has nothing to wait for.vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-canvas-plus-"));+const dir = tempDir("fuobe-canvas-plus-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";@@ -40,7 +40,6 @@ const one = await import("@/app/api/canvases/[id]/route");const run = await import("@/app/api/canvases/[id]/run/route");beforeAll(() => setSetting("demoMode", "auto"));-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));// eslint-disable-next-line @typescript-eslint/no-explicit-anyconst ctx = (id: string) => ({ params: Promise.resolve({ id }) }) as any;diff --git a/tests/canvas-split.test.ts b/tests/canvas-split.test.tsindex b33c403f..d045e2ce 100644--- a/tests/canvas-split.test.ts+++ b/tests/canvas-split.test.ts@@ -1,7 +1,6 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { beforeAll, describe, expect, it, vi } from "vitest";import {cleanGraph,connectionError,@@ -20,13 +19,14 @@ import {} from "@/lib/catalog/canvas";import { CLOUD_SPLIT_PROBLEM, SPLIT_MODEL } from "@/lib/av/split";import type { Generation } from "@/lib/catalog/types";+import { tempDir } from "./helpers/temp-dir";// Canvas → Split soundtrack (DBS D8): a utility node with four outputs (Dialogue, Music, Effects, Music & effects), each// edge carrying its stem on to the next node's chain; OUT stays as Dialogue for boards saved before; DBS on the open// engine only, so the node is disabled on the cloud with the reason.vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-canvas-split-"));+const dir = tempDir("fuobe-canvas-split-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";@@ -38,11 +38,6 @@ const one = await import("@/app/api/canvases/[id]/route");const run = await import("@/app/api/canvases/[id]/run/route");beforeAll(() => setSetting("demoMode", "auto"));-afterAll(() => {- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}-});const at = (x: number) => ({ x, y: 0 });const clip: CanvasNode = { id: "clip", type: "video-input", position: at(0), data: { url: "/api/files/uploads/2026-11-01/interview.mp4" } };diff --git a/tests/canvas-starter-create.test.ts b/tests/canvas-starter-create.test.tsindex 91d0c30a..35756d1e 100644--- a/tests/canvas-starter-create.test.ts+++ b/tests/canvas-starter-create.test.ts@@ -1,15 +1,14 @@import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, describe, expect, it, vi } from "vitest";+import { describe, expect, it, vi } from "vitest";import type { Canvas } from "@/lib/catalog/canvas";+import { tempDir } from "./helpers/temp-dir";// A ready board made by the owner starts with its sample files in place: each input node names a stored copy of the// template's sample, the copy is made once and reused, the Library lists don't show it, and the board plans as it is.vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-starter-"));+const dir = tempDir("fuobe-starter-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";@@ -18,12 +17,6 @@ const { absolutePath, filesRel, listAssets } = await import("@/server/storage");const { sampleFile } = await import("@/server/canvas-samples");const list = await import("@/app/api/canvases/route");-afterAll(() => {- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}-});-const create = async (templateId: string, engine: "open" | "cloud") =>(await (await list.POST(new Request("http://localhost/api/canvases", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ templateId, engine }) }))).json()) as Canvas;diff --git a/tests/chain-fanout.test.ts b/tests/chain-fanout.test.tsindex 851279ff..91bff526 100644--- a/tests/chain-fanout.test.ts+++ b/tests/chain-fanout.test.ts@@ -1,15 +1,15 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { beforeAll, describe, expect, it, vi } from "vitest";import type { Generation, GenerationRequest, OutputFile } from "@/lib/catalog/types";+import { tempDir } from "./helpers/temp-dir";// The per-index chain slot (ChainSlot.index): one step per output of a list-making step (fan-out),// and one step with a slot per index that gathers them back in order (fan-in).vi.setConfig({ testTimeout: 90_000 });-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-fanout-"));+const dir = tempDir("fuobe-fanout-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.OLLAMA_URL = "http://127.0.0.1:9";@@ -21,7 +21,6 @@ const { saveFile } = await import("@/server/storage");const { db } = await import("@/server/db");beforeAll(() => setSetting("demoMode", "auto"));-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));async function settle(id: string, ms = 80_000): Promise<Generation> {const end = Date.now() + ms;diff --git a/tests/chain-optional.test.ts b/tests/chain-optional.test.tsindex e09b2855..235a7f6d 100644--- a/tests/chain-optional.test.ts+++ b/tests/chain-optional.test.ts@@ -1,16 +1,16 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { beforeAll, describe, expect, it, vi } from "vitest";import type { Generation } from "@/lib/catalog/types";import { ANCHOR_FALLBACK } from "@/lib/catalog/character-swap";+import { tempDir } from "./helpers/temp-dir";// An optional chain input (ChainSlot.optional, Genjutsu's anchor first frame): when its step fails the step reading it// runs without it, with the fallback's prompt, and says so; a retry puts the request back as it was planned.vi.setConfig({ testTimeout: 90_000 });-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-optional-"));+const dir = tempDir("fuobe-optional-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.OLLAMA_URL = "http://127.0.0.1:9";@@ -22,7 +22,6 @@ const { saveFile } = await import("@/server/storage");const { db } = await import("@/server/db");beforeAll(() => setSetting("demoMode", "auto"));-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));async function settle(id: string, ms = 80_000): Promise<Generation> {const end = Date.now() + ms;diff --git a/tests/chain-soundtrack.test.ts b/tests/chain-soundtrack.test.tsindex 267a44a4..54657db5 100644--- a/tests/chain-soundtrack.test.ts+++ b/tests/chain-soundtrack.test.ts@@ -1,14 +1,11 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, describe, expect, it } from "vitest";+import { describe, expect, it } from "vitest";import type { OutputFile } from "@/lib/catalog/types";+import { tempDir } from "./helpers/temp-dir";-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-soundtrack-"));+const dir = tempDir("fuobe-soundtrack-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";const { pickOutput } = await import("@/server/generations");-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));const clip: OutputFile = { url: "/api/files/cut.mp4", kind: "video", contentType: "video/mp4" };const still: OutputFile = { url: "/api/files/frame.png", kind: "image", contentType: "image/png" };diff --git a/tests/chains.test.ts b/tests/chains.test.tsindex 6a79dc12..f4cfb543 100644--- a/tests/chains.test.ts+++ b/tests/chains.test.ts@@ -1,9 +1,7 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { beforeAll, describe, expect, it } from "vitest";+import { tempDir } from "./helpers/temp-dir";-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-chains-"));+const dir = tempDir("fuobe-chains-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";@@ -16,7 +14,6 @@ const { planGeneration } = await import("@/lib/catalog/plan");const { getPreset } = await import("@/lib/catalog");beforeAll(() => setSetting("demoMode", "auto"));-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));const dependsOn = (id: string) => {const v = (db().prepare("SELECT depends_on FROM generations WHERE id = ?").get(id) as { depends_on: string | null }).depends_on;diff --git a/tests/character-swap-2k.test.ts b/tests/character-swap-2k.test.tsindex 75463b8b..c97a2f2e 100644--- a/tests/character-swap-2k.test.ts+++ b/tests/character-swap-2k.test.ts@@ -1,9 +1,9 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, describe, expect, it, vi } from "vitest";+import { describe, expect, it, vi } from "vitest";import type { PlanStep } from "@/lib/catalog/shorts";import type { GenerationRequest, GenInput } from "@/lib/catalog/types";+import { tempDir } from "./helpers/temp-dir";// Character swap in 2K: Genjutsu's 1080p / 2K / 4K and Character Swap Studio's Sharpen,// on both engines. Your GPU: the 768p swap regenerated (sigma 0.8, never above the footage's size), then only the@@ -11,10 +11,9 @@ import type { GenerationRequest, GenInput } from "@/lib/catalog/types";// Your GPU's sizes regenerate with Open-H3 Regenerate, which is switched off for now (REGEN_OFFERED); these tests check// them as they run once it is on. tests/regenerate-offered.test.ts checks that nothing offers them while it is off.vi.mock("@/lib/catalog/regenerate", async (importOriginal) => ({ ...(await importOriginal<typeof import("@/lib/catalog/regenerate")>()), REGEN_OFFERED: true }));-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-swap-2k-"));+const dir = tempDir("fuobe-swap-2k-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));const S = await import("@/lib/catalog/sharpen");const C = await import("@/lib/catalog/character-swap");diff --git a/tests/cinema-api.test.ts b/tests/cinema-api.test.tsindex 4592cf7f..7fb771a1 100644--- a/tests/cinema-api.test.ts+++ b/tests/cinema-api.test.ts@@ -1,9 +1,7 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { beforeAll, describe, expect, it } from "vitest";+import { tempDir } from "./helpers/temp-dir";-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-cinema-"));+const dir = tempDir("fuobe-cinema-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";// No LLM in tests: the AI Director answers offline.@@ -26,7 +24,6 @@ beforeAll(() => {setSetting("demoMode", "auto");setSetting("enhanceProvider", "none");});-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));const json = (method: string, body?: unknown) =>new Request("http://x/api", { method, headers: { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });diff --git a/tests/cinema-director.test.ts b/tests/cinema-director.test.tsindex 9b27babc..2e76aae8 100644--- a/tests/cinema-director.test.ts+++ b/tests/cinema-director.test.ts@@ -1,10 +1,8 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, describe, expect, it, vi } from "vitest";+import { describe, expect, it, vi } from "vitest";+import { tempDir } from "./helpers/temp-dir";// The AI Director answers questions instead of storyboarding them, and keeps an LLM's prose answer.-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-cinema-director-"));+const dir = tempDir("fuobe-cinema-director-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.OLLAMA_URL = "http://127.0.0.1:9";@@ -15,7 +13,6 @@ vi.mock("@/server/enhance", async (orig) => ({ ...(await orig<typeof import("@/sconst cinema = await import("@/server/cinema");const { askDirector, isQuestion, offlineDirector, prose } = await import("@/server/cinema-director");-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));const empty = { brief: { title: "", body: "" }, director: {} };diff --git a/tests/cinema-fixes.test.ts b/tests/cinema-fixes.test.tsindex 04dce2ba..ecb2d687 100644--- a/tests/cinema-fixes.test.ts+++ b/tests/cinema-fixes.test.ts@@ -1,11 +1,9 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { beforeAll, describe, expect, it } from "vitest";+import { tempDir } from "./helpers/temp-dir";// Round-3 review fixes: retry (batches, chains as a unit), stale folders, step previews, project-scoped// deletes, spend that survives deletes, "My Generations" ownership.-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-cinema-fixes-"));+const dir = tempDir("fuobe-cinema-fixes-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.OLLAMA_URL = "http://127.0.0.1:9";@@ -24,7 +22,6 @@ beforeAll(() => {setSetting("demoMode", "auto");setSetting("enhanceProvider", "none");});-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));const json = (method: string, body?: unknown) =>new Request("http://x/api", { method, headers: { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });diff --git a/tests/cinema-original.test.ts b/tests/cinema-original.test.tsindex fbdea0d6..7946373c 100644--- a/tests/cinema-original.test.ts+++ b/tests/cinema-original.test.ts@@ -1,15 +1,15 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { beforeAll, describe, expect, it } from "vitest";import type { ComfyWorkflow } from "@/lib/comfy";import type { GenInput, LoraRef, ModelDef, ModelRoute } from "@/lib/catalog/types";import type { DirectorSettings } from "@/lib/catalog/cinema";+import { tempDir } from "./helpers/temp-dir";// Fuobe Cinema as a run (build plan O6): one model on both engines. In the cloud the payload fal receives (LTX-2.3 22B,// prompt expansion off, camera_lora, exact sizes, frames at 24 fps, the plain endpoint unless a LoRA rides along) and its// price; on the user's GPU the Wan 2.2 Lightning graphs, a Fun Camera pose on its graph and a camera LoRA injected.-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-cinema-original-"));+const dir = tempDir("fuobe-cinema-original-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9"; // nothing listens here: open runs fall back to the demo@@ -25,7 +25,6 @@ const { needsToken } = await import("@/lib/catalog/loras");const { finishedUrl } = await import("@/lib/soul-post");beforeAll(() => setSetting("demoMode", "auto"));-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));const view = (engine: "open" | "cloud") => onEngine(getModel(CINEMA_MODEL)!, engine);const fal = (op: string) => view("cloud").routes.find((r) => r.provider === "fal" && r.op === op)!;diff --git a/tests/cinema-path.test.ts b/tests/cinema-path.test.tsindex 7d195633..ff6e8eaf 100644--- a/tests/cinema-path.test.ts+++ b/tests/cinema-path.test.ts@@ -1,13 +1,13 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";+import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";import type { CinemaGenerateInput } from "@/lib/catalog/cinema";import type { ModelDef } from "@/lib/catalog/types";+import { tempDir } from "./helpers/temp-dir";/** Fly path (build plan N7-5): Cinema's "Film this path" on both engines, the H3 Max payload, the Uni3C graph and the API. */-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-cinema-path-"));+const dir = tempDir("fuobe-cinema-path-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.OLLAMA_URL = "http://127.0.0.1:9";@@ -31,7 +31,6 @@ beforeAll(() => {setSetting("enhanceProvider", "none");});afterEach(() => vi.useRealTimers());-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));const STILL = "/api/files/uploads/still.png";const RENDER = "/api/files/uploads/render.webm";diff --git a/tests/cinema-scene.test.ts b/tests/cinema-scene.test.tsindex 0ac8397e..4085e20b 100644--- a/tests/cinema-scene.test.ts+++ b/tests/cinema-scene.test.ts@@ -1,12 +1,10 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { beforeAll, describe, expect, it } from "vitest";import type { CinemaGenerateInput } from "@/lib/catalog/cinema";+import { tempDir } from "./helpers/temp-dir";/** Cinema Studio's 3D scene: "Create 3D scene" on a still, then Capture → recomposition, on both engines. */-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-cinema-scene-"));+const dir = tempDir("fuobe-cinema-scene-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.OLLAMA_URL = "http://127.0.0.1:9";@@ -24,7 +22,6 @@ beforeAll(() => {setSetting("demoMode", "auto");setSetting("enhanceProvider", "none");});-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));const STILL = "/api/files/uploads/still.png";const CAPTURE = "/api/files/uploads/capture.png";diff --git a/tests/clean-dialogue.test.ts b/tests/clean-dialogue.test.tsindex 6680fe7e..ea78d54e 100644--- a/tests/clean-dialogue.test.ts+++ b/tests/clean-dialogue.test.ts@@ -1,7 +1,6 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { beforeAll, describe, expect, it } from "vitest";import {bedOf,CLEAN_DIALOGUE_FEATURE,@@ -23,11 +22,12 @@ import { estimateCost } from "@/lib/catalog/plan";import { getModel } from "@/lib/catalog";import { defaultModelForNode, modelChoices } from "@/lib/catalog/canvas";import type { Generation, GenInput } from "@/lib/catalog/types";+import { tempDir } from "./helpers/temp-dir";// Clean up dialogue (DBS D5): the plan per engine and cleaner, the cloud cleaners' prices and payloads against their// research records, graph C (soundtrack-remix-dbs) in the manifest and its bindings, the hand-offs, and the API in demo// mode.-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-clean-dialogue-"));+const dir = tempDir("fuobe-clean-dialogue-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";@@ -40,7 +40,6 @@ const { outputActions } = await import("@/lib/output-actions");const { STUDIO_ROWS, studioTool } = await import("@/server/gpu/tools");beforeAll(() => setSetting("demoMode", "auto"));-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));const ROOT = path.join(__dirname, "..");const json = (f: string) => JSON.parse(fs.readFileSync(path.join(ROOT, f), "utf8"));diff --git a/tests/clean-voice.test.ts b/tests/clean-voice.test.tsindex 8bc3a568..f26b7970 100644--- a/tests/clean-voice.test.ts+++ b/tests/clean-voice.test.ts@@ -1,7 +1,6 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { beforeAll, describe, expect, it, vi } from "vitest";import {CLEAN_MAX_SECONDS,CLOUD_CLEAN_PROBLEM,@@ -26,10 +25,11 @@ import { APPS, getModel } from "@/lib/catalog";import { blockerFor } from "@/lib/composer";import type { Generation } from "@/lib/catalog/types";import { defaultModelForNode, NODE_SPECS, nodeOps, paletteItems } from "@/lib/catalog/canvas";+import { tempDir } from "./helpers/temp-dir";// Audio → Clean up voice (NVIDIA RE-USE): the planner, the rate and time rules, the Library action, the app, and the API// in demo mode.-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-clean-"));+const dir = tempDir("fuobe-clean-");process.env.FUOBE_DATA_DIR = dir;// Nothing listens: the open model runs on the demo provider.process.env.COMFYUI_URL = "http://127.0.0.1:9";@@ -41,7 +41,6 @@ const gens = await import("@/server/generations");const route = await import("@/app/api/audio-tools/route");beforeAll(() => setSetting("demoMode", "auto"));-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));function upload(seconds: number, channels = 1, name = "voice.wav"): string {const rate = 8000;diff --git a/tests/cli-api.test.ts b/tests/cli-api.test.tsindex bca6cc89..e81bb158 100644--- a/tests/cli-api.test.ts+++ b/tests/cli-api.test.ts@@ -1,16 +1,14 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { beforeAll, describe, expect, it, vi } from "vitest";import { MODELS } from "@/lib/catalog";import { findModels, toModelInfo } from "@/lib/model-list";+import { tempDir } from "./helpers/temp-dir";/** The REST routes the fuobe CLI added: GET /api/models and POST /api/generations?preview=1. */// Route handlers are called directly, outside a Next request: connection() has nothing to wait for.vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-cli-api-"));+const dir = tempDir("fuobe-cli-api-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.OLLAMA_URL = "http://127.0.0.1:9";@@ -20,7 +18,6 @@ const { listGenerations } = await import("@/server/generations");const { setSetting } = await import("@/server/settings");// Placeholders where nothing is connected, as the studio once did by default ("auto": code in this process only).beforeAll(() => setSetting("demoMode", "auto"));-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));type ModelsBody = {engineMode: string;diff --git a/tests/cli-run.test.ts b/tests/cli-run.test.tsindex 65ca6d2d..b5787439 100644--- a/tests/cli-run.test.ts+++ b/tests/cli-run.test.ts@@ -2,10 +2,10 @@ import { spawn } from "node:child_process";import fs from "node:fs";import http from "node:http";import type { AddressInfo } from "node:net";-import os from "node:os";import path from "node:path";import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";import { unzip } from "@/server/assist/unzip";+import { tempDir } from "./helpers/temp-dir";/*** The fuobe CLI as a child process against a stub of Fuobe's REST API: upload → generate → wait →@@ -14,7 +14,7 @@ import { unzip } from "@/server/assist/unzip";const TOKEN = "fuobe_test-token";const CLI = path.join(process.cwd(), "bin/fuobe.mjs");-const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-cli-run-"));+const tmp = tempDir("fuobe-cli-run-");const PNG = Buffer.from("89504e470d0a1a0a0000000d49484452", "hex");interface Seen {@@ -163,7 +163,6 @@ beforeAll(async () => {afterAll(async () => {await new Promise((r) => server.close(r));- fs.rmSync(tmp, { recursive: true, force: true });});beforeEach(() => {diff --git a/tests/cli.test.ts b/tests/cli.test.tsindex f9996e92..25e02c7b 100644--- a/tests/cli.test.ts+++ b/tests/cli.test.ts@@ -1,7 +1,6 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, describe, expect, it } from "vitest";+import { describe, expect, it } from "vitest";import { keyValue, parseArgs, suggest, UsageError } from "../bin/lib/args.mjs";import { defaultModel, fileInputs, generationRequest, isRemoteRef, localFiles, voiceSampleProblem, withInputHint } from "../bin/lib/build.mjs";import { createClient, networkMessage, statusMessage } from "../bin/lib/client.mjs";@@ -11,9 +10,9 @@ import { clip, countOutputs, formatCost, formatDuration, previewText, table } frimport { csvCells, estimateLines, exactCost, findSkillDirs, headerInputs, packSkill, parseSource, priceWords, skillHead, skillValues, toCsv } from "../bin/lib/skills.mjs";import { crc32, zipFiles } from "../bin/lib/zip.mjs";import { unzip } from "@/server/assist/unzip";+import { tempDir } from "./helpers/temp-dir";-const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-cli-"));-afterAll(() => fs.rmSync(tmp, { recursive: true, force: true }));+const tmp = tempDir("fuobe-cli-");const GEN = { ...GEN_OPTIONS, wait: { type: "boolean" as const, short: "w" }, out: { type: "string" as const, short: "o" } };const usage = (fn: () => unknown) => {diff --git a/tests/click-to-ad-endcard.test.ts b/tests/click-to-ad-endcard.test.tsindex 189cc072..4e270453 100644--- a/tests/click-to-ad-endcard.test.ts+++ b/tests/click-to-ad-endcard.test.ts@@ -1,8 +1,6 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { beforeAll, describe, expect, it, vi } from "vitest";import type { Product } from "@/lib/catalog/marketing";+import { tempDir } from "./helpers/temp-dir";// Click to Ad's animated end card: the rendered clip replaces the still and its push-in, the joins stay. Cloud: the// clip gets its silent track (mux) and merge-videos joins it after the ad. Open: one join that keeps the ad's sound,@@ -10,7 +8,7 @@ import type { Product } from "@/lib/catalog/marketing";vi.setConfig({ testTimeout: 60_000 });-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-c2a-motion-"));+const dir = tempDir("fuobe-c2a-motion-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.OLLAMA_URL = "http://127.0.0.1:9";@@ -22,11 +20,6 @@ const { saveFile } = await import("@/server/storage");const { endCardSteps } = await import("@/lib/catalog/marketing");beforeAll(() => setSetting("demoMode", "auto"));-afterAll(() => {- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}-});const PNG = Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), Buffer.alloc(400, 7)]);const upload = (name = "p.png") => saveFile({ data: PNG, contentType: "image/png", name, source: "upload" }).url;diff --git a/tests/comfy-content-factory.test.ts b/tests/comfy-content-factory.test.tsindex 04ca982f..a042d347 100644--- a/tests/comfy-content-factory.test.ts+++ b/tests/comfy-content-factory.test.ts@@ -1,21 +1,18 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, describe, expect, it } from "vitest";+import { describe, expect, it } from "vitest";import type { GenInput } from "@/lib/catalog/types";import type { ComfyWorkflow, ManifestWorkflow } from "@/lib/comfy";import type { MediaInfo } from "@/lib/media-probe";import { parseBrief } from "@/lib/catalog/content-factory";+import { tempDir } from "./helpers/temp-dir";// Content Factory's open route (r4/content-factory): the reference clip → reference-brief-gemma4's bindings// (the clip, how much of it at 24 fps, where to start), and its SaveText answer → a text output the brief parser reads.-const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-comfy-content-factory-"));+const tmp = tempDir("fuobe-comfy-content-factory-");process.env.FUOBE_DATA_DIR = tmp;process.env.COMFYUI_URL = "http://comfy.test:8188";const { prepareWorkflow, getWorkflow, collectOutputs } = await import("@/server/providers/comfyui");const { getModel, getPreset } = await import("@/lib/catalog");const { planGeneration } = await import("@/lib/catalog/plan");-afterAll(() => fs.rmSync(tmp, { recursive: true, force: true }));const ID = "reference-brief-gemma4";const clip = (duration: number): MediaInfo => ({ container: "mp4", hasVideo: true, hasAudio: true, duration, videoDuration: duration, width: 1080, height: 1920, fps: 30 });diff --git a/tests/comfy-dbs-dub.test.ts b/tests/comfy-dbs-dub.test.tsindex 88fed3c2..79402b77 100644--- a/tests/comfy-dbs-dub.test.ts+++ b/tests/comfy-dbs-dub.test.ts@@ -1,20 +1,19 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, describe, expect, it } from "vitest";+import { describe, expect, it } from "vitest";import type { GenInput } from "@/lib/catalog/types";import type { ComfyWorkflow, Manifest, ManifestWorkflow } from "@/lib/comfy";import { licenceInfo, workflowLicence } from "@/lib/licences";import type { DbsModel } from "@/lib/av/split";import type { MediaInfo } from "@/lib/media-probe";+import { tempDir } from "./helpers/temp-dir";// DBS D3: graph B (dub-prepare-dbs-transcribe), the open dub's first step with DBS in place of MelBand RoFormer. Same// output contract and ASR bindings as dub-prepare-separate-transcribe, so the dub only changes its model id.-const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-comfy-dbs-dub-"));+const tmp = tempDir("fuobe-comfy-dbs-dub-");process.env.FUOBE_DATA_DIR = tmp;process.env.COMFYUI_URL = "http://comfy.test:8188";const { collectOutputs, prepareWorkflow } = await import("@/server/providers/comfyui");-afterAll(() => fs.rmSync(tmp, { recursive: true, force: true }));const root = path.resolve(__dirname, "..");const lib = (f: string) => JSON.parse(fs.readFileSync(path.join(root, "workflows/comfyui", f), "utf8"));diff --git a/tests/comfy-dbs.test.ts b/tests/comfy-dbs.test.tsindex 01fb9eb7..aac1c4a1 100644--- a/tests/comfy-dbs.test.ts+++ b/tests/comfy-dbs.test.ts@@ -1,21 +1,20 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, describe, expect, it, vi } from "vitest";+import { describe, expect, it, vi } from "vitest";import type { GenInput } from "@/lib/catalog/types";import type { ComfyWorkflow, Manifest, ManifestWorkflow } from "@/lib/comfy";import { installScript, nodeInstall } from "@/lib/comfy-install";import { ATTRIBUTIONS, licenceInfo, nodePack, workflowLicence } from "@/lib/licences";import type { DbsModel } from "@/lib/av/split";import type { MediaInfo } from "@/lib/media-probe";+import { tempDir } from "./helpers/temp-dir";// DBS D1's ground on the open engine: the pinned pack and weights, graph A (separate-soundtrack-dbs) in the manifest,// the folder models, the licence rows, and how the provider fills the model and channel bindings.-const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-comfy-dbs-"));+const tmp = tempDir("fuobe-comfy-dbs-");process.env.FUOBE_DATA_DIR = tmp;process.env.COMFYUI_URL = "http://comfy.test:8188";const { collectOutputs, comfyDbsModels, comfyDevice, prepareWorkflow } = await import("@/server/providers/comfyui");-afterAll(() => fs.rmSync(tmp, { recursive: true, force: true }));const root = path.resolve(__dirname, "..");const manifest = JSON.parse(fs.readFileSync(path.join(root, "workflows/comfyui/manifest.json"), "utf8")) as Manifest;diff --git a/tests/comfy-faceless-plus.test.ts b/tests/comfy-faceless-plus.test.tsindex 99f0c0b3..a08d67f7 100644--- a/tests/comfy-faceless-plus.test.ts+++ b/tests/comfy-faceless-plus.test.ts@@ -1,22 +1,19 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, describe, expect, it } from "vitest";+import { describe, expect, it } from "vitest";import type { GenInput, Operation } from "@/lib/catalog/types";import type { ComfyWorkflow, ManifestWorkflow } from "@/lib/comfy";import type { MediaInfo } from "@/lib/media-probe";import { expandAudioJoinWorkflow, expandVideoJoinWorkflow } from "@/lib/av/joins";import { probeMedia } from "@/lib/media-probe";+import { tempDir } from "./helpers/temp-dir";// The open engine's Ken Burns, loops and joins through the provider (r4/faceless-plus): canonical params →// kenburns-still / audio-loop-crossfade / audio-join-crossfade / video-concat-encoded bindings, the crossfade// curve the provider writes, and the joins of more clips than the templates bind.-const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-comfy-faceless-plus-"));+const tmp = tempDir("fuobe-comfy-faceless-plus-");process.env.FUOBE_DATA_DIR = tmp;process.env.COMFYUI_URL = "http://comfy.test:8188";const { prepareWorkflow, getWorkflow } = await import("@/server/providers/comfyui");const { getModel } = await import("@/lib/catalog");-afterAll(() => fs.rmSync(tmp, { recursive: true, force: true }));interface Upload {name: string;diff --git a/tests/comfy-guard.test.ts b/tests/comfy-guard.test.tsindex 6105f483..5581bb9b 100644--- a/tests/comfy-guard.test.ts+++ b/tests/comfy-guard.test.ts@@ -8,10 +8,10 @@import { spawnSync } from "node:child_process";import fs from "node:fs";import net from "node:net";-import os from "node:os";import path from "node:path";import { describe, expect, it } from "vitest";import { GUARD_FILE_NAME, GUARD_SOURCE, guardBase64, isGuard } from "@/lib/comfy-guard";+import { tempDir } from "./helpers/temp-dir";function pythonWithAiohttp(): string | null {for (const exe of [process.env.FUOBE_TEST_PYTHON, "python3", "python"].filter(Boolean) as string[]) {@@ -143,7 +143,7 @@ describe("Fuobe's guard for ComfyUI", () => {});const run = async (allowed: string) => {- const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-guard-"));+ const dir = tempDir("fuobe-guard-");const guard = path.join(dir, GUARD_FILE_NAME);const harness = path.join(dir, "harness.py");fs.writeFileSync(guard, GUARD_SOURCE);diff --git a/tests/comfy-install.test.ts b/tests/comfy-install.test.tsindex 337d815b..ca37796c 100644--- a/tests/comfy-install.test.ts+++ b/tests/comfy-install.test.ts@@ -1,10 +1,10 @@import { execFileSync } from "node:child_process";import fs from "node:fs";-import os from "node:os";import path from "node:path";import { describe, expect, it } from "vitest";import type { Manifest } from "@/lib/comfy";import { installScript, nodeInstall, workflowSource } from "@/lib/comfy-install";+import { tempDir } from "./helpers/temp-dir";const manifest = JSON.parse(fs.readFileSync(path.join(__dirname, "../workflows/comfyui/manifest.json"), "utf8")) as Manifest;const workflow = (id: string) => manifest.workflows.find((w) => w.id === id)!;@@ -70,7 +70,7 @@ describe("Workflows → Copy install commands", () => {});it("the commands run, and run again, as install-comfyui.sh does: a pinned clone moves to its pin, a copied pack isn't copied twice", () => {- const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-comfy-install-"));+ const tmp = tempDir("fuobe-comfy-install-");const git = (cwd: string, ...args: string[]) =>execFileSync("git", ["-c", "user.name=t", "-c", "user.email=t@t", "-c", "commit.gpgsign=false", "-c", "init.defaultBranch=main", ...args], { cwd, encoding: "utf8" }).trim();/** A stand-in remote with two commits; the first is the pin. */diff --git a/tests/comfy-library-4.test.ts b/tests/comfy-library-4.test.tsindex a3f508be..452c730f 100644--- a/tests/comfy-library-4.test.ts+++ b/tests/comfy-library-4.test.ts@@ -1,10 +1,10 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, describe, expect, it } from "vitest";+import { describe, expect, it } from "vitest";import type { Operation } from "@/lib/catalog/types";import type { ComfyWorkflow, Manifest, ManifestOutput, ManifestWorkflow } from "@/lib/comfy";import type { MediaInfo } from "@/lib/media-probe";+import { tempDir } from "./helpers/temp-dir";// The round-4 ComfyUI library (docs/research/comfyui-oss-4.json): the 17 graphs with the bindings and outputs the// feature packages drive, and the CausVid licence fix of wan21-vace-14b-ref2v.@@ -437,11 +437,10 @@ describe("round-4 window graphs: VACE remove / swap / insert and VOID", () => {// ---------------------------------------------------------------------------// Every round-4 workflow bound for real through the provider (prepareWorkflow → applyBindings on the library graph).-const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-comfy-library-4-"));+const tmp = tempDir("fuobe-comfy-library-4-");process.env.FUOBE_DATA_DIR = tmp;process.env.COMFYUI_URL = "http://comfy.test:8188";const { prepareWorkflow } = await import("@/server/providers/comfyui");-afterAll(() => fs.rmSync(tmp, { recursive: true, force: true }));const GIVEN = new Set(["img1.png", "mask.png", "clip.mp4", "voice.wav", "voice2.wav", "curve.wav"]);const portrait: MediaInfo = { container: "mp4", hasVideo: true, hasAudio: true, duration: 8, videoDuration: 8, width: 360, height: 640, fps: 30, frames: 240 };diff --git a/tests/comfy-library-7.test.ts b/tests/comfy-library-7.test.tsindex e6fdd538..54d7c127 100644--- a/tests/comfy-library-7.test.ts+++ b/tests/comfy-library-7.test.ts@@ -1,20 +1,19 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, describe, expect, it } from "vitest";+import { describe, expect, it } from "vitest";import type { GenInput } from "@/lib/catalog/types";import type { ComfyWorkflow, Manifest } from "@/lib/comfy";import { getModel } from "@/lib/catalog";import { sizeValue } from "@/lib/catalog/payload";import { compileMoss } from "@/lib/layout-prompt";+import { tempDir } from "./helpers/temp-dir";// Research #7 (docs/research/new-models-7.md §4.4, §4.6): MOSS-Image's core-node graph in the ComfyUI library, its pinned// weights, and how the provider fills it (a compiled layout reaches CLIPTextEncode verbatim; Quality / Fast settings).-const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-comfy-moss-"));+const tmp = tempDir("fuobe-comfy-moss-");process.env.FUOBE_DATA_DIR = tmp;process.env.COMFYUI_URL = "http://comfy.test:8188";const { prepareWorkflow } = await import("@/server/providers/comfyui");-afterAll(() => fs.rmSync(tmp, { recursive: true, force: true }));const dir = path.join(process.cwd(), "workflows/comfyui");const manifest = JSON.parse(fs.readFileSync(path.join(dir, "manifest.json"), "utf8")) as Manifest;diff --git a/tests/comfy-lora.test.ts b/tests/comfy-lora.test.tsindex be8d59c4..c7e13a93 100644--- a/tests/comfy-lora.test.ts+++ b/tests/comfy-lora.test.ts@@ -1,19 +1,16 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, describe, expect, it } from "vitest";+import { describe, expect, it } from "vitest";import { loraEntry, loraRef } from "@/lib/catalog/loras";import type { GenInput, Operation } from "@/lib/catalog/types";import { canTakeLoras, type ComfyWorkflow } from "@/lib/comfy";+import { tempDir } from "./helpers/temp-dir";// LoRAs on the open engine through the provider: a recipe's LoRA stack on the library graphs (injectLoras after// each diffusion model loader, Wan 2.2's high / low-noise experts apart), and graphs that can't take one.-const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-comfy-lora-"));+const tmp = tempDir("fuobe-comfy-lora-");process.env.FUOBE_DATA_DIR = tmp;process.env.COMFYUI_URL = "http://comfy.test:8188";const { prepareWorkflow, getWorkflow } = await import("@/server/providers/comfyui");const { getModel, PRESETS, MOTIONS, EFFECTS } = await import("@/lib/catalog");-afterAll(() => fs.rmSync(tmp, { recursive: true, force: true }));async function prepare(id: string, input: GenInput, op: Operation) {return prepareWorkflow(id, { seed: 7, ...input }, { generationId: "g", op, upload: async (_d, _t, name) => `up_${name}`, media: () => undefined, serverRam: async () => undefined });diff --git a/tests/comfy-provider.test.ts b/tests/comfy-provider.test.tsindex 1d6f378c..2671b4d7 100644--- a/tests/comfy-provider.test.ts+++ b/tests/comfy-provider.test.ts@@ -1,14 +1,12 @@-import fs from "node:fs";import { Worker } from "node:worker_threads";-import os from "node:os";-import path from "node:path";import zlib from "node:zlib";-import { afterAll, afterEach, beforeEach, describe, expect, it } from "vitest";+import { afterEach, beforeEach, describe, expect, it } from "vitest";import type { ManifestWorkflow } from "@/lib/comfy";import type { MediaInfo } from "@/lib/media-probe";import type { ModelDef, ModelRoute } from "@/lib/catalog/types";+import { tempDir } from "./helpers/temp-dir";-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-comfy-provider-"));+const dir = tempDir("fuobe-comfy-provider-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://comfy.test:8188";@@ -17,7 +15,6 @@ const { comfyProvider, collectOutputs, getWorkflow, loadManifest, mediaInfoFor,const { MODELS } = await import("@/lib/catalog");const { computeFrames } = await import("@/lib/comfy");-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));// ---------------------------------------------------------------------------// fetch + WebSocket stubsdiff --git a/tests/comfy-reach.test.ts b/tests/comfy-reach.test.tsindex 803eece8..556fbac4 100644--- a/tests/comfy-reach.test.ts+++ b/tests/comfy-reach.test.ts@@ -1,13 +1,11 @@-import fs from "node:fs";import http from "node:http";import net from "node:net";-import os from "node:os";-import path from "node:path";import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";import type { Generation } from "@/lib/catalog/types";+import { tempDir } from "./helpers/temp-dir";vi.setConfig({ testTimeout: 30_000 });-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-comfy-reach-"));+const dir = tempDir("fuobe-comfy-reach-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";@@ -73,7 +71,6 @@ afterAll(() => {Object.assign(REACH, reach);server.closeAllConnections();server.close();- fs.rmSync(dir, { recursive: true, force: true });});beforeEach(() => {delay = 0;diff --git a/tests/comfy-reuse.test.ts b/tests/comfy-reuse.test.tsindex d3dd3757..4252d924 100644--- a/tests/comfy-reuse.test.ts+++ b/tests/comfy-reuse.test.ts@@ -1,21 +1,20 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, describe, expect, it, vi } from "vitest";+import { describe, expect, it, vi } from "vitest";import type { GenInput } from "@/lib/catalog/types";import type { ComfyWorkflow, Manifest, ManifestWorkflow } from "@/lib/comfy";import { resolveWorkflowId } from "@/lib/comfy-variants";import { ATTRIBUTIONS, licenceInfo, licenceTerms, nodePack, OPENMDW_NOTICE, workflowLicence } from "@/lib/licences";import type { ReuseModel } from "@/lib/av/clean-voice";import type { MediaInfo } from "@/lib/media-probe";+import { tempDir } from "./helpers/temp-dir";// Clean up voice on the open engine: Fuobe's ComfyUI-RE-USE pack in this repository, its two graphs in the manifest, the// pinned weights, the install script, the licence rows, and how the provider fills the RE-USE bindings.-const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-comfy-reuse-"));+const tmp = tempDir("fuobe-comfy-reuse-");process.env.FUOBE_DATA_DIR = tmp;process.env.COMFYUI_URL = "http://comfy.test:8188";const { collectOutputs, comfyReuseModels, prepareWorkflow } = await import("@/server/providers/comfyui");-afterAll(() => fs.rmSync(tmp, { recursive: true, force: true }));const root = path.resolve(__dirname, "..");const read = (p: string) => fs.readFileSync(path.join(root, p), "utf8");diff --git a/tests/comfy-swap-studio.test.ts b/tests/comfy-swap-studio.test.tsindex 272fd131..9b416f78 100644--- a/tests/comfy-swap-studio.test.ts+++ b/tests/comfy-swap-studio.test.ts@@ -1,20 +1,19 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, describe, expect, it } from "vitest";+import { describe, expect, it } from "vitest";import type { ComfyWorkflow, Manifest } from "@/lib/comfy";import { getModel } from "@/lib/catalog";import { graphLoras, H3_WORKFLOWS, SWAP_LORAS, TURBO_LORA } from "@/lib/catalog/character-swap";import { STUDIO_MODELS, STUDIO_WORKFLOWS } from "@/lib/catalog/swap-studio-plan";import type { GenInput, Operation } from "@/lib/catalog/types";import type { MediaInfo } from "@/lib/media-probe";+import { tempDir } from "./helpers/temp-dir";// Character Swap Studio's two ComfyUI graphs (H3 Relay 2.0), bound for real by the provider on the library files.-const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-swap-studio-comfy-"));+const tmp = tempDir("fuobe-swap-studio-comfy-");process.env.FUOBE_DATA_DIR = tmp;process.env.COMFYUI_URL = "http://comfy.test:8188";const { prepareWorkflow } = await import("@/server/providers/comfyui");-afterAll(() => fs.rmSync(tmp, { recursive: true, force: true }));const dir = path.join(process.cwd(), "workflows/comfyui");const manifest = JSON.parse(fs.readFileSync(path.join(dir, "manifest.json"), "utf8")) as Manifest;diff --git a/tests/computer-pure.test.ts b/tests/computer-pure.test.tsindex dda6556f..79087f37 100644--- a/tests/computer-pure.test.ts+++ b/tests/computer-pure.test.ts@@ -1,6 +1,5 @@import { execFileSync } from "node:child_process";import fs from "node:fs";-import os from "node:os";import path from "node:path";import { describe, expect, it } from "vitest";import { corsFlag, fixFor, guessInstall, installFromStats, platformOf, startFile, START_FILE_NAME } from "@/lib/comfy-install";@@ -11,6 +10,7 @@ import { parseComfyBinary, parseComfyText } from "@/lib/comfy-ws";import { tileJob, type LocalJob } from "@/lib/computer-runner";import { browserSupport, COMFY_PORTS, firstPorts, graphProblem, lookStrength, localBase, mayDownload, pageCanReach, pickLook, portsToLook, preflightPath, readPath, sameFinder, settled, statsFacts, typedPort, viewPath, writePath, type Finder } from "@/lib/local-comfy";import { DONE_SHOWN_MS, duration, jobFraction, jobWords, madeNoun, makingWords, queueWords, RELAY_WORDS, reportAllowed, savingWords, sendingWords, tabFailureWords, type RelayState } from "@/lib/relay";+import { tempDir } from "./helpers/temp-dir";const ID = "0f8fad5b-d9cb-469f-a165-70867728950e";const OTHER = "7c9e6679-7425-40de-944b-e07fc1f90ae7";@@ -437,7 +437,7 @@ describe("ComfyUI's one setting", () => {it.runIf(process.platform === "win32")("is PowerShell that parses", () => {const bat = startFile(8189, "http://127.0.0.1:3370");const script = bat.slice(bat.indexOf("#FUOBE-PS"));- const file = path.join(fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-start-")), "s.ps1");+ const file = path.join(tempDir("fuobe-start-"), "s.ps1");fs.writeFileSync(file, script);const out = execFileSync("powershell",diff --git a/tests/computer-relay.test.ts b/tests/computer-relay.test.tsindex 7c92dd8c..94a37136 100644--- a/tests/computer-relay.test.ts+++ b/tests/computer-relay.test.ts@@ -1,14 +1,14 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";import { FAKE_PNG, startLocalComfy, type LocalComfy } from "./helpers/fake-local-comfy";import { loadRoutes, tab, type ComputerRoutes } from "./helpers/computer-tab";+import { tempDir } from "./helpers/temp-dir";vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));vi.setConfig({ testTimeout: 60_000 });-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-computer-relay-"));+const dir = tempDir("fuobe-computer-relay-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://owner-comfy.test:8188";process.env.FUOBE_PUBLIC_SIGNUP = "1";@@ -53,9 +53,6 @@ afterAll(async () => {globalThis.fetch = realFetch;globalThis.__fuobeTestDiskFree = undefined;await fake.close();- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}});beforeEach(() => {resetRates();diff --git a/tests/computer-security.test.ts b/tests/computer-security.test.tsindex 475ee0a3..81db25b0 100644--- a/tests/computer-security.test.ts+++ b/tests/computer-security.test.ts@@ -1,13 +1,13 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";import { FAKE_PNG } from "./helpers/fake-local-comfy";import { loadRoutes, type ComputerRoutes } from "./helpers/computer-tab";+import { tempDir } from "./helpers/temp-dir";vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-computer-security-"));+const dir = tempDir("fuobe-computer-security-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://owner-comfy.test:8188";process.env.FUOBE_PUBLIC_SIGNUP = "1";@@ -49,9 +49,6 @@ beforeAll(async () => {});afterAll(() => {globalThis.__fuobeTestDiskFree = undefined;- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}});beforeEach(() => {resetRates();diff --git a/tests/connect-card-studios.test.ts b/tests/connect-card-studios.test.tsindex 168221ec..86c508f7 100644--- a/tests/connect-card-studios.test.ts+++ b/tests/connect-card-studios.test.ts@@ -1,8 +1,6 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";import { afterAll, beforeAll, describe, expect, it } from "vitest";import type { EpisodeSettings, FacelessEpisode } from "@/lib/catalog/faceless";+import { tempDir } from "./helpers/temp-dir";/*** Placeholder results are off by default, so a studio's run with nothing connected is refused. In the owner's own@@ -10,7 +8,7 @@ import type { EpisodeSettings, FacelessEpisode } from "@/lib/catalog/faceless";* only the image and video composer: never a 500, an error toast, or a request for something else first.*/-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-connect-studios-"));+const dir = tempDir("fuobe-connect-studios-");process.env.FUOBE_DATA_DIR = dir;// Nothing listens: no ComfyUI, no local text model (the offline writer splits the script).process.env.COMFYUI_URL = "http://127.0.0.1:9";@@ -32,7 +30,6 @@ beforeAll(() => setSetting("enhanceProvider", "none"));afterAll(() => {globalThis.__fuobeDb?.close();globalThis.__fuobeDb = undefined;- fs.rmSync(dir, { recursive: true, force: true });});const json = (method: string, body?: unknown) =>diff --git a/tests/connections.test.ts b/tests/connections.test.tsindex 6114091d..8df0aabb 100644--- a/tests/connections.test.ts+++ b/tests/connections.test.ts@@ -1,14 +1,14 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, describe, expect, it, vi } from "vitest";+import { describe, expect, it, vi } from "vitest";import { candidateValues, connectionSummary, FIRST_RUN_KEY, FIRST_RUN_SCRIPT, isTestProvider, nothingConnected, PROVIDER_SETTINGS, settingProblem, showFirstRun, type ConnectionState } from "@/lib/connections";+import { tempDir } from "./helpers/temp-dir";/** Settings' "Save & test", the first-run guide's rule and the connection status strip (R4-02, R4-03, R4-33). */vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-connections-"));+const dir = tempDir("fuobe-connections-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.OLLAMA_URL = "http://127.0.0.1:9";@@ -18,7 +18,6 @@ const { POST: testRoute } = await import("@/app/api/providers/test/route");const { GET: statusRoute } = await import("@/app/api/status/route");const { getSetting, setSetting, withCandidates } = await import("@/server/settings");const { starterPriceLine } = await import("@/lib/starter-prices");-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));/** Answer fetches by URL prefix (status, JSON body); remembers each request's URL and headers. */async function withFetch<T>(answers: Record<string, [number, unknown]>, fn: () => Promise<T>) {diff --git a/tests/content-factory-api.test.ts b/tests/content-factory-api.test.tsindex 0e736c7e..d2c38e2d 100644--- a/tests/content-factory-api.test.ts+++ b/tests/content-factory-api.test.ts@@ -1,13 +1,13 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { beforeAll, describe, expect, it } from "vitest";import { offlineBrief, type SeriesEstimate, type SeriesView } from "@/lib/catalog/content-factory";+import { tempDir } from "./helpers/temp-dir";// Content Factory's server (r4/content-factory): references (an upload, a link through the guard and the// SSRF-safe fetch, a preset), reading them into a brief on both engines (demo mode here), prices, "Generate// here" (a channel and Faceless episodes that carry the brief), "Next episode", and the message for Claude.-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-content-factory-"));+const dir = tempDir("fuobe-content-factory-");process.env.FUOBE_DATA_DIR = dir;// Nothing listens: cloud and open models run on the demo provider, and there's no LLM (the offline writers run).process.env.COMFYUI_URL = "http://127.0.0.1:9";@@ -30,7 +30,6 @@ beforeAll(() => {setSetting("demoMode", "auto");setSetting("enhanceProvider", "none");});-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));const json = (method: string, body?: unknown) =>new Request("http://x/api", { method, headers: { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });diff --git a/tests/covers-from-masters.test.ts b/tests/covers-from-masters.test.tsindex b4d61167..ed1bbec8 100644--- a/tests/covers-from-masters.test.ts+++ b/tests/covers-from-masters.test.ts@@ -1,9 +1,9 @@import { spawnSync } from "node:child_process";import { createHash } from "node:crypto";import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, describe, expect, it } from "vitest";+import { describe, expect, it } from "vitest";+import { tempDir } from "./helpers/temp-dir";/** pnpm eval:covers --from-masters: rendered masters (one folder per preset id) become covers, merged into the manifest. */type Entry = { poster: string; video?: string; run: string; engine: string; model: string; variant: string };@@ -20,8 +20,7 @@ const covers = (await import("../scripts/eval/lib/covers.mjs")) as unknown as {};const { coversFromMasters, dissolveBack, loopsAlready, readManifest, seamless, versionCovers, withVersions, writeManifest } = covers;-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-covers-masters-"));-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));+const dir = tempDir("fuobe-covers-masters-");/** A content version as the covers spell it: the first 8 hex digits of the sha256 of these files, one after another. */const sha8 = (...files: string[]) => {diff --git a/tests/demo-ops.test.ts b/tests/demo-ops.test.tsindex 0322380a..c824df17 100644--- a/tests/demo-ops.test.ts+++ b/tests/demo-ops.test.ts@@ -1,8 +1,8 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { beforeAll, describe, expect, it, vi } from "vitest";import type { Generation, GenerationRequest } from "@/lib/catalog/types";+import { tempDir } from "./helpers/temp-dir";vi.mock("@/lib/catalog", async (importOriginal) => {const mod = await importOriginal<typeof import("@/lib/catalog")>();@@ -13,7 +13,7 @@ vi.mock("@/lib/catalog", async (importOriginal) => {});vi.setConfig({ testTimeout: 60_000 });-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-demo-ops-"));+const dir = tempDir("fuobe-demo-ops-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.OLLAMA_URL = "http://127.0.0.1:9";@@ -24,7 +24,6 @@ const { contentTypeFor, kindFor, saveFile } = await import("@/server/storage");const files = await import("@/app/api/files/[...path]/route");beforeAll(() => setSetting("demoMode", "auto"));-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));async function settle(id: string, ms = 40_000): Promise<Generation> {const end = Date.now() + ms;diff --git a/tests/dop-originals.test.ts b/tests/dop-originals.test.tsindex 9499856f..50ad69a9 100644--- a/tests/dop-originals.test.ts+++ b/tests/dop-originals.test.ts@@ -1,14 +1,12 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { beforeAll, describe, expect, it } from "vitest";import type { ComfyWorkflow } from "@/lib/comfy";import type { GenerationRequest, GenInput, ModelDef, ModelRoute } from "@/lib/catalog/types";+import { tempDir } from "./helpers/temp-dir";// Fuobe DoP as a run (build plan O4): one model on both engines for the camera motions and effects, the cloud payload// from the research's FieldMaps (49 or 81 frames at 16 fps, interpolation off), Mix on both engines, the LTX-2.3 graphs// with LoRAs, the Fun Camera pose, the relight step and the grade the browser applies.-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-dop-"));+const dir = tempDir("fuobe-dop-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9"; // nothing listens here: open runs fall back to the demo@@ -24,7 +22,6 @@ const { gradeOf, nextSteps } = await import("@/lib/output-actions");const { lorasFit } = await import("@/lib/catalog/loras");beforeAll(() => setSetting("demoMode", "auto"));-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));const view = (id: string, engine: "open" | "cloud") => onEngine(getModel(id)!, engine);// A move's own route: as when the model its preview was made with (MiniMax H3) isn't in the catalog, or Fuobe DoP is picked.diff --git a/tests/dropped-branch-migrations.test.ts b/tests/dropped-branch-migrations.test.tsindex 596776fb..a7b6a45d 100644--- a/tests/dropped-branch-migrations.test.ts+++ b/tests/dropped-branch-migrations.test.ts@@ -1,10 +1,10 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";import Database from "better-sqlite3";-import { afterAll, afterEach, describe, expect, it } from "vitest";+import { afterEach, describe, expect, it } from "vitest";+import { tempDir } from "./helpers/temp-dir";-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-dropped-migrations-"));+const dir = tempDir("fuobe-dropped-migrations-");process.env.FUOBE_DATA_DIR = dir;const file = path.join(dir, "fuobe.db");@@ -15,7 +15,6 @@ afterEach(() => {globalThis.__fuobeDb = undefined;for (const f of [file, `${file}-wal`, `${file}-shm`]) fs.rmSync(f, { force: true });});-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));// The dropped branch's own places 23 and 24 (claude/fuobe-r5-batch-7 at c9cd489), cut to what they made that matters// here: acc-1's people table linked to Better Auth and its append-only audit log, and acc-2's DELETE trigger.diff --git a/tests/e2e/_temp.mjs b/tests/e2e/_temp.mjsnew file mode 100644index 00000000..a60c36d7--- /dev/null+++ b/tests/e2e/_temp.mjs@@ -0,0 +1,42 @@+// Temp folders for the e2e scripts: `tempDir("fuobe-x-")` makes a new empty folder under the system temp folder and+// removes it when the script exits, however it exits (an `exit` handler). Removal retries while a stopped server or+// child process lets go of its files (Windows EPERM/EBUSY) and only warns when it can't. Folders a script keeps for+// people to look at (screenshots, renders) are made the usual way and printed instead.+import { spawnSync } from "node:child_process";+import fs from "node:fs";+import os from "node:os";+import path from "node:path";++const made = new Set();++export function tempDir(prefix) {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));+ if (made.size === 0) process.on("exit", () => made.forEach(removeDir));+ made.add(dir);+ return dir;+}++/**+ * Stop a server the script started, with the processes it started, and wait for it to exit, so its files in a temp+ * folder are closed. On Windows `child.kill()` stops only the first process and `next dev`'s own server keeps running.+ */+export async function stopProcess(child, waitMs = 5000) {+ if (!child || child.exitCode !== null || child.signalCode !== null) return;+ const exited = new Promise((r) => child.once("exit", r));+ if (process.platform === "win32" && child.pid) {+ spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });+ } else child.kill("SIGTERM");+ await Promise.race([exited, new Promise((r) => setTimeout(r, waitMs))]);+}++/** Remove a folder now, retrying for a few seconds; never throws. */+export function removeDir(dir) {+ made.delete(dir);+ try {+ fs.rmSync(dir, { recursive: true, force: true, maxRetries: 20, retryDelay: 250 });+ return true;+ } catch (e) {+ console.warn(`Couldn't remove ${dir}: ${e.message}`);+ return false;+ }+}diff --git a/tests/e2e/byo-keys.mjs b/tests/e2e/byo-keys.mjsindex 740c2cc9..04a3d468 100644--- a/tests/e2e/byo-keys.mjs+++ b/tests/e2e/byo-keys.mjs@@ -17,13 +17,14 @@ import os from "node:os";import path from "node:path";import { DESKTOP, launch, PHONE, root } from "./_browser.mjs";import { startFakeFal, startFakeReplicate } from "../helpers/fake-cloud.ts";+import { tempDir, removeDir } from "./_temp.mjs";const APP_PORT = Number(process.env.BYO_PORT ?? 3390);const APP = `http://127.0.0.1:${APP_PORT}`;const shots = path.resolve(process.argv[2] ?? fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-byo-shots-")));fs.mkdirSync(shots, { recursive: true });-const data = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-byo-data-"));-const logFile = path.join(data, "..", `${path.basename(data)}-server.log`);+const data = tempDir("fuobe-byo-data-");+const logFile = path.join(shots, "server.log");const PASSWORD = "owner password for the smoke";const OWNER_FAL = "owner-fal-db-key:owner-fal-db-secret";@@ -244,9 +245,7 @@ try {} finally {await stopAll();console.log(`\nscreenshots: ${shots}\nserver log: ${logFile}`);- try {- fs.rmSync(data, { recursive: true, force: true });- } catch {}+ removeDir(data);}if (failures.length) {console.log(`\n${failures.length} failed`);diff --git a/tests/e2e/character-swap-studio.mjs b/tests/e2e/character-swap-studio.mjsindex d46dca09..3d4a9ded 100644--- a/tests/e2e/character-swap-studio.mjs+++ b/tests/e2e/character-swap-studio.mjs@@ -8,9 +8,9 @@// Exits 1 on a failed check.import { execFileSync } from "node:child_process";import fs from "node:fs";-import os from "node:os";import path from "node:path";import { launch, root } from "./_browser.mjs";+import { tempDir } from "./_temp.mjs";const argv = process.argv.slice(2);const app = (argv.find((a) => !a.startsWith("--") && argv[argv.indexOf(a) - 1] !== "--shots") ?? "http://localhost:3000").replace(/\/$/, "");@@ -25,7 +25,7 @@ const check = (label, ok, extra = "") => {// The walk clip with a hard cut at 4 s (the last 2 s mirrored and inverted), as VP9 WebM: the browser reads its frames// for Detect edits and the frame to click (Playwright's Chromium decodes no H.264).const walk = path.join(root, "scripts/eval/fixtures/walk-6s.mp4");-const clipFile = path.join(fs.mkdtempSync(path.join(os.tmpdir(), "swap-studio-e2e-")), "walk.webm");+const clipFile = path.join(tempDir("swap-studio-e2e-"), "walk.webm");execFileSync("ffmpeg", ["-v", "error", "-y", "-i", walk,"-filter_complex", "[0:v]split[a][b];[a]trim=0:4,setpts=PTS-STARTPTS[v1];[b]trim=4:6,setpts=PTS-STARTPTS,negate,hflip[v2];[v1][v2]concat=n=2:v=1:a=0[v]",diff --git a/tests/e2e/cinema-blockout.mjs b/tests/e2e/cinema-blockout.mjsindex 678896a0..29448304 100644--- a/tests/e2e/cinema-blockout.mjs+++ b/tests/e2e/cinema-blockout.mjs@@ -12,9 +12,9 @@import assert from "node:assert/strict";import { execFileSync } from "node:child_process";import fs from "node:fs";-import os from "node:os";import path from "node:path";import { DESKTOP, PHONE, chromiumPath, loadPlaywright } from "./_browser.mjs";+import { tempDir, removeDir } from "./_temp.mjs";const args = process.argv.slice(2);const app = (args.find((a) => !a.startsWith("--")) ?? "http://localhost:3440").replace(/\/$/, "");@@ -48,7 +48,7 @@ const hideDevBadge = (ctx) =>}),);const noSideScroll = async (page, what) => assert.equal(await page.evaluate(() => document.documentElement.scrollWidth - window.innerWidth), 0, `${what}: nothing scrolls sideways`);-const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-blockout-e2e-"));+const tmp = tempDir("fuobe-blockout-e2e-");/** Frames and codec of a stored file, read with ffprobe. */async function probe(url) {const res = await (await api).fetch(app + url);@@ -237,6 +237,6 @@ try {console.error(e);} finally {await browser.close();- fs.rmSync(tmp, { recursive: true, force: true });+ removeDir(tmp);process.exit(failed ? 1 : 0);}diff --git a/tests/e2e/cinema-path.mjs b/tests/e2e/cinema-path.mjsindex 28e5df78..79bd7619 100644--- a/tests/e2e/cinema-path.mjs+++ b/tests/e2e/cinema-path.mjs@@ -12,9 +12,9 @@import assert from "node:assert/strict";import { execFileSync } from "node:child_process";import fs from "node:fs";-import os from "node:os";import path from "node:path";import { DESKTOP, PHONE, chromiumPath, loadPlaywright } from "./_browser.mjs";+import { tempDir } from "./_temp.mjs";const args = process.argv.slice(2);const app = (args.find((a) => !a.startsWith("--")) ?? "http://localhost:3000").replace(/\/$/, "");@@ -181,7 +181,7 @@ try {const openTake = await until(async () => (await items()).find((g) => g.feature === "cinema-path" && g.request.modelId === "oss-uni3c-path"), "the open path take");const render = openTake.request.inputs.video;assert.match(render, /^\/api\/files\/uploads\/.+\.(webm|mp4)$/);- const tmp = path.join(fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-path-")), path.basename(render));+ const tmp = path.join(tempDir("fuobe-path-"), path.basename(render));fs.writeFileSync(tmp, Buffer.from(await (await (await api).fetch(app + render)).body()));const probe = JSON.parse(execFileSync("ffprobe", ["-v", "error", "-count_frames", "-select_streams", "v:0", "-show_entries", "stream=width,height,nb_read_frames", "-of", "json", tmp]).toString()).streams[0];console.log(` render: ${path.extname(tmp)} ${probe.width}x${probe.height}, ${probe.nb_read_frames} frames`);diff --git a/tests/e2e/comfy-detect.mjs b/tests/e2e/comfy-detect.mjsindex c298cb31..847d2b37 100644--- a/tests/e2e/comfy-detect.mjs+++ b/tests/e2e/comfy-detect.mjs@@ -17,6 +17,7 @@ import http from "node:http";import os from "node:os";import path from "node:path";import { launch, root } from "./_browser.mjs";+import { tempDir, removeDir, stopProcess } from "./_temp.mjs";const APP_PORT = Number(process.env.E2E_APP_PORT ?? 3650);const COMFY_OPEN = 18188;@@ -27,7 +28,7 @@ const DEAD_PORT = 3659;const SITE = `http://127.0.0.1:${APP_PORT}`;const shots = process.env.E2E_SHOTS ?? fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-comfy-detect-shots-"));fs.mkdirSync(shots, { recursive: true });-const data = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-comfy-detect-e2e-"));+const data = tempDir("fuobe-comfy-detect-e2e-");const results = [];const check = (name, ok, detail = "") => {results.push({ name, ok: !!ok, detail });@@ -86,11 +87,8 @@ async function finish(code) {for (const p of procs) p.kill();otherApp.close();readableApp.close();- server.kill();- await sleep(500);- try {- fs.rmSync(data, { recursive: true, force: true });- } catch {}+ await stopProcess(server);+ removeDir(data);const failed = results.filter((r) => !r.ok);console.log(`\n${results.length - failed.length}/${results.length} passed. Screenshots: ${shots}`);if (failed.length) console.log(serverLog.split("\n").slice(-30).join("\n"));diff --git a/tests/e2e/comfyui-selftest.mjs b/tests/e2e/comfyui-selftest.mjsindex 36466f8b..8d2a86a7 100644--- a/tests/e2e/comfyui-selftest.mjs+++ b/tests/e2e/comfyui-selftest.mjs@@ -9,12 +9,12 @@// (local server only: COMFYUI_PID, else the "main.py --port <port>" process found with pgrep; COMFYUI_PORT, default 8188).import { spawnSync } from "node:child_process";import fs from "node:fs";-import os from "node:os";import path from "node:path";import zlib from "node:zlib";+import { tempDir, removeDir } from "./_temp.mjs";const app = process.argv[2] ?? "http://localhost:3000";-const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-selftest-"));+const tmp = tempDir("fuobe-selftest-");const hasFfprobe = spawnSync("ffprobe", ["-version"]).status === 0;const hasFfmpeg = spawnSync("ffmpeg", ["-version"]).status === 0;if (!hasFfprobe) console.warn("! ffprobe not found: outputs are checked for kind and size only");@@ -273,5 +273,5 @@ try {await realClip();console.log("ComfyUI engine OK");} finally {- fs.rmSync(tmp, { recursive: true, force: true });+ removeDir(tmp);}diff --git a/tests/e2e/computer-mode.mjs b/tests/e2e/computer-mode.mjsindex e5104443..94bf2def 100644--- a/tests/e2e/computer-mode.mjs+++ b/tests/e2e/computer-mode.mjs@@ -15,13 +15,14 @@ import fs from "node:fs";import os from "node:os";import path from "node:path";import { launch, root } from "./_browser.mjs";+import { tempDir, removeDir, stopProcess } from "./_temp.mjs";const APP_PORT = Number(process.env.E2E_APP_PORT ?? 3370);const FAKE_PORT = Number(process.env.E2E_FAKE_PORT ?? 3371);const SITE = `http://127.0.0.1:${APP_PORT}`;const FAKE = `http://127.0.0.1:${FAKE_PORT}`;const shots = process.env.E2E_SHOTS ?? fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-computer-shots-"));-const data = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-computer-e2e-"));+const data = tempDir("fuobe-computer-e2e-");const results = [];const check = (name, ok, detail = "") => {results.push({ name, ok: !!ok, detail });@@ -85,11 +86,8 @@ server.stderr.on("data", (d) => (serverLog += d));async function finish(code) {await stopFake().catch(() => {});- server.kill();- await sleep(500);- try {- fs.rmSync(data, { recursive: true, force: true });- } catch {}+ await stopProcess(server);+ removeDir(data);const failed = results.filter((r) => !r.ok);console.log(`\n${results.length - failed.length}/${results.length} passed. Screenshots: ${shots}`);if (failed.length) console.log(serverLog.split("\n").slice(-40).join("\n"));diff --git a/tests/e2e/eval-review.mjs b/tests/e2e/eval-review.mjsindex 0caf407c..14e26306 100644--- a/tests/e2e/eval-review.mjs+++ b/tests/e2e/eval-review.mjs@@ -11,13 +11,14 @@ import os from "node:os";import path from "node:path";import { pathToFileURL } from "node:url";import { DESKTOP, launch, PHONE, root } from "./_browser.mjs";+import { tempDir } from "./_temp.mjs";const { writeReport, loadRun } = await import(path.join(root, "scripts/eval/lib/report.mjs"));const { serveReview, writeReview } = await import(path.join(root, "scripts/eval/lib/review.mjs"));const { latestJobs } = await import(path.join(root, "scripts/eval/lib/store.mjs"));-const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-eval-review-"));-const shots = process.env.SHOTS ?? tmp;+const tmp = tempDir("fuobe-eval-review-");+const shots = process.env.SHOTS ?? fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-eval-review-shots-"));let runDir = process.argv[2] ? path.resolve(process.argv[2]) : null;/** A run like the runner writes: two looks × two variants × two seeds, on the fixture images. */diff --git a/tests/e2e/fuobe-connect.mjs b/tests/e2e/fuobe-connect.mjsindex c78616f7..468fa5bd 100644--- a/tests/e2e/fuobe-connect.mjs+++ b/tests/e2e/fuobe-connect.mjs@@ -11,17 +11,16 @@// reach any other route; an owner API token can't act as a worker; Disconnect in the studio stops the token at its// next call.import { spawn, spawnSync } from "node:child_process";-import fs from "node:fs";-import os from "node:os";import path from "node:path";import readline from "node:readline";import { root } from "./_browser.mjs";+import { tempDir, removeDir, stopProcess } from "./_temp.mjs";const APP_PORT = Number(process.env.E2E_APP_PORT ?? 3361);const FAKE_PORT = Number(process.env.E2E_FAKE_PORT ?? 3362);const SITE = `http://127.0.0.1:${APP_PORT}`;const FAKE = `http://127.0.0.1:${FAKE_PORT}`;-const data = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-connect-e2e-"));+const data = tempDir("fuobe-connect-e2e-");const results = [];const check = (name, ok, detail = "") => {results.push({ name, ok: !!ok, detail });@@ -85,11 +84,8 @@ async function account(email) {async function finish() {for (const c of clients) c.kill();fake.kill();- server.kill();- await sleep(500);- try {- fs.rmSync(data, { recursive: true, force: true });- } catch {}+ await stopProcess(server);+ removeDir(data);const failed = results.filter((r) => !r.ok);console.log(`\n${results.length - failed.length}/${results.length} passed.`);if (failed.length) console.log(serverLog.split("\n").slice(-40).join("\n"));diff --git a/tests/e2e/hosted-catchup.mjs b/tests/e2e/hosted-catchup.mjsindex 327c8005..bd031241 100644--- a/tests/e2e/hosted-catchup.mjs+++ b/tests/e2e/hosted-catchup.mjs@@ -7,9 +7,9 @@// Exits 1 on a failed check.import { spawnSync } from "node:child_process";import fs from "node:fs";-import os from "node:os";import path from "node:path";import { launch, root } from "./_browser.mjs";+import { tempDir, removeDir } from "./_temp.mjs";const argv = process.argv.slice(2);const app = (argv.find((a) => !a.startsWith("--") && argv[argv.indexOf(a) - 1] !== "--shots") ?? "http://localhost:3000").replace(/\/$/, "");@@ -22,7 +22,7 @@ const check = (label, ok, extra = "") => {if (!ok) failures.push(label);};-const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-catchup-e2e-"));+const tmp = tempDir("fuobe-catchup-e2e-");const ff = (args) => {const r = spawnSync("ffmpeg", ["-v", "error", "-y", ...args]);if (r.status !== 0) throw new Error(`ffmpeg failed: ${r.stderr}`);@@ -219,7 +219,7 @@ try {}} finally {await browser.close();- fs.rmSync(tmp, { recursive: true, force: true });+ removeDir(tmp);}if (failures.length) {console.log(`\n${failures.length} failed`);diff --git a/tests/e2e/kinetic-endcard.mjs b/tests/e2e/kinetic-endcard.mjsindex d1381f0b..a295babf 100644--- a/tests/e2e/kinetic-endcard.mjs+++ b/tests/e2e/kinetic-endcard.mjs@@ -22,12 +22,13 @@ import path from "node:path";import sharp from "sharp";import { DESKTOP, launch, PHONE, root } from "./_browser.mjs";import { startFakeFal } from "../helpers/fake-cloud.ts";+import { tempDir } from "./_temp.mjs";const PORT = Number(process.env.KINETIC_PORT ?? 3540);const APP = `http://127.0.0.1:${PORT}`;const out = path.resolve(process.argv[2] ?? fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-kinetic-")));fs.mkdirSync(out, { recursive: true });-const data = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-kinetic-data-"));+const data = tempDir("fuobe-kinetic-data-");const logFile = path.join(out, "server.log");const PASSWORD = "owner password for kinetic";const ACCT_FAL = "acct-kinetic-key:acct-kinetic-secret";diff --git a/tests/e2e/kling-4.mjs b/tests/e2e/kling-4.mjsindex a868dc20..1693ec1e 100644--- a/tests/e2e/kling-4.mjs+++ b/tests/e2e/kling-4.mjs@@ -7,9 +7,9 @@// Exits 1 on a failed check.import { spawnSync } from "node:child_process";import fs from "node:fs";-import os from "node:os";import path from "node:path";import { launch, root } from "./_browser.mjs";+import { tempDir, removeDir } from "./_temp.mjs";const argv = process.argv.slice(2);const app = (@@ -31,7 +31,7 @@ const check = (label, ok, extra = "") => {};// A 4 s 1280×720 clip Kling 4.0 takes, and the 432×768 fixture it doesn't (under 700 px on a side).-const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-kling-4-e2e-"));+const tmp = tempDir("fuobe-kling-4-e2e-");const clip720 = path.join(tmp, "clip-720p.mp4");const made = spawnSync("ffmpeg", ["-v",@@ -324,7 +324,7 @@ try {}} finally {await browser.close();- fs.rmSync(tmp, { recursive: true, force: true });+ removeDir(tmp);}if (failures.length) {console.log(`\n${failures.length} failed`);diff --git a/tests/e2e/library-flows.mjs b/tests/e2e/library-flows.mjsindex 72fd0f7c..dbc1eca6 100644--- a/tests/e2e/library-flows.mjs+++ b/tests/e2e/library-flows.mjs@@ -7,10 +7,9 @@// everything with the tag for good: the results, their files, the folders and the uploads. --keep// leaves them, to look at. Exits 1 when a check fails.import { execFileSync } from "node:child_process";-import fs from "node:fs";-import os from "node:os";import path from "node:path";import { DESKTOP, launch, openRoute, PHONE } from "./_browser.mjs";+import { tempDir } from "./_temp.mjs";const app = (process.argv.slice(2).find((a) => !a.startsWith("--")) ?? "http://localhost:3000").replace(/\/$/, "");const keep = process.argv.includes("--keep");@@ -211,7 +210,7 @@ try {await page.getByRole("button", { name: `Actions for ${A.name}` }).click();const [download] = await Promise.all([page.waitForEvent("download", { timeout: 20_000 }).catch(() => null), page.getByRole("menuitem", { name: "Download (.zip)" }).click()]);if (download) {- const file = path.join(fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-zip-")), "folder.zip");+ const file = path.join(tempDir("fuobe-zip-"), "folder.zip");await download.saveAs(file);const names = execFileSync("python3", ["-I", "-c", "import sys,zipfile;z=zipfile.ZipFile(sys.argv[1]);assert z.testzip() is None;print('|'.join(sorted(z.namelist())))", file]).toString().trim();check("the folder zip keeps subfolders as paths", names.includes(`${B.name}/`) && names.includes(`${B.name}/${C.name}/`), names);diff --git a/tests/e2e/mixed-shorts-original.mjs b/tests/e2e/mixed-shorts-original.mjsindex d5b38d3b..5b212e8c 100644--- a/tests/e2e/mixed-shorts-original.mjs+++ b/tests/e2e/mixed-shorts-original.mjs@@ -9,9 +9,9 @@// Exits 1 on a failed check.import { spawnSync } from "node:child_process";import fs from "node:fs";-import os from "node:os";import path from "node:path";import { launch, root } from "./_browser.mjs";+import { tempDir } from "./_temp.mjs";const argv = process.argv.slice(2);const app = (argv.find((a) => !a.startsWith("--") && argv[argv.indexOf(a) - 1] !== "--shots") ?? "http://localhost:3000").replace(/\/$/, "");@@ -38,7 +38,7 @@ const putSettings = (body) => fetch(`${app}/api/settings`, { method: "PUT", headconst clip = await upload("scripts/eval/fixtures/walk-6s.mp4", "video/mp4", "walk.mp4");// The cloud preview grabs its frame in the browser, and Playwright's Chromium can't decode H.264: Mixed Media gets the// same clip as VP9 when ffmpeg is here (else the cloud preview isn't checked).-const webm = path.join(fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-e2e-o9-")), "walk.webm");+const webm = path.join(tempDir("fuobe-e2e-o9-"), "walk.webm");const vp9 = spawnSync("ffmpeg", ["-v", "error", "-y", "-i", path.join(root, "scripts/eval/fixtures/walk-6s.mp4"), "-c:v", "libvpx-vp9", "-b:v", "300k", "-c:a", "libopus", webm]).status === 0;const mmClip = vp9 ? await upload(webm, "video/webm", "walk.webm") : clip;diff --git a/tests/e2e/owner-computer.mjs b/tests/e2e/owner-computer.mjsindex fce575f6..a9786c36 100644--- a/tests/e2e/owner-computer.mjs+++ b/tests/e2e/owner-computer.mjs@@ -17,6 +17,7 @@ import os from "node:os";import path from "node:path";import { DatabaseSync } from "node:sqlite";import { launch, root } from "./_browser.mjs";+import { tempDir, removeDir, stopProcess } from "./_temp.mjs";const MODE = process.env.E2E_MODE === "local" ? "local" : "hosted";const HOSTED = MODE === "hosted";@@ -29,7 +30,7 @@ const SITE = HOSTED ? `http://studio.test:${APP_PORT}` : `http://127.0.0.1:${APPconst LOCAL = `http://127.0.0.1:${APP_PORT}`;const shots = process.env.E2E_SHOTS ?? fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-owner-computer-shots-"));fs.mkdirSync(shots, { recursive: true });-const data = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-owner-computer-e2e-"));+const data = tempDir("fuobe-owner-computer-e2e-");const PASSWORD = `e2e-${Math.random().toString(36).slice(2)}`;const results = [];const check = (name, ok, detail = "") => {@@ -99,11 +100,8 @@ let browser;async function finish(code) {await browser?.close().catch(() => {});for (const port of [...fakes.keys()]) await stopFake(port).catch(() => {});- server.kill();- await sleep(800);- try {- fs.rmSync(data, { recursive: true, force: true });- } catch {}+ await stopProcess(server);+ removeDir(data);const failed = results.filter((r) => !r.ok);console.log(`\n[${MODE}] ${results.length - failed.length}/${results.length} passed. Screenshots: ${shots}`);if (failed.length) console.log(serverLog.split("\n").slice(-30).join("\n"));diff --git a/tests/e2e/restore-flows.mjs b/tests/e2e/restore-flows.mjsindex 8ab9eb32..9248e2eb 100644--- a/tests/e2e/restore-flows.mjs+++ b/tests/e2e/restore-flows.mjs@@ -6,9 +6,9 @@// Usage: node tests/e2e/restore-flows.mjs [appUrl] [--shots <dir>] Exits 1 on a failed check.import { execFileSync } from "node:child_process";import fs from "node:fs";-import os from "node:os";import path from "node:path";import { launch, root } from "./_browser.mjs";+import { tempDir, removeDir } from "./_temp.mjs";const argv = process.argv.slice(2);const app = (argv.find((a) => !a.startsWith("--") && argv[argv.indexOf(a) - 1] !== "--shots") ?? "http://localhost:3440").replace(/\/$/, "");@@ -23,7 +23,7 @@ const check = (label, ok, extra = "") => {const fixture = path.join(root, "tests/fixtures/shorts-12s.mp4");// Playwright's Chromium has no H.264 decoder: the Explainer reads its still in the browser, so it gets the clip as a// black-and-white VP9 WebM (ffmpeg), which also shows the black-and-white wording.-const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-restore-e2e-"));+const tmp = tempDir("fuobe-restore-e2e-");const greyWebm = path.join(tmp, "harbour-1930.webm");execFileSync("ffmpeg", ["-loglevel", "error", "-y", "-i", fixture, "-t", "4", "-vf", "hue=s=0", "-c:v", "libvpx-vp9", "-b:v", "200k", "-an", greyWebm]);@@ -167,7 +167,7 @@ try {}} finally {await browser.close();- fs.rmSync(tmp, { recursive: true, force: true });+ removeDir(tmp);}console.log(failures.length ? `\n${failures.length} failed` : "\nall checks passed");diff --git a/tests/e2e/worker.mjs b/tests/e2e/worker.mjsindex b34087df..6637a5a1 100644--- a/tests/e2e/worker.mjs+++ b/tests/e2e/worker.mjs@@ -14,14 +14,14 @@import { spawn } from "node:child_process";import fs from "node:fs";import net from "node:net";-import os from "node:os";import path from "node:path";import { root } from "./_browser.mjs";+import { tempDir, removeDir, stopProcess } from "./_temp.mjs";const APP_PORT = Number(process.env.E2E_APP_PORT ?? 3361);const COMFY_PORT = Number(process.env.E2E_FAKE_PORT ?? 3362);const SITE = `http://127.0.0.1:${APP_PORT}`;-const data = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-worker-e2e-"));+const data = tempDir("fuobe-worker-e2e-");const home = path.join(data, "worker-home");const workDir = path.join(data, "worker-folder");const smiState = path.join(data, "smi.json");@@ -77,11 +77,8 @@ const cli = (...args) => new Promise((r) => spawn(process.execPath, [path.join(rasync function finish() {await stopWorker().catch(() => {});- server.kill();- await sleep(500);- try {- fs.rmSync(data, { recursive: true, force: true });- } catch {}+ await stopProcess(server);+ removeDir(data);const failed = results.filter((r) => !r.ok);console.log(`\n${results.length - failed.length}/${results.length} passed.`);if (failed.length) console.log(`--- worker\n${workerLog.split("\n").slice(-40).join("\n")}\n--- studio\n${serverLog.split("\n").slice(-30).join("\n")}`);diff --git a/tests/edit-video-pricing.test.ts b/tests/edit-video-pricing.test.tsindex ef2f2407..31310702 100644--- a/tests/edit-video-pricing.test.ts+++ b/tests/edit-video-pricing.test.ts@@ -1,7 +1,5 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { beforeAll, describe, expect, it } from "vitest";+import { tempDir } from "./helpers/temp-dir";/*** Edit video (the generic v2v studio) prices a clip edit that keeps the clip's length (Happy Horse, Runway Aleph,@@ -9,7 +7,7 @@ import { afterAll, beforeAll, describe, expect, it } from "vitest";* window before anything is paid for (Happy Horse reads up to 60 s but returns at most 15 s, billed for all of it).*/-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-edit-video-"));+const dir = tempDir("fuobe-edit-video-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";@@ -57,9 +55,6 @@ beforeAll(() => {setSetting("demoMode", "auto");setSetting("enhanceProvider", "none");});-afterAll(() => {- fs.rmSync(dir, { recursive: true, force: true });-});describe("Edit video: clip edits priced on the clip, inside the model's window", () => {it("prices Happy Horse on the clip's seconds ($0.28 a second at 720p), not a flat 5 s", () => {diff --git a/tests/engine-mode.test.ts b/tests/engine-mode.test.tsindex 39fde998..417ba84c 100644--- a/tests/engine-mode.test.ts+++ b/tests/engine-mode.test.ts@@ -1,10 +1,8 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { beforeAll, describe, expect, it } from "vitest";+import { tempDir } from "./helpers/temp-dir";// Isolated database for this file (must be set before the server modules load).-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-test-"));+const dir = tempDir("fuobe-test-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9"; // nothing listens here → open models fall back to demo@@ -13,7 +11,6 @@ const { chooseRoute, createGenerations, previewGeneration } = await import("@/seconst { getModel } = await import("@/lib/catalog");beforeAll(() => setSetting("demoMode", "auto"));-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));describe("engine mode", () => {it("defaults to both and rejects invalid values", () => {diff --git a/tests/eval-api.test.ts b/tests/eval-api.test.tsindex 4fce4435..95662185 100644--- a/tests/eval-api.test.ts+++ b/tests/eval-api.test.ts@@ -1,23 +1,22 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { beforeAll, describe, expect, it, vi } from "vitest";import { getModel, getPreset } from "@/lib/catalog";import { planGeneration, routeLoras } from "@/lib/catalog/plan";import { loraEntry, loraRef } from "@/lib/catalog/loras";+import { tempDir } from "./helpers/temp-dir";/** The REST seams the evaluation harness (scripts/eval) needs: a recipe's LoRAs on POST /api/generations, and a preview that says which ones run. */vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-eval-api-"));+const dir = tempDir("fuobe-eval-api-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.OLLAMA_URL = "http://127.0.0.1:9";const { POST } = await import("@/app/api/generations/route");// Placeholders where nothing is connected, as these runs were written for ("auto": code in this process only).beforeAll(async () => (await import("@/server/settings")).setSetting("demoMode", "auto"));-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));const post = async (body: unknown, preview = true) => {const res = await POST(new Request(`http://localhost/api/generations${preview ? "?preview=1" : ""}`, { method: "POST", body: JSON.stringify(body) }));diff --git a/tests/eval-harness.test.ts b/tests/eval-harness.test.tsindex 40c8e238..b053cec9 100644--- a/tests/eval-harness.test.ts+++ b/tests/eval-harness.test.ts@@ -2,10 +2,10 @@ import { spawnSync } from "node:child_process";import fs from "node:fs";import http from "node:http";import type { AddressInfo } from "node:net";-import os from "node:os";import path from "node:path";import { Writable } from "node:stream";import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { tempDir } from "./helpers/temp-dir";/*** The evaluation harness (scripts/eval) end to end against Fuobe's real route handlers, served over@@ -16,7 +16,7 @@ import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));vi.setConfig({ testTimeout: 120_000, hookTimeout: 60_000 });-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-eval-harness-"));+const dir = tempDir("fuobe-eval-harness-");const results = path.join(dir, "results");process.env.FUOBE_DATA_DIR = path.join(dir, "data");process.env.COMFYUI_URL = "http://127.0.0.1:9";@@ -123,7 +123,6 @@ beforeAll(async () => {afterAll(async () => {await new Promise((r) => server.close(r));- fs.rmSync(dir, { recursive: true, force: true });});const sink = () => {diff --git a/tests/evolution-api.test.ts b/tests/evolution-api.test.tsindex d13c68da..b9fbdeca 100644--- a/tests/evolution-api.test.ts+++ b/tests/evolution-api.test.ts@@ -1,14 +1,14 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";import type { Generation } from "@/lib/catalog/types";+import { tempDir } from "./helpers/temp-dir";vi.setConfig({ testTimeout: 120_000 });// /api/evolution end to end in demo mode (no keys, no ComfyUI, no LLM): a run on either engine becomes one pipeline of// ordinary generations that the mock provider runs through; estimates with a fal key price the real hosted VACE route.-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-evolution-"));+const dir = tempDir("fuobe-evolution-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.OLLAMA_URL = "http://127.0.0.1:9";@@ -34,7 +34,6 @@ beforeAll(() => {const data = Buffer.alloc(32 * 32 * 4, 200);ref = saveFile({ data: encodePng({ width: 32, height: 32, data }), contentType: "image/png", source: "upload", name: "ref.png" }).url;});-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));async function settle(id: string, ms = 90_000): Promise<Generation> {const end = Date.now() + ms;diff --git a/tests/evolution-comfy.test.ts b/tests/evolution-comfy.test.tsindex a1d0ee54..daf591e0 100644--- a/tests/evolution-comfy.test.ts+++ b/tests/evolution-comfy.test.ts@@ -1,18 +1,17 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, describe, expect, it } from "vitest";+import { describe, expect, it } from "vitest";import { INTENSITIES, planEvolution } from "@/lib/catalog/evolution";import type { GenInput } from "@/lib/catalog/types";import type { MediaInfo } from "@/lib/media-probe";+import { tempDir } from "./helpers/temp-dir";// The comfyui provider driving Fuobe Evolution's GPU graph (video-evolution-wan22-fun-vace), bound for real on the// library graph, with a planned segment going through it.-const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-evolution-comfy-"));+const tmp = tempDir("fuobe-evolution-comfy-");process.env.FUOBE_DATA_DIR = tmp;process.env.COMFYUI_URL = "http://comfy.test:8188";const { prepareWorkflow } = await import("@/server/providers/comfyui");-afterAll(() => fs.rmSync(tmp, { recursive: true, force: true }));const seg: MediaInfo = { container: "mp4", hasVideo: true, hasAudio: false, duration: 61 / 16, videoDuration: 61 / 16, width: 848, height: 480, fps: 16, frames: 61 };const at = (wf: Record<string, { inputs: Record<string, unknown> }>, node: string, input: string) => wf[node]?.inputs[input];diff --git a/tests/example-refs.test.ts b/tests/example-refs.test.tsindex d1b4cece..96d801df 100644--- a/tests/example-refs.test.ts+++ b/tests/example-refs.test.ts@@ -1,8 +1,8 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";import { startFakeComfy, TINY_PNG, type FakeComfy } from "./helpers/fake-comfy-runner";+import { tempDir } from "./helpers/temp-dir";/*** "Start from an example": a run may read Fuobe's published example inputs (src/server/example-files.ts), the same for@@ -11,7 +11,7 @@ import { startFakeComfy, TINY_PNG, type FakeComfy } from "./helpers/fake-comfy-r* that steps out of its folder, not a link.*/-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-example-refs-"));+const dir = tempDir("fuobe-example-refs-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://owner-comfy.test:8188";process.env.FUOBE_PUBLIC_SIGNUP = "1";@@ -63,9 +63,6 @@ afterAll(async () => {globalThis.__fuobeTestGpuPort = undefined;globalThis.__fuobeTestDiskFree = undefined;await fake.close();- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}});beforeEach(() => {resetRates();diff --git a/tests/explainer-documents.test.ts b/tests/explainer-documents.test.tsindex ef3b426f..ecad0cf9 100644--- a/tests/explainer-documents.test.ts+++ b/tests/explainer-documents.test.ts@@ -1,9 +1,7 @@-import fs from "node:fs";import http from "node:http";-import os from "node:os";-import path from "node:path";import zlib from "node:zlib";import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+import { tempDir } from "./helpers/temp-dir";/** The Explainer's PDF and Word sources: .docx text through the bounded unzip (word/document.xml only),@@ -12,7 +10,7 @@ import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vites*/vi.setConfig({ testTimeout: 60_000 });-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-explainer-docs-"));+const dir = tempDir("fuobe-explainer-docs-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.OLLAMA_URL = "http://127.0.0.1:9";@@ -148,7 +146,6 @@ beforeAll(async () => {});afterAll(() => {ollama.close();- fs.rmSync(dir, { recursive: true, force: true });});beforeEach(async () => {asked.length = 0;diff --git a/tests/faceless-api.test.ts b/tests/faceless-api.test.tsindex 391a572a..179a1b7d 100644--- a/tests/faceless-api.test.ts+++ b/tests/faceless-api.test.ts@@ -1,10 +1,8 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { beforeAll, describe, expect, it } from "vitest";import type { EpisodeSettings, EpisodeView, FacelessChannel, FacelessEpisode } from "@/lib/catalog/faceless";+import { tempDir } from "./helpers/temp-dir";-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-faceless-"));+const dir = tempDir("fuobe-faceless-");process.env.FUOBE_DATA_DIR = dir;// Nothing listens: open models run on the demo provider, and there's no LLM (the offline writer runs).process.env.COMFYUI_URL = "http://127.0.0.1:9";@@ -30,7 +28,6 @@ beforeAll(() => {setSetting("demoMode", "auto");setSetting("enhanceProvider", "none");});-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));const json = (method: string, body?: unknown) =>new Request("http://x/api", { method, headers: { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });diff --git a/tests/faceless-llm.test.ts b/tests/faceless-llm.test.tsindex cea4c97d..05f18178 100644--- a/tests/faceless-llm.test.ts+++ b/tests/faceless-llm.test.ts@@ -1,9 +1,7 @@-import fs from "node:fs";import http from "node:http";-import os from "node:os";-import path from "node:path";import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";import { tooLong, type EpisodeSettings } from "@/lib/catalog/faceless";+import { tempDir } from "./helpers/temp-dir";/** Faceless Studio and the Explainer with an LLM: channel names, topics, scripts, pictures for a pasted@@ -12,7 +10,7 @@ import { tooLong, type EpisodeSettings } from "@/lib/catalog/faceless";*/vi.setConfig({ testTimeout: 60_000 });-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-faceless-llm-"));+const dir = tempDir("fuobe-faceless-llm-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";// The link below is served by the stand-in on 127.0.0.1.@@ -97,7 +95,6 @@ beforeAll(async () => {});afterAll(() => {server.close();- fs.rmSync(dir, { recursive: true, force: true });});const settings: EpisodeSettings = {diff --git a/tests/fal-lora.test.ts b/tests/fal-lora.test.tsindex dca88ac1..e15265f6 100644--- a/tests/fal-lora.test.ts+++ b/tests/fal-lora.test.ts@@ -1,18 +1,15 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, describe, expect, it } from "vitest";+import { describe, expect, it } from "vitest";import { getModel } from "@/lib/catalog";import { loraEntry, loraRef, fitLoras, loraFields, cloudPath, lorasFit } from "@/lib/catalog/loras";import { buildPayload, numFramesValue } from "@/lib/catalog/payload";import { estimateCost } from "@/lib/catalog/plan";import type { GenInput, LoraRef, ModelRoute } from "@/lib/catalog/types";+import { tempDir } from "./helpers/temp-dir";// The fal adapter reads its key from the settings table: a throwaway database.-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-fal-lora-"));+const dir = tempDir("fuobe-fal-lora-");process.env.FUOBE_DATA_DIR = dir;const { falProvider } = await import("@/server/providers/fal");-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));/** Submit through the fal adapter and return the URL and JSON body it posted. */async function submit(route: ModelRoute, input: GenInput): Promise<{ url: string; body: Record<string, unknown> }> {diff --git a/tests/files-route.test.ts b/tests/files-route.test.tsindex b087fafa..14fe62ca 100644--- a/tests/files-route.test.ts+++ b/tests/files-route.test.ts@@ -1,16 +1,11 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, describe, expect, it, vi } from "vitest";+import { describe, expect, it, vi } from "vitest";+import { tempDir } from "./helpers/temp-dir";-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-files-route-"));+const dir = tempDir("fuobe-files-route-");process.env.FUOBE_DATA_DIR = dir;const { GET } = await import("@/app/api/files/[...path]/route");-afterAll(() => {- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}-});const get = (parts: string[]) => GET(new Request(`http://localhost:3000/api/files/${parts.join("/")}`), { params: Promise.resolve({ path: parts }) } as never);diff --git a/tests/flux3-klein.test.ts b/tests/flux3-klein.test.tsindex 4108250b..da3a08e2 100644--- a/tests/flux3-klein.test.ts+++ b/tests/flux3-klein.test.ts@@ -1,7 +1,6 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, describe, expect, it } from "vitest";+import { describe, expect, it } from "vitest";import { getModel, getPreset, MODELS } from "@/lib/catalog";import { loraEndpointFor } from "@/lib/catalog/loras";import { buildPayload } from "@/lib/catalog/payload";@@ -14,11 +13,12 @@ import { filterModels, settingsShape, studioBest } from "@/lib/composer";import { compileFlux3, flux3Boxes, flux3Caption, validateLayout, type LayoutDraft } from "@/lib/layout-prompt";import { licenceInfo } from "@/lib/licences";import { EDIT_STUDIO, IMAGE_STUDIO } from "@/lib/studios";+import { tempDir } from "./helpers/temp-dir";// Package nm10-flux3-klein (docs/research/new-models-10.md §6.3): FLUX 3 Image Klein on both engines. Three ComfyUI graphs from// Comfy-Org's Klein templates on BFL's pinned repack, fal's routes and LoRA twins from research #10's endpoint records, a layout// as fal's bounding_boxes, and a Soul ID training target on fal's Klein Base trainer and on AI-Toolkit's flux3 model.-const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-klein-"));+const tmp = tempDir("fuobe-klein-");process.env.FUOBE_DATA_DIR = tmp;process.env.COMFYUI_URL = "http://comfy.test:8188";const { prepareWorkflow } = await import("@/server/providers/comfyui");@@ -26,7 +26,6 @@ const { setSetting } = await import("@/server/settings");const { createGenerations, getGeneration } = await import("@/server/generations");const { saveFile } = await import("@/server/storage");const { db } = await import("@/server/db");-afterAll(() => fs.rmSync(tmp, { recursive: true, force: true }));const dir = path.join(process.cwd(), "workflows/comfyui");const manifest = JSON.parse(fs.readFileSync(path.join(dir, "manifest.json"), "utf8")) as Manifest;diff --git a/tests/fly-around.test.ts b/tests/fly-around.test.tsindex 65f0bc92..c37b7d5f 100644--- a/tests/fly-around.test.ts+++ b/tests/fly-around.test.ts@@ -1,15 +1,13 @@import { spawnSync } from "node:child_process";-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { beforeAll, describe, expect, it } from "vitest";+import { tempDir } from "./helpers/temp-dir";/*** Exact orbits and Fly around: the orbit's numbers as camera-path keys, the plan on both engines, the* server's headless path render (option B) and its chain slot, and /api/fly-around.*/-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-fly-around-"));+const dir = tempDir("fuobe-fly-around-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.OLLAMA_URL = "http://127.0.0.1:9";@@ -30,7 +28,6 @@ beforeAll(() => {setSetting("demoMode", "auto");setSetting("enhanceProvider", "none");});-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));/** A 64 × 48 still: a red square in the middle of a blue field, and its depth (the square near, bright). */function scene() {diff --git a/tests/generations-local-motion.test.ts b/tests/generations-local-motion.test.tsindex c166cc68..795f8322 100644--- a/tests/generations-local-motion.test.ts+++ b/tests/generations-local-motion.test.ts@@ -1,9 +1,7 @@-import fs from "node:fs";import http from "node:http";-import os from "node:os";-import path from "node:path";import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";import { NextRequest } from "next/server";+import { tempDir } from "./helpers/temp-dir";// Kinetic Motion results through Fuobe (POST /api/generations/local): the owner records its own clip; an account// records only its own clip, made from its own files, as its own run (its list, never the owner's Library), within its@@ -12,7 +10,7 @@ import { NextRequest } from "next/server";vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));vi.setConfig({ testTimeout: 30_000 });-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-local-motion-"));+const dir = tempDir("fuobe-local-motion-");process.env.FUOBE_DATA_DIR = dir;delete process.env.FUOBE_PASSWORD;delete process.env.FUOBE_MODERATION_URL;@@ -53,9 +51,6 @@ afterEach(() => {});afterAll(() => {moderation?.close();- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}});const MP4 = Buffer.concat([Buffer.from([0, 0, 0, 0x18]), Buffer.from("ftypisom"), Buffer.alloc(200, 1)]);diff --git a/tests/genjutsu-api.test.ts b/tests/genjutsu-api.test.tsindex 1d39870e..a6c0a380 100644--- a/tests/genjutsu-api.test.ts+++ b/tests/genjutsu-api.test.ts@@ -1,17 +1,17 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";import http from "node:http";import { CLOUD_NO_LORA } from "@/lib/catalog/character-swap";import { CLOUD_CLICK_PROBLEM } from "@/lib/catalog/genjutsu";import type { Generation } from "@/lib/catalog/types";+import { tempDir } from "./helpers/temp-dir";vi.setConfig({ testTimeout: 120_000 });// /api/genjutsu end to end in demo mode (no keys, no ComfyUI): each mode on both engines becomes one pipeline of// ordinary generations, which the mock provider runs through; estimates with keys set price the real routes.-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-genjutsu-"));+const dir = tempDir("fuobe-genjutsu-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.OLLAMA_URL = "http://127.0.0.1:9";@@ -49,7 +49,6 @@ beforeAll(() => {hero = saveFile({ data: px(64, 64, () => true), contentType: "image/png", source: "upload", name: "hero.png" }).url;mask = saveFile({ data: px(72, 128, (x, y) => x >= 20 && x < 50 && y >= 80 && y < 110), contentType: "image/png", source: "upload", name: "mask.png" }).url;});-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));async function settle(id: string, ms = 90_000): Promise<Generation> {const end = Date.now() + ms;diff --git a/tests/genjutsu-comfy.test.ts b/tests/genjutsu-comfy.test.tsindex 9122e115..2cc07677 100644--- a/tests/genjutsu-comfy.test.ts+++ b/tests/genjutsu-comfy.test.ts@@ -1,18 +1,15 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, describe, expect, it } from "vitest";+import { describe, expect, it } from "vitest";import { getMaker, OPEN_TARGET_PROBLEM, ORIGINALS, planGenjutsu } from "@/lib/catalog/genjutsu";import type { GenInput, Operation } from "@/lib/catalog/types";import type { MediaInfo } from "@/lib/media-probe";+import { tempDir } from "./helpers/temp-dir";// The comfyui provider driving Genjutsu's open graphs (Wan 2.1 VACE swap / insert, Wan Animate 2, MiniMax H3's// Character swap), bound for real on the library graphs, and planned steps going through it.-const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-genjutsu-comfy-"));+const tmp = tempDir("fuobe-genjutsu-comfy-");process.env.FUOBE_DATA_DIR = tmp;process.env.COMFYUI_URL = "http://comfy.test:8188";const { prepareWorkflow, withoutAnchor } = await import("@/server/providers/comfyui");-afterAll(() => fs.rmSync(tmp, { recursive: true, force: true }));const clip: MediaInfo = { container: "mp4", hasVideo: true, hasAudio: true, duration: 12, videoDuration: 12, width: 1280, height: 720, fps: 30, frames: 360 };const prepare = (id: string, input: Partial<GenInput>, op: Operation) =>diff --git a/tests/genjutsu-live.test.ts b/tests/genjutsu-live.test.tsindex 5b075164..b57a0205 100644--- a/tests/genjutsu-live.test.ts+++ b/tests/genjutsu-live.test.ts@@ -1,14 +1,14 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";import { describe, expect, it } from "vitest";import { GENJUTSU_FEATURE_KEYS, GENJUTSU_FEATURES } from "@/lib/catalog/genjutsu";import { genjutsuLive } from "@/server/genjutsu-live";+import { tempDir } from "./helpers/temp-dir";// Genjutsu's Openjutsu features open to everyone one by one: each needs its workflows accepted by ComfyUI AND a real render// recorded as passed (workflows/comfyui/gpu-tested.json). The manifest flag alone never opens one.const ROOT = process.cwd();-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-genjutsu-live-"));+const dir = tempDir("fuobe-genjutsu-live-");const write = (name: string, v: unknown) => {const f = path.join(dir, name);fs.writeFileSync(f, typeof v === "string" ? v : JSON.stringify(v));diff --git a/tests/genjutsu-openjutsu-access.test.ts b/tests/genjutsu-openjutsu-access.test.tsindex e995f1f1..afd04d80 100644--- a/tests/genjutsu-openjutsu-access.test.ts+++ b/tests/genjutsu-openjutsu-access.test.ts@@ -1,8 +1,8 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";+import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";import { NextRequest } from "next/server";+import { tempDir } from "./helpers/temp-dir";vi.setConfig({ testTimeout: 60_000 });@@ -11,7 +11,7 @@ vi.setConfig({ testTimeout: 60_000 });* an account's price check for it is refused in words (the tab isn't shown to them either); runs and From picture's* describer stay the owner's on this server, as every Genjutsu run.*/-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-genjutsu-oj-access-"));+const dir = tempDir("fuobe-genjutsu-oj-access-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.OLLAMA_URL = "http://127.0.0.1:9";@@ -29,11 +29,6 @@ const sceneRoute = await import("@/app/api/genjutsu/scene/route");const { estimateGenjutsu, NOT_HERE } = await import("@/server/genjutsu");const generationsRoute = await import("@/app/api/generations/route");const { directRunFeatures } = await import("@/lib/catalog/genjutsu");-afterAll(() => {- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}-});const passed = (r: Response) => r.headers.get("x-middleware-next") === "1";const req = (url: string, init: { method?: string; cookie?: string } = {}) => {diff --git a/tests/genjutsu-openjutsu-comfy.test.ts b/tests/genjutsu-openjutsu-comfy.test.tsindex 7e6d6772..da69485b 100644--- a/tests/genjutsu-openjutsu-comfy.test.ts+++ b/tests/genjutsu-openjutsu-comfy.test.ts@@ -1,19 +1,16 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, describe, expect, it, vi } from "vitest";+import { describe, expect, it, vi } from "vitest";import { getMaker, planGenjutsu } from "@/lib/catalog/genjutsu";import { danglingLinks, OPENJUTSU_WORKFLOWS as W } from "@/lib/openjutsu-graphs";import type { GenInput, Operation } from "@/lib/catalog/types";import type { MediaInfo } from "@/lib/media-probe";+import { tempDir } from "./helpers/temp-dir";// The comfyui provider driving Genjutsu's Openjutsu graphs: the media bound, the settings written by title, the pictures// a request leaves out taken out with their branches, and a Context Loop job's run folder deleted once it ends.-const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-genjutsu-oj-comfy-"));+const tmp = tempDir("fuobe-genjutsu-oj-comfy-");process.env.FUOBE_DATA_DIR = tmp;process.env.COMFYUI_URL = "http://comfy.test:8188";const { prepareWorkflow, deleteRunFolder } = await import("@/server/providers/comfyui");-afterAll(() => fs.rmSync(tmp, { recursive: true, force: true }));const clip: MediaInfo = { container: "mp4", hasVideo: true, hasAudio: true, duration: 6, videoDuration: 6, width: 1308, height: 736, fps: 24, frames: 144 };const prepare = (id: string, input: Partial<GenInput>, op: Operation) =>diff --git a/tests/glb-finish-safety.test.ts b/tests/glb-finish-safety.test.tsindex 3d0bbd21..2b5f309c 100644--- a/tests/glb-finish-safety.test.ts+++ b/tests/glb-finish-safety.test.ts@@ -1,10 +1,10 @@import { spawnSync } from "node:child_process";import fs from "node:fs";-import os from "node:os";import path from "node:path";import { afterAll, describe, expect, it } from "vitest";+import { tempDir } from "./helpers/temp-dir";-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-glb-safety-"));+const dir = tempDir("fuobe-glb-safety-");process.env.FUOBE_DATA_DIR = path.join(dir, "data");process.env.FUOBE_TEST_SECRET = "do-not-pass-this-on";const { ACCOUNT_TURNTABLE, finishModel, pendingTurntable, scriptEnv } = await import("@/server/model3d-finish");@@ -13,9 +13,6 @@ const { createGenerations } = await import("@/server/generations");const { OWN_GPU_TOOL_MESSAGE } = await import("@/lib/guest-access");afterAll(() => {delete process.env.FUOBE_TEST_SECRET;- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}});const SCRIPT = path.join(process.cwd(), "scripts", "model3d", "finish-glb.mjs");diff --git a/tests/gpu-api.test.ts b/tests/gpu-api.test.tsindex 4ca75fc2..25d58609 100644--- a/tests/gpu-api.test.ts+++ b/tests/gpu-api.test.ts@@ -1,14 +1,14 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";import { NextRequest } from "next/server";import { startFakeComfy, readyFor, type FakeComfy } from "./helpers/fake-comfy";+import { tempDir } from "./helpers/temp-dir";vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));vi.setConfig({ testTimeout: 30_000 });-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-gpu-api-"));+const dir = tempDir("fuobe-gpu-api-");process.env.FUOBE_DATA_DIR = dir;process.env.FUOBE_PUBLIC_SIGNUP = "1";delete process.env.FUOBE_PASSWORD;@@ -38,9 +38,6 @@ const fakes: FakeComfy[] = [];afterAll(async () => {globalThis.__fuobeGpuTestTransport = undefined;await Promise.all(fakes.map((f) => f.close()));- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}});/** Account GPUs live at "<name>.gpu.test:<port>"; the tests resolve those names to the fake server (no env switch). */diff --git a/tests/h3-any-gpu.test.ts b/tests/h3-any-gpu.test.tsindex 34aa5cf4..cbb228c4 100644--- a/tests/h3-any-gpu.test.ts+++ b/tests/h3-any-gpu.test.ts@@ -1,15 +1,15 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";import { afterAll, beforeAll, describe, expect, it } from "vitest";import type { GenInput } from "@/lib/catalog/types";import type { ComfyWorkflow, ManifestWorkflow } from "@/lib/comfy";import type { GpuInventory, RequirementIndex } from "@/lib/gpu/types";+import { tempDir } from "./helpers/temp-dir";// MiniMax H3 on smaller cards (docs/research/new-models-10.md §6.4): MiniMax H3 on 8-31 GB cards (FastH3 V2 and Trim), the GPU// tier decided once per run, the pre-flight checking the graph and file the run loads, the board naming each card's build,// and Fast decode (Sol-H3-VAE) on the full model. All on the open engine: the cloud keeps fal's hosted MiniMax H3.-const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-h3-any-gpu-"));+const tmp = tempDir("fuobe-h3-any-gpu-");process.env.FUOBE_DATA_DIR = tmp;process.env.COMFYUI_URL = "http://comfy.test:8188";const { prepareWorkflow } = await import("@/server/providers/comfyui");@@ -24,7 +24,6 @@ const { writeSnapshot, dropSnapshots } = await import("@/server/gpu/snapshots");const { gateGeneration } = await import("@/server/gpu/gate");const { buildViews } = await import("@/server/gpu/readiness-service");const { STUDIO_ROWS, studioTool } = await import("@/server/gpu/tools");-afterAll(() => fs.rmSync(tmp, { recursive: true, force: true }));const LIBRARY = path.join(process.cwd(), "workflows/comfyui");const read = (f: string) => JSON.parse(fs.readFileSync(path.join(LIBRARY, f), "utf8"));diff --git a/tests/helpers/temp-dir.ts b/tests/helpers/temp-dir.tsnew file mode 100644index 00000000..9a68c835--- /dev/null+++ b/tests/helpers/temp-dir.ts@@ -0,0 +1,117 @@+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterAll } from "vitest";++/**+ * Temp folders for tests. `tempDir("fuobe-x-")` makes a new empty folder under the system temp folder and removes it+ * after the test file's last test, wherever it was made (at the top of the file, in a hook or in a test).+ *+ * Windows won't delete a file that is still open, so when the install's database (src/server/db.ts) lives in the+ * folder, the background runners' timers are stopped and the database is closed first, and removal retries while+ * other handles let go. The worker's temp folder points inside the run's own folder (tests/setup/temp-root.ts), which+ * is removed after the run as well, so a folder this misses is still cleared.+ */++const made = new Set<string>();++export function tempDir(prefix: string): string {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));+ made.add(dir);+ return dir;+}++/** Remove a temp folder now: stops what writes to the database in it, retries on Windows EPERM/EBUSY, never throws. */+export async function removeTempDir(dir: string): Promise<void> {+ made.delete(dir);+ const hadDatabase = holdsDatabase(dir);+ if (hadDatabase) {+ stopBackgroundTimers();+ // A tick that was already running finishes its query before the database closes.+ await sleep(50);+ }+ for (let attempt = 0; attempt < 5; attempt++) {+ closeDatabaseIn(dir);+ if (!(await removeDir(dir))) return;+ if (!hadDatabase) return;+ // A run a test started and didn't wait for can carry on for a moment and open the database again, which makes the+ // folder again. Test processes are stopped, not exited, so nothing can clear it later in this process.+ await sleep(250);+ if (!fs.existsSync(dir)) return;+ }+ console.warn(`[tests] Couldn't remove ${dir}: it was made again after being removed`);+}++const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));++const RETRY = new Set(["EPERM", "EBUSY", "ENOTEMPTY", "EACCES", "EMFILE", "ENFILE"]);++/**+ * Retries cover a handle that is closing (a server, a child process, an antivirus scan); a failure is only a warning.+ * The removal itself is synchronous: `fs.promises.rm` runs on libuv's thread pool, which code under test can keep+ * busy, and then it never finishes. The waits between tries let other handles close.+ */+export async function removeDir(dir: string): Promise<boolean> {+ for (let attempt = 1; ; attempt++) {+ try {+ fs.rmSync(dir, { recursive: true, force: true });+ return true;+ } catch (e) {+ const code = (e as NodeJS.ErrnoException).code ?? "";+ if (!RETRY.has(code) || attempt >= 20) {+ console.warn(`[tests] Couldn't remove ${dir}: ${(e as Error).message}`);+ return false;+ }+ await sleep(Math.min(100 * attempt, 500));+ }+ }+}++function inside(file: string, dir: string): boolean {+ const rel = path.relative(path.resolve(dir), path.resolve(file));+ return rel === "" || (!!rel && !rel.startsWith("..") && !path.isAbsolute(rel));+}++function holdsDatabase(dir: string): boolean {+ const db = globalThis.__fuobeDb;+ return !!db && inside(db.name, dir);+}++/** The database file and its -wal/-shm stay open until the connection closes. A later `db()` opens it again. */+function closeDatabaseIn(dir: string): void {+ const db = globalThis.__fuobeDb;+ if (!db || !inside(db.name, dir)) return;+ try {+ if (db.open) db.close();+ } catch {+ // Already closing.+ }+ globalThis.__fuobeDb = undefined;+}++function isTimer(v: unknown): v is NodeJS.Timeout {+ return typeof v === "object" && v !== null && typeof (v as NodeJS.Timeout).refresh === "function" && typeof (v as NodeJS.Timeout).hasRef === "function";+}++/**+ * The server's background runners (generations, schedules, skills, trash purge and others) keep their timers on+ * `globalThis.__fuobe*`, alone or on a state object. Each tick reads the database and would open it again in a folder+ * that is being removed, so they stop once the file's tests are done. Each test file runs in a process of its own.+ */+function stopBackgroundTimers(): void {+ const g = globalThis as unknown as Record<string, unknown>;+ for (const key of Object.keys(g)) {+ if (!key.startsWith("__fuobe") || key === "__fuobeDb") continue;+ const v = g[key];+ if (isTimer(v)) clearInterval(v);+ else if (v && typeof v === "object" && Object.getPrototypeOf(v) === Object.prototype) {+ for (const inner of Object.values(v)) if (isTimer(inner)) clearInterval(inner);+ }+ }+}++// Registered when the first test file imports this module, so with Vitest's default hook order ("stack") it runs+// after the file's own afterAll hooks have closed their servers and stand-ins.+afterAll(async () => {+ for (const dir of [...made]) await removeTempDir(dir);+}, 60_000);diff --git a/tests/hosted-catchup.test.ts b/tests/hosted-catchup.test.tsindex d94dee60..93c14ef4 100644--- a/tests/hosted-catchup.test.ts+++ b/tests/hosted-catchup.test.ts@@ -1,7 +1,6 @@import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, describe, expect, it } from "vitest";+import { describe, expect, it } from "vitest";+import { tempDir } from "./helpers/temp-dir";/*** The hosted catch-up: fal's H3 Max lip sync, relight, insert and five looks, H3 Max Turbo, Vidu Q4, Meshy retexture and@@ -10,10 +9,9 @@ import { afterAll, describe, expect, it } from "vitest";* them. No paid call is made: pure functions and demo mode only.*/-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-hosted-catchup-"));+const dir = tempDir("fuobe-hosted-catchup-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));const { getModel, getPreset, MODELS } = await import("@/lib/catalog");const { buildPayload, extractOutputs } = await import("@/lib/catalog/payload");diff --git a/tests/hosted-runs-voice-design.test.ts b/tests/hosted-runs-voice-design.test.tsindex bf039beb..c68d2701 100644--- a/tests/hosted-runs-voice-design.test.ts+++ b/tests/hosted-runs-voice-design.test.ts@@ -1,15 +1,13 @@-import fs from "node:fs";import http from "node:http";-import os from "node:os";-import path from "node:path";import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";import { FAKE_POLICY, listenInRange, startFakeBilling, type FakeBilling } from "./helpers/fake-billing";import { startFakeComfy, type FakeComfy } from "./helpers/fake-comfy-runner";+import { tempDir } from "./helpers/temp-dir";// Design a voice on hosted runs (FUOBE_HOSTED_RUNS=1): an account with no GPU of its own may design a voice on this// install's ComfyUI like any open model, priced by the billing service as an audio run. A clone reads a voice sample,// so it follows the policy's audio uploads, and the hosted Qwen3-TTS on fal never runs there.-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-hosted-voice-"));+const dir = tempDir("fuobe-hosted-voice-");process.env.FUOBE_DATA_DIR = dir;process.env.FUOBE_PUBLIC_SIGNUP = "1";delete process.env.FUOBE_PASSWORD;@@ -39,7 +37,6 @@ afterAll(async () => {for (const k of ["FUOBE_HOSTED_RUNS", "FUOBE_BILLING_URL", "FUOBE_BILLING_TOKEN"]) delete process.env[k];await fake.close();await comfy.close();- fs.rmSync(dir, { recursive: true, force: true });});beforeEach(() => {billing.resetBillingCache();diff --git a/tests/hosted-runs.test.ts b/tests/hosted-runs.test.tsindex 491e31e7..4099a198 100644--- a/tests/hosted-runs.test.ts+++ b/tests/hosted-runs.test.ts@@ -1,14 +1,12 @@-import fs from "node:fs";import http from "node:http";-import os from "node:os";-import path from "node:path";import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";import { listenInRange, startFakeBilling, type FakeBilling } from "./helpers/fake-billing";import { startFakeComfy, TINY_MP4, TINY_PNG, type FakeComfy } from "./helpers/fake-comfy-runner";+import { tempDir } from "./helpers/temp-dir";// Hosted runs (FUOBE_HOSTED_RUNS=1): off, everything is as before; on, an account with no GPU of its own may run in// the studios on this install's ComfyUI, and every other tool still needs its own GPU.-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-hosted-runs-"));+const dir = tempDir("fuobe-hosted-runs-");process.env.FUOBE_DATA_DIR = dir;process.env.FUOBE_PUBLIC_SIGNUP = "1";delete process.env.FUOBE_PASSWORD;@@ -47,9 +45,6 @@ afterAll(async () => {for (const k of ["FUOBE_HOSTED_RUNS", "FUOBE_BILLING_URL", "FUOBE_BILLING_TOKEN"]) delete process.env[k];await fake.close();await comfy.close();- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}});beforeEach(() => {resetRates();diff --git a/tests/hosted-untested.test.ts b/tests/hosted-untested.test.tsindex a4a61864..d7eaf722 100644--- a/tests/hosted-untested.test.ts+++ b/tests/hosted-untested.test.ts@@ -1,7 +1,5 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { tempDir } from "./helpers/temp-dir";/*** Hosted routes no live call has passed yet (src/lib/catalog/hosted-untested.ts) run for the owner only: an account's@@ -9,7 +7,7 @@ import { afterAll, beforeAll, describe, expect, it } from "vitest";* model out. A Fuobe Original whose cloud half is untested keeps its open engine.*/-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-hosted-untested-"));+const dir = tempDir("fuobe-hosted-untested-");process.env.FUOBE_DATA_DIR = dir;process.env.FUOBE_PUBLIC_SIGNUP = "1";delete process.env.FUOBE_PASSWORD;@@ -43,9 +41,6 @@ beforeAll(() => {afterAll(() => {globalThis.fetch = realFetch;globalThis.__fuobeTestDiskFree = undefined;- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}});const post = (body: unknown) => {diff --git a/tests/image-studios-api.test.ts b/tests/image-studios-api.test.tsindex 9c4ec59c..7560ef02 100644--- a/tests/image-studios-api.test.ts+++ b/tests/image-studios-api.test.ts@@ -1,12 +1,10 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { beforeAll, describe, expect, it, vi } from "vitest";+import { tempDir } from "./helpers/temp-dir";// A route's GET opts out of prerendering with connection(), which needs a request scope.vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-image-studios-"));+const dir = tempDir("fuobe-image-studios-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";@@ -40,7 +38,6 @@ const { getModel } = await import("@/lib/catalog");beforeAll(() => {setSetting("demoMode", "auto");});-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));const json = (method: string, body?: unknown, url = "http://x/api") =>new Request(url, { method, headers: { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });diff --git a/tests/inbetween-graph.test.ts b/tests/inbetween-graph.test.tsindex d2f147bf..56b6f1af 100644--- a/tests/inbetween-graph.test.ts+++ b/tests/inbetween-graph.test.ts@@ -1,12 +1,10 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, describe, expect, it } from "vitest";+import { describe, expect, it } from "vitest";import type { GenInput } from "@/lib/catalog/types";import { gapSelection, keyTimes, timingFor, totalFrames, WORKFLOW_TIMING, type InbetweenTiming } from "@/lib/inbetween";+import { tempDir } from "./helpers/temp-dir";// Fuobe Animation on your GPU: N keyframes → N − 1 Wan 2.2 first/last-frame passes in one prompt on one set of loaders.-const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-inbetween-graph-"));+const tmp = tempDir("fuobe-inbetween-graph-");process.env.FUOBE_DATA_DIR = tmp;process.env.COMFYUI_URL = "http://comfy.test:8188";const { getWorkflow, prepareWorkflow } = await import("@/server/providers/comfyui");@@ -15,7 +13,6 @@ const { planGeneration } = await import("@/lib/catalog/plan");const { onEngine } = await import("@/lib/catalog/engines");const { getPreset } = await import("@/lib/catalog");const planOn = (engine: "open" | "cloud", req: Parameters<typeof planGeneration>[0]) => planGeneration(req, (id) => onEngine(getModel(id)!, engine), getPreset);-afterAll(() => fs.rmSync(tmp, { recursive: true, force: true }));type Wf = Record<string, { class_type: string; inputs: Record<string, unknown> }>;const keys = (n: number) => Array.from({ length: n }, (_, i) => `key${i + 1}.png`);diff --git a/tests/inbetween-runs.test.ts b/tests/inbetween-runs.test.tsindex b558aa30..6fc65051 100644--- a/tests/inbetween-runs.test.ts+++ b/tests/inbetween-runs.test.ts@@ -1,11 +1,9 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { beforeAll, describe, expect, it } from "vitest";import { keyTimes, WORKFLOW_TIMING } from "@/lib/inbetween";+import { tempDir } from "./helpers/temp-dir";// Fuobe Animation's runs in demo mode (no keys, no GPU): one row on your GPU, one clip per gap and a join in the cloud.-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-inbetween-runs-"));+const dir = tempDir("fuobe-inbetween-runs-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";@@ -15,7 +13,6 @@ const { saveFile } = await import("@/server/storage");const tools = await import("@/server/assist/tools");beforeAll(() => setSetting("demoMode", "auto"));-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));const png = Buffer.from("89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c4890000000d49444154789c63f8cfc0f01f0005000201a2e2b6a40000000049454e44ae426082", "hex");const frames = (n: number) => Array.from({ length: n }, () => saveFile({ data: png, contentType: "image/png", source: "upload" }).url);diff --git a/tests/influencer-api.test.ts b/tests/influencer-api.test.tsindex f11a16da..327875ac 100644--- a/tests/influencer-api.test.ts+++ b/tests/influencer-api.test.ts@@ -1,9 +1,7 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";+import { afterEach, beforeAll, describe, expect, it } from "vitest";+import { tempDir } from "./helpers/temp-dir";-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-influencer-"));+const dir = tempDir("fuobe-influencer-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";@@ -24,7 +22,6 @@ beforeAll(() => {afterEach(() => {setSetting("engineMode", "both");});-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));const PNG = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=", "base64");const upload = () => saveFile({ data: PNG, contentType: "image/png", source: "upload" }).url;diff --git a/tests/influencer-comfy.test.ts b/tests/influencer-comfy.test.tsindex e48dbff7..b5111b06 100644--- a/tests/influencer-comfy.test.ts+++ b/tests/influencer-comfy.test.ts@@ -1,17 +1,14 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, describe, expect, it } from "vitest";+import { describe, expect, it } from "vitest";import type { GenInput, Operation } from "@/lib/catalog/types";import { compileCastPrompt, compileDressPrompt, planInfluencer, type InfluencerState } from "@/lib/influencer";+import { tempDir } from "./helpers/temp-dir";// The comfyui provider driving the AI Influencer builder's open engine on the library graphs: the Soul Cast// sheet (Z-Image Turbo) with the compiled character, then Qwen-Image 2.1 with the sheet first.-const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-influencer-comfy-"));+const tmp = tempDir("fuobe-influencer-comfy-");process.env.FUOBE_DATA_DIR = tmp;process.env.COMFYUI_URL = "http://comfy.test:8188";const { prepareWorkflow } = await import("@/server/providers/comfyui");-afterAll(() => fs.rmSync(tmp, { recursive: true, force: true }));const prepare = (id: string, input: GenInput, op: Operation) => prepareWorkflow(id, input, { generationId: "g1", op, upload: async (_d, _t, name) => `up_${name}` });const at = (wf: Record<string, { inputs: Record<string, unknown> }>, node: string, input: string) => wf[node]?.inputs[input];diff --git a/tests/isolated-worker.test.ts b/tests/isolated-worker.test.tsindex b7ba63bf..62ac3ceb 100644--- a/tests/isolated-worker.test.ts+++ b/tests/isolated-worker.test.ts@@ -1,11 +1,9 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import type { Generation, ModelDef } from "@/lib/catalog/types";+import { tempDir } from "./helpers/temp-dir";vi.setConfig({ testTimeout: 30_000 });-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-isolated-"));+const dir = tempDir("fuobe-isolated-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://comfy.test:8188";@@ -18,7 +16,6 @@ const { studioCatalog } = await import("@/lib/studio-catalog");const { LIPSYNC_STUDIO, SFX_STUDIO, FOLEY_STUDIO } = await import("@/lib/studios");const { toModelRow } = await import("@/lib/model-rows");-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));// fetch + WebSocket stubs, as in comfy-provider.test.tstype Handler = (url: string, init?: RequestInit) => Response | Promise<Response>;diff --git a/tests/keyframes-comfy.test.ts b/tests/keyframes-comfy.test.tsindex ed3b1a30..efc17a48 100644--- a/tests/keyframes-comfy.test.ts+++ b/tests/keyframes-comfy.test.ts@@ -1,18 +1,15 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, describe, expect, it } from "vitest";+import { describe, expect, it } from "vitest";import type { GenInput, Operation } from "@/lib/catalog/types";import { keyframeChain, planKeyframeClips } from "@/lib/catalog/keyframes";+import { tempDir } from "./helpers/temp-dir";// The open keyframe film's clips through the comfyui provider: each pair's start and end frames and its// frame count land in the Wan 2.2 start/end-frame graph exactly as the per-pair plan counted them.-const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-keyframes-comfy-"));+const tmp = tempDir("fuobe-keyframes-comfy-");process.env.FUOBE_DATA_DIR = tmp;process.env.COMFYUI_URL = "http://comfy.test:8188";const { getWorkflow, prepareWorkflow } = await import("@/server/providers/comfyui");const { getModel } = await import("@/lib/catalog");-afterAll(() => fs.rmSync(tmp, { recursive: true, force: true }));const prepare = (id: string, input: Partial<GenInput>, op: Operation) =>prepareWorkflow(id, { prompt: "a paper boat", aspectRatio: "16:9", resolution: "480p", ...input } as GenInput, { generationId: "g1", op, upload: async (_d, _t, name) => `up_${name}` });diff --git a/tests/kling-4-server.test.ts b/tests/kling-4-server.test.tsindex cef2bcd2..5e135f6d 100644--- a/tests/kling-4-server.test.ts+++ b/tests/kling-4-server.test.ts@@ -1,7 +1,5 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { beforeAll, describe, expect, it } from "vitest";+import { tempDir } from "./helpers/temp-dir";/*** Kling 4.0's clip limits on the server (nm10-kling-4): an edit keeps the clip's own length, so the clip is held to the@@ -9,7 +7,7 @@ import { afterAll, beforeAll, describe, expect, it } from "vitest";* before anything goes to fal. No paid call is made: fetch is stubbed and nothing reaches fal.*/-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-kling-4-server-"));+const dir = tempDir("fuobe-kling-4-server-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";@@ -51,9 +49,6 @@ beforeAll(() => {setSetting("demoMode", "auto");setSetting("enhanceProvider", "none");});-afterAll(() => {- fs.rmSync(dir, { recursive: true, force: true });-});describe("Kling 4.0's clip limits before fal is asked", () => {it("refuses an edit's too-wide clip although the request named a length, and a clip element over 8 s", async () => {diff --git a/tests/kling-4.test.ts b/tests/kling-4.test.tsindex 0afa848f..fd106f0c 100644--- a/tests/kling-4.test.ts+++ b/tests/kling-4.test.ts@@ -1,7 +1,6 @@import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, describe, expect, it } from "vitest";+import { describe, expect, it } from "vitest";+import { tempDir } from "./helpers/temp-dir";/*** Kling 4.0 in the cloud (build package nm10-kling-4): fal's four kling/v4 endpoints (API open since round 4 held them@@ -9,10 +8,9 @@ import { afterAll, describe, expect, it } from "vitest";* (docs/research/paid-model-apis-4.json, re-read 2026-11-01). No paid call is made: demo mode and pure functions only.*/-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-kling-4-"));+const dir = tempDir("fuobe-kling-4-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));const { getModel, getPreset, MODELS, modelsFor } =await import("@/lib/catalog");diff --git a/tests/launch-prices.test.ts b/tests/launch-prices.test.tsindex f1c24537..31656ea8 100644--- a/tests/launch-prices.test.ts+++ b/tests/launch-prices.test.ts@@ -1,11 +1,9 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";import { createElement } from "react";import { renderToString } from "react-dom/server";import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";import type { GenerationRequest, ModelDef } from "@/lib/catalog/types";import type { StudioConfig } from "@/components/studio/studio-context";+import { tempDir } from "./helpers/temp-dir";/*** Launch prices (Pricing.promo): H3 Max camera controls at $0.052/s (768P) through 2026-10-31, then $0.08/s; FLUX 3 Max@@ -17,7 +15,7 @@ import type { StudioConfig } from "@/components/studio/studio-context";// The server starts on 2026-10-30, the day before H3 Max's launch price ends, and loads the catalog then.vi.useFakeTimers({ now: Date.parse("2026-10-30T10:00:00Z"), toFake: ["Date"] });-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-launch-prices-"));+const dir = tempDir("fuobe-launch-prices-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.OLLAMA_URL = "http://127.0.0.1:9";@@ -62,7 +60,6 @@ beforeAll(() => {afterEach(() => at("2026-10-30T10:00:00Z"));afterAll(() => {vi.useRealTimers();- fs.rmSync(dir, { recursive: true, force: true });});describe("the catalog keeps both prices", () => {diff --git a/tests/layers-api.test.ts b/tests/layers-api.test.tsindex 279c286c..06e854be 100644--- a/tests/layers-api.test.ts+++ b/tests/layers-api.test.ts@@ -1,14 +1,12 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { beforeAll, describe, expect, it, vi } from "vitest";import type { Generation } from "@/lib/catalog/types";import { elementDraft, initialDoc, nodesFromOutputs, placeOutput, placeTextBlocks, textBlocksFrom, type LayerDoc, type LayerJob, type LayerJobInput, type LayerProject, type LayerProjectView } from "@/lib/layers";+import { tempDir } from "./helpers/temp-dir";// Route handlers are called directly, outside a Next request: connection() has nothing to wait for.vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-layers-"));+const dir = tempDir("fuobe-layers-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";@@ -24,7 +22,6 @@ const job = await import("@/app/api/layers/[id]/jobs/[jobId]/route");const renders = await import("@/app/api/layers/renders/route");beforeAll(() => setSetting("demoMode", "auto"));-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));// eslint-disable-next-line @typescript-eslint/no-explicit-anyconst ctx = (params: Record<string, string>) => ({ params: Promise.resolve(params) }) as any;diff --git a/tests/layers-comfy.test.ts b/tests/layers-comfy.test.tsindex 41288b05..93ee98a8 100644--- a/tests/layers-comfy.test.ts+++ b/tests/layers-comfy.test.ts@@ -1,15 +1,13 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, describe, expect, it } from "vitest";+import { describe, expect, it } from "vitest";import type { ManifestWorkflow } from "@/lib/comfy";import type { GenerationRequest } from "@/lib/catalog/types";import type { LayerJobInput } from "@/lib/layers";import type { MediaInfo } from "@/lib/media-probe";+import { tempDir } from "./helpers/temp-dir";// The Layers tools' open-engine requests, bound into the real library graphs: extras bind by name and// silently fall back to defaults when a name is wrong, so check the values land where they should.-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-layers-comfy-"));+const dir = tempDir("fuobe-layers-comfy-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";@@ -17,7 +15,6 @@ const { collectOutputs, getWorkflow, prepareWorkflow } = await import("@/server/const { jobSteps } = await import("@/server/layers");const { getModel } = await import("@/lib/catalog");-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));/** The request bound into its graph; `size` is what the server read of the picture it sent (its width and height). */async function bind(req: GenerationRequest, size?: { width: number; height: number }) {diff --git a/tests/layers.test.ts b/tests/layers.test.tsindex fbc2973f..af50c0ce 100644--- a/tests/layers.test.ts+++ b/tests/layers.test.ts@@ -1,12 +1,12 @@import { execFileSync } from "node:child_process";import fs from "node:fs";-import os from "node:os";import path from "node:path";import { describe, expect, it } from "vitest";import { getModel, supportsOp } from "@/lib/catalog";import { imageLimit } from "@/lib/catalog/plan";import type { Operation } from "@/lib/catalog/types";import { layersHref } from "@/lib/output-actions";+import { tempDir } from "./helpers/temp-dir";import {addNodes,addRevision,@@ -125,7 +125,7 @@ describe("zip naming", () => {{ name: "composite.png", data: new Uint8Array([137, 80, 78, 71, 1, 2, 3]) },{ name: "layer-z0-background.png", data },]);- const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-layers-zip-"));+ const dir = tempDir("fuobe-layers-zip-");try {const file = path.join(dir, "cropped-layers.zip");fs.writeFileSync(file, zip);diff --git a/tests/layout-mode-server.test.ts b/tests/layout-mode-server.test.tsindex 707ab4dc..bf0d757e 100644--- a/tests/layout-mode-server.test.ts+++ b/tests/layout-mode-server.test.ts@@ -1,12 +1,10 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { beforeAll, describe, expect, it, vi } from "vitest";import type { LayoutDraft } from "@/lib/layout-prompt";+import { tempDir } from "./helpers/temp-dir";// N7-2: a layout run never goes through Fuobe's prompt enhancer (it would rewrite the boxes), even when the request asks// for it; a plain prompt still does. Demo mode (no keys, no GPU): the mock provider makes the picture.-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-layout-"));+const dir = tempDir("fuobe-layout-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";@@ -23,7 +21,6 @@ const { setSetting } = await import("@/server/settings");const { createGenerations, getGeneration, previewGeneration } = await import("@/server/generations");beforeAll(() => setSetting("demoMode", "auto"));-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));const poster: LayoutDraft = {summary: { caption: "A candle sale poster", meta: [], canvas: "single" },diff --git a/tests/layouts-everywhere.test.ts b/tests/layouts-everywhere.test.tsindex 57272d4b..365b9655 100644--- a/tests/layouts-everywhere.test.ts+++ b/tests/layouts-everywhere.test.ts@@ -1,14 +1,12 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, describe, expect, it } from "vitest";+import { describe, expect, it } from "vitest";// Layouts everywhere (docs/research/new-models-7.md §5.9): layouts from Canvas, Marketing Studio, Ads Studio and Assist.-const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-layouts-everywhere-"));+const tmp = tempDir("fuobe-layouts-everywhere-");process.env.FUOBE_DATA_DIR = tmp;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.OLLAMA_URL = "http://127.0.0.1:9";-afterAll(() => fs.rmSync(tmp, { recursive: true, force: true }));const { getModel, getPreset } = await import("@/lib/catalog");const { planGeneration } = await import("@/lib/catalog/plan");@@ -30,6 +28,7 @@ import type { CanvasEdge, CanvasGraph, CanvasNode } from "@/lib/catalog/canvas";import type { BrandKit, Product } from "@/lib/catalog/marketing";import type { GenerationRequest } from "@/lib/catalog/types";import type { LayoutDraft } from "@/lib/layout-prompt";+import { tempDir } from "./helpers/temp-dir";setSetting("demoMode", "auto");diff --git a/tests/library.test.ts b/tests/library.test.tsindex d376c9a9..af331f31 100644--- a/tests/library.test.ts+++ b/tests/library.test.ts@@ -1,13 +1,13 @@import { execFileSync } from "node:child_process";import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { beforeAll, describe, expect, it, vi } from "vitest";+import { tempDir } from "./helpers/temp-dir";// Route handlers call connection() (no request scope in a test).vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-library-"));+const dir = tempDir("fuobe-library-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";@@ -29,7 +29,6 @@ const { db } = await import("@/server/db");const { childFolders, folderTree } = await import("@/lib/library");beforeAll(() => setSetting("demoMode", "auto"));-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));const DAY = 86_400_000;const PNG = Buffer.from("89504e470d0a1a0a0000000d4948445200000001000000010806000000", "hex");diff --git a/tests/live-api.test.ts b/tests/live-api.test.tsindex 2c3ca25a..03fe844c 100644--- a/tests/live-api.test.ts+++ b/tests/live-api.test.ts@@ -5,7 +5,6 @@* use which route (guests, accounts by their GPU, the owner).*/import fs from "node:fs";-import os from "node:os";import path from "node:path";import sharp from "sharp";import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";@@ -13,11 +12,12 @@ import { NextRequest } from "next/server";import { FrameReader, type Frame } from "@/lib/live/frames";import { CONNECT_GPU_MESSAGE, GUEST_RUN_MESSAGE, LIBRARY_MESSAGE, accountLive, liveRoute } from "@/lib/guest-access";import { startLocalComfy, type IndexLike, type LocalComfy } from "./helpers/fake-local-comfy";+import { tempDir } from "./helpers/temp-dir";// Route handlers are called directly, outside a Next request: connection() has nothing to wait for.vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-live-api-"));+const dir = tempDir("fuobe-live-api-");process.env.FUOBE_DATA_DIR = dir;process.env.FUOBE_PUBLIC_SIGNUP = "1";delete process.env.FUOBE_PASSWORD;@@ -56,9 +56,6 @@ afterAll(async () => {globalThis.__fuobeTestDiskFree = undefined;globalThis.__fuobeLiveSocket?.ws?.close();await fake.close();- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}});beforeEach(() => resetRates());diff --git a/tests/llm-hosted.test.ts b/tests/llm-hosted.test.tsindex cf8c2f3d..be1e7ff8 100644--- a/tests/llm-hosted.test.ts+++ b/tests/llm-hosted.test.ts@@ -1,11 +1,9 @@-import fs from "node:fs";import http from "node:http";-import os from "node:os";-import path from "node:path";import { afterAll, beforeAll, describe, expect, it } from "vitest";import type Anthropic from "@anthropic-ai/sdk";import { getLlmModel, getLlmProvider, GEMINI_DUMMY_SIGNATURE, type LlmModelDef } from "@/lib/catalog/llm-providers";import { fakeLlm, type FakeLlm, type Mode } from "./helpers/fake-llm";+import { tempDir } from "./helpers/temp-dir";/** The hosted providers' Chat Completions path, against fakes that enforce each provider's documented@@ -15,7 +13,7 @@ import { fakeLlm, type FakeLlm, type Mode } from "./helpers/fake-llm";* an account's work, never a key over plain http to a public host).*/-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-llm-hosted-"));+const dir = tempDir("fuobe-llm-hosted-");process.env.FUOBE_DATA_DIR = dir;for (const k of Object.keys(process.env)) if (/_API_KEY$|HF_TOKEN$|^FUOBE_LLM_TEST_BASE$/.test(k)) delete process.env[k];@@ -48,9 +46,6 @@ async function fake(mode: Mode, provider: string = mode): Promise<FakeLlm> {afterAll(async () => {await Promise.all(fakes.map((f) => f.close()));delete process.env.FUOBE_LLM_TEST_BASE;- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}});/**diff --git a/tests/llm-registry.test.ts b/tests/llm-registry.test.tsindex 82053d56..acb1db66 100644--- a/tests/llm-registry.test.ts+++ b/tests/llm-registry.test.ts@@ -1,9 +1,7 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";import { describe, expect, it } from "vitest";import { ASSIST_EFFORTS } from "@/lib/assist";import { getLlmModel, LLM_PROVIDERS, LLM_REGISTRY_CHECKED, offersFree, priceOn } from "@/lib/catalog/llm-providers";+import { tempDir } from "./helpers/temp-dir";/** The provider registry is data: these checks keep it honest (official https hosts only, a price or a@@ -11,7 +9,7 @@ import { getLlmModel, LLM_PROVIDERS, LLM_REGISTRY_CHECKED, offersFree, priceOn }* tied to Settings (every key is a secret setting, every region pick a validated one).*/-process.env.FUOBE_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-llm-registry-"));+process.env.FUOBE_DATA_DIR = tempDir("fuobe-llm-registry-");const { SETTINGS } = await import("@/server/settings");/** The hosts each provider's docs give. A base URL anywhere else is a mistake (or worse). */diff --git a/tests/llm-responses.test.ts b/tests/llm-responses.test.tsindex a684ac4c..7014a408 100644--- a/tests/llm-responses.test.ts+++ b/tests/llm-responses.test.ts@@ -1,10 +1,8 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";import { afterAll, beforeAll, describe, expect, it } from "vitest";import type Anthropic from "@anthropic-ai/sdk";import { getLlmModel, getLlmProvider } from "@/lib/catalog/llm-providers";import { fakeLlm, type FakeLlm } from "./helpers/fake-llm";+import { tempDir } from "./helpers/temp-dir";/** OpenAI direct, on the Responses API (GPT-6.x call tools only there): a stateless request@@ -13,7 +11,7 @@ import { fakeLlm, type FakeLlm } from "./helpers/fake-llm";* stays with its calls (the fake refuses a call without it); and a reply cut off by the output limit.*/-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-llm-responses-"));+const dir = tempDir("fuobe-llm-responses-");process.env.FUOBE_DATA_DIR = dir;for (const k of Object.keys(process.env)) if (/_API_KEY$|^FUOBE_LLM_TEST_BASE$/.test(k)) delete process.env[k];@@ -37,9 +35,6 @@ beforeAll(async () => {afterAll(async () => {await f.close();delete process.env.FUOBE_LLM_TEST_BASE;- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}});const sol = () => getLlmModel("openai", "gpt-6.1-sol")!;diff --git a/tests/llm-settings-security.test.ts b/tests/llm-settings-security.test.tsindex 132010d5..d9d3da3f 100644--- a/tests/llm-settings-security.test.ts+++ b/tests/llm-settings-security.test.ts@@ -1,9 +1,7 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";import { NextRequest } from "next/server";import { fakeLlm, type FakeLlm } from "./helpers/fake-llm";+import { tempDir } from "./helpers/temp-dir";/** The hosted providers' keys are the owner's secrets: they never appear in a response (settings, Assist's@@ -14,7 +12,7 @@ import { fakeLlm, type FakeLlm } from "./helpers/fake-llm";vi.setConfig({ testTimeout: 60_000 });vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-llm-security-"));+const dir = tempDir("fuobe-llm-security-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.OLLAMA_URL = "http://127.0.0.1:9";@@ -59,9 +57,6 @@ afterAll(async () => {await ds.close();delete process.env.FUOBE_LLM_TEST_BASE;delete process.env.FUOBE_PUBLIC_SIGNUP;- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}});/** No key, and no long piece of one, anywhere in a body. */diff --git a/tests/llm.test.ts b/tests/llm.test.tsindex e99988a8..756320a4 100644--- a/tests/llm.test.ts+++ b/tests/llm.test.ts@@ -1,13 +1,11 @@-import fs from "node:fs";import http from "node:http";-import os from "node:os";-import path from "node:path";import { Worker } from "node:worker_threads";import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";import type { Generation } from "@/lib/catalog/types";+import { tempDir } from "./helpers/temp-dir";vi.setConfig({ testTimeout: 40_000 });-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-llm-"));+const dir = tempDir("fuobe-llm-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";@@ -48,7 +46,6 @@ beforeAll(async () => {});afterAll(() => {server.close();- fs.rmSync(dir, { recursive: true, force: true });});beforeEach(() => {seen.length = 0;diff --git a/tests/local-llm.test.ts b/tests/local-llm.test.tsindex 66dbfdf9..1fc91280 100644--- a/tests/local-llm.test.ts+++ b/tests/local-llm.test.ts@@ -1,10 +1,8 @@-import fs from "node:fs";import http from "node:http";-import os from "node:os";-import path from "node:path";import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";import type Anthropic from "@anthropic-ai/sdk";import type { Generation } from "@/lib/catalog/types";+import { tempDir } from "./helpers/temp-dir";/** Local LLM servers besides Ollama: LM Studio, Unsloth Studio and any OpenAI-compatible server@@ -15,7 +13,7 @@ import type { Generation } from "@/lib/catalog/types";vi.setConfig({ testTimeout: 60_000 });vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-local-llm-"));+const dir = tempDir("fuobe-local-llm-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.OLLAMA_URL = "http://127.0.0.1:9";@@ -225,9 +223,6 @@ beforeEach(() => {afterAll(() => {for (const s of servers) s.close();// Windows keeps the open SQLite file locked until the worker exits.- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}});// ---------------------------------------------------------------------------diff --git a/tests/lora-fetch.test.ts b/tests/lora-fetch.test.tsindex d73b2a88..88cabaa6 100644--- a/tests/lora-fetch.test.ts+++ b/tests/lora-fetch.test.ts@@ -1,10 +1,10 @@import crypto from "node:crypto";import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { fitLoras, lorasFit, loraEntry, loraRef } from "@/lib/catalog/loras";import type { LoraRef } from "@/lib/catalog/types";+import { tempDir } from "./helpers/temp-dir";// The route's GET opts out of prerendering with connection(), which needs a request scope.vi.mock("next/server", () => ({ connection: async () => {} }));@@ -19,12 +19,11 @@ vi.mock("@/lib/catalog/lora-library.generated", async (importOriginal) => {});// The downloader reads the civitai key and the LoRA folder from the settings table: a throwaway data folder.-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-lora-fetch-"));+const dir = tempDir("fuobe-lora-fetch-");process.env.FUOBE_DATA_DIR = dir;const { downloadLora, ensureLorasOnComfy, gatedFileReady, prepareCloudLoras, listLoraCopies, lorasPath, redact, LORA_CACHE_DIR } = await import("@/server/loras");const { setSetting } = await import("@/server/settings");const { db } = await import("@/server/db");-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));const KEY = "civitai-secret-0123456789abcdef";const bytes = (s: string) => Buffer.from(s.repeat(64));diff --git a/tests/lora-library.test.ts b/tests/lora-library.test.tsindex 0e0e3c03..dea9b1d6 100644--- a/tests/lora-library.test.ts+++ b/tests/lora-library.test.ts@@ -1,10 +1,10 @@import { execFileSync } from "node:child_process";import fs from "node:fs";-import os from "node:os";import path from "node:path";import { describe, expect, it } from "vitest";import { LORA_LIBRARY, LORA_LIBRARY_AS_OF, MOTION_EFFECT_LORAS } from "@/lib/catalog/lora-library.generated";import { civitaiVersion, libraryEntry, licenceLine, loraByFile, loraEntry, loraRef, needsToken } from "@/lib/catalog/loras";+import { tempDir } from "./helpers/temp-dir";const ROOT = path.resolve(__dirname, "..");const DATE = /^\d{4}-\d{2}-\d{2}$/;@@ -115,7 +115,7 @@ describe("LoRA library (lora-library.generated.ts)", () => {});it("is what the generator writes (no hand edits); the generator refuses broken pins and only notes licences", () => {- const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-lora-gen-"));+ const tmp = tempDir("fuobe-lora-gen-");const research = () => JSON.parse(fs.readFileSync(path.join(ROOT, "docs/research/fuobe-originals-recipes-5.json"), "utf8"));const refuses = (data: unknown, why: RegExp) => {fs.writeFileSync(path.join(tmp, "docs/research/fuobe-originals-recipes-5.json"), JSON.stringify(data));diff --git a/tests/marketing-api.test.ts b/tests/marketing-api.test.tsindex 3835de00..3b424f8e 100644--- a/tests/marketing-api.test.ts+++ b/tests/marketing-api.test.ts@@ -1,11 +1,11 @@import fs from "node:fs";import http from "node:http";import type { AddressInfo } from "node:net";-import os from "node:os";import path from "node:path";import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { tempDir } from "./helpers/temp-dir";-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-marketing-"));+const dir = tempDir("fuobe-marketing-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.OLLAMA_URL = "http://127.0.0.1:9";@@ -97,7 +97,6 @@ beforeAll(async () => {});afterAll(() => {server.close();- fs.rmSync(dir, { recursive: true, force: true });});const upload = (name = "product.png") => saveFile({ data: PNG, contentType: "image/png", name, source: "upload" }).url;diff --git a/tests/marketing-endcard.test.ts b/tests/marketing-endcard.test.tsindex 70a713ab..bd455a82 100644--- a/tests/marketing-endcard.test.ts+++ b/tests/marketing-endcard.test.ts@@ -1,11 +1,9 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { beforeAll, describe, expect, it, vi } from "vitest";import type { BrandKit, Product } from "@/lib/catalog/marketing";import type { Generation, GenInput } from "@/lib/catalog/types";import type { ComfyWorkflow, ManifestWorkflow } from "@/lib/comfy";import type { MediaInfo } from "@/lib/media-probe";+import { tempDir } from "./helpers/temp-dir";// Click to Ad's logo end card (r4/marketing-mixed): the plan per engine (cloud ken-burns + merge-videos,// open video-append-endcard or still-to-clip + the sound-keeping join), how it hangs off the ad, a demo run,@@ -13,7 +11,7 @@ import type { MediaInfo } from "@/lib/media-probe";vi.setConfig({ testTimeout: 90_000 });-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-endcard-"));+const dir = tempDir("fuobe-endcard-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.OLLAMA_URL = "http://127.0.0.1:9";@@ -30,12 +28,6 @@ const { planEndCard, siteLabel } = await import("@/components/marketing/end-cardconst { themeFrom } = await import("@/components/ads/layout");beforeAll(() => setSetting("demoMode", "auto"));-afterAll(() => {- // The database stays open until the worker exits (Windows won't delete it before).- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}-});const PNG = Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), Buffer.alloc(400, 7)]);const upload = (name = "p.png") => saveFile({ data: PNG, contentType: "image/png", name, source: "upload" }).url;diff --git a/tests/marketing-fixes.test.ts b/tests/marketing-fixes.test.tsindex bbbcd703..e74ac6b2 100644--- a/tests/marketing-fixes.test.ts+++ b/tests/marketing-fixes.test.ts@@ -1,7 +1,5 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { beforeAll, describe, expect, it } from "vitest";+import { tempDir } from "./helpers/temp-dir";/*** The review fixes of the marketing suite: open joins keep the voice, plans on fal and Replicate alone,@@ -9,7 +7,7 @@ import { afterAll, beforeAll, describe, expect, it } from "vitest";* leftovers, a research bar that never goes back, and the sound-keeping join workflows bound for real.*/-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-marketing-fixes-"));+const dir = tempDir("fuobe-marketing-fixes-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.OLLAMA_URL = "http://127.0.0.1:9";@@ -67,9 +65,6 @@ beforeAll(() => {setSetting("demoMode", "auto");setSetting("enhanceProvider", "none");});-afterAll(() => {- fs.rmSync(dir, { recursive: true, force: true });-});const product = (over: Partial<import("@/lib/catalog/marketing").Product> = {}): import("@/lib/catalog/marketing").Product => ({id: "p1",diff --git a/tests/mcp.test.ts b/tests/mcp.test.tsindex b52592f8..d96b9cc9 100644--- a/tests/mcp.test.ts+++ b/tests/mcp.test.ts@@ -1,15 +1,12 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { beforeAll, describe, expect, it } from "vitest";+import { tempDir } from "./helpers/temp-dir";-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-mcp-"));+const dir = tempDir("fuobe-mcp-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";const { handleMcp } = await import("@/server/mcp");// Placeholders where nothing is connected, as these runs were written for ("auto": code in this process only).beforeAll(async () => (await import("@/server/settings")).setSetting("demoMode", "auto"));-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));const rpc = (method: string, params?: unknown) => handleMcp({ jsonrpc: "2.0", id: 1, method, params });diff --git a/tests/media-clean.test.ts b/tests/media-clean.test.tsindex 1864a9a1..1e004200 100644--- a/tests/media-clean.test.ts+++ b/tests/media-clean.test.ts@@ -1,18 +1,17 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";import { Readable } from "node:stream";import zlib from "node:zlib";-import { afterAll, describe, expect, it } from "vitest";+import { describe, expect, it } from "vitest";import { metadataPatches, overlay, patchStream, type Patch } from "@/server/media-clean";+import { tempDir } from "./helpers/temp-dir";/*** Files on share pages lose the generation data saved inside them (ComfyUI writes its prompt and* workflow into PNG text chunks, MP4/WebM/FLAC/MP3/Ogg tags, GLB extras and SVG metadata). Each* fixture here is a small, well-formed file of that format carrying SECRET where that tool puts it.*/-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-clean-"));-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));+const dir = tempDir("fuobe-clean-");const SECRET = "SECRET violet tiger prompt";let n = 0;diff --git a/tests/mixed-shorts-originals.test.ts b/tests/mixed-shorts-originals.test.tsindex 90efce4f..7a6324fc 100644--- a/tests/mixed-shorts-originals.test.ts+++ b/tests/mixed-shorts-originals.test.ts@@ -1,15 +1,15 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { beforeAll, describe, expect, it } from "vitest";import type { GenInput, ModelDef, ModelRoute } from "@/lib/catalog/types";+import { tempDir } from "./helpers/temp-dir";// Fuobe Mixed Media and Fuobe Shorts (build plan O9): Higgsfield's Mixed Media and Shorts as Originals on both engines.// Frames are floor(seconds × fps) and priced per frame; the cloud fans the Original's frame route out over every frame// (no lanes: one seed, the look's LoRA) and splits clips above 200 frames; Smooth and Shorts run the Wan 2.2 Fun VACE// pass from a restyled first frame; the fal payloads come from the research's FieldMaps; DoP's 32 Mixed Media effects// draw their still on the Original first.-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-o9-"));+const dir = tempDir("fuobe-o9-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9"; // nothing listens here: open runs fall back to the demo@@ -32,7 +32,6 @@ const { maxRefsFor, modelInfos, reframes, resolutionFor } = await import("@/lib/const { MIXED_MEDIA_LOOK_LORAS, LORA_LIBRARY } = await import("@/lib/catalog/lora-library.generated");beforeAll(() => setSetting("demoMode", "auto"));-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));const view = (id: string, engine: "open" | "cloud") => onEngine(getModel(id)!, engine);const noir = mm.getMixedPreset("mixed-noir")!;diff --git a/tests/model-access-listings.test.ts b/tests/model-access-listings.test.tsindex 2b1aa9bc..9f1db5a6 100644--- a/tests/model-access-listings.test.ts+++ b/tests/model-access-listings.test.ts@@ -1,9 +1,7 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, beforeEach, describe, expect, it, vi } from "vitest";+import { beforeEach, describe, expect, it, vi } from "vitest";import { indexEntries } from "@/lib/command-search";import { paletteIndex } from "@/lib/palette-index";+import { tempDir } from "./helpers/temp-dir";/*** Settings → Models & licences in the places that list or pick models: GET /api/models (the CLI's list and the@@ -13,7 +11,7 @@ import { paletteIndex } from "@/lib/palette-index";vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-access-listings-"));+const dir = tempDir("fuobe-access-listings-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.OLLAMA_URL = "http://127.0.0.1:9";@@ -25,7 +23,6 @@ const { changeAccess } = await import("@/server/model-access");const tools = await import("@/server/assist/tools");const { offlinePlan } = await import("@/server/assist/agent");const { setSetting } = await import("@/server/settings");-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));type Body = { defaults: Record<string, { cloud?: string; open?: string }>; items: { id: string; engines: string[] }[] };const models = async (query = "") => (await (await listModels(new Request(`http://localhost/api/models${query}`))).json()) as Body;diff --git a/tests/model-access-studios.test.ts b/tests/model-access-studios.test.tsindex 2e78584c..7f8d68d5 100644--- a/tests/model-access-studios.test.ts+++ b/tests/model-access-studios.test.ts@@ -1,13 +1,11 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, beforeEach, describe, expect, it } from "vitest";+import { beforeEach, describe, expect, it } from "vitest";import { chooseMaker, makersFor } from "@/lib/catalog/genjutsu";import { MOTION_MODELS } from "@/lib/av/katana";import { chooseEraser, erasersFor } from "@/lib/catalog/remove-object";import { SHORTS_MODELS } from "@/lib/catalog/shorts";import { TOOL_MODELS } from "@/lib/layers";import { keepOffered, offered } from "@/lib/model-access";+import { tempDir } from "./helpers/temp-dir";/*** Settings → Models & licences in the studios with their own model menus (Genjutsu, Remove object, Shorts, Layers,@@ -15,7 +13,7 @@ import { keepOffered, offered } from "@/lib/model-access";* gives way to the next one that is on, in the browser (keepOffered + offered) as on the server (firstOn, isOffered).*/-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-access-studios-"));+const dir = tempDir("fuobe-access-studios-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";const { changeAccess, firstOn, isOffered } = await import("@/server/model-access");@@ -24,7 +22,6 @@ const { planKatana } = await import("@/server/katana");const { multiplierModel } = await import("@/server/marketing");const { withOfferedMusic, withOfferedVideo } = await import("@/server/faceless");const { setSetting } = await import("@/server/settings");-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));beforeEach(() => {changeAccess([{ kind: "reset" }]);diff --git a/tests/model-access.test.ts b/tests/model-access.test.tsindex 7dd55a24..f526760b 100644--- a/tests/model-access.test.ts+++ b/tests/model-access.test.ts@@ -1,7 +1,6 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, beforeEach, describe, expect, it } from "vitest";+import { beforeEach, describe, expect, it } from "vitest";import { getModel, MODELS } from "@/lib/catalog";import { LORA_LIBRARY } from "@/lib/catalog/lora-library.generated";import { loraRef, loraEntry } from "@/lib/catalog/loras";@@ -9,15 +8,15 @@ import type { ModelDef } from "@/lib/catalog/types";import type { Manifest } from "@/lib/comfy";import { licenceInfo, loraLicenceInfo, mergeLicences, NODE_PACKS, paidApiLicence, UNKNOWN_LICENCE, workflowLicence } from "@/lib/licences";import { accessSummary, ALL_ON, applyChange, firstOffered, gateModel, offered, offMessage, parseAccess, routeOff, type FactsOf } from "@/lib/model-access";+import { tempDir } from "./helpers/temp-dir";// The switches live in the settings table: a throwaway database.-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-model-access-"));+const dir = tempDir("fuobe-model-access-");process.env.FUOBE_DATA_DIR = dir;const { changeAccess, factsOf, isOffered, offeredDefault, offeredLoras, offeredModels, offeredSummary, readAccess, routeLicence } = await import("@/server/model-access");const { createGenerations, previewGeneration } = await import("@/server/generations");const { setSetting } = await import("@/server/settings");const { db } = await import("@/server/db");-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));const MANIFEST = JSON.parse(fs.readFileSync(path.join(process.cwd(), "workflows/comfyui/manifest.json"), "utf8")) as Manifest;const model = (id: string) => getModel(id)!;diff --git a/tests/model3d-finish.test.ts b/tests/model3d-finish.test.tsindex 458dd687..97797940 100644--- a/tests/model3d-finish.test.ts+++ b/tests/model3d-finish.test.ts@@ -1,6 +1,5 @@import { spawnSync } from "node:child_process";import fs from "node:fs";-import os from "node:os";import path from "node:path";import { Document, getBounds, NodeIO } from "@gltf-transform/core";import { ALL_EXTENSIONS } from "@gltf-transform/extensions";@@ -11,9 +10,10 @@ import { getModel, getPreset } from "@/lib/catalog";import { model3dRequest, model3dView, MODELS_3D, viewerGlb } from "@/lib/av/model3d";import { modelPreview } from "@/lib/output-actions";import type { OutputFile } from "@/lib/catalog/types";+import { tempDir } from "./helpers/temp-dir";vi.setConfig({ testTimeout: 120_000 });-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-3d-finish-"));+const dir = tempDir("fuobe-3d-finish-");process.env.FUOBE_DATA_DIR = dir;const { saveFile } = await import("@/server/storage");const { finishModel, lastJsonLine, modelToFinish, pendingTurntable, startTurntable, withTurntable } = await import("@/server/model3d-finish");diff --git a/tests/model3d-runner.test.ts b/tests/model3d-runner.test.tsindex f01f6670..1df68bab 100644--- a/tests/model3d-runner.test.ts+++ b/tests/model3d-runner.test.ts@@ -1,8 +1,6 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";import { afterAll, describe, expect, it, vi } from "vitest";import type { OutputFile } from "@/lib/catalog/types";+import { tempDir } from "./helpers/temp-dir";// How the runner hands an image-to-3D result from ComfyUI to the server's 3D finish (src/server/model3d-finish.ts):// the outputs are stored, the job stays running until the web GLB is made (a restart resumes it, a cancel stops@@ -10,7 +8,7 @@ import type { OutputFile } from "@/lib/catalog/types";// The finish itself is stubbed here (tests/model3d-finish.test.ts runs the real scripts).vi.setConfig({ testTimeout: 30_000 });-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-3d-runner-"));+const dir = tempDir("fuobe-3d-runner-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.OLLAMA_URL = "http://127.0.0.1:9";@@ -36,12 +34,6 @@ const gens = await import("@/server/generations");const { db } = await import("@/server/db");const { provider } = await import("@/server/providers");-afterAll(() => {- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}-});-const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));async function until<T>(f: () => T | undefined | null | false, ms = 15_000): Promise<T> {const end = Date.now() + ms;diff --git a/tests/model3d.test.ts b/tests/model3d.test.tsindex c4bc2ac6..7051c44b 100644--- a/tests/model3d.test.ts+++ b/tests/model3d.test.ts@@ -1,8 +1,8 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { beforeAll, describe, expect, it } from "vitest";import type { Model3dChoice, Model3dMode } from "@/lib/av/model3d";+import { tempDir } from "./helpers/temp-dir";/*** Image to 3D's modes (r4/3d-plus): the plan per mode and engine, the cloud payloads (SAM 3D's prompt is@@ -10,7 +10,7 @@ import type { Model3dChoice, Model3dMode } from "@/lib/av/model3d";* and Rig & animate.*/-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-model3d-"));+const dir = tempDir("fuobe-model3d-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";@@ -25,7 +25,6 @@ const { dropBranch } = await import("@/lib/comfy");const m3d = await import("@/lib/av/model3d");beforeAll(() => setSetting("demoMode", "auto"));-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));const plan = (req: Parameters<typeof planGeneration>[0]) => planGeneration(req, getModel, getPreset);const photo = "/api/files/uploads/p.png";diff --git a/tests/moderation-hook.test.ts b/tests/moderation-hook.test.tsindex f841cba9..84c7591a 100644--- a/tests/moderation-hook.test.ts+++ b/tests/moderation-hook.test.ts@@ -1,14 +1,12 @@-import fs from "node:fs";import http from "node:http";-import os from "node:os";-import path from "node:path";import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";import { listenInRange, startFakeBilling, startFakeModeration, type FakeBilling, type FakeModeration } from "./helpers/fake-billing";import { startFakeComfy, type FakeComfy } from "./helpers/fake-comfy-runner";+import { tempDir } from "./helpers/temp-dir";// The moderation hook (docs/moderation-hook.md): the run check, the optional output check and reports, against// stand-in services. It ships off: with no address set nothing is checked.-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-moderation-hook-"));+const dir = tempDir("fuobe-moderation-hook-");process.env.FUOBE_DATA_DIR = dir;process.env.FUOBE_PUBLIC_SIGNUP = "1";delete process.env.FUOBE_PASSWORD;@@ -54,9 +52,6 @@ afterAll(async () => {await mod.close();await bill.close();await comfy.close();- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}});beforeEach(() => {resetRates();diff --git a/tests/moss-image.test.ts b/tests/moss-image.test.tsindex 9af98a78..b0083977 100644--- a/tests/moss-image.test.ts+++ b/tests/moss-image.test.ts@@ -1,19 +1,17 @@import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, describe, expect, it } from "vitest";+import { describe, expect, it } from "vitest";import { getModel, getPreset } from "@/lib/catalog";import { buildPayload, sizeValue } from "@/lib/catalog/payload";import { controlSets, estimateCost, planGeneration, routesFor } from "@/lib/catalog/plan";import type { GenerationRequest, ModelRoute } from "@/lib/catalog/types";import { layoutCompilerFor, type LayoutDraft } from "@/lib/layout-prompt";+import { tempDir } from "./helpers/temp-dir";// N7-1 (docs/research/new-models-7.md §4.7): MOSS-Image on fal from research #7's endpointRecords, priced per megapixel, and// on your GPU; the layout flag on the models that read layouts; the Settings → Models & licences rows.-const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-moss-"));+const tmp = tempDir("fuobe-moss-");process.env.FUOBE_DATA_DIR = tmp;const { modelLicence, accessList } = await import("@/server/model-access");-afterAll(() => fs.rmSync(tmp, { recursive: true, force: true }));type Spec = { type?: string; values?: unknown[]; minimum?: number; maximum?: number; default?: unknown; desc?: string; maxItems?: number; itemSchema?: Record<string, Spec> };type Record7 = { endpoint: string; provider: string; inputs: Record<string, Spec>; pricing: { usd: number | null; unit: string } };diff --git a/tests/mp4.test.ts b/tests/mp4.test.tsindex 6e149789..4fe94456 100644--- a/tests/mp4.test.ts+++ b/tests/mp4.test.ts@@ -1,9 +1,9 @@import { execFileSync, spawnSync } from "node:child_process";import fs from "node:fs";-import os from "node:os";import path from "node:path";import { describe, expect, it } from "vitest";import { muxMp4 } from "@/lib/mp4";+import { tempDir } from "./helpers/temp-dir";/** The browser's MP4 writer (Blockout to film's grey-box render for the cloud): its boxes, and a real decoder reading it. */@@ -64,7 +64,7 @@ describe("muxMp4", () => {});it.skipIf(!hasFfmpeg)("makes a file ffmpeg decodes frame for frame", () => {- const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-mp4-"));+ const dir = tempDir("fuobe-mp4-");try {const raw = path.join(dir, "in.h264");execFileSync("ffmpeg", ["-v", "error", "-f", "lavfi", "-i", "testsrc=size=64x48:rate=24", "-frames:v", "30", "-c:v", "libx264", "-bf", "0", "-g", "24", "-pix_fmt", "yuv420p", "-x264-params", "aud=1", "-f", "h264", raw]);diff --git a/tests/music3-hosted.test.ts b/tests/music3-hosted.test.tsindex a5cf6e06..eb2d04ae 100644--- a/tests/music3-hosted.test.ts+++ b/tests/music3-hosted.test.ts@@ -1,15 +1,13 @@-import fs from "node:fs";import http from "node:http";-import os from "node:os";-import path from "node:path";import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";import { listenInRange, startFakeBilling, type FakeBilling } from "./helpers/fake-billing";import { startFakeComfy, type FakeComfy } from "./helpers/fake-comfy-runner";+import { tempDir } from "./helpers/temp-dir";// Full songs under public sign-up: an account's song on this install's GPUs (hosted runs) plans and prices as any studio run// (MiniMax Music 3 and YuE2 are open models on core nodes); a model that needs words is refused before anything is// priced or held.-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-music3-hosted-"));+const dir = tempDir("fuobe-music3-hosted-");process.env.FUOBE_DATA_DIR = dir;process.env.FUOBE_PUBLIC_SIGNUP = "1";delete process.env.FUOBE_PASSWORD;@@ -42,9 +40,6 @@ afterAll(async () => {for (const k of ["FUOBE_HOSTED_RUNS", "FUOBE_BILLING_URL", "FUOBE_BILLING_TOKEN"]) delete process.env[k];await fake.close();await comfy.close();- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}});beforeEach(() => {resetRates();diff --git a/tests/music3-open.test.ts b/tests/music3-open.test.tsindex ea8b10af..b8a03b14 100644--- a/tests/music3-open.test.ts+++ b/tests/music3-open.test.ts@@ -1,16 +1,15 @@import fs from "node:fs";import http from "node:http";-import os from "node:os";-import path from "node:path";import zlib from "node:zlib";import { afterAll, beforeAll, describe, expect, it } from "vitest";import type { GenInput, ModelDef } from "@/lib/catalog/types";import type { MediaInfo } from "@/lib/media-probe";+import { tempDir } from "./helpers/temp-dir";// Full songs on the open engine: MiniMax Music 3 and YuE2 (songs and covers) on core ComfyUI nodes, bound for real; and the// fal provider's song tools (a song sent first through Mureka's files/upload, stems unpacked from Mureka's zip) against a// stand-in fal.ai on this machine.-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-music3-"));+const dir = tempDir("fuobe-music3-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://comfy.test:8188";@@ -151,7 +150,6 @@ describe("the fal provider's song tools", () => {afterAll(async () => {globalThis.__fuobeTestFalUrl = undefined;await new Promise<void>((r) => server.close(() => r()));- fs.rmSync(dir, { recursive: true, force: true });});const model = (id: string) => getModel(id)!;diff --git a/tests/no-higgsfield.test.ts b/tests/no-higgsfield.test.tsindex 00a997be..02021d21 100644--- a/tests/no-higgsfield.test.ts+++ b/tests/no-higgsfield.test.ts@@ -1,7 +1,7 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { beforeAll, describe, expect, it } from "vitest";+import { tempDir } from "./helpers/temp-dir";/*** Build plan O7: Fuobe calls no Higgsfield API. This file fails when a code path names that provider again (its id,@@ -11,7 +11,7 @@ import { afterAll, beforeAll, describe, expect, it } from "vitest";* research and are not scanned; this file is the one test that names the provider.*/-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-no-hf-"));+const dir = tempDir("fuobe-no-hf-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";@@ -36,7 +36,6 @@ const { saveFile } = await import("@/server/storage");// Placeholders where nothing is connected, as these runs were written for ("auto": code in this process only).beforeAll(async () => (await import("@/server/settings")).setSetting("demoMode", "auto"));-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));let rows = 0;/** A generation row as one stored before the switch reads (the retired model and provider, as it was left). */diff --git a/tests/ollama-reach.test.ts b/tests/ollama-reach.test.tsindex 6ffa44a1..ed08afe7 100644--- a/tests/ollama-reach.test.ts+++ b/tests/ollama-reach.test.ts@@ -1,12 +1,10 @@-import fs from "node:fs";import http from "node:http";import net from "node:net";-import os from "node:os";-import path from "node:path";import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+import { tempDir } from "./helpers/temp-dir";vi.setConfig({ testTimeout: 30_000 });-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-ollama-reach-"));+const dir = tempDir("fuobe-ollama-reach-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";@@ -79,7 +77,6 @@ afterAll(() => {Object.assign(REACH, reach);server.closeAllConnections();server.close();- fs.rmSync(dir, { recursive: true, force: true });});beforeEach(() => {delay = 0;diff --git a/tests/open-fibo-2.test.ts b/tests/open-fibo-2.test.tsindex 77917036..c61c6df8 100644--- a/tests/open-fibo-2.test.ts+++ b/tests/open-fibo-2.test.ts@@ -1,14 +1,14 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, describe, expect, it } from "vitest";+import { describe, expect, it } from "vitest";import type { GenInput, Operation } from "@/lib/catalog/types";import type { ComfyWorkflow } from "@/lib/comfy";+import { tempDir } from "./helpers/temp-dir";// FIBO 2 on the open engine (the owner's SOTA image families, 2026-10-31): FIBO 2 Dev for text to image through the// owner's VGL graph (Qwen3.5 writes Bria's structured JSON prompt) and for edits with up to four references, and// FIBO 2 Edit Turbo for 4-step edits. The graphs are the owner's fibo/ workflows; none is rendered through Fuobe yet.-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-fibo2-"));+const dir = tempDir("fuobe-fibo2-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9"; // nothing listens here@@ -20,7 +20,6 @@ const { licenceInfo } = await import("@/lib/licences");const { KNOWN_MODELS } = await import("../scripts/comfy/library.spec.mjs");const known = KNOWN_MODELS as Record<string, { folder: string; url: string; variants?: string[] }>;-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));const ROUTES: Record<string, Partial<Record<Operation, string>>> = {"oss-fibo2-dev": { t2i: "fibo2-dev-t2i", edit: "fibo2-dev-edit" },diff --git a/tests/open-ideogram-4.test.ts b/tests/open-ideogram-4.test.tsindex 06132909..d8af1ff6 100644--- a/tests/open-ideogram-4.test.ts+++ b/tests/open-ideogram-4.test.ts@@ -1,15 +1,15 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";import type { GenInput, Generation, Operation } from "@/lib/catalog/types";import type { ComfyWorkflow, Manifest } from "@/lib/comfy";import type { ChatRequest } from "@/server/llm";+import { tempDir } from "./helpers/temp-dir";// Ideogram 4 on the open engine: the owner's int8 graph with its Quality / Default / Turbo preset table, and the JSON// caption the server writes from the words before the run (lean JSON, src/lib/ideogram-caption.ts).vi.setConfig({ testTimeout: 60_000 });-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-ideogram4-"));+const dir = tempDir("fuobe-ideogram4-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9"; // nothing listens here: runs fall back to the demoprocess.env.OLLAMA_URL = "http://127.0.0.1:9";@@ -41,7 +41,6 @@ const { licenceInfo, licenceTerms } = await import("@/lib/licences");const { captionFromWords, captionRequest, leanProblems, parseCaption, readCaption, writeCaption } = await import("@/lib/ideogram-caption");beforeAll(() => setSetting("demoMode", "auto"));-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));beforeEach(() => {llm.answers = [];llm.seen = [];diff --git a/tests/open-krea-2.test.ts b/tests/open-krea-2.test.tsindex e769372a..dc8fa623 100644--- a/tests/open-krea-2.test.ts+++ b/tests/open-krea-2.test.ts@@ -1,16 +1,16 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, describe, expect, it } from "vitest";+import { describe, expect, it } from "vitest";import type { GenInput, Operation } from "@/lib/catalog/types";import type { ComfyWorkflow, Manifest } from "@/lib/comfy";+import { tempDir } from "./helpers/temp-dir";/*** Krea 2 on the open engine (the owner's SOTA image families, 2026-10-31): Realism and Turbo for text to image, the* General and Identity Edit V2 LoRAs, image to image at a strength, and Inpaint / Expand on Ostris' edit nodes. Each* graph follows the owner's workflow (scripts/comfy/library.spec.mjs notes); the person in Krea 2 Edit is optional.*/-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-krea2-"));+const dir = tempDir("fuobe-krea2-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";@@ -21,7 +21,6 @@ const { computeDimensions, dropBranch } = await import("@/lib/comfy");const { licenceTerms, NODE_PACKS, workflowLicence } = await import("@/lib/licences");const { CUSTOM_NODE_REPOS, KNOWN_MODELS, PACK_CLASSES } = await import("../scripts/comfy/library.spec.mjs");-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));const LIBRARY = path.join(process.cwd(), "workflows/comfyui");const read = (f: string) => JSON.parse(fs.readFileSync(path.join(LIBRARY, f), "utf8"));diff --git a/tests/open-minimax-h3.test.ts b/tests/open-minimax-h3.test.tsindex 39fd0187..1f8129a4 100644--- a/tests/open-minimax-h3.test.ts+++ b/tests/open-minimax-h3.test.ts@@ -1,14 +1,14 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { beforeAll, describe, expect, it } from "vitest";import type { GenInput, ModelDef } from "@/lib/catalog/types";import type { Manifest } from "@/lib/comfy";import { H3_GPU_TIER } from "@/lib/gpu/h3-tier";+import { tempDir } from "./helpers/temp-dir";// MiniMax H3 as an open video model (text, image and start + end frame to video with sound), the Video studio's first// model on both engines, the hosted H3's prices, and the studio defaults that changed with it.-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-open-h3-"));+const dir = tempDir("fuobe-open-h3-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9"; // nothing listens here: open runs fall back to the demo@@ -32,13 +32,6 @@ const { MARKETING_IMAGE_MODEL } = await import("@/lib/catalog/marketing");const { modelHref } = await import("@/lib/palette-index");beforeAll(() => setSetting("demoMode", "auto"));-afterAll(() => {- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {- // Windows keeps the database file open until the process ends.- }-});const ROOT = process.cwd();const LIB = path.join(ROOT, "workflows/comfyui");diff --git a/tests/open-qwen-image-21.test.ts b/tests/open-qwen-image-21.test.tsindex 79fd3514..e8b9118c 100644--- a/tests/open-qwen-image-21.test.ts+++ b/tests/open-qwen-image-21.test.ts@@ -1,13 +1,13 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, describe, expect, it } from "vitest";+import { describe, expect, it } from "vitest";import type { GenInput, Operation } from "@/lib/catalog/types";import { dropBranch, type ComfyWorkflow, type ManifestWorkflow } from "@/lib/comfy";+import { tempDir } from "./helpers/temp-dir";// Qwen-Image 2.1 and Qwen-Image 2.1 Turbo on the open engine (the owner's SOTA image families, 2026-10-31): text to// image, edits with up to four references, inpaint and expand from the owner's workflows and the proven preview graphs.-const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-qwen21-"));+const tmp = tempDir("fuobe-qwen21-");process.env.FUOBE_DATA_DIR = tmp;process.env.COMFYUI_URL = "http://comfy.test:8188";const { prepareWorkflow, getWorkflow } = await import("@/server/providers/comfyui");@@ -15,7 +15,6 @@ const { getModel, getPreset } = await import("@/lib/catalog");const { planGeneration } = await import("@/lib/catalog/plan");const { licenceInfo, NODE_PACKS, workflowLicence } = await import("@/lib/licences");const { KNOWN_MODELS, PACK_CLASSES } = await import("../scripts/comfy/library.spec.mjs");-afterAll(() => fs.rmSync(tmp, { recursive: true, force: true }));const LIBRARY = path.join(process.cwd(), "workflows/comfyui");const read = (f: string) => JSON.parse(fs.readFileSync(path.join(LIBRARY, f), "utf8"));diff --git a/tests/open-tools.test.ts b/tests/open-tools.test.tsindex 8388f7d4..85515628 100644--- a/tests/open-tools.test.ts+++ b/tests/open-tools.test.ts@@ -1,16 +1,16 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { beforeAll, describe, expect, it } from "vitest";import type { GenInput, ModelDef, ModelRoute, Operation } from "@/lib/catalog/types";import type { ComfyWorkflow } from "@/lib/comfy";+import { tempDir } from "./helpers/temp-dir";// Build plan O11 (rebranded open tools, Speak and finishing): Fuobe Angles (Qwen-Image-Edit 2509 + dx8152's// Multiple-angles LoRA on both engines, the Angles app's Higgsfield-like controls), Fuobe Speak (InfiniteTalk with// Higgsfield's Infinite Talk settings on the GPU, fal's InfiniteTalk) and Fuobe Speak · Motion (Wan 2.2 S2V), Depth// Map's Large model as a labelled alternative, the HDR route's LoRA endpoint, and Soul's face mosaic (SAM 3.1 + a// mosaic on the GPU, fal's SAM 3.1 masks pixelated in the browser).-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-o11-"));+const dir = tempDir("fuobe-o11-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9"; // nothing listens here: open runs fall back to the demo@@ -34,7 +34,6 @@ const { accessList } = await import("@/server/model-access");const { licenceInfo } = await import("@/lib/licences");beforeAll(() => setSetting("demoMode", "auto"));-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));const view = (id: string, engine: "open" | "cloud") => onEngine(getModel(id)!, engine);const plan = (r: Parameters<typeof planGeneration>[0], engine: "open" | "cloud") =>diff --git a/tests/original-sound.test.ts b/tests/original-sound.test.tsindex 2b71d609..13fc24af 100644--- a/tests/original-sound.test.ts+++ b/tests/original-sound.test.ts@@ -1,28 +1,21 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { beforeAll, describe, expect, it } from "vitest";import { CLOUD_ORIGINAL_SOUND, ORIGINAL_SOUNDS, originalSoundDefault, originalSoundOn, withOriginalSound } from "@/lib/av/original-sound";import { getMaker, ORIGINALS, planGenjutsu, type GenjutsuPlanInput } from "@/lib/catalog/genjutsu";import { defaultValues, getMixedPreset, planMixed, type MixedPlanInput } from "@/lib/catalog/mixed-media";import { getEraser, planRemoval, type RemovalPlanInput } from "@/lib/catalog/remove-object";import { lookFromPreset, planShorts, SHORTS_MODELS, SHORTS_PRESETS, type PlanStep, type ShortsPlanInput } from "@/lib/catalog/shorts";import type { GenerationRequest } from "@/lib/catalog/types";+import { tempDir } from "./helpers/temp-dir";// "Original sound" (DBS D7): what of a clip's sound goes back under its new picture in Shorts, Mixed Media, Genjutsu,// Remove object and Character Swap Studio. Everything stays as before; on your GPU the other choices split the sound with// DBS and put the chosen stem(s) back with the studio's own mux; the cloud has Everything only.-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-original-sound-"));+const dir = tempDir("fuobe-original-sound-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";const { setSetting } = await import("@/server/settings");const { createPipeline } = await import("@/server/chains");beforeAll(() => setSetting("demoMode", "auto"));-afterAll(() => {- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}-});const mux = (over: Partial<PlanStep> = {}): PlanStep => ({ key: "final", request: { feature: "x", batchTitle: "T", title: "T", modelId: "oss-mux", op: "mux", step: { label: "Final", index: 1200, of: 1000 } }, ...over });const muxOf = (steps: PlanStep[], key: string) => steps.find((s) => s.key === key)!;diff --git a/tests/originals-marketing.test.ts b/tests/originals-marketing.test.tsindex c114ca30..e1a9dfd8 100644--- a/tests/originals-marketing.test.ts+++ b/tests/originals-marketing.test.ts@@ -1,13 +1,13 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, afterEach, describe, expect, it } from "vitest";+import { afterEach, describe, expect, it } from "vitest";import type { GenInput, Operation } from "@/lib/catalog/types";import { injectLoras, type ComfyWorkflow } from "@/lib/comfy";+import { tempDir } from "./helpers/temp-dir";// Build plan O10: Fuobe Marketing Image and Fuobe Try-On on both engines, the try-on LoRA as an adapter with its// licence and switch, the AI Influencer app on Fuobe Soul, and the product-shot graph inside Marketing Image.-const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-originals-marketing-"));+const tmp = tempDir("fuobe-originals-marketing-");process.env.FUOBE_DATA_DIR = tmp;process.env.COMFYUI_URL = "http://127.0.0.1:9";@@ -27,7 +27,6 @@ const research = JSON.parse(fs.readFileSync(path.join(process.cwd(), "docs/reseasetSetting("demoMode", "auto");afterEach(() => changeAccess([{ kind: "reset" }]));-afterAll(() => fs.rmSync(tmp, { recursive: true, force: true }));const TRYON_FILE = "tryon-klein-4b.safetensors";const plan = (r: Parameters<typeof planGeneration>[0], engine: "cloud" | "open") =>diff --git a/tests/owner-computer.test.ts b/tests/owner-computer.test.tsindex db40fc5b..a6e94c60 100644--- a/tests/owner-computer.test.ts+++ b/tests/owner-computer.test.ts@@ -1,9 +1,7 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";import { startLocalComfy, type LocalComfy } from "./helpers/fake-local-comfy";import { loadRoutes, tab, type ComputerRoutes } from "./helpers/computer-tab";+import { tempDir } from "./helpers/temp-dir";/*** The owner's ComfyUI on a hosted studio: an address on the server's own machine or network is never called for a@@ -15,7 +13,7 @@ import { loadRoutes, tab, type ComputerRoutes } from "./helpers/computer-tab";vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));vi.setConfig({ testTimeout: 60_000 });-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-owner-computer-"));+const dir = tempDir("fuobe-owner-computer-");process.env.FUOBE_DATA_DIR = dir;// Nothing answers here: no test may reach a real ComfyUI on this machine.const DEAD = "http://127.0.0.1:9";@@ -74,9 +72,6 @@ afterAll(async () => {globalThis.fetch = realFetch;globalThis.__fuobeTestDiskFree = undefined;await fake.close();- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}});beforeEach(() => {resetRates();diff --git a/tests/person-remove-h3.test.ts b/tests/person-remove-h3.test.tsindex ca7224c0..2fde6f9f 100644--- a/tests/person-remove-h3.test.ts+++ b/tests/person-remove-h3.test.ts@@ -1,7 +1,6 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, describe, expect, it } from "vitest";+import { describe, expect, it } from "vitest";import { getModel, getPreset } from "@/lib/catalog";import { graphLoras, h3Canvas, H3_REMOVAL_WORKFLOW, PERSON_REMOVER_LORA } from "@/lib/catalog/character-swap";import { planGeneration } from "@/lib/catalog/plan";@@ -10,14 +9,14 @@ import type { GenInput } from "@/lib/catalog/types";import type { ManifestWorkflow } from "@/lib/comfy";import { licenceInfo, nodePack } from "@/lib/licences";import type { MediaInfo } from "@/lib/media-probe";+import { tempDir } from "./helpers/temp-dir";// Remove object's "Remove a person (H3)" (docs/research/openjutsu-6.md §4.4, §11.1 item 9): H3 Relay's Person Removal// graph with Akatz Labs' Person Remover LoRA, from a clean first frame, on a clip fitted to 24 fps on the 32 grid.-const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-person-remove-"));+const tmp = tempDir("fuobe-person-remove-");process.env.FUOBE_DATA_DIR = tmp;process.env.COMFYUI_URL = "http://comfy.test:8188";const { prepareWorkflow } = await import("@/server/providers/comfyui");-afterAll(() => fs.rmSync(tmp, { recursive: true, force: true }));const manifest = JSON.parse(fs.readFileSync(path.join(__dirname, "../workflows/comfyui/manifest.json"), "utf8")) as { workflows: (ManifestWorkflow & { validationError?: string })[] };const entry = manifest.workflows.find((w) => w.id === H3_REMOVAL_WORKFLOW)!;diff --git a/tests/person-remover-plus.test.ts b/tests/person-remover-plus.test.tsindex ac065114..dd5c4529 100644--- a/tests/person-remover-plus.test.ts+++ b/tests/person-remover-plus.test.ts@@ -1,7 +1,6 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, describe, expect, it, vi } from "vitest";+import { describe, expect, it, vi } from "vitest";import { getModel, getPreset } from "@/lib/catalog";import { h3Canvas, H3_REMOVAL_WORKFLOW } from "@/lib/catalog/character-swap";import { planGeneration } from "@/lib/catalog/plan";@@ -26,14 +25,14 @@ import {} from "@/lib/catalog/remove-object";import type { GenInput } from "@/lib/catalog/types";import type { ManifestWorkflow } from "@/lib/comfy";+import { tempDir } from "./helpers/temp-dir";// H3 Person Remover, everywhere: mask first, window review and "Redo from here".-const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-person-remover-plus-"));+const tmp = tempDir("fuobe-person-remover-plus-");process.env.FUOBE_DATA_DIR = tmp;process.env.COMFYUI_URL = "http://127.0.0.1:8199";const { prepareWorkflow, withRemovalReview } = await import("@/server/providers/comfyui");const { runAsTenant } = await import("@/server/tenant");-afterAll(() => fs.rmSync(tmp, { recursive: true, force: true }));const manifest = JSON.parse(fs.readFileSync(path.join(__dirname, "../workflows/comfyui/manifest.json"), "utf8")) as { workflows: ManifestWorkflow[] };const src = { url: "/api/files/uploads/clip.mp4", duration: 12, fps: 30, width: 1280, height: 720, hasAudio: true };diff --git a/tests/person-remover-reroll.test.ts b/tests/person-remover-reroll.test.tsindex 90144e27..ca67332c 100644--- a/tests/person-remover-reroll.test.ts+++ b/tests/person-remover-reroll.test.ts@@ -1,14 +1,14 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { beforeAll, describe, expect, it, vi } from "vitest";import type { Generation } from "@/lib/catalog/types";+import { tempDir } from "./helpers/temp-dir";vi.setConfig({ testTimeout: 120_000 });// "Redo from here" end to end in demo mode: an H3 person removal runs through the mock provider (which reports three// windows), then POST /api/remove-object/reroll draws it again from one window and puts the sound back as before.-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-person-reroll-"));+const dir = tempDir("fuobe-person-reroll-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.OLLAMA_URL = "http://127.0.0.1:9";@@ -28,7 +28,6 @@ beforeAll(() => {setSetting("demoMode", "auto");clip = saveFile({ data: fs.readFileSync(path.join(__dirname, "fixtures/shorts-12s.mp4")), contentType: "video/mp4", source: "upload", name: "skate.mp4" }).url;});-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));async function settle(id: string, ms = 90_000): Promise<Generation> {const end = Date.now() + ms;diff --git a/tests/pipeline.test.ts b/tests/pipeline.test.tsindex d6919e2d..792920f5 100644--- a/tests/pipeline.test.ts+++ b/tests/pipeline.test.ts@@ -1,9 +1,9 @@import fs from "node:fs";import http from "node:http";-import os from "node:os";import path from "node:path";-import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { beforeAll, describe, expect, it, vi } from "vitest";import type { Generation } from "@/lib/catalog/types";+import { tempDir } from "./helpers/temp-dir";vi.mock("@/lib/catalog", async (importOriginal) => {const mod = await importOriginal<typeof import("@/lib/catalog")>();@@ -12,7 +12,7 @@ vi.mock("@/lib/catalog", async (importOriginal) => {});vi.setConfig({ testTimeout: 90_000 });-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-pipeline-"));+const dir = tempDir("fuobe-pipeline-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.OLLAMA_URL = "http://127.0.0.1:9";@@ -25,7 +25,6 @@ const { db } = await import("@/server/db");const { probeOllama } = await import("@/server/providers/llm");beforeAll(() => setSetting("demoMode", "auto"));-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));async function settle(id: string, ms = 80_000): Promise<Generation> {const end = Date.now() + ms;diff --git a/tests/placeholder-results.test.ts b/tests/placeholder-results.test.tsindex cec8356c..186a499d 100644--- a/tests/placeholder-results.test.ts+++ b/tests/placeholder-results.test.ts@@ -1,7 +1,5 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";import { afterAll, afterEach, describe, expect, it } from "vitest";+import { tempDir } from "./helpers/temp-dir";/*** Placeholder results are opt-in: off by default on every install, hosted or local, so a run with nothing connected is@@ -9,7 +7,7 @@ import { afterAll, afterEach, describe, expect, it } from "vitest";* becomes off, a saved "on" stays. While on, every run makes a labelled placeholder.*/-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-placeholders-"));+const dir = tempDir("fuobe-placeholders-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9"; // nothing listens here@@ -43,7 +41,6 @@ afterEach(() => {afterAll(() => {globalThis.__fuobeDb?.close();globalThis.__fuobeDb = undefined;- fs.rmSync(dir, { recursive: true, force: true });});describe("the setting", () => {diff --git a/tests/popcorn-looks.test.ts b/tests/popcorn-looks.test.tsindex 42db54d2..1b3d33a1 100644--- a/tests/popcorn-looks.test.ts+++ b/tests/popcorn-looks.test.ts@@ -1,17 +1,15 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { beforeAll, describe, expect, it, vi } from "vitest";import { planStoryboard, STORYBOARD_LOOK_MODEL } from "@/lib/catalog/storyboard";import { buildPayload } from "@/lib/catalog/payload";import { filmReady } from "@/lib/storyboard-board";import { soulLook } from "@/lib/catalog/soul";import type { OutputFile } from "@/lib/catalog/types";+import { tempDir } from "./helpers/temp-dir";vi.setConfig({ testTimeout: 90_000 });// Popcorn with Fuobe Soul's looks (build plan O13): the planner, then boards end to end in demo mode.-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-popcorn-"));+const dir = tempDir("fuobe-popcorn-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.OLLAMA_URL = "http://127.0.0.1:9";@@ -23,7 +21,6 @@ const estimateRoute = await import("@/app/api/storyboards/estimate/route");const { db } = await import("@/server/db");beforeAll(() => setSetting("demoMode", "auto"));-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));const look = soulLook("v1-digitalcam")!;const scenes = ["a girl at a bus stop at night", "the bus arrives", "she looks back"];diff --git a/tests/price-check-reads.test.ts b/tests/price-check-reads.test.tsindex 6c7a5e1e..2843fc74 100644--- a/tests/price-check-reads.test.ts+++ b/tests/price-check-reads.test.ts@@ -1,13 +1,13 @@import fs from "node:fs";import http from "node:http";import type { AddressInfo } from "node:net";-import os from "node:os";import path from "node:path";-import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";+import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";import { NextRequest } from "next/server";+import { tempDir } from "./helpers/temp-dir";vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-price-reads-"));+const dir = tempDir("fuobe-price-reads-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.FUOBE_PUBLIC_SIGNUP = "1";@@ -44,11 +44,6 @@ afterEach(() => {vi.restoreAllMocks();resetRates();});-afterAll(() => {- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}-});/** A mono 16-bit WAV, `seconds` long. */function wav(seconds: number): Buffer {diff --git a/tests/providers.test.ts b/tests/providers.test.tsindex 6de6defb..35d33474 100644--- a/tests/providers.test.ts+++ b/tests/providers.test.ts@@ -1,17 +1,14 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, describe, expect, it } from "vitest";+import { describe, expect, it } from "vitest";import type { ModelDef, ModelRoute } from "@/lib/catalog/types";+import { tempDir } from "./helpers/temp-dir";// Provider adapters read their keys from the settings table: give them a throwaway database.-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-providers-"));+const dir = tempDir("fuobe-providers-");process.env.FUOBE_DATA_DIR = dir;const { falProvider } = await import("@/server/providers/fal");const { replicateProvider } = await import("@/server/providers/replicate");-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));/** Answer fetches from a table of URL → JSON body, in order of registration. */async function withFetch<T>(answers: Record<string, unknown>, fn: () => Promise<T>): Promise<{ result: T; urls: string[] }> {diff --git a/tests/public-signup-tools.test.ts b/tests/public-signup-tools.test.tsindex d5321c96..687e648a 100644--- a/tests/public-signup-tools.test.ts+++ b/tests/public-signup-tools.test.ts@@ -1,8 +1,8 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";+import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";import { NextRequest } from "next/server";+import { tempDir } from "./helpers/temp-dir";/*** PR #15's tools under the owner's public sign-up rules (docs/public-signup.md): Split soundtrack (and its Export mix),@@ -11,7 +11,7 @@ import { NextRequest } from "next/server";* owner's library closed, and the GPU pre-flight board lists the tools like main's studios.*/-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-signup-tools-"));+const dir = tempDir("fuobe-signup-tools-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.OLLAMA_URL = "http://127.0.0.1:9";@@ -32,12 +32,6 @@ const flyAround = await import("@/app/api/fly-around/route");const audioTools = await import("@/app/api/audio-tools/route");const { STUDIO_ROWS, studioOthers, studioTool, toolFor } = await import("@/server/gpu/tools");const { loadIndex } = await import("@/server/gpu/index-file");-afterAll(() => {- // The database stays open until the worker exits (Windows won't delete it before).- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}-});const passed = (r: Response) => r.headers.get("x-middleware-next") === "1";diff --git a/tests/public-signup-visitors.test.ts b/tests/public-signup-visitors.test.tsindex 1a292269..1f29af99 100644--- a/tests/public-signup-visitors.test.ts+++ b/tests/public-signup-visitors.test.ts@@ -1,8 +1,6 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";import { NextRequest } from "next/server";+import { tempDir } from "./helpers/temp-dir";// Route handlers call connection(); outside a request scope it would throw.vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));@@ -12,7 +10,7 @@ vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typ* uploads are its own.*/-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-visitors-"));+const dir = tempDir("fuobe-visitors-");process.env.FUOBE_DATA_DIR = dir;delete process.env.FUOBE_PASSWORD;delete process.env.FUOBE_ALLOWED_ORIGINS;@@ -23,10 +21,6 @@ const access = await import("@/lib/guest-access");const { db } = await import("@/server/db");afterAll(() => {delete process.env.FUOBE_PUBLIC_SIGNUP;- // The database stays open until the worker exits (Windows won't delete it before).- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}});const passed = (r: Response) => r.headers.get("x-middleware-next") === "1";diff --git a/tests/public-signup.test.ts b/tests/public-signup.test.tsindex 3e0d6333..8e744fb9 100644--- a/tests/public-signup.test.ts+++ b/tests/public-signup.test.ts@@ -1,16 +1,16 @@import crypto from "node:crypto";import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";+import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";import { NextRequest } from "next/server";+import { tempDir } from "./helpers/temp-dir";// Route handlers call connection(); outside a request scope it would throw.vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));// Route handlers set the session cookie through cookies() (no request scope in a test): a jar that only records.const jar = vi.hoisted(() => ({ set: vi.fn(), delete: vi.fn(), get: vi.fn() }));vi.mock("next/headers", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/headers")>()), cookies: async () => jar }));-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-signup-"));+const dir = tempDir("fuobe-signup-");process.env.FUOBE_DATA_DIR = dir;delete process.env.FUOBE_PASSWORD;delete process.env.FUOBE_PUBLIC_SIGNUP;@@ -18,12 +18,6 @@ delete process.env.FUOBE_ALLOWED_ORIGINS;const auth = await import("@/server/auth");const { proxy } = await import("@/proxy");const access = await import("@/lib/guest-access");-afterAll(() => {- // The database stays open until the worker exits (Windows won't delete it before).- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}-});const passed = (r: Response) => r.headers.get("x-middleware-next") === "1";const toLogin = (r: Response) => r.status === 307 && new URL(r.headers.get("location") ?? "", "http://x").pathname === "/login";diff --git a/tests/qma-angles.test.ts b/tests/qma-angles.test.tsindex ab4f92a8..1eb48bb8 100644--- a/tests/qma-angles.test.ts+++ b/tests/qma-angles.test.ts@@ -1,14 +1,14 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, describe, expect, it } from "vitest";+import { describe, expect, it } from "vitest";import type { GenInput, Operation } from "@/lib/catalog/types";import type { ComfyWorkflow, ManifestWorkflow } from "@/lib/comfy";+import { tempDir } from "./helpers/temp-dir";// The QMA camera-angles LoRA on Qwen-Image 2.1 (96 views) in the Angles app, Cinema's location views and// 3D re-shoots, the turnaround's missing sides and its 8-view still set, and the Canvas product angles. Open engine only:// fal's Qwen-Image 2.1 takes no LoRAs and Replicate has none.-const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-qma-"));+const tmp = tempDir("fuobe-qma-");process.env.FUOBE_DATA_DIR = tmp;process.env.COMFYUI_URL = "http://comfy.test:8188";const { prepareWorkflow } = await import("@/server/providers/comfyui");@@ -23,7 +23,6 @@ const { QMA_MODEL, QMA_WORKFLOW, parseQmaPrompt } = await import("@/lib/qma");const { STUDIO_ROWS, studioTool } = await import("@/server/gpu/tools");const { modelLicence } = await import("@/server/model-access");const { TurnaroundSchema } = await import("@/server/turnaround");-afterAll(() => fs.rmSync(tmp, { recursive: true, force: true }));const LIBRARY = path.join(process.cwd(), "workflows/comfyui");const read = (f: string) => JSON.parse(fs.readFileSync(path.join(LIBRARY, f), "utf8"));diff --git a/tests/qwen21-fast.test.ts b/tests/qwen21-fast.test.tsindex d0f54159..7c76390d 100644--- a/tests/qwen21-fast.test.ts+++ b/tests/qwen21-fast.test.ts@@ -1,14 +1,14 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, describe, expect, it } from "vitest";+import { describe, expect, it } from "vitest";import type { GenInput, Operation } from "@/lib/catalog/types";import type { ComfyWorkflow, ManifestWorkflow } from "@/lib/comfy";+import { tempDir } from "./helpers/temp-dir";// docs/research/new-models-10.md §6.7: Qwen-Image 2.1 in 2-6 steps (Options → Speed), on 16 GB// cards (Options → GPU, Zen Image Edit's small encoder), with the Texture-Fix VAE (Options → Decoder) and the 2.1// Next-Scene LoRA for Storyboard's next frames. All on the open engine: Qwen-Image 2.1 isn't hosted on fal or Replicate.-const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-qwen21-fast-"));+const tmp = tempDir("fuobe-qwen21-fast-");process.env.FUOBE_DATA_DIR = tmp;process.env.COMFYUI_URL = "http://comfy.test:8188";const { prepareWorkflow } = await import("@/server/providers/comfyui");@@ -29,7 +29,6 @@ const { qwen21Gpu } = await import("@/server/qwen21-gpu");const { writeSnapshot, dropSnapshots } = await import("@/server/gpu/snapshots");const { gateGeneration } = await import("@/server/gpu/gate");const { EDIT_STUDIO, INPAINT_STUDIO } = await import("@/lib/studios");-afterAll(() => fs.rmSync(tmp, { recursive: true, force: true }));const LIBRARY = path.join(process.cwd(), "workflows/comfyui");const read = (f: string) => JSON.parse(fs.readFileSync(path.join(LIBRARY, f), "utf8"));diff --git a/tests/recipe-builder.test.ts b/tests/recipe-builder.test.tsindex 2edd6259..22c8a6de 100644--- a/tests/recipe-builder.test.ts+++ b/tests/recipe-builder.test.ts@@ -1,13 +1,13 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { beforeAll, describe, expect, it, vi } from "vitest";+import { tempDir } from "./helpers/temp-dir";// Route handlers call connection() (no request scope in a test).vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));vi.setConfig({ testTimeout: 120_000 });-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-recipe-builder-"));+const dir = tempDir("fuobe-recipe-builder-");process.env.FUOBE_DATA_DIR = dir;// Nothing listens: open models run on the demo provider, and there's no LLM.process.env.COMFYUI_URL = "http://127.0.0.1:9";@@ -30,7 +30,6 @@ const checkRoute = await import("@/app/api/assist/skills/draft/check/route");const saveRoute = await import("@/app/api/assist/skills/draft/save/route");const nameRoute = await import("@/app/api/assist/skills/draft/name/route");-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));let photo = "";let clip = "";diff --git a/tests/recipes.test.ts b/tests/recipes.test.tsindex cbb77484..9927027e 100644--- a/tests/recipes.test.ts+++ b/tests/recipes.test.ts@@ -1,15 +1,15 @@import fs from "node:fs";import http from "node:http";import type { AddressInfo } from "node:net";-import os from "node:os";import path from "node:path";-import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { beforeAll, describe, expect, it, vi } from "vitest";+import { tempDir } from "./helpers/temp-dir";// Route handlers call connection() (no request scope in a test).vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));vi.setConfig({ testTimeout: 120_000 });-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-recipes-"));+const dir = tempDir("fuobe-recipes-");process.env.FUOBE_DATA_DIR = dir;// Nothing listens: open models run on the demo provider, and there's no LLM.process.env.COMFYUI_URL = "http://127.0.0.1:9";@@ -31,7 +31,6 @@ const verifyRoute = await import("@/app/api/assist/skills/[name]/verify/route");const generationsRoute = await import("@/app/api/generations/route");const { handleMcp } = await import("@/server/mcp");-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));let photo = "";let clip = "";diff --git a/tests/record-pages.test.ts b/tests/record-pages.test.tsindex 854a3264..4768d367 100644--- a/tests/record-pages.test.ts+++ b/tests/record-pages.test.ts@@ -1,17 +1,16 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, describe, expect, it } from "vitest";+import { describe, expect, it } from "vitest";import { NextRequest } from "next/server";import { recordForPath, unknownHubMode } from "@/lib/record-pages";+import { tempDir } from "./helpers/temp-dir";-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-records-"));+const dir = tempDir("fuobe-records-");process.env.FUOBE_DATA_DIR = dir;delete process.env.FUOBE_PASSWORD;const { db } = await import("@/server/db");const { recordExists } = await import("@/server/records");const { proxy } = await import("@/proxy");-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));/** Where the proxy sent a page request: its own path, or the not-found page (with the status). */function routed(pathname: string): { status: number; to: string | null } {diff --git a/tests/regenerate-2k.test.ts b/tests/regenerate-2k.test.tsindex 2a3b254e..a8423a34 100644--- a/tests/regenerate-2k.test.ts+++ b/tests/regenerate-2k.test.ts@@ -1,9 +1,9 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { beforeAll, describe, expect, it, vi } from "vitest";import type { Generation, GenInput, OutputFile } from "@/lib/catalog/types";import type { MediaInfo } from "@/lib/media-probe";+import { tempDir } from "./helpers/temp-dir";// Open-H3 Regenerate 2K (package n7-3-regenerate-2k): the library graph, the model, the provider's strings and frames,// the 15 s parts, the draft preset by source, the result actions per source and engine, the cloud re-render at 2K,@@ -11,7 +11,7 @@ import type { MediaInfo } from "@/lib/media-probe";// Regenerate is switched off for now (REGEN_OFFERED); these tests check it as it runs once switched on.// tests/regenerate-offered.test.ts checks that nothing offers it while it is off.vi.mock("@/lib/catalog/regenerate", async (importOriginal) => ({ ...(await importOriginal<typeof import("@/lib/catalog/regenerate")>()), REGEN_OFFERED: true }));-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-regenerate-"));+const dir = tempDir("fuobe-regenerate-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";delete process.env.FUOBE_PASSWORD;@@ -66,7 +66,6 @@ const stored = (seconds: number, width?: number, height?: number) =>saveFile({ data: mp4(seconds, width, height), contentType: "video/mp4", name: `regen-${seconds}-${width ?? 1280}x${height ?? 720}.mp4`, source: "upload" }).url;beforeAll(() => setSetting("demoMode", "auto"));-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));const ROOT = path.resolve(__dirname, "..");const graph = JSON.parse(fs.readFileSync(path.join(ROOT, "workflows/comfyui/video-regenerate-h3.json"), "utf8")) as Record<diff --git a/tests/relight.test.ts b/tests/relight.test.tsindex 476c65f9..0224a3c2 100644--- a/tests/relight.test.ts+++ b/tests/relight.test.ts@@ -1,5 +1,4 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";import { createElement } from "react";import { renderToStaticMarkup } from "react-dom/server";@@ -53,6 +52,7 @@ import { FLAT_SUBJECT, FRAGMENT, LOW_SHORT, packLight, reachAt, subjectDepthOf,import { isHelperFeature } from "@/lib/library";import { recordLocalGeneration } from "@/server/generations";import { relightToolLive } from "@/server/relight";+import { tempDir } from "./helpers/temp-dir";const NEGATION = /\b(no|not|never|nothing|none|without|don't|do not|doesn't|avoid|remove|removed)\b/i;const ROOT = path.join(__dirname, "..");@@ -690,7 +690,7 @@ describe("where Relight lives", () => {});it("opens the tool to everyone once its workflow has passed its check, and keeps the composer until then", () => {- const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-relight-live-"));+ const dir = tempDir("fuobe-relight-live-");const write = (validated: boolean) => {const f = path.join(dir, `m-${validated}.json`);fs.writeFileSync(f, JSON.stringify({ workflows: [{ id: RELIGHT_WORKFLOW, validated }, { id: "relight-scene-read", validated: true }] }));diff --git a/tests/remote-fetch.test.ts b/tests/remote-fetch.test.tsindex d48e8b5f..07ab475c 100644--- a/tests/remote-fetch.test.ts+++ b/tests/remote-fetch.test.ts@@ -1,10 +1,10 @@import fs from "node:fs";import http from "node:http";-import os from "node:os";import path from "node:path";import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { tempDir } from "./helpers/temp-dir";-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-ssrf-"));+const dir = tempDir("fuobe-ssrf-");process.env.FUOBE_DATA_DIR = dir;const { fetchRemote, fetchRemoteToFile, isPrivateAddress } = await import("@/server/remote-fetch");const { readRef } = await import("@/server/storage");@@ -50,7 +50,6 @@ beforeAll(async () => {});afterAll(() => {server.close();- fs.rmSync(dir, { recursive: true, force: true });});// The test server is on loopback: pretend "public.test" is a public host that resolves to it.diff --git a/tests/remove-dialogue.test.ts b/tests/remove-dialogue.test.tsindex 4d392c0c..bcc01e50 100644--- a/tests/remove-dialogue.test.ts+++ b/tests/remove-dialogue.test.ts@@ -1,7 +1,4 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { beforeAll, describe, expect, it } from "vitest";import {CLOUD_ONLY_REMOVE_PROBLEM,CLOUD_REMOVE_PROBLEM,@@ -23,10 +20,11 @@ import { splitTime } from "@/lib/av/split";import { resolveWorkflowId } from "@/lib/comfy-variants";import { HUB_MODES, modeHref } from "@/lib/hubs";import type { Generation, GenInput, Operation } from "@/lib/catalog/types";+import { tempDir } from "./helpers/temp-dir";// Video tools → Remove dialogue (DBS D2): the planner, the two-step chain on the open engine (graph A, then the// stream-copy mux), the graph the mux runs, the provider's bindings and the API in demo mode.-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-remove-dialogue-"));+const dir = tempDir("fuobe-remove-dialogue-");process.env.FUOBE_DATA_DIR = dir;// Nothing listens: the open models run on the demo provider.process.env.COMFYUI_URL = "http://127.0.0.1:9";@@ -41,7 +39,6 @@ const { nextSteps, outputActions } = await import("@/lib/output-actions");const { STUDIO_ROWS, studioTool } = await import("@/server/gpu/tools");beforeAll(() => setSetting("demoMode", "auto"));-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));const VIDEO = "/api/files/uploads/2026-11-01/interview.mp4";diff --git a/tests/remove-object-api.test.ts b/tests/remove-object-api.test.tsindex bac3a406..e9adca36 100644--- a/tests/remove-object-api.test.ts+++ b/tests/remove-object-api.test.ts@@ -1,14 +1,14 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";import type { Generation } from "@/lib/catalog/types";+import { tempDir } from "./helpers/temp-dir";vi.setConfig({ testTimeout: 120_000 });// /api/remove-object end to end in demo mode (no keys, no ComfyUI): every way of pointing on both engines// becomes one pipeline of ordinary generations, which the mock provider runs through.-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-remove-object-"));+const dir = tempDir("fuobe-remove-object-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.OLLAMA_URL = "http://127.0.0.1:9";@@ -41,7 +41,6 @@ beforeAll(() => {}mask = saveFile({ data: encodePng({ width: 72, height: 128, data }), contentType: "image/png", source: "upload", name: "mask.png" }).url;});-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));async function settle(id: string, ms = 90_000): Promise<Generation> {const end = Date.now() + ms;diff --git a/tests/remove-object-comfy.test.ts b/tests/remove-object-comfy.test.tsindex e8c4a4b8..4b41e94e 100644--- a/tests/remove-object-comfy.test.ts+++ b/tests/remove-object-comfy.test.ts@@ -1,19 +1,16 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, describe, expect, it } from "vitest";+import { describe, expect, it } from "vitest";import type { GenInput, Operation, OutputFile } from "@/lib/catalog/types";import type { MediaInfo } from "@/lib/media-probe";import { CLICK_OPEN_PROBLEM, HAND_OFF, REMOVE_SCENE } from "@/lib/catalog/remove-object";+import { tempDir } from "./helpers/temp-dir";// The comfyui provider driving the remove-object graphs (SAM 3.1 + VACE / VOID), the matte graphs' two outputs and// the depth graphs' colour map and side-by-side switch, bound for real on the library graphs.-const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-remove-object-comfy-"));+const tmp = tempDir("fuobe-remove-object-comfy-");process.env.FUOBE_DATA_DIR = tmp;process.env.COMFYUI_URL = "http://comfy.test:8188";const { collectOutputs, getWorkflow, prepareWorkflow } = await import("@/server/providers/comfyui");const { pickOutput } = await import("@/server/generations");-afterAll(() => fs.rmSync(tmp, { recursive: true, force: true }));const clip: MediaInfo = { container: "mp4", hasVideo: true, hasAudio: true, duration: 8, videoDuration: 8, width: 1280, height: 720, fps: 30, frames: 240 };const prepare = (id: string, input: Partial<GenInput>, op: Operation = "remove-object") =>diff --git a/tests/replicate-lora.test.ts b/tests/replicate-lora.test.tsindex 6be4b7dd..83367eaa 100644--- a/tests/replicate-lora.test.ts+++ b/tests/replicate-lora.test.ts@@ -1,21 +1,18 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, describe, expect, it } from "vitest";+import { describe, expect, it } from "vitest";import { getModel, getPreset, PRESETS } from "@/lib/catalog";import { fitLoras, loraEntry, loraRef } from "@/lib/catalog/loras";import { planGeneration } from "@/lib/catalog/plan";import type { Generation, GenInput, LoraRef, ModelRoute } from "@/lib/catalog/types";import { onEngine } from "@/lib/catalog/engines";+import { tempDir } from "./helpers/temp-dir";// Providers and route choice read keys and preferences from the settings table: a throwaway database.-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-replicate-lora-"));+const dir = tempDir("fuobe-replicate-lora-");process.env.FUOBE_DATA_DIR = dir;const { replicateProvider } = await import("@/server/providers/replicate");const { setSetting } = await import("@/server/settings");const { chooseRoute, createGenerations, getGeneration, previewGeneration } = await import("@/server/generations");const { changeAccess } = await import("@/server/model-access");-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));async function submit(route: ModelRoute, input: GenInput): Promise<{ url: string; body: Record<string, unknown> }> {const real = globalThis.fetch;diff --git a/tests/request-body-limits.test.ts b/tests/request-body-limits.test.tsindex 98bfa340..8b276e7d 100644--- a/tests/request-body-limits.test.ts+++ b/tests/request-body-limits.test.ts@@ -1,10 +1,8 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";+import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";+import { tempDir } from "./helpers/temp-dir";vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-bodies-"));+const dir = tempDir("fuobe-bodies-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.FUOBE_PUBLIC_SIGNUP = "1";@@ -30,11 +28,6 @@ beforeAll(() => {account = auth.createSession(auth.createAccount("[email protected]", "long enough").id).value;});afterEach(() => delete process.env.FUOBE_ALLOWED_ORIGINS);-afterAll(() => {- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}-});const MB = 2 ** 20;const bytes = (v: string | number | undefined) => {diff --git a/tests/restore-api.test.ts b/tests/restore-api.test.tsindex f8289631..0c2674a2 100644--- a/tests/restore-api.test.ts+++ b/tests/restore-api.test.ts@@ -1,8 +1,8 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";import type { Generation } from "@/lib/catalog/types";+import { tempDir } from "./helpers/temp-dir";vi.setConfig({ testTimeout: 120_000 });@@ -21,7 +21,7 @@ vi.mock("@/server/chains", async (original) => {// /api/restore end to end in demo mode (no keys, no ComfyUI, no LLM): a run on either engine becomes one pipeline of// ordinary generations the mock provider runs through; estimates with a fal key price the real LTX-2.3 route.-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-restore-"));+const dir = tempDir("fuobe-restore-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.OLLAMA_URL = "http://127.0.0.1:9";@@ -46,7 +46,6 @@ beforeAll(() => {// A 12 s, 16 fps, 72×128 clip with a sound track: 192 frames.clip = saveFile({ data: fs.readFileSync(path.join(__dirname, "fixtures/shorts-12s.mp4")), contentType: "video/mp4", source: "upload", name: "reel.mp4" }).url;});-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));async function settle(id: string, ms = 90_000): Promise<Generation> {const end = Date.now() + ms;diff --git a/tests/restore-comfy.test.ts b/tests/restore-comfy.test.tsindex 75b912dc..8dda98a4 100644--- a/tests/restore-comfy.test.ts+++ b/tests/restore-comfy.test.ts@@ -1,7 +1,4 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, describe, expect, it } from "vitest";+import { describe, expect, it } from "vitest";import { getModel, getPreset } from "@/lib/catalog";import { onEngine } from "@/lib/catalog/engines";import { loraEntry, loraRef } from "@/lib/catalog/loras";@@ -10,14 +7,14 @@ import { planGeneration } from "@/lib/catalog/plan";import { planRestore, RESTORE, restoreNegative } from "@/lib/catalog/restore";import type { GenInput } from "@/lib/catalog/types";import type { MediaInfo } from "@/lib/media-probe";+import { tempDir } from "./helpers/temp-dir";// Restore & colourise through the ComfyUI provider (the library graph video-restore-ltx25-tiled, bound for real) and// through fal's payload builder (the cloud half's FieldMap from the research).-const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-restore-comfy-"));+const tmp = tempDir("fuobe-restore-comfy-");process.env.FUOBE_DATA_DIR = tmp;process.env.COMFYUI_URL = "http://comfy.test:8188";const { prepareWorkflow } = await import("@/server/providers/comfyui");-afterAll(() => fs.rmSync(tmp, { recursive: true, force: true }));const scan: MediaInfo = { container: "mp4", hasVideo: true, hasAudio: true, duration: 545 / 24, videoDuration: 545 / 24, width: 640, height: 480, fps: 24, frames: 545 };const at = (wf: Record<string, { inputs: Record<string, unknown> }>, node: string, input: string) => wf[node]?.inputs[input];diff --git a/tests/restore-signup.test.ts b/tests/restore-signup.test.tsindex bff18fa4..1e5b110b 100644--- a/tests/restore-signup.test.ts+++ b/tests/restore-signup.test.ts@@ -1,8 +1,6 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";+import { afterEach, beforeAll, describe, expect, it } from "vitest";import { NextRequest } from "next/server";+import { tempDir } from "./helpers/temp-dir";/*** Restore & colourise under the owner's public sign-up rules (docs/public-signup.md): its price@@ -11,7 +9,7 @@ import { NextRequest } from "next/server";* without a GPU); the owner's are unchanged. The GPU pre-flight board has its row, on graphs the requirement index knows.*/-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-restore-signup-"));+const dir = tempDir("fuobe-restore-signup-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.OLLAMA_URL = "http://127.0.0.1:9";@@ -28,11 +26,6 @@ const { PromptSchema } = await import("@/server/restore");const { planRestore } = await import("@/lib/catalog/restore");const { STUDIO_ROWS, studioTool, toolFor } = await import("@/server/gpu/tools");const { loadIndex } = await import("@/server/gpu/index-file");-afterAll(() => {- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}-});const passed = (r: Response) => r.headers.get("x-middleware-next") === "1";diff --git a/tests/runtime-auth.test.ts b/tests/runtime-auth.test.tsindex 54095214..d518f403 100644--- a/tests/runtime-auth.test.ts+++ b/tests/runtime-auth.test.ts@@ -1,16 +1,14 @@-import fs from "node:fs";import os from "node:os";-import path from "node:path";-import { afterAll, describe, expect, it } from "vitest";+import { describe, expect, it } from "vitest";import { NextRequest } from "next/server";+import { tempDir } from "./helpers/temp-dir";-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-auth-rt-"));+const dir = tempDir("fuobe-auth-rt-");process.env.FUOBE_DATA_DIR = dir;delete process.env.FUOBE_PASSWORD;const auth = await import("@/server/auth");const { proxy, config } = await import("@/proxy");const { safeNext } = await import("@/lib/safe-redirect");-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));const post = (url: string, headers: Record<string, string> = {}) => new NextRequest(url, { method: "POST", headers, body: "{}" });diff --git a/tests/runtime-runner.test.ts b/tests/runtime-runner.test.tsindex 37750d0d..193376b8 100644--- a/tests/runtime-runner.test.ts+++ b/tests/runtime-runner.test.ts@@ -1,11 +1,9 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { beforeAll, describe, expect, it, vi } from "vitest";import type { Generation } from "@/lib/catalog/types";+import { tempDir } from "./helpers/temp-dir";vi.setConfig({ testTimeout: 40_000 });-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-runner-"));+const dir = tempDir("fuobe-runner-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.OLLAMA_URL = "http://127.0.0.1:9";@@ -17,7 +15,6 @@ const { mockProvider } = await import("@/server/providers/mock");const live = await import("@/server/live");beforeAll(() => setSetting("demoMode", "auto"));-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));diff --git a/tests/scene3d-provider.test.ts b/tests/scene3d-provider.test.tsindex 5e2cc933..67623410 100644--- a/tests/scene3d-provider.test.ts+++ b/tests/scene3d-provider.test.ts@@ -1,13 +1,11 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, describe, expect, it } from "vitest";+import { describe, expect, it } from "vitest";import type { ManifestWorkflow } from "@/lib/comfy";import type { ModelDef, ModelRoute } from "@/lib/catalog/types";+import { tempDir } from "./helpers/temp-dir";/** Cinema Studio's "Create 3D scene" on both engines: the catalog models, the ComfyUI binding and the outputs. */-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-scene3d-"));+const dir = tempDir("fuobe-scene3d-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://comfy.test:8188";@@ -19,7 +17,6 @@ const { mockProvider } = await import("@/server/providers/mock");const { decodePng } = await import("@/server/png");const { buildPointCloud, depthEncoding } = await import("@/lib/scene3d");-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));const manifestOf = (id: string): ManifestWorkflow => getWorkflow(id).manifest;diff --git a/tests/secret-box.test.ts b/tests/secret-box.test.tsindex 204e48ac..9bdc6e28 100644--- a/tests/secret-box.test.ts+++ b/tests/secret-box.test.ts@@ -1,14 +1,14 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, describe, expect, it, vi } from "vitest";+import { describe, expect, it, vi } from "vitest";+import { tempDir } from "./helpers/temp-dir";/*** Your keys: the box that seals an account's fal.ai key or Replicate token at rest (src/server/secret-box.ts). AES-256-GCM* under a server key in data/secrets.key, made once, never derived from the sign-in secret, bound to the account and the* provider. A broken key file fails closed: nothing is sealed, nothing opens, and the file is never written over.*/-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-secret-box-"));+const dir = tempDir("fuobe-secret-box-");process.env.FUOBE_DATA_DIR = dir;delete process.env.FUOBE_PASSWORD;@@ -16,12 +16,6 @@ const box = await import("@/server/secret-box");const auth = await import("@/server/auth");const keyFile = path.join(dir, "secrets.key");-afterAll(() => {- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}-});-/** Replace the key file's content, with a new modification time so the server reads it again. */// Each rewrite moves the file's time on by a whole second more than the last: two rewrites in the same millisecond// would otherwise get the same mtime, and the box (which caches the key by mtime) would keep the old key.diff --git a/tests/security-lows.test.ts b/tests/security-lows.test.tsindex 03200438..ddc2bdd8 100644--- a/tests/security-lows.test.ts+++ b/tests/security-lows.test.ts@@ -1,10 +1,10 @@import fs from "node:fs";import http from "node:http";-import os from "node:os";import path from "node:path";import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";+import { tempDir } from "./helpers/temp-dir";-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-lows-"));+const dir = tempDir("fuobe-lows-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.FUOBE_PUBLIC_SIGNUP = "1";@@ -30,11 +30,6 @@ afterEach(() => {globalThis.__fuobeSelfAddresses = undefined;globalThis.__fuobeTestGpuPort = undefined;});-afterAll(() => {- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}-});/** A run of `account` (or the owner's), finished. */function runOf(account?: string): string {diff --git a/tests/setup/temp-root.ts b/tests/setup/temp-root.tsnew file mode 100644index 00000000..0b10eaa5--- /dev/null+++ b/tests/setup/temp-root.ts@@ -0,0 +1,83 @@+import fs from "node:fs";+import os from "node:os";+import path from "node:path";++/**+ * Vitest global setup: the whole run's temp files go in one folder of its own, removed when the run ends.+ *+ * TEMP, TMP and TMPDIR point at the run's folder before the test workers start, so `os.tmpdir()` in every test, in the+ * code under test and in any program a test starts lands inside it. Each file removes its own folders as it ends+ * (tests/helpers/temp-dir.ts); this removes what is left once every worker has exited and let go of its files. A run+ * that was stopped before its end leaves its folder behind, and the next run removes it once that run's process is gone.+ */++const PREFIX = "fuobe-test-run-";+const OWNER = ".owner-pid";+const VARS = ["TEMP", "TMP", "TMPDIR"] as const;++function alive(pid: number): boolean {+ try {+ process.kill(pid, 0);+ return true;+ } catch (e) {+ return (e as NodeJS.ErrnoException).code === "EPERM";+ }+}++async function remove(dir: string): Promise<boolean> {+ try {+ await fs.promises.rm(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 });+ return true;+ } catch (e) {+ console.warn(`[tests] Couldn't remove ${dir}: ${(e as Error).message}`);+ return false;+ }+}++/** Folders of earlier runs whose process has exited. A folder without its owner file is left for an hour (just made). */+async function removeStale(base: string): Promise<void> {+ let names: string[] = [];+ try {+ names = fs.readdirSync(base).filter((n) => n.startsWith(PREFIX));+ } catch {+ return;+ }+ for (const name of names) {+ const dir = path.join(base, name);+ try {+ const pid = Number(fs.readFileSync(path.join(dir, OWNER), "utf8"));+ if (Number.isInteger(pid) && pid > 0 && alive(pid)) continue;+ } catch {+ try {+ if (Date.now() - fs.statSync(dir).mtimeMs < 60 * 60_000) continue;+ } catch {+ continue;+ }+ }+ await remove(dir);+ }+}++export default async function setup(): Promise<() => Promise<void>> {+ const base = os.tmpdir();+ await removeStale(base);+ const root = fs.mkdtempSync(path.join(base, PREFIX));+ fs.writeFileSync(path.join(root, OWNER), String(process.pid));+ const saved = Object.fromEntries(VARS.map((k) => [k, process.env[k]]));+ for (const k of VARS) process.env[k] = root;++ return async () => {+ for (const k of VARS) {+ if (saved[k] === undefined) delete process.env[k];+ else process.env[k] = saved[k];+ }+ // A test that makes its folder without tempDir(), or a program that leaves its temp files, shows up here.+ try {+ const left = fs.readdirSync(root).filter((n) => n !== OWNER);+ if (left.length) console.warn(`[tests] Temp files left by the run (removed now): ${left.sort().join(", ")}`);+ } catch {+ // Already gone.+ }+ await remove(root);+ };+}diff --git a/tests/share-links.test.ts b/tests/share-links.test.tsindex 8873d1a7..892956f7 100644--- a/tests/share-links.test.ts+++ b/tests/share-links.test.ts@@ -1,15 +1,15 @@import crypto from "node:crypto";import fs from "node:fs";-import os from "node:os";import path from "node:path";import zlib from "node:zlib";import { createElement } from "react";import { renderToStaticMarkup } from "react-dom/server";-import { afterAll, afterEach, describe, expect, it, vi } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";import { NextRequest } from "next/server";import { userTitle } from "@/lib/library";import type { ShareListItem } from "@/lib/share";import type { ShareRow } from "@/server/share-access";+import { tempDir } from "./helpers/temp-dir";// Route handlers call connection() and the page reads its address from headers() (no request scope in a test).vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));@@ -18,7 +18,7 @@ vi.mock("next/headers", async (importOriginal) => ({headers: async () => new Headers({ host: "studio.example:3000", "x-forwarded-proto": "https" }),}));-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-share-"));+const dir = tempDir("fuobe-share-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";delete process.env.FUOBE_PASSWORD;@@ -41,7 +41,6 @@ const { SharePage } = await import("@/app/s/share-page");const sharePage = await import("@/app/s/[token]/page");const filesRoute = await import("@/app/api/files/[...path]/route");-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));afterEach(() => {vi.restoreAllMocks();globalThis.__fuobeShareGuard = undefined;diff --git a/tests/shorts-api.test.ts b/tests/shorts-api.test.tsindex 8d1ea892..7e640e81 100644--- a/tests/shorts-api.test.ts+++ b/tests/shorts-api.test.ts@@ -1,12 +1,12 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { beforeAll, describe, expect, it, vi } from "vitest";import type { Generation } from "@/lib/catalog/types";+import { tempDir } from "./helpers/temp-dir";vi.setConfig({ testTimeout: 120_000 });-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-shorts-"));+const dir = tempDir("fuobe-shorts-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.OLLAMA_URL = "http://127.0.0.1:9";@@ -44,7 +44,6 @@ beforeAll(() => {clip = saveFile({ data: fs.readFileSync(path.join(__dirname, "fixtures/shorts-12s.mp4")), contentType: "video/mp4", source: "upload", name: "beach day.mp4" }).url;png = saveFile({ data: Buffer.from("89504e470d0a1a0a", "hex"), contentType: "image/png", source: "upload" }).url;});-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));async function settle(id: string, ms = 90_000): Promise<Generation> {const end = Date.now() + ms;diff --git a/tests/sign-in-hardening.test.ts b/tests/sign-in-hardening.test.tsindex 62956104..0d87c35e 100644--- a/tests/sign-in-hardening.test.ts+++ b/tests/sign-in-hardening.test.ts@@ -1,15 +1,15 @@import crypto from "node:crypto";import fs from "node:fs";-import os from "node:os";import path from "node:path";import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";+import { tempDir } from "./helpers/temp-dir";// Route handlers set the session cookie through cookies() (no request scope in a test): a jar that only records.const jar = { set: vi.fn(), delete: vi.fn(), get: vi.fn() };vi.mock("next/headers", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/headers")>()), cookies: async () => jar }));vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-sign-in-"));+const dir = tempDir("fuobe-sign-in-");process.env.FUOBE_DATA_DIR = dir;process.env.FUOBE_PUBLIC_SIGNUP = "1";process.env.FUOBE_TRUST_PROXY = "1";@@ -51,9 +51,6 @@ afterEach(() => {afterAll(() => {delete process.env.FUOBE_PUBLIC_SIGNUP;delete process.env.FUOBE_TRUST_PROXY;- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}});describe("M-1: after sign-in, only pages on this site", () => {diff --git a/tests/sign-out-everyone.test.ts b/tests/sign-out-everyone.test.tsindex 237d22d6..79d325b6 100644--- a/tests/sign-out-everyone.test.ts+++ b/tests/sign-out-everyone.test.ts@@ -1,12 +1,12 @@import crypto from "node:crypto";import fs from "node:fs";-import os from "node:os";import path from "node:path";import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";import { NextRequest } from "next/server";+import { tempDir } from "./helpers/temp-dir";vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-signout-"));+const dir = tempDir("fuobe-signout-");process.env.FUOBE_DATA_DIR = dir;delete process.env.FUOBE_PASSWORD;delete process.env.FUOBE_PUBLIC_SIGNUP;@@ -15,9 +15,6 @@ const { proxy } = await import("@/proxy");const route = await import("@/app/api/auth/sessions/route");afterAll(() => {delete process.env.FUOBE_PASSWORD;- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}});const DAY = 86_400_000;diff --git a/tests/skill-runs.test.ts b/tests/skill-runs.test.tsindex a32d47a5..391e7de6 100644--- a/tests/skill-runs.test.ts+++ b/tests/skill-runs.test.ts@@ -1,7 +1,7 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { beforeAll, describe, expect, it, vi } from "vitest";+import { tempDir } from "./helpers/temp-dir";vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));vi.setConfig({ testTimeout: 180_000 });@@ -12,7 +12,7 @@ vi.setConfig({ testTimeout: 180_000 });* the state survives a restart, and the free dry run deletes the studio records it made.*/-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-skill-runs-"));+const dir = tempDir("fuobe-skill-runs-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.OLLAMA_URL = "http://127.0.0.1:9";@@ -29,14 +29,6 @@ const { runAsDemo, inDemoScope, outsideDemo } = await import("@/server/demo-scopconst { spendOf } = await import("@/lib/assist-schedule");const tools = await import("@/server/assist/tools");-afterAll(() => {- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {- // Windows keeps the open database.- }-});-let clip = "";beforeAll(() => {setSetting("demoMode", "auto");diff --git a/tests/skill-suggest.test.ts b/tests/skill-suggest.test.tsindex 04f280ce..b13a37f9 100644--- a/tests/skill-suggest.test.ts+++ b/tests/skill-suggest.test.ts@@ -1,7 +1,5 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { beforeAll, describe, expect, it, vi } from "vitest";+import { tempDir } from "./helpers/temp-dir";vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));vi.setConfig({ testTimeout: 60_000 });@@ -11,7 +9,7 @@ vi.setConfig({ testTimeout: 60_000 });* words and files) and offers to save it as a skill, at most once a day, until it's saved or dismissed.*/-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-skill-suggest-"));+const dir = tempDir("fuobe-skill-suggest-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.OLLAMA_URL = "http://127.0.0.1:9";@@ -27,14 +25,6 @@ const { encodePng } = await import("@/server/png");const { shapeOf, recipeShapeNodes } = await import("@/lib/recipe");const route = await import("@/app/api/skill-suggestions/route");-afterAll(() => {- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {- // Windows keeps the open database.- }-});-let photo = "";beforeAll(() => {setSetting("demoMode", "auto");diff --git a/tests/soul-fixes.test.ts b/tests/soul-fixes.test.tsindex 48f19be5..55d61187 100644--- a/tests/soul-fixes.test.ts+++ b/tests/soul-fixes.test.ts@@ -1,16 +1,16 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { beforeAll, describe, expect, it, vi } from "vitest";import type { CanvasGraph, CanvasNode } from "@/lib/catalog/canvas";import type { LoraRef } from "@/lib/catalog/types";+import { tempDir } from "./helpers/temp-dir";// Fuobe Soul after review (o/soul): the open engine's batch, a look beside a moved moodboard, the dual-engine// model in the lists, the canvas, the CLI and Assist, fal's megapixel, the civitai rule, Soul HD with a picture,// Soul Cinema's 21:9 crop and the hand-off over the composer's engine swap.vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-soul-fixes-"));+const dir = tempDir("fuobe-soul-fixes-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9"; // nothing listens here: open runs fall back to the demo@@ -33,7 +33,6 @@ const { withoutUnreachableCivitai } = await import("@/server/loras");const { formatCost } = await import("@/lib/format");beforeAll(() => setSetting("demoMode", "auto"));-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));const plan = (engine: "open" | "cloud", req: Partial<Parameters<typeof planGeneration>[0]> = {}, id = "fuobe-soul") => {const m = onEngine(getModel(id)!, engine);diff --git a/tests/soul-id-runtime.test.ts b/tests/soul-id-runtime.test.tsindex f625cd8e..28a5c58e 100644--- a/tests/soul-id-runtime.test.ts+++ b/tests/soul-id-runtime.test.ts@@ -1,11 +1,11 @@import { execFileSync } from "node:child_process";import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { onEngine } from "@/lib/catalog/engines";import { getModel } from "@/lib/catalog";import { identityFor, identityKey, SOUL_ID_COPY } from "@/lib/catalog/training";+import { tempDir } from "./helpers/temp-dir";// fal's storage upload goes through its client: the dataset zip and a LoRA sent to fal land here instead.const uploads = vi.hoisted(() => [] as { data: Buffer; type: string; name?: string }[]);@@ -23,14 +23,13 @@ vi.mock("@/server/providers/fal", async (importOriginal) => {};});-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-soul-id-"));+const dir = tempDir("fuobe-soul-id-");process.env.FUOBE_DATA_DIR = dir;const { db } = await import("@/server/db");const { createElement, getElement, updateElement } = await import("@/server/elements");const { startTraining, pollTrainings, listTrainings, trainingKit, attachLora, trainedCopiesSettled, retiredTraining } = await import("@/server/training");const { ensureLorasOnComfy, prepareCloudLoras, listLoraCopies, TRAINED_DIR } = await import("@/server/loras");const { setSetting } = await import("@/server/settings");-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));/** A fake network: answers by URL prefix, records every call and its body, never touches the internet. */interface Call {diff --git a/tests/soul-runs.test.ts b/tests/soul-runs.test.tsindex 1ed3edf9..5ad2b842 100644--- a/tests/soul-runs.test.ts+++ b/tests/soul-runs.test.ts@@ -1,12 +1,10 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { beforeAll, describe, expect, it } from "vitest";import type { ComfyWorkflow } from "@/lib/comfy";+import { tempDir } from "./helpers/temp-dir";// Fuobe Soul as a run (build plan O2): one model on both engines, the look applied on the server, the cloud// payload from the research's FieldMaps, the ComfyUI graph with the look's LoRA chain, prices and post steps.-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-soul-"));+const dir = tempDir("fuobe-soul-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9"; // nothing listens here: open runs fall back to the demo@@ -21,7 +19,6 @@ const { loraEntry } = await import("@/lib/catalog/loras");const { SOUL_TAILS } = await import("@/lib/catalog/soul-originals.generated");beforeAll(() => setSetting("demoMode", "auto"));-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));const soul = () => getModel("fuobe-soul")!;const plan = (engine: "open" | "cloud", req: Partial<Parameters<typeof planGeneration>[0]> = {}) => {diff --git a/tests/sound-tools-assist.test.ts b/tests/sound-tools-assist.test.tsindex 18732ae2..a928a7ed 100644--- a/tests/sound-tools-assist.test.ts+++ b/tests/sound-tools-assist.test.ts@@ -1,14 +1,14 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { beforeAll, describe, expect, it } from "vitest";import { CLOUD_SPLIT_PROBLEM } from "@/lib/av/split";import { OFF_DB, planRemix, REMIX_FEATURE, remixWords } from "@/lib/av/clean-dialogue";import type { GenInput } from "@/lib/catalog/types";+import { tempDir } from "./helpers/temp-dir";// Assist and MCP's split_soundtrack and remove_dialogue (DBS D9), and the remix at set levels they run on graph C// (oss-dbs-remix, the model Clean up dialogue runs on).-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-sound-assist-"));+const dir = tempDir("fuobe-sound-assist-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.OLLAMA_URL = "http://127.0.0.1:9";@@ -22,11 +22,6 @@ const { handleMcp } = await import("@/server/mcp");const { getGeneration } = await import("@/server/generations");beforeAll(() => setSetting("demoMode", "auto"));-afterAll(() => {- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}-});/** A 16-bit PCM WAV of `seconds` of silence. */function wav(seconds: number, channels = 2, rate = 8000): Buffer {diff --git a/tests/split-soundtrack.test.ts b/tests/split-soundtrack.test.tsindex 93f56b0c..675290a5 100644--- a/tests/split-soundtrack.test.ts+++ b/tests/split-soundtrack.test.ts@@ -1,9 +1,8 @@import fs from "node:fs";import http from "node:http";import type { AddressInfo } from "node:net";-import os from "node:os";import path from "node:path";-import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";import {backgroundLowered,CLOUD_ONLY_PROBLEM,@@ -52,11 +51,12 @@ import {} from "@/lib/av/split";import { getModel } from "@/lib/catalog";import { HUB_MODES, modeHref } from "@/lib/hubs";+import { tempDir } from "./helpers/temp-dir";// Audio → Split soundtrack (DBS D1): the planner, the mixer maths and the API in demo mode.const SURROUND_NOTE ="This file has 6 channels. ComfyUI saves audio in mono or stereo only, so the stems come out in mono (all channels mixed), and Music & effects is the music and effects stems added up.";-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-split-"));+const dir = tempDir("fuobe-split-");process.env.FUOBE_DATA_DIR = dir;// Nothing listens: the open model runs on the demo provider.process.env.COMFYUI_URL = "http://127.0.0.1:9";@@ -74,7 +74,6 @@ const { uploadSource } = await import("@/components/audio-tools/split-tool");const { CONNECT_GPU_HEADER, CONNECT_GPU_MESSAGE, GUEST_HEADER, GUEST_RUN_MESSAGE } = await import("@/lib/guest-access");beforeAll(() => setSetting("demoMode", "auto"));-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));/** A 16-bit WAV of a tone with `channels` channels, saved as an upload. */function upload(seconds: number, channels = 2, name = "film.wav"): string {diff --git a/tests/starters-create.test.ts b/tests/starters-create.test.tsindex c4eb9cdd..acce4a4d 100644--- a/tests/starters-create.test.ts+++ b/tests/starters-create.test.ts@@ -1,8 +1,8 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { beforeAll, describe, expect, it, vi } from "vitest";import type { EpisodeSettings, EpisodeView } from "@/lib/catalog/faceless";+import { tempDir } from "./helpers/temp-dir";// Every ready-made starter of Faceless Studio, Content Factory, Explainer, Ads Studio, Click to Ad and Marketing Studio,// made as the owner's "Use template" makes it, on a fresh data dir, then run on the demo provider to the end: the@@ -14,7 +14,7 @@ vi.mock("next/server", async (importOriginal) => ({after: (task: unknown) => void Promise.resolve(typeof task === "function" ? (task as () => unknown)() : task).catch(() => {}),}));-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-starters-"));+const dir = tempDir("fuobe-starters-");process.env.FUOBE_DATA_DIR = dir;// Nothing listens: models run on the demo provider, and there's no LLM (the offline writers run).process.env.COMFYUI_URL = "http://127.0.0.1:9";@@ -41,11 +41,6 @@ beforeAll(() => {setSetting("demoMode", "auto");setSetting("enhanceProvider", "none");});-afterAll(() => {- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}-});const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));const applyTemplate = async (id: string, engine: "cloud" | "open" = "cloud") => {diff --git a/tests/storyboard-name.test.ts b/tests/storyboard-name.test.tsindex 9bc5713d..6f10a2db 100644--- a/tests/storyboard-name.test.ts+++ b/tests/storyboard-name.test.ts@@ -1,9 +1,7 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { beforeAll, describe, expect, it } from "vitest";+import { tempDir } from "./helpers/temp-dir";-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-storyboard-name-"));+const dir = tempDir("fuobe-storyboard-name-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";@@ -17,7 +15,6 @@ beforeAll(() => {// No prompt LLM: the story is split by the offline shot list.setSetting("enhanceProvider", "none");});-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));const batchTitle = (id: string) => (gens.getGeneration(id)!.request as { batchTitle?: string }).batchTitle;diff --git a/tests/swap-studio-api.test.ts b/tests/swap-studio-api.test.tsindex 8d2e7e91..2d1d44ad 100644--- a/tests/swap-studio-api.test.ts+++ b/tests/swap-studio-api.test.ts@@ -1,16 +1,16 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { beforeAll, describe, expect, it, vi } from "vitest";import { currentSegments, jobState, type SwapProject } from "@/lib/catalog/swap-studio";import type { SwapProjectView } from "@/server/swap-studio";+import { tempDir } from "./helpers/temp-dir";vi.setConfig({ testTimeout: 240_000 });vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));// Character Swap Studio's API end to end in demo mode (no keys, no ComfyUI): projects, clips, cuts, words, masks,// anchors, segments queued with continuations (waiting, launched, stopped), review and the assembly, on both engines.-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-swap-studio-"));+const dir = tempDir("fuobe-swap-studio-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.OLLAMA_URL = "http://127.0.0.1:9";@@ -45,7 +45,6 @@ beforeAll(() => {const data = Buffer.alloc(64 * 64 * 4, 200);hero = saveFile({ data: encodePng({ width: 64, height: 64, data }), contentType: "image/png", source: "upload", name: "hero.png" }).url;});-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));async function view(id: string): Promise<SwapProjectView> {const res = await project.GET(req("GET"), ctx(id) as never);diff --git a/tests/swap-studio-sharpen.test.ts b/tests/swap-studio-sharpen.test.tsindex 7ec4a990..298ac3ff 100644--- a/tests/swap-studio-sharpen.test.ts+++ b/tests/swap-studio-sharpen.test.ts@@ -1,10 +1,8 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { beforeAll, describe, expect, it, vi } from "vitest";import { NextRequest } from "next/server";import type { SwapProject, SwapTake } from "@/lib/catalog/swap-studio";import type { SwapProjectView } from "@/server/swap-studio";+import { tempDir } from "./helpers/temp-dir";vi.setConfig({ testTimeout: 240_000 });vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));@@ -15,7 +13,7 @@ vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typ// Your GPU's sizes regenerate with Open-H3 Regenerate, which is switched off for now (REGEN_OFFERED); these tests check// them as they run once it is on. tests/regenerate-offered.test.ts checks that nothing offers them while it is off.vi.mock("@/lib/catalog/regenerate", async (importOriginal) => ({ ...(await importOriginal<typeof import("@/lib/catalog/regenerate")>()), REGEN_OFFERED: true }));-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-swap-sharpen-"));+const dir = tempDir("fuobe-swap-sharpen-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.OLLAMA_URL = "http://127.0.0.1:9";@@ -76,7 +74,6 @@ beforeAll(() => {square = saveFile({ data: mp4(6, 2048, 2048), contentType: "video/mp4", source: "upload", name: "square.mp4" }).url;hero = saveFile({ data: encodePng({ width: 64, height: 64, data: Buffer.alloc(64 * 64 * 4, 200) }), contentType: "image/png", source: "upload", name: "hero.png" }).url;});-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));async function view(id: string): Promise<SwapProjectView> {const res = await project.GET(req("GET"), ctx(id) as never);diff --git a/tests/template-covers.test.ts b/tests/template-covers.test.tsindex 87cad3c8..4df56a40 100644--- a/tests/template-covers.test.ts+++ b/tests/template-covers.test.ts@@ -1,10 +1,9 @@import { spawnSync } from "node:child_process";import { createHash } from "node:crypto";import fs from "node:fs";-import os from "node:os";import path from "node:path";import { gzipSync } from "node:zlib";-import { afterAll, describe, expect, it } from "vitest";+import { describe, expect, it } from "vitest";import { CANVAS_TEMPLATES } from "@/lib/catalog/canvas";import { PRESETS } from "@/lib/catalog/content-factory";import { EXPLAINER_STYLE_IDS } from "@/lib/catalog/faceless";@@ -19,6 +18,7 @@ import { PRESET_PREVIEWS } from "@/lib/preset-previews.generated";import { STARTERS } from "@/lib/starters/catalog";import { TEMPLATE_GROUPS, templateCover, type TemplateGroup } from "@/lib/template-covers";import { TEMPLATE_COVERS } from "@/lib/template-covers.generated";+import { tempDir } from "./helpers/temp-dir";/** The template tiles' covers manifest (src/lib/template-covers.generated.ts, written by pnpm eval:covers --templates)@@ -142,8 +142,7 @@ describe("the template covers manifest", () => {});const hasFfmpeg = spawnSync("ffmpeg", ["-version"]).status === 0;-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-template-covers-"));-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));+const dir = tempDir("fuobe-template-covers-");const SAMPLE_CLIP = path.join(root, "public", "samples", "demo-landscape.mp4");describe.skipIf(!hasFfmpeg)("pnpm eval:covers --templates", () => {diff --git a/tests/training-runtime.test.ts b/tests/training-runtime.test.tsindex 520c8547..a42a773c 100644--- a/tests/training-runtime.test.ts+++ b/tests/training-runtime.test.ts@@ -1,10 +1,8 @@-import fs from "node:fs";import http from "node:http";-import os from "node:os";-import path from "node:path";import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { tempDir } from "./helpers/temp-dir";-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-train-rt-"));+const dir = tempDir("fuobe-train-rt-");process.env.FUOBE_DATA_DIR = dir;const { db } = await import("@/server/db");@@ -31,7 +29,6 @@ beforeAll(async () => {afterAll(() => {globalThis.__fuobeTestFalUrl = undefined;server.close();- fs.rmSync(dir, { recursive: true, force: true });});function training(o: { target: string; provider: string; status: string; externalId?: string | null; meta?: unknown; age?: number }) {diff --git a/tests/training.test.ts b/tests/training.test.tsindex 1c699a10..9423dac1 100644--- a/tests/training.test.ts+++ b/tests/training.test.ts@@ -1,6 +1,5 @@import { execFileSync } from "node:child_process";import fs from "node:fs";-import os from "node:os";import path from "node:path";import { describe, expect, it } from "vitest";import { getModel, getPreset } from "@/lib/catalog";@@ -37,6 +36,7 @@ import {import { buildPayload } from "@/lib/catalog/payload";import { OWN_LOOK, soulPostSteps, soulRecipe } from "@/lib/catalog/soul";import { zip } from "@/server/zip";+import { tempDir } from "./helpers/temp-dir";const ROOT = path.resolve(__dirname, "..");@@ -236,7 +236,7 @@ describe("Fuobe Soul ID targets (build plan O3)", () => {});it("writes zips other tools can read", () => {- const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-zip-"));+ const dir = tempDir("fuobe-zip-");const file = path.join(dir, "kit.zip");fs.writeFileSync(file, zip([{ name: "dataset/001.txt", data: Buffer.from("photo of nvrysfz") }, { name: "a.yaml", data: Buffer.from("{}") }]));const out = execFileSync("python3", ["-I", "-c", "import sys,zipfile;z=zipfile.ZipFile(sys.argv[1]);print(z.testzip(), z.read('dataset/001.txt').decode())", file]).toString();diff --git a/tests/turnaround-api.test.ts b/tests/turnaround-api.test.tsindex 32eb1586..a67ed4af 100644--- a/tests/turnaround-api.test.ts+++ b/tests/turnaround-api.test.ts@@ -1,11 +1,9 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { beforeAll, describe, expect, it } from "vitest";+import { tempDir } from "./helpers/temp-dir";/** Turnaround video (build plan N7-6) through /api/turnaround and Cinema's "turnaround" action, on the demo provider. */-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-turnaround-"));+const dir = tempDir("fuobe-turnaround-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.OLLAMA_URL = "http://127.0.0.1:9";@@ -27,7 +25,6 @@ beforeAll(() => {setSetting("demoMode", "auto");setSetting("enhanceProvider", "none");});-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));const upload = (name: string, width = 18, height = 32) => saveFile({ data: encodePng({ width, height, data: Buffer.alloc(width * height * 4, 128) }), contentType: "image/png", name, source: "upload" }).url;const post = (body: unknown, preview = false) =>diff --git a/tests/vectorize.test.ts b/tests/vectorize.test.tsindex 7c44e6a8..8e28680b 100644--- a/tests/vectorize.test.ts+++ b/tests/vectorize.test.ts@@ -1,8 +1,6 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { beforeAll, describe, expect, it, vi } from "vitest";import type { Generation, GenInput } from "@/lib/catalog/types";+import { tempDir } from "./helpers/temp-dir";/** The Vectorize app: Recraft Vectorize on the cloud, VTracer through ComfyUI (image-vectorize-vtracer)@@ -10,7 +8,7 @@ import type { Generation, GenInput } from "@/lib/catalog/types";*/vi.setConfig({ testTimeout: 60_000 });-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-vectorize-"));+const dir = tempDir("fuobe-vectorize-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.OLLAMA_URL = "http://127.0.0.1:9";@@ -29,7 +27,6 @@ const { studioCatalog } = await import("@/lib/studio-catalog");const files = await import("@/app/api/files/[...path]/route");beforeAll(() => setSetting("demoMode", "auto"));-afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));async function settle(id: string, ms = 40_000): Promise<Generation> {const end = Date.now() + ms;diff --git a/tests/video-finish.test.ts b/tests/video-finish.test.tsindex 2ae72ee4..9484806a 100644--- a/tests/video-finish.test.ts+++ b/tests/video-finish.test.ts@@ -1,8 +1,7 @@import { execFileSync } from "node:child_process";import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { beforeAll, describe, expect, it, vi } from "vitest";import { FORMAT_INFO, formatList, formatsOf } from "@/lib/av/formats";import { DEFAULT_FPS_TARGET, FPS_TARGETS, fpsFrames, fpsPlan, fpsSummary } from "@/lib/av/fps";import { targetShortEdge, upscaledSize, upscaleFactorFor, upscaleTier } from "@/lib/av/upscale";@@ -18,6 +17,7 @@ import type { MediaInfo } from "@/lib/media-probe";import { editOnlyFormat, outputActions } from "@/lib/output-actions";import { slimModel } from "@/lib/studio-catalog";import { FPS_BOOST_STUDIO, SDR_TO_HDR_STUDIO, UPSCALE_STUDIO, VIDEO_EXPORT_STUDIO, VIDEO_UPSCALE_STUDIO } from "@/lib/studios";+import { tempDir } from "./helpers/temp-dir";// The Upscale hub's video tools (r4/video-finish): FPS Boost and slow motion, SDR to HDR, pro export formats,// the upscalers' options, and chunked open upscaling.@@ -358,7 +358,7 @@ describe("results", () => {// ---------------------------------------------------------------------------// The open engine: values and graph edits prepareWorkflow makes for each tool.-const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-video-finish-"));+const tmp = tempDir("fuobe-video-finish-");process.env.FUOBE_DATA_DIR = tmp;process.env.COMFYUI_URL = "http://127.0.0.1:9";const { prepareWorkflow, comfyProvider, CANCEL_SWEEPS } = await import("@/server/providers/comfyui");@@ -368,7 +368,6 @@ const { mediaFacts } = await import("@/server/media-facts");const { setSetting } = await import("@/server/settings");const gens = await import("@/server/generations");const { saveFile } = await import("@/server/storage");-afterAll(() => fs.rmSync(tmp, { recursive: true, force: true }));const clip = (o: Partial<MediaInfo>): MediaInfo => ({ container: "mp4", hasVideo: true, hasAudio: true, duration: 4, videoDuration: 4, width: 1280, height: 720, fps: 24, frames: 96, ...o });async function prep(endpoint: string, op: Operation, input: GenInput, info: MediaInfo = clip({}), ram = 64 * 2 ** 30) {diff --git a/tests/voice-design-comfy.test.ts b/tests/voice-design-comfy.test.tsindex 1c72c39d..020c8d4f 100644--- a/tests/voice-design-comfy.test.ts+++ b/tests/voice-design-comfy.test.ts@@ -1,14 +1,14 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";import { describe, expect, it } from "vitest";+import { tempDir } from "./helpers/temp-dir";/*** Design a voice on your GPU: the Qwen3-TTS and VoxCPM2 graphs, their node packs pinned for the* GPU pre-flight, and what the ComfyUI provider binds (the voice in words, what a sample says, VoxCPM2's device).*/-process.env.FUOBE_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-voice-design-comfy-"));+process.env.FUOBE_DATA_DIR = tempDir("fuobe-voice-design-comfy-");process.env.COMFYUI_URL = "http://127.0.0.1:9";const root = path.resolve(__dirname, "..");diff --git a/tests/voice-design-server.test.ts b/tests/voice-design-server.test.tsindex 2ad430af..a97517ae 100644--- a/tests/voice-design-server.test.ts+++ b/tests/voice-design-server.test.ts@@ -1,7 +1,7 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { beforeAll, describe, expect, it } from "vitest";+import { tempDir } from "./helpers/temp-dir";/*** Design a voice on the server: an Element voice keeps the model, the words and the take's line; fal's@@ -10,7 +10,7 @@ import { afterAll, beforeAll, describe, expect, it } from "vitest";* fetch is stubbed and nothing reaches fal.*/-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-voice-design-"));+const dir = tempDir("fuobe-voice-design-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";@@ -34,9 +34,6 @@ beforeAll(() => {setSetting("demoMode", "off");setSetting("enhanceProvider", "none");});-afterAll(() => {- fs.rmSync(dir, { recursive: true, force: true });-});describe("Element voices keep a designed voice", () => {it("stores the model, the words and the line; a new clip drops the old clip's embedding", () => {diff --git a/tests/voice-first.test.ts b/tests/voice-first.test.tsindex ffa64830..dc13d203 100644--- a/tests/voice-first.test.ts+++ b/tests/voice-first.test.ts@@ -1,17 +1,17 @@import fs from "node:fs";-import os from "node:os";import path from "node:path";-import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";+import { afterEach, beforeAll, describe, expect, it } from "vitest";import { NextRequest } from "next/server";import { planVoiceFirst, voiceFirstCost, voiceFirstDefault, voiceFirstSource, wantsVoiceFirst, VOICE_FIRST_PARAM } from "@/lib/av/voice-first";import { transcribeRequest } from "@/lib/av/captions";import { planTranscribe } from "@/lib/catalog/swap-studio-plan";import type { GenerationRequest } from "@/lib/catalog/types";+import { tempDir } from "./helpers/temp-dir";// "Clean the voice first" (DBS D6): the speech apart from the music and effects before a transcriber or a lip sync hears// it (DBS on your GPU, ElevenLabs voice isolation in the cloud), and after a lip re-sync on your GPU the music and effects// of the same recording go back under it. The studio owner's until it has passed a real run.-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-voice-first-"));+const dir = tempDir("fuobe-voice-first-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";delete process.env.FUOBE_PASSWORD;@@ -28,11 +28,6 @@ beforeAll(() => setSetting("demoMode", "auto"));afterEach(() => {delete process.env.FUOBE_PUBLIC_SIGNUP;});-afterAll(() => {- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}-});const flag = { extra: { [VOICE_FIRST_PARAM]: true } };const clipUrl = () => saveFile({ data: fs.readFileSync(path.join(__dirname, "fixtures/shorts-12s.mp4")), contentType: "video/mp4", source: "upload", name: "talk.mp4" }).url;@@ -124,7 +119,7 @@ describe("runs (demo mode)", () => {describe("public sign-up: the studio owner's until it has passed a real run", () => {it("starts closed in this repository, and opens only with a validated graph and a passed run", () => {expect(soundLive()).toEqual({ "clean-voice-first": false, "original-sound": false });- const d = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-sound-live-"));+ const d = tempDir("fuobe-sound-live-");const files = (validated: boolean, passed: boolean) => {fs.writeFileSync(path.join(d, "m.json"), JSON.stringify({ workflows: [{ id: "separate-soundtrack-dbs", validated }] }));fs.writeFileSync(path.join(d, "r.json"), JSON.stringify({ features: { "clean-voice-first": { passed } } }));diff --git a/tests/webm.test.ts b/tests/webm.test.tsindex 94afa95c..0b8d8f71 100644--- a/tests/webm.test.ts+++ b/tests/webm.test.ts@@ -1,9 +1,9 @@import { execFileSync } from "node:child_process";import fs from "node:fs";-import os from "node:os";import path from "node:path";import { describe, expect, it } from "vitest";import { muxWebM, type EncodedFrame } from "@/lib/webm";+import { tempDir } from "./helpers/temp-dir";/** The WebM writer behind the browser's path render (N7-5): real VP8 frames in, a file ffmpeg reads frame for frame. */@@ -43,7 +43,7 @@ describe("muxWebM", () => {});it.skipIf(!has("ffmpeg") || !has("ffprobe"))("muxes real VP8 frames into a file ffmpeg decodes frame for frame at the given rate", () => {- const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-webm-"));+ const dir = tempDir("fuobe-webm-");try {const ivf = path.join(dir, "in.ivf");execFileSync("ffmpeg", ["-v", "error", "-f", "lavfi", "-i", "testsrc=size=96x64:rate=16", "-frames:v", "81", "-c:v", "libvpx", "-g", "30", "-f", "ivf", ivf]);diff --git a/tests/worker-program.test.ts b/tests/worker-program.test.tsindex 925646c7..6b290dd0 100644--- a/tests/worker-program.test.ts+++ b/tests/worker-program.test.ts@@ -1,6 +1,5 @@import fs from "node:fs";import net from "node:net";-import os from "node:os";import path from "node:path";import { describe, expect, it } from "vitest";import { GpuWatch, othersOf, parseApps, parseGpu } from "../bin/lib/worker/gpu.mjs";@@ -9,6 +8,7 @@ import { comfyArgs, OwnComfy, PortBusy, portFree } from "../bin/lib/worker/comfyimport { parseFor, syncedFolder } from "../bin/lib/worker/config.mjs";import { localPause } from "../bin/lib/worker/run.mjs";import { inventoryHash as workerHash } from "../bin/lib/worker/inventory.mjs";+import { tempDir } from "./helpers/temp-dir";const MIN = 60_000;const PORT = 3367;@@ -100,7 +100,7 @@ describe("its own ComfyUI (check 12)", () => {await new Promise<void>((r) => squatter.listen(PORT, "127.0.0.1", r));try {expect(await portFree(PORT)).toBe(false);- const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-worker-port-"));+ const dir = tempDir("fuobe-worker-port-");const c = new OwnComfy({ port: PORT, workDir: dir, comfyDir: dir, comfyCommand: [process.execPath, "-e", "setTimeout(()=>{},1e6)"] });await expect(c.start()).rejects.toBeInstanceOf(PortBusy);expect(c.alive()).toBe(false);@@ -120,7 +120,7 @@ describe("its own ComfyUI (check 12)", () => {describe("cleanup (check 13) and setup", () => {it("after a job, its files leave the worker folder and its history entry goes", async () => {- const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-worker-clean-"));+ const dir = tempDir("fuobe-worker-clean-");const f = { input: path.join(dir, "input"), output: path.join(dir, "output"), temp: path.join(dir, "temp") };for (const d of Object.values(f)) fs.mkdirSync(d, { recursive: true });fs.writeFileSync(path.join(f.input, "fuobe_abcdefgh12.png"), "x");diff --git a/tests/workers-pairing.test.ts b/tests/workers-pairing.test.tsindex dc1ef0cb..d4560eba 100644--- a/tests/workers-pairing.test.ts+++ b/tests/workers-pairing.test.ts@@ -1,12 +1,10 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";import { NextRequest } from "next/server";-import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+import { tempDir } from "./helpers/temp-dir";vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-workers-pairing-"));+const dir = tempDir("fuobe-workers-pairing-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://owner-comfy.test:8188";process.env.FUOBE_PUBLIC_SIGNUP = "1";@@ -58,11 +56,6 @@ beforeAll(() => {cookies.b = `${auth.SESSION_COOKIE}=${auth.createSession(b).value}`;cookies.owner = `${auth.SESSION_COOKIE}=${auth.createSession().value}`;});-afterAll(() => {- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}-});beforeEach(() => {resetRates();db().prepare("DELETE FROM relay_workers").run();diff --git a/tests/workers-pool.test.ts b/tests/workers-pool.test.tsindex 44ce31e3..28f67fd6 100644--- a/tests/workers-pool.test.ts+++ b/tests/workers-pool.test.ts@@ -1,13 +1,11 @@import crypto from "node:crypto";-import fs from "node:fs";-import os from "node:os";-import path from "node:path";import sharp from "sharp";-import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+import { tempDir } from "./helpers/temp-dir";vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-workers-pool-"));+const dir = tempDir("fuobe-workers-pool-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://owner-comfy.test:8188";delete process.env.FUOBE_PASSWORD;@@ -82,11 +80,6 @@ const everyDay = (from: string, to: string) => ({ tz: "UTC", days: Object.fromEnconst state = (id: string) => db().prepare("SELECT * FROM relay_tasks WHERE id = ?").get(id) as import("@/server/computer/tasks").TaskRow;beforeAll(() => setSetting("comfyWhere", "workers"));-afterAll(() => {- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}-});beforeEach(() => {resetRates();clock += 60 * MIN;diff --git a/tests/workflows-page-marks.test.ts b/tests/workflows-page-marks.test.tsindex 27e4fddd..6360f018 100644--- a/tests/workflows-page-marks.test.ts+++ b/tests/workflows-page-marks.test.ts@@ -1,13 +1,11 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { tempDir } from "./helpers/temp-dir";// GET /api/comfyui: the owner gets each graph's `validated` as it is; anyone else gets it on the graphs that passed.vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));-const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-workflow-marks-"));+const dir = tempDir("fuobe-workflow-marks-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.FUOBE_PUBLIC_SIGNUP = "1";@@ -30,9 +28,6 @@ beforeAll(() => {});afterAll(() => {globalThis.fetch = realFetch;- try {- fs.rmSync(dir, { recursive: true, force: true });- } catch {}});type Listed = { id: string; validated?: unknown };diff --git a/vitest.config.ts b/vitest.config.tsindex 0ad2cdf1..65c52a07 100644--- a/vitest.config.ts+++ b/vitest.config.ts@@ -11,6 +11,9 @@ export default defineConfig({test: {include: ["tests/**/*.test.ts"],environment: "node",+ // Every temp file of a run goes in one folder of its own, removed when the run ends (tests/setup/temp-root.ts).+ // Tests make their folders with tempDir() from tests/helpers/temp-dir.ts, which removes each after its file.+ globalSetup: ["tests/setup/temp-root.ts"],// Local LLM servers on this machine (LM Studio on :1234, Unsloth Studio on :8888) stay out of the// tests: Automatic would find them. Tests that need one start a stand-in and point Settings at it.// Hosted LLM keys from this machine's environment stay out too, so no test reaches a real provider: tests that need