Skip to content

Enterprise agent platform for building, deploying, and operating AI teammates.

14.4 KB
Raw Blame
"use client";

import React, { useEffect, useRef, useState } from "react";
import { useParams, useRouter } from "next/navigation";
import { ArrowLeft, Loader2 } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { useI18n } from "@/contexts/i18n-context";
import { useApp } from "@/contexts/app-context-chat";
import { apiRequest } from "@/lib/api-wrapper";
import { getApiUrl } from "@/lib/utils";
import { hireAgentFromTemplate } from "@/lib/hire-agent";
import { PersonaAvatar } from "@/components/templates/persona-avatar";
import { TOOL_CATEGORY_I18N_KEYS, capitalize } from "@/lib/tool-category-labels";
import type { TemplateDetail } from "@/types/template";
import { getAgentTaskHref } from "@/lib/agent-ui-access";

type LoadStatus = "loading" | "not_found" | "error" | "ready";

export default function TemplateDetailPage() {
  const params = useParams();
  const router = useRouter();
  const { dispatch } = useApp();
  const { t, tDynamic, locale } = useI18n();
  const id = Array.isArray(params.id) ? params.id[0] : params.id;

  const [template, setTemplate] = useState<TemplateDetail | null>(null);
  const [status, setStatus] = useState<LoadStatus>("loading");
  const [retryToken, setRetryToken] = useState(0);
  const [hiring, setHiring] = useState(false);
  // Guards handlePrimaryAction against a second invocation (double-click,
  // a repeated Enter keypress) firing before React commits `hiring: true` -
  // a ref updates synchronously, a state setter does not.
  const hiringRef = useRef(false);
  const isMountedRef = useRef(true);

  useEffect(() => {
    // Not redundant with useRef(true)'s initial value: React 18 StrictMode
    // double-invokes this effect in dev (mount -> cleanup -> mount), and the
    // cleanup below runs in between - without resetting to true on the
    // second invocation, isMountedRef.current would stay false forever even
    // though the component is genuinely still mounted.
    isMountedRef.current = true;
    return () => {
      isMountedRef.current = false;
    };
  }, []);

  useEffect(() => {
    if (!id) return;
    let cancelled = false;
    setStatus("loading");

    (async () => {
      try {
        const response = await apiRequest(
          `${getApiUrl()}/api/templates/${encodeURIComponent(id)}?lang=${locale}`
        );
        if (cancelled) return;
        if (!response.ok) {
          // A genuine 404 means the template doesn't exist - no retry would
          // help. Any other failure mode (5xx, a transient network error,
          // malformed JSON below) is presumed recoverable, so it gets its
          // own state with a retry action rather than reusing "not found"
          // and telling the user something untrue.
          setStatus(response.status === 404 ? "not_found" : "error");
          return;
        }
        const data = (await response.json()) as TemplateDetail;
        if (cancelled) return;
        setTemplate(data);
        setStatus("ready");
      } catch {
        if (!cancelled) setStatus("error");
      }
    })();

    return () => {
      cancelled = true;
    };
  }, [id, locale, retryToken]);

  // A workforce-type template (or any agent-type template with no
  // marketplace persona) has no meaningful detail view here - the
  // marketplace list never links to this page for one, so reaching this
  // state means a stale/direct URL. Checking `type` explicitly (not just
  // persona-is-null) matches the same guard library-template-card.tsx uses
  // before it will touch persona at all.
  const persona = template && template.type !== "workforce" ? template.persona : null;
  const isReady = status === "ready" && template !== null && persona !== null;

  const getToolLabel = (category: string): string => {
    const key = TOOL_CATEGORY_I18N_KEYS[category];
    return key ? tDynamic(key, capitalize(category)) : capitalize(category);
  };

  const handleBack = () => router.push("/templates");
  const handleRetry = () => setRetryToken((token) => token + 1);

  const handlePrimaryAction = async () => {
    if (!template || !persona || hiringRef.current) return;

    if (template.hired && template.hired_agent_id) {
      router.push(getAgentTaskHref(template.hired_agent_id));
      return;
    }

    hiringRef.current = true;
    setHiring(true);
    try {
      // `template.hired` was fetched once on mount and never revalidated,
      // so a second tab (or a bookmarked/back-navigated stale page) that
      // hired this template in the meantime would still see hired: false
      // here. hireAgentFromTemplate's own resolve step is idempotent
      // (reuses the agent), but task/create always mints a new task, so
      // without this recheck a race would seed a second opening message
      // onto an agent the user already has a real conversation with. Best
      // effort only: if the recheck itself fails, fall through to the
      // normal hire flow rather than blocking the action on it.
      try {
        const freshCheck = await apiRequest(
          `${getApiUrl()}/api/templates/${encodeURIComponent(template.id)}?lang=${locale}`
        );
        if (freshCheck.ok) {
          const freshTemplate = (await freshCheck.json()) as TemplateDetail;
          if (freshTemplate.hired && freshTemplate.hired_agent_id) {
            if (isMountedRef.current) {
              dispatch({ type: "TRIGGER_TASK_UPDATE" });
              router.push(getAgentTaskHref(freshTemplate.hired_agent_id));
            }
            return;
          }
        }
      } catch {
        // Fall through - see the best-effort note above.
      }
      if (!isMountedRef.current) return;

      const result = await hireAgentFromTemplate({
        templateId: template.id,
        persona,
        strings: {
          beforeWeStart: t("templates.marketplace.beforeWeStart"),
          closingNote: t("templates.marketplace.hireClosingNote"),
          connectAppsLabel: t("chatPage.clarification.connectApps.title"),
        },
        connections: template.connections,
      });
      if (!isMountedRef.current) return;
      // The persistent sidebar needs an explicit refresh after a new hire.
      dispatch({ type: "TRIGGER_TASK_UPDATE" });
      router.push(`/task/${result.taskId}`);
    } catch {
      if (!isMountedRef.current) return;
      toast.error(t("templates.marketplace.hireFailed", { name: persona.name }));
      hiringRef.current = false;
      setHiring(false);
    }
  };

  if (status === "loading") {
    return (
      <div className="flex h-full items-center justify-center">
        <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
      </div>
    );
  }

  if (status === "error") {
    return (
      <div className="flex h-full flex-col items-center justify-center gap-4 text-center">
        <p className="text-muted-foreground">{t("templates.marketplace.loadFailed")}</p>
        <div className="flex gap-2">
          <Button variant="outline" onClick={handleBack}>
            <ArrowLeft className="mr-2 h-4 w-4" />
            {t("templates.marketplace.back")}
          </Button>
          <Button onClick={handleRetry}>{t("templates.marketplace.retry")}</Button>
        </div>
      </div>
    );
  }

  if (!isReady || !template || !persona) {
    return (
      <div className="flex h-full flex-col items-center justify-center gap-4 text-center">
        <p className="text-muted-foreground">{t("templates.marketplace.notFound")}</p>
        <Button variant="outline" onClick={handleBack}>
          <ArrowLeft className="mr-2 h-4 w-4" />
          {t("templates.marketplace.back")}
        </Button>
      </div>
    );
  }

  const toolCategories = (template.agent_config?.tool_categories || []).filter(
    (category) => !category.startsWith("mcp:")
  );
  const connectedApps = template.connections || [];
  const skills = template.agent_config?.skills || [];
  const samplePrompts = template.sample_prompts || [];

  return (
    <div className="flex h-full flex-col overflow-y-auto bg-background">
      <div className="mx-auto w-full max-w-5xl px-6 py-6 md:px-8">
        <button
          type="button"
          onClick={handleBack}
          className="mb-6 flex items-center gap-1.5 text-sm font-medium text-muted-foreground transition-colors hover:text-foreground"
        >
          <ArrowLeft className="h-4 w-4" />
          {t("templates.marketplace.back")}
        </button>

        <div className="mb-6 flex flex-wrap items-center justify-between gap-4">
          <div className="flex items-center gap-4">
            <PersonaAvatar persona={persona} sizeClassName="h-16 w-16" textClassName="text-xl" />
            <div>
              <h1 className="text-2xl font-bold text-foreground">{persona.name}</h1>
              <p className="text-muted-foreground">{persona.role}</p>
            </div>
          </div>
          <Button onClick={handlePrimaryAction} disabled={hiring} size="lg">
            {hiring ? (
              <>
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                {t("templates.marketplace.hiring")}
              </>
            ) : template.hired ? (
              t("templates.marketplace.chat")
            ) : (
              t("templates.marketplace.hire", { name: persona.name })
            )}
          </Button>
        </div>

        <p className="mb-8 max-w-2xl text-[15px] leading-relaxed text-muted-foreground">
          {template.description}
        </p>

        <div className="grid grid-cols-1 gap-8 lg:grid-cols-3">
          <div className="flex flex-col gap-8 lg:col-span-2">
            {template.features.length > 0 && (
              <section>
                <h2 className="mb-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                  {t("templates.marketplace.whatItDoes")}
                </h2>
                <ul className="flex flex-col gap-2">
                  {template.features.map((feature, index) => (
                    <li
                      key={index}
                      className="flex gap-2 text-[14px] leading-relaxed text-foreground/90"
                    >
                      <span className="flex-none text-muted-foreground/60">›</span>
                      <span>{feature}</span>
                    </li>
                  ))}
                </ul>
              </section>
            )}

            {samplePrompts.length > 0 && (
              <section>
                <h2 className="mb-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                  {t("templates.marketplace.tryAsking")}
                </h2>
                <div className="flex flex-col gap-2">
                  {samplePrompts.map((prompt, index) => (
                    <div
                      key={index}
                      className="rounded-[10px] border border-border bg-muted/40 px-3.5 py-2.5 text-[13.5px] text-foreground/90"
                    >
                      {prompt.prompt}
                    </div>
                  ))}
                </div>
              </section>
            )}
          </div>

          <div className="flex flex-col gap-5 rounded-[14px] border border-border bg-card p-5">
            <h2 className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
              {t("templates.marketplace.whatsIncluded")}
            </h2>

            {template.agent_config?.execution_mode && (
              <div>
                <div className="text-[11.5px] font-medium text-muted-foreground">
                  {t("templates.marketplace.thinking")}
                </div>
                <div className="text-[13.5px] font-medium text-foreground">
                  {tDynamic(
                    `builds.configForm.executionMode.${template.agent_config.execution_mode}.title`,
                    capitalize(template.agent_config.execution_mode)
                  )}
                </div>
              </div>
            )}

            {toolCategories.length > 0 && (
              <div>
                <div className="mb-1.5 text-[11.5px] font-medium text-muted-foreground">
                  {t("templates.marketplace.tools")}
                </div>
                <div className="flex flex-wrap gap-1.5">
                  {toolCategories.map((category) => (
                    <span
                      key={category}
                      className="rounded-full bg-muted px-2.5 py-1 text-[11.5px] font-medium text-foreground/80"
                    >
                      {getToolLabel(category)}
                    </span>
                  ))}
                </div>
              </div>
            )}

            {connectedApps.length > 0 && (
              <div>
                <div className="mb-1.5 text-[11.5px] font-medium text-muted-foreground">
                  {t("templates.marketplace.connectedApps")}
                </div>
                <div className="flex flex-wrap gap-1.5">
                  {connectedApps.map((app) => (
                    <span
                      key={app.name}
                      className="flex items-center gap-1.5 rounded-full bg-muted px-2.5 py-1 text-[11.5px] font-medium text-foreground/80"
                    >
                      {app.logo ? (
                        <img src={app.logo} alt="" className="h-3.5 w-3.5" />
                      ) : null}
                      {app.name}
                    </span>
                  ))}
                </div>
              </div>
            )}

            {skills.length > 0 && (
              <div>
                <div className="mb-1.5 text-[11.5px] font-medium text-muted-foreground">
                  {t("templates.marketplace.skills")}
                </div>
                <div className="flex flex-wrap gap-1.5">
                  {skills.map((skill) => (
                    <span
                      key={skill}
                      className="rounded-full bg-muted px-2.5 py-1 text-[11.5px] font-medium text-foreground/80"
                    >
                      {skill}
                    </span>
                  ))}
                </div>
              </div>
            )}
          </div>
        </div>

        {!template.hired && (
          <button
            type="button"
            onClick={() => router.push(`/build/new?template=${encodeURIComponent(template.id)}`)}
            className="mt-8 text-[13px] font-medium text-muted-foreground underline-offset-2 hover:text-foreground hover:underline"
          >
            {t("templates.marketplace.customizeBeforeHiring")}
          </button>
        )}
      </div>
    </div>
  );
}