Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions packages/ui-server/tests/storage-pressure.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ test("capacity exact entry/recovery boundaries require two additional observatio
value = observePressure(value, evidence(at, 10_001), at); expect(value.severity).toBe("observed");
value = observePressure(value, evidence(at + 1, 10_000), at + 1); expect(value.severity).toBe("low");
value = observePressure(value, evidence(at + 2, 5000), at + 2); expect(value.severity).toBe("critical");
const episode = value.episode; expect(episode).toBeTruthy();
const episode = value.episode; expect(episode, "STORAGE_CRITICAL_ENTRY_OPENS_EPISODE").toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/);
value = observePressure(value, evidence(at + 60_002, 7000), at + 60_002); expect(value.recoveryAt).toBeNull();
value = observePressure(value, evidence(at + 120_002, 7001), at + 120_002); expect(value.severity).toBe("critical");
value = observePressure(value, evidence(at + 180_001, 7001), at + 180_001); expect(value.severity, "STORAGE_RECOVERY_REQUIRES_SIXTY_SECONDS").toBe("critical");
Expand All @@ -40,7 +40,7 @@ test("every active cause must recover; stale, reversal, failed and incompatible
let value = observePressure(newPressure(identity, rootScope), evidence(at, 5000, finite(7), finite(7)), at);
value = observePressure(value, evidence(at + 60_000, 13000), at + 60_000); expect(value.recoveryAt).toBeNull();
const good = (time: number) => evidence(time, 13000, nondepleting, nondepleting);
value = observePressure(value, good(at + 120_000), at + 120_000); expect(value.recoveryAt).not.toBeNull();
value = observePressure(value, good(at + 120_000), at + 120_000); expect(value.recoveryAt, "STORAGE_RECOVERY_PAIR_STARTS_AT_FIRST_GOOD_OBSERVATION").toBe(at + 120_000);
value = observePressure(value, null, at + 130_000); expect(value.recoveryAt).toBeNull();
value = observePressure(value, good(at + 180_000), at + 180_000); expect(value.severity).toBe("critical");
value = observePressure(value, good(at + 170_000), at + 180_000); expect(value.recoveryAt).toBeNull();
Expand Down
6 changes: 4 additions & 2 deletions packages/ui-server/tests/storage-removal.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@ test("exact removal retains original bytes, keeps references and history facts s
expect(existsSync(join(f.brain,"attachments/chart.pdf"))).toBe(false);
expect(readFileSync(join(f.brain,"voyage.md"),"utf8")).toContain("attachments/chart.pdf");
expect(result.after?.attribution).toBe("concurrent-writers-possible");
expect(f.calls.filter(call=>call.purpose==="storage-removal-review").every(call=>call.publish===false && call.credentials===false)).toBe(true);
const reviews=f.calls.filter(call=>call.purpose==="storage-removal-review");
expect(reviews.length,"STORAGE_REMOVAL_REVIEW_RAN_THROUGH_BOUNDARY").toBeGreaterThan(0);
expect(reviews.map(call=>({publish:call.publish,credentials:call.credentials})),"STORAGE_REMOVAL_REVIEW_UNPUBLISHED_UNCREDENTIALED").toEqual(reviews.map(()=>({publish:false,credentials:false})));
const db = createUiDb(f.dbPath), journal = createTurnJournal(db, {brainPath:f.brain,dbPath:f.dbPath,objectsRoot:join(f.root,"objects"),nativeManager:f.native.manager}), reopened = createStorageRemoval(db, {...f.options,journal,gate:createWriterGate(db,f.brain,{pollMs:1})});
try {
expect((await reopened.start("odysseus", id, review.review.fingerprint)).state, "STORAGE_REMOVAL_NO_REPLAY").toBe("complete");
Expand Down Expand Up @@ -64,7 +66,7 @@ test("ignored, protected, linked, executable and uncovered attachments never bec
writeFileSync(join(f.brain,"attachments/exec.pdf"),"executable"); chmodSync(join(f.brain,"attachments/exec.pdf"),0o700);
f.options.protectedPaths.push("attachments/private.pdf"); writeFileSync(join(f.brain,"attachments/private.pdf"),"protected");
const review = await f.removal.review("odysseus","odysseus-protected-1",["attachments/chart.pdf","attachments/score.pdf","attachments/link.pdf","attachments/exec.pdf","attachments/private.pdf"]);
expect(review.review.files.every(file=>!file.eligible), "STORAGE_REMOVAL_PROTECTED_SELECTION").toBe(true);
expect(review.review.files.map(file=>[file.path,file.eligible]).sort(), "STORAGE_REMOVAL_PROTECTED_SELECTION").toEqual([["attachments/chart.pdf",false],["attachments/exec.pdf",false],["attachments/link.pdf",false],["attachments/private.pdf",false],["attachments/score.pdf",false]]);
await expectRejection(f.removal.start("odysseus",review.review.id,review.review.fingerprint), "Refresh");
expect(readFileSync(join(f.brain,"attachments/chart.pdf"))).toEqual(f.original);
} finally { await f.close(); }
Expand Down
5 changes: 4 additions & 1 deletion packages/ui-server/tests/subscription-login.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { resolveServerConfig } from "../src/config/env";
import { resolveAmbientPrincipal } from "../src/db/principals";
import type { WSContext } from "../src/ws/clients";
import { createWsHandlers } from "../src/ws/connection";
import { requireTurnFreeSpace } from "./helpers/turn-free-space.js";

// Obviously fake: the shape Claude Code accepts, the bytes of no real token.
const FIRST_TOKEN = `sk-ant-oat01-${"a".repeat(95)}AA`;
Expand Down Expand Up @@ -108,6 +109,8 @@ async function deploy(token: string, mintedAt: string): Promise<BrainUiApp> {

/** Send one turn and return every frame the client got. */
async function sendTurn(app: BrainUiApp): Promise<Array<Record<string, unknown>>> {
// A real turn needs the scope free-space floor; say so instead of failing on it (#2551).
requireTurnFreeSpace(app.config.brainPath);
const sent: string[] = [];
const ws = { send: (data: string) => sent.push(data), close: () => {}, readyState: 1 } as unknown as WSContext;
const principal = resolveAmbientPrincipal(app.db, "none", "No authentication", "No authentication");
Expand Down Expand Up @@ -179,6 +182,6 @@ describe("a rejected subscription token", () => {
}
expect(seen.length).toBeGreaterThan(0);
expect(seen.filter((request) => request.xApiKey !== null)).toEqual([]);
expect(seen.every((request) => request.authorization === `Bearer ${FIRST_TOKEN}`)).toBe(true);
expect(new Set(seen.map((request) => request.authorization))).toEqual(new Set([`Bearer ${FIRST_TOKEN}`]));
}, 120_000);
});
3 changes: 3 additions & 0 deletions packages/ui-server/tests/subscription-status.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ import { createRecordingObservability, type RecordingObservability } from "../sr
import type { WSContext } from "../src/ws/clients";
import { createWsHandlers } from "../src/ws/connection";
import { makeFakeBackend } from "./helpers/fake-backend";
import { requireTurnFreeSpace } from "./helpers/turn-free-space.js";

const FAKE_TOKEN = `sk-ant-oat01-${"f".repeat(95)}AA`;
const DAY = 24 * 60 * 60 * 1000;
Expand Down Expand Up @@ -252,6 +253,8 @@ async function boot(
}

async function turn(app: BrainUiApp): Promise<void> {
// A real turn needs the scope free-space floor; say so instead of failing on it (#2551).
requireTurnFreeSpace(app.config.brainPath);
const sent: string[] = [];
const ws = { send: (data: string) => sent.push(data), close: () => {}, readyState: 1 } as unknown as WSContext;
// The principal an AUTH_MODE=none app gives every connection.
Expand Down
2 changes: 1 addition & 1 deletion packages/ui-server/tests/sync-runtime.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ describe("BrainClient.sync reads the result", () => {
{ agent: base.agent },
];
for (const v of variants) expect(parseSyncResult(JSON.stringify(v))).toBeNull();
expect(parseSyncResult(INVOKED_KNOWN)).not.toBeNull();
expect(parseSyncResult(INVOKED_KNOWN), "SYNC_RESULT_KNOWN_SHAPE_PARSED_EXACTLY").toEqual(base);
});
});

