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.

4.9 KB
Raw Blame
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 { trackExperts } from "@/services/experts/experts-analytics";
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.expert.setup_status === "installing"
        ? "Their skills and workflows are installing."
        : undefined,
    variant: "success",
    action: (
      <Button
        as="NextLink"
        href="/team"
        variant="outline"
        size="small"
        className="border-white text-white hover:border-white hover:bg-white/15 hover:text-white"
      >
        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();
  const [hireResult, setHireResult] = useState<HireResult | null>(null);
  const [isVoicePickOpen, setIsVoicePickOpen] = useState(false);
  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);
    setIsVoicePickOpen(false);
    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, surface: "expert_page" },
      });
      const result = response.data as HireResult;
      await invalidateExpertRosterQueries(queryClient);
      pendingCelebrationRef.current = result;
      setHireResult(result);
      if ((expert.voice_samples ?? []).length > 0) {
        setIsVoicePickOpen(true);
        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();
  }

  function dismiss() {
    if (isVoicePickOpen) {
      trackExperts("hire_flow_abandoned", {
        template_id: expert?.id ?? null,
        stage: "voice",
      });
    }
    finish();
  }

  return {
    hire,
    isHiring,
    isVoicePickOpen,
    hireResult,
    pickVoice,
    skipVoice: finish,
    dismissVoicePick: dismiss,
    isSavingVoice,
  };
}