Skip to content

The open-source app everyone uses to manage agents at work

fix(onboarding): do not restore wizard state for a company the user does not own (#11370)

Tonio66515582e4f4
diff --git a/ui/src/components/OnboardingWizard.test.tsx b/ui/src/components/OnboardingWizard.test.tsx
new file mode 100644
index 0000000000..dc985e9983
--- /dev/null
+++ b/ui/src/components/OnboardingWizard.test.tsx
@@ -0,0 +1,516 @@
+// @vitest-environment jsdom
+
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+// --- Mocks (hoisted so vi.mock factories can close over them) ----------------
+
+const mockDialog = vi.hoisted(() => ({
+ onboardingOpen: true,
+ onboardingOptions: {} as { initialStep?: number; companyId?: string },
+ closeOnboarding: vi.fn(),
+ onboardingRouteDismissed: false,
+ setOnboardingRouteDismissed: vi.fn(),
+}));
+
+const mockCompany = vi.hoisted(() => ({
+ companies: [] as Array<{ id: string; name: string; issuePrefix: string }>,
+ setSelectedCompanyId: vi.fn(),
+ loading: false,
+ error: null as Error | null,
+}));
+
+const mockCompaniesApi = vi.hoisted(() => ({
+ create: vi.fn(),
+ update: vi.fn(),
+}));
+const mockGoalsApi = vi.hoisted(() => ({
+ create: vi.fn(),
+ list: vi.fn(async () => []),
+}));
+const mockAgentsApi = vi.hoisted(() => ({
+ adapterModels: vi.fn(async () => [] as Array<{ id: string; label: string }>),
+ testEnvironment: vi.fn(async () => ({
+ adapterType: "claude_local",
+ status: "pass" as const,
+ checks: [],
+ testedAt: new Date().toISOString(),
+ })),
+ hire: vi.fn(async () => ({ agent: { id: "agent-1" }, approval: null })),
+ instructionsBundle: vi.fn(async () => ({ entryFile: "AGENTS.md" })),
+ saveInstructionsFile: vi.fn(async () => ({})),
+}));
+const mockApprovalsApi = vi.hoisted(() => ({
+ create: vi.fn(),
+}));
+const mockIssuesApi = vi.hoisted(() => ({
+ create: vi.fn(),
+}));
+const mockProjectsApi = vi.hoisted(() => ({
+ create: vi.fn(),
+ list: vi.fn(async () => []),
+}));
+
+// The real adapter registry eagerly imports every adapter package. The
+// model/harness picker internals are out of scope here, so stub the adapter
+// layer entirely and drive it through this knob.
+const mockAdapterRegistry = vi.hoisted(() => ({
+ list: [] as Array<{ type: string }>,
+ disabled: new Set<string>(),
+}));
+
+vi.mock("@/lib/router", () => ({
+ useLocation: () => ({ pathname: "/", search: "", hash: "", state: null }),
+ useNavigate: () => vi.fn(),
+ useParams: () => ({}),
+}));
+vi.mock("../context/DialogContext", () => ({
+ useDialog: () => mockDialog,
+}));
+vi.mock("../context/CompanyContext", () => ({
+ useCompany: () => mockCompany,
+}));
+vi.mock("../api/companies", () => ({ companiesApi: mockCompaniesApi }));
+vi.mock("../api/goals", () => ({ goalsApi: mockGoalsApi }));
+vi.mock("../api/agents", () => ({ agentsApi: mockAgentsApi }));
+vi.mock("../api/approvals", () => ({ approvalsApi: mockApprovalsApi }));
+vi.mock("../api/issues", () => ({ issuesApi: mockIssuesApi }));
+vi.mock("../api/projects", () => ({ projectsApi: mockProjectsApi }));
+vi.mock("../adapters", () => ({
+ listUIAdapters: () => mockAdapterRegistry.list,
+ getUIAdapter: () => ({ buildAdapterConfig: () => ({}) }),
+}));
+vi.mock("../adapters/metadata", () => ({ isVisualAdapterChoice: () => true }));
+vi.mock("../adapters/adapter-display-registry", () => ({
+ getAdapterDisplay: (type: string) => ({
+ type,
+ recommended: false,
+ label: type,
+ description: "",
+ icon: () => null,
+ }),
+}));
+vi.mock("../adapters/use-disabled-adapters", () => ({
+ useDisabledAdaptersSync: () => mockAdapterRegistry.disabled,
+ // Added by #11371's adapter snap. A module mock replaces the whole module,
+ // so every export the component reaches for has to be here — omitting one
+ // makes it undefined and the call throws.
+ useAdapterRegistryLoaded: () => true,
+}));
+vi.mock("../adapters/use-adapter-capabilities", () => ({
+ useAdapterCapabilities: () => () => ({
+ supportsInstructionsBundle: false,
+ supportsSkills: false,
+ supportsLocalAgentJwt: false,
+ requiresMaterializedRuntimeSkills: false,
+ supportsModelProfiles: false,
+ }),
+}));
+// Animation / canvas-ish children that add nothing to the logic under test.
+vi.mock("./AsciiArtAnimation", () => ({ AsciiArtAnimation: () => null }));
+vi.mock("./FrontDoor", () => ({ FrontDoor: () => null }));
+vi.mock("./AgentCapsule", () => ({ AgentCapsule: () => null }));
+
+import { ONBOARDING_STORAGE_KEY, OnboardingWizard } from "./OnboardingWizard";
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
+
+async function flushReact() {
+ await act(async () => {
+ await Promise.resolve();
+ await new Promise((resolve) => window.setTimeout(resolve, 0));
+ });
+}
+
+function render() {
+ const container = document.createElement("div");
+ document.body.appendChild(container);
+ const root = createRoot(container);
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ return { container, root, queryClient };
+}
+
+describe("OnboardingWizard restore-gate (stale localStorage across accounts)", () => {
+ beforeEach(() => {
+ window.localStorage.clear();
+ mockDialog.onboardingOpen = true;
+ mockDialog.onboardingOptions = {};
+ mockDialog.onboardingRouteDismissed = false;
+ mockCompany.companies = [];
+ mockCompany.loading = false;
+ mockCompany.error = null;
+ mockAdapterRegistry.list = [];
+ mockAdapterRegistry.disabled = new Set<string>();
+ mockCompaniesApi.create.mockResolvedValue({
+ id: "created",
+ name: "Created Co",
+ issuePrefix: "CRE",
+ });
+ mockCompaniesApi.update.mockResolvedValue({
+ id: "c1",
+ name: "Acme Rockets",
+ issuePrefix: "PAP",
+ });
+ mockGoalsApi.create.mockResolvedValue({ id: "goal-1" });
+ mockGoalsApi.list.mockResolvedValue([]);
+ });
+
+ afterEach(() => {
+ document.body.innerHTML = "";
+ vi.clearAllMocks();
+ });
+
+ it("re-syncs a restored draft once companies resolve asynchronously (companies start empty/loading)", async () => {
+ // Regression for the initializer-only restore bug: the inner wizard's
+ // ~20 useState(saved?.x ?? default) initializers only read `saved` on
+ // their very first render. useCompany() starts with companies=[] and
+ // loading=true and resolves later; if the inner component mounted before
+ // that resolution, restoreOnboardingState would see an empty companies
+ // list and the whole draft would lock to defaults forever, even after
+ // companies arrive. The fix defers mounting the inner wizard until
+ // companies settle.
+ window.localStorage.setItem(
+ ONBOARDING_STORAGE_KEY,
+ JSON.stringify({
+ step: 3,
+ companyName: "Saved Co",
+ agentName: "Ops Lead",
+ createdCompanyId: "c1",
+ }),
+ );
+ mockDialog.onboardingOptions = {};
+ mockCompany.companies = [];
+ mockCompany.loading = true;
+
+ const { container, root, queryClient } = render();
+ const renderTree = () =>
+ act(async () => {
+ root.render(
+ <QueryClientProvider client={queryClient}>
+ <OnboardingWizard />
+ </QueryClientProvider>,
+ );
+ });
+
+ await renderTree();
+ await flushReact();
+
+ // Nothing mounts yet: no premature guess, and the draft is not touched.
+ expect(container.textContent).toBe("");
+ expect(document.body.textContent).toBe("");
+ expect(window.localStorage.getItem(ONBOARDING_STORAGE_KEY)).not.toBeNull();
+
+ // Companies resolve asynchronously, owning the saved company.
+ mockCompany.companies = [{ id: "c1", name: "Saved Co", issuePrefix: "SC" }];
+ mockCompany.loading = false;
+
+ await renderTree();
+ await flushReact();
+
+ // The draft is restored once companies settle: step 3 (Create your first
+ // agent) with the saved agent name in the input, not the defaults
+ // (step 0, "Chief of staff").
+ expect(document.body.textContent).toContain("Create your first agent");
+ const nameInput = document.body.querySelector(
+ 'input[placeholder="Chief of staff"]',
+ ) as HTMLInputElement | null;
+ expect(nameInput?.value).toBe("Ops Lead");
+ const currentStep = document.body.querySelector('[aria-current="step"]');
+ expect(currentStep?.getAttribute("aria-label")).toBe("Step 3");
+
+ await act(async () => {
+ root.unmount();
+ });
+ });
+
+ it("discards a saved draft for a company the signed-in account does not own, and wipes the stale blob", async () => {
+ // The actual vulnerability this fix closes: localStorage is per-origin,
+ // not per-account, so a browser that already onboarded "company-old" for
+ // a different account hands its id straight to a brand-new session.
+ window.localStorage.setItem(
+ ONBOARDING_STORAGE_KEY,
+ JSON.stringify({
+ step: 4,
+ companyName: "Someone Else's Co",
+ createdCompanyId: "company-old",
+ }),
+ );
+ mockCompany.companies = [{ id: "company-new", name: "My Co", issuePrefix: "MC" }];
+ mockCompany.loading = false;
+
+ const { root, queryClient } = render();
+ await act(async () => {
+ root.render(
+ <QueryClientProvider client={queryClient}>
+ <OnboardingWizard />
+ </QueryClientProvider>,
+ );
+ });
+ await flushReact();
+
+ // Falls back to the wizard's default first step, not the stale step 4
+ // draft for a company this account does not own.
+ expect(document.body.textContent).not.toContain("Someone Else's Co");
+ // The stale blob must not linger to confuse the next onboarding attempt.
+ expect(window.localStorage.getItem(ONBOARDING_STORAGE_KEY)).toBeNull();
+
+ await act(async () => {
+ root.unmount();
+ });
+ });
+ it("opens, and keeps the draft, when the initial company query fails", async () => {
+ // React Query reports a failed list as `isLoading === false` with `data`
+ // defaulted to `[]`, which is indistinguishable from "settled, and this
+ // account owns nothing" — the verdict that wipes the blob. Deleting a
+ // customer's onboarding because their company request timed out is the one
+ // outcome here that cannot be undone.
+ window.localStorage.setItem(
+ ONBOARDING_STORAGE_KEY,
+ JSON.stringify({
+ step: 3,
+ companyName: "Saved Co",
+ agentName: "Ops Lead",
+ createdCompanyId: "c1",
+ }),
+ );
+ mockCompany.companies = [];
+ mockCompany.loading = false;
+ mockCompany.error = new Error("company list unavailable");
+
+ const { root, queryClient } = render();
+ await act(async () => {
+ root.render(
+ <QueryClientProvider client={queryClient}>
+ <OnboardingWizard />
+ </QueryClientProvider>,
+ );
+ });
+ await flushReact();
+
+ // It mounts: the companies query sets `retry: false`, and with no
+ // companies the dashboard's "Get Started" button opens onboarding — a gate
+ // that rendered nothing here would make that button dead.
+ expect(document.body.textContent).not.toBe("");
+ // The draft is not restored, because ownership cannot be verified...
+ const nameInput = document.body.querySelector(
+ 'input[placeholder="Chief of staff"]',
+ ) as HTMLInputElement | null;
+ expect(nameInput?.value ?? "").not.toBe("Ops Lead");
+ // ...and not deleted either. The wizard is open in this harness, so the
+ // persist effect does supersede it - the point is that the ownership check
+ // did not *discard* it. The closed case below is where it survives intact.
+ expect(window.localStorage.getItem(ONBOARDING_STORAGE_KEY)).not.toBeNull();
+
+ await act(async () => {
+ root.unmount();
+ });
+ });
+
+ it("renders instead of throwing when the browser denies storage access", async () => {
+ // Safari's private mode and blocked third-party contexts make getItem
+ // throw outright. This runs during render, so an escaping exception takes
+ // the whole app down rather than just losing a draft.
+ // A browser that refuses the read refuses the write too, so deny both —
+ // otherwise the cleanup effect's removeItem is never exercised.
+ const deny = () => {
+ throw new DOMException("The operation is insecure.", "SecurityError");
+ };
+ const getItem = vi.spyOn(Storage.prototype, "getItem").mockImplementation(deny);
+ const removeItem = vi
+ .spyOn(Storage.prototype, "removeItem")
+ .mockImplementation(deny);
+ const setItem = vi.spyOn(Storage.prototype, "setItem").mockImplementation(deny);
+ mockCompany.companies = [{ id: "c1", name: "My Co", issuePrefix: "MC" }];
+ mockCompany.loading = false;
+
+ const { root, queryClient } = render();
+ await act(async () => {
+ root.render(
+ <QueryClientProvider client={queryClient}>
+ <OnboardingWizard />
+ </QueryClientProvider>,
+ );
+ });
+ await flushReact();
+
+ expect(getItem).toHaveBeenCalled();
+ // It mounted: the wizard is open with no draft, rather than the render
+ // throwing on the way in.
+ expect(document.body.textContent).not.toBe("");
+
+ getItem.mockRestore();
+ removeItem.mockRestore();
+ setItem.mockRestore();
+ await act(async () => {
+ root.unmount();
+ });
+ });
+
+ it("opens but does not restore when a refetch fails over a cached list", async () => {
+ // The companies cache is not account-scoped and survives sign-out, so a
+ // failed refetch after an account switch can leave the *previous*
+ // account's companies in hand. Trusting a non-empty list there would find
+ // the old company id in it and hand that draft to the new account — the
+ // leak this whole change closes, through a different door.
+ //
+ // So: mount (no dead end), do not restore, do not delete.
+ window.localStorage.setItem(
+ ONBOARDING_STORAGE_KEY,
+ JSON.stringify({
+ step: 3,
+ companyName: "Saved Co",
+ agentName: "Ops Lead",
+ createdCompanyId: "c1",
+ }),
+ );
+ mockCompany.companies = [{ id: "c1", name: "Saved Co", issuePrefix: "SC" }];
+ mockCompany.loading = false;
+ mockCompany.error = new Error("refetch failed");
+
+ const { root, queryClient } = render();
+ await act(async () => {
+ root.render(
+ <QueryClientProvider client={queryClient}>
+ <OnboardingWizard />
+ </QueryClientProvider>,
+ );
+ });
+ await flushReact();
+
+ // Mounted rather than blank...
+ expect(document.body.textContent).not.toBe("");
+ // ...but the draft was not restored, because the list cannot be trusted.
+ const nameInput = document.body.querySelector(
+ 'input[placeholder="Chief of staff"]',
+ ) as HTMLInputElement | null;
+ expect(nameInput?.value ?? "").not.toBe("Ops Lead");
+
+ await act(async () => {
+ root.unmount();
+ });
+ });
+ it("closes without throwing when the browser denies storage access", async () => {
+ // `reset()` clears the draft and `handleClose` calls it, so the close
+ // button is a fourth storage call site. Guarding the read, the cleanup and
+ // the persist effect one at a time is how this one stayed unguarded while
+ // the others looked fixed.
+ const deny = () => {
+ throw new DOMException("The operation is insecure.", "SecurityError");
+ };
+ const getItem = vi.spyOn(Storage.prototype, "getItem").mockImplementation(deny);
+ const removeItem = vi.spyOn(Storage.prototype, "removeItem").mockImplementation(deny);
+ const setItem = vi.spyOn(Storage.prototype, "setItem").mockImplementation(deny);
+ mockCompany.companies = [{ id: "c1", name: "My Co", issuePrefix: "MC" }];
+ mockCompany.loading = false;
+
+ const { root, queryClient } = render();
+ await act(async () => {
+ root.render(
+ <QueryClientProvider client={queryClient}>
+ <OnboardingWizard />
+ </QueryClientProvider>,
+ );
+ });
+ await flushReact();
+
+ const close = [...document.body.querySelectorAll("button")].find((b) =>
+ b.textContent?.includes("Close"),
+ );
+ expect(close).toBeDefined();
+ await act(async () => {
+ close!.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ });
+ await flushReact();
+
+ expect(mockDialog.closeOnboarding).toHaveBeenCalled();
+
+ getItem.mockRestore();
+ removeItem.mockRestore();
+ setItem.mockRestore();
+ await act(async () => {
+ root.unmount();
+ });
+ });
+ it("leaves the draft untouched when the company query fails and onboarding is closed", async () => {
+ // Mounting is safe for the draft precisely because the persist effect is
+ // gated on the wizard being open. A closed wizard writes nothing, so the
+ // blob survives for a later load that can actually verify ownership.
+ const draft = JSON.stringify({
+ step: 3,
+ companyName: "Saved Co",
+ agentName: "Ops Lead",
+ createdCompanyId: "c1",
+ });
+ window.localStorage.setItem(ONBOARDING_STORAGE_KEY, draft);
+ mockDialog.onboardingOpen = false;
+ mockDialog.onboardingRouteDismissed = true;
+ mockCompany.companies = [];
+ mockCompany.loading = false;
+ mockCompany.error = new Error("company list unavailable");
+
+ const { root, queryClient } = render();
+ await act(async () => {
+ root.render(
+ <QueryClientProvider client={queryClient}>
+ <OnboardingWizard />
+ </QueryClientProvider>,
+ );
+ });
+ await flushReact();
+
+ expect(window.localStorage.getItem(ONBOARDING_STORAGE_KEY)).toBe(draft);
+
+ await act(async () => {
+ root.unmount();
+ });
+ });
+ it("does not hand one account's draft to the next when a refetch fails after a switch", async () => {
+ // The attack path in full. Account A onboards and leaves a draft naming
+ // its company. A signs out — which does not clear the companies cache,
+ // because `useSignOut` invalidates only the session and health queries.
+ // B signs in and the companies refetch fails, so A's list is still in
+ // hand. A list that still contains A's company must not be read as proof
+ // that B owns it.
+ window.localStorage.setItem(
+ ONBOARDING_STORAGE_KEY,
+ JSON.stringify({
+ // Step 3 so the agent-name input renders and can be asserted on —
+ // step 4 has no such field, which would make this pass for the wrong
+ // reason whether or not the draft was restored.
+ step: 3,
+ companyName: "Account A Co",
+ agentName: "A's Lead",
+ createdCompanyId: "company-a",
+ }),
+ );
+ mockCompany.companies = [{ id: "company-a", name: "Account A Co", issuePrefix: "AAC" }];
+ mockCompany.loading = false;
+ mockCompany.error = new Error("refetch failed for the new account");
+
+ const { root, queryClient } = render();
+ await act(async () => {
+ root.render(
+ <QueryClientProvider client={queryClient}>
+ <OnboardingWizard />
+ </QueryClientProvider>,
+ );
+ });
+ await flushReact();
+
+ // Account A's agent name must not appear in account B's wizard.
+ expect(document.body.textContent).not.toContain("A's Lead");
+ const nameInput = document.body.querySelector(
+ 'input[placeholder="Chief of staff"]',
+ ) as HTMLInputElement | null;
+ expect(nameInput?.value ?? "").not.toBe("A's Lead");
+
+ await act(async () => {
+ root.unmount();
+ });
+ });
+});
diff --git a/ui/src/components/OnboardingWizard.tsx b/ui/src/components/OnboardingWizard.tsx
index 3028262ac5..8737f7939f 100644
--- a/ui/src/components/OnboardingWizard.tsx
+++ b/ui/src/components/OnboardingWizard.tsx
@@ -31,6 +31,7 @@ import { useAdapterCapabilities } from "../adapters/use-adapter-capabilities";
import { getAdapterDisplay } from "../adapters/adapter-display-registry";
import { defaultCreateValues } from "./agent-config-defaults";
import { parseOnboardingGoalInput } from "../lib/onboarding-goal";
+import { restoreOnboardingState } from "../lib/onboarding-state";
import { composeCeoInstructions } from "../lib/ceo-instructions";
import {
buildOnboardingIssuePayload,
@@ -85,7 +86,9 @@ function buildMissionFromQuestionnaire(q1: string, q2: string, q3: string, q4: s
return parts.join(" ");
}
-const ONBOARDING_STORAGE_KEY = "paperclip-onboarding-state";
+// Exported so tests write/read the exact key the component uses, instead of
+// duplicating the literal and silently drifting from it if it's ever renamed.
+export const ONBOARDING_STORAGE_KEY = "paperclip-onboarding-state";
const DEFAULT_TASK_TITLE = "Paperclip onboarding";
const DEFAULT_TASK_DESCRIPTION = `You are the Paperclip agent. This is your first task. Your job here is to
understand what the user wants and turn it into a concrete plan — not to
@@ -114,19 +117,153 @@ Work in this order:
4. On approval, execute only what they kept. Create exactly the checked options — hire the checked agents and create + delegate the checked follow-up tasks, each in its own task. Skip anything the user unchecked.
Propose, don't decide. Keep it conversational.`;
+/**
+ * The onboarding draft in `localStorage`, via a browser that is allowed to say
+ * no.
+ *
+ * Storage access throws outright where a browser denies it — Safari's private
+ * mode, a blocked third-party context — and every call site here sits in a
+ * render, an effect, or a close handler, so an escaping exception takes down
+ * something the customer was using. Losing the ability to resume onboarding is
+ * a far smaller failure than the wizard tearing down mid-answer, or refusing
+ * to close.
+ *
+ * Routed through one object on purpose. Guarding these one at a time is how
+ * three of the four call sites ended up unguarded while the fourth looked
+ * fixed: the read, the stale-blob cleanup, the persist effect, and `reset()`
+ * all have the same failure and want the same answer.
+ */
+const onboardingDraftStorage = {
+ read(): string | null {
+ try {
+ return localStorage.getItem(ONBOARDING_STORAGE_KEY);
+ } catch {
+ return null;
+ }
+ },
+ write(value: string): void {
+ try {
+ localStorage.setItem(ONBOARDING_STORAGE_KEY, value);
+ } catch {
+ // Storage unavailable: the draft is simply not resumable this session.
+ }
+ },
+ clear(): void {
+ try {
+ localStorage.removeItem(ONBOARDING_STORAGE_KEY);
+ } catch {
+ // Nothing to do. A draft that cannot be cleared is re-rejected on the
+ // next load by the same ownership check that rejected it here.
+ }
+ },
+};
+
const INCOMPLETE_ONBOARDING_STATE_MESSAGE =
"Onboarding state is incomplete. Please restart onboarding and try again.";
-function loadSavedState(): Record<string, unknown> | null {
- try {
- const raw = localStorage.getItem(ONBOARDING_STORAGE_KEY);
- return raw ? JSON.parse(raw) : null;
- } catch {
+/**
+ * Thin gate in front of {@link OnboardingWizardInner}. The inner component's
+ * ~20 `useState(saved?.x ?? default)` initializers only read `saved` on their
+ * very first render, so it must never mount before the restored draft is
+ * final, otherwise every field locks to its default and the draft is lost
+ * for good. restoreOnboardingState requires the SETTLED companies list (see
+ * its JSDoc), so when a saved blob exists we wait for `companiesLoading` to
+ * clear before computing `saved` and mounting the inner component at all.
+ */
+export function OnboardingWizard() {
+ const { companies, loading: companiesLoading, error: companiesError } = useCompany();
+
+ // Parsed once (not re-parsed by the cleanup effect below) so the restored
+ // value and the "should we wipe the blob" decision always agree.
+ const rawBlob = useMemo(() => {
+ const raw = onboardingDraftStorage.read();
+ if (!raw) return undefined;
+ try {
+ return JSON.parse(raw) as unknown;
+ } catch {
+ return null; // malformed: treated as stale below
+ }
+ }, []);
+
+ // A failed company query is not an answer *when it left us with nothing*.
+ // React Query reports that as `isLoading === false` with `data` defaulted to
+ // an empty list, which reads exactly like "settled, and this account owns
+ // nothing" - and that verdict deletes the draft below. Discarding a
+ // customer's onboarding because their company request timed out is the one
+ // outcome here that cannot be undone.
+ //
+ // An error with companies still in hand is a different thing: a background
+ // refetch failed over a cache that is still good. Blocking on that would
+ // fail closed, and onboarding would simply never appear for a customer whose
+ // list is fine. Only an error that leaves the list empty is undecidable.
+ // Named for what it governs: whether the *draft* can be judged. It is not
+ // the same question as whether to mount - see the gate below.
+ // Any error at all, not only one that left the list empty.
+ //
+ // The companies cache is not scoped to an account and survives sign-out -
+ // `useSignOut` invalidates only the session and health queries, and
+ // invalidation keeps serving the old data anyway. So after A signs out and B
+ // signs in, a *failed* refetch leaves A's companies in hand. Trusting a
+ // non-empty list there would find A's company id in it, call the draft
+ // owned, and hand A's onboarding to B - which is the exact leak this whole
+ // change exists to close, reached through a different door.
+ //
+ // The cost is small and recoverable: during a transient refetch failure the
+ // draft is not restored. It is not deleted either, and the next successful
+ // load restores it.
+ //
+ // A truthy check rather than `!== null`. The context types this
+ // `Error | null`, but `undefined` reaches here from any consumer that
+ // provides the company context without an `error` key, and `undefined !==
+ // null` would read a healthy load as a failure.
+ const ownershipUndecidable = companiesLoading || Boolean(companiesError);
+
+ const { saved, staleStateDetected } = useMemo(() => {
+ if (rawBlob === undefined) return { saved: null, staleStateDetected: false };
+ // Companies not settled yet: restoreOnboardingState must not be called
+ // (see its CONTRACT). Not stale, just not decidable yet.
+ if (ownershipUndecidable) return { saved: null, staleStateDetected: false };
+ if (rawBlob === null) return { saved: null, staleStateDetected: true };
+ const restored = restoreOnboardingState(rawBlob, companies);
+ return { saved: restored, staleStateDetected: restored === null };
+ }, [rawBlob, ownershipUndecidable, companies]);
+
+ // A discarded/malformed state should not sit in storage waiting to confuse
+ // the next onboarding attempt (e.g. a different signed-in user).
+ useEffect(() => {
+ if (!staleStateDetected) return;
+ onboardingDraftStorage.clear();
+ }, [staleStateDetected]);
+
+ // A saved blob exists and the company list is still in flight: wait rather
+ // than mount the inner wizard with a premature, and unrecoverable, guess at
+ // the draft.
+ //
+ // Only while *loading*, not on error. An error with an empty list is still
+ // undecidable - nothing is restored and nothing is cleared, per the memo
+ // above - but withholding the wizard on top of that is a dead end, because
+ // the companies query sets `retry: false`. With no companies the dashboard
+ // offers a "Get Started" button that opens onboarding, and a gate that
+ // returned null here would make that button do nothing at all until a
+ // refetch happened to succeed.
+ //
+ // Mounting does not cost the draft. The persist effect that would overwrite
+ // it is itself gated on `effectiveOnboardingOpen`, so a mounted-but-closed
+ // wizard writes nothing, and the blob survives for a later load that can
+ // decide. If the wizard *is* open the customer is onboarding right now,
+ // which supersedes the draft anyway.
+ if (rawBlob !== undefined && companiesLoading) {
return null;
}
+
+ return <OnboardingWizardInner saved={saved} />;
}
-export function OnboardingWizard() {
+function OnboardingWizardInner({
+ saved,
+}: {
+ saved: Record<string, unknown> | null;
+}) {
const {
onboardingOpen,
onboardingOptions,
@@ -186,9 +323,6 @@ export function OnboardingWizard() {
const initialStep = effectiveOnboardingOptions.initialStep ?? 0;
const existingCompanyId = effectiveOnboardingOptions.companyId;
- // Restore saved state from localStorage (read once on mount)
- const saved = useMemo(loadSavedState, []);
-
const [step, setStep] = useState<Step>((saved?.step as Step) ?? initialStep);
const [onboardingPath, setOnboardingPath] = useState<"create" | "grow" | null>((saved?.onboardingPath as "create" | "grow" | null) ?? null);
@@ -396,7 +530,7 @@ export function OnboardingWizard() {
createdCompanyGoalId, createdProjectId, createdIssueRef,
onboardingPath, growWorkflows, growPainPoints, growAutomate,
};
- localStorage.setItem(ONBOARDING_STORAGE_KEY, JSON.stringify(state));
+ onboardingDraftStorage.write(JSON.stringify(state));
}, [
effectiveOnboardingOpen, step, companyName, companyGoal, missionPath, missionConfirmed,
q1, q2, q3, q4, agentName, adapterType, cwd, model, command, args, url,
@@ -551,7 +685,7 @@ export function OnboardingWizard() {
}, [filteredModels, adapterType]);
function reset() {
- localStorage.removeItem(ONBOARDING_STORAGE_KEY);
+ onboardingDraftStorage.clear();
setStep(0);
setOnboardingPath(null);
setGrowWorkflows("");
diff --git a/ui/src/lib/onboarding-state.test.ts b/ui/src/lib/onboarding-state.test.ts
new file mode 100644
index 0000000000..35071a33d9
--- /dev/null
+++ b/ui/src/lib/onboarding-state.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it } from "vitest";
+import { restoreOnboardingState } from "./onboarding-state";
+
+const companies = [{ id: "company-new" }];
+
+describe("restoreOnboardingState", () => {
+ it("returns null for unusable input", () => {
+ expect(restoreOnboardingState(null, companies)).toBeNull();
+ expect(restoreOnboardingState("nonsense", companies)).toBeNull();
+ });
+
+ it("discards state whose company the user does not own", () => {
+ const saved = { step: 4, companyName: "Old Co", createdCompanyId: "company-old" };
+ expect(restoreOnboardingState(saved, companies)).toBeNull();
+ });
+
+ it("keeps state for a company the user does own", () => {
+ const saved = { step: 4, companyName: "New Co", createdCompanyId: "company-new" };
+ expect(restoreOnboardingState(saved, companies)?.companyName).toBe("New Co");
+ });
+
+ it("keeps in-progress state that has no company yet", () => {
+ const saved = { step: 1, companyName: "Draft" };
+ expect(restoreOnboardingState(saved, companies)?.companyName).toBe("Draft");
+ });
+
+ it("discards a company id against an empty (settled) companies list", () => {
+ // Per the CONTRACT in the JSDoc, callers must only invoke this once
+ // companies have settled. An empty settled list legitimately means the
+ // account owns no companies, so a saved company id is discarded exactly
+ // like an unowned one.
+ const saved = { step: 4, createdCompanyId: "company-new" };
+ expect(restoreOnboardingState(saved, [])).toBeNull();
+ });
+});
diff --git a/ui/src/lib/onboarding-state.ts b/ui/src/lib/onboarding-state.ts
new file mode 100644
index 0000000000..e9dfed0e8a
--- /dev/null
+++ b/ui/src/lib/onboarding-state.ts
@@ -0,0 +1,31 @@
+/**
+ * localStorage is scoped per ORIGIN, not per account, so a browser that already
+ * ran onboarding will happily hand a previous company's id to a brand new
+ * session. Every downstream call then targets the wrong company: goals,
+ * agents, and issues get created there, and requests targeting the actual
+ * company fail with authorization errors.
+ *
+ * So restoring is an authorization decision, not a convenience. If the saved
+ * company is not one the signed-in user owns, the whole blob is discarded.
+ *
+ * CONTRACT: `companies` must be the caller's SETTLED companies list (its
+ * loading query/context has finished, e.g. `companiesLoading === false`).
+ * This function has no way to tell an empty-because-still-loading list apart
+ * from an empty-because-the-account-owns-nothing list, so it always treats
+ * an empty `companies` as "owns nothing" and discards a saved company id.
+ * Callers must not invoke this while companies are still loading, wait for
+ * the settled list first, or a legitimate draft gets discarded by mistake.
+ */
+export function restoreOnboardingState(
+ raw: unknown,
+ companies: Array<{ id: string }>,
+): Record<string, unknown> | null {
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
+
+ const saved = { ...(raw as Record<string, unknown>) };
+
+ const companyId = saved.createdCompanyId;
+ if (typeof companyId !== "string" || companyId === "") return saved;
+
+ return companies.some((c) => c.id === companyId) ? saved : null;
+}