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,