Skip to content

The platform for continuously improving AI agents.

14.7 KB
Raw Blame
import { type FormEvent, useState } from "react";

import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Link, useNavigate, useRouterState } from "@tanstack/react-router";

import api from "@/client";
import sidebarStyles from "@/components/app-sidebar.module.css";
import { Button } from "@/components/ui/button";
import { ConfirmDialog } from "@/components/ui/confirm-dialog";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Icon } from "@/components/ui/icons";
import { Input } from "@/components/ui/input";
import { useSidebar } from "@/components/ui/sidebar";
import { Spinner } from "@/components/ui/spinner";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { useAuthContext } from "@/contexts/auth-context";
import { notify } from "@/lib/notify";
import { localStore } from "@/lib/storage";
import { cn } from "@/lib/utils";
import { newWorkspaceTab } from "@/lib/workspace-navigation";
import type { ExperimentList } from "@/openapi";

const sections = [
  "Pinned",
  "Today",
  "Yesterday",
  "Previous 7 days",
  "Previous 30 days",
  "Older",
] as const;
const activeStates = new Set(["accepted", "pending", "queued", "preparing", "running", "stopping"]);

function groupSessions(rows: ExperimentList[], pins: string[], search: string) {
  const now = new Date();
  const startOfDay = (daysAgo: number) =>
    new Date(now.getFullYear(), now.getMonth(), now.getDate() - daysAgo).getTime();
  const boundaries = [0, 1, 6, 29].map(startOfDay);
  const activity = (row: ExperimentList) =>
    Math.max(row.updatedAt.getTime(), row.lastRunAt?.getTime() ?? 0);
  const groups = sections.map((title) => ({ rows: [] as ExperimentList[], title }));
  const terms = search.trim().toLowerCase().split(/\s+/);
  for (const row of [...rows].sort((left, right) => activity(right) - activity(left))) {
    if (!terms.every((term) => row.name.toLowerCase().includes(term))) continue;
    const boundary = boundaries.findIndex((time) => activity(row) >= time);
    const index = pins.includes(row.id) ? 0 : boundary < 0 ? sections.length - 1 : boundary + 1;
    groups[index].rows.push(row);
  }
  return groups.filter((group) => group.rows.length > 0);
}

function readPins(key: string): string[] {
  try {
    const pins: unknown = JSON.parse(localStore.get(key) ?? "[]");
    return Array.isArray(pins) ? pins.filter((pin): pin is string => typeof pin === "string") : [];
  } catch {
    return [];
  }
}

