A local-first multi-agent app development platform, built on PenguinHarness
test(server): share the project, Agent and model suites' apps (#932)
Yaowei Zheng9088ff9e3a8d
diff --git a/packages/server/test/agent-config-call-description.test.ts b/packages/server/test/agent-config-call-description.test.tsindex b4c4d46f..16439a85 100644--- a/packages/server/test/agent-config-call-description.test.ts+++ b/packages/server/test/agent-config-call-description.test.ts@@ -1,10 +1,12 @@/**- * Agent config route: the per-tool `call_description` field on toolsBuiltin rows. The- * default config writes `call_description: true` (plus the `description` property in- * parameters) on the four command/subagent tools; PUT round-trips a flipped `false` into- * system_config.yaml (preserving the rest of the file); a non-boolean value is a 400.+ * The Agent config route's per-tool `call_description` field on toolsBuiltin rows.+ *+ * - The defaults carry `call_description: true` (and the `description` parameter) on the four+ * command and subagent tools; a PUT of `false` round-trips into system_config.yaml, keeping+ * the rest of the file.+ * - A non-boolean value is a 400.*/-import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";import fs from "node:fs/promises";import { systemConfigPath } from "@prismshadow/penguin-core";import type { ToolDefinitionConfig } from "@prismshadow/penguin-core";@@ -18,21 +20,29 @@ describe("agent config: per-tool call_description", () => {let projectId: string;let configPath: string;- beforeEach(async () => {+ beforeAll(async () => {t = await createTestApp();const a = await provisionUser(t.app, "owner_cd");owner = apiClient(t.app, a.cookie);+ });+ afterAll(async () => {+ await t.cleanup();+ });++ // Every case works in a Project of its own.+ let projects = 0;+ beforeEach(async () => {+ projects += 1;const created = (await (- await owner.post("/api/projects", { projectId: "owner_cd-calldesc", name: "cd project" })+ await owner.post("/api/projects", {+ projectId: `owner_cd-calldesc_${projects}`,+ name: "cd project",+ })).json()) as ProjectCreateResponse;projectId = created.project.projectId;configPath = `/api/projects/${projectId}/agents/default_agent/config`;});- afterEach(async () => {- await t.cleanup();- });-it("defaults carry call_description: true and the description property; PUT false round-trips", async () => {const initial = (await (await owner.get(configPath)).json()) as AgentConfigResponse;const names = initial.config.toolsBuiltin.map((tool) => tool.name);diff --git a/packages/server/test/agent-config-mcp-servers.test.ts b/packages/server/test/agent-config-mcp-servers.test.tsindex 31c0f06a..976510b2 100644--- a/packages/server/test/agent-config-mcp-servers.test.ts+++ b/packages/server/test/agent-config-mcp-servers.test.ts@@ -1,10 +1,13 @@/**- * Agent config route: the `mcpServers` list. PUT round-trips valid entries into- * system_config.yaml; invalid entries are rejected with a precise 400 through the core- * transport resolver (single source of truth with the runtime), so a broken server config- * cannot be saved and silently skipped at the next Session start.+ * The Agent config route's `mcpServers` list.+ *+ * - A PUT round-trips valid stdio and http entries into system_config.yaml.+ * - An invalid entry is refused with a precise 400 from core's transport resolver (the runtime's+ * own), so a broken server config cannot be saved and silently skipped at the next Session.+ * - POST /config/mcp-test lists a reachable server's prefixed tools, reports an unreachable one+ * as ok:false with the connect failure, and refuses a malformed entry before connecting.*/-import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";import fs from "node:fs/promises";import { fileURLToPath } from "node:url";import { systemConfigPath } from "@prismshadow/penguin-core";@@ -18,21 +21,29 @@ describe("agent config: mcpServers", () => {let projectId: string;let configPath: string;- beforeEach(async () => {+ beforeAll(async () => {t = await createTestApp();const a = await provisionUser(t.app, "owner_mcp");owner = apiClient(t.app, a.cookie);+ });+ afterAll(async () => {+ await t.cleanup();+ });++ // Every case works in a Project of its own.+ let projects = 0;+ beforeEach(async () => {+ projects += 1;const created = (await (- await owner.post("/api/projects", { projectId: "owner_mcp-mcp", name: "mcp project" })+ await owner.post("/api/projects", {+ projectId: `owner_mcp-mcp_${projects}`,+ name: "mcp project",+ })).json()) as ProjectCreateResponse;projectId = created.project.projectId;configPath = `/api/projects/${projectId}/agents/default_agent/config`;});- afterEach(async () => {- await t.cleanup();- });-it("PUT round-trips valid stdio and http entries into the YAML", async () => {const servers = [{ name: "fs", config: { command: "npx", args: ["-y", "pkg"], env: { A: "1" } } },diff --git a/packages/server/test/agent-config-reset.test.ts b/packages/server/test/agent-config-reset.test.tsindex 88210fdb..b6b7da30 100644--- a/packages/server/test/agent-config-reset.test.ts+++ b/packages/server/test/agent-config-reset.test.ts@@ -1,10 +1,13 @@/**- * POST /api/projects/:projectId/agents/:agentId/config/reset — overwrites- * system_config.yaml with the current code defaults, keeping only the identity fields- * (name / description / version); the config-side analogue of a skill update. Same- * member-level authorization as PUT config; a non-member gets 404 without a write.+ * POST /api/projects/:projectId/agents/:agentId/config/reset — the config-side analogue of a+ * skill update.+ *+ * - It rewrites system_config.yaml with the current defaults, keeping only name, description+ * and version.+ * - A nonexistent Agent is a 404 with no initialization side effect; a non-member gets 404 and+ * the config is not touched.*/-import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";import { defaultSystemConfig } from "@prismshadow/penguin-core";import type { AgentConfigResponse, ProjectCreateResponse } from "../src/api/types.js";import { apiClient, createTestApp, provisionUser } from "./helpers.js";@@ -16,19 +19,28 @@ describe("POST agent config reset", () => {let projectId: string;const configUrl = () => `/api/projects/${projectId}/agents/default_agent/config`;- beforeEach(async () => {+ beforeAll(async () => {t = await createTestApp();const a = await provisionUser(t.app, "alice");alice = apiClient(t.app, a.cookie);+ });+ afterAll(async () => {+ await t.cleanup();+ });++ // Every case works in a Project of its own.+ let projects = 0;+ beforeEach(async () => {+ projects += 1;// Project ids are username-prefixed (`alice-…`), same as the other route tests.const created = (await (- await alice.post("/api/projects", { projectId: "alice-reset", name: "Reset project" })+ await alice.post("/api/projects", {+ projectId: `alice-reset_${projects}`,+ name: "Reset project",+ })).json()) as ProjectCreateResponse;projectId = created.project.projectId;});- afterEach(async () => {- await t.cleanup();- });it("restores the defaults while preserving name / description / version", async () => {// Customize everything the reset is supposed to overwrite, plus the kept fields.diff --git a/packages/server/test/agent-kernel-update.test.ts b/packages/server/test/agent-kernel-update.test.tsindex ca194c3e..b52ad0b4 100644--- a/packages/server/test/agent-kernel-update.test.ts+++ b/packages/server/test/agent-kernel-update.test.ts@@ -1,12 +1,15 @@/**- * POST /api/projects/:projectId/agents/:agentId/config/kernel-update — smart-merges- * system_config.yaml up to the current defaults generation: untouched old defaults advance,- * customizations are kept and reported, the config is stamped. Also covers the kernel fields- * of the config DTO and the agents-list kernelOutdated flag. Same member-level authorization- * as /reset; a non-member gets 404 without a write.+ * POST /api/projects/:projectId/agents/:agentId/config/kernel-update — the smart merge of+ * system_config.yaml up to the current defaults generation.+ *+ * - A fresh Agent reports stamped and current, in the config DTO and on the Agent list.+ * - A pre-stamp config is flagged outdated; the update advances untouched old defaults, keeps+ * and reports the customizations, and stamps the config.+ * - A nonexistent Agent is a 404 with no initialization side effect; a non-member gets 404 and+ * the config is not touched.*/import fs from "node:fs/promises";-import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";import { parse as parseYaml, stringify as stringifyYaml } from "yaml";import {KERNEL_VERSION,@@ -33,18 +36,27 @@ describe("POST agent config kernel-update", () => {let projectId: string;const configUrl = () => `/api/projects/${projectId}/agents/default_agent/config`;- beforeEach(async () => {+ beforeAll(async () => {t = await createTestApp();const a = await provisionUser(t.app, "alice");alice = apiClient(t.app, a.cookie);+ });+ afterAll(async () => {+ await t.cleanup();+ });++ // Every case works in a Project of its own.+ let projects = 0;+ beforeEach(async () => {+ projects += 1;const created = (await (- await alice.post("/api/projects", { projectId: "alice-kernel", name: "Kernel project" })+ await alice.post("/api/projects", {+ projectId: `alice-kernel_${projects}`,+ name: "Kernel project",+ })).json()) as ProjectCreateResponse;projectId = created.project.projectId;});- afterEach(async () => {- await t.cleanup();- });/*** Rewrites default_agent's config on disk into a pre-toggles-era shape with one userdiff --git a/packages/server/test/agent-transfer.test.ts b/packages/server/test/agent-transfer.test.tsindex 09a17291..460324ac 100644--- a/packages/server/test/agent-transfer.test.ts+++ b/packages/server/test/agent-transfer.test.ts@@ -1,13 +1,19 @@/**- * Agent State export/import integration tests: export auto-packages (excluding .vault.toml), any member can export, only the owner can- * import, importing the same or an older version requires confirmation (409 -> succeeds- * after confirm), import replaces agent_state while keeping the current vault, invalid- * packages return 400, and snapshots are written to snapshots/v<N>.tar.gz.+ * Agent State export and import.+ *+ * - Any member exports (auto-packaged, `.vault.toml` left out); only the owner imports.+ * - Re-importing the same or an older version needs confirmation (409, then success), replaces+ * agent_state and keeps the current vault; a newer package imports directly and records its+ * version; a `.vault.toml` inside a package is ignored; an invalid package is a 400.+ * - Snapshots are written to snapshots/v<N>.tar.gz; initializing and seeding one are mutually+ * exclusive.+ * - Creating an Agent from a package takes its state, name and version (explicit name and+ * description win); an invalid package fails the creation and leaves no Agent behind.*/import fs from "node:fs/promises";import path from "node:path";import * as tar from "tar";-import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";import { agentStateDir, snapshotsDir } from "@prismshadow/penguin-core";import type {AgentCreateResponse,@@ -26,14 +32,26 @@ describe("agent export/import", () => {let projectId: string;let base: string;- beforeEach(async () => {+ beforeAll(async () => {t = await createTestApp();const a = await provisionUser(t.app, "owner_a");const b = await provisionUser(t.app, "member_b");owner = apiClient(t.app, a.cookie);member = apiClient(t.app, b.cookie);+ });+ afterAll(async () => {+ await t.cleanup();+ });++ // Every case works in a Project of its own.+ let projects = 0;+ beforeEach(async () => {+ projects += 1;const created = (await (- await owner.post("/api/projects", { projectId: "owner_a-snap", name: "Snapshot project" })+ await owner.post("/api/projects", {+ projectId: `owner_a-snap_${projects}`,+ name: "Snapshot project",+ })).json()) as ProjectCreateResponse;projectId = created.project.projectId;base = `/api/projects/${projectId}/agents/default_agent`;@@ -41,9 +59,6 @@ describe("agent export/import", () => {(await owner.post(`/api/projects/${projectId}/members`, { userId: "member_b" })).status,).toBe(201);});- afterEach(async () => {- await t.cleanup();- });it("reimport same version: confirm required, agent_state replaced, vault kept", async () => {// First set a vault key (must be preserved after import).diff --git a/packages/server/test/benchmarks.test.ts b/packages/server/test/benchmarks.test.tsindex 84fc47a8..efa9ea48 100644--- a/packages/server/test/benchmarks.test.ts+++ b/packages/server/test/benchmarks.test.ts@@ -1,19 +1,23 @@/**- * Benchmark API integration tests: benchmark_config.toml title/description, runs and status- * pass-through (only a literal draft status locks a Benchmark; a directory without a config is- * not listed), scoreboard.yaml v2's- * evaluations[] (summary pass-through, the Agent each evaluation tested, model-written- * Case/Evaluation averages and per-case runs arrays), rejection of legacy Scoreboard entries,- * case count, empty when unconfigured, permissions (members can read, outsiders get 404), and- * the owner-only create (the on-disk layout the Skills read) and delete routes.+ * The Benchmark API.*- * Benchmarks are Project-level, so a new Project arrives with default_agent's sample- * Benchmark; setup deletes that one directory to isolate these cases, keeping `benchmarks/`- * itself. Its own assertions live in builtin-agents.test.ts.+ * - The list reads each benchmark_config.toml's title, description and status (only a literal+ * draft locks a Benchmark; draft and failed are themselves, anything else is published),+ * lists a Benchmark that never ran but not a directory without a config, and is empty when+ * nothing is configured.+ * - scoreboard.yaml v2's evaluations pass through: the summary, the Agent each tested, the+ * model-written Case and Evaluation averages and the per-case runs; legacy Scoreboard entries+ * are neither migrated nor backfilled; the case count is reported.+ * - Members read and outsiders get 404; only the owner creates (the server writes the layout+ * the Skills read, refusing malformed requests without writing) and deletes a Benchmark whole.+ *+ * Benchmarks are Project-level, so a new Project arrives with default_agent's sample Benchmark;+ * setup deletes that directory (keeping `benchmarks/`), and builtin-agents.test.ts owns its+ * assertions. One app for the file; every case works in a Project of its own.*/import fs from "node:fs/promises";import path from "node:path";-import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";import { parse as parseToml } from "smol-toml";import { benchmarksDir } from "@prismshadow/penguin-core";import type {@@ -39,7 +43,7 @@ describe("benchmarks api", () => {let projectId: string;let base: string;- beforeEach(async () => {+ beforeAll(async () => {t = await createTestApp();const a = await provisionUser(t.app, "owner_a");const b = await provisionUser(t.app, "member_b");@@ -47,8 +51,20 @@ describe("benchmarks api", () => {owner = apiClient(t.app, a.cookie);member = apiClient(t.app, b.cookie);outsider = apiClient(t.app, c.cookie);+ });+ afterAll(async () => {+ await t.cleanup();+ });++ // Every case works in a Project of its own.+ let projects = 0;+ beforeEach(async () => {+ projects += 1;const created = (await (- await owner.post("/api/projects", { projectId: "owner_a-bench", name: "Bench project" })+ await owner.post("/api/projects", {+ projectId: `owner_a-bench_${projects}`,+ name: "Bench project",+ })).json()) as ProjectCreateResponse;projectId = created.project.projectId;// Creating the Project seeded default_agent's sample Benchmark at the Project level; these@@ -63,9 +79,6 @@ describe("benchmarks api", () => {(await owner.post(`/api/projects/${projectId}/members`, { userId: "member_b" })).status,).toBe(201);});- afterEach(async () => {- await t.cleanup();- });it("returns an empty list when unconfigured", async () => {expect((await (await owner.get(base)).json()) as BenchmarksResponse).toEqual({diff --git a/packages/server/test/memory.test.ts b/packages/server/test/memory.test.tsindex 3c47d613..62da44f5 100644--- a/packages/server/test/memory.test.ts+++ b/packages/server/test/memory.test.ts@@ -1,17 +1,35 @@/**- * Integration tests for the Memory routes (agent_state/memory/): the overview reports the- * Agent-level switch and one entry per scope (user scope first), topic files can be listed /- * read / deleted, deleting a file prunes its index lines, path traversal in a scope key or- * file name is rejected, the switch round-trips through the Agent config without touching any- * file, and non-members see 404.+ * The Memory routes (agent_state/memory/).*- * A second suite covers whole-scope transfer: what an export carries, each branch of the import- * collision policy (skip / overwrite / replace, and when a confirmation is required), every- * rejection on that untrusted write path, and the owner gate on import.+ * Reading and curating:+ * - The overview reports the Agent-level switch and one entry per scope, the user scope first+ * (created on demand for an Agent that predates Memory; a Workspace key with no directory is+ * still a 404), accepting a key that starts with an underscore.+ * - Topic files are listed and read with their frontmatter (the `.workspace` marker and the+ * MEMORY.md index are not topic files, under any casing), a non-ASCII one included; deleting+ * one prunes its index lines and leaves the others; traversal, non-Markdown names, a symlinked+ * topic file or scope and an unknown Workspace are refused.+ * - The switch and the memory prompts round-trip through the Agent config without touching a+ * file; a template missing the {{MEMORY}} placeholder is reported and fixed on request; the+ * Agent list counts memories across scopes minus the indexes.+ * - A non-member gets 404 on every route.+ *+ * Moving a scope (export/import):+ * - An export carries every topic file and the index as one attachment (the user scope too, with+ * no workspace path) and imports into another scope.+ * - Import defaults to skip; overwrite and replace need confirmation that names what would be+ * lost, unless nothing would be; replace deletes what the document does not carry and prunes+ * the index.+ * - The untrusted document is checked whole before anything is written: a path-like name, a+ * non-text entry, absurd counts or sizes, a foreign or future format; no temporary file stays.+ * - Any member exports, only the owner imports, and a non-member learns nothing.+ *+ * One app for the file and one Project per describe; every case works in a plain Agent of its+ * own.*/import fs from "node:fs/promises";import path from "node:path";-import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";import {MEMORY_INDEX_FILENAME,USER_SCOPE_KEY,@@ -48,37 +66,53 @@ updated_at: 2026-08-07- Integration tests talk to a real database.`;+/** The file's app and its three users; each describe below works in a Project of its own. */+let t: TestApp;+let owner: ReturnType<typeof apiClient>;+let member: ReturnType<typeof apiClient>;+let outsider: ReturnType<typeof apiClient>;++beforeAll(async () => {+ t = await createTestApp();+ const a = await provisionUser(t.app, "owner_a");+ const b = await provisionUser(t.app, "member_b");+ const c = await provisionUser(t.app, "outsider_c");+ owner = apiClient(t.app, a.cookie);+ member = apiClient(t.app, b.cookie);+ outsider = apiClient(t.app, c.cookie);+});+afterAll(async () => {+ await t.cleanup();+});+describe("memory api", () => {- let t: TestApp;- let owner: ReturnType<typeof apiClient>;- let outsider: ReturnType<typeof apiClient>;let projectId: string;let memoryPath: string;let configPath: string;/** The Workspace Memory directory a Session would have created. */let wsDir: string;- beforeEach(async () => {- t = await createTestApp();- const a = await provisionUser(t.app, "owner_a");- const c = await provisionUser(t.app, "outsider_c");- owner = apiClient(t.app, a.cookie);- outsider = apiClient(t.app, c.cookie);+ // Every case reads and writes the Memory of a plain Agent of its own, in the one Project.+ let agentId: string;+ let agents = 0;+ beforeAll(async () => {const created = (await (await owner.post("/api/projects", { projectId: "owner_a-memory", name: "memory project" })).json()) as ProjectCreateResponse;projectId = created.project.projectId;- memoryPath = `/api/projects/${projectId}/agents/default_agent/memory`;- configPath = `/api/projects/${projectId}/agents/default_agent/config`;- wsDir = memoryScopeDir(t.root, projectId, "default_agent", WORKSPACE_KEY);+ });+ beforeEach(async () => {+ agents += 1;+ agentId = `memory_${agents}`;+ const made = await owner.post(`/api/projects/${projectId}/agents`, { agentId });+ expect(made.status, await made.text()).toBe(201);+ memoryPath = `/api/projects/${projectId}/agents/${agentId}/memory`;+ configPath = `/api/projects/${projectId}/agents/${agentId}/config`;+ wsDir = memoryScopeDir(t.root, projectId, agentId, WORKSPACE_KEY);await fs.mkdir(wsDir, { recursive: true });await fs.writeFile(path.join(wsDir, ".workspace"), "/home/dev/my-app\n", "utf8");});- afterEach(async () => {- await t.cleanup();- });-const filesPath = (key = WORKSPACE_KEY) => `${memoryPath}/scopes/${key}/files`;it("overview reports the switch, the user scope, and one entry per Workspace", async () => {@@ -88,9 +122,9 @@ describe("memory api", () => {expect(body.enabled).toBe(true);// A freshly created Agent gets the current default template, which carries {{MEMORY}}.expect(body.templateHasMemory).toBe(true);- expect(body.memoryDir).toBe(memoryDir(t.root, projectId, "default_agent"));+ expect(body.memoryDir).toBe(memoryDir(t.root, projectId, agentId));expect(body.scopes).toHaveLength(2);- // The user scope leads the list (default_agent was initialized with it on disk).+ // The user scope leads the list (the Agent was initialized with it on disk).expect(body.scopes[0]).toMatchObject({scopeKey: USER_SCOPE_KEY,kind: "user",@@ -120,7 +154,7 @@ describe("memory api", () => {it("accepts a workspace key starting with an underscore, as core generates for _site-style directories", async () => {const key = "_site-1a2b3c4d";- const dir = memoryScopeDir(t.root, projectId, "default_agent", key);+ const dir = memoryScopeDir(t.root, projectId, agentId, key);await fs.mkdir(dir, { recursive: true });await fs.writeFile(path.join(dir, "notes.md"), "---\nname: n\n---\nbody\n", "utf8");const list = (await (await owner.get(filesPath(key))).json()) as MemoryFilesResponse;@@ -139,7 +173,7 @@ describe("memory api", () => {});itWithSymlinks("neither lists nor follows a symlinked topic file", async () => {- const outside = path.join(t.root, "outside-secret.txt");+ const outside = path.join(t.root, `${agentId}-outside-secret.txt`);await fs.writeFile(outside, "secret", "utf8");await fs.symlink(outside, path.join(wsDir, "leak.md"));const list = (await (await owner.get(filesPath())).json()) as MemoryFilesResponse;@@ -149,23 +183,23 @@ describe("memory api", () => {});itWithSymlinks("404s a scope directory smuggled in as a symlink", async () => {- const outside = path.join(t.root, "outside-dir");+ const outside = path.join(t.root, `${agentId}-outside-dir`);await fs.mkdir(outside, { recursive: true });await fs.writeFile(path.join(outside, "loot.md"), "---\nname: l\n---\nx\n", "utf8");- await fs.symlink(outside, memoryScopeDir(t.root, projectId, "default_agent", "evil-12345678"));+ await fs.symlink(outside, memoryScopeDir(t.root, projectId, agentId, "evil-12345678"));expect((await owner.get(filesPath("evil-12345678"))).status).toBe(404);});it("lists the user scope of an Agent that predates Memory, creating it on demand", async () => {// A Workspace directory comes from a Session, but the user scope belongs to the Agent.- await fs.rm(memoryScopeDir(t.root, projectId, "default_agent", USER_SCOPE_KEY), {+ await fs.rm(memoryScopeDir(t.root, projectId, agentId, USER_SCOPE_KEY), {recursive: true,force: true,});const list = (await (await owner.get(filesPath(USER_SCOPE_KEY))).json()) as MemoryFilesResponse;expect(list.files).toHaveLength(0);await expect(- fs.stat(memoryScopeDir(t.root, projectId, "default_agent", USER_SCOPE_KEY)),+ fs.stat(memoryScopeDir(t.root, projectId, agentId, USER_SCOPE_KEY)),).resolves.toBeTruthy();});@@ -290,14 +324,14 @@ describe("memory api", () => {it("reports the memory count on the Agent list, summed across scopes minus the indexes", async () => {await fs.writeFile(path.join(wsDir, "testing-conventions.md"), TOPIC, "utf8");await fs.writeFile(path.join(wsDir, MEMORY_INDEX_FILENAME), "- [t](t.md) — hook\n", "utf8");- const userDir = memoryScopeDir(t.root, projectId, "default_agent", USER_SCOPE_KEY);+ const userDir = memoryScopeDir(t.root, projectId, agentId, USER_SCOPE_KEY);await fs.mkdir(userDir, { recursive: true });await fs.writeFile(path.join(userDir, "prefers-pnpm.md"), "---\nname: p\n---\nx\n", "utf8");const body = (await (await owner.get(`/api/projects/${projectId}/agents`)).json()) as {agents: { agentId: string; memoryCount: number }[];};- const agent = body.agents.find((a) => a.agentId === "default_agent");+ const agent = body.agents.find((a) => a.agentId === agentId);expect(agent?.memoryCount).toBe(2);});@@ -311,22 +345,14 @@ describe("memory api", () => {});describe("memory scope export/import", () => {- let t: TestApp;- let owner: ReturnType<typeof apiClient>;- let member: ReturnType<typeof apiClient>;- let outsider: ReturnType<typeof apiClient>;let projectId: string;let memoryPath: string;let wsDir: string;- beforeEach(async () => {- t = await createTestApp();- const a = await provisionUser(t.app, "owner_a");- const b = await provisionUser(t.app, "member_b");- const c = await provisionUser(t.app, "outsider_c");- owner = apiClient(t.app, a.cookie);- member = apiClient(t.app, b.cookie);- outsider = apiClient(t.app, c.cookie);+ // Every case moves memories in and out of a plain Agent of its own, in the one Project.+ let agentId: string;+ let agents = 0;+ beforeAll(async () => {const created = (await (await owner.post("/api/projects", { projectId: "owner_a-transfer", name: "transfer" })).json()) as ProjectCreateResponse;@@ -334,16 +360,18 @@ describe("memory scope export/import", () => {expect((await owner.post(`/api/projects/${projectId}/members`, { userId: "member_b" })).status,).toBe(201);- memoryPath = `/api/projects/${projectId}/agents/default_agent/memory`;- wsDir = memoryScopeDir(t.root, projectId, "default_agent", WORKSPACE_KEY);+ });+ beforeEach(async () => {+ agents += 1;+ agentId = `transfer_${agents}`;+ const made = await owner.post(`/api/projects/${projectId}/agents`, { agentId });+ expect(made.status, await made.text()).toBe(201);+ memoryPath = `/api/projects/${projectId}/agents/${agentId}/memory`;+ wsDir = memoryScopeDir(t.root, projectId, agentId, WORKSPACE_KEY);await fs.mkdir(wsDir, { recursive: true });await fs.writeFile(path.join(wsDir, ".workspace"), "/home/dev/my-app\n", "utf8");});- afterEach(async () => {- await t.cleanup();- });-const exportPath = (key = WORKSPACE_KEY) => `${memoryPath}/scopes/${key}/export`;const importPath = (key = WORKSPACE_KEY) => `${memoryPath}/scopes/${key}/import`;@@ -392,7 +420,7 @@ describe("memory scope export/import", () => {const res = await owner.get(exportPath());expect(res.status).toBe(200);expect(res.headers.get("content-disposition")).toMatch(- new RegExp(`filename="default_agent-${WORKSPACE_KEY}-memory-\\d{8}-\\d{4}\\.json"`),+ new RegExp(`filename="${agentId}-${WORKSPACE_KEY}-memory-\\d{8}-\\d{4}\\.json"`),);const doc = (await res.json()) as MemoryScopeExport;expect(doc.format).toBe("penguin-memory-scope");@@ -432,7 +460,7 @@ describe("memory scope export/import", () => {added: ["testing-conventions.md"],indexWritten: true,});- const userDir = memoryScopeDir(t.root, projectId, "default_agent", USER_SCOPE_KEY);+ const userDir = memoryScopeDir(t.root, projectId, agentId, USER_SCOPE_KEY);expect(await fs.readFile(path.join(userDir, "testing-conventions.md"), "utf8")).toBe(TOPIC);expect(await fs.readFile(path.join(userDir, MEMORY_INDEX_FILENAME), "utf8")).toBe("- [T](testing-conventions.md)\n",@@ -563,7 +591,7 @@ describe("memory scope export/import", () => {};it("rejects a name that is a path, climbs out, or is not a topic file", async () => {- const outside = path.join(t.root, "outside-target.md");+ const outside = path.join(t.root, `${agentId}-outside-target.md`);await rejects([topic("../escape.md", "x")], "parent traversal");await rejects([topic("..\\escape.md", "x")], "windows traversal");await rejects([topic("sub/notes.md", "x")], "nested path");@@ -629,7 +657,7 @@ describe("memory scope export/import", () => {itWithSymlinks("replaces a symlink standing at a memory's name instead of writing through it",async () => {- const outside = path.join(t.root, "outside-secret.md");+ const outside = path.join(t.root, `${agentId}-outside-secret.md`);await fs.writeFile(outside, "secret\n", "utf8");await fs.symlink(outside, path.join(wsDir, "leak.md"));@@ -659,12 +687,9 @@ describe("memory scope export/import", () => {expect((await owner.get(exportPath("never-run-0badc0de"))).status).toBe(404);expect((await runImport(document([]), { key: "never-run-0badc0de" })).status).toBe(404);- const outside = path.join(t.root, "outside-dir");+ const outside = path.join(t.root, `${agentId}-outside-dir`);await fs.mkdir(outside, { recursive: true });- await fs.symlink(- outside,- memoryScopeDir(t.root, projectId, "default_agent", "evil-12345678"),- );+ await fs.symlink(outside, memoryScopeDir(t.root, projectId, agentId, "evil-12345678"));expect((await owner.get(exportPath("evil-12345678"))).status).toBe(404);expect((await runImport(document([topic("a.md", "x")]), { key: "evil-12345678" })).status,diff --git a/packages/server/test/model-oauth.test.ts b/packages/server/test/model-oauth.test.tsindex 2d942be4..25331306 100644--- a/packages/server/test/model-oauth.test.ts+++ b/packages/server/test/model-oauth.test.ts@@ -1,18 +1,30 @@/**- * Provider key-minting flow: PKCE derivation, authorize-URL construction, the flow store's- * expiry and single-use rules, the exchange's error mapping, and the routes end to end —- * owner-only, key written to every model of the group, `credentials_updated` published.+ * Provider key minting (the OAuth-style flow a catalog group declares).*- * The redirect receiver is the one route of the group that answers without a session, and- * the last describe covers exactly that: what the flow id alone buys, and — case by case —- * what it still does not.+ * - PKCE: the challenge is the unpadded base64url SHA-256 of a fresh, in-window verifier; the+ * authorize URL carries the callback, the harness's own app URL and the key name, encoded,+ * and manual mode omits the callback but still pins S256.+ * - The exchange posts code, verifier and method as JSON and returns the key; a 400, a 403, any+ * other failure, a 200 without a usable key and an unreachable endpoint each map to their own+ * reason, never carrying the request's detail.+ * - A flow belongs to one user in one Project, expires after ten minutes and is single use; a+ * failed exchange or an unstorable key ends it with its reason. A redirect deposits the code+ * once (a manual flow takes none) and only the owner's poll redeems it; an unpolled deposit+ * expires with the flow. The callback origin follows the request unless a proxy is trusted.+ * - The routes: only the owner starts, polls and redeems; the key lands on every model of the+ * group and the Project's open Session channels hear credentials_updated; a rejected code+ * reaches the dialog through the poll and touches no model; a malformed link answers a page.+ * - The redirect receiver answers without a session: the flow id buys a deposit and nothing+ * more — not for another user, an unknown flow, another Project, a stale or replayed flow,+ * a HEAD, or a manual flow — and the exemption covers exactly its literal path.*- * No test reaches the network: `exchangeCode` takes its fetch as an argument, and the route- * cases stub the global one.+ * No test reaches the network: the exchange endpoint is the suite's fetch fake, handed to+ * `exchangeCode` and the service, and standing in for the global fetch in the route cases. The+ * route describes share one app, every case in a Project of its own.*/import { readFile } from "node:fs/promises";import path from "node:path";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";import { APP_URL, presetModelEntries, providerInfo } from "@prismshadow/penguin-core/model-catalog";import type {ModelOAuthCodeResponse,@@ -32,6 +44,9 @@ import {ModelOAuthService,} from "../src/services/model-oauth-service.js";import { requestOrigin } from "../src/http/routes/model-oauth.js";+import { fakeFetch, jsonResponse, stubFetch } from "./fixtures/fetch.js";+import type { FetchFake } from "./fixtures/fetch.js";+import { sessionRow } from "./fixtures/session.js";import { apiClient, createTestApp, provisionUser } from "./helpers.js";import type { TestApp } from "./helpers.js";import { wire } from "@prismshadow/penguin-core/kernel";@@ -45,14 +60,6 @@ const TOKENDANCE = providerInfo("tokendance")!;*/const TOKENDANCE_MODELS = presetModelEntries().filter((m) => m.provider === "tokendance").length;-/** A JSON reply from the exchange endpoint, without touching the network. */-function jsonResponse(status: number, body: unknown): Response {- return new Response(JSON.stringify(body), {- status,- headers: { "content-type": "application/json" },- });-}-describe("PKCE derivation", () => {it("challenge is the unpadded base64url SHA-256 of the verifier (RFC 7636 vector)", () => {expect(codeChallenge("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk")).toBe(@@ -126,15 +133,11 @@ describe("code exchange", () => {});it("posts the code, the verifier and the method as JSON, and returns the minted key", async () => {- const seen: { url: string; body: unknown } = { url: "", body: null };- const res = await call((async (url: string, init: RequestInit) => {- seen.url = url;- seen.body = JSON.parse(String(init.body));- return jsonResponse(200, { key: "sk-minted" });- }) as unknown as typeof fetch);+ const exchange = fakeFetch(() => jsonResponse({ key: "sk-minted" }));+ const res = await call(exchange.fetch);expect(res).toEqual({ ok: true, key: "sk-minted" });- expect(seen.url).toBe(TOKENDANCE.oauth!.exchangeUrl);- expect(seen.body).toEqual({+ expect(exchange.calls.map((c) => c.url)).toEqual([TOKENDANCE.oauth!.exchangeUrl]);+ expect(JSON.parse(exchange.calls[0]!.body)).toEqual({code: "the-code",code_verifier: "the-verifier",code_challenge_method: "S256",@@ -143,31 +146,31 @@ describe("code exchange", () => {it("400 is a malformed authorization request; 403 is a rejected code", async () => {const fail = (status: number) =>- call((async () => jsonResponse(status, { error: "no" })) as unknown as typeof fetch);+ call(fakeFetch(() => jsonResponse({ error: "no" }, status)).fetch);expect(await fail(400)).toEqual({ ok: false, error: "invalid_request" });expect(await fail(403)).toEqual({ ok: false, error: "code_rejected" });expect(await fail(500)).toEqual({ ok: false, error: "upstream_failed" });});it("a 200 without a usable key is a failure, not a key", async () => {- expect(- await call((async () => jsonResponse(200, { key: "" })) as unknown as typeof fetch),- ).toEqual({ ok: false, error: "upstream_failed" });- expect(await call((async () => jsonResponse(200, {})) as unknown as typeof fetch)).toEqual({+ const answered = (response: Response) => call(fakeFetch(() => response).fetch);+ expect(await answered(jsonResponse({ key: "" }))).toEqual({+ ok: false,+ error: "upstream_failed",+ });+ expect(await answered(jsonResponse({}))).toEqual({ ok: false, error: "upstream_failed" });+ expect(await answered(new Response("not json", { status: 200 }))).toEqual({ok: false,error: "upstream_failed",});- expect(- await call(- (async () => new Response("not json", { status: 200 })) as unknown as typeof fetch,- ),- ).toEqual({ ok: false, error: "upstream_failed" });});it("a transport failure reports unreachable and carries no detail (the request holds the code)", async () => {- const res = await call((async () => {- throw new Error("connect ECONNREFUSED sk-leak");- }) as unknown as typeof fetch);+ const res = await call(+ fakeFetch(() => {+ throw new Error("connect ECONNREFUSED sk-leak");+ }).fetch,+ );expect(res).toEqual({ ok: false, error: "unreachable" });expect(JSON.stringify(res)).not.toContain("sk-leak");});@@ -176,8 +179,11 @@ describe("code exchange", () => {describe("flow store", () => {let clock: number;let applied: { projectId: string; provider: string; apiKey: string }[];- /** Codes the stub exchange was asked to redeem, in order. */- let exchanged: string[];+ /** The provider's exchange endpoint. */+ let exchange: FetchFake;+ /** Codes the exchange endpoint was asked to redeem, in order. */+ const exchanged = () =>+ exchange.calls.map((call) => (JSON.parse(call.body) as { code: string }).code);let service: ModelOAuthService;const start = () =>@@ -192,16 +198,13 @@ describe("flow store", () => {beforeEach(() => {clock = 1_700_000_000_000;applied = [];- exchanged = [];+ exchange = fakeFetch(() => jsonResponse({ key: "sk-minted" }));service = wire(ModelOAuthService, {applyGroupKey: async (projectId: string, provider: string, apiKey: string) => {applied.push({ projectId, provider, apiKey });return 6;},- fetchImpl: (async (_url: string, init: RequestInit) => {- exchanged.push((JSON.parse(String(init.body)) as { code: string }).code);- return jsonResponse(200, { key: "sk-minted" });- }) as unknown as typeof fetch,+ fetchImpl: exchange.fetch,now: () => clock,});});@@ -273,7 +276,7 @@ describe("flow store", () => {it("a failed exchange ends the flow and reports the mapped reason", async () => {service = wire(ModelOAuthService, {applyGroupKey: async () => 6,- fetchImpl: (async () => jsonResponse(403, {})) as unknown as typeof fetch,+ fetchImpl: fakeFetch(() => jsonResponse({}, 403)).fetch,now: () => clock,});const { flowId } = start();@@ -290,7 +293,7 @@ describe("flow store", () => {applyGroupKey: async () => {throw new Error("disk full");},- fetchImpl: (async () => jsonResponse(200, { key: "sk-minted" })) as unknown as typeof fetch,+ fetchImpl: fakeFetch(() => jsonResponse({ key: "sk-minted" })).fetch,now: () => clock,});const { flowId } = start();@@ -331,10 +334,10 @@ describe("flow store", () => {service.deposit({ flowId, projectId: "p1", code: "first" });expect(() => service.deposit({ flowId, projectId: "p1", code: "second" })).toThrow(HttpError);expect((await service.poll({ flowId, userId: "u1", projectId: "p1" })).status).toBe("done");- expect(exchanged).toEqual(["first"]);+ expect(exchanged()).toEqual(["first"]);// And once redeemed there is nothing left to deposit into either.expect(() => service.deposit({ flowId, projectId: "p1", code: "third" })).toThrow(HttpError);- expect(exchanged).toEqual(["first"]);+ expect(exchanged()).toEqual(["first"]);});it("a deposited code that nobody polls for expires with the flow", async () => {@@ -344,7 +347,7 @@ describe("flow store", () => {await expect(service.poll({ flowId, userId: "u1", projectId: "p1" })).rejects.toThrow(HttpError,);- expect(exchanged).toEqual([]);+ expect(exchanged()).toEqual([]);expect(applied).toEqual([]);});});@@ -373,41 +376,53 @@ describe("callback origin", () => {});});+/** The route describes' app and the owner of every Project in it. */+let t: TestApp;+let owner: ReturnType<typeof apiClient>;++beforeAll(async () => {+ t = await createTestApp();+ owner = apiClient(t.app, (await provisionUser(t.app, "owner_o")).cookie);+});+afterAll(async () => {+ await t.cleanup();+});+describe("model-oauth routes", () => {- let t: TestApp;- let owner: ReturnType<typeof apiClient>;let member: ReturnType<typeof apiClient>;let projectId: string;- let exchanges: { url: string; body: Record<string, unknown> }[];+ /** The provider's exchange endpoint, standing in for the global fetch. */+ let exchange: FetchFake;+ const exchanges = () =>+ exchange.calls.map((call) => ({+ url: call.url,+ body: JSON.parse(call.body) as Record<string, unknown>,+ }));const base = () => `/api/projects/${projectId}/model-oauth`;+ beforeAll(async () => {+ member = apiClient(t.app, (await provisionUser(t.app, "member_m")).cookie);+ });++ // Every case runs its flows against a Project of its own.+ let projects = 0;beforeEach(async () => {- t = await createTestApp();- const a = await provisionUser(t.app, "owner_o");- const b = await provisionUser(t.app, "member_m");- owner = apiClient(t.app, a.cookie);- member = apiClient(t.app, b.cookie);+ projects += 1;const created = (await (- await owner.post("/api/projects", { projectId: "owner_o-td", name: "TokenDance project" })+ await owner.post("/api/projects", {+ projectId: `owner_o-td_${projects}`,+ name: "TokenDance project",+ })).json()) as ProjectCreateResponse;projectId = created.project.projectId;expect((await owner.post(`/api/projects/${projectId}/members`, { userId: "member_m" })).status,).toBe(201);-- exchanges = [];- vi.stubGlobal(- "fetch",- vi.fn(async (url: string, init: RequestInit) => {- exchanges.push({ url, body: JSON.parse(String(init.body)) as Record<string, unknown> });- return jsonResponse(200, { key: "sk-oauth-minted-key-9911" });- }),- );+ exchange = stubFetch(() => jsonResponse({ key: "sk-oauth-minted-key-9911" }));});- afterEach(async () => {+ afterEach(() => {vi.unstubAllGlobals();- await t.cleanup();});it("owner starts a flow; a member cannot, and neither can start one for a group with no flow", async () => {@@ -432,18 +447,7 @@ describe("model-oauth routes", () => {).json()) as ModelOAuthStartResponse;// A subscribed tab of this Project must be told the credentials changed.- t.deps.sessionsRepo.insert({- sessionId: "td-live",- projectId,- agentId: "default_agent",- modelId: "m1",- provider: "custom",- workspace: t.root,- approvalMode: "allow-all",- title: null,- createdAt: new Date().toISOString(),- lastActiveAt: new Date().toISOString(),- });+ t.deps.sessionsRepo.insert(sessionRow("td-live", { projectId, workspace: t.root }));const events: ChannelEvent[] = [];t.deps.channels.get("td-live").subscribe((e) => events.push(e));@@ -459,7 +463,7 @@ describe("model-oauth routes", () => {expect(page).not.toContain("auth-code-1");expect(page).not.toContain("http://");// The receiver only wrote the code onto the flow: no provider was called yet.- expect(exchanges).toHaveLength(0);+ expect(exchanges()).toHaveLength(0);// The owner's poll is what redeems it, and it reports the finished flow in the same tick.const status = (await (@@ -468,12 +472,12 @@ describe("model-oauth routes", () => {expect(status).toEqual({ status: "done", provider: "tokendance", applied: TOKENDANCE_MODELS });// The exchange spoke the documented protocol, with a verifier this side never published.- expect(exchanges).toHaveLength(1);- expect(exchanges[0]!.url).toBe(TOKENDANCE.oauth!.exchangeUrl);- expect(exchanges[0]!.body.code).toBe("auth-code-1");- expect(exchanges[0]!.body.code_challenge_method).toBe("S256");- expect(String(exchanges[0]!.body.code_verifier)).toMatch(/^[A-Za-z0-9._~-]{43,128}$/);- expect(started.authorizeUrl).not.toContain(String(exchanges[0]!.body.code_verifier));+ expect(exchanges()).toHaveLength(1);+ expect(exchanges()[0]!.url).toBe(TOKENDANCE.oauth!.exchangeUrl);+ expect(exchanges()[0]!.body.code).toBe("auth-code-1");+ expect(exchanges()[0]!.body.code_challenge_method).toBe("S256");+ expect(String(exchanges()[0]!.body.code_verifier)).toMatch(/^[A-Za-z0-9._~-]{43,128}$/);+ expect(started.authorizeUrl).not.toContain(String(exchanges()[0]!.body.code_verifier));const models = (await (await owner.get(`/api/projects/${projectId}/models`)@@ -513,14 +517,11 @@ describe("model-oauth routes", () => {`${base()}/callback?flow=${encodeURIComponent(started.flowId)}&code=auth-code-1`,);expect(replay.status).toBe(400);- expect(exchanges).toHaveLength(1);+ expect(exchanges()).toHaveLength(1);});it("a rejected code leaves the flow in error, reaches the dialog through the poll, and never touches the models", async () => {- vi.stubGlobal(- "fetch",- vi.fn(async () => jsonResponse(403, { error: "invalid_code" })),- );+ exchange = stubFetch(() => jsonResponse({ error: "invalid_code" }, 403));const started = (await (await owner.post(`${base()}/start`, { provider: "tokendance" })).json()) as ModelOAuthStartResponse;@@ -550,7 +551,7 @@ describe("model-oauth routes", () => {expect(res.status).toBe(400);expect(res.headers.get("content-type")).toContain("text/html");expect(await res.text()).toContain("Authorization failed");- expect(exchanges).toHaveLength(0);+ expect(exchanges()).toHaveLength(0);});it("manual mode drops the callback and redeems a pasted code instead", async () => {@@ -564,7 +565,7 @@ describe("model-oauth routes", () => {const body = (await res.json()) as ModelOAuthCodeResponse;expect(body.ok).toBe(true);expect(body.applied).toBeGreaterThan(0);- expect(exchanges[0]!.body.code).toBe("pasted-code");+ expect(exchanges()[0]!.body.code).toBe("pasted-code");// Single use here too.const again = await owner.post(`${base()}/${started.flowId}/code`, { code: "pasted-code" });@@ -600,13 +601,12 @@ describe("model-oauth routes", () => {* asserted with NO cookie unless the case is specifically about a signed-in browser.*/describe("model-oauth callback without a session", () => {- let t: TestApp;- let owner: ReturnType<typeof apiClient>;/** A signed-in member of the flow's Project who is not its owner — the closest anyone gets. */let stranger: ReturnType<typeof apiClient>;let projectId: string;let otherProjectId: string;- let exchanges: number;+ /** The provider's exchange endpoint, standing in for the global fetch. */+ let exchange: FetchFake;const base = (p = projectId) => `/api/projects/${p}/model-oauth`;/** The system browser the provider redirected: a request carrying no cookie at all. */@@ -634,37 +634,33 @@ describe("model-oauth callback without a session", () => {);};+ /** A Project of the owner's. */+ const create = async (id: string): Promise<string> =>+ (+ (await (+ await owner.post("/api/projects", { projectId: id, name: id })+ ).json()) as ProjectCreateResponse+ ).project.projectId;++ // The stranger, and another Project the owner also holds (a flow presented under it stores+ // nothing there, which no case changes), are the describe's; the flow's Project is per case.+ beforeAll(async () => {+ stranger = apiClient(t.app, (await provisionUser(t.app, "stranger_s")).cookie);+ otherProjectId = await create("owner_o-other");+ });++ let projects = 0;beforeEach(async () => {- t = await createTestApp();- const a = await provisionUser(t.app, "owner_o");- owner = apiClient(t.app, a.cookie);- const b = await provisionUser(t.app, "stranger_s");- stranger = apiClient(t.app, b.cookie);- const create = async (id: string): Promise<string> =>- (- (await (- await owner.post("/api/projects", { projectId: id, name: id })- ).json()) as ProjectCreateResponse- ).project.projectId;- projectId = await create("owner_o-td");- otherProjectId = await create("owner_o-td2");+ projects += 1;+ projectId = await create(`owner_o-cb_${projects}`);expect((await owner.post(`/api/projects/${projectId}/members`, { userId: "stranger_s" })).status,).toBe(201);-- exchanges = 0;- vi.stubGlobal(- "fetch",- vi.fn(async () => {- exchanges += 1;- return jsonResponse(200, { key: "sk-oauth-minted-key-9911" });- }),- );+ exchange = stubFetch(() => jsonResponse({ key: "sk-oauth-minted-key-9911" }));});- afterEach(async () => {+ afterEach(() => {vi.unstubAllGlobals();vi.restoreAllMocks();- await t.cleanup();});it("takes the code from the system browser, which carries no cookie, and writes nothing until the owner polls", async () => {@@ -680,7 +676,7 @@ describe("model-oauth callback without a session", () => {expect(page).not.toContain("auth-code-1");// Nothing was redeemed and nothing was stored: the route has no such authority.- expect(exchanges).toBe(0);+ expect(exchange.calls).toHaveLength(0);expect(await groupHasKey()).toBe(false);// The owner's own poll is what spends the code and lands the key.@@ -689,7 +685,7 @@ describe("model-oauth callback without a session", () => {provider: "tokendance",applied: TOKENDANCE_MODELS,});- expect(exchanges).toBe(1);+ expect(exchange.calls).toHaveLength(1);expect(await groupHasKey()).toBe(true);});@@ -705,7 +701,7 @@ describe("model-oauth callback without a session", () => {provider: "tokendance",applied: TOKENDANCE_MODELS,});- expect(exchanges).toBe(1);+ expect(exchange.calls).toHaveLength(1);expect(await groupHasKey()).toBe(true);});@@ -716,7 +712,7 @@ describe("model-oauth callback without a session", () => {// And that is the end of what it buys them: they cannot poll the flow, so they cannot// make the code they deposited become a key in someone else's Project.expect((await stranger.get(`${base()}/${flowId}`)).status).toBe(403);- expect(exchanges).toBe(0);+ expect(exchange.calls).toHaveLength(0);expect(await groupHasKey()).toBe(false);// Only the owner's poll spends it.expect((await poll(flowId)).status).toBe("done");@@ -728,7 +724,7 @@ describe("model-oauth callback without a session", () => {expect(res.status).toBe(400);// The same page an expired or foreign flow gets: a flow id is not a probe for what exists.expect(await res.text()).toContain("Authorization failed");- expect(exchanges).toBe(0);+ expect(exchange.calls).toHaveLength(0);expect(await groupHasKey()).toBe(false);});@@ -736,7 +732,7 @@ describe("model-oauth callback without a session", () => {const flowId = await startFlow();const res = await noSession(callback(flowId, "auth-code-1", otherProjectId));expect(res.status).toBe(400);- expect(exchanges).toBe(0);+ expect(exchange.calls).toHaveLength(0);expect(await groupHasKey(otherProjectId)).toBe(false);// And the flow itself is untouched — the misdirected attempt did not spend it.expect((await noSession(callback(flowId))).status).toBe(200);@@ -751,7 +747,7 @@ describe("model-oauth callback without a session", () => {vi.spyOn(Date, "now").mockReturnValue(expired);const res = await noSession(callback(flowId));expect(res.status).toBe(400);- expect(exchanges).toBe(0);+ expect(exchange.calls).toHaveLength(0);vi.restoreAllMocks();expect(await groupHasKey()).toBe(false);});@@ -763,7 +759,7 @@ describe("model-oauth callback without a session", () => {vi.spyOn(Date, "now").mockReturnValue(Date.now() + FLOW_TTL_MS + 1);expect((await owner.get(`${base()}/${flowId}`)).status).toBe(404);vi.restoreAllMocks();- expect(exchanges).toBe(0);+ expect(exchange.calls).toHaveLength(0);expect(await groupHasKey()).toBe(false);});@@ -778,7 +774,7 @@ describe("model-oauth callback without a session", () => {expect((await poll(flowId)).status).toBe("done");expect((await noSession(callback(flowId))).status).toBe(400);// One code redeemed, one verifier spent — and it was the first code, not the replay's.- expect(exchanges).toBe(1);+ expect(exchange.calls).toHaveLength(1);});it("deposits once when two redirects arrive together, and spends it once", async () => {@@ -790,7 +786,7 @@ describe("model-oauth callback without a session", () => {// The deposit slot is claimed synchronously, so exactly one of them can take it.expect(both.map((r) => r.status).sort()).toEqual([200, 400]);expect((await poll(flowId)).status).toBe("done");- expect(exchanges).toBe(1);+ expect(exchange.calls).toHaveLength(1);});it("redeems a deposited code once when two polls arrive together", async () => {@@ -799,7 +795,7 @@ describe("model-oauth callback without a session", () => {const flowId = await startFlow();expect((await noSession(callback(flowId))).status).toBe(200);const both = await Promise.all([poll(flowId), poll(flowId)]);- expect(exchanges).toBe(1);+ expect(exchange.calls).toHaveLength(1);expect(both.map((r) => r.status)).toContain("done");for (const r of both) expect(r.status).not.toBe("error");expect(await groupHasKey()).toBe(true);@@ -813,7 +809,7 @@ describe("model-oauth callback without a session", () => {// A method HTTP requires to be safe changed nothing, so the real redirect still lands.expect((await noSession(callback(flowId))).status).toBe(200);expect((await poll(flowId)).status).toBe("done");- expect(exchanges).toBe(1);+ expect(exchange.calls).toHaveLength(1);expect(await groupHasKey()).toBe(true);});@@ -827,14 +823,14 @@ describe("model-oauth callback without a session", () => {const res = await noSession(callback(started.flowId));expect(res.status).toBe(400);expect(await res.text()).toContain("Authorization failed");- expect(exchanges).toBe(0);+ expect(exchange.calls).toHaveLength(0);expect(await groupHasKey()).toBe(false);// The paste box that mode did opt into still redeems it.expect((await owner.post(`${base()}/${started.flowId}/code`, { code: "pasted" })).status).toBe(200,);- expect(exchanges).toBe(1);+ expect(exchange.calls).toHaveLength(1);expect(await groupHasKey()).toBe(true);});@@ -851,6 +847,6 @@ describe("model-oauth callback without a session", () => {expect((await noSession(`${base()}/start`, { method: "POST" })).status).toBe(401);expect((await noSession(`${base()}/${flowId}`)).status).toBe(401);expect((await noSession(`${base()}/${flowId}/code`, { method: "POST" })).status).toBe(401);- expect(exchanges).toBe(0);+ expect(exchange.calls).toHaveLength(0);});});diff --git a/packages/server/test/models-fast-mode.test.ts b/packages/server/test/models-fast-mode.test.tsindex d215cb92..17dd1305 100644--- a/packages/server/test/models-fast-mode.test.ts+++ b/packages/server/test/models-fast-mode.test.ts@@ -1,9 +1,12 @@/**- * Round-trip of a model's fast_mode annotation (premium faster serving tier) through- * PUT/GET: only `true` is persisted and read back; false or omission clears it (absent =- * off — existing configs are untouched by the feature); a non-boolean value returns 400.+ * A model's fast_mode annotation (the premium faster serving tier) through PUT/GET.+ *+ * - Only `true` is persisted and read back; false or omission clears it (absent means off, so+ * existing configs are untouched).+ * - A preset model takes the annotation too (it is the user's; the catalog never presets it).+ * - A non-boolean value is a 400.*/-import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";import type { ModelsResponse, ProjectCreateResponse } from "../src/api/types.js";import { apiClient, createTestApp, provisionUser } from "./helpers.js";import type { TestApp } from "./helpers.js";@@ -13,18 +16,27 @@ describe("models fast-mode annotation", () => {let owner: ReturnType<typeof apiClient>;let projectId: string;- beforeEach(async () => {+ beforeAll(async () => {t = await createTestApp();const a = await provisionUser(t.app, "owner_f");owner = apiClient(t.app, a.cookie);+ });+ afterAll(async () => {+ await t.cleanup();+ });++ // Every case works in a Project of its own.+ let projects = 0;+ beforeEach(async () => {+ projects += 1;const created = (await (- await owner.post("/api/projects", { projectId: "owner_f-fast", name: "fast project" })+ await owner.post("/api/projects", {+ projectId: `owner_f-fast_${projects}`,+ name: "fast project",+ })).json()) as ProjectCreateResponse;projectId = created.project.projectId;});- afterEach(async () => {- await t.cleanup();- });it("fastMode=true persists and reads back; false or omitted = off (no field)", async () => {const put = await owner.put(`/api/projects/${projectId}/models`, {diff --git a/packages/server/test/models-list.test.ts b/packages/server/test/models-list.test.tsindex 1ec7dbb8..eae26da1 100644--- a/packages/server/test/models-list.test.ts+++ b/packages/server/test/models-list.test.ts@@ -1,12 +1,17 @@/**- * Endpoint model listing (POST /api/projects/:p/models/list): the service collapses every- * failure into `{ ok:false }` (UnsupportedOperationError additionally flagged, listings- * bounded in time), and the route validates shape/ownership before anything is fetched.+ * Endpoint model listing (POST /api/projects/:p/models/list).+ *+ * - The service returns a listing verbatim (the legacy openai spelling canonicalized), omits an+ * absent key, flags AgentHub's UnsupportedOperationError so the dialog can point at the+ * manual path, and collapses every other failure — a timeout included — into ok:false with+ * the reason truncated.+ * - The route refuses a non-http(s) base URL and a missing clientType before anything is+ * fetched, is owner-only, and answers in the service's DTO shape.*/import path from "node:path";import { tmpdir } from "node:os";import { mkdtemp, rm } from "node:fs/promises";-import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";import type { EndpointModelListResponse, ProjectCreateResponse } from "../src/api/types.js";import { ProjectConfigService } from "../src/services/project-config-service.js";import { apiClient, createTestApp, provisionUser } from "./helpers.js";@@ -83,18 +88,24 @@ describe("POST /api/projects/:p/models/list route validation", () => {let projectId: string;const url = () => `/api/projects/${projectId}/models/list`;- beforeEach(async () => {+ beforeAll(async () => {t = await createTestApp();const { cookie } = await provisionUser(t.app, "alice");api = apiClient(t.app, cookie);+ });+ afterAll(async () => {+ await t.cleanup();+ });++ // Every case works in a Project of its own.+ let projects = 0;+ beforeEach(async () => {+ projects += 1;const created = (await (- await api.post("/api/projects", { projectId: "alice-list", name: "List project" })+ await api.post("/api/projects", { projectId: `alice-list_${projects}`, name: "List project" })).json()) as ProjectCreateResponse;projectId = created.project.projectId;});- afterEach(async () => {- await t.cleanup();- });it("rejects a non-http(s) base URL and a missing clientType before anything is fetched", async () => {const noProto = await api.post(url(), { baseUrl: "gw.example/v1", clientType: "openai-chat" });@@ -123,7 +134,10 @@ describe("POST /api/projects/:p/models/list route validation", () => {const original = t.deps.projectConfigService.listEndpointModels.bind(t.deps.projectConfigService,);- t.deps.projectConfigService.listEndpointModels = (r) => original(r, async () => ["m-1", "m-2"]);+ // A spy, so the shared app gets its real lister back after this case.+ vi.spyOn(t.deps.projectConfigService, "listEndpointModels").mockImplementation((r) =>+ original(r, async () => ["m-1", "m-2"]),+ );const res = await api.post(url(), {baseUrl: "https://gw.example/v1",clientType: "openai-chat",diff --git a/packages/server/test/models-vision.test.ts b/packages/server/test/models-vision.test.tsindex 78e83583..e10bd8d5 100644--- a/packages/server/test/models-vision.test.ts+++ b/packages/server/test/models-vision.test.ts@@ -1,9 +1,13 @@/**- * Round-trip of a model's vision flag (whether image input is supported) through- * PUT/GET: explicit false is persisted and read back; omission means supported- * (the response carries no field); a non-boolean value returns 400.+ * A model's vision flag (image input supported) through PUT/GET.+ *+ * - An explicit false is persisted and read back; omission means supported (no field) for a+ * model outside the catalog, and a catalog model without an annotation takes the catalog's.+ * - The visionModel pointer round-trips, survives omission, and goes once its target is+ * invalid; one naming a model that is absent or has no image support is a 400.+ * - A non-boolean vision is a 400.*/-import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";import type { ModelsResponse, ProjectCreateResponse } from "../src/api/types.js";import { apiClient, createTestApp, provisionUser } from "./helpers.js";import type { TestApp } from "./helpers.js";@@ -13,18 +17,27 @@ describe("models vision annotation", () => {let owner: ReturnType<typeof apiClient>;let projectId: string;- beforeEach(async () => {+ beforeAll(async () => {t = await createTestApp();const a = await provisionUser(t.app, "owner_v");owner = apiClient(t.app, a.cookie);+ });+ afterAll(async () => {+ await t.cleanup();+ });++ // Every case works in a Project of its own.+ let projects = 0;+ beforeEach(async () => {+ projects += 1;const created = (await (- await owner.post("/api/projects", { projectId: "owner_v-vision", name: "vision project" })+ await owner.post("/api/projects", {+ projectId: `owner_v-vision_${projects}`,+ name: "vision project",+ })).json()) as ProjectCreateResponse;projectId = created.project.projectId;});- afterEach(async () => {- await t.cleanup();- });it("vision=false persists and reads back; omitted on a non-catalog model = supported (no field)", async () => {// Use a custom id outside the catalog to verify pure TOML semantics (a catalog iddiff --git a/packages/server/test/models.test.ts b/packages/server/test/models.test.tsindex f67b6eca..f62426e5 100644--- a/packages/server/test/models.test.ts+++ b/packages/server/test/models.test.ts@@ -1,18 +1,41 @@/**- * Model config integration tests: both a fresh Project and the admin-seeded default_project come- * preloaded with the built-in model catalog (`provider` and `model_id` are **stored as separate- * columns**; the (provider, model_id) pair is the unique key, ids are never concatenated, and the user- * only adds an API key); credentials are inlined in the single config file `.project_config.toml`- * (0600); GET models looks up the catalog by the paired ref to fill in displayName / envKey, taking- * vision from the TOML annotation and falling back to the catalog default; PUT persists a custom- * model's vision and an OPENAI_API_KEY fallback for client_type=openai; connectivity-test model refs- * are given as a pair in the request body.+ * A Project's model configuration: the built-in catalog as presets, one config file holding the+ * credentials, rekeying, pricing fields, the connectivity test, and what a save does to loaded+ * Sessions.+ *+ * - A new Project, and default_project when the seeded admin adopts it, is preset with every+ * built-in model (provider and model_id stored as separate fields, the pair the key) and the+ * default model, so a Session opens with no model ref; a default_project the CLI already+ * configured is left alone.+ * - Credentials live inline in `.project_config.toml` (0600) and GET shows only a mask; the env+ * fallback is reported and masked only where the entry is allowed one, never leaking a value.+ * - GET fills in display name and env key from the catalog; vision comes from the file, else the+ * catalog default; a pre-rename `client_type = "openai"` reads as openai-chat; a model the+ * catalog dropped still loads and stays usable; one model_id under two providers is two rows.+ * - PUT persists a custom model's vision flag and max_tokens (clearing and rejecting bad values),+ * falls back to OPENAI_API_KEY for the openai protocol, requires a provider, refuses an id a+ * vendor group cannot route when the request introduces it, and stores or clears a discount.+ * - renamedFrom (and a group change) migrates the credential, the config and the default and+ * vision pointers; without it a rekey is delete-then-create; an invalid one is 400. A+ * ModelScope settings save is serialized with a group credential write.+ * - The display name is persisted only when it differs from the catalog's; an absent one+ * inherits, an empty one clears, and a cleared one is restorable.+ * - A scheduled row answers both rates from its one price on disk; a hand-edited price and a+ * promotion apply in both tiers.+ * - The connectivity test sends the entry's upstream model_id, no tools, works for saved and+ * draft models, converges to ok:false with no credential, tests the draft (clearApiKey) rather+ * than the stored key, and refuses a keyless gateway row or a Penguin Go probe without reaching+ * for vendor environment keys or the network.+ * - A PUT invalidates the Project's cached Session runtimes (reads do not), tells the Project's+ * open Session channels only, and GET/PUT report the file's updatedAt.+ *+ * One app per describe; every case works in a Project of its own.*/import { createServer } from "node:http";import type { AddressInfo } from "node:net";import { readFile, stat, writeFile } from "node:fs/promises";import path from "node:path";-import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";import {MODEL_CATALOG,PENGUIN_GO_BASE_URL,@@ -29,8 +52,9 @@ import type {SessionCreateResponse,} from "../src/api/types.js";import { ProjectConfigService } from "../src/services/project-config-service.js";-import type { RuntimeSession } from "../src/runtime/session-manager.js";import type { ChannelEvent } from "../src/runtime/channel.js";+import { jsonResponse, stubFetch } from "./fixtures/fetch.js";+import { fakeSession, sessionRow } from "./fixtures/session.js";import { apiClient, createTestApp, loginAdmin, provisionUser, waitFor } from "./helpers.js";import type { TestApp } from "./helpers.js";import { wire } from "@prismshadow/penguin-core/kernel";@@ -51,18 +75,25 @@ describe("models preset & catalog enrichment", () => {let projectId: string;const url = () => `/api/projects/${projectId}/models`;- beforeEach(async () => {+ beforeAll(async () => {t = await createTestApp();const { cookie } = await provisionUser(t.app, "alice");api = apiClient(t.app, cookie);+ });+ afterAll(async () => {+ await t.cleanup();+ });+ let projects = 0;+ beforeEach(async () => {+ projects += 1;const created = (await (- await api.post("/api/projects", { projectId: "alice-preset", name: "Preset project" })+ await api.post("/api/projects", {+ projectId: `alice-preset_${projects}`,+ name: "Preset project",+ })).json()) as ProjectCreateResponse;projectId = created.project.projectId;});- afterEach(async () => {- await t.cleanup();- });it("credentials are inlined in one file: the apiKey from PUT lands in .project_config.toml (0600), GET returns only a mask", async () => {const put = await api.put(url(), {@@ -119,48 +150,42 @@ describe("models preset & catalog enrichment", () => {expect(retired.length).toBeGreaterThan(0);expect(body.models.map(pairKey).filter((key) => retired.includes(key))).toEqual([]);+ // Every row reads its display name, context window, list price, vision and pinned+ // protocol and endpoint off its catalog row; nothing of the vendor's is copied here.+ for (const row of body.models) {+ const entry = catalogEntryFor(row.provider, row.modelId)!;+ const key = `${row.provider}/${row.modelId}`;+ expect(row.displayName, key).toBe(entry.displayName);+ expect(row.contextWindow, key).toBe(entry.contextWindow);+ expect(row.vision, key).toBe(entry.supportsVision);+ expect(row.clientType, key).toBe(entry.clientType);+ expect(row.credential?.baseUrl, key).toBe(entry.baseUrl);+ // A preset carries no secret.+ expect(row.credential?.apiKeyMasked, key).toBeUndefined();+ }++ // A vendor's own row falls back to its client's environment variable; it has no stored+ // credential and no client_type (AgentHub routes it by its upstream id).const sonnet = pick(body, "anthropic", "claude-sonnet-4-6");expect(sonnet.isDefault).toBe(false);- expect(sonnet.displayName).toBe("Claude Sonnet 4.6");- // Vision: not annotated in TOML (preset vision models aren't persisted), so GET falls back to the catalog annotation.- expect(sonnet.vision).toBe(true);expect(sonnet.envKey).toBe("ANTHROPIC_API_KEY");- expect(sonnet.contextWindow).toBe(1000000);- expect(sonnet.pricing).toEqual({ cacheRead: 0.3, cacheWrite: 3.75, output: 15 });- // Preset models have no credential and no client_type (AgentHub auto-routes by upstream id).expect(sonnet.credential).toBeUndefined();expect(sonnet.clientType).toBeUndefined();-- const deepseek = pick(body, "deepseek", "deepseek-v4-pro");- expect(deepseek.vision).toBe(false);- expect(deepseek.envKey).toBe("DEEPSEEK_API_KEY");+ expect(pick(body, "deepseek", "deepseek-v4-pro").envKey).toBe("DEEPSEEK_API_KEY");expect(pick(body, "deepseek", "deepseek-flash").isDefault).toBe(true);- // OpenRouter gateway model: the upstream id contains `/`, but under column storage it's just a- // plain string; openai-responses protocol + a preset base URL inlined on the entry (no secret).- const mimo = pick(body, "openrouter", "xiaomi/mimo-v2.5");- expect(mimo.clientType).toBe("openai-responses");- expect(mimo.credential?.baseUrl).toBe("https://openrouter.ai/api/v1");- expect(mimo.credential?.apiKeyMasked).toBeUndefined();-- // OpenCode Go pins each row's protocol and endpoint, so one group holds rows on different- // clients: a Messages row sits on the base without /v1, a Chat Completions row on the /v1- // base. Like every gateway's rows, neither falls back to its client's environment- // variable — that holds the user's vendor key, and the gateway is not the vendor.+ // A gateway pins each row's protocol and endpoint, so one group can hold rows on different+ // clients (OpenCode Go: a Messages row and a Chat Completions row). Like every gateway's+ // rows, neither falls back to its client's environment variable — that holds the user's+ // vendor key, and the gateway is not the vendor. An upstream id with a `/` is a plain+ // string under column storage.const messagesRow = pick(body, "opencode-go", "qwen3.8-max");- expect(messagesRow).toMatchObject({- clientType: "ant-messages",- credential: { baseUrl: "https://opencode.ai/zen/go" },- vision: true,- });- expect(messagesRow.envKey).toBeUndefined();const chatRow = pick(body, "opencode-go", "glm-5.3");- expect(chatRow).toMatchObject({- clientType: "openai-chat",- credential: { baseUrl: "https://opencode.ai/zen/go/v1" },- vision: false,- });+ expect(messagesRow.clientType).toBe("ant-messages");+ expect(chatRow.clientType).toBe("openai-chat");+ expect(messagesRow.envKey).toBeUndefined();expect(chatRow.envKey).toBeUndefined();+ expect(pick(body, "openrouter", "xiaomi/mimo-v2.5").credential?.baseUrl).toBeDefined();// A catalog row on a promotion is preset at its LIST price like every other row, and the// promotion is seeded beside it in web.db: the rows reporting a discount are exactly the@@ -660,18 +685,25 @@ describe("model-reference rekeying and the connectivity test", () => {const url = () => `/api/projects/${projectId}/models`;const testUrl = () => `${url()}/test`;- beforeEach(async () => {+ beforeAll(async () => {t = await createTestApp();const { cookie } = await provisionUser(t.app, "carol");api = apiClient(t.app, cookie);+ });+ afterAll(async () => {+ await t.cleanup();+ });+ let projects = 0;+ beforeEach(async () => {+ projects += 1;const created = (await (- await api.post("/api/projects", { projectId: "carol-rename", name: "Rename project" })+ await api.post("/api/projects", {+ projectId: `carol-rename_${projects}`,+ name: "Rename project",+ })).json()) as ProjectCreateResponse;projectId = created.project.projectId;});- afterEach(async () => {- await t.cleanup();- });it("renamedFrom migrates the credential and the config; the default / vision model pointers follow the rekey", async () => {await api.put(url(), {@@ -1135,28 +1167,44 @@ describe("model-reference rekeying and the connectivity test", () => {});it("connectivity test: both a saved model and a **not-yet-saved** custom model can be tested (the LLM layer throws nothing, every outcome converges)", async () => {- await api.put(url(), {- models: [{ provider: "openai", modelId: "gpt-5.5", apiKey: "sk-invalid-key-for-test" }],- });- const saved = await api.post(testUrl(), { provider: "openai", modelId: "gpt-5.5" });- expect(saved.status).toBe(200);- const savedBody = (await saved.json()) as ModelTestResponse;- expect(savedBody.ok).toBe(false);- expect(typeof savedBody.message).toBe("string");-- // "Test before save" for adding a custom model: the model isn't in the config, so all params come from the request body.- const unsaved = await api.post(testUrl(), {- provider: "custom",- modelId: "my-new-model",- apiKey: "sk-invalid",- baseUrl: "https://example.invalid/v1",- clientType: "openai",- });- expect(unsaved.status).toBe(200);- const unsavedBody = (await unsaved.json()) as ModelTestResponse;- expect(unsavedBody.ok).toBe(false);- expect(typeof unsavedBody.message).toBe("string");- }, 40_000);+ // Both endpoints refuse the key they are handed.+ const network = stubFetch(() =>+ jsonResponse(+ { error: { message: "Incorrect API key provided.", code: "invalid_api_key" } },+ 401,+ ),+ );+ try {+ await api.put(url(), {+ models: [{ provider: "openai", modelId: "gpt-5.5", apiKey: "sk-invalid-key-for-test" }],+ });+ const saved = await api.post(testUrl(), { provider: "openai", modelId: "gpt-5.5" });+ expect(saved.status).toBe(200);+ const savedBody = (await saved.json()) as ModelTestResponse;+ expect(savedBody.ok).toBe(false);+ expect(typeof savedBody.message).toBe("string");++ // "Test before save" for adding a custom model: the model isn't in the config, so all params come from the request body.+ const unsaved = await api.post(testUrl(), {+ provider: "custom",+ modelId: "my-new-model",+ apiKey: "sk-invalid",+ baseUrl: "https://example.invalid/v1",+ clientType: "openai",+ });+ expect(unsaved.status).toBe(200);+ const unsavedBody = (await unsaved.json()) as ModelTestResponse;+ expect(unsavedBody.ok).toBe(false);+ expect(typeof unsavedBody.message).toBe("string");+ // Each probe went to its own model's endpoint, with its own key.+ const keyAt = (host: string) =>+ network.calls.find((c) => c.url.startsWith(host))?.headers.get("authorization");+ expect(keyAt("https://api.openai.com/")).toBe("Bearer sk-invalid-key-for-test");+ expect(keyAt("https://example.invalid/v1")).toBe("Bearer sk-invalid");+ } finally {+ vi.unstubAllGlobals();+ }+ });it("connectivity test: a model with no credential at all converges to ok:false instead of 500", async () => {// A model using the OpenAI protocol: the provider SDK throws at **client construction** because@@ -1185,12 +1233,9 @@ describe("model-reference rekeying and the connectivity test", () => {const saved = { openai: process.env.OPENAI_API_KEY, anthropic: process.env.ANTHROPIC_API_KEY };process.env.OPENAI_API_KEY = "vendor-openai-must-not-cross";process.env.ANTHROPIC_API_KEY = "vendor-anthropic-must-not-cross";- const realFetch = globalThis.fetch;- let requests = 0;- globalThis.fetch = (async () => {- requests += 1;+ const network = stubFetch(() => {throw new Error("no request may leave the process for a refused probe");- }) as typeof fetch;+ });try {// A gateway preset: the group's endpoint, no key. Both OpenAI-protocol gateways and the// Messages-protocol custom preset (Atria — the path that carried the Anthropic key in the@@ -1229,9 +1274,9 @@ describe("model-reference rekeying and the connectivity test", () => {outcome: "failed",message: expect.stringMatching(/has no API key/) as string,});- expect(requests).toBe(0);+ expect(network.calls).toEqual([]);} finally {- globalThis.fetch = realFetch;+ vi.unstubAllGlobals();for (const [key, value] of [["OPENAI_API_KEY", saved.openai],["ANTHROPIC_API_KEY", saved.anthropic],@@ -1334,31 +1379,8 @@ describe("models update reaches loaded sessions (invalidation + live unlock)", (/** Loader call count: how many times the manager (re)built a runtime from the index. */let loads: number;- /** Minimal fake runtime Session (no LLM calls; mirrors vault.test.ts). */- const fakeRuntimeSession = (sessionId: string): RuntimeSession => ({- sessionId,- toolPermission: () => "rw",- generateTitle: async () => ({ title: null, usage: null }),- compactability: () => "ok" as const,- steer: () => false,- skipReconnectWait: () => false,- async *run() {},- async *compact() {},- });-const insertSession = (sessionId: string, project: string): void => {- t.deps.sessionsRepo.insert({- sessionId,- projectId: project,- agentId: "default_agent",- modelId: "m1",- provider: "custom",- workspace: t.root,- approvalMode: "allow-all",- title: null,- createdAt: new Date().toISOString(),- lastActiveAt: new Date().toISOString(),- });+ t.deps.sessionsRepo.insert(sessionRow(sessionId, { projectId: project, workspace: t.root }));};const putModels = (apiKey: string) =>@@ -1367,26 +1389,34 @@ describe("models update reaches loaded sessions (invalidation + live unlock)", (models: [{ provider: "custom", modelId: "m-inv", apiKey }],});- beforeEach(async () => {- loads = 0;+ beforeAll(async () => {+ // Every runtime the manager builds from the index is an idle fake: no LLM call is made.t = await createTestApp({loader: {load: async (row) => {loads++;- return fakeRuntimeSession(row.sessionId);+ return fakeSession(row.sessionId);},},});const { cookie } = await provisionUser(t.app, "inv_owner");api = apiClient(t.app, cookie);+ });+ afterAll(async () => {+ await t.cleanup();+ });+ let projects = 0;+ beforeEach(async () => {+ loads = 0;+ projects += 1;const created = (await (- await api.post("/api/projects", { projectId: "inv_owner-models", name: "invalidation" })+ await api.post("/api/projects", {+ projectId: `inv_owner-models_${projects}`,+ name: "invalidation",+ })).json()) as ProjectCreateResponse;projectId = created.project.projectId;});- afterEach(async () => {- await t.cleanup();- });it("PUT invalidates the Project's cached Session runtimes: the next Task re-resumes with the new key", async () => {insertSession("models-sess-1", projectId);diff --git a/packages/server/test/modelscope-auth.test.ts b/packages/server/test/modelscope-auth.test.tsindex c3e104f8..ee580b2a 100644--- a/packages/server/test/modelscope-auth.test.ts+++ b/packages/server/test/modelscope-auth.test.ts@@ -1,4 +1,26 @@+/**+ * ModelScope key authorization: the harness starts a flow at the Penguin bridge, polls it, and+ * writes the delivered token to the ModelScope group; later it refreshes that token.+ *+ * - The flow: the bridge's own authorize URL is passed through (never one a tab must not open),+ * the delivered token is written, a failed or swallowed write keeps the token for a retry+ * without polling again, every terminal status maps onto the flow's own states and ends the+ * polling, an unreachable bridge or a rejected start is an upstream failure, the bridge's+ * rate limit surfaces with its Retry-After on start and backs a poll off, cancelling reaches+ * the bridge and applies nothing, a flow is hidden from another Project or user and forgotten+ * once expired, and a delivery is validated rather than trusted.+ * - Refresh: a token about to expire is refreshed silently, dropped if the stored refresh token+ * changed meanwhile, kept usable when a proactive refresh fails, and re-authorization is asked+ * for when an expired token cannot be refreshed or after three failures (a changed refresh+ * token resets the count).+ * - The routes: only the owner starts; the token lands on the group's preset rows and no account+ * state is exposed; an unknown or foreign flow has its own not-found code.+ *+ * No test reaches the network: the bridge is the suite's fetch fake, handed to the service or+ * standing in for the global fetch in the route cases.+ */import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { presetModelEntries } from "@prismshadow/penguin-core/model-catalog";import type {ModelScopeAuthFlowStatusResponse,ModelScopeAuthStartResponse,@@ -9,24 +31,21 @@ import {ModelScopeAuthService,modelscopeAccessToken,} from "../src/services/modelscope-auth-service.js";+import { fakeFetch, jsonResponse, stubFetch } from "./fixtures/fetch.js";import { apiClient, createTestApp, provisionUser } from "./helpers.js";import type { TestApp } from "./helpers.js";/** The production bridge address, path prefix included: the prefix must survive into every call. */const BRIDGE = "https://go.penguin.ooo/modelscope";-function json(status: number, body: unknown): Response {- return new Response(JSON.stringify(body), {- status,- headers: { "content-type": "application/json" },- });-}-function started(expiresInMs = 60_000): Response {- return json(201, {- authorizeUrl: `${BRIDGE}/oauth/authorize?code=abc`,- expiresAt: new Date(Date.now() + expiresInMs).toISOString(),- });+ return jsonResponse(+ {+ authorizeUrl: `${BRIDGE}/oauth/authorize?code=abc`,+ expiresAt: new Date(Date.now() + expiresInMs).toISOString(),+ },+ 201,+ );}function pathOf(input: string | URL | Request): string {@@ -63,7 +82,7 @@ describe("ModelScope key authorization service", () => {applied.push({ projectId, token: credential.accessToken });return 1;},- fetchImpl: async (input, init) => {+ fetchImpl: fakeFetch(async ({ url: input, init }) => {if (pathOf(input) === "/modelscope/oauth/start") {const body = JSON.parse(String(init?.body)) as Record<string, unknown>;expect(body.client).toEqual({ id: "penguin-harness" });@@ -74,8 +93,8 @@ describe("ModelScope key authorization service", () => {}expect(init?.redirect).toBe("manual");polls += 1;- return polls === 1 ? json(200, { status: "pending" }) : json(200, delivery);- },+ return polls === 1 ? jsonResponse({ status: "pending" }) : jsonResponse(delivery);+ }).fetch,});const flow = await service.start(owner);@@ -104,11 +123,11 @@ describe("ModelScope key authorization service", () => {if (applies === 1) throw new Error("disk busy");return 1;},- fetchImpl: async (input) => {+ fetchImpl: fakeFetch(async ({ url: input }) => {if (pathOf(input).endsWith("/start")) return started();polls += 1;- return json(200, delivery);- },+ return jsonResponse(delivery);+ }).fetch,});const flow = await service.start(owner);expect(await service.status({ ...owner, flowId: flow.flowId })).toMatchObject({@@ -130,8 +149,9 @@ describe("ModelScope key authorization service", () => {const service = new ModelScopeAuthService({bridgeUrl: BRIDGE,applyCredential: async () => 0,- fetchImpl: async (input) =>- pathOf(input).endsWith("/start") ? started() : json(200, delivery),+ fetchImpl: fakeFetch(async ({ url: input }) =>+ pathOf(input).endsWith("/start") ? started() : jsonResponse(delivery),+ ).fetch,});const flow = await service.start(owner);expect(await service.status({ ...owner, flowId: flow.flowId })).toMatchObject({@@ -159,8 +179,9 @@ describe("ModelScope key authorization service", () => {const service = new ModelScopeAuthService({bridgeUrl: BRIDGE,applyCredential: async () => 1,- fetchImpl: async (input) =>- pathOf(input).endsWith("/start") ? started() : json(200, { status: reported }),+ fetchImpl: fakeFetch(async ({ url: input }) =>+ pathOf(input).endsWith("/start") ? started() : jsonResponse({ status: reported }),+ ).fetch,});const flow = await service.start(owner);const result = await service.status({ ...owner, flowId: flow.flowId });@@ -175,11 +196,11 @@ describe("ModelScope key authorization service", () => {const service = new ModelScopeAuthService({bridgeUrl: BRIDGE,applyCredential: async () => 1,- fetchImpl: async (input) => {+ fetchImpl: fakeFetch(async ({ url: input }) => {if (pathOf(input).endsWith("/start")) return started();polls += 1;- return json(200, { status: "expired" });- },+ return jsonResponse({ status: "expired" });+ }).fetch,});const flow = await service.start(owner);await service.status({ ...owner, flowId: flow.flowId });@@ -191,9 +212,9 @@ describe("ModelScope key authorization service", () => {const unreachable = new ModelScopeAuthService({bridgeUrl: BRIDGE,applyCredential: async () => 1,- fetchImpl: async () => {+ fetchImpl: fakeFetch(async () => {throw new Error("ECONNREFUSED");- },+ }).fetch,});await expect(unreachable.start(owner)).rejects.toMatchObject({status: 502,@@ -203,7 +224,7 @@ describe("ModelScope key authorization service", () => {const refused = new ModelScopeAuthService({bridgeUrl: BRIDGE,applyCredential: async () => 1,- fetchImpl: async () => json(409, { error: "flow_conflict" }),+ fetchImpl: fakeFetch(async () => jsonResponse({ error: "flow_conflict" }, 409)).fetch,});await expect(refused.start(owner)).rejects.toMatchObject({status: 502,@@ -216,11 +237,15 @@ describe("ModelScope key authorization service", () => {const service = new ModelScopeAuthService({bridgeUrl: BRIDGE,applyCredential: async () => 1,- fetchImpl: async () =>- json(201, {- authorizeUrl,- expiresAt: new Date(Date.now() + 60_000).toISOString(),- }),+ fetchImpl: fakeFetch(async () =>+ jsonResponse(+ {+ authorizeUrl,+ expiresAt: new Date(Date.now() + 60_000).toISOString(),+ },+ 201,+ ),+ ).fetch,});await expect(service.start(owner)).rejects.toMatchObject({status: 502,@@ -233,7 +258,9 @@ describe("ModelScope key authorization service", () => {const service = new ModelScopeAuthService({bridgeUrl: BRIDGE,applyCredential: async () => 1,- fetchImpl: async () => json(429, { error: "rate_limited", retryAfterSeconds: 12 }),+ fetchImpl: fakeFetch(async () =>+ jsonResponse({ error: "rate_limited", retryAfterSeconds: 12 }, 429),+ ).fetch,});await expect(service.start(owner)).rejects.toMatchObject({status: 429,@@ -249,18 +276,21 @@ describe("ModelScope key authorization service", () => {bridgeUrl: BRIDGE,now: () => now,applyCredential: async () => 1,- fetchImpl: async (input) => {+ fetchImpl: fakeFetch(async ({ url: input }) => {if (pathOf(input).endsWith("/start")) {- return json(201, {- authorizeUrl: `${BRIDGE}/oauth/authorize?code=abc`,- expiresAt: new Date(now + 60_000).toISOString(),- });+ return jsonResponse(+ {+ authorizeUrl: `${BRIDGE}/oauth/authorize?code=abc`,+ expiresAt: new Date(now + 60_000).toISOString(),+ },+ 201,+ );}polls += 1;return polls === 1- ? json(429, { error: "rate_limited", retryAfterSeconds: 2 })- : json(200, delivery);- },+ ? jsonResponse({ error: "rate_limited", retryAfterSeconds: 2 }, 429)+ : jsonResponse(delivery);+ }).fetch,});const flow = await service.start(owner);expect(await service.status({ ...owner, flowId: flow.flowId })).toEqual({ status: "pending" });@@ -292,17 +322,17 @@ describe("ModelScope key authorization service", () => {expect(credential.refreshToken).toBe("new-refresh");return 3;},- fetchImpl: async (input, init) => {+ fetchImpl: fakeFetch(async ({ url: input, init }) => {expect(pathOf(input)).toBe("/modelscope/oauth/refresh");expect(JSON.parse(String(init?.body))).toEqual({ refreshToken: "old-refresh" });- return json(200, {+ return jsonResponse({token: {accessToken: "new-access",refreshToken: "new-refresh",expiresAt: new Date(now + 3_600_000).toISOString(),},});- },+ }).fetch,});await expect(service.ensureFresh({ projectId: "p1", provider: "modelscope" })).resolves.toEqual({ changed: true },@@ -326,14 +356,15 @@ describe("ModelScope key authorization service", () => {expect(options).toEqual({ expectedRefreshToken: "old-refresh" });return 0;},- fetchImpl: async () =>- json(200, {+ fetchImpl: fakeFetch(async () =>+ jsonResponse({token: {accessToken: "new-access",refreshToken: "new-refresh",expiresAt: new Date(now + 3_600_000).toISOString(),},}),+ ).fetch,});await expect(service.ensureFresh({ projectId: "p1", provider: "modelscope" })).resolves.toEqual({ changed: false },@@ -354,7 +385,7 @@ describe("ModelScope key authorization service", () => {applyCredential: async () => {throw new Error("must not apply");},- fetchImpl: async () => json(502, { error: "bridge_down" }),+ fetchImpl: fakeFetch(async () => jsonResponse({ error: "bridge_down" }, 502)).fetch,});await expect(service.ensureFresh({ projectId: "p1", provider: "modelscope" })).resolves.toEqual({ changed: false },@@ -373,7 +404,7 @@ describe("ModelScope key authorization service", () => {updatedAt: new Date(now - 1_000).toISOString(),}),applyCredential: async () => 1,- fetchImpl: async () => json(401, { error: "invalid_grant" }),+ fetchImpl: fakeFetch(async () => jsonResponse({ error: "invalid_grant" }, 401)).fetch,});await expect(service.ensureFresh({ projectId: "p1", provider: "modelscope" }),@@ -393,10 +424,10 @@ describe("ModelScope key authorization service", () => {updatedAt: new Date(0).toISOString(),}),applyCredential: async () => 1,- fetchImpl: async () => {+ fetchImpl: fakeFetch(async () => {attempts += 1;- return json(502, { error: "bridge_down" });- },+ return jsonResponse({ error: "bridge_down" }, 502);+ }).fetch,});await expect(service.ensureFresh({ projectId: "p1", provider: "modelscope" })).resolves.toEqual(@@ -430,17 +461,17 @@ describe("ModelScope key authorization service", () => {updatedAt: new Date(now - 1_000).toISOString(),}),applyCredential: async () => 3,- fetchImpl: async () => {+ fetchImpl: fakeFetch(async () => {attempts += 1;- if (refreshToken === "old-refresh") return json(502, { error: "bridge_down" });- return json(200, {+ if (refreshToken === "old-refresh") return jsonResponse({ error: "bridge_down" }, 502);+ return jsonResponse({token: {accessToken: "reauthorized-access",refreshToken,expiresAt: new Date(now + 3_600_000).toISOString(),},});- },+ }).fetch,});await service.ensureFresh({ projectId: "p1", provider: "modelscope" });@@ -467,14 +498,14 @@ describe("ModelScope key authorization service", () => {applied += 1;return 1;},- fetchImpl: async (input) => {+ fetchImpl: fakeFetch(async ({ url: input }) => {if (pathOf(input).endsWith("/start")) return started();if (pathOf(input).endsWith("/cancel")) {cancelled += 1;- return json(200, { ok: true });+ return jsonResponse({ ok: true });}- return json(200, delivery);- },+ return jsonResponse(delivery);+ }).fetch,});const flow = await service.start(owner);service.cancel({ ...owner, flowId: flow.flowId });@@ -492,7 +523,7 @@ describe("ModelScope key authorization service", () => {bridgeUrl: BRIDGE,now: () => now,applyCredential: async () => 1,- fetchImpl: async () => started(600_000),+ fetchImpl: fakeFetch(async () => started(600_000)).fetch,});const flow = await service.start(owner);const gone = { status: 404, code: "modelscope_auth_flow_not_found" };@@ -551,23 +582,20 @@ describe("ModelScope key authorization routes", () => {).toBe(201);pollCount = 0;- vi.stubGlobal(- "fetch",- vi.fn(async (input: string | URL | Request, init?: RequestInit) => {- const path = pathOf(input);- // Every call carries the bridge's path prefix; a lost prefix is a 404 at the bridge.- if (path === "/modelscope/oauth/start") {- const body = JSON.parse(String(init?.body)) as Record<string, unknown>;- expect(body.client).toEqual({ id: "penguin-harness" });- return started();- }- if (path === "/modelscope/oauth/poll") {- pollCount += 1;- return pollCount === 1 ? json(200, { status: "pending" }) : json(200, delivery);- }- throw new Error(`Unexpected bridge request: ${path}`);- }),- );+ stubFetch(({ url, init }) => {+ const path = pathOf(url);+ // Every call carries the bridge's path prefix; a lost prefix is a 404 at the bridge.+ if (path === "/modelscope/oauth/start") {+ const body = JSON.parse(String(init?.body)) as Record<string, unknown>;+ expect(body.client).toEqual({ id: "penguin-harness" });+ return started();+ }+ if (path === "/modelscope/oauth/poll") {+ pollCount += 1;+ return pollCount === 1 ? jsonResponse({ status: "pending" }) : jsonResponse(delivery);+ }+ throw new Error(`Unexpected bridge request: ${path}`);+ });});afterEach(async () => {@@ -582,11 +610,14 @@ describe("ModelScope key authorization routes", () => {await ownerClient.get(`/api/projects/${projectId}/models`)).json()) as ModelsResponse;const preset = before.models.filter((model) => model.provider === "modelscope");- expect(preset.map((model) => model.modelId)).toEqual([- "deepseek-ai/DeepSeek-V4.1-Flash",- "Qwen/Qwen3.8-27B",- "Qwen/Qwen3.8-Flash-Next",- ]);+ // The group's rows are the catalog's ModelScope presets.+ expect(preset).not.toEqual([]);+ expect(preset.map((model) => model.modelId).sort()).toEqual(+ presetModelEntries()+ .filter((entry) => entry.provider === "modelscope")+ .map((entry) => entry.model_id)+ .sort(),+ );expect(preset.every((model) => model.clientType === "openai-responses")).toBe(true);expect(preset.every((model) => model.credential?.apiKeyMasked === undefined)).toBe(true);diff --git a/packages/server/test/project-chat-defaults.test.ts b/packages/server/test/project-chat-defaults.test.tsindex 2dc93a43..e974fa4d 100644--- a/packages/server/test/project-chat-defaults.test.ts+++ b/packages/server/test/project-chat-defaults.test.ts@@ -1,18 +1,22 @@/**- * GET|PUT /api/projects/:p/chat-defaults — per-Project new-chat defaults (the- * `[default_chat]` block of .project_config.toml) — and PUT /api/projects/:p/models/default,- * the narrow default-model switch project settings uses.+ * A Project's new-chat defaults (GET|PUT /api/projects/:p/chat-defaults, the `[default_chat]`+ * block of .project_config.toml) and the narrow default-model switch (PUT+ * /api/projects/:p/models/default).*- * Pins the contract's load-bearing corners: who may read (any member) and write (owner- * only, with a non-member unable to tell the Project exists), that PUT is a declarative- * whole-block replace (an omitted key clears it; an empty body removes the block), that a- * defaults write is a read-modify-write of the same toml — models, credentials and the- * display name must survive — and that agentId / enum values are validated (the model- * default stays the SAME top-level `default_model` the models page maintains, so the- * narrow route must reject a pair outside the models table exactly like the whole-table- * PUT does).+ * - Any member reads (an absent block is an empty object); only the owner writes, and a+ * non-member cannot tell the Project exists.+ * - A PUT replaces the whole block: an omitted key clears it, an empty body removes it.+ * - The write is read-modify-write: models, credentials and the name survive, and a config+ * carrying the block still parses back whole.+ * - agentId must name an Agent of the Project; enum values are validated (thinkingLevel+ * `none` included).+ * - The default-model switch writes the same top-level `default_model` the models page keeps:+ * the response mirrors GET models, credentials survive, a pair outside the models table is+ * a 400, and it is owner-only.+ *+ * One app for the file; every case works in a Project of its own.*/-import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";import fs from "node:fs/promises";import path from "node:path";import type {@@ -30,25 +34,36 @@ const SERVED = {sandbox: { mode: "danger-full-access", network: "open", localNetworkSupported: false },};+/** The file's app and its three users; every case below works in a Project of its own. */+let t: TestApp;+let owner: ReturnType<typeof apiClient>;+let member: ReturnType<typeof apiClient>;+let outsider: ReturnType<typeof apiClient>;++beforeAll(async () => {+ t = await createTestApp();+ const a = await provisionUser(t.app, "owner_a");+ const b = await provisionUser(t.app, "member_b");+ const c = await provisionUser(t.app, "outsider_c");+ owner = apiClient(t.app, a.cookie);+ member = apiClient(t.app, b.cookie);+ outsider = apiClient(t.app, c.cookie);+});+afterAll(async () => {+ await t.cleanup();+});+describe("project chat defaults", () => {- let t: TestApp;- let owner: ReturnType<typeof apiClient>;- let member: ReturnType<typeof apiClient>;- let outsider: ReturnType<typeof apiClient>;let projectId: string;let url: string;+ // Every case works in a Project of its own.+ let projects = 0;beforeEach(async () => {- t = await createTestApp();- const a = await provisionUser(t.app, "owner_a");- const b = await provisionUser(t.app, "member_b");- const c = await provisionUser(t.app, "outsider_c");- owner = apiClient(t.app, a.cookie);- member = apiClient(t.app, b.cookie);- outsider = apiClient(t.app, c.cookie);+ projects += 1;// createProject provisions the built-in default_agent, so a valid agentId exists.const created = (await (- await owner.post("/api/projects", { projectId: "owner_a-shared", name: "Shared" })+ await owner.post("/api/projects", { projectId: `owner_a-shared_${projects}`, name: "Shared" })).json()) as ProjectCreateResponse;projectId = created.project.projectId;url = `/api/projects/${projectId}/chat-defaults`;@@ -56,9 +71,6 @@ describe("project chat defaults", () => {(await owner.post(`/api/projects/${projectId}/members`, { userId: "member_b" })).status,).toBe(201);});- afterEach(async () => {- await t.cleanup();- });it("any member reads; an absent block is an empty object; a non-member gets 404", async () => {const res = await member.get(url);@@ -161,23 +173,15 @@ describe("project chat defaults", () => {});describe("models default (narrow default-model switch)", () => {- let t: TestApp;- let owner: ReturnType<typeof apiClient>;- let member: ReturnType<typeof apiClient>;- let outsider: ReturnType<typeof apiClient>;let projectId: string;let url: string;+ // Every case works in a Project of its own.+ let projects = 0;beforeEach(async () => {- t = await createTestApp();- const a = await provisionUser(t.app, "owner_a");- const b = await provisionUser(t.app, "member_b");- const c = await provisionUser(t.app, "outsider_c");- owner = apiClient(t.app, a.cookie);- member = apiClient(t.app, b.cookie);- outsider = apiClient(t.app, c.cookie);+ projects += 1;const created = (await (- await owner.post("/api/projects", { projectId: "owner_a-models", name: "Models" })+ await owner.post("/api/projects", { projectId: `owner_a-models_${projects}`, name: "Models" })).json()) as ProjectCreateResponse;projectId = created.project.projectId;url = `/api/projects/${projectId}/models/default`;@@ -197,9 +201,6 @@ describe("models default (narrow default-model switch)", () => {(await owner.post(`/api/projects/${projectId}/members`, { userId: "member_b" })).status,).toBe(201);});- afterEach(async () => {- await t.cleanup();- });it("owner flips the default; the response mirrors GET models' defaultModel; credentials survive", async () => {const res = await owner.put(url, { provider: "custom", modelId: "m-2" });diff --git a/packages/server/test/project-command-policy.test.ts b/packages/server/test/project-command-policy.test.tsindex 21275bc0..8e3d564e 100644--- a/packages/server/test/project-command-policy.test.ts+++ b/packages/server/test/project-command-policy.test.ts@@ -1,16 +1,16 @@/**- * GET|PUT /api/projects/:p/command-policy — the Project sandbox command policy (the+ * A Project's sandbox command policy (GET|PUT /api/projects/:p/command-policy, the* `[command_policy]` block of .project_config.toml).*- * Pins the contract's load-bearing corners: who may read (any member) and write (owner- * only, a non-member unable to tell the Project exists); that a new project is seeded with- * the factory rules while a pre-seeding project (no stored block) still serves them as the- * effective set; that the rules are plain editable data (edit / disable / delete / add all- * round-trip) and a PUT materializes the full list; that an uncompilable pattern is- * rejected up front (a rule that cannot fire must not save); and that a policy write is a- * read-modify-write — the models table must survive.+ * - A new Project is seeded with the factory rules; one from before seeding (no stored block)+ * still serves them as the effective set.+ * - Any member reads; only the owner writes, and a non-member cannot tell the Project exists.+ * - The rules are plain data: edit, disable, delete and add all round-trip, as do an empty+ * list and a disabled policy, and a PUT materializes the full list.+ * - An uncompilable pattern is refused naming its rule; malformed bodies are refused.+ * - The write is read-modify-write: the models table survives.*/-import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";import fs from "node:fs/promises";import path from "node:path";import type {@@ -30,7 +30,7 @@ describe("project command policy", () => {let projectId: string;let url: string;- beforeEach(async () => {+ beforeAll(async () => {t = await createTestApp();const a = await provisionUser(t.app, "owner_a");const b = await provisionUser(t.app, "member_b");@@ -38,8 +38,17 @@ describe("project command policy", () => {owner = apiClient(t.app, a.cookie);member = apiClient(t.app, b.cookie);outsider = apiClient(t.app, c.cookie);+ });+ afterAll(async () => {+ await t.cleanup();+ });++ // Every case works in a Project of its own.+ let projects = 0;+ beforeEach(async () => {+ projects += 1;const created = (await (- await owner.post("/api/projects", { projectId: "owner_a-shared", name: "Shared" })+ await owner.post("/api/projects", { projectId: `owner_a-shared_${projects}`, name: "Shared" })).json()) as ProjectCreateResponse;projectId = created.project.projectId;url = `/api/projects/${projectId}/command-policy`;@@ -47,9 +56,6 @@ describe("project command policy", () => {(await owner.post(`/api/projects/${projectId}/members`, { userId: "member_b" })).status,).toBe(201);});- afterEach(async () => {- await t.cleanup();- });it("a new project is seeded with the factory rules; any member reads; a non-member gets 404", async () => {// Seeded at creation, model-presets style: the file itself carries the block.diff --git a/packages/server/test/project-rename.test.ts b/packages/server/test/project-rename.test.tsindex 98b7e002..55331dd9 100644--- a/packages/server/test/project-rename.test.ts+++ b/packages/server/test/project-rename.test.ts@@ -1,14 +1,13 @@/**- * PATCH /api/projects/:projectId — renaming a Project's display name.+ * Renaming a Project (PATCH /api/projects/:projectId): the display name is the only mutable+ * field, since the id names the directory, the Workspace paths and every stored reference.*- * The display name is the only mutable field of a Project: the id names the directory, the- * Workspace paths and every stored reference, so it stays immutable and there is no route that- * changes it. These tests pin the three things that could quietly go wrong: who is allowed to- * rename (owner only, with a non-member unable to tell the Project exists), that the write is a- * read-modify-write of project_config.toml rather than a replacement — models and their- * credentials must survive a rename — and that a blank name is refused rather than stored.+ * - The owner renames: the response, the Project list and the toml carry the new name, trimmed.+ * - The write is read-modify-write: models and their credentials survive.+ * - Only the owner renames; a member gets 403 and a non-member 404 (existence is not leaked).+ * - A missing, blank or over-long name is refused.*/-import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";import fs from "node:fs/promises";import path from "node:path";import type {@@ -27,7 +26,7 @@ describe("project rename", () => {let outsider: ReturnType<typeof apiClient>;let projectId: string;- beforeEach(async () => {+ beforeAll(async () => {t = await createTestApp();const a = await provisionUser(t.app, "owner_a");const b = await provisionUser(t.app, "member_b");@@ -35,17 +34,23 @@ describe("project rename", () => {owner = apiClient(t.app, a.cookie);member = apiClient(t.app, b.cookie);outsider = apiClient(t.app, c.cookie);+ });+ afterAll(async () => {+ await t.cleanup();+ });++ // Every case works in a Project of its own.+ let projects = 0;+ beforeEach(async () => {+ projects += 1;const created = (await (- await owner.post("/api/projects", { projectId: "owner_a-shared", name: "Before" })+ await owner.post("/api/projects", { projectId: `owner_a-shared_${projects}`, name: "Before" })).json()) as ProjectCreateResponse;projectId = created.project.projectId;expect((await owner.post(`/api/projects/${projectId}/members`, { userId: "member_b" })).status,).toBe(201);});- afterEach(async () => {- await t.cleanup();- });it("owner renames: the response, the Project list and the toml all carry the new name", async () => {const res = await owner.patch(`/api/projects/${projectId}`, { name: "After" });diff --git a/packages/server/test/prompt-sections.test.ts b/packages/server/test/prompt-sections.test.tsindex 2892c1eb..80ecd3a5 100644--- a/packages/server/test/prompt-sections.test.ts+++ b/packages/server/test/prompt-sections.test.ts@@ -1,14 +1,17 @@/**- * Integration tests for the Vault / Skills / Schedules prompt-injection config (the- * memory-style placeholder + toggle + editable prompt pattern): the config route reports- * effective values plus template facts (placeholder presence, legacy-section presence),- * toggles and prompts round-trip through PUT …/config, and each feature's- * POST …/template-placeholder inserts — or, for a legacy hardcoded section, migrates to —- * its placeholder, with the routers' own permission models (skills member-level,- * vault/schedules owner-only). The Hooks tab's switch rides on the same config route with no- * prompt half — `hooks.enabled` decides whether a new Session runs the installed hook packages.+ * The Vault, Skills and Schedules prompt sections (placeholder, toggle and editable prompt,+ * as Memory has) and the Hooks switch, all on the Agent config route.+ *+ * - A fresh Agent reports the three sections enabled, with default prompts, placeholders+ * present and no legacy section.+ * - Each toggle, a custom prompt (the other sections untouched) and the hook switch (no prompt+ * half) round-trip through PUT …/config.+ * - POST …/template-placeholder migrates a legacy template's hardcoded sections placeholder by+ * placeholder, and otherwise inserts {{SCHEDULES}} before # Environment.+ * - Skills is member-level; the vault and schedules endpoints are owner-only; outsiders get 404+ * everywhere.*/-import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";import { LEGACY_SKILLS_SECTION, LEGACY_VAULT_SECTION } from "@prismshadow/penguin-core";import type {AgentConfigResponse,@@ -31,7 +34,7 @@ describe("prompt-injection config (vault / skills / schedules)", () => {let configPath: string;let agentBase: string;- beforeEach(async () => {+ beforeAll(async () => {t = await createTestApp();const a = await provisionUser(t.app, "owner_a");const b = await provisionUser(t.app, "member_b");@@ -39,8 +42,20 @@ describe("prompt-injection config (vault / skills / schedules)", () => {owner = apiClient(t.app, a.cookie);member = apiClient(t.app, b.cookie);outsider = apiClient(t.app, c.cookie);+ });+ afterAll(async () => {+ await t.cleanup();+ });++ // Every case works in a Project of its own.+ let projects = 0;+ beforeEach(async () => {+ projects += 1;const created = (await (- await owner.post("/api/projects", { projectId: "owner_a-sections", name: "sections" })+ await owner.post("/api/projects", {+ projectId: `owner_a-sections_${projects}`,+ name: "sections",+ })).json()) as { project: { projectId: string } };projectId = created.project.projectId;await owner.post(`/api/projects/${projectId}/members`, { userId: "member_b" });@@ -48,10 +63,6 @@ describe("prompt-injection config (vault / skills / schedules)", () => {configPath = `${agentBase}/config`;});- afterEach(async () => {- await t.cleanup();- });-const getConfig = async (): Promise<AgentConfigResponse> =>(await (await owner.get(configPath)).json()) as AgentConfigResponse;diff --git a/packages/server/test/protocol-detect.test.ts b/packages/server/test/protocol-detect.test.tsindex eddfac9c..0a634cec 100644--- a/packages/server/test/protocol-detect.test.ts+++ b/packages/server/test/protocol-detect.test.ts@@ -1,20 +1,33 @@/**- * Protocol auto-detection tests: classification of probe answers (route-exists vs- * route-missing 404/405 vs HTML/gateway junk vs 5xx), the candidate base URLs a typed URL- * expands to (an extra `/v1`, a missing `/v1`, a whole endpoint URL pasted in), the- * required probe order (openai-responses → ant-messages → openai-chat, candidate by- * candidate, stop at the first served protocol) and the base URL reported back,- * auth header shapes per protocol (Bearer for the OpenAI protocols; x-api-key +- * Bearer + anthropic-version for ant-messages, mirroring AgentHub's clients), the- * per-protocol environment-variable fallback used when no key was typed or stored- * (ANTHROPIC_* for ant-messages, OPENAI_* for the other two), and the- * POST /api/projects/:p/models/detect route (validation, stored-key fallback via the- * paired reference, and that the key never appears in the response).+ * Protocol auto-detection: which wire protocol a typed base URL speaks.+ *+ * - A probe's answer is classified by what it proves: 404/405 is a missing route by status+ * alone; a 4xx in an API-error shape (auth failures included, a FastAPI `detail` only when it+ * carries a message) is a served route; HTML, non-JSON, a 2xx without protocol markers and+ * shapeless 4xx JSON are junk; a 5xx proves nothing.+ * - A typed URL expands to candidates covering one `/v1` too many, one too few and a whole+ * endpoint URL pasted in (the longest endpoint path stripped, repeats collapsed, the rest kept+ * exactly as typed), joined to protocol paths the way the wrapped SDKs do.+ * - Probes run openai-responses → ant-messages → openai-chat, candidate by candidate, stop at the+ * first served protocol and report the base URL it was served on; a probe that fails or+ * floods (abandoned at the body cap) does not stop the sequence.+ * - Auth headers mirror AgentHub's clients (Bearer for the OpenAI protocols; x-api-key, Bearer+ * and anthropic-version for ant-messages); a keyless probe sends no credential; the key never+ * reaches a URL or the reported probes.+ * - With no key typed or stored, each probe of a vendor's own URL borrows that protocol's+ * environment variable (ANTHROPIC_* for ant-messages, OPENAI_* for the others), never for any+ * other URL; unset and blank are absent, and a typed key wins.+ * - POST /api/projects/:p/models/detect validates the URL, falls back to the stored key of the+ * paired reference unless clearApiKey says not to, never echoes the key, and never sends+ * vendor environment keys to the Penguin Go relay.+ *+ * No test reaches the network except against a loopback server of its own: the probed endpoint+ * is the suite's fetch fake.*/import { createServer } from "node:http";import type { AddressInfo } from "node:net";import type { IncomingMessage, Server, ServerResponse } from "node:http";-import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";import type { ModelProtocolDetectResponse, ModelsResponse } from "../src/api/types.js";import {MAX_PROBE_BODY_BYTES,@@ -25,6 +38,7 @@ import {isHttpUrl,probeUrl,} from "../src/services/protocol-detect.js";+import { fakeFetch } from "./fixtures/fetch.js";import { apiClient, createTestApp, provisionUser } from "./helpers.js";import type { TestApp } from "./helpers.js";@@ -225,30 +239,23 @@ interface SeenCall {body: string;}-/** Fake fetch serving fixed answers by pathname; unknown paths get an OpenAI-style JSON 404 (like real OpenAI-compatible servers). */-function fakeFetch(+/**+ * The endpoint under probe, over the suite's fetch fake: fixed answers by pathname, and an+ * OpenAI-style JSON 404 for any other path (like real OpenAI-compatible servers). Each request+ * lands in `seen` with its headers as a lower-cased record, so an absent one reads undefined.+ */+function gateway(routes: Record<string, { status: number; body: string }>,seen?: SeenCall[],): typeof fetch {- return (async (input: Parameters<typeof fetch>[0], init?: RequestInit) => {- const url = String(input);- const headers: Record<string, string> = {};- for (const [k, v] of Object.entries((init?.headers ?? {}) as Record<string, string>)) {- headers[k.toLowerCase()] = v;- }- seen?.push({ url, headers, body: String(init?.body ?? "") });- const route = routes[new URL(url).pathname];- if (!route) {- return new Response(OPENAI_ERROR, {- status: 404,- headers: { "content-type": "application/json" },- });- }- return new Response(route.body, {- status: route.status,+ return fakeFetch((call) => {+ seen?.push({ url: call.url, headers: Object.fromEntries(call.headers), body: call.body });+ const route = routes[new URL(call.url).pathname];+ return new Response(route?.body ?? OPENAI_ERROR, {+ status: route?.status ?? 404,headers: { "content-type": "application/json" },});- }) as typeof fetch;+ }).fetch;}describe("detectModelProtocol (order and stop-at-first)", () => {@@ -259,7 +266,7 @@ describe("detectModelProtocol (order and stop-at-first)", () => {const res = await detectModelProtocol({baseUrl: BASE,apiKey: "sk-unit",- fetchImpl: fakeFetch(+ fetchImpl: gateway({"/v1/responses": { status: 401, body: OPENAI_ERROR },"/v1/v1/messages": { status: 401, body: ANTHROPIC_ERROR },@@ -278,7 +285,7 @@ describe("detectModelProtocol (order and stop-at-first)", () => {it("falls through to ant-messages when /responses is missing", async () => {const res = await detectModelProtocol({baseUrl: BASE,- fetchImpl: fakeFetch({+ fetchImpl: gateway({"/v1/v1/messages": { status: 401, body: ANTHROPIC_ERROR },"/v1/chat/completions": { status: 401, body: OPENAI_ERROR },}),@@ -294,7 +301,7 @@ describe("detectModelProtocol (order and stop-at-first)", () => {it("openai-chat is the last resort", async () => {const res = await detectModelProtocol({baseUrl: BASE,- fetchImpl: fakeFetch({+ fetchImpl: gateway({"/v1/chat/completions": { status: 400, body: OPENAI_ERROR },}),});@@ -303,7 +310,7 @@ describe("detectModelProtocol (order and stop-at-first)", () => {});it("nothing matches: no detected protocol, no base URL, and every candidate's probes reported", async () => {- const res = await detectModelProtocol({ baseUrl: BASE, fetchImpl: fakeFetch({}) });+ const res = await detectModelProtocol({ baseUrl: BASE, fetchImpl: gateway({}) });expect(res.detected).toBeUndefined();expect(res.baseUrl).toBeUndefined();expect(res.probes).toHaveLength(candidateBaseUrls(BASE).length * 3);@@ -322,7 +329,7 @@ describe("detectModelProtocol (order and stop-at-first)", () => {it("a pasted endpoint URL detects on the base it strips down to, and reports that base back", async () => {const res = await detectModelProtocol({baseUrl: "https://gw.example.com/v1/chat/completions",- fetchImpl: fakeFetch({ "/v1/chat/completions": { status: 401, body: OPENAI_ERROR } }),+ fetchImpl: gateway({ "/v1/chat/completions": { status: 401, body: OPENAI_ERROR } }),});expect(res.detected).toBe("openai-chat");expect(res.baseUrl).toBe("https://gw.example.com/v1");@@ -337,7 +344,7 @@ describe("detectModelProtocol (order and stop-at-first)", () => {it("a base URL typed without /v1 falls through to the /v1 candidate and reports it", async () => {const res = await detectModelProtocol({baseUrl: "https://gw.example.com",- fetchImpl: fakeFetch({ "/v1/responses": { status: 400, body: OPENAI_ERROR } }),+ fetchImpl: gateway({ "/v1/responses": { status: 400, body: OPENAI_ERROR } }),});expect(res.detected).toBe("openai-responses");expect(res.baseUrl).toBe("https://gw.example.com/v1");@@ -351,8 +358,8 @@ describe("detectModelProtocol (order and stop-at-first)", () => {});it("probe failures do not stop the sequence: a timeout on /responses still finds chat completions", async () => {- const timeoutOnResponses: typeof fetch = (async (input: Parameters<typeof fetch>[0]) => {- const path = new URL(String(input)).pathname;+ const timeoutOnResponses = fakeFetch((call) => {+ const path = new URL(call.url).pathname;if (path === "/v1/responses") {throw new DOMException("The operation timed out", "TimeoutError");}@@ -363,7 +370,7 @@ describe("detectModelProtocol (order and stop-at-first)", () => {status: 401,headers: { "content-type": "application/json" },});- }) as typeof fetch;+ }).fetch;const res = await detectModelProtocol({ baseUrl: BASE, fetchImpl: timeoutOnResponses });expect(res.detected).toBe("openai-chat");expect(res.probes.map((p) => p.outcome)).toEqual(["timeout", "network_error", "served"]);@@ -373,8 +380,8 @@ describe("detectModelProtocol (order and stop-at-first)", () => {// Streams well past MAX_PROBE_BODY_BYTES; the reader must stop at the cap rather than// materialize the whole thing, and the probe must not be credited as served.let pushed = 0;- const flooder: typeof fetch = (async (input: Parameters<typeof fetch>[0]) => {- const path = new URL(String(input)).pathname;+ const flooder = fakeFetch((call) => {+ const path = new URL(call.url).pathname;if (path === "/v1/v1/messages") {return new Response(OPENAI_ERROR, {status: 404,@@ -402,7 +409,7 @@ describe("detectModelProtocol (order and stop-at-first)", () => {}),{ status: 200, headers: { "content-type": "application/json" } },);- }) as typeof fetch;+ }).fetch;const res = await detectModelProtocol({ baseUrl: BASE, fetchImpl: flooder });expect(res.probes[0]?.outcome).toBe("junk");expect(res.detected).toBe("openai-chat");@@ -417,7 +424,7 @@ describe("detectModelProtocol (order and stop-at-first)", () => {await detectModelProtocol({baseUrl: `${BASE}/`, // trailing slash must not double upapiKey: "sk-secret-key",- fetchImpl: fakeFetch({}, seen),+ fetchImpl: gateway({}, seen),});// Nothing serves, so both candidates are probed; the header shapes are asserted on the// first candidate's three calls.@@ -444,7 +451,7 @@ describe("detectModelProtocol (order and stop-at-first)", () => {// Empty env: no key from anywhere, so this stays the genuinely keyless case// regardless of what the machine running the suite happens to export.env: {},- fetchImpl: fakeFetch({ "/v1/responses": { status: 401, body: OPENAI_ERROR } }, seen),+ fetchImpl: gateway({ "/v1/responses": { status: 401, body: OPENAI_ERROR } }, seen),});expect(res.detected).toBe("openai-responses");expect(seen[0]!.headers.authorization).toBeUndefined();@@ -506,7 +513,7 @@ describe("detectModelProtocol env fallback", () => {OPENAI_BASE_URL: BASE,ANTHROPIC_API_KEY: "sk-anthropic",},- fetchImpl: fakeFetch({}, seen), // every path 404s, so both candidates run all three probes+ fetchImpl: gateway({}, seen), // every path 404s, so both candidates run all three probes});expect(seen).toHaveLength(6);for (const call of seen) {@@ -520,7 +527,7 @@ describe("detectModelProtocol env fallback", () => {await detectModelProtocol({baseUrl: "https://api.openai.com/v1",env: { OPENAI_API_KEY: "sk-openai", ANTHROPIC_API_KEY: "sk-anthropic" },- fetchImpl: fakeFetch({}, seen), // every path 404s, so both candidates run all three probes+ fetchImpl: gateway({}, seen), // every path 404s, so both candidates run all three probes});expect(seen).toHaveLength(6);const [responses, messages, chat] = seen as [SeenCall, SeenCall, SeenCall];@@ -547,7 +554,7 @@ describe("detectModelProtocol env fallback", () => {baseUrl: BASE,apiKey: "sk-typed",env: { OPENAI_API_KEY: "sk-openai", ANTHROPIC_API_KEY: "sk-anthropic" },- fetchImpl: fakeFetch({}, seen),+ fetchImpl: gateway({}, seen),});for (const call of seen) expect(call.headers.authorization).toBe("Bearer sk-typed");expect((seen[1] as SeenCall).headers["x-api-key"]).toBe("sk-typed");@@ -558,7 +565,7 @@ describe("detectModelProtocol env fallback", () => {await detectModelProtocol({baseUrl: "https://api.anthropic.com",env: { ANTHROPIC_API_KEY: "sk-anthropic" },- fetchImpl: fakeFetch({}, seen),+ fetchImpl: gateway({}, seen),});const [responses, messages, chat] = seen as [SeenCall, SeenCall, SeenCall];expect(responses.headers.authorization).toBeUndefined();@@ -570,7 +577,7 @@ describe("detectModelProtocol env fallback", () => {const res = await detectModelProtocol({baseUrl: "https://api.openai.com/v1",env: { OPENAI_API_KEY: "sk-openai", ANTHROPIC_API_KEY: "sk-anthropic" },- fetchImpl: fakeFetch({ "/v1/responses": { status: 401, body: OPENAI_ERROR } }),+ fetchImpl: gateway({ "/v1/responses": { status: 401, body: OPENAI_ERROR } }),});expect(res.detected).toBe("openai-responses");expect(JSON.stringify(res)).not.toContain("sk-openai");@@ -612,18 +619,27 @@ describe("POST /api/projects/:p/models/detect", () => {let projectId: string;const detectUrl = () => `/api/projects/${projectId}/models/detect`;- beforeEach(async () => {+ beforeAll(async () => {t = await createTestApp();const { cookie } = await provisionUser(t.app, "diana");api = apiClient(t.app, cookie);+ });+ afterAll(async () => {+ await t.cleanup();+ });++ // Every case works in a Project of its own.+ let projects = 0;+ beforeEach(async () => {+ projects += 1;const created = (await (- await api.post("/api/projects", { projectId: "diana-detect", name: "Detect project" })+ await api.post("/api/projects", {+ projectId: `diana-detect_${projects}`,+ name: "Detect project",+ })).json()) as { project: { projectId: string } };projectId = created.project.projectId;});- afterEach(async () => {- await t.cleanup();- });it("validates baseUrl: required and absolute http(s)", async () => {expect((await api.post(detectUrl(), {})).status).toBe(400);