Expand Down
5 changes: 2 additions & 3 deletions packages/ui-server/tests/ws-apify.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,7 @@ async function hostedTurn(backendId: "pi" | "claude", policy: Record<string, unk
await handlers.onOpen(undefined as never, ws);
handlers.onMessage({ data: JSON.stringify({ type: "chat_message", text: "Chart the way home", requestId: "apify-request" }) } as MessageEvent, ws);
const until = Date.now() + 45_000;
while (!finished) { if (Date.now() > until) throw new Error(`turn did not finish: ${sent.join("\n")}`); await Bun.sleep(10); }
await Bun.sleep(50);
while (!finished || app.isTurnActive()) { if (Date.now() > until) throw new Error(`turn did not finish: ${sent.join("\n")}`); await Bun.sleep(10); }
if (scriptError) throw scriptError;
const taint = app.db.query("SELECT session_id, turn_id, payload FROM governance_events WHERE kind = 'taint'").all() as Array<{ session_id: string | null; turn_id: string | null; payload: string }>;
return { root, fake, sent, taint, ledger: resolve(root, "ui.db.apify-ledger.sqlite") };
Expand Down Expand Up @@ -121,7 +120,7 @@ test("a pi turn reaches the hosted operations with its own context, ledger and t
expect(envelopes.map(envelope => envelope.ok ? "ok" : envelope.error.code), "APIFY_APP_WIRING_SEQUENCE").toEqual(["ok", "ok", "ok", "ok"]);
expect((envelopes[1] as { data: { eligibility: { executable: boolean } } }).data.eligibility.executable, "APIFY_NO_PROFILE_GATE").toBe(true);
expect(outcome.fake.starts(), "APIFY_APP_APPROVED_ACTOR_STARTED").toBe(1);
expect(outcome.sent.some(text => { const frame = JSON.parse(text); return frame.type === "tool_approval_request" && frame.kind === "actor"; }), "APIFY_ACTOR_APPROVAL_CARD").toBe(true);
expect(outcome.sent.map(text => JSON.parse(text)).filter(frame => frame.type === "tool_approval_request").map(frame => frame.kind), "APIFY_ACTOR_APPROVAL_CARD").toContain("actor");
// Discovery and inspection each delivered a separate untrusted page.
expect(outcome.taint.map(row => ({ session: row.session_id, source: JSON.parse(row.payload).source })), "APIFY_TAINTS_SESSION")
.toEqual([{ session: "sess-ithaca-apify", source: "apify_result" }, { session: "sess-ithaca-apify", source: "apify_result" }]);
Expand Down
2 changes: 1 addition & 1 deletion packages/ui-server/tests/ws-effort.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ test("invalid effort is rejected on the socket before backend execution; a valid
const ws = { send: (raw: string) => frames.push(JSON.parse(raw)) };
const handlers = createWsHandlers(testHost(), testPrincipal());
handlers.onMessage({ data: JSON.stringify({ type: "chat_message", text: "invalid", thinkingLevel: "enormous" }) } as MessageEvent, ws);
await Bun.sleep(10);
await until(() => frames.some((frame) => frame.type === "error"));
expect(frames.find((frame) => frame.type === "error")).toMatchObject({ code: "PARSE_ERROR" });
expect(calls).toHaveLength(0);
handlers.onMessage({ data: JSON.stringify({ type: "chat_message", text: "valid", thinkingLevel: "medium" }) } as MessageEvent, ws);
Expand Down
5 changes: 3 additions & 2 deletions packages/ui-server/tests/ws-follow-up-queue.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,8 @@ describe("session_queue", () => {

s.finishCurrent();
await until(() => s.prompts.length === 2);
await settle();
await until(() => client.all().some((f) => f.type === "session_queue" && f.started?.requestId === "req-winds")
&& client.all().some((f) => f.type === "session_info" && f.requestId === "req-winds"));

const frames = client.all();
const startedAt = frames.findIndex((f) => f.type === "session_queue" && f.started);
Expand All @@ -167,7 +168,7 @@ describe("session_queue", () => {
// The last one goes the same way, and the queue is then empty.
s.finishCurrent();
await until(() => s.prompts.length === 3);
await settle();
await until(() => client.frames("session_queue").at(-1)?.started?.requestId === "req-bag");
const last = client.frames("session_queue").at(-1);
expect(last.started).toMatchObject({ requestId: "req-bag" });
expect(last.followUps).toEqual([]);
Expand Down
16 changes: 12 additions & 4 deletions packages/ui-server/tests/ws-pill-labels.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,14 @@ async function until(cond: () => boolean, timeoutMs = 2000): Promise<void> {
}
}
const settle = () => new Promise((r) => setTimeout(r, 25));
/** Poll an asynchronous read, such as the session list route, until it holds. */
async function untilAsync(cond: () => Promise<boolean>, timeoutMs = 2000): Promise<void> {
const start = Date.now();
while (!(await cond())) {
if (Date.now() - start > timeoutMs) throw new Error("untilAsync: timed out");
await new Promise((r) => setTimeout(r, 5));
}
}

const SESSION = "sess-ithaca";
const LABELS: Record<string, string> = {
Expand Down Expand Up @@ -186,14 +194,14 @@ describe("pill labels (#1004)", () => {
const client = await s.connect();
await s.busy(client);
await until(() => s.asked.length === 1);
await settle();
await untilAsync(async () => (await s.listed()).label === "Route home");
expect((await s.listed()).label).toBe("Route home");

client.send({ type: "chat_message", text: "Ask Aeolus about the winds", sessionId: SESSION, requestId: "req-winds" });
await until(() => labels(client.frames("session_queue").at(-1))[0] === "Asking Aeolus");
s.finishers.at(-1)!();
await until(() => s.prompts.length === 2);
await settle();
await untilAsync(async () => (await s.listed()).label === "Asking Aeolus");
expect((await s.listed()).label).toBe("Asking Aeolus");
// The turn's request was labelled when it was queued: no second call.
expect(s.asked).toEqual(["Chart the way home", "Ask Aeolus about the winds"]);
Expand All @@ -207,7 +215,7 @@ describe("pill labels (#1004)", () => {
await until(() => labels(client.frames("session_queue").at(-1))[0] === "Bag of winds");
s.finishers.at(-1)!();
await until(() => s.prompts.length === 2);
await settle();
await untilAsync(async () => (await s.listed()).label === "Bag of winds");
expect((await s.listed()).label).toBe("Bag of winds");
expect(s.asked.filter((text) => text === "Keep the bag of winds shut")).toHaveLength(1);
});
Expand All @@ -233,7 +241,7 @@ describe("pill labels (#1004)", () => {
client.send({ type: "chat_message", text: "Chart the way home", sessionId: SESSION, requestId: "req-resume" });
await until(() => s.finishers.length === 1);
await until(() => s.asked.length === 1);
await settle();
await untilAsync(async () => (await s.listed()).label === "Route home");
expect((await s.listed()).label).toBe("Route home");
});

Expand Down
3 changes: 3 additions & 0 deletions packages/ui-server/tests/ws-scope-caps.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { createWsHandlers } from "../src/ws/connection.js";
import { createPrincipal } from "../src/db/principals.js";
import { createFixtureBrain } from "../../../scripts/captures/core-fixture.js";
import { scopePiProgress } from "./helpers/scope-pi-progress.js";
import { requireTurnFreeSpace } from "./helpers/turn-free-space.js";
import type { ServerMessage, ScopeCapReceipt } from "@schlessera/brain-ui-sdk/protocol";

async function wait(check: () => boolean, detail: () => unknown) { const end = Date.now() + 8000; while (!check()) { if (Date.now() > end) throw Error(JSON.stringify(detail())); await Bun.sleep(10); } }
Expand Down Expand Up @@ -97,6 +98,8 @@ for (const { adapter, voice, overshoot } of cases) test(`${adapter}: ${overshoot
});
}
try {
// The real scope monitor enforces a free-space floor; name it instead of reading it as the cap under test (#2551).
requireTurnFreeSpace(brain);
app = await createApp({ config: resolveServerConfig({ BRAIN_PATH: brain, DB_PATH: join(root, "ui.db"), HOST: "127.0.0.1", AUTH_MODE: "none", NODE_ENV: "test", BRAIN_UI_MODEL_DISCOVERY: "0", BRAIN_UI_PRICING_DISCOVERY: "0" }),
registry: createStaticBackendRegistry([backend], backend.id), observability: createRecordingObservability() });
const principal = createPrincipal(app.db, { authMethod: "password", label: "Athena scope", ttlSeconds: 60 });
Expand Down
2 changes: 1 addition & 1 deletion packages/ui-server/tests/ws-tool-resolution.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ describe("tool_resolution", () => {
const turnId = await s.raise(client);
client.send({ type: "cancel", sessionId: "sess-loom" });
await until(() => s.host.coordinator.pendingApprovals.size === 0);
await settle();
await until(() => client.frames("tool_resolution").length > 0);
expect(client.frames("tool_resolution")[0]).toEqual({
type: "tool_resolution", toolUseId: "tool-loom", outcome: "expired", sessionId: "sess-loom", turnId, reason: "Cancelled by user",
});
Expand Down
Loading