import { usePrimaryAgentPresentation } from "@/components/primary-agent/PrimaryAgentPresentation"; import { isWaitingToStart } from "../lib/agent-queue-wait"; import { AgentAvatar } from "@/components/AgentAvatar"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { Link, useLocation } from "@/lib/router"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { MoreHorizontal, Loader2, LogOut, PauseCircle, Pencil, PlayCircle, Plus, Star, Users, AlertTriangle, } from "lucide-react"; import { useCompany } from "../context/CompanyContext"; import { useDialogActions } from "../context/DialogContext"; import { useSidebar } from "../context/SidebarContext"; import { useToastActions } from "../context/ToastContext"; import { agentsApi } from "../api/agents"; import { builtInAgentsApi, type BuiltInAgentStatus } from "../api/builtInAgents"; import { BuiltInLifecycleChip } from "./BuiltInAgentBadges"; import { authApi } from "../api/auth"; import { heartbeatsApi } from "../api/heartbeats"; import { instanceSettingsApi } from "../api/instanceSettings"; import { SIDEBAR_SCROLL_RESET_STATE } from "../lib/navigation-scroll"; import { queryKeys } from "../lib/queryKeys"; import { cn, agentRouteRef, agentUrl } from "../lib/utils"; import { useAgentOrder } from "../hooks/useAgentOrder"; import { isStarred, resourceMembershipState, starredResourceIds, useResourceMembershipMutation, useResourceMemberships, } from "../hooks/useResourceMemberships"; import { usePublishSharedQueryData, useSharedPollingQuery } from "../hooks/useSharedPolling"; import { AGENT_SORT_MODE_UPDATED_EVENT, getAgentSortModeStorageKey, readAgentSortMode, type AgentSortModeUpdatedDetail, type AgentSidebarSortMode, writeAgentSortMode, } from "../lib/agent-order"; import { BudgetSidebarMarker } from "./BudgetSidebarMarker"; import { SidebarNavItem } from "./SidebarNavItem"; import { SidebarSection, type SidebarSectionRadioChoice } from "./SidebarSection"; import { StarToggle } from "./StarToggle"; import { Button } from "@/components/ui/button"; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu"; import type { Agent } from "@paperclipai/shared"; /** * When no agent is running, the sidebar falls back to showing at most this many * recently-active agents plus a "See all agents" link (IA Phase 5). */ const RECENT_AGENT_LIMIT = 3; const LIVE_AGENT_LINGER_MS = 120_000; const AGENT_SORT_CHOICES: SidebarSectionRadioChoice[] = [ { value: "top", label: "Top" }, { value: "alphabetical", label: "Alphabetical" }, { value: "recent", label: "Recent" }, ]; function agentTimestamp(agent: Agent, field: "lastHeartbeatAt" | "updatedAt" | "createdAt"): number { const raw = agent[field]; if (!raw) return 0; const time = new Date(raw).getTime(); return Number.isFinite(time) ? time : 0; } function sortAgents(agents: Agent[], sortMode: AgentSidebarSortMode): Agent[] { if (sortMode === "top") return agents; const sorted = [...agents]; if (sortMode === "alphabetical") { sorted.sort((left, right) => left.name.localeCompare(right.name, undefined, { sensitivity: "base" })); return sorted; } sorted.sort((left, right) => { const heartbeatDiff = agentTimestamp(right, "lastHeartbeatAt") - agentTimestamp(left, "lastHeartbeatAt"); if (heartbeatDiff !== 0) return heartbeatDiff; const updatedDiff = agentTimestamp(right, "updatedAt") - agentTimestamp(left, "updatedAt"); if (updatedDiff !== 0) return updatedDiff; const createdDiff = agentTimestamp(right, "createdAt") - agentTimestamp(left, "createdAt"); return createdDiff !== 0 ? createdDiff : left.name.localeCompare(right.name, undefined, { sensitivity: "base" }); }); return sorted; } // Sidebar star reveals with the agent row's own group, not the shared group. const AGENT_STAR_ROW_REVEAL = "opacity-0 transition-opacity group-hover/agent:opacity-100 group-focus-within/agent:opacity-100"; function SidebarAgentItem({ activeAgentId, activeTab, agent, disabled, isMobile, leaving, onLeaveAgent, onPauseResume, runCount, setSidebarOpen, builtInStatus, starred = false, onToggleStar, starPending = false, }: { activeAgentId: string | null; activeTab: string | null; agent: Agent; disabled: boolean; isMobile: boolean; leaving: boolean; onLeaveAgent: (agent: Agent) => void; onPauseResume: (agent: Agent, action: "pause" | "resume") => void; runCount: number; setSidebarOpen: (open: boolean) => void; builtInStatus?: BuiltInAgentStatus; starred?: boolean; onToggleStar?: (agent: Agent, starred: boolean) => void; starPending?: boolean; }) { const routeRef = agentRouteRef(agent); const href = activeTab ? `${agentUrl(agent)}/${activeTab}` : agentUrl(agent); const editHref = `${agentUrl(agent)}/configuration`; const isActive = activeAgentId === routeRef; const isPaused = agent.status === "paused"; const isBudgetPaused = isPaused && agent.pauseReason === "budget"; const hasInvalidOrgChain = agent.orgChainHealth?.status === "invalid_org_chain"; const pauseResumeLabel = isPaused ? "Resume agent" : "Pause agent"; const pauseResumeDisabled = disabled || agent.status === "pending_approval" || isBudgetPaused || (isPaused && hasInvalidOrgChain); const pauseResumeDisabledLabel = disabled ? "Updating..." : isBudgetPaused ? "Budget paused" : isPaused && hasInvalidOrgChain ? "Invalid org chain" : pauseResumeLabel; const showBuiltInLifecycle = builtInStatus === "needs_setup" || builtInStatus === "pending_approval"; const navItem = ( } active={isActive} liveCount={runCount} labelClassName={showBuiltInLifecycle ? "min-w-(--sz-4_5rem) flex-initial" : undefined} className={cn( "min-w-0 flex-1", // Reserve room for the hover ⋯ menu; starred rows widen it for the // inline unstar star. starred && !isMobile ? "pr-14" : "pr-8", )} trailing={ showBuiltInLifecycle || hasInvalidOrgChain ? ( {showBuiltInLifecycle ? : null} {hasInvalidOrgChain ? ( ) : null} ) : undefined } liveAccessory={ agent.pauseReason === "budget" ? : undefined } /> ); return (
{navItem} {starred && !isMobile && onToggleStar ? ( // Desktop: quiet inline unstar, left of the ⋯ menu, revealed on hover/focus. onToggleStar(agent, false)} revealClassName={AGENT_STAR_ROW_REVEAL} /> ) : null} {onToggleStar ? ( <> { if (starPending) return; onToggleStar(agent, !starred); }} disabled={starPending} > {starPending ? ( ) : ( )} {starred ? "Remove from starred" : "Star agent"} ) : null} { if (isMobile) setSidebarOpen(false); }} > Edit agent { if (pauseResumeDisabled) return; onPauseResume(agent, isPaused ? "resume" : "pause"); }} disabled={pauseResumeDisabled} title={isBudgetPaused ? "Agent was paused by budget limits" : undefined} > {isPaused ? : } {pauseResumeDisabledLabel} { if (leaving) return; onLeaveAgent(agent); }} disabled={leaving} > {leaving ? : } {leaving ? "Leaving..." : "Leave agent"}
); } export function SidebarAgents({ streamlined = false }: { streamlined?: boolean } = {}) { const [open, setOpen] = useState(true); const [pendingAgentIds, setPendingAgentIds] = useState>(() => new Set()); const [liveLingerVersion, setLiveLingerVersion] = useState(0); const lastSeenLiveAtRef = useRef>(new Map()); const queryClient = useQueryClient(); const { selectedCompanyId } = useCompany(); const primary = usePrimaryAgentPresentation(selectedCompanyId); const { openNewAgent } = useDialogActions(); const { isMobile, setSidebarOpen } = useSidebar(); const { pushToast } = useToastActions(); const location = useLocation(); const { data: agents } = useQuery({ queryKey: queryKeys.agents.list(selectedCompanyId!), queryFn: () => agentsApi.list(selectedCompanyId!), enabled: !!selectedCompanyId, }); const { data: experimentalSettings } = useQuery({ queryKey: queryKeys.instance.experimentalSettings, queryFn: () => instanceSettingsApi.getExperimental(), enabled: !!selectedCompanyId, }); const builtInAgentsEnabled = experimentalSettings?.enableBuiltInAgents === true; const { data: builtInAgents } = useQuery({ queryKey: queryKeys.builtInAgents.list(selectedCompanyId!), queryFn: () => builtInAgentsApi.list(selectedCompanyId!), enabled: !!selectedCompanyId && builtInAgentsEnabled, }); const builtInStatusByAgentId = useMemo(() => { const map = new Map(); if (!builtInAgentsEnabled) return map; for (const entry of builtInAgents ?? []) { if (entry.agentId) map.set(entry.agentId, entry.status); } return map; }, [builtInAgents, builtInAgentsEnabled]); const { data: session } = useQuery({ queryKey: queryKeys.auth.session, queryFn: () => authApi.getSession(), }); const membershipsQuery = useResourceMemberships(selectedCompanyId); const membershipMutation = useResourceMembershipMutation(selectedCompanyId); const liveRunsQueryKey = queryKeys.liveRuns(selectedCompanyId!); const sharedLiveRuns = useSharedPollingQuery({ companyId: selectedCompanyId, resourceKey: "live-runs", queryKey: liveRunsQueryKey, enabled: !!selectedCompanyId, // Event-sourced via LiveUpdatesProvider (issue 9627); no interval poll needed. refetchInterval: false, leaderOnly: true, }); const { data: liveRuns, dataUpdatedAt: liveRunsUpdatedAt } = useQuery({ queryKey: liveRunsQueryKey, queryFn: () => heartbeatsApi.liveRunsForCompany(selectedCompanyId!), enabled: sharedLiveRuns.enabled, refetchInterval: sharedLiveRuns.refetchInterval, }); usePublishSharedQueryData(sharedLiveRuns, liveRuns, liveRunsUpdatedAt); const liveCountByAgent = useMemo(() => { const counts = new Map(); // "N live" counts work that started; queued runs only wait for a slot. for (const run of liveRuns ?? []) { if (isWaitingToStart(run)) continue; counts.set(run.agentId, (counts.get(run.agentId) ?? 0) + 1); } return counts; }, [liveRuns]); const liveAgentIds = useMemo( () => new Set((liveRuns ?? []).map((run) => run.agentId)), [liveRuns], ); const visibleAgents = useMemo(() => { const filtered = (agents ?? []).filter( (a: Agent) => a.status !== "terminated" && ( !membershipsQuery.isSuccess || resourceMembershipState(membershipsQuery.data, "agent", a.id) !== "left" ) ); return filtered; }, [agents, membershipsQuery.data, membershipsQuery.isSuccess]); const currentUserId = session?.user?.id ?? session?.session?.userId ?? null; const sortModeStorageKey = useMemo(() => { if (!selectedCompanyId) return null; return getAgentSortModeStorageKey(selectedCompanyId, currentUserId); }, [currentUserId, selectedCompanyId]); const [sortMode, setSortMode] = useState(() => { if (!sortModeStorageKey) return "top"; return readAgentSortMode(sortModeStorageKey); }); const { orderedAgents } = useAgentOrder({ agents: visibleAgents, companyId: selectedCompanyId, userId: currentUserId, }); const sortedAgents = useMemo( () => sortAgents(orderedAgents, sortMode), [orderedAgents, sortMode], ); const sortedAgentIdSet = useMemo( () => new Set(sortedAgents.map((agent: Agent) => agent.id)), [sortedAgents], ); useEffect(() => { const now = Date.now(); for (const agentId of liveAgentIds) { lastSeenLiveAtRef.current.set(agentId, now); } for (const agentId of lastSeenLiveAtRef.current.keys()) { if (!sortedAgentIdSet.has(agentId)) { lastSeenLiveAtRef.current.delete(agentId); } } }, [liveAgentIds, sortedAgentIdSet]); // IA Phase 5 (streamlined): if any agent has a live run, show only those // active agents. Agents that just stopped running linger briefly so clustered // run boundaries do not make rows pop out and the section does not immediately // swap to the recent fallback during short all-idle gaps. Otherwise fall back // to up to RECENT_AGENT_LIMIT agents. Either way a "See all agents" link is // shown so the full list is always reachable. // Classic mode (PAP-89, flag OFF) restores the show-all behavior. const runningAgents = useMemo(() => { const nowForLiveLinger = Date.now(); const lastSeenLiveAtByAgent = lastSeenLiveAtRef.current; return sortedAgents.filter((agent: Agent) => { if ((liveCountByAgent.get(agent.id) ?? 0) > 0) return true; const lastSeenLiveAt = lastSeenLiveAtByAgent.get(agent.id); return lastSeenLiveAt !== undefined && nowForLiveLinger - lastSeenLiveAt <= LIVE_AGENT_LINGER_MS; }); }, [liveCountByAgent, liveLingerVersion, sortedAgents]); const hasActiveAgents = runningAgents.length > 0; const displayedAgents = !streamlined ? sortedAgents : hasActiveAgents ? runningAgents : sortedAgents.slice(0, RECENT_AGENT_LIMIT); // Always expose "See all agents" whenever the displayed list is a subset of all // agents, so users never lose the entry point to the full list. In classic mode // every agent is already shown, so the link is unnecessary. const showSeeAllLink = streamlined && sortedAgents.length > 0; const agentMatch = location.pathname.match(/^\/(?:[^/]+\/)?agents\/([^/]+)(?:\/([^/]+))?/); const activeAgentId = agentMatch?.[1] ?? null; const activeTab = agentMatch?.[2] ?? null; useEffect(() => { if (!sortModeStorageKey) { setSortMode("top"); return; } setSortMode(readAgentSortMode(sortModeStorageKey)); }, [sortModeStorageKey]); useEffect(() => { if (!sortModeStorageKey) return; const onStorage = (event: StorageEvent) => { if (event.key !== sortModeStorageKey) return; setSortMode(readAgentSortMode(sortModeStorageKey)); }; const onCustomEvent = (event: Event) => { const detail = (event as CustomEvent).detail; if (!detail || detail.storageKey !== sortModeStorageKey) return; setSortMode(detail.sortMode); }; window.addEventListener("storage", onStorage); window.addEventListener(AGENT_SORT_MODE_UPDATED_EVENT, onCustomEvent); return () => { window.removeEventListener("storage", onStorage); window.removeEventListener(AGENT_SORT_MODE_UPDATED_EVENT, onCustomEvent); }; }, [sortModeStorageKey]); useEffect(() => { if (!streamlined) return; const now = Date.now(); let nextExpiryAt: number | null = null; for (const agent of sortedAgents) { if ((liveCountByAgent.get(agent.id) ?? 0) > 0) continue; const lastSeenLiveAt = lastSeenLiveAtRef.current.get(agent.id); if (lastSeenLiveAt === undefined) continue; const expiresAt = lastSeenLiveAt + LIVE_AGENT_LINGER_MS; if (expiresAt < now) continue; nextExpiryAt = nextExpiryAt === null ? expiresAt : Math.min(nextExpiryAt, expiresAt); } if (nextExpiryAt === null) return; const timeoutId = window.setTimeout(() => { setLiveLingerVersion((version) => version + 1); }, Math.max(0, nextExpiryAt - now + 1)); return () => { window.clearTimeout(timeoutId); }; }, [streamlined, sortedAgents, liveCountByAgent, liveLingerVersion]); const persistSortMode = useCallback( (value: string) => { const nextSortMode: AgentSidebarSortMode = value === "alphabetical" || value === "recent" ? value : "top"; setSortMode(nextSortMode); if (sortModeStorageKey) { writeAgentSortMode(sortModeStorageKey, nextSortMode); } }, [sortModeStorageKey], ); const pauseResumeAgent = useMutation({ mutationFn: ({ agent, action }: { agent: Agent; action: "pause" | "resume" }) => action === "pause" ? agentsApi.pause(agent.id, selectedCompanyId ?? undefined) : agentsApi.resume(agent.id, selectedCompanyId ?? undefined), onMutate: ({ agent }) => { setPendingAgentIds((current) => { const next = new Set(current); next.add(agent.id); return next; }); }, onSuccess: async (_agent, { agent, action }) => { if (selectedCompanyId) { await Promise.all([ queryClient.invalidateQueries({ queryKey: queryKeys.agents.list(selectedCompanyId) }), queryClient.invalidateQueries({ queryKey: queryKeys.liveRuns(selectedCompanyId) }), queryClient.invalidateQueries({ queryKey: queryKeys.dashboard(selectedCompanyId) }), ]); } await Promise.all([ queryClient.invalidateQueries({ queryKey: queryKeys.agents.detail(agent.id) }), queryClient.invalidateQueries({ queryKey: queryKeys.agents.detail(agentRouteRef(agent)) }), ]); pushToast({ title: action === "pause" ? "Agent paused" : "Agent resumed", body: agent.name, tone: "success", }); }, onError: (error, { agent, action }) => { pushToast({ title: action === "pause" ? "Could not pause agent" : "Could not resume agent", body: error instanceof Error ? error.message : agent.name, tone: "error", }); }, onSettled: (_data, _error, { agent }) => { setPendingAgentIds((current) => { const next = new Set(current); next.delete(agent.id); return next; }); }, }); const leaveAgent = useCallback( (agent: Agent) => membershipMutation.mutate({ resourceType: "agent", resourceId: agent.id, resourceName: agent.name, state: "left", }), [membershipMutation], ); const agentLeaving = useCallback( (agent: Agent) => membershipMutation.isPending && membershipMutation.variables?.resourceType === "agent" && membershipMutation.variables.resourceId === agent.id, [membershipMutation.isPending, membershipMutation.variables], ); const toggleStarAgent = useCallback( (agent: Agent, starred: boolean) => membershipMutation.mutate({ resourceType: "agent", resourceId: agent.id, resourceName: agent.name, starred, }), [membershipMutation], ); const agentStarPending = useCallback( (agent: Agent) => membershipMutation.isPending && membershipMutation.variables?.resourceType === "agent" && membershipMutation.variables.resourceId === agent.id && membershipMutation.variables.starred !== undefined, [membershipMutation.isPending, membershipMutation.variables], ); // Starred agents pin to the top of the section (name order), and are deduped // out of the active/recent subset so no agent appears twice. const starredAgentIdSet = useMemo( () => new Set(starredResourceIds(membershipsQuery.data, "agent")), [membershipsQuery.data], ); const starredAgents = useMemo( () => sortAgents(visibleAgents.filter((agent: Agent) => starredAgentIdSet.has(agent.id)), "alphabetical"), [visibleAgents, starredAgentIdSet], ); const dedupedDisplayedAgents = useMemo( () => displayedAgents.filter((agent: Agent) => !starredAgentIdSet.has(agent.id)), [displayedAgents, starredAgentIdSet], ); const primaryAgent = primary && !primary.loading ? visibleAgents.find(agent => agent.id === primary.primaryAgentId) : undefined; const renderAgentRow = (agent: Agent, isStarredRow: boolean) => ( pauseResumeAgent.mutate({ agent: targetAgent, action })} runCount={liveCountByAgent.get(agent.id) ?? 0} setSidebarOpen={setSidebarOpen} builtInStatus={builtInStatusByAgentId.get(agent.id)} starred={isStarredRow || isStarred(membershipsQuery.data, "agent", agent.id)} onToggleStar={toggleStarAgent} starPending={agentStarPending(agent)} /> ); return ( {[ ...(primaryAgent ? [primaryAgent] : []), ...starredAgents.filter(agent => agent.id !== primaryAgent?.id), ...dedupedDisplayedAgents.filter(agent => agent.id !== primaryAgent?.id), ].map(agent => renderAgentRow(agent, starredAgentIdSet.has(agent.id)))} {showSeeAllLink && (() => { // Deliberately NOT a SidebarNavItem: this is a quiet muted affordance // (plain Link) that must not adopt nav-row active-route highlighting. return ( { if (isMobile) setSidebarOpen(false); }} className="flex items-center gap-2.5 mx-2 rounded-lg px-2 py-1.5 pointer-coarse:py-1 text-(length:--text-compact) font-medium text-muted-foreground transition-colors hover:bg-sidebar-accent hover:text-sidebar-accent-foreground" > See all agents ); })()} ); }