Skip to content

The platform for continuously improving AI agents.

12.8 KB
Raw Blame
import { type ComponentProps, type ComponentType, type SVGProps, useEffect, useState } from "react";

import { Link, useNavigate, useRouterState, useSearch } from "@tanstack/react-router";

import { identifyUser, trackEvent } from "@/analytics";
import overmindEyeIcon from "@/assets/overmind-eye-copper.svg";
import { AccountMenu } from "@/components/account-menu";
import { FeedbackDialog } from "@/components/feedback-dialog";
import {
  JobNotificationBadge,
  type JobNotificationBadgeTone,
} from "@/components/job-notification-badge";
import { ProjectSelector } from "@/components/project-selector";
import { RunningJobsButton } from "@/components/running-jobs-button";
import { Button } from "@/components/ui/button";
import { Icon } from "@/components/ui/icons";
import { Kbd } from "@/components/ui/kbd";
import {
  Sidebar,
  SidebarContent,
  SidebarFooter,
  SidebarHeader,
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
  useSidebar,
} from "@/components/ui/sidebar";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { ExperimentSessions } from "@/components/workspace/experiment-sessions";
import { useAuthContext } from "@/contexts/auth-context";
import { useAllEvalRunsQuery } from "@/hooks/use-evaluations";
import { useFinetuningJobsQuery } from "@/hooks/use-finetuning";
import { useGuestGate } from "@/hooks/use-guest-gate";
import { useUnseenSignalCountQuery } from "@/hooks/use-signals";
import { featureFlags } from "@/lib/feature-flags";
import { isGuestAllowedPath } from "@/lib/guest";
import { isMac } from "@/lib/platform";
import { buildRunningJobs, type RunningJobKind } from "@/lib/running-jobs";
import {
  clearUnseenCompletionsForKinds,
  kindsForPathname,
  useUnseenCompletions,
} from "@/lib/unseen-job-completions";
import { cn } from "@/lib/utils";
import styles from "./app-sidebar.module.css";

interface NavLeaf {
  flag?: keyof typeof featureFlags;
  icon: ComponentType<SVGProps<SVGSVGElement>>;
  label: string;
  to: string;
}
type Badge = { count: number; tone: JobNotificationBadgeTone };

const platformNav: NavLeaf[] = (
  [
    { icon: Icon.agent, label: "Agent", to: "/agent" },
    { icon: Icon.observability, label: "Traces", to: "/observability" },
    { icon: Icon.notify, label: "Signals", to: "/telemetry/signals" },
    { icon: Icon.chartBar, label: "Metrics", to: "/telemetry/metrics" },
    { icon: Icon.gitBranch, label: "Graph", to: "/telemetry/graph" },
    { flag: "datasets", icon: Icon.dataset, label: "Datasets", to: "/datasets" },
    { flag: "evaluations", icon: Icon.eval, label: "Evaluations", to: "/evaluations" },
    { flag: "finetuning", icon: Icon.training, label: "Training", to: "/training" },
    { flag: "inference", icon: Icon.inference, label: "Inference", to: "/inference" },
  ] satisfies NavLeaf[]
).filter((leaf) => !leaf.flag || featureFlags[leaf.flag]);

/** Every destination, for the command palette. The account menu reaches the last three. */
export const navLinks: NavLeaf[] = [
  ...platformNav,
  { icon: Icon.settings, label: "Settings", to: "/settings" },
  { icon: Icon.project, label: "Projects", to: "/projects" },
  { icon: Icon.integrations, label: "Integrations", to: "/integrations" },
];

const isActive = (pathname: string, to: string) => {
  if (to === "/telemetry") {
    return (
      pathname === "/telemetry" ||
      (pathname.startsWith("/telemetry/") &&
        !pathname.startsWith("/telemetry/signals") &&
        !pathname.startsWith("/telemetry/metrics") &&
        !pathname.startsWith("/telemetry/graph"))
    );
  }
  return pathname.startsWith(to) || (to === "/agent" && pathname.startsWith("/capabilities"));
};

const JOB_ROUTE: Record<RunningJobKind, string> = { eval: "/evaluations", finetuning: "/training" };

