AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
feat(frontend/onboarding): hire the whole recommended team in one click on the hire step (#15836)
Reinier van der Leer939e2c312429
diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/HireStep/HireStep.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/HireStep/HireStep.tsxindex b9f2b1f90d..65239d9424 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/HireStep/HireStep.tsx+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/HireStep/HireStep.tsx@@ -1,17 +1,17 @@"use client";-import { Button } from "@/components/atoms/Button/Button";import { FadeIn } from "@/components/atoms/FadeIn/FadeIn";import { Skeleton } from "@/components/atoms/Skeleton/Skeleton";import { Text } from "@/components/atoms/Text/Text";import { AutopilotAvatar } from "@/components/molecules/AutopilotAvatar/AutopilotAvatar";import { cn } from "@/lib/utils";import { useRef } from "react";+import { HireStepActions } from "./components/HireStepActions";import {EXPERT_CARD_CLASS,RecommendedExpertCard,} from "./components/RecommendedExpertCard";-import { continueLabel, hireDiagnosis, hireTitle, raiseNote } from "./helpers";+import { hireDiagnosis, hireTitle, raiseNote } from "./helpers";import { useHireStep } from "./useHireStep";import { useScrollEdges } from "./useScrollEdges";@@ -23,13 +23,13 @@ const EDGE_FADE_CLASS =// Otto's first act as Head of AI: right after the brain dump, before the// user is asked to pay for anything, it proposes the experts that take the-// problems it heard off the user's plate. Hiring here is one click per card;-// the voice pick waits for the expert's own page.+// problems it heard off the user's plate. One click hires the whole team, or+// one card at a time; the voice pick waits for the expert's own page.export function HireStep() {const step = useHireStep();const note = raiseNote(step.raiseRole);const diagnosis = hireDiagnosis(step.team, step.isPending);- const isHiring = step.hiringTemplateId !== null;+ const isBusy = step.isCardHiring || step.isHiringAll;const gridRef = useRef<HTMLDivElement>(null);const { hiddenAbove, hiddenBelow } = useScrollEdges(gridRef);@@ -109,11 +109,13 @@ export function HireStep() {isHired={step.hiredTemplateIds.includes(expert.template_id,)}- isHiringThis={- step.hiringTemplateId === expert.template_id- }- disabled={isHiring}+ isHiringThis={step.isHiringCard(expert.template_id)}+ isIncluded={step.isIncluded(expert.template_id)}+ disabled={isBusy}onHire={() => step.hire(expert, index)}+ onToggleIncluded={() =>+ step.toggleIncluded(expert.template_id)+ }/></div>))}@@ -131,15 +133,15 @@ export function HireStep() {</Text>) : null}- <Button- type="button"- size="small"- onClick={step.handleContinue}- disabled={isHiring}- className="h-10 w-56 rounded-xl"- >- {continueLabel(step.hiredTemplateIds.length)}- </Button>+ <HireStepActions+ isPending={step.isPending}+ isHiringAll={step.isHiringAll}+ isCardHiring={step.isCardHiring}+ primaryLabel={step.primaryLabel}+ secondaryLabel={step.secondaryLabel}+ onPrimary={step.handlePrimary}+ onSecondary={step.handleSecondary}+ /></div></FadeIn>);diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/HireStep/__tests__/HireStep.test.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/HireStep/__tests__/HireStep.test.tsxindex 2a32cca237..4bf37e7bc8 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/HireStep/__tests__/HireStep.test.tsx+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/HireStep/__tests__/HireStep.test.tsx@@ -60,6 +60,22 @@ const FALLBACK_TEAM: ExpertRecommendations = {raise_suggestion: null,};+const THREE_TEAM: ExpertRecommendations = {+ ...TEAM,+ experts: [+ ...TEAM.experts!,+ {+ template_id: "tpl-sam",+ name: "Sam",+ role: "Support",+ avatar_url: null,+ reason: "Tickets pile up over the weekend.",+ workflow_names: [],+ },+ ],+ raise_suggestion: null,+};+const EMPTY_TEAM: ExpertRecommendations = {diagnosis: "Hard to say what eats your week yet.",source: "fallback",@@ -71,6 +87,28 @@ function mockTeam(team: ExpertRecommendations | null, ready = true) {server.use(getGetBrainDumpRecommendedExpertsMockHandler200({ ready, team }));}+// Records every hire's template id; `failing` answers 503 until removed.+function mockHires(failing = new Set<string>(), gate?: Promise<void>) {+ const hired: string[] = [];+ server.use(+ http.post("*/api/experts", async ({ request }) => {+ const { template_id } = (await request.json()) as {+ template_id: string;+ };+ hired.push(template_id);+ await gate;+ return failing.has(template_id)+ ? HttpResponse.json({ detail: "unavailable" }, { status: 503 })+ : HttpResponse.json({ expert: { id: `exp-${template_id}` } });+ }),+ );+ return hired;+}++function events(name: string) {+ return capture.mock.calls.filter(([event]) => event === name);+}+beforeEach(() => {capture.mockReset();toast.mockReset();@@ -143,9 +181,10 @@ describe("HireStep — the team", () => {"Hard to say what eats your week yet.",);expect(screen.queryAllByTestId("hire-step-expert")).toHaveLength(0);+ expect(screen.getByRole("button", { name: "Continue" })).toBeDefined();expect(- screen.getByRole("button", { name: "I'll add members later" }),- ).toBeDefined();+ screen.queryByRole("button", { name: "I'll add members later" }),+ ).toBeNull();});});@@ -178,7 +217,8 @@ describe("HireStep — hiring", () => {]);// One hire down, one still open.expect(screen.getAllByRole("button", { name: "Hire" })).toHaveLength(1);- expect(screen.getByRole("button", { name: "Next" })).toBeDefined();+ expect(screen.getByRole("button", { name: "Hire Max too" })).toBeDefined();+ expect(screen.getByRole("button", { name: "Continue" })).toBeDefined();// One hire_started per click; the hire itself is the backend's// expert_hired, so the browser sends no completion event.expect(@@ -235,17 +275,327 @@ describe("HireStep — hiring", () => {await userEvent.click((await screen.findAllByRole("button", { name: "Hire" }))[0],);- await screen.findByRole("button", { name: "Next" });- await userEvent.click(screen.getByRole("button", { name: "Next" }));+ await userEvent.click(+ await screen.findByRole("button", { name: "Continue" }),+ );expect(useOnboardingWizardStore.getState().currentStep).toBe(6);expect(capture).toHaveBeenCalledWith("hire_step_continued", {hired: 1,recommended: 2,+ via: "continue",});});});+describe("HireStep — hiring the whole team", () => {+ it.each([+ {+ team: TEAM,+ hired: [],+ primary: "Hire all 2",+ skip: "I'll add members later",+ },+ {+ team: { ...TEAM, experts: TEAM.experts!.slice(0, 1) },+ hired: [],+ primary: "Hire Maria",+ skip: "I'll add members later",+ },+ {+ team: THREE_TEAM,+ hired: ["tpl-maria"],+ primary: "Hire the other 2",+ skip: "Continue",+ },+ {+ team: THREE_TEAM,+ hired: ["tpl-maria", "tpl-max"],+ primary: "Hire Sam too",+ skip: "Continue",+ },+ {+ team: THREE_TEAM,+ hired: ["tpl-maria", "tpl-max", "tpl-sam"],+ primary: "Continue",+ skip: null,+ },+ ])(+ "offers '$primary' with $hired.length hired",+ async ({ team, hired, primary, skip }) => {+ mockTeam(team);+ hired.forEach((id) => useOnboardingWizardStore.getState().markHired(id));+ render(<HireStep />);++ expect(+ await screen.findByRole("button", { name: primary }),+ ).toBeDefined();+ const skips = ["I'll add members later", "Continue"].filter(+ (name) => name !== primary && screen.queryByRole("button", { name }),+ );+ expect(skips).toEqual(skip ? [skip] : []);+ },+ );++ it("hires every recommended expert in one click, then moves on", async () => {+ mockTeam(THREE_TEAM);+ const hired = mockHires();+ render(<HireStep />);++ await userEvent.click(+ await screen.findByRole("button", { name: "Hire all 3" }),+ );++ expect(await screen.findAllByText("Hired")).toHaveLength(3);+ await waitFor(() =>+ expect(useOnboardingWizardStore.getState().currentStep).toBe(6),+ );+ expect(hired).toEqual(["tpl-maria", "tpl-max", "tpl-sam"]);+ expect(useOnboardingWizardStore.getState().hiredTemplateIds).toEqual([+ "tpl-maria",+ "tpl-max",+ "tpl-sam",+ ]);+ expect(events("hire_all_clicked")).toEqual([+ [+ "hire_all_clicked",+ { count: 3, already_hired: 0, recommended: 3, retry: false },+ ],+ ]);+ expect(events("hire_started")).toHaveLength(3);+ expect(events("expert_recommendation_clicked")).toEqual([]);+ expect(events("hire_step_continued")).toEqual([+ ["hire_step_continued", { hired: 3, recommended: 3, via: "auto" }],+ ]);+ });++ it("counts who is left in as cards are left out, down to the skip alone", async () => {+ mockTeam(THREE_TEAM);+ render(<HireStep />);++ await screen.findByRole("button", { name: "Hire all 3" });+ const max = screen.getByRole("button", { name: "Include Max" });+ expect(max.getAttribute("aria-pressed")).toBe("true");++ await userEvent.click(max);+ expect(max.getAttribute("aria-pressed")).toBe("false");+ expect(screen.getByRole("button", { name: "Hire 2" })).toBeDefined();++ await userEvent.click(screen.getByRole("button", { name: "Include Sam" }));+ expect(screen.getByRole("button", { name: "Hire Maria" })).toBeDefined();++ await userEvent.click(+ screen.getByRole("button", { name: "Include Maria" }),+ );+ const stepActions = screen+ .getAllByRole("button")+ .filter(+ (button) =>+ !button.getAttribute("aria-label")?.startsWith("Include") &&+ button.textContent !== "Hire",+ )+ .map((button) => button.textContent);+ expect(stepActions).toEqual(["I'll add members later"]);++ await userEvent.click(screen.getByRole("button", { name: "Include Sam" }));+ expect(screen.getByRole("button", { name: "Hire Sam" })).toBeDefined();+ });++ it("does not hire an expert the user left out", async () => {+ mockTeam(THREE_TEAM);+ const hired = mockHires();+ render(<HireStep />);++ await userEvent.click(+ await screen.findByRole("button", { name: "Include Max" }),+ );+ await userEvent.click(screen.getByRole("button", { name: "Hire 2" }));++ await waitFor(() =>+ expect(useOnboardingWizardStore.getState().currentStep).toBe(6),+ );+ expect(hired).toEqual(["tpl-maria", "tpl-sam"]);+ expect(useOnboardingWizardStore.getState().hiredTemplateIds).toEqual([+ "tpl-maria",+ "tpl-sam",+ ]);+ expect(events("hire_all_clicked")).toEqual([+ [+ "hire_all_clicked",+ { count: 2, already_hired: 0, recommended: 3, retry: false },+ ],+ ]);+ });++ it("hides the skip and holds Back from the click until the step moves on", async () => {+ mockTeam(THREE_TEAM);+ let release!: () => void;+ mockHires(new Set(), new Promise<void>((resolve) => (release = resolve)));+ // Back is hidden while the step is busy; a Back during the advance beat+ // would land the timer's nextStep on the previous step.+ const busyChangesOnHireStep: boolean[] = [];+ const unsubscribe = useOnboardingWizardStore.subscribe((state, prev) => {+ if (state.currentStep === 5 && state.isStepBusy !== prev.isStepBusy) {+ busyChangesOnHireStep.push(state.isStepBusy);+ }+ });+ render(<HireStep />);++ await userEvent.click(+ await screen.findByRole("button", { name: "Hire all 3" }),+ );++ expect(+ await screen.findByRole("button", { name: "Hiring…" }),+ ).toBeDefined();+ expect(+ screen.queryByRole("button", { name: "I'll add members later" }),+ ).toBeNull();+ release();+ await waitFor(() =>+ expect(useOnboardingWizardStore.getState().currentStep).toBe(6),+ );+ unsubscribe();+ expect(busyChangesOnHireStep).toEqual([true]);+ });++ it.each([+ { when: "before its hires land", landFirst: false },+ { when: "during the advance beat", landFirst: true },+ ])(+ "does not move the wizard on when the step is left $when",+ async ({ landFirst }) => {+ mockTeam(THREE_TEAM);+ let release!: () => void;+ mockHires(new Set(), new Promise<void>((resolve) => (release = resolve)));+ const { unmount } = render(<HireStep />);++ await userEvent.click(+ await screen.findByRole("button", { name: "Hire all 3" }),+ );+ await screen.findByRole("button", { name: "Hiring…" });+ if (landFirst) {+ release();+ expect(await screen.findAllByText("Hired")).toHaveLength(3);+ }+ // Browser navigation unmounts the step; Back being hidden does not stop it.+ unmount();+ render(<HireStep />);+ await screen.findAllByTestId("hire-step-expert");+ release();++ await waitFor(() =>+ expect(+ useOnboardingWizardStore.getState().hiredTemplateIds,+ ).toHaveLength(3),+ );+ await new Promise((resolve) => setTimeout(resolve, 800));+ expect(useOnboardingWizardStore.getState().currentStep).toBe(5);+ expect(events("hire_step_continued")).toEqual([]);+ },+ );++ it("keeps the hires that landed, names the one that did not, and offers to try it again", async () => {+ mockTeam(THREE_TEAM);+ const failing = new Set(["tpl-sam"]);+ const hired = mockHires(failing);+ render(<HireStep />);++ await userEvent.click(+ await screen.findByRole("button", { name: "Hire all 3" }),+ );++ await waitFor(() =>+ expect(toast).toHaveBeenCalledWith({+ title: "Couldn't hire Sam",+ description:+ "Something went wrong. Try again, or continue without them.",+ variant: "destructive",+ }),+ );+ expect(screen.getAllByText("Hired")).toHaveLength(2);+ expect(screen.getByRole("button", { name: "Continue" })).toBeDefined();+ // A failure never auto-advances, however long the user looks at it.+ await new Promise((resolve) => setTimeout(resolve, 800));+ expect(useOnboardingWizardStore.getState().currentStep).toBe(5);++ failing.clear();+ await userEvent.click(screen.getByRole("button", { name: "Try again" }));++ await waitFor(() =>+ expect(useOnboardingWizardStore.getState().currentStep).toBe(6),+ );+ expect(hired).toEqual(["tpl-maria", "tpl-max", "tpl-sam", "tpl-sam"]);+ expect(events("hire_all_clicked")[1]).toEqual([+ "hire_all_clicked",+ { count: 1, already_hired: 2, recommended: 3, retry: true },+ ]);+ });++ it("says the team could not be hired when every hire fails", async () => {+ mockTeam(THREE_TEAM);+ mockHires(new Set(["tpl-maria", "tpl-max", "tpl-sam"]));+ render(<HireStep />);++ await userEvent.click(+ await screen.findByRole("button", { name: "Hire all 3" }),+ );++ await waitFor(() =>+ expect(toast).toHaveBeenCalledWith({+ title: "Couldn't hire your team",+ description: "Something went wrong. Please try again.",+ variant: "destructive",+ }),+ );+ expect(screen.getByRole("button", { name: "Try again" })).toBeDefined();+ expect(+ screen.getByRole("button", { name: "I'll add members later" }),+ ).toBeDefined();+ expect(screen.queryByText("Hired")).toBeNull();+ });++ it("starts one batch and moves on once on a double click", async () => {+ mockTeam(THREE_TEAM);+ let release!: () => void;+ const hired = mockHires(+ new Set(),+ new Promise<void>((resolve) => (release = resolve)),+ );+ render(<HireStep />);++ await userEvent.dblClick(+ await screen.findByRole("button", { name: "Hire all 3" }),+ );+ release();++ await waitFor(() =>+ expect(useOnboardingWizardStore.getState().currentStep).toBe(6),+ );+ // Past the advance beat: a second nextStep would skip the next step.+ await new Promise((resolve) => setTimeout(resolve, 800));+ expect(useOnboardingWizardStore.getState().currentStep).toBe(6);+ expect(hired).toEqual(["tpl-maria", "tpl-max", "tpl-sam"]);+ expect(events("hire_step_continued")).toHaveLength(1);+ });++ it("still lets the user skip without hiring anyone", async () => {+ mockTeam(TEAM);+ const hired = mockHires();+ render(<HireStep />);++ await userEvent.click(+ await screen.findByRole("button", { name: "I'll add members later" }),+ );++ expect(useOnboardingWizardStore.getState().currentStep).toBe(6);+ expect(hired).toEqual([]);+ expect(events("hire_step_continued")).toEqual([+ ["hire_step_continued", { hired: 0, recommended: 2, via: "later" }],+ ]);+ });+});+describe("HireStep — while the job is still running", () => {it("shows skeleton cards and the way out, then the team when it lands", async () => {let ready = false;@@ -262,6 +612,7 @@ describe("HireStep — while the job is still running", () => {0,);expect(screen.getByText("Thinking about who you'd need…")).toBeDefined();+ expect(screen.getByTestId("hire-step-primary-pending")).toBeDefined();expect(screen.getByRole("button", { name: "I'll add members later" }),).toBeDefined();diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/HireStep/components/HireStepActions.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/HireStep/components/HireStepActions.tsxnew file mode 100644index 0000000000..d7b2498d80--- /dev/null+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/HireStep/components/HireStepActions.tsx@@ -0,0 +1,60 @@+"use client";++import { Button } from "@/components/atoms/Button/Button";+import { Skeleton } from "@/components/atoms/Skeleton/Skeleton";++interface Props {+ isPending: boolean;+ isHiringAll: boolean;+ isCardHiring: boolean;+ primaryLabel: string | null;+ secondaryLabel: string | null;+ onPrimary: () => void;+ onSecondary: () => void;+}++// The dark pill hires, the grey line moves on. The line is hidden, not+// disabled, mid-batch: a skip then would advance under a hire still landing.+export function HireStepActions({+ isPending,+ isHiringAll,+ isCardHiring,+ primaryLabel,+ secondaryLabel,+ onPrimary,+ onSecondary,+}: Props) {+ return (+ <div className="flex flex-col items-center gap-2">+ {isPending ? (+ <Skeleton+ className="h-10 w-56 rounded-xl"+ data-testid="hire-step-primary-pending"+ />+ ) : isHiringAll || primaryLabel ? (+ <Button+ type="button"+ size="small"+ onClick={onPrimary}+ disabled={isCardHiring}+ loading={isHiringAll}+ className="h-10 w-56 rounded-xl"+ >+ {isHiringAll ? "Hiring…" : primaryLabel}+ </Button>+ ) : null}+ {secondaryLabel && !isHiringAll ? (+ <Button+ type="button"+ variant="ghost"+ size="xs"+ onClick={onSecondary}+ disabled={isCardHiring}+ className="text-zinc-500 hover:text-zinc-900"+ >+ {secondaryLabel}+ </Button>+ ) : null}+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/HireStep/components/RecommendedExpertCard.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/HireStep/components/RecommendedExpertCard.tsxindex 3e5fbaffc1..d9dcb7f1f5 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/HireStep/components/RecommendedExpertCard.tsx+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/HireStep/components/RecommendedExpertCard.tsx@@ -14,8 +14,10 @@ interface Props {expert: RecommendedExpert;isHired: boolean;isHiringThis: boolean;+ isIncluded: boolean;disabled: boolean;onHire: () => void;+ onToggleIncluded: () => void;}export const EXPERT_CARD_CLASS =@@ -25,19 +27,53 @@ export function RecommendedExpertCard({expert,isHired,isHiringThis,+ isIncluded,disabled,onHire,+ onToggleIncluded,}: Props) {+ const isLeftOut = !isHired && !isIncluded;return (<divclassName={cn(EXPERT_CARD_CLASS,+ "relative",isHired ? "border-zinc-900" : "border-zinc-200",)}data-testid="hire-step-expert"data-hired={isHired || undefined}>- <div className="flex items-center gap-3">+ {isHired ? null : (+ // The wizard's own pick badge (SelectableCard), as a toggle: ticked+ // cards are what the step's primary action hires.+ <button+ type="button"+ aria-pressed={isIncluded}+ aria-label={`Include ${expert.name}`}+ disabled={disabled}+ onClick={onToggleIncluded}+ className="absolute right-2 top-2 flex size-7 items-center justify-center rounded-full disabled:cursor-not-allowed"+ >+ <span+ className={cn(+ "flex size-4 items-center justify-center rounded-full border transition-colors",+ isIncluded+ ? "border-zinc-900 bg-zinc-900"+ : "border-zinc-300 bg-white",+ )}+ >+ {isIncluded ? (+ <Icon icon={Tick02Icon} size={10} className="text-white" />+ ) : null}+ </span>+ </button>+ )}+ <div+ className={cn(+ "flex items-center gap-3 pr-6 transition-opacity",+ isLeftOut && "opacity-50",+ )}+ ><ExpertAvatarname={expert.name}avatarUrl={expert.avatar_url ?? null}@@ -56,7 +92,10 @@ export function RecommendedExpertCard({<Textvariant="body"tone="secondary"- className="line-clamp-2 text-pretty"+ className={cn(+ "line-clamp-2 text-pretty transition-opacity",+ isLeftOut && "opacity-50",+ )}>{expert.reason}</Text>diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/HireStep/helpers.ts b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/HireStep/helpers.tsindex d3dd9e56bf..4a53e22e77 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/HireStep/helpers.ts+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/HireStep/helpers.ts@@ -1,4 +1,5 @@import type { ExpertRecommendations } from "@/app/api/__generated__/models/expertRecommendations";+import type { RecommendedExpert } from "@/app/api/__generated__/models/recommendedExpert";export const HIRE_TITLE_LLM = "Based on what you told me, here's who I'd hire";export const HIRE_TITLE_FALLBACK =@@ -15,6 +16,15 @@ export const RECOMMENDATIONS_POLL_MS = 2_500;// the user on this step: past this ceiling the step shows what it has, or the// way out, rather than a skeleton forever.export const RECOMMENDATIONS_MAX_WAIT_MS = 20_000;+// Long enough to see the last card flip to Hired before the step moves on.+export const HIRE_ALL_ADVANCE_DELAY_MS = 500;++export type ContinueVia = "auto" | "continue" | "later";++export const SKIP_ACTION = {+ label: "I'll add members later",+ via: "later",+} as const;export function hireTitle(team: ExpertRecommendations | null,@@ -37,11 +47,92 @@ export function hireDiagnosis(return team?.diagnosis?.trim() || null;}-export function continueLabel(hiredCount: number): string {- return hiredCount > 0 ? "Next" : "I'll add members later";-}-export function raiseNote(role: string | null | undefined): string | null {if (!role) return null;return `Nobody on the roster covers ${role} yet — you can create your own ${role} once you're set up.`;}++interface ActionArgs {+ experts: RecommendedExpert[];+ hiredTemplateIds: string[];+ failedTemplateIds: string[];+ excludedTemplateIds: string[];+}++// The primary hires every unhired expert the user left in, and moves on once+// nobody is unhired; with everyone left out, the skip is the only action. The+// secondary always moves on without hiring more.+export function hireStepActions({+ experts,+ hiredTemplateIds,+ failedTemplateIds,+ excludedTemplateIds,+}: ActionArgs) {+ const unhired = experts.filter(+ (expert) => !hiredTemplateIds.includes(expert.template_id),+ );+ const batch = unhired.filter(+ (expert) => !excludedTemplateIds.includes(expert.template_id),+ );+ const hiredCount = experts.length - unhired.length;+ const isRetry =+ batch.length > 0 &&+ batch.every((expert) => failedTemplateIds.includes(expert.template_id));+ const skip =+ hiredCount > 0+ ? ({ label: "Continue", via: "continue" } as const)+ : SKIP_ACTION;++ if (unhired.length === 0) {+ return { primaryLabel: "Continue", batch, isRetry, skip: null };+ }+ return {+ primaryLabel: isRetry+ ? "Try again"+ : hireLabel(batch, unhired.length, hiredCount),+ batch,+ isRetry,+ skip,+ };+}++export function hireFailureToast(+ failed: RecommendedExpert[],+ batchSize: number,+ anyHired: boolean,+) {+ if (!anyHired && batchSize > 1 && failed.length === batchSize) {+ return {+ title: "Couldn't hire your team",+ description: "Something went wrong. Please try again.",+ };+ }+ return {+ title: `Couldn't hire ${failedNames(failed)}`,+ description: anyHired+ ? "Something went wrong. Try again, or continue without them."+ : "Something went wrong. Please try again.",+ };+}++function hireLabel(+ batch: RecommendedExpert[],+ unhiredCount: number,+ hiredCount: number,+) {+ if (batch.length === 0) return null;+ if (batch.length === 1) {+ return `Hire ${batch[0].name}${hiredCount > 0 ? " too" : ""}`;+ }+ if (batch.length < unhiredCount) return `Hire ${batch.length}`;+ return hiredCount > 0+ ? `Hire the other ${batch.length}`+ : `Hire all ${batch.length}`;+}++function failedNames(failed: RecommendedExpert[]) {+ const names = failed.map((expert) => expert.name);+ if (names.length > 3) return `${names.length} experts`;+ if (names.length === 1) return names[0];+ return `${names.slice(0, -1).join(", ")} and ${names[names.length - 1]}`;+}diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/HireStep/useHireAll.ts b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/HireStep/useHireAll.tsnew file mode 100644index 0000000000..4869ec005e--- /dev/null+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/HireStep/useHireAll.ts@@ -0,0 +1,101 @@+import { useHireExpert } from "@/app/api/__generated__/endpoints/experts/experts";+import type { RecommendedExpert } from "@/app/api/__generated__/models/recommendedExpert";+import { toast } from "@/components/molecules/Toast/use-toast";+import { trackFunnel } from "@/services/experts/experts-analytics";+import { invalidateExpertRosterQueries } from "@/services/experts/invalidate-experts";+import { trackBrainDump } from "@/services/onboarding/brain-dump-analytics";+import { useQueryClient } from "@tanstack/react-query";+import { useEffect, useRef, useState } from "react";+import { useOnboardingWizardStore } from "../../store";+import { HIRE_ALL_ADVANCE_DELAY_MS, hireFailureToast } from "./helpers";++interface Args {+ experts: RecommendedExpert[];+ onTeamHired: () => void;+}++// The step's primary action: hires a batch in parallel, lets each card flip+// as its own request lands, and moves on only when every hire succeeded.+export function useHireAll({ experts, onTeamHired }: Args) {+ const markHired = useOnboardingWizardStore((s) => s.markHired);+ const setStepBusy = useOnboardingWizardStore((s) => s.setStepBusy);+ const queryClient = useQueryClient();+ const { mutateAsync: hireExpert } = useHireExpert();+ const [isHiringAll, setIsHiringAll] = useState(false);+ const [hiringTemplateIds, setHiringTemplateIds] = useState<string[]>([]);+ const [failedTemplateIds, setFailedTemplateIds] = useState<string[]>([]);+ const advanceTimer = useRef<ReturnType<typeof setTimeout>>(undefined);+ const isMounted = useRef(false);++ // Busy through the advance beat too: Back then would land the timer's+ // nextStep on the previous step.+ useEffect(() => {+ setStepBusy(isHiringAll);+ return () => setStepBusy(false);+ }, [isHiringAll, setStepBusy]);++ useEffect(() => {+ isMounted.current = true;+ return () => {+ isMounted.current = false;+ clearTimeout(advanceTimer.current);+ };+ }, []);++ async function hireAll(batch: RecommendedExpert[], isRetry: boolean) {+ trackBrainDump("hire_all_clicked", {+ count: batch.length,+ already_hired: hiredCount(experts),+ recommended: experts.length,+ retry: isRetry,+ });+ setIsHiringAll(true);+ setFailedTemplateIds([]);+ setHiringTemplateIds(batch.map((expert) => expert.template_id));++ const results = await Promise.allSettled(batch.map(hireOne));+ const failed = batch.filter((_, i) => results[i].status === "rejected");+ // Best effort, as for a card hire: the roster is not on screen here.+ await invalidateExpertRosterQueries(queryClient).catch(() => undefined);+ // Browser navigation can unmount the step mid-batch; the wizard store+ // outlives it, so a stale batch must not drive the wizard.+ if (!isMounted.current) return;++ if (failed.length === 0) {+ advanceTimer.current = setTimeout(onTeamHired, HIRE_ALL_ADVANCE_DELAY_MS);+ return;+ }+ setFailedTemplateIds(failed.map((expert) => expert.template_id));+ setIsHiringAll(false);+ toast({+ ...hireFailureToast(failed, batch.length, hiredCount(experts) > 0),+ variant: "destructive",+ });+ }++ async function hireOne(expert: RecommendedExpert) {+ trackFunnel("hire_started", {+ template_id: expert.template_id,+ surface: "onboarding",+ });+ try {+ await hireExpert({+ data: { template_id: expert.template_id, surface: "onboarding" },+ });+ markHired(expert.template_id);+ } finally {+ setHiringTemplateIds((ids) =>+ ids.filter((id) => id !== expert.template_id),+ );+ }+ }++ return { isHiringAll, hiringTemplateIds, failedTemplateIds, hireAll };+}++// Read from the store, not the render: the batch's own hires land after the+// closure was made.+function hiredCount(experts: RecommendedExpert[]) {+ const hired = useOnboardingWizardStore.getState().hiredTemplateIds;+ return experts.filter((expert) => hired.includes(expert.template_id)).length;+}diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/HireStep/useHireStep.ts b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/HireStep/useHireStep.tsindex 15c235af11..432542c270 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/HireStep/useHireStep.ts+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/HireStep/useHireStep.ts@@ -10,9 +10,13 @@ import { useQueryClient } from "@tanstack/react-query";import { useEffect, useRef, useState } from "react";import { useOnboardingWizardStore } from "../../store";import {+ type ContinueVia,+ hireStepActions,RECOMMENDATIONS_MAX_WAIT_MS,RECOMMENDATIONS_POLL_MS,+ SKIP_ACTION,} from "./helpers";+import { useHireAll } from "./useHireAll";export function useHireStep() {const nextStep = useOnboardingWizardStore((s) => s.nextStep);@@ -21,6 +25,7 @@ export function useHireStep() {const queryClient = useQueryClient();const [hiringTemplateId, setHiringTemplateId] = useState<string | null>(null);const [gaveUpWaiting, setGaveUpWaiting] = useState(false);+ const [excludedTemplateIds, setExcludedTemplateIds] = useState<string[]>([]);const reportedIds = useRef(new Set<string>());const waitStartedAt = useRef<number | null>(null);@@ -42,6 +47,16 @@ export function useHireStep() {const isPending = !gaveUpWaiting && (!answered || !isReadyPerServer);const team: ExpertRecommendations | null =data?.status === 200 ? (data.data.team ?? null) : null;+ const experts = team?.experts ?? [];+ const { isHiringAll, hiringTemplateIds, failedTemplateIds, hireAll } =+ useHireAll({ experts, onTeamHired: () => handleContinue("auto") });+ const actions = hireStepActions({+ experts,+ hiredTemplateIds,+ failedTemplateIds,+ excludedTemplateIds,+ });+ const skip = isPending ? SKIP_ACTION : actions.skip;// The ceiling is absolute from the first pending render: a pending flip// (transient error, then a fresh poll) re-arms the timer with what is left@@ -75,7 +90,7 @@ export function useHireStep() {const { mutateAsync: hireExpert } = useHireExpert();async function hire(expert: RecommendedExpert, position: number) {- if (hiringTemplateId !== null) return;+ if (hiringTemplateId !== null || isHiringAll) return;trackBrainDump("expert_recommendation_clicked", {template_id: expert.template_id,position,@@ -104,10 +119,30 @@ export function useHireStep() {}}- function handleContinue() {+ function toggleIncluded(templateId: string) {+ setExcludedTemplateIds((ids) =>+ ids.includes(templateId)+ ? ids.filter((id) => id !== templateId)+ : [...ids, templateId],+ );+ }++ function handlePrimary() {+ if (actions.batch.length > 0) void hireAll(actions.batch, actions.isRetry);+ else handleContinue("continue");+ }++ function handleSecondary() {+ if (skip) handleContinue(skip.via);+ }++ function handleContinue(via: ContinueVia) {trackBrainDump("hire_step_continued", {- hired: hiredTemplateIds.length,- recommended: team?.experts?.length ?? 0,+ // From the store: the auto-advance runs in a closure older than the+ // batch's hires.+ hired: useOnboardingWizardStore.getState().hiredTemplateIds.length,+ recommended: experts.length,+ via,});nextStep();}@@ -115,11 +150,20 @@ export function useHireStep() {return {team,isPending,- experts: team?.experts ?? [],+ experts,raiseRole: team?.raise_suggestion?.role ?? null,hiredTemplateIds,- hiringTemplateId,+ isHiringAll,+ isCardHiring: hiringTemplateId !== null,+ isHiringCard: (templateId: string) =>+ hiringTemplateId === templateId || hiringTemplateIds.includes(templateId),+ isIncluded: (templateId: string) =>+ !excludedTemplateIds.includes(templateId),+ primaryLabel: actions.primaryLabel,+ secondaryLabel: skip?.label ?? null,hire,- handleContinue,+ toggleIncluded,+ handlePrimary,+ handleSecondary,};}diff --git a/autogpt_platform/frontend/src/services/analytics/__tests__/posthog-events.test.ts b/autogpt_platform/frontend/src/services/analytics/__tests__/posthog-events.test.tsindex 58cf083660..69a5ba54c0 100644--- a/autogpt_platform/frontend/src/services/analytics/__tests__/posthog-events.test.ts+++ b/autogpt_platform/frontend/src/services/analytics/__tests__/posthog-events.test.ts@@ -36,6 +36,7 @@ const LIVE_EVENT_NAMES = ["expert_thread_created","experts_section_viewed","feature_flag_mismatched",+ "hire_all_clicked","hire_flow_abandoned","hire_started","hire_step_continued",diff --git a/autogpt_platform/frontend/src/services/analytics/posthog-events.ts b/autogpt_platform/frontend/src/services/analytics/posthog-events.tsindex f67ab7df41..2e9c40eda7 100644--- a/autogpt_platform/frontend/src/services/analytics/posthog-events.ts+++ b/autogpt_platform/frontend/src/services/analytics/posthog-events.ts@@ -88,9 +88,12 @@ export const BrainDumpEvent = {// through, or skip straight to the builder.EXPERT_RECOMMENDED: "expert_recommended",EXPERT_RECOMMENDATION_CLICKED: "expert_recommendation_clicked",+ // The hire step's primary was clicked to hire every expert still unhired+ // (or, with `retry`, the ones a batch failed to hire).+ HIRE_ALL_CLICKED: "hire_all_clicked",// The wizard's hire step was left, with how many of the proposed experts// were hired, so the funnel can tell "hired a team" from "skipped past it".- // The hires themselves are the backend's `expert_hired`.+ // `via` says how. The hires themselves are the backend's `expert_hired`.HIRE_STEP_CONTINUED: "hire_step_continued",} as const;diff --git a/docs/engineering/tracking-plan.md b/docs/engineering/tracking-plan.mdindex ddc09c791c..6a58361d06 100644--- a/docs/engineering/tracking-plan.md+++ b/docs/engineering/tracking-plan.md@@ -249,7 +249,8 @@ retried on the next tour visit in that session.| `later_dump_completed` | browser | live | — | A brain dump sent later from the composer. || `expert_recommended` | browser | live | `template_id`, `position`, `team_source` | A recommended expert card is shown. || `expert_recommendation_clicked` | browser | live | `template_id`, `position` | A recommended expert card is clicked. |-| `hire_step_continued` | browser | live | `hired`, `recommended` | The hire step is left. |+| `hire_all_clicked` | browser | live | `count` (experts this click hires), `already_hired`, `recommended`, `retry` | The hire step's primary button is clicked to hire every expert still unhired, or with `retry` the ones a batch failed to hire. |+| `hire_step_continued` | browser | live | `hired`, `recommended`, `via` (`auto` after a full batch, `continue`, `later` for "I'll add members later") | The hire step is left. || `tab_intro_shown` | browser | live | `tab` | A tab intro card is shown. || `tab_intro_cta_clicked` | browser | live | `tab`, `cta` | Its primary CTA is used. || `tab_intro_dismissed` | browser | live | `tab` | It is dismissed any other way. |@@ -285,7 +286,7 @@ retried on the next tour visit in that session.| `voice_mode_error` | browser | live | `stage` | The VAD, synthesis or send failed. || `experts_section_viewed` | browser | live | — | The marketplace experts shelf renders with results. || `expert_profile_opened` | browser | live | `template_id` | An expert profile page opens. |-| `hire_started` | browser | live | `template_id`, `surface` (`onboarding`, `expert_page`) | A hire button is clicked. |+| `hire_started` | browser | live | `template_id`, `surface` (`onboarding`, `expert_page`) | A hire button is clicked, or once per expert of the hire step's batch. || `hire_flow_abandoned` | browser | live | `template_id`, `stage` | The hire dialog is closed before hiring. || `expert_hired` | backend | live | `expert_id`, `template_id`, `name`, `failed_preloads_count`, `surface` (`onboarding`, `expert_page`, `copilot`; unset for other API callers) | An expert is hired or an archived one revived, from any surface (`experts_db.hire_expert`). Sent once the hire's background setup settles (`_run_hire_setup`), so `failed_preloads_count` is known; a revival with nothing to set up sends it at once. An idempotent re-hire of an active expert does not fire. || `hire_failed` | backend | live | `template_id`, `failed_preloads_count` | Hiring raised. |