Skip to content
56 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 { getViewer, 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 }: Route.LoaderArgs): Promise<AgentsLayoutData> {
18 const viewer = getViewer(context);
19 if (!roleIn(viewer, params.owner)) throw data(null, { status: 404 });
20 const slug = params.owner.toLowerCase();
21 const [listed, live] = await Promise.all([
22 workspaceAgents.list(slug, viewer!).catch(() => null),
23 // Every live session counts, private ones too: a count says nothing about what it is.
24 workspaceAgents.sessions(slug, viewer!, { status: "live", limit: 200 }).catch(() => null),
25 ]);
26 const counts: Record<string, number> = {};
27 for (const session of live?.ok ? live.value : []) counts[session.agent_id] = (counts[session.agent_id] ?? 0) + 1;
28 return {
29 slug,
30 live: counts,
31 agents: listed?.ok ? listed.value.filter((agent) => !agent.archived_at).sort((a, b) => a.display_name.localeCompare(b.display_name)) : null,
32 };
33}
34
35/** The list changes when an agent is made or changed, or work is stopped or started; not when moving between them. */
36export function shouldRevalidate({ currentParams, nextParams, formMethod, defaultShouldRevalidate }: ShouldRevalidateFunctionArgs) {
37 if (formMethod && formMethod !== "GET") return defaultShouldRevalidate;
38 return currentParams.owner !== nextParams.owner;
39}
40
41export default function AgentsLayout({ loaderData }: Route.ComponentProps) {
42 const root = useRouteLoaderData("root") as { user?: { workspaces?: { slug: string; role: string; code_access?: boolean }[] } | null } | undefined;
43 const membership = root?.user?.workspaces?.find((m) => m.slug === loaderData.slug) ?? null;
44 // A phone: the agents first, as a list; the fleet's numbers under it.
45 const index = useMatch("/:owner/-/agents");
46 return (
47 <>
48 {index && (
49 <div className="-mx-4 -mt-6 mb-8 md:hidden">
50 <AgentsSidebar slug={loaderData.slug} shellAgents={null} code={hasCodeAccess(membership)} owner={membership?.role === "owner"} phone />
51 </div>
52 )}
53 <Outlet />
54 </>
55 );
56}