Skip to content
57 linesCodeBlameRaw
1import { Outlet, data, type ShouldRevalidateFunctionArgs, useMatch, useRouteLoaderData } from "react-router";
2
3import { type WorkspaceAgent, hasCodeAccess } from "@g1t/contracts";
4
5import { AgentsSidebar } from "../../../components/agents-mode";
6
7import type { Route } from "./+types/layout";
8import { workspaceAgents } from "../../../lib/services.server";
9import { requireUser, roleIn } from "../../../lib/session.server";
10
11/**
12 * Agents mode: the workspace's agents, for its sidebar, and how many live
13 * sessions each has (by agent id); null when the agents service does not answer.
14 */
15export type AgentsLayoutData = { slug: string; agents: WorkspaceAgent[] | null; live: Record<string, number> };
16
17export async function loader({ params, context, request }: Route.LoaderArgs): Promise<AgentsLayoutData> {
18 // Signed out, sign in first (as Chat and Docs do), rather than a 404.
19 const viewer = requireUser(context, request);
20 if (!roleIn(viewer, params.owner)) throw data(null, { status: 404 });
21 const slug = params.owner.toLowerCase();
22 const [listed, live] = await Promise.all([
23 workspaceAgents.list(slug, viewer!).catch(() => null),
24 // Every live session counts, private ones too: a count says nothing about what it is.
25 workspaceAgents.sessions(slug, viewer!, { status: "live", limit: 200 }).catch(() => null),
26 ]);
27 const counts: Record<string, number> = {};
28 for (const session of live?.ok ? live.value : []) counts[session.agent_id] = (counts[session.agent_id] ?? 0) + 1;
29 return {
30 slug,
31 live: counts,
32 agents: listed?.ok ? listed.value.filter((agent) => !agent.archived_at).sort((a, b) => a.display_name.localeCompare(b.display_name)) : null,
33 };
34}
35
36/** The list changes when an agent is made or changed, or work is stopped or started; not when moving between them. */
37export function shouldRevalidate({ currentParams, nextParams, formMethod, defaultShouldRevalidate }: ShouldRevalidateFunctionArgs) {
38 if (formMethod && formMethod !== "GET") return defaultShouldRevalidate;
39 return currentParams.owner !== nextParams.owner;
40}
41
42export default function AgentsLayout({ loaderData }: Route.ComponentProps) {
43 const root = useRouteLoaderData("root") as { user?: { workspaces?: { slug: string; role: string; code_access?: boolean }[] } | null } | undefined;
44 const membership = root?.user?.workspaces?.find((m) => m.slug === loaderData.slug) ?? null;
45 // A phone: the agents first, as a list; the fleet's numbers under it.
46 const index = useMatch("/:owner/-/agents");
47 return (
48 <>
49 {index && (
50 <div className="-mx-4 -mt-6 mb-8 md:hidden">
51 <AgentsSidebar slug={loaderData.slug} shellAgents={null} code={hasCodeAccess(membership)} owner={membership?.role === "owner"} phone />
52 </div>
53 )}
54 <Outlet />
55 </>
56 );
57}