The open-source app everyone uses to manage agents at work
TypeScript acpxagent-orchestrationagent-skillsagentic-aiai-agentsai-engineeringai-governanceai-toolsautonomous-agentsclaudeclaude-codeclaude-skillscodexhermesllmmcpmulti-agentopenclawproject-managementworkflow-automation
import type { Meta, StoryObj } from "@storybook/react-vite";
import { expect, screen, userEvent, waitFor } from "storybook/test";
import { useEffect, useState } from "react";
import { OnboardingWizard } from "@/components/OnboardingWizard";
import { PillGuy } from "@/components/onboarding/PillGuy";
import { Stepper } from "@/components/onboarding/Stepper";
import { storybookHiredAgent } from "../../fixtures/paperclipData";
import { useCompanyListQuery } from "@/api/companies-query";
import { useDialog } from "@/context/DialogContext";
import {
ONBOARDING_ARC_ENTRY_STEP,
STORYBOOK_COMPANY_ID,
clearOnboardingDraft,
seedOnboardingDraft,
} from "../../fixtures/onboardingDraft";
import {
resetOnboardingFixtureState,
setOnboardingFixtureState,
} from "../../fixtures/onboardingEnvironment";
/**
* The onboarding wizard's agent arc: create the agent, connect a model, review.
* These are the three steps a customer walks inside the tenant — the
* organization is named in Cloud before they arrive, which is why the strip
* counts to three rather than to the wizard's own step numbers.
*
* The step stories below mount the real wizard against the Storybook API
* fixtures. That matters more here than in most stories: these screens only
* render for a signed-in account that owns a provisioned stack, so before this
* existed the only way to see them was to walk a real signup — and when the
* connect step failed on a live stack, the review step behind it could not be
* reached at all.
*/
const meta = {
id: "onboarding-agent-arc",
title: "Getting started and access/Onboarding and first work/Onboarding/Agent arc",
parameters: { layout: "centered",
paperclip: {
"capabilities": [
"onboarding/adapter",
"onboarding/first-task"
],
"implementation": "production",
"boundary": "fixtures",
"notes": "Production wizard with simulated accounts, immutable-target discovery, native/Legacy setup and refused/unconfirmed cleanup. Fixtures do not prove isolation, lease cleanup, runtime limits, draft reload persistence or model execution."
},
},
} satisfies Meta;
export default meta;
/**
* Seeds the draft the wizard restores from, opens it at the arc's first step,
* and takes the draft back out again on the way past.
*
* Three details the wizard's own design forces:
*
* The draft is written during render, not in an effect. Roughly twenty
* `useState(saved?.x ?? default)` initializers read the restored blob exactly
* once, on first render, so a draft written after mount arrives too late to
* matter.
*
* `createdCompanyId` has to be a company the fixtures report as owned.
* `restoreOnboardingState` treats restoring as an authorization decision and
* discards the whole blob when the saved company is not in the list — correctly,
* since localStorage is per-origin and would otherwise hand one account's draft
* to another.
*
* Every story enters here, at step 3, and the later ones walk forward. Opening
* directly on a later step is the obvious shortcut and it is wrong: `entryStep`
* is captured once at mount from exactly this draft, `initialStep` sets both it
* and the current step together, and Back is offered only while
* `currentStep > entryStep`. A story opened on step 4 is a step 4 that can never
* show its Back button — which is not a preview of the step, it is a preview of
* a state no customer is ever in.
*
* And the cleanup is not housekeeping. That same per-origin storage is shared
* with every other story in the session: a draft left behind makes the next
* story restore a saved step ahead of the one it asked for, so the reviewer
* lands on a screen they did not click on and reads it as a wizard bug.
*/
function WizardArc() {
const [seeded] = useState(() => {
seedOnboardingDraft();
return true;
});
useEffect(() => clearOnboardingDraft, []);
// Nothing is mounted until the companies list has settled, and that ordering
// is load-bearing rather than tidiness. The wizard's own mount gate waits on
// `isFetching`, but this query is *disabled* until the account settles, and a
// disabled query is not fetching — so mounting immediately gets an inner
// wizard whose ~20 one-shot initializers read a null draft, take `initialStep`
// instead, and then persist that back over the seed. A real session does not
// hit this because the dashboard has already loaded the list by the time
// anyone opens onboarding.
const companies = useCompanyListQuery();
const ready = companies.isSuccess && companies.data !== undefined;
const { openOnboarding } = useDialog();
useEffect(() => {
if (!seeded || !ready) return;
openOnboarding({
initialStep: ONBOARDING_ARC_ENTRY_STEP,
companyId: STORYBOOK_COMPANY_ID,
});
}, [seeded, ready, openOnboarding]);
if (!ready) return null;
return <OnboardingWizard />;
}
/**
* Every wait here is given an explicit timeout because the library's default is
* one second, and every wait in this file outlasts it: the wizard does not mount
* until the companies query settles, the hire runs four requests end to end. A
* default-timeout wait gives up, the play function fails, and the story renders
* the step it started on — which looks exactly like a story that was written to
* open there. That is the failure this whole file exists to avoid, so it is
* worth naming rather than inlining.
*/
const STEP_TIMEOUT_MS = 15_000;
/**
* Presses the wizard's primary button once it is enabled, and waits for the
* step it opens.
*
* The dialog is portalled to `document.body`, so the queries are scoped to the
* body rather than to `canvasElement` — a canvas-scoped query finds an empty
* mount point and times out.
*
* Waiting for `toBeEnabled` is not defensive padding. Connect stays disabled
* through `adapterEnvLoading` and `missionUnresolvedForHire`, both of which
* resolve from queries, so clicking on first paint clicks a dead button and the
* story silently stops one step short of where it says it is.
*
* The button is queried again immediately before the click rather than reused
* from the wait above. The wizard re-renders as those queries land, and a node
* captured a moment earlier can be detached by the time it is clicked — a click
* that raises no error and does nothing.
*
* Wait for the destination's accessible heading, since button labels repeat
* across steps and the heading's animated text lives inside a nested span.
* A direct text query restricted to h1/h2 misses that span and stops the story
* before it can pick a source or reach Review.
*/
async function advance(to: string) {
await waitFor(
() => expect(screen.getByRole("button", { name: PRIMARY })).toBeEnabled(),
{ timeout: STEP_TIMEOUT_MS },
);
await userEvent.click(screen.getByRole("button", { name: PRIMARY }));
await screen.findByRole("heading", { name: to }, { timeout: STEP_TIMEOUT_MS });
}
/** Naming advances with Next; the selected model source advances with Connect. */
const PRIMARY = /^(Next|Connect)$/;
/**
* Pick a model source, which the connect step needs before it will go forward.
*
* Nothing is selected on arrival — deliberately, so the row reads as a question
* rather than a confirmation — and the CTA stays disabled until one is pressed.
* Found by role rather than by label so the choice does not depend on which
* adapters the fixture registry happens to offer.
*/
async function pickFirstSource() {
const tiles = await screen.findAllByRole("radio", {}, { timeout: STEP_TIMEOUT_MS });
await userEvent.click(tiles[0]!);
}
/**
* Naming the organization — the step before the arc, and the one a self-hosted
* run starts on. It carries no draft and no company: this is where a company is
* created, so seeding either would be describing a run that had already been
* here.
*
* Worth a story because it is dressed as the arc steps that follow it, and that
* only holds if the three are looked at together. Its Back leaves the wizard's
* steps for the front door rather than walking back through them, so it is the
* one Back on the flow that `canGoBackFromOnboardingStep` does not decide.
*/
function NamingStep() {
useEffect(() => clearOnboardingDraft, []);
const companies = useCompanyListQuery();
const ready = companies.isSuccess && companies.data !== undefined;
const { openOnboarding } = useDialog();
useEffect(() => {
if (!ready) return;
// No `companyId`: this step is where one is created, and naming the run's
// company here would be handing it the thing it exists to ask for.
openOnboarding({ initialStep: 1 });
}, [ready, openOnboarding]);
if (!ready) return null;
return <OnboardingWizard />;
}
export const NameYourOrganization: StoryObj = {
render: () => <NamingStep />,
};
/**
* The arc's first step, and the one place Back is correctly absent: a run
* entering here has nowhere behind it that belongs to it — step 1 creates a
* company, and this run already holds one.
*/
export const CreateYourAgent: StoryObj = {
render: () => <WizardArc />,
};
/**
* The arrival a cloud-managed workspace makes: its organization was named in
* Cloud, so the wizard opens on a fresh page straight at the agent step and
* plays the hand-off's second half (hero room opening, content making room
* then filling) rather than mounting cold. Mounted on a press so the arrival
* can be watched — and measured — from its first frame.
*/
function ArrivalStage() {
const [mounted, setMounted] = useState(false);
if (mounted) return <WizardArc />;
return (
<button type="button" className="rounded-full border px-4 py-2 text-sm" onClick={() => setMounted(true)}>
Arrive at the agent step
</button>
);
}
export const ArriveFromCloud: StoryObj = {
render: () => <ArrivalStage />,
};
/**
* The connect step as a signed-out cloud tenant meets it: a managed sandbox
* resolves, and the provider sign-in panel is offered because the auth signal
* comes back absent.
*/
export const ConnectAModel: StoryObj = {
beforeEach: () => {
setOnboardingFixtureState({
environments: "managed-sandbox",
authSignal: "absent",
});
return resetOnboardingFixtureState;
},
render: () => <WizardArc />,
play: async () => {
const name = await screen.findByRole("textbox", { name: "Agent name" }, { timeout: STEP_TIMEOUT_MS });
await userEvent.clear(name);
await userEvent.type(name, " {Enter}");
await expect(screen.getByRole("button", { name: PRIMARY })).toBeDisabled();
await userEvent.type(name, "Chief of staff{Enter}");
await screen.findByRole("heading", { name: "Connect a model" }, { timeout: STEP_TIMEOUT_MS });
},
};
/**
* The same step once the provider is already authenticated. The sign-in panel
* is gone — this is the only difference, and it is worth a story because the
* panel's absence is otherwise indistinguishable from it being broken.
*/
export const ConnectAModelAlreadySignedIn: StoryObj = {
beforeEach: () => {
setOnboardingFixtureState({
environments: "managed-sandbox",
authSignal: "present",
});
return resetOnboardingFixtureState;
},
render: () => <WizardArc />,
play: () => advance("Connect a model"),
};
/**
* No managed sandbox to test against.
*
* This is the state a walker actually hit on staging, and the step is honest
* about it rather than passing and stranding them later. Worth being able to
* look at without breaking a stack to get there.
*/
export const ConnectAModelNoSandbox: StoryObj = {
beforeEach: () => {
setOnboardingFixtureState({ environments: "none", authSignal: "unknown" });
return resetOnboardingFixtureState;
},
render: () => <WizardArc />,
play: () => advance("Connect a model"),
};
/**
* The review step, reached by hiring rather than by claiming a hire happened.
*
* Walking the whole arc is what makes this an honest preview of the step: the
* Back button is offered because the run genuinely walked forward into it, and
* `launchStateIncomplete` is satisfied because an agent genuinely exists. A
* seeded `createdAgentId` would paint over that guard rather than clear it.
*/
export const Review: StoryObj = {
beforeEach: () => {
setOnboardingFixtureState({
environments: "managed-sandbox",
authSignal: "present",
});
return resetOnboardingFixtureState;
},
render: () => <WizardArc />,
play: async () => {
await advance("Connect a model");
await pickFirstSource();
await advance("Let's get started...");
},
};
export const ProgressStrip: StoryObj = {
render: () => (
<div className="w-[420px] space-y-10">
{[1, 2, 3].map((step) => (
<Stepper key={step} step={step} />
))}
</div>
),
};
/**
* The agent's two states, side by side. `dormant` waits to be configured;
* `alive` is the hired agent on the review step.
*/
export const PillStates: StoryObj = {
render: () => (
<div className="flex items-center gap-12">
{(["dormant", "alive"] as const).map((state) => (
<div key={state} className="flex flex-col items-center gap-3">
<PillGuy state={state} className="size-(--sz-72px)" />
<span className="text-(length:--text-micro) uppercase tracking-widest text-muted-foreground">
{state}
</span>
</div>
))}
</div>
),
};
/**
* The transition on its own, on a loop.
*
* Worth a story of its own because it is the arc's payoff and the hardest part
* to judge from a still. The two states share a silhouette but differ in fill,
* eye shape, and a tuft the dormant state does not have at all, so they
* cross-fade rather than path-morph — there is no honest interpolation between
* them, and a faked one warps the eyes through shapes the design never draws.
*/
export const PillMorph: StoryObj = {
render: function PillMorphStory() {
const [alive, setAlive] = useState(false);
useEffect(() => {
const id = setInterval(() => setAlive((v) => !v), 1800);
return () => clearInterval(id);
}, []);
return (
<div className="flex flex-col items-center gap-4">
<PillGuy
state={alive ? "alive" : "dormant"}
className="size-(--sz-72px)"
/>
<button
type="button"
onClick={() => setAlive((v) => !v)}
className="text-(length:--text-micro) uppercase tracking-widest text-muted-foreground hover:text-foreground"
>
{alive ? "alive" : "dormant"} — click to toggle
</button>
</div>
);
},
};
// These mount the shipped onboarding flow, not ConnectModelPreview. Selecting
// a source opens its actual login panel against the Storybook API fixtures.
function signedOutConnectionFixture() {
clearOnboardingDraft();
setOnboardingFixtureState({ environments: "managed-sandbox", authSignal: "absent" });
return () => { clearOnboardingDraft(); resetOnboardingFixtureState(); };
}
async function openProviderConnection(provider: "Claude" | "OpenAI", mode: "subscription" | "api") {
await advance("Connect a model");
await userEvent.click(await screen.findByRole("button", { name: "Use API key instead" }, { timeout: STEP_TIMEOUT_MS }));
if (mode === "subscription") {
await userEvent.click(await screen.findByRole("button", { name: "Use subscription instead" }, { timeout: STEP_TIMEOUT_MS }));
}
await userEvent.click(await screen.findByRole("radio", { name: new RegExp(`^${provider} `) }, { timeout: STEP_TIMEOUT_MS }));
if (mode === "api") {
await screen.findByLabelText("API key", {}, { timeout: STEP_TIMEOUT_MS });
} else if (provider === "Claude") {
await screen.findByLabelText("Authorization code", {}, { timeout: STEP_TIMEOUT_MS });
} else {
await screen.findByText("STORY-BOOK", {}, { timeout: STEP_TIMEOUT_MS });
}
}
export const ClaudeSubscription: StoryObj = {
name: "Connect · Claude subscription",
beforeEach: signedOutConnectionFixture,
render: () => <WizardArc />,
play: () => openProviderConnection("Claude", "subscription"),
};
export const CodexSubscription: StoryObj = {
name: "Connect · Codex / OpenAI subscription",
beforeEach: signedOutConnectionFixture,
render: () => <WizardArc />,
play: () => openProviderConnection("OpenAI", "subscription"),
};
export const ClaudeApiKey: StoryObj = {
name: "Connect · Claude API key",
beforeEach: signedOutConnectionFixture,
render: () => <WizardArc />,
play: () => openProviderConnection("Claude", "api"),
};
export const CodexApiKey: StoryObj = {
name: "Connect · Codex / OpenAI API key",
beforeEach: signedOutConnectionFixture,
render: () => <WizardArc />,
play: () => openProviderConnection("OpenAI", "api"),
};
/** Production onboarding, with the current user's previously saved provider key. */
export const ConnectWithSavedApiKey: StoryObj = {
beforeEach: () => {
setOnboardingFixtureState({ savedApiKeys: true, authSignal: "absent" });
return resetOnboardingFixtureState;
},
render: () => <WizardArc />,
play: async () => {
await advance("Connect a model");
await pickFirstSource();
await screen.findByRole("combobox", { name: "Saved API key" }, { timeout: STEP_TIMEOUT_MS });
await expect(screen.getByRole("combobox", { name: "Saved API key" })).toHaveValue("user:ANTHROPIC_API_KEY");
},
};
export const ConnectWithSavedChatGptSubscription: StoryObj = {
beforeEach: () => {
setOnboardingFixtureState({ savedCodexLogin: true, authSignal: "unknown" });
return resetOnboardingFixtureState;
},
render: () => <WizardArc />,
play: async () => {
await advance("Connect a model");
await userEvent.click(screen.getByRole("radio", {name: /OpenAI/}));
await screen.findByRole("heading", { name: "Let's get started..." }, { timeout: STEP_TIMEOUT_MS });
await expect(screen.queryByRole("combobox", { name: "Saved subscription" })).not.toBeInTheDocument();
},
};
export const ConnectWithSavedClaudeSubscription: StoryObj = {
beforeEach: () => {
setOnboardingFixtureState({ savedClaudeLogin: true, savedApiKeys: true, authSignal: "absent" });
return resetOnboardingFixtureState;
},
render: () => <WizardArc />,
play: async () => {
await advance("Connect a model");
await pickFirstSource();
await screen.findByRole("heading", { name: "Let's get started..." }, { timeout: STEP_TIMEOUT_MS });
await expect(screen.queryByRole("combobox", { name: "Saved API key" })).not.toBeInTheDocument();
},
};
/** Local terminal sign-in with the production wizard and controllable API responses. */
function localSubscriptionStory(
provider: "Claude" | "OpenAI",
state: "sign-in" | "detected" | "testing" | "retry" | "success",
): StoryObj {
return {
name: `Local ${provider} · ${state}`,
beforeEach: () => {
setOnboardingFixtureState({
environments: "local",
localLoginStatus: state === "detected" ? "ready" : "sign_in_required",
connectPending: state === "detected",
testPending: state === "testing",
testFailuresRemaining: state === "retry" ? 1 : 0,
testDelayMs: state === "success" || state === "retry" ? 800 : 0,
});
return resetOnboardingFixtureState;
},
render: () => <WizardArc />,
play: async () => {
await advance("Connect a model");
await userEvent.click(screen.getByRole("radio", { name: new RegExp(provider) }));
if (state === "detected") {
await screen.findByRole("button", { name: "Connecting…" }, { timeout: STEP_TIMEOUT_MS });
await expect(screen.getByRole("button", { name: "Connecting…" })).toBeDisabled();
} else {
await screen.findByText(/Run this in a terminal/, {}, { timeout: STEP_TIMEOUT_MS });
if (state === "sign-in") {
await expect(screen.getByRole("button", { name: "Connect" })).toBeEnabled();
return;
}
// Simulate the terminal finishing; the user's return triggers the real
// login hook, which must advance without a second Connect click.
setOnboardingFixtureState({ localLoginStatus: "ready" });
window.dispatchEvent(new Event("focus"));
if (state === "testing") {
await screen.findByRole("button", { name: "Testing…" }, { timeout: STEP_TIMEOUT_MS });
await expect(screen.getByRole("button", { name: "Testing…" })).toBeDisabled();
await expect(screen.getByRole("status")).toHaveTextContent("Testing connection…");
} else if (state === "retry") {
await screen.findByText("The provider did not respond. Try connecting again.", {}, { timeout: STEP_TIMEOUT_MS });
await expect(screen.getByRole("button", { name: "Connect" })).toBeEnabled();
} else {
await screen.findByRole("heading", { name: "Let's get started..." }, { timeout: STEP_TIMEOUT_MS });
}
}
await expect(screen.queryByRole("combobox", { name: "Saved subscription" })).not.toBeInTheDocument();
await expect(screen.queryByText(/Run this in a terminal/)).not.toBeInTheDocument();
await expect(screen.queryByRole("button", { name: "Start sign-in again" })).not.toBeInTheDocument();
},
};
}
export const LocalClaudeSignInRequired = localSubscriptionStory("Claude", "sign-in");
export const LocalCodexSignInRequired = localSubscriptionStory("OpenAI", "sign-in");
export const LocalClaudeDetected = localSubscriptionStory("Claude", "detected");
export const LocalCodexDetected = localSubscriptionStory("OpenAI", "detected");
export const LocalClaudeTesting = localSubscriptionStory("Claude", "testing");
export const LocalCodexTesting = localSubscriptionStory("OpenAI", "testing");
export const LocalClaudeRetry = localSubscriptionStory("Claude", "retry");
export const LocalCodexRetry = localSubscriptionStory("OpenAI", "retry");
export const LocalClaudeSuccess = localSubscriptionStory("Claude", "success");
export const LocalCodexSuccess = localSubscriptionStory("OpenAI", "success");
type CodexPlatformFixtureOutcome = "native" | "legacy" | "permission" | "cleanup";
interface CodexPlatformFixtureReceipt {
calls: string[];
testRequests: Record<string, unknown>[];
hireRequests: Record<string, unknown>[];
createdAdapterType: string | null;
}
let codexPlatformFixtureReceipt: CodexPlatformFixtureReceipt | null = null;
function installCodexPlatformFixture(outcome: CodexPlatformFixtureOutcome) {
clearOnboardingDraft();
resetOnboardingFixtureState();
setOnboardingFixtureState({ environments: "managed-sandbox", authSignal: "present", savedManagedSubscription: "openai" });
const previous = window.fetch;
const receipt: CodexPlatformFixtureReceipt = { calls: [], testRequests: [], hireRequests: [], createdAdapterType: null };
codexPlatformFixtureReceipt = receipt;
let qualified = false;
const diagnostic = outcome === "permission"
? "Instance admin access is required to qualify this environment. Ask an instance admin or choose Legacy runner in Advanced."
: "The setup lease could not be confirmed as released. Ask an instance admin to resolve cleanup or choose Legacy runner in Advanced.";
const fixtureFetch: typeof fetch = async (input, init) => {
const url = new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url, window.location.origin);
const method = init?.method ?? (input instanceof Request ? input.method : "GET");
const payload = async (): Promise<Record<string, unknown>> => JSON.parse(typeof init?.body === "string" ? init.body : input instanceof Request ? await input.clone().text() : "{}");
if (url.pathname === `/api/companies/${STORYBOOK_COMPANY_ID}/environments` && method === "GET") {
const response = await previous(input, init);
const environments = await response.json();
return Response.json(environments.map((environment: { id: string; config: Record<string, unknown> }) => ({ ...environment,
config: { ...environment.config, image: `registry.example.test/paperclip@sha256:${"a".repeat(64)}` },
})));
}
if (url.pathname === "/api/adapters" && url.searchParams.get("companyId") === STORYBOOK_COMPANY_ID) {
if (url.searchParams.get("environmentId") !== "environment-storybook-sandbox") return Response.json({ error: "Discovery requires the selected environment." }, { status: 400 });
receipt.calls.push(qualified ? "discovery-after" : "discovery-before");
const response = await previous(input, init);
const adapters = (await response.json()).map((adapter: { type: string }) => adapter.type === "codex_local" ? { ...adapter,
defaultRunner: qualified && outcome === "native" ? "paperclip" : "legacy",
supportedRunners: qualified && outcome === "native" ? ["paperclip", "legacy"] : ["legacy"],
} : adapter);
return Response.json([...adapters, { type: "paperclip_runner", loaded: true, disabled: false, source: "builtin", label: "Paperclip Runner", modelsCount: 0 }]);
}
if (url.pathname === "/api/environments/environment-storybook-sandbox/probe" && method === "POST") {
receipt.calls.push("platform");
if (url.searchParams.get("companyId") !== STORYBOOK_COMPANY_ID) return Response.json({ error: "The probe requires this company's context." }, { status: 403 });
if (outcome === "permission") return Response.json({ error: diagnostic }, { status: 403 });
if (outcome === "cleanup") return Response.json({ ok: false, driver: "sandbox", summary: diagnostic,
details: { platformQualificationRecorded: false, leaseId: "storybook-platform-lease", platformQualificationDiagnostic: diagnostic } });
qualified = true;
return Response.json({ ok: true, driver: "sandbox", summary: "The immutable image was measured and its setup lease released.",
details: { platformQualificationRecorded: true, leaseId: "storybook-platform-lease" } });
}
if (url.pathname === `/api/companies/${STORYBOOK_COMPANY_ID}/adapters/codex_local/test-environment` && method === "POST") {
receipt.calls.push("adapter");
receipt.testRequests.push(await payload());
const response = await previous(input, init);
const result = await response.json();
return Response.json({ ...result, adapterType: outcome === "native" && qualified ? "paperclip_runner" : "codex_local" });
}
if (url.pathname === `/api/companies/${STORYBOOK_COMPANY_ID}/agent-hires` && method === "POST") {
receipt.calls.push("hire");
const request = await payload();
receipt.hireRequests.push(request);
const native = outcome === "native" && qualified;
receipt.createdAdapterType = native ? "paperclip_runner" : "codex_local";
const adapterConfig = request.adapterConfig as Record<string, unknown>;
return Response.json({ agent: { ...storybookHiredAgent, ...request, adapterType: receipt.createdAdapterType,
adapterConfig: { ...adapterConfig, ...(native ? { provider: "codex" } : {}) } }, approval: null });
}
return previous(input, init);
};
window.fetch = fixtureFetch;
return () => {
if (window.fetch === fixtureFetch) window.fetch = previous;
if (codexPlatformFixtureReceipt === receipt) codexPlatformFixtureReceipt = null;
clearOnboardingDraft();
resetOnboardingFixtureState();
};
}
function managedCodexQualificationStory(outcome: CodexPlatformFixtureOutcome): StoryObj {
return {
beforeEach: () => installCodexPlatformFixture(outcome),
render: () => <WizardArc />,
parameters: { docs: { description: { story: "Production onboarding with simulated immutable OCI environment, scoped runner discovery and saved platform probe. No sandbox, login, cleanup or provider execution is performed." } } },
play: async () => {
await advance("Connect a model");
await userEvent.click(await screen.findByRole("radio", { name: /^OpenAI / }, { timeout: STEP_TIMEOUT_MS }));
const success = outcome === "native" || outcome === "legacy";
if (success) {
await screen.findByRole("heading", { name: "Let's get started..." }, { timeout: STEP_TIMEOUT_MS });
} else {
await screen.findByText(outcome === "permission"
? "Instance admin access is required to qualify this environment. Ask an instance admin or choose Legacy runner in Advanced."
: "The setup lease could not be confirmed as released. Ask an instance admin to resolve cleanup or choose Legacy runner in Advanced.", {}, { timeout: STEP_TIMEOUT_MS });
await userEvent.click(screen.getByText("Advanced", { exact: true, selector: "summary" }));
const runnerControl = screen.getByRole("button", { name: "Runner" });
await expect(runnerControl).toHaveTextContent("Legacy runner (default)");
await waitFor(() => expect(runnerControl).toBeEnabled(), { timeout: STEP_TIMEOUT_MS });
await userEvent.click(runnerControl);
await expect(await screen.findByRole("option", { name: "Legacy runner (default)" })).toBeEnabled();
await userEvent.keyboard("{Escape}");
await expect(screen.queryByRole("heading", { name: "Let's get started..." })).not.toBeInTheDocument();
}
const receipt = codexPlatformFixtureReceipt!;
await expect(receipt.calls.filter(call => call === "platform")).toHaveLength(1);
await expect(receipt.testRequests).toHaveLength(success ? 1 : 0);
await expect(receipt.hireRequests).toHaveLength(success ? 1 : 0);
if (success) {
await expect(receipt.calls.indexOf("discovery-after")).toBeGreaterThan(receipt.calls.indexOf("platform"));
await expect(receipt.calls.indexOf("adapter")).toBeGreaterThan(receipt.calls.indexOf("discovery-after"));
await expect(receipt.calls.indexOf("hire")).toBeGreaterThan(receipt.calls.indexOf("adapter"));
await expect(receipt.testRequests[0]).not.toHaveProperty("runner");
await expect(receipt.testRequests[0]).toHaveProperty("environmentId", "environment-storybook-sandbox");
await expect(receipt.hireRequests[0]).not.toHaveProperty("runner");
await expect(receipt.createdAdapterType).toBe(outcome === "native" ? "paperclip_runner" : "codex_local");
}
},
};
}
export const ManagedCodexQualifiesOnConnect = managedCodexQualificationStory("native");
export const ManagedCodexMeasuredLegacy = managedCodexQualificationStory("legacy");
export const ManagedCodexQualificationRefused = managedCodexQualificationStory("permission");
export const ManagedCodexCleanupUnconfirmed = managedCodexQualificationStory("cleanup");