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
7 changes: 7 additions & 0 deletions docs/process/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -383,6 +383,13 @@ boundary, the reasons and the file- and assertion-level inventory are in
`python3`, `bwrap`, `unshare`, `setpriv` and `ip`, permitted namespaces and a
built workspace (`bun run build`), and refuses to start without them. `bun run test experiments/<file>` runs one
file while debugging.
- **Nested worker namespaces.** The installed-runtime placement control also
needs the real worker host probe to pass inside its outer offline namespace.
An AppArmor profile on the outer `bwrap` can deny the inner worker's namespace
creation even when a direct host probe succeeds. The control fails early
with `OWNED_CLAUDE_NESTED_WORKER_HOST_REQUIRED`, the probe's cause and the
current AppArmor label when available. Use a qualified isolated proof host;
neither a skipped placement nor disabling either boundary supplies proof.
- **The release gate.** Release preparation runs the tier after
`bun run version` and before `bun run release` (the
[release skill](../../.agents/skills/release/SKILL.md) has the sequence).
Expand Down
10 changes: 10 additions & 0 deletions experiments/fixtures/runtime-placement-probe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { createRequire } from "node:module";
import { join, resolve } from "node:path";
import { captureSurface } from "../../scripts/capture-turn-surface.js";
import { observedSkills } from "../../scripts/turn-surface-skills.js";
import { requireWorkerHostAsync } from "../../packages/ui-sdk/src/server/worker-launcher.js";

