From 630cf04230241ca7fa71962756d3e7246847653f Mon Sep 17 00:00:00 2001 From: Nicky Leach Date: Mon, 30 Nov 2026 13:34:23 -0800 Subject: [PATCH] feat(onboarding): create the first agent's setup draft in the naming step (#23315) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Onboarding creates a company, names its first agent, and then connects the agent to an AI provider > - A plugin can manage an execution environment that its driver prepares for each agent (`requiresAgent`). The agent's lifecycle starts that preparation when the agent's setup draft exists > - Onboarding created the setup draft when the connect step opened, after the agent was named > - The preparation can be slow, and a subscription sign-in in that environment waits for it > - This pull request creates the setup draft in the naming step, so the preparation overlaps naming > - The benefit is a shorter wait before sign-in when the default environment is plugin-managed ## Linked Issues or Issue Description Refs #23312. **What existing behavior does this improve?** The onboarding naming step and the connect step for a new company. **Current behavior** The wizard creates the first agent's provisional setup draft when the connect step opens. A plugin-managed execution environment starts its preparation for the agent only then. A subscription sign-in in that environment waits for the full preparation (see #23312). **Proposed behavior** The wizard creates the same provisional setup draft when the naming step opens for a company with no agents. The preparation runs while the user names the agent. **Reason and benefit** The preparation does not depend on the provider choice. A later configuration change prepares the same environment again, which is fast because the environment already exists. The user waits less before sign-in. ## What Changed - The naming step creates the provisional setup draft as soon as a company with no agents exists. The draft is the same record the connect step created before: a provisional adapter, `setupAdapterPending`, and the role label as a placeholder name. - The naming step saves the typed name to the draft after a 400 ms pause in typing. The connect step saves it at once, as before. - A company that has agents keeps the old path, so the connect step's same-name reuse still applies. A failed early create also falls back to the connect step. The wizard tries the early create once per company. - When the connect step restores a provisional draft (source still pending), the wizard keeps its own name, role and appearance when it has a name. A name typed after a reload in the naming step is newer than the draft's name. - The `create-company path` e2e test now expects the draft when the naming step opens. A new e2e test covers the early draft, the saved name, a reload in the naming step, and that the connect step adopts the same record. ## Verification - `pnpm typecheck` in `ui/`: no errors. - `PAPERCLIP_PLAYWRIGHT_CHANNEL=chrome npx playwright test --config tests/e2e/playwright.config.ts tests/e2e/onboarding-early-setup.spec.ts tests/e2e/onboarding.spec.ts -g "naming step creates|create-company path"`: 2 tests pass. - The new `onboarding-early-setup` test fails without the wizard change: it times out while it waits for the draft in the naming step. - I did not measure the time saved on a live plugin-managed execution environment. It is about the time the user spends in the naming step. ## Risks - A user who stops onboarding in the naming step leaves a setup draft. In a plugin-managed execution environment, that draft also keeps its prepared environment. Before this change, the same happened to a user who stopped in the connect step. - The draft's name is the role label until the first save in the naming step. A reload in the first 400 ms after typing can lose those characters. The wizard keeps the name that is typed after the reload. - No migration and no API change. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), with extended thinking and tool use (code search, shell, tests) in Claude Code. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- tests/e2e/onboarding-early-setup.spec.ts | 52 +++++++++++++++ tests/e2e/onboarding.spec.ts | 14 ++-- ui/src/components/OnboardingWizard.tsx | 82 ++++++++++++++++++++---- 3 files changed, 130 insertions(+), 18 deletions(-) create mode 100644 tests/e2e/onboarding-early-setup.spec.ts diff --git a/tests/e2e/onboarding-early-setup.spec.ts b/tests/e2e/onboarding-early-setup.spec.ts new file mode 100644 index 00000000000..3f26510147f --- /dev/null +++ b/tests/e2e/onboarding-early-setup.spec.ts @@ -0,0 +1,52 @@ +import { test, expect } from "@playwright/test"; + +const COMPANY_NAME = `E2E-Early-Setup-${Date.now()}`; + +test.describe("Onboarding wizard", () => { + test("the naming step creates the setup draft and keeps the typed name", async ({ page }) => { + const pageErrors: string[] = []; + page.on("pageerror", (err) => pageErrors.push(err.message)); + + await page.goto("/onboarding"); + const startBtn = page.getByRole("button", { name: /Start Onboarding|New Organization|Add Agent/ }); + if (await startBtn.count()) await startBtn.first().click(); + const createCard = page.getByRole("button", { name: /Build a new organization/ }); + if (await createCard.count()) await createCard.first().click(); + + await expect( + page.getByRole("heading", { name: "What is the name of your organization?" }), + ).toBeVisible({ timeout: 15_000 }); + await page.getByPlaceholder("e.g. Northwind Labs").fill(COMPANY_NAME); + const draftCreated = page.waitForResponse((response) => + response.request().method() === "POST" + && /^\/api\/companies\/[^/]+\/agents$/.test(new URL(response.url()).pathname), { timeout: 30_000 }); + await page.getByRole("button", { name: /^Continue/ }).click(); + + const nameField = page.locator("#onboarding-agent-name"); + await nameField.waitFor({ timeout: 30_000 }); + const draft = await (await draftCreated).json(); + await expect(nameField).toBeVisible(); + expect(draft).toMatchObject({ pauseReason: "setup", metadata: { setupAdapterPending: true } }); + const companyId: string = draft.companyId; + const readDraft = async () => + (await (await page.request.get(`/api/agents/${draft.id}?companyId=${companyId}`)).json()) as { name: string }; + + await nameField.fill("Ada"); + await expect.poll(async () => (await readDraft()).name, { timeout: 15_000 }).toBe("Ada"); + + await page.reload(); + await nameField.waitFor({ timeout: 30_000 }); + await nameField.fill("Grace"); + await expect.poll(async () => (await readDraft()).name, { timeout: 15_000 }).toBe("Grace"); + await page.getByRole("button", { name: "Next" }).click(); + + await expect(page.getByRole("radio").first()).toBeVisible({ timeout: 30_000 }); + await expect(page.getByTestId("onboarding-wizard").getByText("Grace", { exact: true })).toBeVisible(); + await expect.poll(async () => (await readDraft()).name, { timeout: 15_000 }).toBe("Grace"); + + const agents = await (await page.request.get(`/api/companies/${companyId}/agents`)).json() as Array<{ id: string; status: string }>; + expect(agents.filter((agent) => agent.status !== "terminated").map((agent) => agent.id)).toEqual([draft.id]); + + expect(pageErrors, pageErrors.join("\n")).toHaveLength(0); + }); +}); diff --git a/tests/e2e/onboarding.spec.ts b/tests/e2e/onboarding.spec.ts index 99b56d0c873..1cb40bac9e4 100644 --- a/tests/e2e/onboarding.spec.ts +++ b/tests/e2e/onboarding.spec.ts @@ -76,6 +76,9 @@ test.describe("Onboarding wizard", () => { ).toBeVisible({ timeout: 15_000 }); await page.getByPlaceholder("e.g. Northwind Labs").fill(COMPANY_NAME); delayCompanyListRefetch = true; + const firstSetupResponse = page.waitForResponse(response => + response.request().method() === "POST" && /^\/api\/companies\/[^/]+\/agents$/.test(new URL(response.url()).pathname), + { timeout: 30_000 }); await page.getByRole("button", { name: /^Continue/ }).click(); // Step 1's "Next" now creates the company and goes straight to the agent. @@ -112,13 +115,12 @@ test.describe("Onboarding wizard", () => { "onboarding must not invent a mission the customer never gave", ).toBeFalsy(); - // Name submission persists an inactive record before the provider question. - await page.locator("#onboarding-agent-name").fill("Ada"); - const firstSetupResponse = page.waitForResponse(response => - response.request().method() === "POST" && response.url().endsWith(`/api/companies/${company.id}/agents`)); - await page.getByRole("button", { name: "Next", exact: true }).click(); const firstSetup = await (await firstSetupResponse).json(); - expect(firstSetup).toMatchObject({ name: "Ada", pauseReason: "setup", metadata: { setupAdapterPending: true } }); + expect(firstSetup).toMatchObject({ companyId: company.id, pauseReason: "setup", metadata: { setupAdapterPending: true } }); + await page.locator("#onboarding-agent-name").fill("Ada"); + await page.getByRole("button", { name: "Next", exact: true }).click(); + await expect.poll(async () => (await (await page.request.get(`/api/agents/${firstSetup.id}?companyId=${company.id}`)).json()).name) + .toBe("Ada"); await expect(page.getByRole("radio").first()).toBeVisible(); await expect(page.locator('[role="radio"][aria-checked="true"]')).toHaveCount(0); diff --git a/ui/src/components/OnboardingWizard.tsx b/ui/src/components/OnboardingWizard.tsx index b66b0e7786f..2934a00bc95 100644 --- a/ui/src/components/OnboardingWizard.tsx +++ b/ui/src/components/OnboardingWizard.tsx @@ -732,6 +732,7 @@ function OnboardingWizardInner({ const [setupError, setSetupError] = useState(false); const [setupAttempt, setSetupAttempt] = useState(0); const preparingSetup = useRef(new Set()); + const earlySetupTried = useRef(new Set()); const [restoredSetup, setRestoredSetup] = useState(null); const setupSave = useRef>(Promise.resolve()); const [createdCompanyGoalId, setCreatedCompanyGoalId] = useState( @@ -1389,6 +1390,56 @@ function OnboardingWizardInner({ && !selectedSavedKey && (restoredSetup.adapterConfig.env as Record | undefined)?.[apiKeyEnvKeyFor(adapterType)]; const connectStepReady = Boolean(setupPrepared || createdAgentId) && sourceSelected && !adapterEnvLoading && !savedKeys.loading && runnerDiscoveryReady && !browserSignInUnavailable && connectionModelReady; + useEffect(() => { + if (step !== 3 || !createdCompanyId || !setupAgentId || createdAgentId || setupPrepared + || preparingSetup.current.has(createdCompanyId) || setupError) return; + const companyId = createdCompanyId; + const id = setupAgentId; + preparingSetup.current.add(companyId); + void agentsApi.get(id, companyId).then(agent => { + if (!stillTheSameCompany(companyId) || agent.id !== id || agent.companyId !== companyId + || agent.pauseReason !== "setup" || agent.metadata?.setupAdapterPending !== true) return; + if (agent.name !== AGENT_ROLE_LABELS[agent.role]) setAgentName(current => current.trim() ? current : agent.name); + setSetupPrepared(true); + }).catch(() => {}).finally(() => { + preparingSetup.current.delete(companyId); + setSetupAttempt(attempt => attempt + 1); + }); + }, [step, createdCompanyId, setupAgentId, createdAgentId, setupPrepared, setupError]); + + useEffect(() => { + if (step !== 3 || !createdCompanyId || !adapterRegistryLoaded || setupAgentId || createdAgentId + || setupPrepared || preparingSetup.current.has(createdCompanyId) || earlySetupTried.current.has(createdCompanyId) + || setupError) return; + const companyId = createdCompanyId; + earlySetupTried.current.add(companyId); + preparingSetup.current.add(companyId); + const id = crypto.randomUUID(); + void (async () => { + if ((await agentsApi.list(companyId)).some(agent => agent.status !== "terminated")) return null; + const provisionalAdapter = disabledTypes.has("process") ? recommendedAdapters[0]?.type : "process"; + if (!provisionalAdapter || !stillTheSameCompany(companyId)) return null; + setSetupAgentId(id); + return agentsApi.create(companyId, { + setupId: id, name: AGENT_ROLE_LABELS[agentRole], appearance: agentAppearance, + role: agentRole, adapterType: provisionalAdapter, adapterConfig: {}, + metadata: { setupAdapterPending: true }, + onboardingFirstAgent: true, runtimeConfig: buildNewAgentRuntimeConfig({ heartbeatEnabled: false }), + }); + })().then(agent => { + if (!agent || !stillTheSameCompany(companyId)) return; + setSetupAgentId(agent.id); + if (agent.pauseReason !== "setup" && agent.status !== "pending_approval") setCreatedAgentId(agent.id); + setSetupPrepared(true); + void queryClient.invalidateQueries({ queryKey: queryKeys.agents.list(companyId) }); + }).catch(() => { + if (stillTheSameCompany(companyId)) setSetupAgentId(current => current === id ? null : current); + }).finally(() => { + preparingSetup.current.delete(companyId); + setSetupAttempt(attempt => attempt + 1); + }); + }, [step, createdCompanyId, adapterRegistryLoaded, setupAgentId, createdAgentId, setupPrepared, setupError]); + useEffect(() => { if (step !== 4 || !createdCompanyId || !agentName.trim() || !adapterRegistryLoaded || createdAgentId || setupPrepared || preparingSetup.current.has(createdCompanyId) || setupError @@ -1435,9 +1486,11 @@ function OnboardingWizardInner({ if (!restoring && agent.name) setAgentName(current => current.trim() === agentName.trim() ? agent.name : current); if (restoring && agent.adapterConfig) { setRestoredSetup(agent); - setAgentName(agent.name); - setAgentRole(agent.role); - setAgentAppearance(resolveAgentAppearance(agent.appearance, agent.id)); + if (!(agent.metadata?.setupAdapterPending === true && agentName.trim())) { + setAgentName(agent.name); + setAgentRole(agent.role); + setAgentAppearance(resolveAgentAppearance(agent.appearance, agent.id)); + } const config = agent.adapterConfig; if (agent.metadata?.setupAdapterPending === true) { setRunner("auto"); @@ -2262,7 +2315,7 @@ function OnboardingWizardInner({ return { ...runtimeConfig, ...(!existingAgent ? buildNewAgentRuntimeConfig({ heartbeatEnabled }) : {}), ...(binding ? { aiConnection: binding } : {}) }; } - const setupSnapshot = step === 4 && setupPrepared && setupAgentId && !createdAgentId && !loading + const setupSnapshot = (step === 3 || step === 4) && setupPrepared && setupAgentId && !createdAgentId && !loading ? JSON.stringify({ name: agentName.trim() || AGENT_ROLE_LABELS[agentRole], appearance: agentAppearance, ...(sourceSelected && runnerDiscoveryReady ? { adapterType, runner, @@ -2276,14 +2329,19 @@ function OnboardingWizardInner({ if (!setupSnapshot || !setupAgentId || !createdCompanyId) return; const companyId = createdCompanyId; const id = setupAgentId; - setupSave.current = setupSave.current.catch(() => {}).then(async () => { - if (!stillTheSameCompany(companyId) || hiringAgentRef.current !== null) return; - await agentsApi.update(id, JSON.parse(setupSnapshot), companyId); - }); - void setupSave.current.catch(cause => { - if (stillTheSameCompany(companyId)) setError(cause instanceof Error ? cause.message : "Could not save agent setup."); - }); - }, [setupSnapshot, setupAgentId, createdCompanyId]); + const save = () => { + setupSave.current = setupSave.current.catch(() => {}).then(async () => { + if (!stillTheSameCompany(companyId) || hiringAgentRef.current !== null) return; + await agentsApi.update(id, JSON.parse(setupSnapshot), companyId); + }); + void setupSave.current.catch(cause => { + if (stillTheSameCompany(companyId)) setError(cause instanceof Error ? cause.message : "Could not save agent setup."); + }); + }; + if (step !== 3) { save(); return; } + const timer = setTimeout(save, 400); + return () => clearTimeout(timer); + }, [setupSnapshot, setupAgentId, createdCompanyId, step]); async function runAdapterEnvironmentTest( adapterConfigOverride?: Record,