A local-first multi-agent app development platform, built on PenguinHarness
test(server): cut the real waits and per-case apps in the remaining suites (#933)
Yaowei Zhengcb241dd96784
diff --git a/packages/server/test/builtin-browser/page-scripts.test.ts b/packages/server/test/builtin-browser/page-scripts.test.tsindex 8534c768..d5bd6b42 100644--- a/packages/server/test/builtin-browser/page-scripts.test.ts+++ b/packages/server/test/builtin-browser/page-scripts.test.ts@@ -1,11 +1,17 @@/**- * The page scripts. Every script parses (always). Then, when a Chromium is at hand — a- * Playwright download, or PENGUIN_TEST_CHROMIUM — they run for real: a headless Chromium is- * driven over its DevTools socket through the same link, driver and actions the routes use,- * with a small fake shell in between that forwards `cdp` to the page. A fixture page has- * visible and hidden text, a long list, a toast, a field and a form, so the port is checked on- * what GenericAgent's own behaviour hinges on: hidden elements dropped, the list folded to a- * `[FAKE ELEMENT]` hint, truncation to the budget, a trusted click, transients and the diff.+ * The page scripts: the half of the built-in browser that runs inside the page.+ *+ * - Every script parses as the driver wraps it, always; exec's rules that need no page run in+ * Node: the outcome as JSON text, the explicit return or else the last expression, a last+ * line that returns after a statement, a return inside a callback, a string or a comment.+ * - Given a Chromium (a Playwright download, or PENGUIN_TEST_CHROMIUM) they run for real, over+ * its DevTools socket through the same link, driver and actions the routes use, a small fake+ * shell forwarding `cdp` to the page: a scan keeps the visible page, folds the long list to a+ * `[FAKE ELEMENT]` hint (keeping the items that match the instruction), drops what is hidden,+ * truncates to the budget and never makes the page load a shortened address; scripts run+ * GenericAgent's way; a script's change and a toast that came and went are reported; typing+ * and a trusted click land; dialogs are answered; a navigation is a reload; a page that+ * enforces Trusted Types and forbids eval still works; screenshots are taken.*/import { spawn } from "node:child_process";import type { ChildProcess } from "node:child_process";@@ -144,6 +150,16 @@ function findChromium(): string | null {const CHROMIUM = findChromium();+/**+ * The pause after an action before the page is measured. The product waits a second+ * (GenericAgent's sleep(1)) for a real site to react; these fixture pages react at once, so a+ * shorter window measures the same diff. Transients are the exception: the monitor samples the+ * page's text every 450 ms, so a toast has to outlive one sample and be gone before the+ * product's own second is up, and that case runs on the product's timing.+ */+const SETTLE_MS = 300;+const TOAST_MS = 700;+type CdpEventListener = (method: string,params: Record<string, unknown>,@@ -297,7 +313,7 @@ ${Array.from(const t = document.createElement('div');t.textContent = 'Added to cart successfully';document.body.appendChild(t);- setTimeout(() => t.remove(), 700);+ setTimeout(() => t.remove(), ${TOAST_MS});});document.getElementById('f').addEventListener('submit', (event) => {event.preventDefault();@@ -411,7 +427,11 @@ describe.skipIf(CHROMIUM === null)("page scripts in a real Chromium", () => {);link = new ShellLink(new ForwardingPort(cdp, sessionId));driver = new BrowserDriver(link);- actions = new BrowserActions({ driver, tabs: new TabRegistry(), timing: { popupClaimMs: 0 } });+ actions = new BrowserActions({+ driver,+ tabs: new TabRegistry(),+ timing: { popupClaimMs: 0, settleMs: SETTLE_MS },+ });}, 60_000);afterAll(async () => {@@ -520,14 +540,20 @@ describe.skipIf(CHROMIUM === null)("page scripts in a real Chromium", () => {expect(changed.diff?.changed).toBeGreaterThan(0);expect(changed.diff?.topChange).toContain("Changed by the script");- const toast = await actions.exec(TAB, "document.getElementById('toast').click()");+ // The product's own settle, so the monitor's sampling catches the toast in between.+ const monitored = new BrowserActions({+ driver,+ tabs: new TabRegistry(),+ timing: { popupClaimMs: 0 },+ });+ const toast = await monitored.exec(TAB, "document.getElementById('toast').click()");expect(toast.transients).toContain("Added to cart successfully");// A longer message is reported with its first 80 characters.const message ="Your order of wireless headphones has shipped and should arrive by Thursday, 2 October, at your door";- const shipped = await actions.exec(+ const shipped = await monitored.exec(TAB,- `const t = document.createElement('div');\nt.textContent = ${JSON.stringify(message)};\ndocument.body.appendChild(t);\nsetTimeout(() => t.remove(), 700);\nreturn 1`,+ `const t = document.createElement('div');\nt.textContent = ${JSON.stringify(message)};\ndocument.body.appendChild(t);\nsetTimeout(() => t.remove(), ${TOAST_MS});\nreturn 1`,);expect(shipped.transients).toContain(message.slice(0, 80));diff --git a/packages/server/test/machines-transport-session.test.ts b/packages/server/test/machines-transport-session.test.tsindex 2edd79a6..98a243c2 100644--- a/packages/server/test/machines-transport-session.test.ts+++ b/packages/server/test/machines-transport-session.test.ts@@ -1,12 +1,22 @@/*** The one connection per machine, against a stub `ssh` on PATH that becomes a real `sh` when- * asked for one: the framing, the heredoc input, progress relayed as it arrives, one session- * however many ask, and what a session that dies says.+ * asked for one (POSIX only).+ *+ * - Commands run with their exit code, and an `exit` cannot end the session.+ * - A command gets its stdin as a heredoc, bytes intact, and its lines are relayed as they+ * arrive.+ * - There is one session however many ask: commands to one machine queue, two opens spawn+ * once, and different machines run side by side.+ * - A session that dies says why in ssh's own words and is not kept.+ * - A command that outlasts its timeout answers with the timeout, and the next one gets a+ * live session; on a held session the corpse is dropped but the hold kept.+ * - A held session that dies comes back on its own after the shortest reconnect wait; a+ * closed one stays closed; closing lets go, and the next ask opens a new session.*/import fs from "node:fs";import os from "node:os";import path from "node:path";-import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { closeConnectionTo, connectionTo, sessionOf } from "../src/machines/transport/index.js";const posixOnly = process.platform === "win32" ? describe.skip : describe;@@ -105,37 +115,50 @@ exit 1});it("a held session that dies comes back on its own; a closed one stays closed", async () => {- const conn = connectionTo({ alias: "nas", user: "deploy" });- const held = await conn.hold();- expect(held.ok).toBe(true);- expect(conn.held()).toBe(true);- const first = sessionOf("ssh:nas")!.pid;+ // The reopen wait is a timer and the clock is the test's: the reconnect and the silence+ // after a close are advanced to, not waited out. The child processes stay real, so what+ // they do is waited for by turning the event loop, never by a timer.+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });+ const until = async (condition: () => boolean, what: string): Promise<void> => {+ const deadline = Date.now() + 5_000;+ while (!condition()) {+ if (Date.now() > deadline) throw new Error(`timed out waiting for ${what}`);+ await new Promise((resolve) => setImmediate(resolve));+ }+ };+ try {+ const conn = connectionTo({ alias: "nas", user: "deploy" });+ const held = await conn.hold();+ expect(held.ok).toBe(true);+ expect(conn.held()).toBe(true);+ const first = sessionOf("ssh:nas")!.pid;- // The link drops — the ssh child is gone, as after keepalives give up on a dead link.- process.kill(first);- await new Promise((resolve) => setTimeout(resolve, 100));- expect(sessionOf("ssh:nas")).toBeNull();- // Held, so the transport brings it back: the shortest wait is a second.- const deadline = Date.now() + 5_000;- while (sessionOf("ssh:nas") === null && Date.now() < deadline) {- await new Promise((resolve) => setTimeout(resolve, 100));- }- const second = sessionOf("ssh:nas");- expect(second).not.toBeNull();- expect(second!.pid).not.toBe(first);- // And it is a working session, still held. The spawn count is read only after a command- // has completed over it: the stub logs its own invocation from inside the child, after- // spawn() has already returned a pid, so a session can exist before its line is there.- expect(await conn.exec("echo back")).toMatchObject({ code: 0, stdout: "back\n" });- expect(spawns()).toHaveLength(2);- expect(conn.held()).toBe(true);+ // The link drops — the ssh child is gone, as after keepalives give up on a dead link.+ process.kill(first);+ await until(() => sessionOf("ssh:nas") === null, "the session to drop");+ // Held, so the transport brings it back after the shortest wait, a second.+ await vi.advanceTimersByTimeAsync(999);+ expect(sessionOf("ssh:nas")).toBeNull();+ await vi.advanceTimersByTimeAsync(1);+ await until(() => sessionOf("ssh:nas") !== null, "the session to come back");+ const second = sessionOf("ssh:nas");+ expect(second!.pid).not.toBe(first);+ // And it is a working session, still held. The spawn count is read only after a command+ // has completed over it: the stub logs its own invocation from inside the child, after+ // spawn() has already returned a pid, so a session can exist before its line is there.+ expect(await conn.exec("echo back")).toMatchObject({ code: 0, stdout: "back\n" });+ expect(spawns()).toHaveLength(2);+ expect(conn.held()).toBe(true);- // An explicit close lets go for good: nothing reopens it.- closeConnectionTo("ssh:nas");- expect(conn.held()).toBe(false);- await new Promise((resolve) => setTimeout(resolve, 1_500));- expect(sessionOf("ssh:nas")).toBeNull();- expect(spawns()).toHaveLength(2);+ // An explicit close lets go for good: past every reopen wait, nothing reopens it.+ closeConnectionTo("ssh:nas");+ expect(conn.held()).toBe(false);+ await vi.advanceTimersByTimeAsync(120_000);+ expect(sessionOf("ssh:nas")).toBeNull();+ expect(spawns()).toHaveLength(2);+ } finally {+ vi.useRealTimers();+ }});it("a command that times out on a held session drops the corpse but keeps the hold", async () => {diff --git a/packages/server/test/organizations-routes.test.ts b/packages/server/test/organizations-routes.test.tsindex 4fc34c44..18414f6e 100644--- a/packages/server/test/organizations-routes.test.ts+++ b/packages/server/test/organizations-routes.test.ts@@ -1,18 +1,23 @@/**- * Organization routes over the real app: the admin master switch starts off, 404s the whole- * group while it is off, and is reported by /api/me and /api/admin/settings; Project- * authorization gates reads and writes (an outsider gets 404, a member may write) and only- * the owner deletes an organization; bodies are validated before the service is asked; and the- * calling session and employee ride write bodies as `sessionId` / `agentId` (a read's query- * string), but only from the control environment's API token — a signed-in member's claim is- * dropped. The service itself is a recording fake here — its semantics have their- * own suites — so no Agent is created and no session runs. The one exception is the sessions- * route's desk mark, which is wiring rather than semantics: an organization written straight to- * disk is served by the real service, and a desk's enabled messaging binding has to reach its- * row from the real bindings table.+ * Organization routes over the real app. The service is a recording fake — its semantics have+ * their own suites — so no Agent is created and no Session runs, except in the sessions-route+ * case, which is wiring rather than semantics.+ *+ * - The admin master switch starts off; while it is off every route answers 404+ * company_mode_off, and /api/me and /api/admin/settings report it.+ * - Project authorization gates the group: an outsider gets 404, a member reads and writes, and+ * only the owner deletes an organization (pausing stays a setting any writer may change).+ * - Bodies are validated before the service is asked: organizations, tickets (owner and slug+ * included), handbook documents by their relative path, the channel family and its members.+ * - The organization's language, a ticket's owner and slug, and the channel of the path reach+ * the service.+ * - The calling session and employee ride a read's query and a write's body only from the+ * control environment's API token; a signed-in member's claim is dropped.+ * - The sessions route marks a desk whose Session has an enabled messaging binding, read from+ * the real bindings table for an organization written straight to disk.*/import path from "node:path";-import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";import type {MeResponse,OrgSessionsResponse,@@ -97,26 +102,29 @@ function fromSession(t: TestApp, apiPath: string, body: unknown) {describe("organization routes", () => {let t: TestApp;- let calls: Call[];+ const calls: Call[] = [];let owner: ReturnType<typeof apiClient>;- let ownerProject: string;+ const ownerProject = "olivia-default_project";- beforeEach(async () => {- calls = [];- // The service is a recording fake: it goes in as a boot override, since the route- // group takes the one the module tree provides at creation.+ // One app serves the group. The service is a recording fake: it goes in as a boot override,+ // since the route group takes the one the module tree provides at creation.+ beforeAll(async () => {t = await createTestApp({ orgService: fakeService(calls) });- // Company mode is off on a server nobody turned it on (its own test below): every case- // here is about what the routes do once an admin has enabled it.- t.deps.serverSettingsRepo.setCompanyMode(true);- const u = await provisionUser(t.app, "olivia");- owner = apiClient(t.app, u.cookie);- ownerProject = "olivia-default_project";+ owner = apiClient(t.app, (await provisionUser(t.app, "olivia")).cookie);+ // The control environment's credential is the admin's: it joins the Project the CLI+ // writes to, as the Session-attribution cases below need.+ const grant = await owner.post(`/api/projects/${ownerProject}/members`, { userId: "admin" });+ expect([200, 201]).toContain(grant.status);});-- afterEach(async () => {+ afterAll(async () => {await t.cleanup();});+ beforeEach(() => {+ calls.length = 0;+ // Company mode is off on a server nobody turned it on (its own case below): every other+ // case is about what the routes do once an admin has enabled it.+ t.deps.serverSettingsRepo.setCompanyMode(true);+ });it("is off on a server whose admin never touched the switch", async () => {const fresh = await createTestApp();@@ -189,10 +197,10 @@ describe("organization routes", () => {// A Project-level management operation, like deleting an Agent: a member who can write// everything else in the organization cannot make it go away.const path = `/api/projects/${ownerProject}/organizations/acme`;- const mia = await provisionUser(t.app, "mia");- await owner.post(`/api/projects/${ownerProject}/members`, { userId: "mia" });+ const mira = await provisionUser(t.app, "mira");+ await owner.post(`/api/projects/${ownerProject}/members`, { userId: "mira" });calls.length = 0;- expect((await apiClient(t.app, mia.cookie).delete(path)).status).toBe(403);+ expect((await apiClient(t.app, mira.cookie).delete(path)).status).toBe(403);expect(calls).toEqual([]);expect((await owner.delete(path)).status).toBe(204);expect(calls.at(-1)).toEqual({ method: "delete", args: [ownerProject, "acme"] });@@ -437,9 +445,6 @@ describe("organization routes", () => {it("honours a read's sessionId only from the control environment", async () => {const base = `/api/projects/${ownerProject}/organizations/acme/channels`;- expect([200, 201]).toContain(- (await owner.post(`/api/projects/${ownerProject}/members`, { userId: "admin" })).status,- );const res = await t.app.request(`${base}?sessionId=session-desk&agentId=acme_dev`, {headers: { authorization: `Bearer ${t.deps.authService.localApiToken()}` },});@@ -462,9 +467,6 @@ describe("organization routes", () => {it("passes the calling session through write bodies so the file records the employee", async () => {const base = `/api/projects/${ownerProject}/organizations/acme/tickets/2026-09-01-site`;- // The control environment's credential: the admin joins the Project the CLI writes to.- const grant = await owner.post(`/api/projects/${ownerProject}/members`, { userId: "admin" });- expect([200, 201]).toContain(grant.status);const res = await fromSession(t, `${base}/progress`, {text: "half done",sessionId: "session-desk",diff --git a/packages/server/test/terminal-relay.test.ts b/packages/server/test/terminal-relay.test.tsindex 35437057..ce5a3ea8 100644--- a/packages/server/test/terminal-relay.test.ts+++ b/packages/server/test/terminal-relay.test.ts@@ -1,11 +1,18 @@/**- * A pty on a machine is named in the terminal id (machines/terminal-relay.ts).+ * A pty on a machine, reached through this server (machines/terminal-relay.ts).** The runtime serves one socket path and asks the platform for the session by id, so the- * whole of "which machine, which pty, which user" has to fit in that id. Pinned: the spelling- * round-trips, an ordinary id is never mistaken for a remote one, and the owner the runtime- * checks is exactly the user the client named — which is what makes naming anyone else- * refusable before the relay runs.+ * whole of "which machine, which pty, which user" has to fit in that id:+ * - The `<terminalId>@<machineId>@<userId>` spelling round-trips (a percent-encoded separator+ * included); a plain local id, or anything half-spelled, is never read as a remote one; the+ * owner the runtime checks is exactly the user the client named, so naming anyone else is+ * refusable before the relay runs.+ *+ * The relay itself:+ * - A viewer that left while the machine was being reached dials nobody, so no stream is left+ * attached to a pty over there with no reader.+ * - Frames typed before the machine's stream opened are held and delivered, and the machine's+ * output reaches the viewer once both ends are up.*/import { afterEach, beforeEach, describe, expect, it } from "vitest";import { EventEmitter, once } from "node:events";@@ -113,8 +120,9 @@ describe("relaying a viewer to a machine's stream", () => {isAdmin: () => true,});- const settle = async (predicate: () => boolean): Promise<void> => {- for (let attempt = 0; attempt < 100; attempt += 1) {+ /** Waits for `predicate`, giving up after `attempts` × 10 ms. */+ const settle = async (predicate: () => boolean, attempts = 100): Promise<void> => {+ for (let attempt = 0; attempt < attempts; attempt += 1) {if (predicate()) return;await new Promise((resolve) => setTimeout(resolve, 10));}@@ -137,7 +145,9 @@ describe("relaying a viewer to a machine's stream", () => {viewer.drop();reached({ agent: new http.Agent(), port: machinePort, cookie: "" });await relaying;- await settle(() => accepted.length > 0);+ // No event marks a dial that never happens; one to this loopback server is accepted within+ // a few milliseconds, so a quarter of a second of quiet is the proof.+ await settle(() => accepted.length > 0, 25);// Nothing was opened, so nothing is attached to a pty over there with no reader. Before// the viewer's close was listened to from the start, this left one stream per pane.expect(accepted).toHaveLength(0);diff --git a/packages/server/test/workspace-files.test.ts b/packages/server/test/workspace-files.test.tsindex f3836b7d..33f3da9f 100644--- a/packages/server/test/workspace-files.test.ts+++ b/packages/server/test/workspace-files.test.ts@@ -1,13 +1,40 @@/**- * Unit tests for the Workspace files service: directory-listing order, read/write,- * move / delete / search, path confinement (`..` traversal and symlink escape), size-limit- * protection, batch existence checks (files/stat); the desktop-only files/reveal route; and- * the Agent delete route (default_agent cannot be deleted, owner-only, directory and index- * cleanup).+ * A Session's Workspace files: the service and the routes over it.+ *+ * The service:+ * - Listings put directories first, sorted by name, and drill into subdirectories (a Workspace+ * at the filesystem root included); reads carry content and type; writes overwrite and create+ * missing parents; `..`, absolute paths and symlink escapes are refused, as are files past the+ * size limit.+ * - A write, move or delete holds to the version marker a read returned: a stale one changes+ * nothing, no marker only creates a file that was never there, and a directory has none.+ * - A move renames, crosses directories and creates the destination parent, refusing an+ * occupied destination, a missing source and its own path; a delete refuses a directory and a+ * missing file.+ * - A search finds a file no listing reached, reported as a tree row, by name rather than path,+ * shallow matches and directories first, capped and saying so; an empty or oversize query is+ * refused.+ *+ * The routes:+ * - files/content serves HTML as text/plain inline, as text/html under a CSP sandbox for a+ * preview and with its real type for a download; SVG inline under a sandbox CSP; never cached;+ * the read's version is demanded back, so a save over an Agent's rewrite is a 409.+ * - files/stat answers existing paths in order, deduplicated, counting missing, directory and+ * out-of-bounds paths as absent, always 200; malformed bodies are 400.+ * - files/move, files/search and the files/content delete behave as the service does (409+ * target_exists, 409 file_changed); outsiders get 404 everywhere, with no Workspace touched.+ * - Deleting an Agent removes its directory and list entry; default_agent is a 409; outsiders+ * get 404.+ * - files/reveal opens the canonical path for the desktop shell's own window only (a browser+ * session is desktop_shell_only; outside desktop mode the route does not exist), resolves the+ * path as a read does, and reports an opener that cannot start as 502 reveal_failed.+ *+ * The route describes share one app and one Project, every case working in a Session (and so a+ * Workspace) of its own; the desktop-mode reveal cases share one desktop app.*/import fs 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 } from "vitest";import {SEARCH_MAX_HITS,SEARCH_MAX_QUERY_LEN,@@ -435,38 +462,50 @@ describe("workspace-files-service", () => {});});+/**+ * The route describes' app: an owner whose Project has a model configured, and an outsider.+ * Every case works in a Session of its own, and so in a Workspace of its own.+ */+let t: TestApp;+let owner: ReturnType<typeof apiClient>;+let outsider: ReturnType<typeof apiClient>;+let projectId: string;++beforeAll(async () => {+ t = await createTestApp();+ owner = apiClient(t.app, (await provisionUser(t.app, "owner")).cookie);+ outsider = apiClient(t.app, (await provisionUser(t.app, "outsider")).cookie);+ const created = (await (+ await owner.post("/api/projects", { projectId: "owner-ws", name: "project" })+ ).json()) as ProjectCreateResponse;+ projectId = created.project.projectId;+ await owner.put(`/api/projects/${projectId}/models`, {+ defaultModel: { provider: "anthropic", modelId: "claude-sonnet-4-6" },+ models: [{ provider: "anthropic", modelId: "claude-sonnet-4-6", contextWindow: 128000 }],+ });+});+afterAll(async () => {+ await t.cleanup();+});++/** A new Session of the owner's, its Workspace holding a.txt and sub/b.md. */+async function sessionWithFiles(): Promise<{ sessionId: string; workspace: string }> {+ const sess = (await (+ await owner.post(`/api/projects/${projectId}/agents/default_agent/sessions`, {})+ ).json()) as SessionCreateResponse;+ const workspace = sess.session.workspace;+ await fs.mkdir(path.join(workspace, "sub"));+ await fs.writeFile(path.join(workspace, "a.txt"), "A");+ await fs.writeFile(path.join(workspace, "sub", "b.md"), "B");+ return { sessionId: sess.session.sessionId, workspace };+}+describe("files/stat route (batch existence check)", () => {- let t: TestApp;- let owner: ReturnType<typeof apiClient>;- let outsider: ReturnType<typeof apiClient>;let sessionId: string;let workspace: string;beforeEach(async () => {- t = await createTestApp();- const a = await provisionUser(t.app, "owner");- const b = await provisionUser(t.app, "outsider");- owner = apiClient(t.app, a.cookie);- outsider = apiClient(t.app, b.cookie);- const created = (await (- await owner.post("/api/projects", { projectId: "owner-stat", name: "project" })- ).json()) as ProjectCreateResponse;- const projectId = created.project.projectId;- await owner.put(`/api/projects/${projectId}/models`, {- defaultModel: { provider: "anthropic", modelId: "claude-sonnet-4-6" },- models: [{ provider: "anthropic", modelId: "claude-sonnet-4-6", contextWindow: 128000 }],- });- const sess = (await (- await owner.post(`/api/projects/${projectId}/agents/default_agent/sessions`, {})- ).json()) as SessionCreateResponse;- sessionId = sess.session.sessionId;- workspace = sess.session.workspace;- await fs.mkdir(path.join(sess.session.workspace, "sub"));- await fs.writeFile(path.join(sess.session.workspace, "a.txt"), "A");- await fs.writeFile(path.join(sess.session.workspace, "sub", "b.md"), "B");- });- afterEach(async () => {- await t.cleanup();+ ({ sessionId, workspace } = await sessionWithFiles());});it("files/content on html: inline stays text/plain; preview=1 keeps text/html under a CSP sandbox; download keeps the real type with no CSP", async () => {@@ -604,37 +643,11 @@ describe("files/stat route (batch existence check)", () => {});describe("files/move, files/search and the files/content delete", () => {- let t: TestApp;- let owner: ReturnType<typeof apiClient>;- let outsider: ReturnType<typeof apiClient>;let sessionId: string;let workspace: string;beforeEach(async () => {- t = await createTestApp();- const a = await provisionUser(t.app, "owner");- const b = await provisionUser(t.app, "outsider");- owner = apiClient(t.app, a.cookie);- outsider = apiClient(t.app, b.cookie);- const created = (await (- await owner.post("/api/projects", { projectId: "owner-ops", name: "project" })- ).json()) as ProjectCreateResponse;- const projectId = created.project.projectId;- await owner.put(`/api/projects/${projectId}/models`, {- defaultModel: { provider: "anthropic", modelId: "claude-sonnet-4-6" },- models: [{ provider: "anthropic", modelId: "claude-sonnet-4-6", contextWindow: 128000 }],- });- const sess = (await (- await owner.post(`/api/projects/${projectId}/agents/default_agent/sessions`, {})- ).json()) as SessionCreateResponse;- sessionId = sess.session.sessionId;- workspace = sess.session.workspace;- await fs.mkdir(path.join(workspace, "sub"));- await fs.writeFile(path.join(workspace, "a.txt"), "A");- await fs.writeFile(path.join(workspace, "sub", "b.md"), "B");- });- afterEach(async () => {- await t.cleanup();+ ({ sessionId, workspace } = await sessionWithFiles());});it("files/move: 204 and the file is where it was sent; an occupied destination is 409 target_exists; a directory is a 400", async () => {@@ -730,29 +743,16 @@ describe("files/move, files/search and the files/content delete", () => {});describe("agent delete route", () => {- let t: TestApp;- let owner: ReturnType<typeof apiClient>;- let outsider: ReturnType<typeof apiClient>;- let projectId: string;-- beforeEach(async () => {- t = await createTestApp();- const a = await provisionUser(t.app, "owner");- const b = await provisionUser(t.app, "outsider");- owner = apiClient(t.app, a.cookie);- outsider = apiClient(t.app, b.cookie);- const created = (await (- await owner.post("/api/projects", { projectId: "owner-ws", name: "project" })- ).json()) as ProjectCreateResponse;- projectId = created.project.projectId;- });- afterEach(async () => {- await t.cleanup();- });+ // A name per attempt: the Project is the file's, so a retry must not meet its own Agent.+ let temps = 0;it("owner deletes an Agent: 204, the directory and list entry disappear; default_agent 409; outsiders 404", async () => {+ temps += 1;const created = (await (- await owner.post(`/api/projects/${projectId}/agents`, { agentId: "temp_agent", name: "temp" })+ await owner.post(`/api/projects/${projectId}/agents`, {+ agentId: `temp_agent_${temps}`,+ name: "temp",+ })).json()) as AgentCreateResponse;const agentId = created.agent.agentId;const dir = path.join(t.root, projectId, "agents", agentId);@@ -795,50 +795,48 @@ describe("files/reveal route (the desktop shell's own window)", () => {return { cookie: admin.cookie, sessionId: session.sessionId, workspace: session.workspace };}+ // One desktop-mode app for the cases that need one; each case sets what its opener does.+ let desktop: TestApp;+ let shell: ReturnType<typeof apiClient>;+ let revealed: string[];+ let opener: (filePath: string) => Promise<void>;++ beforeAll(async () => {+ desktop = await createDesktopApp({ reveal: (filePath) => opener(filePath) });+ shell = apiClient(desktop.app, await desktopLoginCookie(desktop.app));+ });+ afterAll(async () => {+ await desktop.cleanup();+ });+ beforeEach(() => {+ revealed = [];+ opener = async (filePath) => {+ revealed.push(filePath);+ };+ });+it("opens the file for the shell's own window: 204, and the opener is handed the canonical path", async () => {- const revealed: string[] = [];- const t = await createDesktopApp({- reveal: async (filePath) => {- revealed.push(filePath);- },- });- try {- const { sessionId, workspace } = await seedSession(t);- const shell = apiClient(t.app, await desktopLoginCookie(t.app));- const res = await shell.post(`/api/sessions/${sessionId}/files/reveal?path=a.txt`);- expect(res.status).toBe(204);- expect(await res.text()).toBe("");- // The absolute path the OS can act on, with every symlink already resolved away.- expect(revealed).toEqual([await fs.realpath(path.join(workspace, "a.txt"))]);- } finally {- await t.cleanup();- }+ const { sessionId, workspace } = await seedSession(desktop);+ const res = await shell.post(`/api/sessions/${sessionId}/files/reveal?path=a.txt`);+ expect(res.status).toBe(204);+ expect(await res.text()).toBe("");+ // The absolute path the OS can act on, with every symlink already resolved away.+ expect(revealed).toEqual([await fs.realpath(path.join(workspace, "a.txt"))]);});it("refuses a browser session on the same desktop-mode server with desktop_shell_only", async () => {- const revealed: string[] = [];- const t = await createDesktopApp({- reveal: async (filePath) => {- revealed.push(filePath);- },- });- try {- const { cookie, sessionId } = await seedSession(t);- // The seeded admin signed in through the login form: the same user, the same machine- // for all the server knows, and still not the window the shell is drawing.- const res = await apiClient(t.app, cookie).post(- `/api/sessions/${sessionId}/files/reveal?path=a.txt`,- );- expect(res.status).toBe(403);- expect(((await res.json()) as ErrorBody).error.code).toBe("desktop_shell_only");- expect(revealed).toEqual([]);- } finally {- await t.cleanup();- }+ const { cookie, sessionId } = await seedSession(desktop);+ // The seeded admin signed in through the login form: the same user, the same machine+ // for all the server knows, and still not the window the shell is drawing.+ const res = await apiClient(desktop.app, cookie).post(+ `/api/sessions/${sessionId}/files/reveal?path=a.txt`,+ );+ expect(res.status).toBe(403);+ expect(((await res.json()) as ErrorBody).error.code).toBe("desktop_shell_only");+ expect(revealed).toEqual([]);});it("does not exist outside desktop mode", async () => {- const revealed: string[] = [];const t = await createTestApp({reveal: async (filePath) => {revealed.push(filePath);@@ -858,42 +856,24 @@ describe("files/reveal route (the desktop shell's own window)", () => {});it("resolves the path as a read does: `..` is a 400 and a missing file a 404, with nothing opened", async () => {- const revealed: string[] = [];- const t = await createDesktopApp({- reveal: async (filePath) => {- revealed.push(filePath);- },- });- try {- const { sessionId } = await seedSession(t);- const shell = apiClient(t.app, await desktopLoginCookie(t.app));- const escape = await shell.post(- `/api/sessions/${sessionId}/files/reveal?path=${encodeURIComponent("../secret.txt")}`,- );- expect(escape.status).toBe(400);- const missing = await shell.post(`/api/sessions/${sessionId}/files/reveal?path=nope.txt`);- expect(missing.status).toBe(404);- expect(((await missing.json()) as ErrorBody).error.code).toBe("path_not_found");- expect(revealed).toEqual([]);- } finally {- await t.cleanup();- }+ const { sessionId } = await seedSession(desktop);+ const escape = await shell.post(+ `/api/sessions/${sessionId}/files/reveal?path=${encodeURIComponent("../secret.txt")}`,+ );+ expect(escape.status).toBe(400);+ const missing = await shell.post(`/api/sessions/${sessionId}/files/reveal?path=nope.txt`);+ expect(missing.status).toBe(404);+ expect(((await missing.json()) as ErrorBody).error.code).toBe("path_not_found");+ expect(revealed).toEqual([]);});it("reports an opener that cannot start as 502 reveal_failed", async () => {- const t = await createDesktopApp({- reveal: () => Promise.reject(new Error("spawn xdg-open ENOENT")),- });- try {- const { sessionId } = await seedSession(t);- const shell = apiClient(t.app, await desktopLoginCookie(t.app));- const res = await shell.post(`/api/sessions/${sessionId}/files/reveal?path=a.txt`);- expect(res.status).toBe(502);- const body = (await res.json()) as ErrorBody;- expect(body.error.code).toBe("reveal_failed");- expect(body.error.message).toContain("ENOENT");- } finally {- await t.cleanup();- }+ opener = () => Promise.reject(new Error("spawn xdg-open ENOENT"));+ const { sessionId } = await seedSession(desktop);+ const res = await shell.post(`/api/sessions/${sessionId}/files/reveal?path=a.txt`);+ expect(res.status).toBe(502);+ const body = (await res.json()) as ErrorBody;+ expect(body.error.code).toBe("reveal_failed");+ expect(body.error.message).toContain("ENOENT");});});diff --git a/packages/server/test/workspace-preview.test.ts b/packages/server/test/workspace-preview.test.tsindex c95f1e3c..2fb5e753 100644--- a/packages/server/test/workspace-preview.test.ts+++ b/packages/server/test/workspace-preview.test.ts@@ -1,14 +1,25 @@/**- * Workspace HTML preview on the separate preview origin: token signing/verification,- * the mint endpoint's origin derivation, and the preview route.+ * Workspace HTML preview on a separate preview origin.*- * The load-bearing case is "same token, App origin's Host": the preview route answers on- * the same process as the App, so if it served Agent-written HTML there, it would be a- * same-origin XSS with the session cookie attached.+ * The load-bearing case is "same token, App origin's Host": the preview route answers in the+ * App's process, so if it served Agent-written HTML there it would be a same-origin XSS with+ * the session cookie attached.+ *+ * - A preview token round-trips, and a tampered, foreign-signed, malformed or expired one is+ * refused.+ * - The preview origin is the loopback counterpart of the App's host on the server's own port+ * (IPv6 brackets kept, fixed roles only for loopback binds); none while the port is still 0 or+ * when the counterpart is unreachable from the bind; a configured origin wins, unless it is+ * the App request's own host.+ * - The route redirects to the counterpart, serves the file with its real type, no sandbox and+ * no referrer, resolves relative subresources under the same token, refuses the App origin's+ * host, refuses a garbage token and keeps path confinement, and serves nothing but /preview on+ * the preview host; minting needs a session and a valid path; /api/me reports isolation; a+ * configured origin turns the loopback guard off.*/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 {createPreviewTokenSigner,hostOnly,@@ -179,13 +190,22 @@ describe("preview route", () => {let sessionId: string;let workspace: string;- beforeEach(async () => {+ beforeAll(async () => {t = await createTestApp();const a = await provisionUser(t.app, "owner");owner = apiClient(t.app, a.cookie);ownerCookie = 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-preview", name: "project" })+ await owner.post("/api/projects", { projectId: `owner-preview_${projects}`, name: "project" })).json()) as ProjectCreateResponse;const projectId = created.project.projectId;await owner.put(`/api/projects/${projectId}/models`, {@@ -201,9 +221,6 @@ describe("preview route", () => {await fs.writeFile(path.join(workspace, "index.html"), "<!doctype html><script src=app.js>");await fs.writeFile(path.join(workspace, "assets", "app.js"), "console.log(1)");});- afterEach(async () => {- await t.cleanup();- });/*** Follow the "open in a new tab" link the way a browser would; app.request() addresses