Skip to content

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.

fix(frontend/marketplace): gate the expert page's Coming soon on the hire-experts flag (#14445)

Ubbe014ce105f7b7
diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/experts/[expertId]/components/ExpertComingSoonLabel.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/experts/[expertId]/components/ExpertComingSoonLabel.tsx
index 65e53e1637..cde40884cb 100644
--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/experts/[expertId]/components/ExpertComingSoonLabel.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/experts/[expertId]/components/ExpertComingSoonLabel.tsx
@@ -1,5 +1,5 @@
-/** Hiring is not open yet, so the header shows a label where the hire
- * action will go. Every visitor sees it, signed in or not. */
+/** Shown where the hire action goes while the ``hire-experts`` flag is off
+ * for this viewer: the profile stays public, the hiring does not. */
export function ExpertComingSoonLabel() {
return (
<span className="inline-flex h-9 items-center rounded-full border border-zinc-200 bg-white px-3.5 text-sm font-medium text-zinc-500">
diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/experts/[expertId]/components/ExpertHireActions.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/experts/[expertId]/components/ExpertHireActions.tsx
new file mode 100644
index 0000000000..08e80400d3
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/experts/[expertId]/components/ExpertHireActions.tsx
@@ -0,0 +1,78 @@
+import { Expert } from "@/app/api/__generated__/models/expert";
+import { Badge } from "@/components/atoms/Badge/Badge";
+import { Button } from "@/components/atoms/Button/Button";
+import { Icon } from "@/components/atoms/Icon/Icon";
+import { CheckmarkCircle02Icon } from "@hugeicons/core-free-icons";
+
+// Sized and shaped like the small button beside it so the pair reads as one row.
+const STATUS_CLASS = "h-9 rounded-full px-3.5 text-sm";
+
+// A white, hairline-bordered secondary so the button sits quietly next to
+// the status badge instead of reading as a solid grey slab.
+const SECONDARY_CLASS =
+ "border-zinc-200 bg-white shadow-[0_1px_2px_rgba(16,24,40,0.05)] hover:border-zinc-300 hover:bg-zinc-50";
+
+interface Props {
+ expert: Expert;
+ hiredExpert: Expert | null;
+ isLoggedIn: boolean;
+ isHiring: boolean;
+ onHire: () => void;
+}
+
+/** The page's one call to action, sitting in the header beside the name.
+ * Signed-out visitors get a sign-up prompt that brings them back here. */
+export function ExpertHireActions({
+ expert,
+ hiredExpert,
+ isLoggedIn,
+ isHiring,
+ onHire,
+}: Props) {
+ if (!isLoggedIn) {
+ const next = encodeURIComponent(`/marketplace/experts/${expert.id}`);
+ return (
+ <Button
+ as="NextLink"
+ href={`/signup?next=${next}`}
+ variant="primary"
+ size="small"
+ className="w-full sm:w-auto"
+ >
+ Get started
+ </Button>
+ );
+ }
+
+ if (hiredExpert) {
+ return (
+ <div className="flex flex-wrap items-center gap-3">
+ <Badge variant="success" className={STATUS_CLASS}>
+ <Icon icon={CheckmarkCircle02Icon} size={16} />
+ On your team
+ </Badge>
+ <Button
+ as="NextLink"
+ href={`/copilot?expertId=${hiredExpert.id}`}
+ variant="secondary"
+ size="small"
+ className={SECONDARY_CLASS}
+ >
+ {`Chat with ${expert.name}`}
+ </Button>
+ </div>
+ );
+ }
+
+ return (
+ <Button
+ variant="primary"
+ size="small"
+ onClick={onHire}
+ loading={isHiring}
+ className="w-full sm:w-auto"
+ >
+ {`Hire ${expert.name}`}
+ </Button>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/experts/[expertId]/page.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/experts/[expertId]/page.tsx
index 7e2520c270..e81ebe7609 100644
--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/experts/[expertId]/page.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/experts/[expertId]/page.tsx
@@ -3,16 +3,21 @@
import { getExpertAccent } from "@/app/(platform)/marketplace/components/ExpertsSection/helpers";
import { Icon } from "@/components/atoms/Icon/Icon";
import { Skeleton } from "@/components/atoms/Skeleton/Skeleton";
+import { Dialog } from "@/components/molecules/Dialog/Dialog";
import { ErrorCard } from "@/components/molecules/ErrorCard/ErrorCard";
+import { VoicePicker } from "@/components/organisms/VoicePicker/VoicePicker";
import { ArrowLeft02Icon } from "@hugeicons/core-free-icons";
import Link from "next/link";
import { notFound, useParams } from "next/navigation";
+import { ReactNode } from "react";
import { ExpertAbout } from "./components/ExpertAbout";
import { ExpertComingSoonLabel } from "./components/ExpertComingSoonLabel";
+import { ExpertHireActions } from "./components/ExpertHireActions";
import { ExpertPageHeader } from "./components/ExpertPageHeader";
import { ExpertSkills } from "./components/ExpertSkills";
import { ExpertWorkflowList } from "./components/ExpertWorkflowList";
import { useExpertPage } from "./useExpertPage";
+import { useHireFlow } from "./useHireFlow";
const MAIN_CLASS =
"mx-auto flex w-full max-w-[760px] flex-col px-6 pb-24 pt-8 md:px-8";
@@ -31,7 +36,25 @@ function BackToMarketplaceLink() {
export default function MarketplaceExpertPage() {
const { expertId } = useParams<{ expertId: string }>();
- const { expert, isLoading, isError, refetch } = useExpertPage({ expertId });
+ const {
+ expert,
+ hiredExpert,
+ isLoggedIn,
+ isHiringOpen,
+ isActionReady,
+ isLoading,
+ isError,
+ refetch,
+ } = useExpertPage({ expertId });
+ const {
+ hire,
+ isHiring,
+ hireResult,
+ pickVoice,
+ skipVoice,
+ dismissVoicePick,
+ isSavingVoice,
+ } = useHireFlow(expert);
if (isLoading) {
return (
@@ -74,14 +97,25 @@ export default function MarketplaceExpertPage() {
const accent = getExpertAccent(expert.role);
+ let actions: ReactNode = <Skeleton className="h-9 w-28 rounded-full" />;
+ if (isActionReady) {
+ actions = isHiringOpen ? (
+ <ExpertHireActions
+ expert={expert}
+ hiredExpert={hiredExpert}
+ isLoggedIn={isLoggedIn}
+ isHiring={isHiring}
+ onHire={hire}
+ />
+ ) : (
+ <ExpertComingSoonLabel />
+ );
+ }
+
return (
<main className={MAIN_CLASS}>
<BackToMarketplaceLink />
- <ExpertPageHeader
- expert={expert}
- accent={accent}
- actions={<ExpertComingSoonLabel />}
- />
+ <ExpertPageHeader expert={expert} accent={accent} actions={actions} />
<div className="mt-8 flex flex-col gap-10 border-t border-zinc-200 pt-8">
<ExpertAbout key={expert.id} text={expert.bio || expert.identity} />
<ExpertSkills skills={expert.skills ?? []} accent={accent} />
@@ -91,6 +125,30 @@ export default function MarketplaceExpertPage() {
accent={accent}
/>
</div>
+
+ {/* The voice pick follows a successful hire when the persona ships
+ writing samples; dismissing it still celebrates the hire. */}
+ <Dialog
+ styling={{ width: "640px" }}
+ controlled={{
+ isOpen: hireResult !== null,
+ set: (open) => {
+ if (!open) dismissVoicePick();
+ },
+ }}
+ >
+ <Dialog.Content>
+ {hireResult ? (
+ <VoicePicker
+ name={hireResult.expert.name}
+ samples={expert.voice_samples ?? []}
+ onPick={pickVoice}
+ onSkip={skipVoice}
+ isSubmitting={isSavingVoice}
+ />
+ ) : null}
+ </Dialog.Content>
+ </Dialog>
</main>
);
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/experts/[expertId]/useExpertPage.ts b/autogpt_platform/frontend/src/app/(platform)/marketplace/experts/[expertId]/useExpertPage.ts
index 4b75e9754f..6239aea004 100644
--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/experts/[expertId]/useExpertPage.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/experts/[expertId]/useExpertPage.ts
@@ -1,23 +1,49 @@
-import { useListExpertTemplates } from "@/app/api/__generated__/endpoints/experts/experts";
+import {
+ useListExperts,
+ useListExpertTemplates,
+} from "@/app/api/__generated__/endpoints/experts/experts";
import { Expert } from "@/app/api/__generated__/models/expert";
+import { useAuth } from "@/lib/auth/hooks/useAuth";
+import { Flag, useFlagStatus } from "@/services/feature-flags/use-get-flag";
interface Args {
expertId: string;
}
-/** The template behind a marketplace expert page. Templates are public, so
- * every visitor sees the same profile; hiring is not open yet. */
+/** The template behind a marketplace expert page, plus whether this viewer
+ * can hire it. Templates are public, so the profile loads for everyone; the
+ * hired roster and the hire itself need a session and the experts flag.
+ * With the flag off the header shows its coming-soon label instead. */
export function useExpertPage({ expertId }: Args) {
+ const { isLoggedIn, isUserLoading } = useAuth();
+ const { enabled, ready } = useFlagStatus(Flag.HIRE_EXPERTS);
+ const isHiringOpen = Boolean(enabled);
+ const canHire = isLoggedIn && isHiringOpen;
+
const templatesQuery = useListExpertTemplates({
query: { select: (x) => x.data as Expert[] },
});
+ const expertsQuery = useListExperts({
+ query: { select: (x) => x.data as Expert[], enabled: canHire },
+ });
const expert =
(templatesQuery.data ?? []).find((template) => template.id === expertId) ??
null;
+ const hiredExpert =
+ (expertsQuery.data ?? []).find(
+ (hired) => !hired.is_archived && hired.source_template_id === expertId,
+ ) ?? null;
return {
expert,
+ hiredExpert,
+ isLoggedIn,
+ isHiringOpen,
+ // Which header action to show is only decided once LaunchDarkly has
+ // answered: rendering "Coming soon" first would flash the wrong state at
+ // the users who do have hiring.
+ isActionReady: !isUserLoading && ready,
isLoading: templatesQuery.isLoading,
isError: templatesQuery.isError,
refetch: templatesQuery.refetch,
diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/experts/[expertId]/useHireFlow.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/experts/[expertId]/useHireFlow.tsx
new file mode 100644
index 0000000000..a8456f6afa
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/experts/[expertId]/useHireFlow.tsx
@@ -0,0 +1,136 @@
+import {
+ getGetExpertQueryKey,
+ useHireExpert,
+ useUpdateExpertSoul,
+} from "@/app/api/__generated__/endpoints/experts/experts";
+import { Expert } from "@/app/api/__generated__/models/expert";
+import { HireResult } from "@/app/api/__generated__/models/hireResult";
+import { Button } from "@/components/atoms/Button/Button";
+import { toast } from "@/components/molecules/Toast/use-toast";
+import {
+ buildVoicePreferences,
+ type VoicePickResult,
+} from "@/components/organisms/VoicePicker/helpers";
+import { invalidateExpertRosterQueries } from "@/services/experts/invalidate-experts";
+import { useQueryClient } from "@tanstack/react-query";
+import { useRouter } from "next/navigation";
+import { useRef, useState } from "react";
+
+function celebrate(result: HireResult) {
+ toast({
+ title: `${result.expert.name} joined your team`,
+ description: result.failed_preloads.length
+ ? `Couldn't attach: ${result.failed_preloads.join(", ")}`
+ : undefined,
+ variant: "success",
+ action: (
+ <Button as="NextLink" href="/team" variant="ghost" size="small">
+ View team
+ </Button>
+ ),
+ });
+}
+
+/** Hiring from the expert page: hire the template, offer a voice pick when
+ * the persona ships writing samples, then celebrate and hand the user to
+ * the expert's first thread. */
+export function useHireFlow(expert: Expert | null) {
+ const queryClient = useQueryClient();
+ const router = useRouter();
+ // Set once a hire succeeds for a persona with writing samples: it opens
+ // the voice pick before the hire is celebrated.
+ const [hireResult, setHireResult] = useState<HireResult | null>(null);
+ const pendingCelebrationRef = useRef<HireResult | null>(null);
+
+ const { mutateAsync: hireExpert, isPending: isHiring } = useHireExpert();
+ const { mutateAsync: updateSoul, isPending: isSavingVoice } =
+ useUpdateExpertSoul();
+
+ function finish() {
+ const completedHire = pendingCelebrationRef.current;
+ pendingCelebrationRef.current = null;
+ setHireResult(null);
+ if (completedHire) {
+ celebrate(completedHire);
+ // Hiring isn't installing: hand the user straight to the expert's
+ // thread with kickoff=1 so it introduces itself and starts its job.
+ router.push(`/copilot?expertId=${completedHire.expert.id}&kickoff=1`);
+ }
+ }
+
+ async function hire() {
+ if (!expert || !expert.is_template) return;
+ try {
+ const response = await hireExpert({ data: { template_id: expert.id } });
+ const result = response.data as HireResult;
+ await invalidateExpertRosterQueries(queryClient);
+ pendingCelebrationRef.current = result;
+ if ((expert.voice_samples ?? []).length > 0) {
+ setHireResult(result);
+ return;
+ }
+ finish();
+ } catch {
+ toast({
+ title: `Couldn't hire ${expert.name}`,
+ description: "Something went wrong. Please try again.",
+ variant: "destructive",
+ });
+ }
+ }
+
+ async function pickVoice(result: VoicePickResult) {
+ if (!hireResult || !expert) return;
+ const hired = hireResult.expert;
+ const voicePreferences = buildVoicePreferences(
+ result,
+ expert.voice_samples ?? [],
+ );
+ // Nothing storable (missing sample, blank custom text): keep the hired
+ // expert's existing voice instead of blanking it with an empty PATCH.
+ if (voicePreferences === null) {
+ finish();
+ return;
+ }
+ try {
+ await updateSoul({
+ expertId: hired.id,
+ data: {
+ name: hired.name,
+ identity: hired.identity,
+ voice_preferences: voicePreferences,
+ boundaries: hired.boundaries,
+ },
+ });
+ // The hire-time refetch cached the pre-voice expert as fresh; without
+ // this, a Soul edit within the stale window would silently write that
+ // old description back over the chosen voice.
+ await Promise.all([
+ invalidateExpertRosterQueries(queryClient),
+ queryClient.invalidateQueries({
+ queryKey: getGetExpertQueryKey(hired.id),
+ }),
+ ]);
+ } catch {
+ // The hire itself succeeded; keep the picker open so the choice can be
+ // retried, and point at the Soul editor as the fallback.
+ toast({
+ title: "Couldn't save the voice",
+ description: "You can set it later in the Soul editor.",
+ variant: "destructive",
+ });
+ return;
+ }
+ finish();
+ }
+
+ return {
+ hire,
+ isHiring,
+ hireResult,
+ pickVoice,
+ skipVoice: finish,
+ dismissVoicePick: finish,
+ isSavingVoice,
+ };
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/experts/__tests__/expert-page.test.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/experts/__tests__/expert-page.test.tsx
index d65938cd57..f0fd147b8f 100644
--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/experts/__tests__/expert-page.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/experts/__tests__/expert-page.test.tsx
@@ -1,19 +1,31 @@
-import { getListExpertTemplatesMockHandler } from "@/app/api/__generated__/endpoints/experts/experts.msw";
+import {
+ getHireExpertMockHandler,
+ getListExpertsMockHandler,
+ getListExpertTemplatesMockHandler,
+ getUpdateExpertSoulMockHandler,
+} from "@/app/api/__generated__/endpoints/experts/experts.msw";
import { Expert } from "@/app/api/__generated__/models/expert";
+import { Toaster } from "@/components/molecules/Toast/toaster";
import { server } from "@/mocks/mock-server";
-import { render, screen } from "@/tests/integrations/test-utils";
+import { render, screen, waitFor } from "@/tests/integrations/test-utils";
+import userEvent from "@testing-library/user-event";
+import { HttpResponse, http } from "msw";
import { beforeEach, describe, expect, test, vi } from "vitest";
import MarketplaceExpertPage from "../[expertId]/page";
const mockUseAuth = vi.hoisted(() => vi.fn());
+const mockRouterPush = vi.hoisted(() => vi.fn());
const mockParams = vi.hoisted(() => ({ expertId: "template-maria" }));
+const flagStatusMock = vi.hoisted(() =>
+ vi.fn(() => ({ enabled: true, ready: true })),
+);
vi.mock("next/navigation", () => ({
useRouter: () => ({
back: vi.fn(),
forward: vi.fn(),
prefetch: vi.fn(),
- push: vi.fn(),
+ push: mockRouterPush,
refresh: vi.fn(),
replace: vi.fn(),
}),
@@ -29,6 +41,20 @@ vi.mock("@/lib/auth/hooks/useAuth", () => ({
useAuth: mockUseAuth,
}));
+vi.mock("@/services/feature-flags/use-get-flag", async (importOriginal) => {
+ const actual =
+ await importOriginal<
+ typeof import("@/services/feature-flags/use-get-flag")
+ >();
+ return {
+ ...actual,
+ useFlagStatus: (flag: string) =>
+ flag === "hire-experts"
+ ? flagStatusMock()
+ : actual.useFlagStatus(flag as never),
+ };
+});
+
const mariaTemplate: Expert = {
id: "template-maria",
name: "Maria",
@@ -56,15 +82,49 @@ const mariaTemplate: Expert = {
],
};
+const hiredMaria: Expert = {
+ ...mariaTemplate,
+ id: "expert-maria",
+ is_template: false,
+ source_template_id: "template-maria",
+};
+
+const mariaWithSamples: Expert = {
+ ...mariaTemplate,
+ voice_samples: [
+ { label: "Punchy and bold", text: "Stop guessing what your buyers want." },
+ {
+ label: "Warm and story-led",
+ text: "Every campaign starts with a person, not a product.",
+ },
+ ],
+};
+
+function renderPage() {
+ return render(
+ <>
+ <MarketplaceExpertPage />
+ <Toaster />
+ </>,
+ );
+}
+
describe("Marketplace expert page", () => {
beforeEach(() => {
+ mockRouterPush.mockReset();
mockParams.expertId = "template-maria";
+ flagStatusMock.mockReturnValue({ enabled: true, ready: true });
mockUseAuth.mockReturnValue({ user: { id: "user-1" }, isLoggedIn: true });
- server.use(getListExpertTemplatesMockHandler([mariaTemplate]));
});
- test("shows the profile with a coming-soon label and no hire action", async () => {
- render(<MarketplaceExpertPage />);
+ test("shows the profile and hires from the page", async () => {
+ server.use(
+ getListExpertTemplatesMockHandler([mariaTemplate]),
+ getListExpertsMockHandler([]),
+ getHireExpertMockHandler({ expert: hiredMaria, failed_preloads: [] }),
+ );
+
+ renderPage();
expect(
await screen.findByRole("heading", { level: 1, name: "Maria" }),
@@ -72,26 +132,216 @@ describe("Marketplace expert page", () => {
expect(screen.getByText("Grows your brand while you sleep")).toBeDefined();
expect(screen.getByText("Content strategy")).toBeDefined();
expect(screen.getByText("LinkedIn Post Generator")).toBeDefined();
- expect(screen.getByText("Coming soon")).toBeDefined();
- expect(screen.queryByRole("button", { name: /hire/i })).toBeNull();
- expect(screen.queryByRole("link", { name: "Get started" })).toBeNull();
expect(
screen
.getByRole("link", { name: "Back to marketplace" })
.getAttribute("href"),
).toBe("/marketplace#experts");
+
+ await userEvent.click(screen.getByRole("button", { name: "Hire Maria" }));
+
+ expect(await screen.findByText("Maria joined your team")).toBeDefined();
+ expect(mockRouterPush).toHaveBeenCalledWith(
+ `/copilot?expertId=${hiredMaria.id}&kickoff=1`,
+ );
});
- test("shows the same profile and label to signed-out visitors", async () => {
+ test("shows the on-your-team state with a way into the chat", async () => {
+ server.use(
+ getListExpertTemplatesMockHandler([mariaTemplate]),
+ getListExpertsMockHandler([hiredMaria]),
+ );
+
+ renderPage();
+
+ expect(await screen.findByText("On your team")).toBeDefined();
+ expect(
+ screen
+ .getByRole("link", { name: "Chat with Maria" })
+ .getAttribute("href"),
+ ).toBe("/copilot?expertId=expert-maria");
+ expect(screen.queryByRole("button", { name: "Hire Maria" })).toBeNull();
+ });
+
+ test("captures a voice pick as a plain-text soul PATCH after hire", async () => {
+ let savedVoice = "";
+ server.use(
+ getListExpertTemplatesMockHandler([mariaWithSamples]),
+ getListExpertsMockHandler([]),
+ getHireExpertMockHandler({ expert: hiredMaria, failed_preloads: [] }),
+ getUpdateExpertSoulMockHandler(async (info) => {
+ const body = (await info.request.json()) as {
+ voice_preferences: string;
+ };
+ savedVoice = body.voice_preferences;
+ return { ...hiredMaria, voice_preferences: body.voice_preferences };
+ }),
+ );
+
+ renderPage();
+
+ await userEvent.click(
+ await screen.findByRole("button", { name: "Hire Maria" }),
+ );
+
+ expect(await screen.findByText("How should Maria write?")).toBeDefined();
+ await userEvent.click(await screen.findByText("Punchy and bold"));
+ await userEvent.click(
+ screen.getByRole("button", { name: "Use this voice" }),
+ );
+
+ expect(await screen.findByText("Maria joined your team")).toBeDefined();
+ expect(savedVoice).toContain("Preferred writing style: Punchy and bold.");
+ expect(savedVoice.startsWith("{")).toBe(false);
+ });
+
+ test("skips the voice pick without patching the soul", async () => {
+ let soulPatched = false;
+ server.use(
+ getListExpertTemplatesMockHandler([mariaWithSamples]),
+ getListExpertsMockHandler([]),
+ getHireExpertMockHandler({ expert: hiredMaria, failed_preloads: [] }),
+ getUpdateExpertSoulMockHandler(() => {
+ soulPatched = true;
+ return hiredMaria;
+ }),
+ );
+
+ renderPage();
+
+ await userEvent.click(
+ await screen.findByRole("button", { name: "Hire Maria" }),
+ );
+ expect(await screen.findByText("How should Maria write?")).toBeDefined();
+ await userEvent.click(
+ await screen.findByRole("button", { name: "Skip for now" }),
+ );
+
+ expect(await screen.findByText("Maria joined your team")).toBeDefined();
+ expect(soulPatched).toBe(false);
+ });
+
+ test("retries a failed voice PATCH, then celebrates and closes", async () => {
+ let patchAttempts = 0;
+ server.use(
+ getListExpertTemplatesMockHandler([mariaWithSamples]),
+ getListExpertsMockHandler([]),
+ getHireExpertMockHandler({ expert: hiredMaria, failed_preloads: [] }),
+ http.patch("/api/proxy/api/experts/:expertId/soul", () => {
+ patchAttempts += 1;
+ return patchAttempts === 1
+ ? HttpResponse.json({ detail: [] }, { status: 422 })
+ : HttpResponse.json(hiredMaria);
+ }),
+ );
+
+ renderPage();
+
+ await userEvent.click(
+ await screen.findByRole("button", { name: "Hire Maria" }),
+ );
+ expect(await screen.findByText("How should Maria write?")).toBeDefined();
+ await userEvent.click(await screen.findByText("Punchy and bold"));
+ await userEvent.click(
+ screen.getByRole("button", { name: "Use this voice" }),
+ );
+
+ expect(await screen.findByText("Couldn't save the voice")).toBeDefined();
+ expect(screen.getByText("How should Maria write?")).toBeDefined();
+
+ await userEvent.click(
+ screen.getByRole("button", { name: "Use this voice" }),
+ );
+
+ expect(await screen.findByText("Maria joined your team")).toBeDefined();
+ await waitFor(() =>
+ expect(screen.queryByText("How should Maria write?")).toBeNull(),
+ );
+ expect(patchAttempts).toBe(2);
+ });
+
+ test("celebrates exactly once when the voice pick is dismissed", async () => {
+ server.use(
+ getListExpertTemplatesMockHandler([mariaWithSamples]),
+ getListExpertsMockHandler([]),
+ getHireExpertMockHandler({ expert: hiredMaria, failed_preloads: [] }),
+ );
+
+ renderPage();
+
+ await userEvent.click(
+ await screen.findByRole("button", { name: "Hire Maria" }),
+ );
+ expect(await screen.findByText("How should Maria write?")).toBeDefined();
+
+ await userEvent.keyboard("{Escape}");
+
+ expect(await screen.findByText("Maria joined your team")).toBeDefined();
+ await waitFor(() =>
+ expect(screen.queryByText("How should Maria write?")).toBeNull(),
+ );
+ expect(screen.getAllByText("Maria joined your team")).toHaveLength(1);
+ });
+
+ test("shows the profile to signed-out visitors with a way to sign up", async () => {
mockUseAuth.mockReturnValue({ user: null, isLoggedIn: false });
+ let rosterRequested = false;
+ server.use(
+ getListExpertTemplatesMockHandler([mariaTemplate]),
+ getListExpertsMockHandler(() => {
+ rosterRequested = true;
+ return [];
+ }),
+ );
- render(<MarketplaceExpertPage />);
+ renderPage();
+
+ expect(
+ await screen.findByRole("heading", { level: 1, name: "Maria" }),
+ ).toBeDefined();
+ expect(
+ screen.getByRole("link", { name: "Get started" }).getAttribute("href"),
+ ).toBe("/signup?next=%2Fmarketplace%2Fexperts%2Ftemplate-maria");
+ expect(screen.queryByRole("button", { name: "Hire Maria" })).toBeNull();
+ expect(screen.queryByText("Coming soon")).toBeNull();
+ expect(rosterRequested).toBe(false);
+ });
+
+ test("shows the coming-soon label instead of hire actions when the flag is off", async () => {
+ flagStatusMock.mockReturnValue({ enabled: false, ready: true });
+ let rosterRequested = false;
+ server.use(
+ getListExpertTemplatesMockHandler([mariaTemplate]),
+ getListExpertsMockHandler(() => {
+ rosterRequested = true;
+ return [];
+ }),
+ );
+
+ renderPage();
expect(
await screen.findByRole("heading", { level: 1, name: "Maria" }),
).toBeDefined();
expect(screen.getByText("Coming soon")).toBeDefined();
+ expect(screen.queryByRole("button", { name: "Hire Maria" })).toBeNull();
expect(screen.queryByRole("link", { name: "Get started" })).toBeNull();
- expect(screen.queryByRole("button", { name: /hire/i })).toBeNull();
+ expect(rosterRequested).toBe(false);
+ });
+
+ test("waits for the flag before showing a header action", async () => {
+ flagStatusMock.mockReturnValue({ enabled: false, ready: false });
+ server.use(
+ getListExpertTemplatesMockHandler([mariaTemplate]),
+ getListExpertsMockHandler([]),
+ );
+
+ renderPage();
+
+ expect(
+ await screen.findByRole("heading", { level: 1, name: "Maria" }),
+ ).toBeDefined();
+ expect(screen.queryByText("Coming soon")).toBeNull();
+ expect(screen.queryByRole("button", { name: "Hire Maria" })).toBeNull();
});
});