export function ExperimentSessions({ projectId, onNew }: { projectId: string; onNew: () => void }) {
  const { user } = useAuthContext();
  const { isMobile, setOpenMobile } = useSidebar();
  const location = useRouterState({ select: (state) => state.location });
  const navigate = useNavigate();
  const client = useQueryClient();
  const [search, setSearch] = useState("");
  const [edit, setEdit] = useState<{ id: string; name: string }>();
  const [remove, setRemove] = useState<ExperimentList>();
  const pinKey = `experiment-pins:${user?.id ?? "guest"}:${projectId}`;
  const [pins, setPins] = useState(() => readPins(pinKey));
  const listKey = ["research-experiments", projectId, "sessions"] as const;
  const history = useQuery({
    queryFn: async ({ signal }) => {
      const rows: ExperimentList[] = [];
      for (let page = 1; ; page++) {
        const result = await api.researchExperiments.researchExperimentsList(
          { ordering: "-created_at", page, pageSize: 100, project: projectId },
          { signal }
        );
        rows.push(...result.results);
        if (!result.next) return rows;
      }
    },
    queryKey: listKey,
    refetchInterval: 30_000,
  });
  const updatePins = (next: string[]) => {
    setPins(next);
    // A refused write keeps the pins until the page is closed.
    localStore.set(pinKey, JSON.stringify(next));
  };
  const rename = useMutation({
    mutationFn: ({ id, name }: { id: string; name: string }) =>
      api.researchExperiments.researchExperimentsPartialUpdate({
        id,
        patchedExperimentRenameRequest: { name },
      }),
    onError: (error) => notify.error(error, "Rename failed"),
    onSuccess: (row) => {
      setEdit(undefined);
      client.setQueryData<ExperimentList[]>(listKey, (old) =>
        old?.map((item) => (item.id === row.id ? row : item))
      );
      void client.invalidateQueries({ queryKey: ["research-experiment", row.id] });
      void client.invalidateQueries({ queryKey: ["research-experiments", projectId] });
    },
  });
  const destroy = useMutation({
    mutationFn: (id: string) => api.researchExperiments.researchExperimentsDestroy({ id }),
    onSuccess: (_, id) => {
      setRemove(undefined);
      updatePins(pins.filter((pin) => pin !== id));
      client.setQueryData<ExperimentList[]>(listKey, (old) =>
        old?.filter((item) => item.id !== id)
      );
      void client.invalidateQueries({ queryKey: ["research-experiments", projectId] });
      if (location.pathname === `/experiments/${id}`)
        void navigate({ search: { projectId }, to: "/" });
    },
  });
  const closeMobile = () => {
    if (isMobile) setOpenMobile(false);
  };
  const currentTab = location.pathname.startsWith("/experiments/")
    ? location.search.workspaceTab
    : undefined;
  const groups = groupSessions(history.data ?? [], pins, search);
  const submitName = (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    const name = edit?.name.trim();
    if (!edit || !name || rename.isPending) return;
    if (name === history.data?.find((row) => row.id === edit.id)?.name) {
      setEdit(undefined);
      return;
    }
    rename.mutate({ id: edit.id, name });
  };

  return (
    <div
      aria-label="Experiment sessions"
      className={cn("flex h-full min-h-0 min-w-0 flex-col", sidebarStyles.sessions)}
    >
      <div className="flex shrink-0 items-center gap-1 px-1 pb-2">
        <div className="relative min-w-0 flex-1">
          <Icon.search className="pointer-events-none absolute top-1/2 left-2 size-3.5 -translate-y-1/2 text-muted-foreground" />
          <Input
            aria-label="Search experiments"
            className="border-transparent bg-wash-subtle pl-7 focus-visible:ring-1 focus-visible:ring-inset"
            onChange={(event) => setSearch(event.target.value)}
            placeholder="Search"
            type="search"
            value={search}
          />
        </div>
        <Tooltip>
          <TooltipTrigger asChild>
            <Button aria-label="New experiment" onClick={onNew} size="icon" variant="ghost">
              <Icon.edit />
            </Button>
          </TooltipTrigger>
          <TooltipContent side="right">New experiment</TooltipContent>
        </Tooltip>
      </div>
      <div className="min-h-0 min-w-0 flex-1 space-y-3 overflow-y-auto overscroll-contain scroll-fade-y px-1 pb-4">
        {history.isError && (
          <Button onClick={() => void history.refetch()} size="xs" variant="outline">
            Retry loading experiments
          </Button>
        )}
        {history.isPending && (
          <p
            className="flex items-center gap-1.5 px-2 py-1.5 text-xs text-muted-foreground"
            role="status"
          >
            <Spinner size="sm" />
            Loading experiments…
          </p>
        )}
        {history.isSuccess && groups.length === 0 && (
          <p className="px-2 py-1.5 text-xs text-muted-foreground" role="status">
            {search.trim() ? "No matching experiments" : "No experiments yet"}
          </p>
        )}
        {groups.map((group) => (
          <section aria-label={group.title} key={group.title}>
            <p className="px-2 pt-1 pb-1.5 text-xs text-muted-foreground">{group.title}</p>
            <ul className="space-y-px">
              {group.rows.map((row) => (
                <li
                  className="group/session relative flex min-h-8 min-w-0 items-center"
                  key={row.id}
                >
                  {edit?.id === row.id ? (
                    <form className="flex w-full min-w-0 items-center gap-1" onSubmit={submitName}>
                      <Input
                        aria-label="Experiment name"
                        disabled={rename.isPending}
                        maxLength={255}
                        onChange={(event) => setEdit({ id: row.id, name: event.target.value })}
                        onFocus={(event) => event.currentTarget.select()}
                        onKeyDown={(event) => {
                          if (event.key === "Escape" && !rename.isPending) setEdit(undefined);
                        }}
                        ref={(input) => input?.focus()}
                        size="xs"
                        value={edit.name}
                      />
                      <Button
                        aria-label="Save name"
                        disabled={!edit.name.trim() || rename.isPending}
                        size="icon-xs"
                        type="submit"
                        variant="ghost"
                      >
                        <Icon.success />
                      </Button>
                      <Button
                        aria-label="Cancel rename"
                        disabled={rename.isPending}
                        onClick={() => setEdit(undefined)}
                        size="icon-xs"
                        type="button"
                        variant="ghost"
                      >
                        <Icon.close />
                      </Button>
                    </form>
                  ) : (
                    <>
                      <Link
                        activeOptions={{ exact: true, includeSearch: false }}
                        className={cn(
                          "flex min-h-8 w-full min-w-0 items-center gap-1.5 rounded-sm py-1 pr-7 pl-2 text-xs text-muted-foreground outline-none hover:text-sidebar-foreground focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring aria-[current=page]:text-sidebar-foreground",
                          sidebarStyles.session
                        )}
                        onClick={closeMobile}
                        params={{ experimentId: row.id }}
                        search={{ projectId, workspaceTab: currentTab }}
                        title={row.name}
                        to="/experiments/$experimentId"
                      >
                        <span className="truncate">{row.name}</span>
                      </Link>
                      {activeStates.has(row.state) && (
                        <span
                          aria-label="Running"
                          className="pointer-events-none absolute right-1.5 text-muted-foreground transition-opacity duration-150 group-hover/session:opacity-0 group-focus-within/session:opacity-0 motion-reduce:transition-none"
                          role="status"
                        >
                          <Spinner size="sm" />
                        </span>
                      )}
                      <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                          <Button
                            aria-label={`Options for ${row.name}`}
                            className="absolute right-0 translate-x-0.5 text-muted-foreground opacity-0 transition-[opacity,translate] duration-150 data-[state=open]:translate-x-0 data-[state=open]:opacity-100 group-hover/session:translate-x-0 group-hover/session:opacity-100 group-focus-within/session:translate-x-0 group-focus-within/session:opacity-100 pointer-coarse:translate-x-0 pointer-coarse:opacity-100 motion-reduce:transition-none"
                            size="icon-xs"
                            variant="ghost"
                          >
                            <Icon.menu />
                          </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent
                          align="start"
                          className="motion-reduce:animate-none"
                          side="right"
                        >
                          <DropdownMenuItem
                            onSelect={() =>
                              updatePins(
                                pins.includes(row.id)
                                  ? pins.filter((pin) => pin !== row.id)
                                  : [...pins, row.id]
                              )
                            }
                          >
                            <Icon.pin /> {pins.includes(row.id) ? "Unpin" : "Pin"}
                          </DropdownMenuItem>
                          <DropdownMenuItem
                            onSelect={() => setEdit({ id: row.id, name: row.name })}
                          >
                            <Icon.edit /> Rename
                          </DropdownMenuItem>
                          <DropdownMenuItem
                            onSelect={() => {
                              closeMobile();
                              void navigate({
                                params: { experimentId: row.id },
                                search: {
                                  projectId,
                                  workspaceTab: newWorkspaceTab("/experiments"),
                                },
                                to: "/experiments/$experimentId",
                              });
                            }}
                          >
                            <Icon.externalLink /> Open in new tab
                          </DropdownMenuItem>
                          <DropdownMenuSeparator />
                          <DropdownMenuItem
                            onSelect={() => {
                              destroy.reset();
                              setRemove(row);
                            }}
                            variant="destructive"
                          >
                            <Icon.delete /> Delete
                          </DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </>
                  )}
                </li>
              ))}
            </ul>
          </section>
        ))}
      </div>
      <ConfirmDialog
        confirmLabel="Delete"
        description={remove ? `Delete “${remove.name}” from experiment history?` : undefined}
        destructive
        error={destroy.error}
        isPending={destroy.isPending}
        keepOpenOnError
        onConfirm={async () => {
          if (remove) await destroy.mutateAsync(remove.id);
        }}
        onOpenChange={(open) => {
          if (!open && !destroy.isPending) setRemove(undefined);
        }}
        open={!!remove}
        title="Delete experiment?"
      />
    </div>
  );
}