Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

test(server): slim the session runtime suites onto one Session fake (#926)

Yaowei Zhengfe0243b5c6b3
diff --git a/packages/server/test/abort-compaction.test.ts b/packages/server/test/abort-compaction.test.ts
index 0a48059d..7a035c4e 100644
--- a/packages/server/test/abort-compaction.test.ts
+++ b/packages/server/test/abort-compaction.test.ts
@@ -1,24 +1,22 @@
/**
* POST /api/sessions/:id/abort while a **compaction** is in flight.
*
- * The composer's Stop button used to be gated on the Session being `running`, so a
- * compacting Session showed a disabled Send instead and a compaction could not be
- * interrupted from the Web App. The button was the whole of that bug — this file pins the
- * half underneath it, so a future change cannot quietly make the server the problem too:
- * the abort route does not care which non-idle state the Session is in, and the signal it
- * fires reaches the compaction (the runtime's `compact` generator sees it and finishes),
- * returning the Session to idle.
+ * The composer's Stop button used to be gated on the Session being `running`, so a compacting
+ * Session could not be interrupted from the Web App. This file pins the half underneath that
+ * button: the abort route does not care which non-idle state the Session is in, and the signal
+ * it fires reaches the compaction.
+ *
+ * - Given a compacting Session, an abort answers 202, the compaction sees the signal and ends
+ * `aborted` (the original context kept), and the Session goes idle.
+ * - Given an idle Session, an abort answers 204 and starts nothing.
*/
-import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { compactionBegin, compactionEnd } from "@prismshadow/penguin-core";
import type { OmniMessage } from "@prismshadow/penguin-core";
-import type { SessionRow } from "../src/db/repos/sessions.js";
-import type { RuntimeSession } from "../src/runtime/session-manager.js";
+import { adoptSession, fakeSession, uniqueSessionId } from "./fixtures/session.js";
import { apiClient, createTestApp, provisionUser, waitFor } from "./helpers.js";
import type { TestApp } from "./helpers.js";
-const SID = "session-2026-08-19-10-00-00-aabb0003";
-
/** Records what the compaction saw of the abort signal. */
interface CompactionProbe {
started: boolean;
@@ -27,87 +25,59 @@ interface CompactionProbe {
endStatus: string | null;
}
-/**
- * Fake Session whose compaction parks until the signal fires — the shape of a real one, whose
- * compaction request is a full LLM round trip against the largest context of the session and
- * therefore the thing a user most wants to be able to stop.
- */
-function compactingFakeSession(sessionId: string, probe: CompactionProbe): RuntimeSession {
- return {
- sessionId,
- toolPermission: () => "rw",
- generateTitle: async () => ({ title: null, usage: null }),
- compactability: () => "ok" as const,
- steer: () => false,
- skipReconnectWait: () => false,
- // eslint-disable-next-line require-yield
- async *run() {},
- async *compact(opts: { signal: AbortSignal }): AsyncGenerator<OmniMessage> {
- probe.started = true;
- yield compactionBegin({ reason: "manual", mode: "summarize", context: 1000, turns: 3 });
- await new Promise<void>((resolve) => {
- if (opts.signal.aborted) {
- resolve();
- return;
- }
- opts.signal.addEventListener("abort", () => resolve(), { once: true });
- });
- probe.sawAbort = opts.signal.aborted;
- // Core's own interrupted-compaction outcome: the pair closes `aborted`, the original
- // context is kept, and the half-written summary is discarded.
- probe.endStatus = "aborted";
- yield compactionEnd({ reason: "manual", mode: "summarize", status: "aborted" });
- },
- };
-}
-
describe("abort during compaction", () => {
let t: TestApp;
let api: ReturnType<typeof apiClient>;
+ let sid: string;
let probe: CompactionProbe;
- beforeEach(async () => {
+ beforeAll(async () => {
t = await createTestApp();
- const { cookie } = await provisionUser(t.app, "compactstopper");
- api = apiClient(t.app, cookie);
- const row: SessionRow = {
- sessionId: SID,
- projectId: "compactstopper-default_project",
- agentId: "default_agent",
- modelId: "m1",
- provider: "custom",
- workspace: "/tmp/w",
- approvalMode: "always-ask",
- title: null,
- createdAt: new Date().toISOString(),
- lastActiveAt: new Date().toISOString(),
- };
- t.deps.sessionsRepo.insert(row);
- probe = { started: false, sawAbort: false, endStatus: null };
- t.deps.manager.adopt(row, compactingFakeSession(SID, probe));
+ api = apiClient(t.app, (await provisionUser(t.app, "compactstopper")).cookie);
});
- afterEach(async () => {
+ afterAll(async () => {
await t.cleanup();
});
+ // A compaction that parks until the signal fires — the shape of a real one, whose request
+ // is a full LLM round trip over the Session's largest context.
+ beforeEach(() => {
+ sid = uniqueSessionId();
+ probe = { started: false, sawAbort: false, endStatus: null };
+ const session = fakeSession(sid, {
+ async *compact(opts: { signal: AbortSignal }): AsyncGenerator<OmniMessage> {
+ probe.started = true;
+ yield compactionBegin({ reason: "manual", mode: "summarize", context: 1000, turns: 3 });
+ await new Promise<void>((resolve) => {
+ if (opts.signal.aborted) resolve();
+ else opts.signal.addEventListener("abort", () => resolve(), { once: true });
+ });
+ probe.sawAbort = opts.signal.aborted;
+ // Core's own interrupted-compaction outcome: the pair closes `aborted`, the original
+ // context is kept, and the half-written summary is discarded.
+ probe.endStatus = "aborted";
+ yield compactionEnd({ reason: "manual", mode: "summarize", status: "aborted" });
+ },
+ });
+ adoptSession(t.deps, session, { projectId: "compactstopper-default_project" });
+ });
+
it("takes the abort while compacting: 202, the signal reaches the compaction, the Session goes idle", async () => {
- await t.deps.manager.startCompact(SID);
- await waitFor(() => probe.started && t.deps.manager.statusOf(SID) === "compacting");
+ await t.deps.manager.startCompact(sid);
+ await waitFor(() => probe.started && t.deps.manager.statusOf(sid) === "compacting");
- const res = await api.post(`/api/sessions/${SID}/abort`, {});
+ const res = await api.post(`/api/sessions/${sid}/abort`, {});
// 202 = an interrupt was triggered (204 would mean "nothing in progress" — the answer
// this route would give if it only recognized `running` as interruptible).
expect(res.status).toBe(202);
- await waitFor(() => t.deps.manager.statusOf(SID) === "idle");
+ await waitFor(() => t.deps.manager.statusOf(sid) === "idle");
expect(probe.sawAbort).toBe(true);
- // The interrupted compaction settles in the same well-defined state a crash-interrupted
- // one does: aborted, with the original context kept.
expect(probe.endStatus).toBe("aborted");
});
it("an idle Session reports 204: there is no compaction to stop", async () => {
- const res = await api.post(`/api/sessions/${SID}/abort`, {});
+ const res = await api.post(`/api/sessions/${sid}/abort`, {});
expect(res.status).toBe(204);
expect(probe.started).toBe(false);
});
diff --git a/packages/server/test/body-limit.test.ts b/packages/server/test/body-limit.test.ts
index a8bd42db..bef207bb 100644
--- a/packages/server/test/body-limit.test.ts
+++ b/packages/server/test/body-limit.test.ts
@@ -1,29 +1,26 @@
/**
- * Global request body cap (`/api/*`).
+ * The global request-body cap on `/api/*`.
*
- * The cap used to read `content-length` only, which a chunked request simply does not carry —
- * `Number(undefined ?? 0)` is 0, so a body of any size passed straight through to the sinks
- * behind it (task input images, file attachments, Trace import). These tests post a body with
- * **no declared length** and require the same 413 `payload_too_large` a declared one gets, plus
- * an under-cap streamed body still arriving intact (the cap has to re-feed what it counted).
+ * The cap used to read `content-length` only, which a chunked request does not carry, so a
+ * body of any size passed straight through to the sinks behind it (task input images, file
+ * attachments, Trace import). The cap is derived from the admin-set attachment budget
+ * (bodyLimitBytes), so these cases set that budget to its floor and compute the expected cap
+ * with the server's own helper — a hardcoded byte count would stop testing the cap the moment
+ * the defaults moved.
*
- * The cap is no longer a constant: it is derived from the admin-settable attachment budget
- * (bodyLimitBytes). So these tests turn that budget down to its floor and compute the expected
- * cap with the same helper the server uses — which makes them a test of the derivation too, not
- * just of the middleware. A hardcoded byte count here would silently stop testing the cap the
- * moment the defaults moved.
+ * - A streamed body with no declared length over the cap is refused 413 `payload_too_large`,
+ * and no Task starts.
+ * - A declared over-cap length is refused before the body is read.
+ * - An under-cap streamed body passes through intact (the cap re-feeds what it counted).
*/
-import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { assistantText } from "@prismshadow/penguin-core";
import type { OmniMessage } from "@prismshadow/penguin-core";
-import type { SessionRow } from "../src/db/repos/sessions.js";
-import type { RuntimeSession } from "../src/runtime/session-manager.js";
import { bodyLimitBytes, MIN_ATTACHMENT_MB } from "../src/services/attachment-limits.js";
-import { apiClient, createTestApp, provisionUser, waitFor } from "./helpers.js";
+import { adoptSession, fakeSession, uniqueSessionId } from "./fixtures/session.js";
+import { createTestApp, provisionUser, waitFor } from "./helpers.js";
import type { TestApp } from "./helpers.js";
-const SID = "session-2026-07-29-13-00-00-aabb0004";
-const PROJECT_ID = "streamer-default_project";
const MB = 1024 * 1024;
/**
@@ -61,10 +58,10 @@ function streamedTaskBody(fill: number): ReadableStream<Uint8Array> {
describe("request body cap", () => {
let t: TestApp;
- let api: ReturnType<typeof apiClient>;
let cookie: string;
+ let SID: string;
let runs: OmniMessage[][];
- /** The body cap implied by the budget set in beforeEach. */
+ /** The body cap implied by the smallest budget an admin can set. */
let cap: number;
const postStream = (fill: number) =>
@@ -77,38 +74,9 @@ describe("request body cap", () => {
duplex: "half",
} as RequestInit);
- beforeEach(async () => {
+ beforeAll(async () => {
t = await createTestApp();
({ cookie } = await provisionUser(t.app, "streamer"));
- api = apiClient(t.app, cookie);
- const row: SessionRow = {
- sessionId: SID,
- projectId: PROJECT_ID,
- agentId: "default_agent",
- provider: "custom",
- modelId: "m1",
- workspace: "/tmp/w",
- approvalMode: "allow-all",
- title: null,
- createdAt: new Date().toISOString(),
- lastActiveAt: new Date().toISOString(),
- };
- t.deps.sessionsRepo.insert(row);
- runs = [];
- const session: RuntimeSession = {
- sessionId: SID,
- toolPermission: () => "rw",
- generateTitle: async () => ({ title: null, usage: null }),
- compactability: () => "ok" as const,
- steer: () => false,
- skipReconnectWait: () => false,
- async *run(input: OmniMessage[]) {
- runs.push(input);
- yield assistantText("done");
- },
- async *compact() {},
- };
- t.deps.manager.adopt(row, session);
// Smallest budget an admin can set, so the derived cap is as low as it goes and the
// over-cap body these tests have to stream stays cheap to produce.
t.deps.serverSettingsRepo.setAttachmentMaxMb(MIN_ATTACHMENT_MB);
@@ -118,9 +86,20 @@ describe("request body cap", () => {
attachmentTotalMb: MIN_ATTACHMENT_MB,
});
});
- afterEach(async () => {
+ afterAll(async () => {
await t.cleanup();
});
+ beforeEach(() => {
+ SID = uniqueSessionId();
+ runs = [];
+ const session = fakeSession(SID, {
+ async *run(input: OmniMessage[]) {
+ runs.push(input);
+ yield assistantText("done");
+ },
+ });
+ adoptSession(t.deps, session, { projectId: "streamer-default_project" });
+ });
it("a body with no declared length is still capped", async () => {
const res = await postStream(cap + 2 * MB);
diff --git a/packages/server/test/fixtures/session.ts b/packages/server/test/fixtures/session.ts
new file mode 100644
index 00000000..0d790139
--- /dev/null
+++ b/packages/server/test/fixtures/session.ts
@@ -0,0 +1,67 @@
+/**
+ * The suite's stand-in for a running core Session: the SessionManager's RuntimeSession seam,
+ * behind which the LLM and the Environment live. Every member answers the way an idle Session
+ * with nothing to report does, and a test overrides only what its scenario is about — most
+ * often `run`, the scripted stream of messages one Task yields.
+ *
+ * `adoptSession` indexes a Session row and adopts the fake as its runtime, the state a Session
+ * is in right after it was opened, so the routes, the bridge and the manager can drive it.
+ */
+import type { SessionRow } from "../../src/db/repos/sessions.js";
+import type { RuntimeSession } from "../../src/runtime/session-manager.js";
+import type { TestDeps } from "../helpers.js";
+
+export function fakeSession(
+ sessionId: string,
+ overrides: Partial<Omit<RuntimeSession, "sessionId">> = {},
+): RuntimeSession {
+ return {
+ sessionId,
+ toolPermission: () => "rw",
+ generateTitle: async () => ({ title: null, usage: null }),
+ compactability: () => "ok",
+ steer: () => false,
+ skipReconnectWait: () => false,
+ async *run() {},
+ async *compact() {},
+ ...overrides,
+ };
+}
+
+let sequence = 0;
+
+/** A Session id no other test in this process holds, in the shape the server mints. */
+export function uniqueSessionId(): string {
+ sequence += 1;
+ return `session-2026-09-01-10-00-00-${sequence.toString(16).padStart(8, "0")}`;
+}
+
+/** An index row for `sessionId`; the scenario overrides what it depends on (its Project, its approval mode). */
+export function sessionRow(sessionId: string, fields: Partial<SessionRow> = {}): SessionRow {
+ const now = new Date().toISOString();
+ return {
+ sessionId,
+ projectId: "default_project",
+ agentId: "default_agent",
+ provider: "custom",
+ modelId: "m1",
+ workspace: "/tmp/w",
+ approvalMode: "allow-all",
+ title: null,
+ createdAt: now,
+ lastActiveAt: now,
+ ...fields,
+ };
+}
+
+/** Indexes `session`'s row and adopts the fake as its runtime; returns the row. */
+export function adoptSession(
+ deps: Pick<TestDeps, "sessionsRepo" | "manager">,
+ session: RuntimeSession,
+ fields: Partial<SessionRow> = {},
+): SessionRow {
+ const row = sessionRow(session.sessionId, fields);
+ deps.sessionsRepo.insert(row);
+ deps.manager.adopt(row, session);
+ return row;
+}
diff --git a/packages/server/test/followup.test.ts b/packages/server/test/followup.test.ts
index d887039f..51157b44 100644
--- a/packages/server/test/followup.test.ts
+++ b/packages/server/test/followup.test.ts
@@ -1,73 +1,63 @@
/**
- * Integration tests for the follow-up queue (POST /api/sessions/:id/tasks with
- * `queueIfBusy`):
- * - busy session → 202 `{queued: true}`, input held server-side, auto-started as an
- * ordinary task once the current run finishes;
- * - idle session → the flag is a no-op (`queued: false`, task starts directly);
- * - one queued input starts exactly one task, and recall works whichever path queued it.
- * (The queued count on task_state events is covered by the session-manager unit tests.)
+ * The follow-up queue: POST /api/sessions/:id/tasks with `queueIfBusy`, and its recall.
+ *
+ * - Given an idle Session the flag is a no-op (`queued: false`, the task starts at once);
+ * given a busy one the input is held server-side (`queued: true`, where a plain POST is a
+ * 409) and auto-starts as an ordinary task once the current run finishes.
+ * - A queued follow-up can be recalled with its content, and then never starts; one already
+ * started (or recalled) answers 409 `follow_up_started`.
+ * - The SSE subscribe snapshot carries the queued list, so a reloaded page can still recall.
+ * - A recall racing the auto-start in the idle gap wins exactly once: nothing starts.
+ * - One queued follow-up starts exactly one task, whether the run before it completes or is
+ * aborted.
+ * - A follow-up queued straight through the manager (the messaging bridge's door) is
+ * recallable the same way.
+ *
+ * The queued count on task_state events is covered by the session-manager suite.
*/
-import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { approvalDecision, assistantText, toolCall, userText } from "@prismshadow/penguin-core";
import type { ApproveFn, OmniMessage } from "@prismshadow/penguin-core";
import type { TaskCreateResponse } from "../src/api/types.js";
-import type { SessionRow } from "../src/db/repos/sessions.js";
-import type { RecallStore, RuntimeSession } from "../src/runtime/session-manager.js";
+import type { RecallStore } from "../src/runtime/session-manager.js";
+import { adoptSession, fakeSession, uniqueSessionId } from "./fixtures/session.js";
import { apiClient, createTestApp, provisionUser, waitFor } from "./helpers.js";
import type { TestApp } from "./helpers.js";
-const SID = "session-2026-07-06-10-00-00-eeff0001";
-
-/** Fake Session that parks on one approval per run (keeps the Task running) and records each run's input. */
-function parkingFakeSession(sessionId: string, runs: string[][]): RuntimeSession {
- return {
- sessionId,
- toolPermission: () => "rw",
- generateTitle: async () => ({ title: null, usage: null }),
- compactability: () => "ok" as const,
- steer: () => false,
- skipReconnectWait: () => false,
- async *run(input: OmniMessage[], opts: { approve: ApproveFn; signal: AbortSignal }) {
- runs.push(input.map((m) => (m.payload as { text?: string }).text ?? ""));
- const tc = toolCall({ name: "exec_command", arguments: "{}", toolCallId: "tc-fu" });
- yield tc;
- const decision = await opts.approve(tc);
- yield approvalDecision(decision, "tc-fu");
- yield assistantText("done");
- },
- async *compact() {},
- };
-}
-
describe("follow-up queue route", () => {
let t: TestApp;
let api: ReturnType<typeof apiClient>;
+ let SID: string;
let runs: string[][];
- beforeEach(async () => {
+ beforeAll(async () => {
t = await createTestApp();
- const { cookie } = await provisionUser(t.app, "queuer");
- api = apiClient(t.app, cookie);
- const row: SessionRow = {
- sessionId: SID,
- projectId: "queuer-default_project",
- agentId: "default_agent",
- provider: "custom",
- modelId: "m1",
- workspace: "/tmp/w",
- approvalMode: "always-ask",
- title: null,
- createdAt: new Date().toISOString(),
- lastActiveAt: new Date().toISOString(),
- };
- t.deps.sessionsRepo.insert(row);
- runs = [];
- t.deps.manager.adopt(row, parkingFakeSession(SID, runs));
+ api = apiClient(t.app, (await provisionUser(t.app, "queuer")).cookie);
});
- afterEach(async () => {
+ afterAll(async () => {
await t.cleanup();
});
+ // A Session that parks on one approval per run (keeping the Task running) and records each
+ // run's input.
+ beforeEach(() => {
+ SID = uniqueSessionId();
+ runs = [];
+ const session = fakeSession(SID, {
+ async *run(input: OmniMessage[], opts: { approve: ApproveFn; signal: AbortSignal }) {
+ runs.push(input.map((m) => (m.payload as { text?: string }).text ?? ""));
+ const tc = toolCall({ name: "exec_command", arguments: "{}", toolCallId: "tc-fu" });
+ yield tc;
+ yield approvalDecision(await opts.approve(tc), "tc-fu");
+ yield assistantText("done");
+ },
+ });
+ adoptSession(t.deps, session, {
+ projectId: "queuer-default_project",
+ approvalMode: "always-ask",
+ });
+ });
+
it("busy → 202 queued:true and auto-starts after the current run; idle → queued:false", async () => {
// Idle: the flag is a no-op, the task starts directly.
const direct = await api.post(`/api/sessions/${SID}/tasks`, {
diff --git a/packages/server/test/goals.test.ts b/packages/server/test/goals.test.ts
index 0df07c79..cc77e3c9 100644
--- a/packages/server/test/goals.test.ts
+++ b/packages/server/test/goals.test.ts
@@ -1,15 +1,22 @@
/**
- * Goal-mode server tests.
+ * Goal mode on the server: SessionManager.startGoal and the goal events it derives.
*
- * - SessionManager.startGoal running the goal plugin's user_prompt hook on a fake Session
- * (no real LLM requests, no scripts) and driving one `session.run` — the round and
- * terminal server events derived from the stream's harness-injected inputs and goal hook
- * events.
- * - A real core Session that runs the installed scripts against a loopback model endpoint,
- * with a hand-written every-prompt package beside the goal package: on a goal start that
- * package's context rides round 1 without counting as a round, and an ordinary Task starts
- * no goal — for the goal package the library ships and for one installed before
- * user_prompt commands ran on every Prompt.
+ * On a fake Session (the goal plugin's start answered in its place, no scripts, no LLM):
+ * - A goal run maps its round inputs and the goal hook's answers to goal_round and
+ * goal_finished events.
+ * - The recorded objective leaves the attached images out, so the display copy stays path-free.
+ * - A background completion notice inside a round is not a round boundary.
+ * - A second goal while one runs is a 409; a Session with no goal start hook is a 409
+ * goal_plugin_not_installed.
+ * - A throw after the terminal event publishes no contradicting outcome; a stream that ends
+ * without the terminal event closes the goal as aborted.
+ *
+ * On a real core Session running the installed scripts against a loopback model, with a
+ * hand-written every-prompt package beside the goal package (both for the package the library
+ * ships and for one installed before user_prompt ran on every Prompt):
+ * - A goal start runs the goal's start by name, and the other package's context rides round 1
+ * without counting as a round.
+ * - An ordinary Task starts no goal; only the other package's hook runs for it.
*/
import fs from "node:fs/promises";
import path from "node:path";
@@ -20,7 +27,6 @@ import {
assistantText,
buildSkillsMessage,
createAgent,
- emptyTokenCounts,
hookEvent,
hooksDir,
imageUrlMessage,
@@ -40,6 +46,7 @@ import type { ChannelEvent } from "../src/runtime/channel.js";
import { SessionManager, createCoreSessionLoader } from "../src/runtime/session-manager.js";
import type { RuntimeSession } from "../src/runtime/session-manager.js";
import { SessionSources } from "../src/runtime/session-sources.js";
+import { fakeSession } from "./fixtures/session.js";
import { makeTempRoot, waitFor } from "./helpers.js";
import {
MOCK_MODEL_ID,
@@ -129,28 +136,18 @@ describe("SessionManager.startGoal", () => {
const runOpts: RunOpts[] = [];
const runs: OmniMessage[][] = [];
const starts: Array<{ name: string; prompt: string; extras: unknown }> = [];
- return {
- sessionId: ROW.sessionId,
- runOpts,
- runs,
- starts,
- toolPermission: () => "rw",
- generateTitle: async () => ({ title: null, usage: null }),
- compactability: () => "ok" as const,
- steer: () => false,
- skipReconnectWait: () => false,
+ const session = fakeSession(ROW.sessionId, {
async runUserPromptHook(name, prompt, extras) {
starts.push({ name, prompt, extras });
return { context: "goal round 1 protocol lines" };
},
- async *run(input: OmniMessage[], opts) {
+ async *run(input: OmniMessage[]) {
runs.push(input);
- void opts;
runOpts.push({});
yield* stream(input);
},
- async *compact() {},
- };
+ });
+ return Object.assign(session, { runOpts, runs, starts });
}
function makeManager(session: RuntimeSession): SessionManager {
@@ -370,10 +367,6 @@ describe("SessionManager.startGoal", () => {
used: 0,
});
});
-
- it("sanity: emptyTokenCounts helper stays exported for fakes", () => {
- expect(emptyTokenCounts().total).toBe(0);
- });
});
/**
diff --git a/packages/server/test/hooks.test.ts b/packages/server/test/hooks.test.ts
index f13fc5dd..9ba7cbea 100644
--- a/packages/server/test/hooks.test.ts
+++ b/packages/server/test/hooks.test.ts
@@ -1,18 +1,27 @@
/**
- * Integration tests for the hook package routes: the installed list (a package written by
- * hand included), the zip archive install (layouts, manifest validation, zip-slip, 409
- * hook_exists + overwrite, a user_prompt command's trigger) and the byte-identical export
- * round-trip. Whether Sessions run hooks at all is the Agent-level `hooks.enabled` switch,
- * tested with the rest of the Agent config (prompt-sections.test.ts).
+ * Hook packages: the routes that list, install, export and remove them, and what an installed
+ * package does to a conversation. Whether Sessions run hooks at all is the Agent-level
+ * `hooks.enabled` switch, tested with the rest of the Agent config (prompt-sections.test.ts).
*
- * The last block drives real Sessions against a loopback model endpoint: what an
- * every-prompt package adds to a conversation, and an install or uninstall through these
- * routes reaching a conversation that is already open.
+ * - The list shows what a library install wrote (with no switch written into the manifest) and
+ * a package written by hand whose manifest names only the hook point it uses.
+ * - A zip installs under its top directory's name, or the manifest's for a root layout, and
+ * uninstalls; a manifest the loader or a Session could not run is refused, writing nothing; a
+ * user_prompt command's trigger is kept.
+ * - Zip-slip paths, malformed bodies, an entry over the per-file cap (however small the
+ * archive) and an entry lying about its size are refused, writing nothing.
+ * - Installing over an installed package is a 409 hook_exists; overwrite replaces the whole
+ * directory.
+ * - An export round-trips byte-identically and re-imports on another Agent; a package not
+ * installed is a 404.
+ * - In a real conversation, an every-prompt package's context follows the user's message,
+ * stamped harness, live and in the history; a package installed or removed through the
+ * routes reaches the open conversation on its next Task.
*/
import fs from "node:fs/promises";
import path from "node:path";
import { strToU8, unzipSync, zipSync } from "fflate";
-import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { hooksDir } from "@prismshadow/penguin-core";
import type { OmniMessage } from "@prismshadow/penguin-core";
import type {
@@ -46,7 +55,8 @@ describe("hooks api", () => {
const manifestFile = (agentId: string, name: string) =>
path.join(hooksDir(t.root, projectId, agentId), name, "hooks.json");
- beforeEach(async () => {
+ // Every case works on an Agent of its own, so one app serves them all.
+ beforeAll(async () => {
t = await createTestApp();
const a = await provisionUser(t.app, "owner_h");
const b = await provisionUser(t.app, "member_h");
@@ -62,7 +72,7 @@ describe("hooks api", () => {
(await owner.post(`/api/projects/${projectId}/members`, { userId: "member_h" })).status,
).toBe(201);
});
- afterEach(async () => {
+ afterAll(async () => {
await t.cleanup();
});
diff --git a/packages/server/test/messages-live.test.ts b/packages/server/test/messages-live.test.ts
index d2e82497..1b094670 100644
--- a/packages/server/test/messages-live.test.ts
+++ b/packages/server/test/messages-live.test.ts
@@ -1,10 +1,16 @@
/**
- * GET /api/sessions/:id/messages live-tail integration: while a Task runs, the response
- * carries `live` — a channel cursor plus one synthetic `partial_* start` per open
- * streaming fragment (origin preserved for subagent fragments); once the run ends the
- * field disappears and the tail is cleared.
+ * GET /api/sessions/:id/messages while a Task runs: the live tail a reloading page resumes
+ * the stream from.
+ *
+ * - Given an idle Session, the response carries no `live` field.
+ * - Given a running one, `live` carries a channel cursor and one synthetic `partial_* start`
+ * per streaming fragment still open (a subagent fragment keeps its origin); once the run
+ * ends the tail is cleared and the field disappears.
+ * - Windowed reads carry `live` on tail pages with the same content, never on `before` pages.
+ * - A read without paging parameters is byte-identical to the transcript alone, and malformed
+ * paging parameters are refused.
*/
-import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
import {
approvalDecision,
assistantText,
@@ -21,24 +27,17 @@ import type { ApproveFn, OmniMessage } from "@prismshadow/penguin-core";
import type { MessagesResponse } from "../src/api/types.js";
import type { SessionRow } from "../src/db/repos/sessions.js";
import type { RuntimeSession } from "../src/runtime/session-manager.js";
+import { fakeSession, sessionRow, uniqueSessionId } from "./fixtures/session.js";
import { apiClient, createTestApp, provisionUser, waitFor } from "./helpers.js";
import type { TestApp } from "./helpers.js";
-const SID = "session-2026-07-25-10-00-00-cafe0001";
-
/**
* Fake session frozen mid-stream: it streams a thinking fragment, a closed text segment,
* a tool call with a partially streamed output, and a subagent text fragment, then blocks
* on approval (always-ask) so the Task stays running while the test inspects /messages.
*/
function midStreamFakeSession(sessionId: string): RuntimeSession {
- return {
- sessionId,
- toolPermission: () => "rw",
- generateTitle: async () => ({ title: null, usage: null }),
- compactability: () => "ok" as const,
- steer: () => false,
- skipReconnectWait: () => false,
+ return fakeSession(sessionId, {
async *run(_input: OmniMessage[], opts: { approve: ApproveFn; signal: AbortSignal }) {
// A real run opens its first LLM request before any model output — and the
// manager's pending-input holds end exactly there.
@@ -60,35 +59,27 @@ function midStreamFakeSession(sessionId: string): RuntimeSession {
yield toolCallOutput({ output: "line 1\nline 2\n", toolCallId: "tc-lv" });
yield assistantText("done");
},
- async *compact() {},
- };
+ });
}
describe("messages live tail", () => {
let t: TestApp;
let cookie: string;
+ let SID: string;
let row: SessionRow;
- beforeEach(async () => {
+ beforeAll(async () => {
t = await createTestApp();
({ cookie } = await provisionUser(t.app, "livetailer"));
- row = {
- sessionId: SID,
- projectId: "livetailer-default_project",
- agentId: "default_agent",
- modelId: "m1",
- provider: "custom",
- workspace: "/tmp/w",
- approvalMode: "always-ask",
- title: null,
- createdAt: new Date().toISOString(),
- lastActiveAt: new Date().toISOString(),
- };
- t.deps.sessionsRepo.insert(row);
});
- afterEach(async () => {
+ afterAll(async () => {
await t.cleanup();
});
+ beforeEach(() => {
+ SID = uniqueSessionId();
+ row = sessionRow(SID, { projectId: "livetailer-default_project", approvalMode: "always-ask" });
+ t.deps.sessionsRepo.insert(row);
+ });
const getMessages = async (query = ""): Promise<MessagesResponse> => {
const res = await apiClient(t.app, cookie).get(`/api/sessions/${SID}/messages${query}`);
diff --git a/packages/server/test/messages-pending-input.test.ts b/packages/server/test/messages-pending-input.test.ts
index 58afd78b..34ffa037 100644
--- a/packages/server/test/messages-pending-input.test.ts
+++ b/packages/server/test/messages-pending-input.test.ts
@@ -1,17 +1,18 @@
/**
- * GET /messages during the first run's bootstrap window (MCP connect + discovery): the
- * engine writes the input to the Trace only after the bootstrap, and the draft flow
- * subscribes to the stream only after the input publish — so history rebuilds during the
- * connect used to lose the user's own message. The manager now holds the published
- * inputs until the run's FIRST request_begin (by which point the engine has written
- * input + bootstrap records to the Trace) and the messages endpoint appends whichever
- * of them the Trace read has not caught up to (exact-envelope dedup); idle clears the
- * holds as a backstop for runs that never issue a request. Ending the holds at
- * request_begin is what keeps a LONG run from re-serving the input: the endpoint's
- * dedup only scans the history tail, and a hold outliving that window would append the
- * user's message a second time at the end of the conversation.
+ * GET /messages during the first run's bootstrap window (MCP connect and discovery). The engine
+ * writes the input to the Trace only after the bootstrap, and a draft subscribes to the stream
+ * only after the input is published, so a history rebuild during the connect used to lose the
+ * user's own message. The manager holds the published inputs until the run's FIRST
+ * request_begin, and the endpoint appends whichever of them the Trace has not caught up to.
+ *
+ * - Given a run in its bootstrap window, the endpoint serves the input and the connect status
+ * (full and tail reads alike) exactly once, and both holds end at the first request_begin,
+ * while the run is still going — a hold outliving the tail window would re-append the input.
+ * - An input already persisted with a Trace position is not served twice.
+ * - A run aborted mid-bootstrap keeps its holds, so a reload still sees the message; the next
+ * run appends its own input and drops the stale connect pair.
*/
-import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
import {
assistantText,
mcpConnectBegin,
@@ -21,12 +22,12 @@ import {
} from "@prismshadow/penguin-core";
import type { OmniMessage } from "@prismshadow/penguin-core";
import type { MessagesResponse } from "../src/api/types.js";
-import type { SessionRow } from "../src/db/repos/sessions.js";
import type { RuntimeSession } from "../src/runtime/session-manager.js";
+import { adoptSession, fakeSession, uniqueSessionId } from "./fixtures/session.js";
import { apiClient, createTestApp, provisionUser, waitFor, writeTraceFile } from "./helpers.js";
import type { TestApp } from "./helpers.js";
-const SID = "session-2026-08-10-10-00-00-eeff0002";
+const PROJECT = "pender-default_project";
/**
* Fake Session that yields the MCP connect begin (the real Session streams it live before
@@ -40,13 +41,7 @@ function parkedBootstrapSession(
bootstrapGate: Promise<void>,
requestGate: Promise<void>,
): RuntimeSession {
- return {
- sessionId,
- toolPermission: () => "rw",
- generateTitle: async () => ({ title: null, usage: null }),
- compactability: () => "ok" as const,
- steer: () => false,
- skipReconnectWait: () => false,
+ return fakeSession(sessionId, {
async *run() {
yield mcpConnectBegin(["fx"]);
await bootstrapGate;
@@ -54,46 +49,39 @@ function parkedBootstrapSession(
await requestGate;
yield assistantText("done");
},
- async *compact() {},
- };
+ });
}
describe("GET /messages serves the running task's pending inputs", () => {
let t: TestApp;
let api: ReturnType<typeof apiClient>;
+ let SID: string;
let releaseBootstrap!: () => void;
let releaseRequest!: () => void;
- beforeEach(async () => {
+ beforeAll(async () => {
t = await createTestApp();
- const { cookie } = await provisionUser(t.app, "pender");
- api = apiClient(t.app, cookie);
- const row: SessionRow = {
- sessionId: SID,
- projectId: "pender-default_project",
- agentId: "default_agent",
- provider: "custom",
- modelId: "m1",
- workspace: "/tmp/w",
- approvalMode: "always-ask",
- title: null,
- createdAt: new Date().toISOString(),
- lastActiveAt: new Date().toISOString(),
- };
- t.deps.sessionsRepo.insert(row);
+ api = apiClient(t.app, (await provisionUser(t.app, "pender")).cookie);
+ });
+ afterAll(async () => {
+ await t.cleanup();
+ });
+ beforeEach(() => {
+ SID = uniqueSessionId();
const bootstrapGate = new Promise<void>((resolve) => {
releaseBootstrap = resolve;
});
const requestGate = new Promise<void>((resolve) => {
releaseRequest = resolve;
});
- t.deps.manager.adopt(row, parkedBootstrapSession(SID, bootstrapGate, requestGate));
+ adoptSession(t.deps, parkedBootstrapSession(SID, bootstrapGate, requestGate), {
+ projectId: PROJECT,
+ approvalMode: "always-ask",
+ });
});
-
- afterEach(async () => {
+ afterEach(() => {
releaseBootstrap();
releaseRequest();
- await t.cleanup();
});
it("appends the input during the bootstrap window and ends both holds at the run's first request_begin", async () => {
@@ -162,7 +150,7 @@ describe("GET /messages serves the running task's pending inputs", () => {
expect(res.status).toBe(202);
await waitFor(() => t.deps.manager.pendingBootstrap(SID).length === 1);
const input = t.deps.manager.pendingInputs(SID)[0]!;
- await writeTraceFile(t.root, "pender-default_project", "default_agent", "2026-08-15", SID, 1, [
+ await writeTraceFile(t.root, PROJECT, "default_agent", "2026-08-15", SID, 1, [
sessionMeta({
session_id: SID,
provider: "custom",
@@ -191,20 +179,7 @@ describe("GET /messages serves the running task's pending inputs", () => {
});
it("keeps the holds after a run aborted mid-bootstrap (no request_begin): a reload still sees the message; the next run appends", async () => {
- const SID2 = "session-2026-08-11-10-00-00-eeff0003";
- const row: SessionRow = {
- sessionId: SID2,
- projectId: "pender-default_project",
- agentId: "default_agent",
- provider: "custom",
- modelId: "m1",
- workspace: "/tmp/w",
- approvalMode: "always-ask",
- title: null,
- createdAt: new Date().toISOString(),
- lastActiveAt: new Date().toISOString(),
- };
- t.deps.sessionsRepo.insert(row);
+ const SID2 = uniqueSessionId();
// First run: connect aborted before any request (the core cancels the bootstrap and
// carries the input). Second run: a fresh connect that reaches request_begin.
let runs = 0;
@@ -216,13 +191,7 @@ describe("GET /messages serves the running task's pending inputs", () => {
const secondGate = new Promise<void>((resolve) => {
releaseSecond = resolve;
});
- t.deps.manager.adopt(row, {
- sessionId: SID2,
- toolPermission: () => "rw",
- generateTitle: async () => ({ title: null, usage: null }),
- compactability: () => "ok" as const,
- steer: () => false,
- skipReconnectWait: () => false,
+ const session = fakeSession(SID2, {
async *run() {
runs += 1;
yield mcpConnectBegin(["fx"]);
@@ -237,8 +206,8 @@ describe("GET /messages serves the running task's pending inputs", () => {
await secondGate;
yield assistantText("done");
},
- async *compact() {},
});
+ adoptSession(t.deps, session, { projectId: PROJECT, approvalMode: "always-ask" });
const first = await api.post(`/api/sessions/${SID2}/tasks`, {
input: [{ type: "text", text: "lost?" }],
diff --git a/packages/server/test/retry-now.test.ts b/packages/server/test/retry-now.test.ts
index 26b713ee..81b3183a 100644
--- a/packages/server/test/retry-now.test.ts
+++ b/packages/server/test/retry-now.test.ts
@@ -1,100 +1,83 @@
/**
- * Integration tests for POST /api/sessions/:id/retry-now ("retry now" on the reconnect
- * countdown — skips the in-progress backoff wait):
- * - 200 {skipped:true} while the runtime reports a wait was skipped;
- * - 200 {skipped:false} as a benign no-op when the session is idle or no wait is in
- * progress (timing races must not surface as errors);
- * - 404 for foreign/unknown sessions (via the shared resolveSession lookup).
+ * POST /api/sessions/:id/retry-now: "retry now" on the reconnect countdown, which skips the
+ * backoff wait in progress.
+ *
+ * - Given an idle Session, the route answers a benign 200 `{skipped:false}` and never pokes
+ * the runtime (a timing race must not surface as an error).
+ * - Given a running Session parked in a wait, it answers `{skipped:true}` and the skip reaches
+ * the runtime.
+ * - A foreign or unknown Session is a 404, as on every other Session route.
*/
-import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { approvalDecision, assistantText, toolCall, userText } from "@prismshadow/penguin-core";
import type { ApproveFn, OmniMessage } from "@prismshadow/penguin-core";
import type { RetryNowResponse } from "../src/api/types.js";
-import type { SessionRow } from "../src/db/repos/sessions.js";
-import type { RuntimeSession } from "../src/runtime/session-manager.js";
+import { adoptSession, fakeSession, uniqueSessionId } from "./fixtures/session.js";
import { apiClient, createTestApp, provisionUser, waitFor } from "./helpers.js";
import type { TestApp } from "./helpers.js";
-const SID = "session-2026-07-27-10-00-00-ccdd0002";
-
-/** Fake Session that parks on one approval (keeps the Task running) and records skip calls. */
-function backoffFakeSession(sessionId: string, skips: number[]): RuntimeSession {
- return {
- sessionId,
- toolPermission: () => "rw",
- generateTitle: async () => ({ title: null, usage: null }),
- compactability: () => "ok" as const,
- steer: () => false,
- skipReconnectWait: () => {
- skips.push(Date.now());
- return true; // pretend a reconnect wait was in progress and got skipped
- },
- async *run(_input: OmniMessage[], opts: { approve: ApproveFn; signal: AbortSignal }) {
- const tc = toolCall({ name: "exec_command", arguments: "{}", toolCallId: "tc-retry" });
- yield tc;
- const decision = await opts.approve(tc);
- yield approvalDecision(decision, "tc-retry");
- yield assistantText("done");
- },
- async *compact() {},
- };
-}
-
describe("retry-now route", () => {
let t: TestApp;
let api: ReturnType<typeof apiClient>;
let outsider: ReturnType<typeof apiClient>;
- let skips: number[];
+ let sid: string;
+ let skips: number;
- beforeEach(async () => {
+ beforeAll(async () => {
t = await createTestApp();
- const { cookie } = await provisionUser(t.app, "retrier");
- const other = await provisionUser(t.app, "outsider_r");
- api = apiClient(t.app, cookie);
- outsider = apiClient(t.app, other.cookie);
- const row: SessionRow = {
- sessionId: SID,
- projectId: "retrier-default_project",
- agentId: "default_agent",
- modelId: "m1",
- provider: "custom",
- workspace: "/tmp/w",
- approvalMode: "always-ask",
- title: null,
- createdAt: new Date().toISOString(),
- lastActiveAt: new Date().toISOString(),
- };
- t.deps.sessionsRepo.insert(row);
- skips = [];
- t.deps.manager.adopt(row, backoffFakeSession(SID, skips));
+ api = apiClient(t.app, (await provisionUser(t.app, "retrier")).cookie);
+ outsider = apiClient(t.app, (await provisionUser(t.app, "outsider_r")).cookie);
});
- afterEach(async () => {
+ afterAll(async () => {
await t.cleanup();
});
+ // A Session that parks on one approval (keeping its Task running) and reports every skip as
+ // one that interrupted a reconnect wait.
+ beforeEach(() => {
+ sid = uniqueSessionId();
+ skips = 0;
+ const session = fakeSession(sid, {
+ skipReconnectWait: () => {
+ skips += 1;
+ return true;
+ },
+ async *run(_input: OmniMessage[], opts: { approve: ApproveFn; signal: AbortSignal }) {
+ const tc = toolCall({ name: "exec_command", arguments: "{}", toolCallId: "tc-retry" });
+ yield tc;
+ yield approvalDecision(await opts.approve(tc), "tc-retry");
+ yield assistantText("done");
+ },
+ });
+ adoptSession(t.deps, session, {
+ projectId: "retrier-default_project",
+ approvalMode: "always-ask",
+ });
+ });
+
it("idle → benign 200 {skipped:false}; the runtime is never poked", async () => {
- const res = await api.post(`/api/sessions/${SID}/retry-now`, {});
+ const res = await api.post(`/api/sessions/${sid}/retry-now`, {});
expect(res.status).toBe(200);
expect((await res.json()) as RetryNowResponse).toEqual({ skipped: false });
- expect(skips).toEqual([]);
+ expect(skips).toBe(0);
});
it("running (parked in a wait) → 200 {skipped:true}, the skip reaches the runtime", async () => {
- await t.deps.manager.startTask(SID, [userText("go")]);
- await waitFor(() => t.deps.manager.pendingApprovalCount(SID) === 1);
+ await t.deps.manager.startTask(sid, [userText("go")]);
+ await waitFor(() => t.deps.manager.pendingApprovalCount(sid) === 1);
- const res = await api.post(`/api/sessions/${SID}/retry-now`, {});
+ const res = await api.post(`/api/sessions/${sid}/retry-now`, {});
expect(res.status).toBe(200);
expect((await res.json()) as RetryNowResponse).toEqual({ skipped: true });
- expect(skips).toHaveLength(1);
+ expect(skips).toBe(1);
- t.deps.manager.decideApproval(SID, "tc-retry", "allow");
- await waitFor(() => t.deps.manager.statusOf(SID) === "idle");
+ t.deps.manager.decideApproval(sid, "tc-retry", "allow");
+ await waitFor(() => t.deps.manager.statusOf(sid) === "idle");
});
it("foreign and unknown sessions → 404 (same auth semantics as the other session routes)", async () => {
- expect((await outsider.post(`/api/sessions/${SID}/retry-now`, {})).status).toBe(404);
+ expect((await outsider.post(`/api/sessions/${sid}/retry-now`, {})).status).toBe(404);
expect((await api.post(`/api/sessions/session-ghost/retry-now`, {})).status).toBe(404);
- expect(skips).toEqual([]);
+ expect(skips).toBe(0);
});
});
diff --git a/packages/server/test/session-background-tasks.test.ts b/packages/server/test/session-background-tasks.test.ts
index b00f5608..e7524057 100644
--- a/packages/server/test/session-background-tasks.test.ts
+++ b/packages/server/test/session-background-tasks.test.ts
@@ -1,27 +1,25 @@
/**
* `SessionInfo.backgroundTasks` and its user-channel event `session_background`.
*
- * The counts are read live from a LOADED runtime's registries — command sessions still
- * running past their yield window, subagent sessions promoted to a `subagent_id` and
- * mid-round — and the field is present only while something is running: an unloaded Session
- * (a resumed entry starts with empty registries) and a Session with nothing running both
- * omit it, so a list can treat the field's presence as "this row has background work".
+ * The counts are read live from a LOADED runtime's registries: command sessions still running
+ * past their yield window, and subagent sessions promoted to a `subagent_id` and mid-round.
*
- * The event is the core background-state ping re-counted: it is published only when the
- * counts moved, carries the counts as they now stand (zeros included, so a list can clear its
- * mark without refetching), and reaches the same audience `session_state` does.
+ * - The single GET and the list rows carry the counts while something is running; an unloaded
+ * Session (a resumed entry starts with empty registries) and one with nothing running omit
+ * the field, so a list can read its presence as "this row has background work".
+ * - The event is published only when the counts moved, carries them as they now stand (zeros
+ * included, so a list clears its mark without refetching), and reaches the same audience
+ * `session_state` does: never a stranger's live channel.
*/
-import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
import type { BackgroundCommandInfo, BackgroundSubagentInfo } from "@prismshadow/penguin-core";
import type { ServerEvent, SessionResponse, SessionsResponse } from "../src/api/types.js";
-import type { SessionRow } from "../src/db/repos/sessions.js";
import { userChannelKey } from "../src/http/routes/events.js";
import type { RuntimeSession } from "../src/runtime/session-manager.js";
+import { adoptSession, fakeSession, sessionRow, uniqueSessionId } from "./fixtures/session.js";
import { apiClient, createTestApp, provisionUser } from "./helpers.js";
import type { TestApp } from "./helpers.js";
-const SID = "session-2026-09-02-10-00-00-bbcc0001";
-const SID_UNLOADED = "session-2026-09-02-10-00-00-bbcc0002";
const PROJECT = "owner-default_project";
const STARTED_AT = Date.UTC(2026, 8, 2, 10, 4, 0);
@@ -56,36 +54,13 @@ function backgroundFakeSession(
subs: BackgroundSubagentInfo[],
hook: Hook,
): RuntimeSession {
- return {
- sessionId,
- toolPermission: () => "rw",
- generateTitle: async () => ({ title: null, usage: null }),
- compactability: () => "ok" as const,
- steer: () => false,
- skipReconnectWait: () => false,
- async *run() {},
- async *compact() {},
+ return fakeSession(sessionId, {
listBackgroundCommands: () => [...procs],
listBackgroundSubagents: () => [...subs],
onBackgroundState: (listener) => {
hook.ping = listener;
},
- };
-}
-
-function sessionRow(sessionId: string): SessionRow {
- return {
- sessionId,
- projectId: PROJECT,
- agentId: "default_agent",
- provider: "custom",
- modelId: "m1",
- workspace: "/tmp/w",
- approvalMode: "allow-all",
- title: null,
- createdAt: "2026-09-02T09:00:00.000Z",
- lastActiveAt: "2026-09-02T09:00:00.000Z",
- };
+ });
}
/** Everything one user's channel received, as a connected client would see it. */
@@ -100,17 +75,29 @@ function inbox(t: TestApp, userId: string) {
};
}
+let t: TestApp;
+let api: ReturnType<typeof apiClient>;
+
+beforeAll(async () => {
+ t = await createTestApp();
+ api = apiClient(t.app, (await provisionUser(t.app, "owner")).cookie);
+ // A logged-in user with a live channel of their own and no access to the Project.
+ await provisionUser(t.app, "stranger");
+});
+afterAll(async () => {
+ await t.cleanup();
+});
+
describe("SessionInfo.backgroundTasks", () => {
- let t: TestApp;
- let api: ReturnType<typeof apiClient>;
+ let SID: string;
+ let SID_UNLOADED: string;
let procs: BackgroundCommandInfo[];
let subs: BackgroundSubagentInfo[];
const hook: Hook = { ping: () => undefined };
- beforeEach(async () => {
- t = await createTestApp();
- const { cookie } = await provisionUser(t.app, "owner");
- api = apiClient(t.app, cookie);
+ beforeEach(() => {
+ SID = uniqueSessionId();
+ SID_UNLOADED = uniqueSessionId();
procs = [proc("proc-11111111", true), proc("proc-22222222", false)];
subs = [
sub("session-child-0000000000000001", "subagent-00000001", true),
@@ -118,12 +105,8 @@ describe("SessionInfo.backgroundTasks", () => {
sub("session-child-0000000000000002", null, true),
sub("session-child-0000000000000003", "subagent-00000003", false),
];
- t.deps.sessionsRepo.insert(sessionRow(SID));
- t.deps.manager.adopt(sessionRow(SID), backgroundFakeSession(SID, procs, subs, hook));
- t.deps.sessionsRepo.insert(sessionRow(SID_UNLOADED));
- });
- afterEach(async () => {
- await t.cleanup();
+ adoptSession(t.deps, backgroundFakeSession(SID, procs, subs, hook), { projectId: PROJECT });
+ t.deps.sessionsRepo.insert(sessionRow(SID_UNLOADED, { projectId: PROJECT }));
});
it("counts running processes and promoted, mid-round subagents on the single GET and on list rows", async () => {
@@ -155,28 +138,21 @@ describe("SessionInfo.backgroundTasks", () => {
});
describe("session_background on the user channel", () => {
- let t: TestApp;
+ let SID: string;
let procs: BackgroundCommandInfo[];
let subs: BackgroundSubagentInfo[];
const hook: Hook = { ping: () => undefined };
let owner: ReturnType<typeof inbox>;
let stranger: ReturnType<typeof inbox>;
- beforeEach(async () => {
- t = await createTestApp();
- await provisionUser(t.app, "owner");
- // A logged-in user with a live channel of their own and no access to the Project.
- await provisionUser(t.app, "stranger");
+ beforeEach(() => {
+ SID = uniqueSessionId();
procs = [];
subs = [];
- t.deps.sessionsRepo.insert(sessionRow(SID));
- t.deps.manager.adopt(sessionRow(SID), backgroundFakeSession(SID, procs, subs, hook));
+ adoptSession(t.deps, backgroundFakeSession(SID, procs, subs, hook), { projectId: PROJECT });
owner = inbox(t, "owner");
stranger = inbox(t, "stranger");
});
- afterEach(async () => {
- await t.cleanup();
- });
it("publishes the counts as they stand after each change, and nothing when they did not move", () => {
// The counts at load time are the baseline: a ping that changes nothing is not news.
@@ -217,13 +193,4 @@ describe("session_background on the user channel", () => {
// The same audience rule as session_state: a stranger's live channel hears nothing.
expect(stranger.events).toEqual([]);
});
-
- it("reads the same counts the manager's query surface reports", () => {
- procs.push(proc("proc-11111111", true), proc("proc-22222222", true));
- hook.ping();
- const last = owner.background().at(-1)!;
- expect(last).toMatchObject({ processes: 2, subagents: 0 });
- expect(t.deps.manager.backgroundTasksOf(SID)).toEqual({ processes: 2, subagents: 0 });
- expect(t.deps.manager.backgroundTasksOf(SID_UNLOADED)).toBeUndefined();
- });
});
diff --git a/packages/server/test/session-created-events.test.ts b/packages/server/test/session-created-events.test.ts
index bdb15d53..6e7d8639 100644
--- a/packages/server/test/session-created-events.test.ts
+++ b/packages/server/test/session-created-events.test.ts
@@ -1,14 +1,18 @@
/**
* `session_created` on the user channel: the list learns about rows it did not make.
*
- * A Session created by the CLI, by another tab, by a schedule or by an agent spawning a
- * child went through the same route as one created from the list — and the list never
- * heard about it, because nothing announced it. `session_state` and `session_title` cannot
- * stand in: both act on a row the list already holds and ignore an unknown id. So this
- * event is the one thing that makes a Session appear without a reload, and the audience
- * rule is the same as for the state events: the Project's owner and members, nobody else.
+ * A Session created by the CLI, another tab, a schedule or an agent spawning a child goes
+ * through the same route as one created from the list, and the list never heard about it.
+ * `session_state` and `session_title` cannot stand in: both act on a row the list already
+ * holds. So this event is what makes a Session appear without a reload.
+ *
+ * - A new Session reaches the Project's owner and members with its ids (and no source marker
+ * for a user-created one), and nobody else.
+ * - The event is published after the row is in place, so a reader who reloads on it finds it.
+ * - A title set by PATCH (the CLI's --title, another tab's rename) is announced to the same
+ * audience.
*/
-import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
import type {
ProjectCreateResponse,
ServerEvent,
@@ -36,7 +40,7 @@ describe("session_created on the user channel", () => {
let projectId: string;
let boxes: { owner: ServerEvent[]; member: ServerEvent[]; stranger: ServerEvent[] };
- beforeEach(async () => {
+ beforeAll(async () => {
t = await createTestApp();
const a = await provisionUser(t.app, "owner");
await provisionUser(t.app, "member");
@@ -51,6 +55,11 @@ describe("session_created on the user channel", () => {
defaultModel: { provider: "anthropic", modelId: "claude-sonnet-4-6" },
models: [{ provider: "anthropic", modelId: "claude-sonnet-4-6", contextWindow: 128000 }],
});
+ });
+ afterAll(async () => {
+ await t.cleanup();
+ });
+ beforeEach(() => {
boxes = {
owner: inbox(t, "owner"),
member: inbox(t, "member"),
@@ -58,10 +67,6 @@ describe("session_created on the user channel", () => {
};
});
- afterEach(async () => {
- await t.cleanup();
- });
-
it("reaches the Project's owner and members with the new row's ids, and nobody else", async () => {
const res = (await (
await owner.post(`/api/projects/${projectId}/agents/default_agent/sessions`, {})
diff --git a/packages/server/test/session-delete-scratchpad.test.ts b/packages/server/test/session-delete-scratchpad.test.ts
index cd29945a..0bbdc166 100644
--- a/packages/server/test/session-delete-scratchpad.test.ts
+++ b/packages/server/test/session-delete-scratchpad.test.ts
@@ -1,12 +1,17 @@
/**
- * Integration tests for Session deletion cleanup: DELETE /api/sessions/:id
- * removes the Session's scratchpad directory (model-generated temp files and
- * input images saved to disk for models without image support) in addition
- * to its Trace and index row.
+ * A Session's scratchpad through its routes: the per-Session directory holding the files its
+ * Tasks attached and the model wrote.
+ *
+ * - Deleting a Session removes its scratchpad along with its Trace and index row; deleting one
+ * that never had a scratchpad succeeds too.
+ * - A scratchpad file reads back with its content type, a non-ASCII name included; a missing
+ * file and any name that is a path (separators either way, traversal) are 404s.
+ *
+ * Both cases create their own Sessions, so one app serves them.
*/
import fs from "node:fs/promises";
import path from "node:path";
-import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { scratchpadDir } from "@prismshadow/penguin-core";
import type { ProjectCreateResponse, SessionCreateResponse } from "../src/api/types.js";
import { apiClient, createTestApp, provisionUser } from "./helpers.js";
@@ -26,7 +31,7 @@ describe("session deletion cleans up the scratchpad", () => {
let owner: ReturnType<typeof apiClient>;
let projectId: string;
- beforeEach(async () => {
+ beforeAll(async () => {
t = await createTestApp();
const a = await provisionUser(t.app, "owner_s");
owner = apiClient(t.app, a.cookie);
@@ -42,7 +47,7 @@ describe("session deletion cleans up the scratchpad", () => {
models: [{ provider: "anthropic", modelId: "claude-sonnet-4-6" }],
});
});
- afterEach(async () => {
+ afterAll(async () => {
await t.cleanup();
});
diff --git a/packages/server/test/session-fork.test.ts b/packages/server/test/session-fork.test.ts
index b528457b..65de1381 100644
--- a/packages/server/test/session-fork.test.ts
+++ b/packages/server/test/session-fork.test.ts
@@ -1,3 +1,19 @@
+/**
+ * Forking a Session at one of its replies (POST /api/sessions/:id/fork).
+ *
+ * - A fork copies the history through the selected reply, snapshots the scratchpad, rewrites
+ * the local attachment markers to its own copy, and outlives the source's deletion.
+ * - Forks of one source share a persistent number sequence, whatever reply they start from; a
+ * source with no title forks under a readable numbered fallback.
+ * - A fork that fails after its row was committed removes the row and the cloned files.
+ * - A user message, an intermediate assistant segment and a hidden compaction summary are not
+ * fork points; a running source is a 409 task_in_progress.
+ * - A missing scratchpad forks as empty, and deleting the fork leaves the source intact.
+ * - Completed earlier shards are cloned and the selected one cut, with stable positions on a
+ * tail page.
+ * - Concurrent forks get unique Sessions and never overwrite the source.
+ * - A user without Project access is not told the endpoint exists.
+ */
import fs from "node:fs/promises";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -25,6 +41,7 @@ import { apiClient, createTestApp, provisionUser, writeTraceFile, waitFor } from
import type { TestApp } from "./helpers.js";
import type { SessionRow } from "../src/db/repos/sessions.js";
import type { RuntimeSession } from "../src/runtime/session-manager.js";
+import { fakeSession } from "./fixtures/session.js";
const SID = "session-2026-08-14-10-00-00-aabbcc01";
@@ -37,19 +54,12 @@ function at(timestamp: string, message: OmniMessage): OmniMessage {
}
function parkingFakeSession(sessionId: string, until: Promise<void>): RuntimeSession {
- return {
- sessionId,
- toolPermission: () => "rw",
- generateTitle: async () => ({ title: null, usage: null }),
- compactability: () => "ok" as const,
- steer: () => false,
- skipReconnectWait: () => false,
+ return fakeSession(sessionId, {
async *run() {
await until;
yield assistantText("done");
},
- async *compact() {},
- };
+ });
}
describe("session fork", () => {
diff --git a/packages/server/test/session-manager.test.ts b/packages/server/test/session-manager.test.ts
index 606be9c0..efd36a29 100644
--- a/packages/server/test/session-manager.test.ts
+++ b/packages/server/test/session-manager.test.ts
@@ -1,15 +1,47 @@
/**
- * Unit tests for the Session runtime (a fake Session / Loader is injected; no
- * real LLM requests are made): driving and state transitions, 409 mutual
- * exclusion, the four approval modes and taking effect immediately on change,
- * an organization's session denying rather than waiting for a person who is not there,
- * abort collapsing to deny, self-healing id swaps, vault invalidation re-resuming
- * stale runtimes, and LLM / tool errors in the message stream being persisted
- * (core doesn't throw, so try/catch can't catch them).
+ * The Session runtime (SessionManager) over scripted runtime Sessions. No model is ever
+ * called; one case drives a real core Session, with a scripted LLM, and a real OS process.
+ *
+ * Driving:
+ * - An unknown Session is a 404. A Task publishes its input first, runs, returns to idle and
+ * pushes task_state; the row's last-active stamp moves at the start and the end of each run
+ * (a failing stamp write strands nothing); outputs reach the recorder with their context.
+ * - The thinking level is runtime state the manager assigns, reaching a live child and a
+ * runtime still loading.
+ * - Background notices arriving while idle auto-start a Task carrying them (adopted Sessions
+ * included); live subagent messages are published and their usage recorded; end to end, a
+ * real background command finishing after idle reaches the channel as a harness message.
+ * - LLM and tool failures folded into the stream are recorded with the Session's context.
+ * - A second Task or a compaction while running is a 409; each compact refusal has its own code.
+ * - Steering reaches the running Session (idle or a lost race is a 409), with a mirror that is
+ * broadcast, shifted at delivery and dropped at the run's end; follow-ups queue while running
+ * or compacting and start in order afterwards, surviving an abort.
+ *
+ * Approvals:
+ * - always-ask parks the call and pushes approval_request; deny-all and read-only decide
+ * without a person; an organization's Session denies what would wait for a person, while a
+ * development Session under the same mode still waits; a mode PATCHed mid-run applies to the
+ * next decision; an abort collapses pending approvals to deny before the signal fires.
+ * - A sub-session inherits its parent's organization stamp and persists its session_meta.
+ *
+ * Lifecycle:
+ * - Session deletion interrupts and blocks new Tasks until it ends; a loader answering a new id
+ * heals the index; a swept channel is re-read before every publish; a Project abort hands
+ * back its in-flight runs; a loader's HttpError passes through; shutdown disposes every
+ * environment and refuses new Tasks, and a run parked on an approval is denied, winds down,
+ * and is disposed only after it has.
+ * - Idle entries are evicted (running ones, pending approvals and working subagents pin them);
+ * invalidating an Agent's or a Project's runtimes rebuilds them at next access, never
+ * mid-run, and publishes a discarded runtime's background count as cleared.
+ *
+ * Titles:
+ * - Title generation fires at Task start, before any model output, from the user's input
+ * alone (never from a compaction); a subagent's fires at registration from its spawning
+ * prompt.
*/
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import type { DatabaseSync } from "node:sqlite";
-import { mkdtemp, rm } from "node:fs/promises";
+import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import {
@@ -53,6 +85,7 @@ import type { RuntimeSession, SessionLoader } from "../src/runtime/session-manag
import { SessionSources } from "../src/runtime/session-sources.js";
import type { TitleRequest } from "../src/runtime/title-generator.js";
import type { UsageContext } from "../src/runtime/usage-recorder.js";
+import { fakeSession } from "./fixtures/session.js";
import { waitFor } from "./helpers.js";
import { wire } from "@prismshadow/penguin-core/kernel";
@@ -71,13 +104,8 @@ const ROW: SessionRow = {
/** A simple, scriptable fake Session: run yields one tool_call and requests approval for it. */
function approvalFakeSession(sessionId: string, toolName = "write_file"): RuntimeSession {
- return {
- sessionId,
+ return fakeSession(sessionId, {
toolPermission: (name) => (name === "read_tool" ? "r" : "rw"),
- generateTitle: async () => ({ title: null, usage: null }),
- compactability: () => "ok" as const,
- steer: () => false,
- skipReconnectWait: () => false,
async *run(_input: OmniMessage[], opts: { approve: ApproveFn; signal: AbortSignal }) {
const tc = toolCall({ name: toolName, arguments: "{}", toolCallId: "tc-1" });
yield tc;
@@ -93,7 +121,7 @@ function approvalFakeSession(sessionId: string, toolName = "write_file"): Runtim
yield compactionBegin({ reason: "manual", mode: "summarize", context: 1, turns: 1 });
yield compactionEnd({ reason: "manual", mode: "summarize", status: "completed" });
},
- };
+ });
}
/**
@@ -281,20 +309,13 @@ describe("session-manager", () => {
it("startTask carries no thinking level: the manager assigns runtime state instead", async () => {
sessions.updateApprovalMode("session-1", "allow-all");
const runOpts: Record<string, unknown>[] = [];
- const fake: RuntimeSession = {
- sessionId: "session-1",
- toolPermission: () => "rw",
+ const fake: RuntimeSession = fakeSession("session-1", {
thinkingLevel: undefined,
- generateTitle: async () => ({ title: null, usage: null }),
- compactability: () => "ok" as const,
- steer: () => false,
- skipReconnectWait: () => false,
async *run(_input: OmniMessage[], opts: Record<string, unknown>) {
runOpts.push(opts);
yield assistantText("ok");
},
- async *compact(): AsyncGenerator<OmniMessage> {},
- };
+ });
const manager = makeManager(loaderOf(fake));
await manager.startTask("session-1", [userText("a")]);
await waitFor(() => manager.statusOf("session-1") === "idle" && runOpts.length === 1);
@@ -358,21 +379,14 @@ describe("session-manager", () => {
let noticeCb: (() => void) | null = null;
const queue: OmniMessage[] = [];
const runInputs: OmniMessage[][] = [];
- const fake: RuntimeSession = {
- sessionId: "session-1",
- toolPermission: () => "rw",
- generateTitle: async () => ({ title: null, usage: null }),
- compactability: () => "ok" as const,
- steer: () => false,
- skipReconnectWait: () => false,
+ const fake: RuntimeSession = fakeSession("session-1", {
onBackgroundNotice: (cb) => (noticeCb = cb),
takeBackgroundNotices: () => queue.splice(0),
async *run(input: OmniMessage[]) {
runInputs.push(input);
yield assistantText("ok");
},
- async *compact(): AsyncGenerator<OmniMessage> {},
- };
+ });
const manager = makeManager(loaderOf(fake));
// First task loads the entry (which registers the notice listener) and finishes.
await manager.startTask("session-1", [userText("hi")]);
@@ -398,17 +412,10 @@ describe("session-manager", () => {
it("live-forwarded background-subagent messages publish to the channel and record usage", async () => {
let forward: ((msg: OmniMessage) => void) | null = null;
- const fake: RuntimeSession = {
- sessionId: "session-1",
- toolPermission: () => "rw",
- generateTitle: async () => ({ title: null, usage: null }),
- compactability: () => "ok" as const,
- steer: () => false,
- skipReconnectWait: () => false,
+ const fake: RuntimeSession = fakeSession("session-1", {
onBackgroundMessage: (cb) => (forward = cb),
async *run() {},
- async *compact(): AsyncGenerator<OmniMessage> {},
- };
+ });
const manager = makeManager(loaderOf(fake));
manager.adopt(sessions.findById("session-1")!, fake);
expect(forward).not.toBeNull();
@@ -428,21 +435,14 @@ describe("session-manager", () => {
let noticeCb: (() => void) | null = null;
const queue: OmniMessage[] = [];
const runInputs: OmniMessage[][] = [];
- const fake: RuntimeSession = {
- sessionId: "session-1",
- toolPermission: () => "rw",
- generateTitle: async () => ({ title: null, usage: null }),
- compactability: () => "ok" as const,
- steer: () => false,
- skipReconnectWait: () => false,
+ const fake: RuntimeSession = fakeSession("session-1", {
onBackgroundNotice: (cb) => (noticeCb = cb),
takeBackgroundNotices: () => queue.splice(0),
async *run(input: OmniMessage[]) {
runInputs.push(input);
yield assistantText("ok");
},
- async *compact(): AsyncGenerator<OmniMessage> {},
- };
+ });
const manager = makeManager(loaderOf(fake));
const row = sessions.findById("session-1")!;
manager.adopt(row, fake);
@@ -476,7 +476,9 @@ describe("session-manager", () => {
},
});
// Turn 1: launch a command that outlives the task; turn 2: final reply (task ends,
- // session idle, process still running); turn 3 is the auto-started notice task.
+ // session idle, process still running); turn 3 is the auto-started notice task. The
+ // command waits for a file the test writes once the Session is idle, so "finishing after
+ // idle" is an ordering the test makes rather than a race against a sleep.
const llm = new (class implements LLMInterface {
calls = 0;
inputs: OmniMessage[][] = [];
@@ -489,7 +491,7 @@ describe("session-manager", () => {
yield toolCall({
name: "exec_command",
arguments: JSON.stringify({
- cmd: "printf 'serving'; sleep 1",
+ cmd: "printf 'serving'; while [ ! -f release ]; do sleep 0.05; done",
run_in_background: true,
}),
toolCallId: "tc_bg",
@@ -531,8 +533,9 @@ describe("session-manager", () => {
// what follows is genuinely the idle-arrival path.
expect(events.some((e) => e.data.includes("background_task_done"))).toBe(false);
- // The process exits ~1s in: the completion report must land on the channel as a
- // harness user message and auto-start a task the model answers.
+ // Let the command finish: its completion report must land on the channel as a harness
+ // user message and auto-start a task the model answers.
+ await writeFile(path.join(dir, "release"), "");
await waitFor(() => events.some((e) => e.data.includes("background_task_done")), 8000);
const notice = events.find((e) => e.data.includes("background_task_done"))!;
expect(notice.data).toContain('"sender":"harness"');
@@ -559,13 +562,7 @@ describe("session-manager", () => {
// core folds LLM / tool failures into the message stream (no throw): a tool
// failure produces one tool_call_output(failed), an LLM failure produces one
// request_end(failed) + an abort carrying the real reason.
- const failing: RuntimeSession = {
- sessionId: "session-1",
- toolPermission: () => "rw",
- generateTitle: async () => ({ title: null, usage: null }),
- compactability: () => "ok" as const,
- steer: () => false,
- skipReconnectWait: () => false,
+ const failing: RuntimeSession = fakeSession("session-1", {
async *run(): AsyncGenerator<OmniMessage> {
yield requestBegin();
yield toolCall({ name: "write_file", arguments: "{}", toolCallId: "tc-1" });
@@ -582,8 +579,7 @@ describe("session-manager", () => {
errorMessage: "500 upstream",
});
},
- async *compact(): AsyncGenerator<OmniMessage> {},
- };
+ });
const manager = makeManager(loaderOf(failing), { record: (args) => captured.push(args) });
await manager.startTask("session-1", [userText("run")]);
await waitFor(() => manager.statusOf("session-1") === "idle" && captured.length >= 2);
@@ -794,13 +790,7 @@ describe("session-manager", () => {
it("queueIfBusy during compaction: the queue drains once the compaction ends", async () => {
const runInputs: string[][] = [];
let releaseCompact: (() => void) | null = null;
- const fake: RuntimeSession = {
- sessionId: "session-1",
- toolPermission: () => "rw",
- generateTitle: async () => ({ title: null, usage: null }),
- compactability: () => "ok" as const,
- steer: () => false,
- skipReconnectWait: () => false,
+ const fake: RuntimeSession = fakeSession("session-1", {
// eslint-disable-next-line require-yield
async *run(input: OmniMessage[]): AsyncGenerator<OmniMessage> {
runInputs.push(input.map((m) => (m.payload as { text?: string }).text ?? ""));
@@ -812,7 +802,7 @@ describe("session-manager", () => {
yield compactionBegin({ reason: "manual", mode: "summarize", context: 1, turns: 1 });
yield compactionEnd({ reason: "manual", mode: "summarize", status: "completed" });
},
- };
+ });
const manager = makeManager(loaderOf(fake));
await manager.startCompact("session-1");
await waitFor(() => releaseCompact !== null);
@@ -931,32 +921,26 @@ describe("session-manager", () => {
it("a sub-session registered under an organization's Session inherits its org stamp; one under an ordinary Session stays unmarked", async () => {
// A desk session: the organization runtime stamped it at creation.
sessions.insert({ ...ROW, sessionId: "session-org", client: "org" });
- const spawning = (sessionId: string, childId: string): RuntimeSession => ({
- sessionId,
- toolPermission: () => "rw",
- generateTitle: async () => ({ title: null, usage: null }),
- compactability: () => "ok" as const,
- steer: () => false,
- skipReconnectWait: () => false,
- async *run() {
- yield withOrigin(
- sessionMeta({
- session_id: childId,
- model_id: "m-child",
- provider: "custom",
- model_context_window: 1000,
- system_prompt: "sys",
- agent_state: "/root/p1/child_agent/agent_state",
- workspace: "/tmp/w-child",
- source: "subagent",
- }),
- childId,
- );
- yield withOrigin(assistantText("child done"), childId);
- yield assistantText("done");
- },
- async *compact() {},
- });
+ const spawning = (sessionId: string, childId: string): RuntimeSession =>
+ fakeSession(sessionId, {
+ async *run() {
+ yield withOrigin(
+ sessionMeta({
+ session_id: childId,
+ model_id: "m-child",
+ provider: "custom",
+ model_context_window: 1000,
+ system_prompt: "sys",
+ agent_state: "/root/p1/child_agent/agent_state",
+ workspace: "/tmp/w-child",
+ source: "subagent",
+ }),
+ childId,
+ );
+ yield withOrigin(assistantText("child done"), childId);
+ yield assistantText("done");
+ },
+ });
const manager = makeManager({
load: async (row) =>
spawning(row.sessionId, row.sessionId === "session-org" ? "child-org" : "child-plain"),
@@ -973,13 +957,7 @@ describe("session-manager", () => {
});
it("sub-session (origin) registration: session_meta persists; the title is generated from the spawning prompt", async () => {
- const fake: RuntimeSession = {
- sessionId: "session-1",
- toolPermission: () => "rw",
- generateTitle: async () => ({ title: null, usage: null }),
- compactability: () => "ok" as const,
- steer: () => false,
- skipReconnectWait: () => false,
+ const fake: RuntimeSession = fakeSession("session-1", {
async *run() {
// The parent-level run_subagent call (no origin): its prompt becomes the sub-session title.
yield toolCall({
@@ -1003,8 +981,7 @@ describe("session-manager", () => {
yield withOrigin(assistantText("child done"), hop);
yield assistantText("done");
},
- async *compact() {},
- };
+ });
const notified: Array<{ ctx: UsageContext; req: TitleRequest }> = [];
const manager = new SessionManager({
sessions,
@@ -1050,13 +1027,7 @@ describe("session-manager", () => {
it("approval mode takes effect immediately: after a mid-run PATCH, the next decision uses the new mode", async () => {
// A fake Session that requests approval twice.
- const fake: RuntimeSession = {
- sessionId: "session-1",
- toolPermission: () => "rw",
- generateTitle: async () => ({ title: null, usage: null }),
- compactability: () => "ok" as const,
- steer: () => false,
- skipReconnectWait: () => false,
+ const fake: RuntimeSession = fakeSession("session-1", {
async *run(_input, opts) {
const tc1 = toolCall({ name: "t1", arguments: "{}", toolCallId: "tc-1" });
yield tc1;
@@ -1065,8 +1036,7 @@ describe("session-manager", () => {
yield tc2;
yield approvalDecision(await opts.approve(tc2), "tc-2");
},
- async *compact() {},
- };
+ });
const manager = makeManager(loaderOf(fake));
await manager.startTask("session-1", [userText("go")]);
await waitFor(() => manager.pendingApprovalCount("session-1") === 1);
@@ -1188,6 +1158,34 @@ describe("session-manager", () => {
expect(disposed).toBe(1);
});
+ it("shutdown denies a call parked on a person, lets the run wind down, and disposes after it", async () => {
+ // What a hot swap or an exit meets mid-conversation: a run waiting on an approval nobody
+ // in this process will ever give.
+ const order: string[] = [];
+ const fake = fakeSession("session-1", {
+ async *run(_input: OmniMessage[], opts: { approve: ApproveFn; signal: AbortSignal }) {
+ try {
+ const tc = toolCall({ name: "write_file", arguments: "{}", toolCallId: "tc-1" });
+ yield tc;
+ order.push(`decided ${await opts.approve(tc)}`);
+ order.push(`aborted ${String(opts.signal.aborted)}`);
+ } finally {
+ order.push("run ended");
+ }
+ },
+ });
+ (fake as { dispose?: () => void }).dispose = () => {
+ order.push("disposed");
+ };
+ const manager = makeManager(loaderOf(fake));
+ await manager.startTask("session-1", [userText("write it")]);
+ await waitFor(() => manager.pendingApprovalCount("session-1") === 1);
+
+ await manager.shutdown();
+ // The environment goes only once the run has let go of it.
+ expect(order).toEqual(["decided deny", "aborted true", "run ended", "disposed"]);
+ });
+
it("rejects new Tasks once shutdown is set (503 shutting_down)", async () => {
const manager = makeManager(loaderOf(approvalFakeSession("session-1")));
await manager.shutdown();
@@ -1372,18 +1370,12 @@ describe("session-manager", () => {
let running = true;
let loads = 0;
let forward: ((msg: OmniMessage) => void) | null = null;
- const fake = (): RuntimeSession => ({
- sessionId: "session-1",
- toolPermission: () => "rw",
- generateTitle: async () => ({ title: null, usage: null }),
- compactability: () => "ok" as const,
- steer: () => false,
- skipReconnectWait: () => false,
- hasRunningBackgroundSubagents: () => running,
- onBackgroundMessage: (cb) => (forward = cb),
- async *run() {},
- async *compact(): AsyncGenerator<OmniMessage> {},
- });
+ const fake = (): RuntimeSession =>
+ fakeSession("session-1", {
+ hasRunningBackgroundSubagents: () => running,
+ onBackgroundMessage: (cb) => (forward = cb),
+ async *run() {},
+ });
const manager = makeManager({
load: async () => {
loads++;
@@ -1432,13 +1424,7 @@ describe("session-manager", () => {
it("notifies title generation at Task start: fallback and generation material are the user input alone; compaction doesn't notify", async () => {
const notified: { ctx: UsageContext; session: unknown; req: TitleRequest }[] = [];
- const plainSession: RuntimeSession = {
- sessionId: "session-1",
- toolPermission: () => "rw",
- generateTitle: async () => ({ title: null, usage: null }),
- compactability: () => "ok" as const,
- steer: () => false,
- skipReconnectWait: () => false,
+ const plainSession: RuntimeSession = fakeSession("session-1", {
async *run() {
yield thinkingMessage("thinking");
yield assistantText("answer A");
@@ -1449,7 +1435,7 @@ describe("session-manager", () => {
yield compactionBegin({ reason: "manual", mode: "summarize", context: 1, turns: 1 });
yield compactionEnd({ reason: "manual", mode: "summarize", status: "completed" });
},
- };
+ });
const manager = new SessionManager({
sessions,
channels,
@@ -1495,19 +1481,12 @@ describe("session-manager", () => {
// generation starts without waiting on any model output.
let release!: () => void;
const gate = new Promise<void>((r) => (release = r));
- const gatedRun: RuntimeSession = {
- sessionId: "session-1",
- toolPermission: () => "rw",
- generateTitle: async () => ({ title: null, usage: null }),
- compactability: () => "ok" as const,
- steer: () => false,
- skipReconnectWait: () => false,
+ const gatedRun: RuntimeSession = fakeSession("session-1", {
async *run() {
await gate;
yield assistantText("answer");
},
- async *compact() {},
- };
+ });
const manager = new SessionManager({
sessions,
channels,
@@ -1541,13 +1520,7 @@ describe("session-manager", () => {
// be in by then, proving neither waited for the run to complete.
let release!: () => void;
const gate = new Promise<void>((r) => (release = r));
- const delegating: RuntimeSession = {
- sessionId: "session-1",
- toolPermission: () => "rw",
- generateTitle: async () => ({ title: null, usage: null }),
- compactability: () => "ok" as const,
- steer: () => false,
- skipReconnectWait: () => false,
+ const delegating: RuntimeSession = fakeSession("session-1", {
async *run() {
yield toolCall({
name: "run_subagent",
@@ -1571,8 +1544,7 @@ describe("session-manager", () => {
await gate;
yield assistantText("short answer");
},
- async *compact() {},
- };
+ });
const manager = new SessionManager({
sessions,
channels,
diff --git a/packages/server/test/session-processes.test.ts b/packages/server/test/session-processes.test.ts
index 0352e749..06b66abf 100644
--- a/packages/server/test/session-processes.test.ts
+++ b/packages/server/test/session-processes.test.ts
@@ -1,31 +1,25 @@
/**
- * Integration tests for the session background-process endpoints:
- * - GET /api/sessions/:id/processes — list (ISO startedAt, running flag);
- * - POST /api/sessions/:id/processes/:pid/kill — stop a running process (drops the row);
- * - DELETE /api/sessions/:id/processes/:pid — remove an EXITED entry from the list:
- * 204 removes it, 409 process_running while it still runs (stop is the kill route's
- * job — removal never signals a live process group), 404 for unknown ids and for
- * sessions whose runtime is gone (nothing left to remove either way);
- * - POST /api/sessions/:id/tool-calls/:tcid/background — hand an executing call back as a
- * background task: 204, 404 tool_call_not_found when nothing with that id is running,
- * 409 tool_not_detachable when the tool has no background form;
- * - 404 for foreign/unknown sessions (the shared resolveSession semantics).
+ * The Session background-process endpoints the process panel drives.
+ *
+ * - GET lists the runtime's processes with ISO start times (refreshing their service probes);
+ * an unloaded Session reports none.
+ * - Kill stops a running process and drops its row.
+ * - DELETE removes an EXITED entry (204); a running one is a 409 process_running (removal never
+ * signals a live process group — stopping is the kill route's job); an unknown id, or a
+ * Session whose runtime is gone, is a 404.
+ * - Backgrounding hands an executing call back as a background task (204); a call that is not
+ * running is a 404 tool_call_not_found, a tool with no background form a 409.
+ * - Foreign and unknown Sessions are 404s, as on every Session route.
*/
-import { afterEach, beforeEach, describe, expect, it } from "vitest";
-import type {
- BackgroundCommandInfo,
- OmniMessage,
- ApproveFn,
- ToolDetachResult,
-} from "@prismshadow/penguin-core";
+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
+import type { BackgroundCommandInfo, ToolDetachResult } from "@prismshadow/penguin-core";
import type { SessionProcessesResponse } from "../src/api/types.js";
-import type { SessionRow } from "../src/db/repos/sessions.js";
import type { RuntimeSession } from "../src/runtime/session-manager.js";
+import { adoptSession, fakeSession, sessionRow, uniqueSessionId } from "./fixtures/session.js";
import { apiClient, createTestApp, provisionUser } from "./helpers.js";
import type { TestApp } from "./helpers.js";
-const SID = "session-2026-08-18-10-00-00-ccdd0031";
-const SID_UNLOADED = "session-2026-08-18-10-00-00-ccdd0032";
+const PROJECT = "procuser-default_project";
const STARTED_AT = Date.UTC(2026, 7, 18, 12, 4, 0);
/**
@@ -46,15 +40,7 @@ function processesFakeSession(
probes?: string[],
detaches?: string[],
): RuntimeSession {
- return {
- sessionId,
- toolPermission: () => "rw",
- generateTitle: async () => ({ title: null, usage: null }),
- compactability: () => "ok" as const,
- steer: () => false,
- skipReconnectWait: () => false,
- async *run(_input: OmniMessage[], _opts: { approve: ApproveFn; signal: AbortSignal }) {},
- async *compact() {},
+ return fakeSession(sessionId, {
listBackgroundCommands: () => [...procs],
probeBackgroundCommandServices: async () => {
probes?.push(sessionId);
@@ -71,37 +57,31 @@ function processesFakeSession(
if (answer === "detached") detaches?.push(toolCallId);
return answer;
},
- };
+ });
}
describe("session processes routes", () => {
let t: TestApp;
let api: ReturnType<typeof apiClient>;
let outsider: ReturnType<typeof apiClient>;
+ let SID: string;
+ let SID_UNLOADED: string;
let procs: BackgroundCommandInfo[];
let kills: string[];
let probes: string[];
let detaches: string[];
- const sessionRow = (sessionId: string): SessionRow => ({
- sessionId,
- projectId: "procuser-default_project",
- agentId: "default_agent",
- modelId: "m1",
- provider: "custom",
- workspace: "/tmp/w",
- approvalMode: "always-ask",
- title: null,
- createdAt: new Date().toISOString(),
- lastActiveAt: new Date().toISOString(),
- });
-
- beforeEach(async () => {
+ beforeAll(async () => {
t = await createTestApp();
- const { cookie } = await provisionUser(t.app, "procuser");
- const other = await provisionUser(t.app, "outsider_p");
- api = apiClient(t.app, cookie);
- outsider = apiClient(t.app, other.cookie);
+ api = apiClient(t.app, (await provisionUser(t.app, "procuser")).cookie);
+ outsider = apiClient(t.app, (await provisionUser(t.app, "outsider_p")).cookie);
+ });
+ afterAll(async () => {
+ await t.cleanup();
+ });
+ beforeEach(() => {
+ SID = uniqueSessionId();
+ SID_UNLOADED = uniqueSessionId();
procs = [
{
processId: "proc-11111111",
@@ -124,16 +104,12 @@ describe("session processes routes", () => {
kills = [];
probes = [];
detaches = [];
- t.deps.sessionsRepo.insert(sessionRow(SID));
- t.deps.manager.adopt(
- sessionRow(SID),
- processesFakeSession(SID, procs, kills, probes, detaches),
- );
+ adoptSession(t.deps, processesFakeSession(SID, procs, kills, probes, detaches), {
+ projectId: PROJECT,
+ approvalMode: "always-ask",
+ });
// A second session with no runtime entry: truthfully reports no processes.
- t.deps.sessionsRepo.insert(sessionRow(SID_UNLOADED));
- });
- afterEach(async () => {
- await t.cleanup();
+ t.deps.sessionsRepo.insert(sessionRow(SID_UNLOADED, { projectId: PROJECT }));
});
it("GET lists the runtime's processes with ISO start times; an unloaded session reports none", async () => {
diff --git a/packages/server/test/session-state-events.test.ts b/packages/server/test/session-state-events.test.ts
index aa28a6a2..f952b6c4 100644
--- a/packages/server/test/session-state-events.test.ts
+++ b/packages/server/test/session-state-events.test.ts
@@ -2,44 +2,29 @@
* `session_state` on the user channel: the run-state flip a Session list can act on.
*
* The per-Session `task_state` event is session-scoped and deliberately carries no id, so it
- * only ever reaches the one conversation a client has subscribed to. This is its user-channel
- * counterpart — named by `sessionId`, carrying the row stamp — and what these tests pin is its
- * SCOPE: it reaches the Project's owner and its members, and nobody else, not even a logged-in
- * user with a live channel of their own.
+ * only ever reaches the one conversation a client has subscribed to (sse-stream.test.ts pins
+ * its shape). This is its user-channel counterpart, named by `sessionId` and carrying the row
+ * stamp, and what these tests pin is its SCOPE.
*
- * The unchanged shape of `task_state` itself is pinned by sse-stream.test.ts, which compares
- * the frame with `toEqual` and would fail the moment an id appeared on it.
+ * - A run's running → idle flips reach the Project's owner and its members, and no other user,
+ * not even one with a live channel of their own.
+ * - The event names the Session and carries the row stamp a list fetch would return.
+ * - It carries hasTrace true from the first flip of a Session that had never run.
+ * - It carries none of the composer state the Session channel owns.
+ * - A member removed from the Project stops hearing about its Sessions.
*/
-import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { assistantText } from "@prismshadow/penguin-core";
import type { ServerEvent } from "../src/api/types.js";
-import type { SessionRow } from "../src/db/repos/sessions.js";
import { userChannelKey } from "../src/http/routes/events.js";
-import type { RuntimeSession } from "../src/runtime/session-manager.js";
+import { adoptSession, fakeSession, uniqueSessionId } from "./fixtures/session.js";
import { apiClient, createTestApp, provisionUser, waitFor } from "./helpers.js";
import type { TestApp } from "./helpers.js";
-const SID = "session-2026-08-19-10-00-00-abcd0001";
const PROJECT = "owner-default_project";
/** Comfortably before the run: the run-end stamp must be visibly later than this. */
const INSERTED_AT = "2026-08-19T09:00:00.000Z";
-/** Fake Session that answers once and returns, so a run is one clean running → idle pair. */
-function quickFakeSession(sessionId: string): RuntimeSession {
- return {
- sessionId,
- toolPermission: () => "rw",
- generateTitle: async () => ({ title: null, usage: null }),
- compactability: () => "ok" as const,
- steer: () => false,
- skipReconnectWait: () => false,
- async *run() {
- yield assistantText("done");
- },
- async *compact() {},
- };
-}
-
/** Everything one user's channel received, as a connected client would see it. */
function inbox(t: TestApp, userId: string) {
const events: ServerEvent[] = [];
@@ -55,10 +40,11 @@ function inbox(t: TestApp, userId: string) {
describe("session_state on the user channel", () => {
let t: TestApp;
let owner: { cookie: string };
+ let SID: string;
let boxes: { owner: ReturnType<typeof inbox>; member: ReturnType<typeof inbox> };
let stranger: ReturnType<typeof inbox>;
- beforeEach(async () => {
+ beforeAll(async () => {
t = await createTestApp();
owner = await provisionUser(t.app, "owner");
await provisionUser(t.app, "member");
@@ -71,30 +57,29 @@ describe("session_state on the user channel", () => {
})
).status,
).toBe(201);
+ });
+ afterAll(async () => {
+ await t.cleanup();
+ });
- const row: SessionRow = {
- sessionId: SID,
- projectId: PROJECT,
- agentId: "default_agent",
- provider: "custom",
- modelId: "m1",
- workspace: "/tmp/w",
- approvalMode: "allow-all",
- title: null,
- createdAt: INSERTED_AT,
- lastActiveAt: INSERTED_AT,
- };
- t.deps.sessionsRepo.insert(row);
- t.deps.manager.adopt(row, quickFakeSession(SID));
-
+ beforeEach(() => {
+ // A Session that answers once and returns, so a run is one clean running → idle pair,
+ // indexed without has_trace exactly as a freshly created conversation is.
+ SID = uniqueSessionId();
+ adoptSession(
+ t.deps,
+ fakeSession(SID, {
+ async *run() {
+ yield assistantText("done");
+ },
+ }),
+ { projectId: PROJECT, createdAt: INSERTED_AT, lastActiveAt: INSERTED_AT },
+ );
// Subscribe before anything runs: `peek` on the publish side means a channel that does not
// exist is skipped, so the test has to be listening the way a real client would be.
boxes = { owner: inbox(t, "owner"), member: inbox(t, "member") };
stranger = inbox(t, "stranger");
});
- afterEach(async () => {
- await t.cleanup();
- });
const runTask = async () => {
const res = await apiClient(t.app, owner.cookie).post(`/api/sessions/${SID}/tasks`, {
@@ -139,23 +124,21 @@ describe("session_state on the user channel", () => {
// queued / pendingSteering / pendingFollowUps belong to the conversation being watched,
// not to a list row.
for (const e of boxes.owner.states()) {
- expect(Object.keys(e).sort()).toEqual([
- "hasTrace",
- "lastActiveAt",
- "sessionId",
- "state",
- "type",
- ]);
+ expect(e).not.toHaveProperty("queued");
+ expect(e).not.toHaveProperty("pendingSteering");
+ expect(e).not.toHaveProperty("pendingFollowUps");
}
});
it("a member removed from the Project stops hearing about its Sessions", async () => {
- expect(
- (await apiClient(t.app, owner.cookie).delete(`/api/projects/${PROJECT}/members/member`))
- .status,
- ).toBe(204);
- await runTask();
- expect(boxes.owner.run()).toEqual(["running", "idle"]);
- expect(boxes.member.events).toEqual([]);
+ const api = apiClient(t.app, owner.cookie);
+ expect((await api.delete(`/api/projects/${PROJECT}/members/member`)).status).toBe(204);
+ try {
+ await runTask();
+ expect(boxes.owner.run()).toEqual(["running", "idle"]);
+ expect(boxes.member.events).toEqual([]);
+ } finally {
+ await api.post(`/api/projects/${PROJECT}/members`, { userId: "member" });
+ }
});
});
diff --git a/packages/server/test/session-subagents.test.ts b/packages/server/test/session-subagents.test.ts
index e187b5ed..489b1f56 100644
--- a/packages/server/test/session-subagents.test.ts
+++ b/packages/server/test/session-subagents.test.ts
@@ -1,36 +1,33 @@
/**
- * Integration tests for the panel's subagent endpoints and the child-liveness broadcast:
- * - POST /api/sessions/:id/subagents/:childSessionId/message — a user input on the child,
- * whatever its state: {outcome:"steered"} while it runs, {outcome:"started"} while idle,
- * {outcome:"resumed"} when the released child was revived; the resume option carries the
- * child's owning agent from its session row; 404 subagent_gone when nothing can be
- * revived, 409 subagent_busy when the child cannot take the message, 400 without text;
- * - POST /api/sessions/:id/subagents/:childSessionId/abort — 202 when a run was aborted,
- * 204 when the child is idle/unknown (nothing left to stop);
- * - `task_state` republished with the live `subagents` listing on every child state ping,
- * and the SSE subscribe snapshot carrying the same listing;
- * - 404 for foreign/unknown sessions (the shared resolveSession semantics).
+ * The panel's subagent endpoints and the child-liveness broadcast.
+ *
+ * - A message to a child is a user input whatever its state: steering while it runs, a
+ * follow-up run while it is idle, a revival when it was released (the resume carries the
+ * child's owning Agent from its session row); nothing to revive is a 404 subagent_gone, a
+ * child that cannot take it a 409 subagent_busy, no text a 400.
+ * - An abort ends the running child's round (202); an idle or unknown child is a 204.
+ * - task_state is republished with the live subagents listing on every child state ping, and
+ * the SSE subscribe snapshot carries the same listing.
+ * - Foreign and unknown Sessions are 404s, as on every Session route.
*/
-import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { toolCall, withOrigin } from "@prismshadow/penguin-core";
import type {
BackgroundSubagentInfo,
OmniMessage,
- ApproveFn,
SubagentMessageOptions,
SubagentMessageOutcome,
} from "@prismshadow/penguin-core";
import { ApprovalRegistry } from "../src/runtime/approvals.js";
import type { ServerEvent, SubagentMessageResponse } from "../src/api/types.js";
-import type { SessionRow } from "../src/db/repos/sessions.js";
import type { RuntimeSession } from "../src/runtime/session-manager.js";
+import { adoptSession, fakeSession, sessionRow, uniqueSessionId } from "./fixtures/session.js";
import { apiClient, createTestApp, provisionUser } from "./helpers.js";
import type { TestApp } from "./helpers.js";
-const SID = "session-2026-08-24-10-00-00-ccdd0041";
+const PROJECT = "subuser-default_project";
const CHILD_RUNNING = "session-2026-08-24-10-01-00-child001";
const CHILD_IDLE = "session-2026-08-24-10-01-00-child002";
-const CHILD_RELEASED = "session-2026-08-24-10-01-00-child003";
interface SentMessage {
childSessionId: string;
@@ -46,15 +43,7 @@ function subagentsFakeSession(
aborts: string[],
stateListeners: (() => void)[],
): RuntimeSession {
- return {
- sessionId,
- toolPermission: () => "rw",
- generateTitle: async () => ({ title: null, usage: null }),
- compactability: () => "ok" as const,
- steer: () => false,
- skipReconnectWait: () => false,
- async *run(_input: OmniMessage[], _opts: { approve: ApproveFn; signal: AbortSignal }) {},
- async *compact() {},
+ return fakeSession(sessionId, {
listBackgroundSubagents: () => children.map((c) => ({ ...c })),
sendToBackgroundSubagent: async (
childSessionId: string,
@@ -89,37 +78,31 @@ function subagentsFakeSession(
stateListeners.push(listener);
},
setSubagentApprovalFallback: () => {},
- };
+ });
}
describe("session subagent routes and liveness", () => {
let t: TestApp;
let api: ReturnType<typeof apiClient>;
let outsider: ReturnType<typeof apiClient>;
+ let SID: string;
+ let CHILD_RELEASED: string;
let children: BackgroundSubagentInfo[];
let sent: SentMessage[];
let aborts: string[];
let stateListeners: (() => void)[];
- const sessionRow = (sessionId: string): SessionRow => ({
- sessionId,
- projectId: "subuser-default_project",
- agentId: "default_agent",
- modelId: "m1",
- provider: "custom",
- workspace: "/tmp/w",
- approvalMode: "always-ask",
- title: null,
- createdAt: new Date().toISOString(),
- lastActiveAt: new Date().toISOString(),
- });
-
- beforeEach(async () => {
+ beforeAll(async () => {
t = await createTestApp();
- const { cookie } = await provisionUser(t.app, "subuser");
- const other = await provisionUser(t.app, "outsider_s");
- api = apiClient(t.app, cookie);
- outsider = apiClient(t.app, other.cookie);
+ api = apiClient(t.app, (await provisionUser(t.app, "subuser")).cookie);
+ outsider = apiClient(t.app, (await provisionUser(t.app, "outsider_s")).cookie);
+ });
+ afterAll(async () => {
+ await t.cleanup();
+ });
+ beforeEach(() => {
+ SID = uniqueSessionId();
+ CHILD_RELEASED = uniqueSessionId();
children = [
{ sessionId: CHILD_RUNNING, subagentId: "subagent-child001", running: true },
{ sessionId: CHILD_IDLE, subagentId: null, running: false },
@@ -127,17 +110,13 @@ describe("session subagent routes and liveness", () => {
sent = [];
aborts = [];
stateListeners = [];
- t.deps.sessionsRepo.insert(sessionRow(SID));
- t.deps.manager.adopt(
- sessionRow(SID),
- subagentsFakeSession(SID, children, sent, aborts, stateListeners),
- );
+ adoptSession(t.deps, subagentsFakeSession(SID, children, sent, aborts, stateListeners), {
+ projectId: PROJECT,
+ approvalMode: "always-ask",
+ });
// A released child with its own session row: the message route resolves its owning agent
// from this row and asks core to revive it.
- t.deps.sessionsRepo.insert(sessionRow(CHILD_RELEASED));
- });
- afterEach(async () => {
- await t.cleanup();
+ t.deps.sessionsRepo.insert(sessionRow(CHILD_RELEASED, { projectId: PROJECT }));
});
it("message: steering while the child runs, a follow-up run while it is idle", async () => {
diff --git a/packages/server/test/sse-stream.test.ts b/packages/server/test/sse-stream.test.ts
index 1aae372c..fe0eb16a 100644
--- a/packages/server/test/sse-stream.test.ts
+++ b/packages/server/test/sse-stream.test.ts
@@ -1,20 +1,22 @@
/**
- * Integration tests for the SSE endpoint (FD-1 / FD-2):
- * - Subscribing immediately delivers the current task_state snapshot (first
- * frame, ahead of any pending-approval replay);
- * - A Last-Event-ID with a mismatched/unknown epoch → sends resync_required
- * first; a buffer hit → replays events after it.
+ * The Session SSE endpoint (FD-1 / FD-2) and the user event stream.
+ *
+ * - A new subscription's first frame is always the task_state snapshot: idle when idle; when
+ * running, `running` followed by the replay of pending approvals.
+ * - A Last-Event-ID from another epoch gets resync_required first, then the snapshot; one that
+ * hits the replay buffer gets the later events, then the snapshot.
+ * - An admin resetting a user's password ends that user's open event streams at once, and the
+ * old session cannot reopen one.
*/
-import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { approvalDecision, assistantText, toolCall, userText } from "@prismshadow/penguin-core";
import type { ApproveFn, OmniMessage } from "@prismshadow/penguin-core";
import type { SessionRow } from "../src/db/repos/sessions.js";
import type { RuntimeSession } from "../src/runtime/session-manager.js";
+import { fakeSession, sessionRow, uniqueSessionId } from "./fixtures/session.js";
import { apiClient, createTestApp, loginAdmin, provisionUser, waitFor } from "./helpers.js";
import type { TestApp } from "./helpers.js";
-const SID = "session-2026-07-06-10-00-00-aabb0001";
-
interface SseFrame {
event?: string;
id?: string;
@@ -58,51 +60,36 @@ async function readSseFrames(res: Response, count: number, timeoutMs = 3000): Pr
/** Fake Session that requests one approval (for the running state and approval-replay scenarios). */
function approvalFakeSession(sessionId: string): RuntimeSession {
- return {
- sessionId,
- toolPermission: () => "rw",
- generateTitle: async () => ({ title: null, usage: null }),
- compactability: () => "ok" as const,
- steer: () => false,
- skipReconnectWait: () => false,
+ return fakeSession(sessionId, {
async *run(_input: OmniMessage[], opts: { approve: ApproveFn; signal: AbortSignal }) {
const tc = toolCall({ name: "exec_command", arguments: "{}", toolCallId: "tc-sse" });
yield tc;
- const decision = await opts.approve(tc);
- yield approvalDecision(decision, "tc-sse");
+ yield approvalDecision(await opts.approve(tc), "tc-sse");
yield assistantText("done");
},
- async *compact() {},
- };
+ });
}
describe("sse-stream", () => {
let t: TestApp;
let cookie: string;
+ let SID: string;
let row: SessionRow;
- beforeEach(async () => {
+ beforeAll(async () => {
t = await createTestApp();
({ cookie } = await provisionUser(t.app, "streamer"));
- row = {
- sessionId: SID,
- // streamer's own initial Project (default_project belongs to admin; others
- // get 404 via the index lookup).
- projectId: "streamer-default_project",
- agentId: "default_agent",
- modelId: "m1",
- provider: "custom",
- workspace: "/tmp/w",
- approvalMode: "always-ask",
- title: null,
- createdAt: new Date().toISOString(),
- lastActiveAt: new Date().toISOString(),
- };
- t.deps.sessionsRepo.insert(row);
});
- afterEach(async () => {
+ afterAll(async () => {
await t.cleanup();
});
+ beforeEach(() => {
+ SID = uniqueSessionId();
+ // streamer's own initial Project (default_project belongs to admin; others get 404 via
+ // the index lookup).
+ row = sessionRow(SID, { projectId: "streamer-default_project", approvalMode: "always-ask" });
+ t.deps.sessionsRepo.insert(row);
+ });
const getStream = (headers: Record<string, string> = {}) =>
t.app.request(`/api/sessions/${SID}/stream`, { headers: { cookie, ...headers } });
@@ -147,7 +134,9 @@ describe("sse-stream", () => {
});
it("an admin resetting the password ends the streams that user had open", async () => {
- const res = await t.app.request("/api/events", { headers: { cookie } });
+ // Its own user: the reset retires the session it is about.
+ const { cookie: own } = await provisionUser(t.app, "reset_streamer");
+ const res = await t.app.request("/api/events", { headers: { cookie: own } });
expect(res.status).toBe(200);
const reader = res.body!.getReader();
// The hello frame proves the subscription is live — and therefore registered — before
@@ -155,15 +144,16 @@ describe("sse-stream", () => {
expect(new TextDecoder().decode((await reader.read()).value)).toContain("hello");
const admin = await loginAdmin(t.app);
- const reset = await apiClient(t.app, admin.cookie).post("/api/admin/users/streamer/password", {
- password: "password-456",
- });
+ const reset = await apiClient(t.app, admin.cookie).post(
+ "/api/admin/users/reset_streamer/password",
+ { password: "password-456" },
+ );
expect(reset.status).toBe(204);
// Ended by the reset itself, within the same request: no heartbeat has passed, and the
// reader has made no request of its own that could have noticed.
expect((await reader.read()).done).toBe(true);
- expect((await t.app.request("/api/events", { headers: { cookie } })).status).toBe(401);
+ expect((await t.app.request("/api/events", { headers: { cookie: own } })).status).toBe(401);
});
it("FD-2: same-epoch Last-Event-ID hitting the buffer → replays later events, then the task_state snapshot", async () => {
diff --git a/packages/server/test/steer.test.ts b/packages/server/test/steer.test.ts
index f892cd68..a15c1004 100644
--- a/packages/server/test/steer.test.ts
+++ b/packages/server/test/steer.test.ts
@@ -1,17 +1,20 @@
/**
- * Integration tests for POST /api/sessions/:id/steer (mid-run steering):
- * - 202 while a Task is running, forwarding the trimmed text and its images to the core session;
- * - 400 when neither text nor images nor files carry a message, and for malformed
- * image URLs / file parts;
- * - file attachments land in the Session scratchpad and ride the steering text as
- * `[attached file: <path>]` lines (a 409 cleans them up again);
- * - the SSE subscribe snapshot carries the pending-steering mirror (task_state), which is
- * what keeps the composer's "steering queued" hint alive across reloads;
- * - 409 not_running when the Session is idle (the frontend then falls back to a
- * normal task POST);
- * - 404 for foreign/unknown sessions (via the shared resolveSession lookup).
+ * POST /api/sessions/:id/steer: mid-run steering, and its recall.
+ *
+ * - Given an idle Session, a steer is a 409 not_running (the composer falls back to a task).
+ * - Given a running one, the trimmed text reaches the core Session; a message with nothing in
+ * it, and malformed image URLs or file parts, are 400s.
+ * - Images ride along with the text, or carry the message alone.
+ * - File attachments land in the Session's scratchpad and ride the text as
+ * `[attached file: <path>]` lines; a refused steer cleans them up again.
+ * - The SSE subscribe snapshot carries the pending-steering mirror, which keeps the composer's
+ * "steering queued" hint alive across reloads.
+ * - A foreign or unknown Session is a 404.
+ * - A queued steer can be recalled with its content until core takes it; steering the run
+ * never delivered is handed back to the composer when it ends, once; steering it did deliver
+ * is not; a recall after delivery is a 409 not_pending.
*/
-import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { readFile, readdir, realpath } from "node:fs/promises";
import path from "node:path";
import {
@@ -23,14 +26,13 @@ import {
userText,
} from "@prismshadow/penguin-core";
import type { ApproveFn, OmniMessage } from "@prismshadow/penguin-core";
-import type { SessionRow } from "../src/db/repos/sessions.js";
import type { RuntimeSession } from "../src/runtime/session-manager.js";
+import { adoptSession, fakeSession, uniqueSessionId } from "./fixtures/session.js";
import { apiClient, createTestApp, provisionUser, waitFor } from "./helpers.js";
import type { TestApp } from "./helpers.js";
-const SID = "session-2026-07-06-10-00-00-ccdd0001";
+const PROJECT = "steerer-default_project";
-/** One recorded steer call: the trimmed text plus the images that rode along with it. */
/** A recorded steering input, one `text:`/`img:` line per message, in delivered order. */
const shape = (input: OmniMessage[]): string[] =>
input.map((m) => {
@@ -40,11 +42,7 @@ const shape = (input: OmniMessage[]): string[] =>
/** Fake Session that parks on one approval (keeps the Task running) and records steer calls. */
function steeringFakeSession(sessionId: string, steered: OmniMessage[][]): RuntimeSession {
- return {
- sessionId,
- toolPermission: () => "rw",
- generateTitle: async () => ({ title: null, usage: null }),
- compactability: () => "ok" as const,
+ return fakeSession(sessionId, {
steer: (input: OmniMessage[]) => {
steered.push(input);
return true;
@@ -57,46 +55,36 @@ function steeringFakeSession(sessionId: string, steered: OmniMessage[][]): Runti
steered.splice(i, 1);
return true;
},
- skipReconnectWait: () => false,
async *run(_input: OmniMessage[], opts: { approve: ApproveFn; signal: AbortSignal }) {
const tc = toolCall({ name: "exec_command", arguments: "{}", toolCallId: "tc-steer" });
yield tc;
- const decision = await opts.approve(tc);
- yield approvalDecision(decision, "tc-steer");
+ yield approvalDecision(await opts.approve(tc), "tc-steer");
yield assistantText("done");
},
- async *compact() {},
- };
+ });
}
describe("steer route", () => {
let t: TestApp;
let api: ReturnType<typeof apiClient>;
+ let SID: string;
let steered: OmniMessage[][];
- beforeEach(async () => {
+ beforeAll(async () => {
t = await createTestApp();
- const { cookie } = await provisionUser(t.app, "steerer");
- api = apiClient(t.app, cookie);
- const row: SessionRow = {
- sessionId: SID,
- projectId: "steerer-default_project",
- agentId: "default_agent",
- modelId: "m1",
- provider: "custom",
- workspace: "/tmp/w",
- approvalMode: "always-ask",
- title: null,
- createdAt: new Date().toISOString(),
- lastActiveAt: new Date().toISOString(),
- };
- t.deps.sessionsRepo.insert(row);
- steered = [];
- t.deps.manager.adopt(row, steeringFakeSession(SID, steered));
+ api = apiClient(t.app, (await provisionUser(t.app, "steerer")).cookie);
});
- afterEach(async () => {
+ afterAll(async () => {
await t.cleanup();
});
+ beforeEach(() => {
+ SID = uniqueSessionId();
+ steered = [];
+ adoptSession(t.deps, steeringFakeSession(SID, steered), {
+ projectId: PROJECT,
+ approvalMode: "always-ask",
+ });
+ });
it("idle → 409 not_running (the frontend falls back to a normal task POST)", async () => {
const res = await api.post(`/api/sessions/${SID}/steer`, { text: "hello" });
@@ -207,10 +195,7 @@ describe("steer route", () => {
// realpath, not string prefixes: on the Windows CI runner the temp root mixes 8.3
// short and long name forms, so two spellings of the same directory are expected.
const written = /\[attached file: (.*)\]/.exec(first[0]!)![1]!;
- const expectedDir = path.join(
- scratchpadDir(t.root, "steerer-default_project", "default_agent"),
- SID,
- );
+ const expectedDir = path.join(scratchpadDir(t.root, PROJECT, "default_agent"), SID);
expect(await realpath(path.dirname(written))).toBe(await realpath(expectedDir));
expect(path.basename(written)).toBe("notes.txt");
expect(await readFile(written, "utf8")).toBe("hello notes");
@@ -248,7 +233,7 @@ describe("steer route", () => {
files: [{ fileName: "orphan.txt", dataUrl: data }],
});
expect(res.status).toBe(409);
- const dir = path.join(scratchpadDir(t.root, "steerer-default_project", "default_agent"), SID);
+ const dir = path.join(scratchpadDir(t.root, PROJECT, "default_agent"), SID);
expect(await readdir(dir).catch(() => [])).toEqual([]);
});
@@ -307,7 +292,7 @@ describe("steer route", () => {
// Withdrawn everywhere: core's queue (the fake's unsteer), the mirror, and the disk copy.
expect(steered).toHaveLength(0);
expect(t.deps.manager.pendingSteeringOf(SID)).toEqual([]);
- const dir = path.join(scratchpadDir(t.root, "steerer-default_project", "default_agent"), SID);
+ const dir = path.join(scratchpadDir(t.root, PROJECT, "default_agent"), SID);
expect(await readdir(dir).catch(() => [])).toEqual([]);
// Nothing left under that id: a second recall (double click, another tab) is a 409.
@@ -370,32 +355,23 @@ describe("steer route", () => {
// handback runs after that stream is drained. A delivered message must therefore not
// return to the composer as though the user still owed it.
const delivering: OmniMessage[][] = [];
- const sid2 = "session-2026-07-06-10-00-00-ccdd0002";
- const row: SessionRow = {
- sessionId: sid2,
- projectId: "steerer-default_project",
- agentId: "default_agent",
- modelId: "m1",
- provider: "custom",
- workspace: "/tmp/w",
- approvalMode: "always-ask",
- title: null,
- createdAt: new Date().toISOString(),
- lastActiveAt: new Date().toISOString(),
- };
- t.deps.sessionsRepo.insert(row);
- t.deps.manager.adopt(row, {
- ...steeringFakeSession(sid2, delivering),
- async *run(_input: OmniMessage[], opts: { approve: ApproveFn; signal: AbortSignal }) {
- const tc = toolCall({ name: "exec_command", arguments: "{}", toolCallId: "tc-steer" });
- yield tc;
- const decision = await opts.approve(tc);
- yield approvalDecision(decision, "tc-steer");
- // The delivery itself: core emits one such message per queued entry.
- yield userText(userSteeringText("already gone"));
- yield assistantText("done");
+ const sid2 = uniqueSessionId();
+ const session = steeringFakeSession(sid2, delivering);
+ adoptSession(
+ t.deps,
+ {
+ ...session,
+ async *run(_input: OmniMessage[], opts: { approve: ApproveFn; signal: AbortSignal }) {
+ const tc = toolCall({ name: "exec_command", arguments: "{}", toolCallId: "tc-steer" });
+ yield tc;
+ yield approvalDecision(await opts.approve(tc), "tc-steer");
+ // The delivery itself: core emits one such message per queued entry.
+ yield userText(userSteeringText("already gone"));
+ yield assistantText("done");
+ },
},
- });
+ { projectId: PROJECT, approvalMode: "always-ask" },
+ );
await t.deps.manager.startTask(sid2, [userText("go")]);
await waitFor(() => t.deps.manager.pendingApprovalCount(sid2) === 1);
diff --git a/packages/server/test/task-attachments.test.ts b/packages/server/test/task-attachments.test.ts
index 5997df0a..6d39eccf 100644
--- a/packages/server/test/task-attachments.test.ts
+++ b/packages/server/test/task-attachments.test.ts
@@ -1,20 +1,24 @@
/**
- * Integration tests for composer file attachments (POST /api/sessions/:id/tasks with a
- * `{type:"file"}` input part):
- * - the bytes land in the Session scratchpad and the Prompt gains an
- * `[attached file: <path>]` line, so the model reaches the file by path;
- * - a files-only Prompt still reaches the model (the lines become the message), including
- * when the only text message is a `[handoff_from]` origin block that must stay parseable;
- * - two uploads of the same name coexist instead of overwriting each other;
- * - malformed parts are 400s, an oversize file / too many files / too many bytes are 413s,
- * and goal mode rejects attachments before anything is written;
- * - nothing survives a request that does not end up starting a Task, and a scratchpad
- * directory that resolves outside the Agent's scratchpad root is refused outright.
+ * Composer file attachments: POST /api/sessions/:id/tasks with `{type:"file"}` input parts.
+ *
+ * - The bytes land in the Session's scratchpad and the Prompt gains an `[attached file: <path>]`
+ * line after the user's text, so the model reaches the file by path.
+ * - A files-only Prompt still reaches the model (the lines become the message), and a Prompt
+ * whose only text is a `[handoff_from]` origin block keeps that block parseable.
+ * - Two uploads of one name coexist; unsafe names are sanitized (keeping the extension,
+ * non-ASCII kept, the stem capped by UTF-8 bytes, Windows device names prefixed).
+ * - A media type with parameters is accepted; malformed parts are 400s and write nothing.
+ * - A file over the per-file cap, more files or more bytes than one request may carry are 413s
+ * that write nothing; what /api/me advertises is exactly what is enforced; an inline image
+ * has its own cap, independent of the attachment limit.
+ * - Goal mode, and a busy Session without queueIfBusy, refuse before anything is written.
+ * - A Task that never starts leaves no orphaned bytes, and a scratchpad directory resolving
+ * outside the Agent's scratchpad root is refused, not written through.
*/
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
-import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
import {
assistantText,
buildHandoffMessage,
@@ -26,14 +30,14 @@ import type { OmniMessage } from "@prismshadow/penguin-core";
import type { SessionRow } from "../src/db/repos/sessions.js";
import type { RuntimeSession } from "../src/runtime/session-manager.js";
import { MAX_ATTACHMENT_COUNT } from "../src/services/attachment-limits.js";
+import { adoptSession, fakeSession, sessionRow, uniqueSessionId } from "./fixtures/session.js";
import { apiClient, createTestApp, provisionUser, waitFor } from "./helpers.js";
import type { TestApp } from "./helpers.js";
-const SID = "session-2026-07-29-10-00-00-aabb0001";
const PROJECT_ID = "attacher-default_project";
/**
- * Deliberately tiny limits for the cap tests (see beforeEach), in whole MB and in bytes. The
+ * Deliberately tiny limits for the cap tests (see beforeAll), in whole MB and in bytes. The
* total is kept below twice the per-file cap so that "two individually legal files that together
* cross the aggregate" is expressible — with total >= 2x per-file, each half would trip the
* per-file check first and the aggregate cap would never be the thing under test.
@@ -45,30 +49,22 @@ const TEST_TOTAL_BYTES = TEST_TOTAL_MB * 1024 * 1024;
/** Fake Session that records each run's input and finishes immediately (no LLM, no approvals). */
function recordingFakeSession(sessionId: string, runs: OmniMessage[][]): RuntimeSession {
- return {
- sessionId,
- toolPermission: () => "rw",
- generateTitle: async () => ({ title: null, usage: null }),
- compactability: () => "ok" as const,
- steer: () => false,
- skipReconnectWait: () => false,
+ return fakeSession(sessionId, {
async *run(input: OmniMessage[]) {
runs.push(input);
yield assistantText("done");
},
- async *compact() {},
- };
+ });
}
/** Fake Session whose run parks until `until` resolves, so the Session stays busy while the test posts. */
function parkingFakeSession(sessionId: string, until: Promise<void>): RuntimeSession {
- return {
- ...recordingFakeSession(sessionId, []),
+ return fakeSession(sessionId, {
async *run() {
await until;
yield assistantText("done");
},
- };
+ });
}
/** Base64 data URL of some bytes, the shape the composer submits. */
@@ -87,30 +83,14 @@ function promptText(input: OmniMessage[]): string {
describe("task input file attachments", () => {
let t: TestApp;
let api: ReturnType<typeof apiClient>;
+ let SID: string;
let runs: OmniMessage[][];
let dir: string;
let row: SessionRow;
- beforeEach(async () => {
+ beforeAll(async () => {
t = await createTestApp();
- const { cookie } = await provisionUser(t.app, "attacher");
- api = apiClient(t.app, cookie);
- row = {
- sessionId: SID,
- projectId: PROJECT_ID,
- agentId: "default_agent",
- provider: "custom",
- modelId: "m1",
- workspace: "/tmp/w",
- approvalMode: "allow-all",
- title: null,
- createdAt: new Date().toISOString(),
- lastActiveAt: new Date().toISOString(),
- };
- t.deps.sessionsRepo.insert(row);
- runs = [];
- t.deps.manager.adopt(row, recordingFakeSession(SID, runs));
- dir = path.join(scratchpadDir(t.root, PROJECT_ID, "default_agent"), SID);
+ api = apiClient(t.app, (await provisionUser(t.app, "attacher")).cookie);
// The shipped defaults are 100MB/120MB — allocating buffers that size to prove a cap works
// would cost hundreds of megabytes per assertion. The caps are read from the settings repo
// per request, so the tests turn them down instead: that also makes these the tests of the
@@ -118,9 +98,15 @@ describe("task input file attachments", () => {
t.deps.serverSettingsRepo.setAttachmentMaxMb(TEST_MAX_MB);
t.deps.serverSettingsRepo.setAttachmentTotalMb(TEST_TOTAL_MB);
});
- afterEach(async () => {
+ afterAll(async () => {
await t.cleanup();
});
+ beforeEach(() => {
+ SID = uniqueSessionId();
+ runs = [];
+ row = adoptSession(t.deps, recordingFakeSession(SID, runs), { projectId: PROJECT_ID });
+ dir = path.join(scratchpadDir(t.root, PROJECT_ID, "default_agent"), SID);
+ });
it("writes the file into the session scratchpad and appends the marker line to the text", async () => {
const res = await api.post(`/api/sessions/${SID}/tasks`, {
@@ -423,6 +409,28 @@ describe("task input file attachments", () => {
release();
await waitFor(() => t.deps.manager.statusOf(SID) === "idle");
});
+
+ // Symlink creation needs a privilege or developer mode on Windows; the containment rule
+ // itself is platform-independent.
+ it.skipIf(process.platform === "win32")(
+ "a session directory symlinked out of the scratchpad root is refused, not written through",
+ async () => {
+ const outside = await fs.mkdtemp(path.join(os.tmpdir(), "penguin-outside-"));
+ try {
+ await fs.mkdir(path.dirname(dir), { recursive: true });
+ // `fs.mkdir(dir, {recursive:true})` succeeds silently on an existing symlink-to-directory,
+ // so without the realpath check the upload would land in `outside`.
+ await fs.symlink(outside, dir, "dir");
+ const res = await api.post(`/api/sessions/${SID}/tasks`, {
+ input: [{ type: "file", fileName: "escape.txt", dataUrl: dataUrl("bytes") }],
+ });
+ expect(res.status).toBe(500);
+ expect(await fs.readdir(outside)).toEqual([]);
+ } finally {
+ await fs.rm(outside, { recursive: true, force: true });
+ }
+ },
+ );
});
describe("task attachments are removed when the Task never starts", () => {
@@ -445,18 +453,7 @@ describe("task attachments are removed when the Task never starts", () => {
});
const { cookie } = await provisionUser(t.app, "failer");
api = apiClient(t.app, cookie);
- t.deps.sessionsRepo.insert({
- sessionId: FAIL_SID,
- projectId: PID,
- agentId: "default_agent",
- provider: "custom",
- modelId: "m1",
- workspace: "/tmp/w",
- approvalMode: "allow-all",
- title: null,
- createdAt: new Date().toISOString(),
- lastActiveAt: new Date().toISOString(),
- });
+ t.deps.sessionsRepo.insert(sessionRow(FAIL_SID, { projectId: PID }));
dir = path.join(scratchpadDir(t.root, PID, "default_agent"), FAIL_SID);
});
afterEach(async () => {
@@ -476,56 +473,3 @@ describe("task attachments are removed when the Task never starts", () => {
expect(await fs.readdir(dir).catch(() => [])).toEqual([]);
});
});
-
-describe("scratchpad directory containment", () => {
- const LINK_SID = "session-2026-07-29-12-00-00-aabb0003";
- const PID = "linker-default_project";
- let t: TestApp;
- let api: ReturnType<typeof apiClient>;
- let outside: string;
-
- beforeEach(async () => {
- t = await createTestApp();
- const { cookie } = await provisionUser(t.app, "linker");
- api = apiClient(t.app, cookie);
- t.deps.sessionsRepo.insert({
- sessionId: LINK_SID,
- projectId: PID,
- agentId: "default_agent",
- provider: "custom",
- modelId: "m1",
- workspace: "/tmp/w",
- approvalMode: "allow-all",
- title: null,
- createdAt: new Date().toISOString(),
- lastActiveAt: new Date().toISOString(),
- });
- t.deps.manager.adopt(
- t.deps.sessionsRepo.findById(LINK_SID)!,
- recordingFakeSession(LINK_SID, []),
- );
- outside = await fs.mkdtemp(path.join(os.tmpdir(), "penguin-outside-"));
- });
- afterEach(async () => {
- await fs.rm(outside, { recursive: true, force: true });
- await t.cleanup();
- });
-
- // Symlink creation needs a privilege or developer mode on Windows; the containment rule
- // itself is platform-independent.
- it.skipIf(process.platform === "win32")(
- "a session directory symlinked out of the scratchpad root is refused, not written through",
- async () => {
- const root = scratchpadDir(t.root, PID, "default_agent");
- await fs.mkdir(root, { recursive: true });
- // `fs.mkdir(dir, {recursive:true})` succeeds silently on an existing symlink-to-directory,
- // so without the realpath check the upload would land in `outside`.
- await fs.symlink(outside, path.join(root, LINK_SID), "dir");
- const res = await api.post(`/api/sessions/${LINK_SID}/tasks`, {
- input: [{ type: "file", fileName: "escape.txt", dataUrl: dataUrl("bytes") }],
- });
- expect(res.status).toBe(500);
- expect(await fs.readdir(outside)).toEqual([]);
- },
- );
-});
diff --git a/packages/server/test/title-http-path.test.ts b/packages/server/test/title-http-path.test.ts
index 83a83a92..964ecf56 100644
--- a/packages/server/test/title-http-path.test.ts
+++ b/packages/server/test/title-http-path.test.ts
@@ -1,20 +1,18 @@
/**
- * End-to-end title generation over the same HTTP path the Web App uses: create the
- * Session via POST /api/projects/:p/agents/:a/sessions, start the first Task via
- * POST /api/sessions/:id/tasks, and assert against the real wiring (real
- * SessionManager, real TitleGenerator, real ChannelHub, real DB) that
- * 1. the created row's title is NULL (the "New chat" label is a client-side
- * display fallback, not a stored default),
- * 2. the user-input fallback title is persisted and pushed on the session's SSE
- * channel while the run is still parked before any model output,
- * 3. the LLM title replaces it when the one-shot request resolves.
- * Only the runtime Session is faked (adopted into the manager's active table); the
- * fake's generateTitle is gated so "before any model output" is provable.
+ * Title generation over the HTTP path the Web App uses — create the Session, then start its
+ * first Task — against the real wiring (SessionManager, TitleGenerator, ChannelHub, DB); only
+ * the runtime Session is faked, with its run and its title request gated.
+ *
+ * - A new Session's stored title is NULL ("New chat" is the client's display fallback).
+ * - The first Task's input is persisted as the fallback title and pushed on the Session's
+ * channel and on the user channel before any model output.
+ * - The model's title then replaces it, pushed on both channels too.
*/
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import type { RuntimeSession } from "../src/runtime/session-manager.js";
import type { ChannelEvent } from "../src/runtime/channel.js";
import { userChannelKey } from "../src/http/routes/events.js";
+import { fakeSession } from "./fixtures/session.js";
import { apiClient, createTestApp, provisionUser, waitFor } from "./helpers.js";
import type { TestApp } from "./helpers.js";
@@ -24,21 +22,15 @@ function gatedSession(
runGate: Promise<void>,
titleGate: Promise<void>,
): RuntimeSession {
- return {
- sessionId,
- toolPermission: () => "rw",
+ return fakeSession(sessionId, {
generateTitle: async () => {
await titleGate;
return { title: "Login page bug", usage: null };
},
- compactability: () => "ok" as const,
- steer: () => false,
- skipReconnectWait: () => false,
async *run() {
await runGate;
},
- async *compact() {},
- };
+ });
}
describe("title generation over the web's HTTP path", () => {
diff --git a/packages/server/test/vault.test.ts b/packages/server/test/vault.test.ts
index 8b6eb46e..cbde707c 100644
--- a/packages/server/test/vault.test.ts
+++ b/packages/server/test/vault.test.ts
@@ -1,33 +1,24 @@
/**
- * Integration tests for the Vault environment variable routes (Agent-level
- * agent_state/.vault.toml): GET masks values (plaintext
- * is never sent), PUT is owner-only, whole-table replace semantics (omitting
- * value keeps the original, an absent key is deleted, a new key must supply a
- * value), 400 on key/shape validation, 404 for a nonexistent Agent, vaults of
- * different Agents are independent of each other, and PUT leaves the Agent's cached
- * Session runtimes alone (core reads the vault into each Session's next model context).
+ * The Vault routes: an Agent's environment variables (agent_state/.vault.toml).
+ *
+ * - GET masks every value (short ones entirely) and never sends plaintext, the PUT response
+ * included; members read, outsiders get 404; an empty vault is an empty table.
+ * - PUT is owner-only: a member gets 403, an outsider 404.
+ * - PUT replaces the whole table: an entry without a value keeps its stored one, an absent key
+ * is deleted, and a new key without a value is a 400.
+ * - A vault write leaves the Project's model credentials alone.
+ * - A vault write leaves the Agent's cached Session runtimes alone: core reads the vault into
+ * each Session's next model context, so nothing is rebuilt.
+ * - Each Agent's vault is its own; an Agent that does not exist is a 404.
+ * - Malformed keys, values and bodies are 400s.
*/
-import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { userText } from "@prismshadow/penguin-core";
import type { ProjectCreateResponse, VaultResponse } from "../src/api/types.js";
-import type { RuntimeSession } from "../src/runtime/session-manager.js";
+import { fakeSession, sessionRow, uniqueSessionId } from "./fixtures/session.js";
import { apiClient, createTestApp, provisionUser, waitFor } from "./helpers.js";
import type { TestApp } from "./helpers.js";
-/** Minimal fake runtime Session: one assistant reply, no approvals (keeps the loader-count test free of LLM calls). */
-function fakeRuntimeSession(sessionId: string): RuntimeSession {
- return {
- sessionId,
- toolPermission: () => "rw",
- generateTitle: async () => ({ title: null, usage: null }),
- compactability: () => "ok" as const,
- steer: () => false,
- skipReconnectWait: () => false,
- async *run() {},
- async *compact() {},
- };
-}
-
describe("vault api", () => {
let t: TestApp;
let owner: ReturnType<typeof apiClient>;
@@ -38,13 +29,14 @@ describe("vault api", () => {
/** Loader call count: how many times the manager (re)built a runtime from the index. */
let loads: number;
- beforeEach(async () => {
- loads = 0;
+ beforeAll(async () => {
+ // The loader counts how many times the manager (re)built a runtime from the index; the
+ // runtime it builds answers with nothing, so no case reaches an LLM.
t = await createTestApp({
loader: {
load: async (row) => {
loads++;
- return fakeRuntimeSession(row.sessionId);
+ return fakeSession(row.sessionId);
},
},
});
@@ -62,9 +54,13 @@ describe("vault api", () => {
const add = await owner.post(`/api/projects/${projectId}/members`, { userId: "member_b" });
expect(add.status).toBe(201);
});
- afterEach(async () => {
+ afterAll(async () => {
await t.cleanup();
});
+ beforeEach(async () => {
+ loads = 0;
+ expect((await owner.put(vaultPath, { entries: [] })).status).toBe(200);
+ });
it("GET masks values and never sends plaintext; members can read, outsiders 404; an empty vault returns an empty table", async () => {
// Not configured yet: an empty table.
@@ -140,24 +136,14 @@ describe("vault api", () => {
});
it("PUT leaves the Agent's cached Session runtimes alone: the vault reaches a running Session at its next compaction, not by a rebuild", async () => {
- t.deps.sessionsRepo.insert({
- sessionId: "vault-sess-1",
- projectId,
- agentId: "default_agent",
- modelId: "m1",
- provider: "custom",
- workspace: t.root,
- approvalMode: "allow-all",
- title: null,
- createdAt: new Date().toISOString(),
- lastActiveAt: new Date().toISOString(),
- });
- const idle = () => t.deps.manager.statusOf("vault-sess-1") === "idle";
+ const sid = uniqueSessionId();
+ t.deps.sessionsRepo.insert(sessionRow(sid, { projectId, workspace: t.root }));
+ const idle = () => t.deps.manager.statusOf(sid) === "idle";
// First Task builds the runtime (load #1); the second reuses the active-table entry.
- await t.deps.manager.startTask("vault-sess-1", [userText("a")]);
+ await t.deps.manager.startTask(sid, [userText("a")]);
await waitFor(idle);
- await t.deps.manager.startTask("vault-sess-1", [userText("b")]);
+ await t.deps.manager.startTask(sid, [userText("b")]);
await waitFor(idle);
expect(loads).toBe(1);
@@ -167,11 +153,11 @@ describe("vault api", () => {
// next context it opens, exactly as the CLI's in-process Session does.
const put = await owner.put(vaultPath, { entries: [{ key: "NEW_KEY", value: "v-secret-1" }] });
expect(put.status).toBe(200);
- await t.deps.manager.startTask("vault-sess-1", [userText("c")]);
+ await t.deps.manager.startTask(sid, [userText("c")]);
await waitFor(idle);
expect(loads).toBe(1);
expect((await owner.get(vaultPath)).status).toBe(200);
- await t.deps.manager.startTask("vault-sess-1", [userText("d")]);
+ await t.deps.manager.startTask(sid, [userText("d")]);
await waitFor(idle);
expect(loads).toBe(1);
});