/** Unseen completions outrank running jobs. Shares query keys with notifications. */
function useNavBadges(projectId: string | undefined): Record<string, Badge> {
  const running = buildRunningJobs({
    evalRuns: useAllEvalRunsQuery(projectId).data?.results,
    finetuning: useFinetuningJobsQuery(projectId).data?.results,
  });
  const unseen = useUnseenCompletions();
  const signals = useUnseenSignalCountQuery(featureFlags.signals ? projectId : undefined).data;
  const badges: Record<string, Badge> = {};
  for (const route of Object.values(JOB_ROUTE)) {
    const unseenCount = unseen.filter((job) => JOB_ROUTE[job.kind] === route).length;
    const runningCount = running.filter((job) => JOB_ROUTE[job.kind] === route).length;
    if (unseenCount) badges[route] = { count: unseenCount, tone: "success" };
    else if (runningCount) badges[route] = { count: runningCount, tone: "running" };
  }
  if (signals) badges["/observability"] = { count: signals, tone: "success" };
  return badges;
}

function NavBadge({ badge }: { badge?: Badge }) {
  return badge ? (
    <JobNotificationBadge
      className={cn("sidebar-label ml-auto shrink-0", styles.label)}
      {...badge}
    />
  ) : null;
}

function NavDestination({ leaf, onClick, ...props }: ComponentProps<"a"> & { leaf: NavLeaf }) {
  const guard = useGuestGate();
  const { isMobile, setOpenMobile } = useSidebar();
  return (
    <Link
      {...props}
      onClick={(event) => {
        if (!isGuestAllowedPath(leaf.to)) guard()(event);
        if (event.defaultPrevented) return;
        onClick?.(event);
        if (isMobile) setOpenMobile(false);
      }}
      search={(prev) => ({
        projectId: prev.projectId,
        workspaceTab: undefined,
      })}
      to={leaf.to}
    />
  );
}