const networkInterfaces = readFileSync("/proc/net/dev", "utf8").trim().split("\n").slice(2).map(line => line.split(":")[0]!.trim());
assert.deepEqual(networkInterfaces, ["lo"], "OWNED_CLAUDE_REQUIRES_OFFLINE_NAMESPACE");
Expand All @@ -18,6 +19,15 @@ const sdkRequire = createRequire(Bun.resolveSync("@anthropic-ai/claude-agent-sdk
const installed = sdkRequire.resolve(`@anthropic-ai/claude-agent-sdk-linux-${process.arch}/claude`);
const manifest = JSON.parse(readFileSync(sdkRequire.resolve("./manifest.json"), "utf8"));
try {
// The outer offline namespace can inherit an AppArmor label that forbids
// the real worker's nested namespaces, before either copied CLI starts.
try { await requireWorkerHostAsync(outside); }
catch (cause) {
let label = "unavailable";
try { label = readFileSync("/proc/self/attr/current", "utf8").replace(/\0/g, "").trim(); } catch { /* AppArmor is optional. */ }
throw new Error("OWNED_CLAUDE_NESTED_WORKER_HOST_REQUIRED: the outer offline namespace must permit the inner worker boundary. " +
"AppArmor label: " + JSON.stringify(label) + ". " + (cause instanceof Error ? cause.message : String(cause)), { cause });
}
const paths = [outside, inside].map(root => {
writeFileSync(join(root, "package.json"), '{"name":"odysseus-owned-cli-control"}\n');
const path = join(root, "claude"); copyFileSync(installed, path); return path;
Expand Down
16 changes: 16 additions & 0 deletions experiments/turn-surface-runtime-placement.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,22 @@
import { expect, test } from "bun:test";
import { join } from "node:path";

test("a refused nested worker host reports its first cause before runtime capture", async () => {
const script = [
"const { workerHostBoundary } = await import(" + JSON.stringify(join(import.meta.dir, "../packages/ui-sdk/src/server/worker-launcher.ts")) + ");",
'workerHostBoundary.probe = () => ({ ok: false, requirement: "Odysseus controlled nested namespace refusal" });',
"await import(" + JSON.stringify(join(import.meta.dir, "fixtures/runtime-placement-probe.ts")) + ");",
].join("\n");
const child = Bun.spawn(["bwrap", "--unshare-net", "--bind", "/", "/", "--proc", "/proc", "--dev", "/dev", process.execPath,
"--eval", script], { stdout: "pipe", stderr: "pipe" });
const [code, output, errors] = await Promise.all([child.exited, new Response(child.stdout).text(), new Response(child.stderr).text()]);
expect(code).toBe(1);
expect(errors, "NESTED_WORKER_HOST_FIRST_CAUSE").toContain("OWNED_CLAUDE_NESTED_WORKER_HOST_REQUIRED");
expect(errors).toContain("Odysseus controlled nested namespace refusal");
expect(errors).toContain("AppArmor label:");
expect(output, "no placement receipt on an unsupported host").toBe("");
});

test("same installed Claude runtime under /tmp retains the measured request and private worker", async () => {
const child = Bun.spawn(["bwrap", "--unshare-net", "--bind", "/", "/", "--proc", "/proc", "--dev", "/dev", process.execPath,
join(import.meta.dir, "fixtures/runtime-placement-probe.ts")],
Expand Down
13 changes: 11 additions & 2 deletions packages/ui-react/tests/parallel-sessions-runtime.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { runtimeHookPhases } from "./fixtures/runtime-hook-phases";
import { runtimePackageBuild } from "./fixtures/runtime-package-build";
import { afterAll, beforeAll, describe, expect, test } from "bun:test";
import { afterAll, afterEach, beforeAll, describe, expect, test } from "bun:test";
import { statSync } from "node:fs";
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
Expand Down Expand Up @@ -168,6 +168,9 @@ function scriptedBackend(): AgentBackend {
answers.set(prompt, decision);
bridge.emit({ type: "tool_result", sessionId, toolUseId, output: "Actor decision recorded.", isError: decision.behavior !== "allow" });
finish(`Actor answered: ${title}.`, "success");
// Keep the last Actor turn registered after its result. The fixture
// must drain this real predecessor window before the next case connects.
if (prompt.includes("Deny")) await new Promise<"ok" | "fail">(release => gates.set(prompt, release));
return;
}
if (kind === "Approve" || kind === "Subapprove" || kind === "Remember") {
Expand Down Expand Up @@ -260,6 +263,11 @@ beforeAll(async () => {
browser = await chromium.launch({ executablePath, headless: true, args: ["--no-sandbox", "--disable-dev-shm-usage"], timeout: 120_000 });
}, 240_000);

// A result is visible before the host releases its turn. Closing a page does
// not drain that turn, and a following page can receive its connect snapshot.
// Await the real host's cancellation and close before another case connects.
afterEach(async () => { if (app) await restartHost(); });

afterAll(async () => {
app?.cancelActiveTurns();
for (const release of gates.values()) release("ok");
Expand Down Expand Up @@ -677,7 +685,8 @@ describe.skipIf(!executablePath)("mounted parallel sessions", () => {
await until(a.page, "p.activeSessionId() !== null && p.streaming(p.activeSessionId())");
const A = (await probe(a.page, (p) => p.activeSessionId()))!;
await a.page.getByText("Setting out: Sail past the Sirens").first().waitFor();
expect(await probe(a.page, (p) => p.views().length), "a watched session is not tracked").toBe(0);
const watched = await probe(a.page, p => ({ active: p.activeSessionId(), views: p.views() }));
expect(watched.views, "a watched session is not tracked: " + JSON.stringify(watched)).toEqual([]);

// A's own unsent words and image, typed while it streams, saved on the host.
await composer(a.page).fill(draftA);
Expand Down
25 changes: 15 additions & 10 deletions packages/ui-sdk/tests/worker-pipes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
*/
import { afterEach, expect, spyOn, test } from "bun:test";
import { availableParallelism } from "node:os";
import { closeSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readlinkSync, rmSync, writeFileSync } from "node:fs";
import { closeSync, constants, existsSync, mkdirSync, mkdtempSync, openSync, readdirSync, readlinkSync, rmSync, writeFileSync } from "node:fs";
import { readFile, writeFile } from "node:fs/promises";
import { basename, join, resolve } from "node:path";
import { tmpdir } from "node:os";
Expand Down Expand Up @@ -73,15 +73,15 @@ function ownedTmp() {

/**
* Marks when a maintenance worker's two output streams have both ended: from
* then on only Bun's own duplicates of their descriptors can still be open.
* then on Bun's own duplicates or a test's retained reader can still be open.
* `launched` runs when the first is created, which is when the launch is done.
*/
function workerOutputs(launched?: () => void) {
function workerOutputs(launched?: (fd: number) => void) {
const real = workerPipes.fifoStream;
let created = 0, ended = 0, end!: () => void;
const done = new Promise<void>(resolve => { end = resolve; });
const spy = spyOn(workerPipes, "fifoStream").mockImplementation(fd => {
if (created++ === 0) launched?.();
if (created++ === 0) launched?.(fd);
return real(fd).pipeThrough(new TransformStream<Uint8Array, Uint8Array>({ flush: () => { if (++ended === 2) end(); } }));
});
return { ended: done, restore: () => spy.mockRestore() };
Expand Down Expand Up @@ -183,19 +183,24 @@ test("an abort that lands while a finished maintenance command's pipes close sti
const startupView = createFixtureWorkerStartupView(f.brain);
const tmp = ownedTmp();
const controller = new AbortController();
let pool: ReturnType<typeof holdWorkPool> | undefined;
// The pool is held from the end of the launch, before any Bun stream exists.
const outputs = workerOutputs(() => { pool = holdWorkPool(f.root); });
let held: number | undefined;
// A real extra reader keeps this FIFO's release pending, independent of
// whether foreign work overtakes a queued pool hold (#3995). It cannot
// delay EOF: it holds no writing end.
const outputs = workerOutputs(fd => { held = openSync("/proc/self/fd/" + fd, constants.O_RDONLY | constants.O_NONBLOCK); });
const release = () => { if (held !== undefined) { closeSync(held); held = undefined; } };
let run: Promise<Error | undefined> | undefined;
try {
run = refusal(() => runMaintenanceWorker({ brainPath: f.brain, startupView, command: ["/bin/sh", "-c", "printf ithaca"],
env: { PATH: "/usr/bin:/bin" }, credentials: false, tempDomain: { statePath: join(f.root, "maintenance-state.db") }, signal: controller.signal }));
// The command has finished; the abort lands while its pipes wait for the pool, which then frees.
void outputs.ended.then(async () => { await Bun.sleep(50); controller.abort(); await Bun.sleep(200); await pool?.release(); });
expect(await Promise.race([outputs.ended.then(() => "ended"), run]), "OUTPUT_EOF_PRECEDES_MAINTENANCE_SETTLEMENT").toBe("ended");
expect(held, "ABORT_WAITS_FOR_OUTPUT_EOF_WITH_FIFO_HELD").toBeNumber();
controller.abort();
release();
expect(await run, "ABORT_DURING_RELEASE_REFUSES").toBeInstanceOf(DOMException);
expect(tmp.remains(), "ABORT_DURING_RELEASE_RELEASES_PIPES").toEqual({ directories: [], descriptors: [] });
} finally {
controller.abort(); await pool?.release(); await run;
controller.abort(); release(); await run;
outputs.restore(); tmp.restore(); startupView.cleanup(); f.cleanup();
}
});
Loading