Skip to content

The platform for continuously improving AI agents.

4.8 KB
Raw Blame
import { useMemo, useSyncExternalStore } from "react";

import type { RunningJobItem } from "@/lib/running-jobs";
import { sessionStore } from "@/lib/storage";
import { newWorkspaceTab } from "@/lib/workspace-navigation";

export interface LaunchedTab {
  id: string;
  href: string;
  title: string;
  jobKey: string;
  userId: string;
  projectId: string;
  unseen: boolean;
}

const STORAGE = "workspace-launched-tabs";

let tabs: LaunchedTab[] = readStored();
const listeners = new Set<() => void>();

function readStored(): LaunchedTab[] {
  try {
    const value: unknown = JSON.parse(sessionStore.get(STORAGE) ?? "null");
    if (!Array.isArray(value)) return [];
    return value.flatMap((item) => {
      if (
        !item ||
        typeof item.id !== "string" ||
        typeof item.href !== "string" ||
        typeof item.title !== "string" ||
        typeof item.jobKey !== "string" ||
        typeof item.userId !== "string" ||
        typeof item.projectId !== "string" ||
        !item.href.startsWith("/") ||
        item.href.startsWith("//")
      )
        return [];
      return [
        {
          href: item.href,
          id: item.id,
          jobKey: item.jobKey,
          projectId: item.projectId,
          title: item.title.slice(0, 100),
          unseen: item.unseen !== false,
          userId: item.userId,
        },
      ];
    });
  } catch {
    return [];
  }
}

function emit() {
  sessionStore.set(STORAGE, JSON.stringify(tabs));
  for (const listener of listeners) listener();
}

function subscribe(listener: () => void) {
  listeners.add(listener);
  return () => listeners.delete(listener);
}

export function currentLaunchedTabs(): LaunchedTab[] {
  return tabs;
}

const EMPTY: LaunchedTab[] = [];

export function scopedLaunchedTabs(
  tabs: LaunchedTab[],
  userId: string | undefined,
  projectId: string | undefined
) {
  return tabs.filter((tab) => tab.userId === userId && tab.projectId === projectId);
}

export function useLaunchedTabs(
  userId: string | undefined,
  projectId: string | undefined
): LaunchedTab[] {
  const stored = useSyncExternalStore(subscribe, currentLaunchedTabs, () => EMPTY);
  return useMemo(() => scopedLaunchedTabs(stored, userId, projectId), [stored, userId, projectId]);
}

function viewedJobKey(userId: string, projectId: string, jobKey: string) {
  return `workspace-viewed-job:${userId}:${projectId}:${jobKey}`;
}

export function acknowledgeLaunchedTab(id: string) {
  const tab = tabs.find((tab) => tab.id === id);
  if (!tab) return;
  sessionStore.set(viewedJobKey(tab.userId, tab.projectId, tab.jobKey), "1");
  tabs = tabs.filter((tab) => tab.id !== id);
  emit();
}

export function launchRecordedTab(input: {
  userId: string | undefined;
  jobKey: string;
  title: string;
  section: "/training" | "/evaluations" | "/datasets";
  id?: string;
  path: string;
  search: Record<string, string | undefined>;
}) {
  const projectId = input.search.projectId;
  if (!input.userId || !projectId) return;
  if (sessionStore.get(viewedJobKey(input.userId, projectId, input.jobKey))) return;
  if (
    tabs.some(
      (tab) =>
        (tab.jobKey === input.jobKey || (input.id && tab.id === input.id)) &&
        tab.userId === input.userId &&
        tab.projectId === projectId
    )
  )
    return;
  const id = input.id ?? newWorkspaceTab(input.section);
  const params = new URLSearchParams();
  for (const [key, value] of Object.entries({ ...input.search, workspaceTab: id })) {
    if (value) params.set(key, value);
  }
  tabs = [
    ...tabs,
    {
      href: `${input.path}?${params.toString()}`,
      id,
      jobKey: input.jobKey,
      projectId,
      title: input.title.slice(0, 100) || "Run",
      unseen: true,
      userId: input.userId,
    },
  ];
  emit();
  return tabs.at(-1);
}

export function launchJobTab(job: RunningJobItem, projectId: string, userId: string | undefined) {
  if (!projectId || !["running", "deploying"].includes(job.status)) return;
  if (job.kind === "finetuning") {
    launchRecordedTab({
      jobKey: job.key,
      path: "/training",
      search: {
        groupId: job.groupId ?? job.id,
        jobId: job.id === (job.groupId ?? job.id) ? undefined : job.id,
        projectId,
      },
      section: "/training",
      title: job.title,
      userId,
    });
    return;
  }
  launchRecordedTab({
    jobKey: job.key,
    path: `/evaluations/runs/${job.id}`,
    search: { projectId },
    section: "/evaluations",
    title: job.title,
    userId,
  });
}

export function withLaunchedTabs<T extends { id: string }>(
  open: readonly T[],
  launched: readonly LaunchedTab[]
): T[] {
  const ids = new Set(open.map((tab) => tab.id));
  return [
    ...open,
    ...launched
      .filter((tab) => !ids.has(tab.id))
      .map((tab) => ({ href: tab.href, id: tab.id, title: tab.title }) as unknown as T),
  ];
}