export function AppSidebar({ onSearchOpen }: { onSearchOpen: () => void }) {
  const { projectId } = useSearch({ from: "/_auth" });
  const pathname = useRouterState({ select: (s) => s.location.pathname });
  const { state, isMobile, toggleSidebar, openMobile, setOpenMobile, setOpen } = useSidebar();
  const { isSignedIn, isGuest, requestUpgrade, user } = useAuthContext();
  const badges = useNavBadges(projectId);
  const [feedbackOpen, setFeedbackOpen] = useState(false);
  const [showHistory, setShowHistory] = useState(false);
  const navigate = useNavigate();
  const iconOnly = state === "collapsed" && !isMobile;
  const expanded = isMobile ? openMobile : state === "expanded";
  const toggleLabel = expanded ? "Collapse sidebar" : "Expand sidebar";
  const history = showHistory && !iconOnly && !!projectId && !isGuest;
  // A new Home chat: Home keeps the first one's draft in its own tab.
  const newExperiment = () => {
    if (isMobile) setOpenMobile(false);
    void navigate({ search: { projectId, workspace: crypto.randomUUID() }, to: "/" });
  };

  useEffect(() => {
    trackEvent("login_changed", { isSignedIn });
  }, [isSignedIn]);
  const [userId, email, name] = [user?.id ?? "", user?.email || undefined, user?.name || undefined];
  useEffect(() => {
    identifyUser({ clerkUserId: userId, email, name, userId });
  }, [userId, email, name]);
  useEffect(() => {
    const kinds = kindsForPathname(pathname);
    if (kinds) clearUnseenCompletionsForKinds(kinds);
  }, [pathname]);

  return (
    <Sidebar collapsible="icon">
      <div className={cn("flex h-full min-h-0 flex-col", styles.shell)} data-compact={iconOnly}>
        <SidebarHeader className={cn("shrink-0 items-start px-2.5 pt-4 pb-0", styles.header)}>
          <Tooltip>
            <TooltipTrigger asChild>
              <Button
                aria-expanded={expanded}
                aria-label={toggleLabel}
                className={cn("relative shrink-0", styles.brandButton)}
                onClick={toggleSidebar}
                size="icon"
                variant="ghost"
              >
                <img
                  alt=""
                  className={cn("size-6 object-contain", styles.brand)}
                  src={overmindEyeIcon}
                />
                <span className={cn("absolute inset-0 grid place-items-center", styles.toggle)}>
                  <Icon.sidebar />
                </span>
              </Button>
            </TooltipTrigger>
            <TooltipContent side="right">{toggleLabel}</TooltipContent>
          </Tooltip>
          <SidebarMenuButton
            aria-label="Search"
            className={cn("min-w-0 bg-wash-subtle", styles.search)}
            onClick={() => {
              if (isMobile) setOpenMobile(false);
              onSearchOpen();
            }}
            tooltip="Search"
          >
            <Icon.search className="!size-[17px]" />
            <span className={cn("sidebar-label flex-1 truncate", styles.label)}>Search</span>
            <Kbd className={cn("h-5 px-1.5", styles.label)}>{isMac ? "⌘ K" : "Ctrl K"}</Kbd>
          </SidebarMenuButton>
        </SidebarHeader>

        {projectId && !isGuest && (
          <SidebarMenu
            aria-label="Experiments"
            className={cn("shrink-0 pt-1", iconOnly ? "px-2" : "px-2.5 pb-1.5")}
          >
            <SidebarMenuItem className="flex items-center gap-1">
              <SidebarMenuButton
                aria-label={history ? "Back to navigation" : "Experiments"}
                className={iconOnly ? "flex-none" : "min-w-0 flex-1"}
                onClick={() => {
                  if (iconOnly) setOpen(true);
                  setShowHistory(!history);
                }}
                tooltip="Experiments"
              >
                {history ? (
                  <Icon.back className="!size-[17px]" />
                ) : (
                  <Icon.history className="!size-[17px]" />
                )}
                <span className={cn("sidebar-label truncate", styles.label)}>
                  {history ? "Back" : "Experiments"}
                </span>
              </SidebarMenuButton>
              {!iconOnly && !history && (
                <Tooltip>
                  <TooltipTrigger asChild>
                    <Button
                      aria-label="New experiment"
                      onClick={newExperiment}
                      size="icon"
                      variant="ghost"
                    >
                      <Icon.add />
                    </Button>
                  </TooltipTrigger>
                  <TooltipContent side="right">New experiment</TooltipContent>
                </Tooltip>
              )}
            </SidebarMenuItem>
          </SidebarMenu>
        )}

        <SidebarContent className="px-2.5 pt-1 pb-2 group-data-[collapsible=icon]:px-2">
          {history && projectId ? (
            <ExperimentSessions
              key={`${user?.id}:${projectId}`}
              onNew={newExperiment}
              projectId={projectId}
            />
          ) : (
            <SidebarMenu aria-label="Platform" className="gap-1">
              {platformNav.map((leaf) => {
                const active = isActive(pathname, leaf.to);
                return (
                  <SidebarMenuItem key={leaf.to}>
                    <SidebarMenuButton asChild isActive={active} tooltip={leaf.label}>
                      <NavDestination aria-current={active ? "page" : undefined} leaf={leaf}>
                        <leaf.icon className="!size-[17px]" />
                        <span className={cn("sidebar-label truncate", styles.label)}>
                          {leaf.label}
                        </span>
                        <NavBadge badge={badges[leaf.to]} />
                      </NavDestination>
                    </SidebarMenuButton>
                  </SidebarMenuItem>
                );
              })}
            </SidebarMenu>
          )}
        </SidebarContent>

        <SidebarFooter className="mx-2 mb-2 shrink-0 gap-1 px-0.5 pt-2 pb-0 group-data-[collapsible=icon]:px-0">
          {!isGuest && <RunningJobsButton />}
          <SidebarMenu>
            <SidebarMenuItem>
              <ProjectSelector compact={iconOnly} />
            </SidebarMenuItem>
            {isGuest ? (
              <SidebarMenuItem>
                <SidebarMenuButton
                  className="!py-2.5"
                  onClick={requestUpgrade}
                  tooltip="Create account"
                >
                  <Icon.login className="!size-[17px]" />
                  <span className={cn("sidebar-label", styles.label)}>Create account</span>
                </SidebarMenuButton>
              </SidebarMenuItem>
            ) : (
              !isSignedIn && (
                <SidebarMenuItem>
                  <SidebarMenuButton asChild className="!py-2.5" tooltip="Sign in">
                    <Link to="/login">
                      <Icon.login className="!size-[17px]" />
                      <span className={cn("sidebar-label", styles.label)}>Sign in</span>
                    </Link>
                  </SidebarMenuButton>
                </SidebarMenuItem>
              )
            )}
            <SidebarMenuItem>
              <AccountMenu onFeedback={() => setFeedbackOpen(true)} />
            </SidebarMenuItem>
          </SidebarMenu>
        </SidebarFooter>
        <FeedbackDialog onOpenChange={setFeedbackOpen} open={feedbackOpen} />
      </div>
    </Sidebar>
  );
}