diff --git a/desktop/src/features/agents/hooks.ts b/desktop/src/features/agents/hooks.ts index 0fdb599d13..b3500b55df 100644 --- a/desktop/src/features/agents/hooks.ts +++ b/desktop/src/features/agents/hooks.ts @@ -38,6 +38,7 @@ import { import type { AgentPersona, AgentTeam, + ChannelMember, CreateManagedAgentInput, CreatePersonaInput, CreateTeamInput, @@ -46,6 +47,7 @@ import type { UpdatePersonaInput, UpdateTeamInput, } from "@/shared/api/types"; +import { normalizePubkey } from "@/shared/lib/pubkey"; import type { AttachManagedAgentToChannelInput, AttachManagedAgentToChannelResult, @@ -356,6 +358,29 @@ export function useAttachManagedAgentToChannelMutation( return attachManagedAgentToChannel(channelId, input); }, + onMutate: async (input) => { + if (!channelId) return; + const membersKey = ["channels", channelId, "members"]; + await queryClient.cancelQueries({ queryKey: membersKey }); + const previous = + queryClient.getQueryData(membersKey) ?? []; + const optimistic: ChannelMember = { + pubkey: normalizePubkey(input.agent.pubkey), + role: input.role ?? "bot", + joinedAt: new Date().toISOString(), + displayName: input.agent.name, + }; + queryClient.setQueryData(membersKey, [ + ...previous, + optimistic, + ]); + return { previous, membersKey }; + }, + onError: (_err, _vars, context) => { + if (context?.membersKey) { + queryClient.setQueryData(context.membersKey, context.previous); + } + }, onSettled: async () => { await invalidateAgentQueries(queryClient, channelId); }, @@ -394,6 +419,27 @@ export function useCreateChannelManagedAgentMutation(channelId: string | null) { return createChannelManagedAgent(channelId, input); }, + onSuccess: (result) => { + if (!channelId) return; + const membersKey = ["channels", channelId, "members"]; + const current = + queryClient.getQueryData(membersKey) ?? []; + const alreadyPresent = current.some( + (m) => + normalizePubkey(m.pubkey) === normalizePubkey(result.agent.pubkey), + ); + if (!alreadyPresent) { + queryClient.setQueryData(membersKey, [ + ...current, + { + pubkey: normalizePubkey(result.agent.pubkey), + role: "bot", + joinedAt: new Date().toISOString(), + displayName: result.agent.name, + }, + ]); + } + }, onSettled: async () => { await invalidateAgentQueries(queryClient, channelId); }, @@ -415,6 +461,29 @@ export function useCreateChannelManagedAgentsMutation( return createChannelManagedAgents(channelId, inputs); }, + onSuccess: (result) => { + if (!channelId) return; + const membersKey = ["channels", channelId, "members"]; + const current = + queryClient.getQueryData(membersKey) ?? []; + const existingPubkeys = new Set( + current.map((m) => normalizePubkey(m.pubkey)), + ); + const newMembers: ChannelMember[] = result.successes + .filter((s) => !existingPubkeys.has(normalizePubkey(s.agent.pubkey))) + .map((s) => ({ + pubkey: normalizePubkey(s.agent.pubkey), + role: "bot" as const, + joinedAt: new Date().toISOString(), + displayName: s.agent.name, + })); + if (newMembers.length > 0) { + queryClient.setQueryData(membersKey, [ + ...current, + ...newMembers, + ]); + } + }, onSettled: async () => { await invalidateAgentQueries(queryClient, channelId); }, diff --git a/desktop/src/features/channels/ui/QuickAddAgentItemRow.tsx b/desktop/src/features/channels/ui/QuickAddAgentItemRow.tsx new file mode 100644 index 0000000000..8ad02493b9 --- /dev/null +++ b/desktop/src/features/channels/ui/QuickAddAgentItemRow.tsx @@ -0,0 +1,152 @@ +import { Check, X } from "lucide-react"; +import { motion } from "motion/react"; +import * as React from "react"; + +import { rewriteRelayUrl } from "@/shared/lib/mediaUrl"; +import { cn } from "@/shared/lib/cn"; +import { Spinner } from "@/shared/ui/spinner"; +import type { QuickAddAgentItem } from "./useQuickAddAgentItems"; + +// ── Avatar ──────────────────────────────────────────────────────────────────── + +export function QuickAddAgentAvatar({ + avatarUrl, + label, + isRunning, +}: { + avatarUrl: string | null; + label: string; + isRunning: boolean; +}) { + const initials = label + .split(" ") + .map((part) => part[0]) + .join("") + .slice(0, 2) + .toUpperCase(); + + return ( +
+ {avatarUrl ? ( + {label} + ) : ( + + {initials} + + )} + {isRunning ? ( + + ) : null} +
+ ); +} + +// ── Item Row ────────────────────────────────────────────────────────────────── + +type QuickAddAgentItemRowProps = { + item: QuickAddAgentItem; + itemKey: string; + isSelected: boolean; + isPending: boolean; + selectMode: boolean; + disabled: boolean; + onClick: () => void; + onRemove: (pubkey: string) => void; +}; + +export const QuickAddAgentItemRow = React.memo(function QuickAddAgentItemRow({ + item, + itemKey, + isSelected, + isPending, + selectMode, + disabled, + onClick, + onRemove, +}: QuickAddAgentItemRowProps) { + const isInChannel = item.kind === "running-in-channel"; + + return ( + + + ) : null} + {isPending ? ( + + ) : null} + + + + ); +}); diff --git a/desktop/src/features/channels/ui/QuickAddAgentPopover.tsx b/desktop/src/features/channels/ui/QuickAddAgentPopover.tsx index 882dd759be..99d37933ec 100644 --- a/desktop/src/features/channels/ui/QuickAddAgentPopover.tsx +++ b/desktop/src/features/channels/ui/QuickAddAgentPopover.tsx @@ -1,63 +1,16 @@ -import { Check, Settings2, X } from "lucide-react"; +import { Settings2 } from "lucide-react"; import { AnimatePresence, motion } from "motion/react"; import * as React from "react"; -import { - useAcpProvidersQuery, - useAttachManagedAgentToChannelMutation, - useCreateChannelManagedAgentMutation, - useCreateChannelManagedAgentsMutation, - useManagedAgentsQuery, - usePersonasQuery, - useTeamsQuery, -} from "@/features/agents/hooks"; import { Toggle } from "@/shared/ui/toggle"; -import { useChannelMembersQuery, useRemoveChannelMemberMutation } from "@/features/channels/hooks"; -import { getActivePersonas } from "@/features/agents/lib/catalog"; -import { resolvePersonaProvider } from "@/features/agents/lib/resolvePersonaProvider"; -import { pickBotName } from "@/features/agents/lib/pickBotName"; -import { useBotRecents } from "@/features/agents/lib/useBotRecents"; -import { - getUsableTeams, - resolveTeamPersonas, -} from "@/features/agents/lib/teamPersonas"; -import type { AgentPersona, AgentTeam, ManagedAgent } from "@/shared/api/types"; -import { normalizePubkey } from "@/shared/lib/pubkey"; -import { rewriteRelayUrl } from "@/shared/lib/mediaUrl"; -import { cn } from "@/shared/lib/cn"; import { Button } from "@/shared/ui/button"; import { Popover, PopoverContent, PopoverTrigger } from "@/shared/ui/popover"; import { Spinner } from "@/shared/ui/spinner"; +import { getItemKey, useQuickAddAgentItems } from "./useQuickAddAgentItems"; +import { useQuickAddAgentActions } from "./useQuickAddAgentActions"; +import { QuickAddAgentItemRow } from "./QuickAddAgentItemRow"; -// ── Types ───────────────────────────────────────────────────────────────────── - -type RunningAvailableItem = { - kind: "running-available"; - agent: ManagedAgent; - persona: AgentPersona | null; - label: string; - avatarUrl: string | null; -}; - -type RunningInChannelItem = { - kind: "running-in-channel"; - agent: ManagedAgent; - persona: AgentPersona | null; - label: string; - avatarUrl: string | null; -}; - -type PersonaItem = { - kind: "persona"; - persona: AgentPersona; - label: string; - avatarUrl: string | null; -}; - -type QuickAddAgentItem = - | RunningAvailableItem - | RunningInChannelItem - | PersonaItem; +// ── Component ───────────────────────────────────────────────────────────────── type QuickAddAgentPopoverProps = { channelId: string | null; @@ -67,27 +20,6 @@ type QuickAddAgentPopoverProps = { children: React.ReactNode; }; -// ── Helpers ─────────────────────────────────────────────────────────────────── - -function getItemKey(item: QuickAddAgentItem): string { - switch (item.kind) { - case "persona": - return `persona:${item.persona.id}`; - case "running-available": - case "running-in-channel": - return `agent:${item.agent.pubkey}`; - } -} - -function safeBotName(persona: AgentPersona, usedNames: Set): string { - const pool = persona.namePool ?? []; - const name = pickBotName(pool, usedNames); - if (name && name.trim().length > 0) return name; - return persona.displayName || "Agent"; -} - -// ── Component ───────────────────────────────────────────────────────────────── - export function QuickAddAgentPopover({ channelId, open, @@ -95,393 +27,45 @@ export function QuickAddAgentPopover({ onMoreOptions, children, }: QuickAddAgentPopoverProps) { - const managedAgentsQuery = useManagedAgentsQuery(); - const personasQuery = usePersonasQuery(); - const providersQuery = useAcpProvidersQuery(); - const teamsQuery = useTeamsQuery(); - const membersQuery = useChannelMembersQuery( + const { + items, + isLoading, + managedAgents, + personas, + providers, + defaultProvider, + usableTeams, + pushRecent, + } = useQuickAddAgentItems(channelId, open && channelId !== null); + + const { + pendingKey, + errorMessage, + selectMode, + setSelectMode, + selectedKeys, + selectedTeamIds, + reset, + handleCancelSelect, + handleTeamToggle, + handleBatchAdd, + handleItemClick, + removeMutation, + } = useQuickAddAgentActions({ channelId, - open && channelId !== null, - ); - const attachMutation = useAttachManagedAgentToChannelMutation(channelId); - const createMutation = useCreateChannelManagedAgentMutation(channelId); - const batchCreateMutation = useCreateChannelManagedAgentsMutation(channelId); - const removeMutation = useRemoveChannelMemberMutation(channelId); - const { recentIds, pushRecent } = useBotRecents(); - - const [pendingKey, setPendingKey] = React.useState(null); - const [errorMessage, setErrorMessage] = React.useState(null); - const [selectMode, setSelectMode] = React.useState(false); - const [selectedKeys, setSelectedKeys] = React.useState>( - new Set(), - ); - const [selectedTeamIds, setSelectedTeamIds] = React.useState>( - new Set(), - ); - - const managedAgents = managedAgentsQuery.data ?? []; - const personas = React.useMemo( - () => getActivePersonas(personasQuery.data ?? []), - [personasQuery.data], - ); - const providers = providersQuery.data ?? []; - const defaultProvider = providers[0] ?? null; - const members = membersQuery.data ?? []; - const teams = teamsQuery.data ?? []; - - const channelMemberPubkeys = React.useMemo( - () => new Set(members.map((m) => normalizePubkey(m.pubkey))), - [members], - ); - - const usableTeams = React.useMemo( - () => getUsableTeams(teams, personas), - [teams, personas], - ); - - // Build the sorted item list - const items: QuickAddAgentItem[] = React.useMemo(() => { - const result: QuickAddAgentItem[] = []; - - const runningAvailable = managedAgents.filter( - (agent) => - (agent.status === "running" || agent.status === "deployed") && - !channelMemberPubkeys.has(normalizePubkey(agent.pubkey)), - ); - - const runningInChannel = managedAgents.filter( - (agent) => - (agent.status === "running" || agent.status === "deployed") && - channelMemberPubkeys.has(normalizePubkey(agent.pubkey)), - ); - - const personaIdsInChannel = new Set( - managedAgents - .filter((agent) => - channelMemberPubkeys.has(normalizePubkey(agent.pubkey)), - ) - .map((agent) => agent.personaId) - .filter((id): id is string => Boolean(id)), - ); - - const availablePersonas = personas.filter( - (persona) => - !personaIdsInChannel.has(persona.id) && - !runningAvailable.some((agent) => agent.personaId === persona.id), - ); - - const sortedRunningAvailable = [...runningAvailable].sort((a, b) => { - const aPersonaIdx = a.personaId ? recentIds.indexOf(a.personaId) : -1; - const bPersonaIdx = b.personaId ? recentIds.indexOf(b.personaId) : -1; - const aScore = aPersonaIdx >= 0 ? aPersonaIdx : 999; - const bScore = bPersonaIdx >= 0 ? bPersonaIdx : 999; - return aScore - bScore; - }); - - for (const agent of runningInChannel) { - const persona = agent.personaId - ? (personas.find((p) => p.id === agent.personaId) ?? null) - : null; - result.push({ - kind: "running-in-channel", - agent, - persona, - label: agent.name, - avatarUrl: persona?.avatarUrl ?? null, - }); - } - - for (const agent of sortedRunningAvailable) { - const persona = agent.personaId - ? (personas.find((p) => p.id === agent.personaId) ?? null) - : null; - result.push({ - kind: "running-available", - agent, - persona, - label: agent.name, - avatarUrl: persona?.avatarUrl ?? null, - }); - } - - const sortedPersonas = [...availablePersonas].sort((a, b) => { - const aIdx = recentIds.indexOf(a.id); - const bIdx = recentIds.indexOf(b.id); - if (aIdx >= 0 && bIdx >= 0) return aIdx - bIdx; - if (aIdx >= 0) return -1; - if (bIdx >= 0) return 1; - return a.displayName.localeCompare(b.displayName); - }); - - for (const persona of sortedPersonas) { - result.push({ - kind: "persona", - persona, - label: persona.displayName, - avatarUrl: persona.avatarUrl, - }); - } - - return result; - }, [managedAgents, personas, channelMemberPubkeys, recentIds]); - + items, + managedAgents, + personas, + providers, + defaultProvider, + usableTeams, + pushRecent, + }); // Reset state when popover closes React.useEffect(() => { - if (!open) { - setPendingKey(null); - setErrorMessage(null); - setSelectMode(false); - setSelectedKeys(new Set()); - setSelectedTeamIds(new Set()); - } - }, [open]); - - // ── Single-add handlers ─────────────────────────────────────────────────── - - async function handleAddRunningAgent(agent: ManagedAgent) { - if (!channelId) return; - const key = `agent:${agent.pubkey}`; - setPendingKey(key); - setErrorMessage(null); - - try { - await attachMutation.mutateAsync({ agent, ensureRunning: true }); - if (agent.personaId) pushRecent(agent.personaId); - setPendingKey(null); - } catch (err) { - setErrorMessage( - err instanceof Error ? err.message : "Failed to add agent.", - ); - setPendingKey(null); - } - } - - async function handleAddPersona(persona: AgentPersona) { - if (!channelId) return; - const key = `persona:${persona.id}`; - setPendingKey(key); - setErrorMessage(null); - - const { provider } = resolvePersonaProvider( - persona.provider, - providers, - defaultProvider, - ); - - if (!provider) { - setErrorMessage("No agent runtime available."); - setPendingKey(null); - return; - } - - const usedNames = new Set(managedAgents.map((a) => a.name)); - const instanceName = safeBotName(persona, usedNames); - - try { - await createMutation.mutateAsync({ - provider, - name: instanceName, - systemPrompt: persona.systemPrompt, - avatarUrl: persona.avatarUrl ?? undefined, - personaId: persona.id, - model: persona.model ?? undefined, - }); - pushRecent(persona.id); - setPendingKey(null); - } catch (err) { - setErrorMessage( - err instanceof Error ? err.message : "Failed to add agent.", - ); - setPendingKey(null); - } - } - - // ── Multi-select handlers ───────────────────────────────────────────────── - - function handleCancelSelect() { - setSelectMode(false); - setSelectedKeys(new Set()); - setSelectedTeamIds(new Set()); - } - - function toggleSelection(key: string) { - setSelectedKeys((prev) => { - const next = new Set(prev); - if (next.has(key)) { - next.delete(key); - } else { - next.add(key); - } - - // Deselect any team whose members are no longer all selected - setSelectedTeamIds((prevTeams) => { - const nextTeams = new Set(prevTeams); - for (const team of usableTeams) { - if (!nextTeams.has(team.id)) continue; - const resolution = resolveTeamPersonas(team, personas); - const allSelected = resolution.resolvedPersonas.every((persona) => { - const runningItem = items.find( - (i) => i.kind === "running-available" && i.agent.personaId === persona.id, - ); - const itemKey = runningItem - ? getItemKey(runningItem) - : (() => { - const personaItem = items.find( - (i) => i.kind === "persona" && i.persona.id === persona.id, - ); - return personaItem ? getItemKey(personaItem) : null; - })(); - return itemKey ? next.has(itemKey) : true; - }); - if (!allSelected) { - nextTeams.delete(team.id); - } - } - return nextTeams; - }); - - return next; - }); - } - - function handleTeamToggle(team: AgentTeam, pressed: boolean) { - const resolution = resolveTeamPersonas(team, personas); - const memberKeys: string[] = []; - for (const persona of resolution.resolvedPersonas) { - const runningItem = items.find( - (i) => - i.kind === "running-available" && i.agent.personaId === persona.id, - ); - if (runningItem) { - memberKeys.push(getItemKey(runningItem)); - } else { - const personaItem = items.find( - (i) => i.kind === "persona" && i.persona.id === persona.id, - ); - if (personaItem) { - memberKeys.push(getItemKey(personaItem)); - } - } - } - - setSelectedTeamIds((prev) => { - const next = new Set(prev); - if (pressed) { - next.add(team.id); - } else { - next.delete(team.id); - } - return next; - }); - - setSelectedKeys((prev) => { - const next = new Set(prev); - if (pressed) { - for (const key of memberKeys) { - next.add(key); - } - } else { - for (const key of memberKeys) { - next.delete(key); - } - } - return next; - }); - } - - async function handleBatchAdd() { - if (!channelId || selectedKeys.size === 0) return; - setPendingKey("batch"); - setErrorMessage(null); - - const usedNames = new Set(managedAgents.map((a) => a.name)); - const toAttach: ManagedAgent[] = []; - const toCreate: Array<{ persona: AgentPersona; instanceName: string }> = []; - - for (const key of selectedKeys) { - const item = items.find((i) => getItemKey(i) === key); - if (!item || item.kind === "running-in-channel") continue; - - if (item.kind === "running-available") { - toAttach.push(item.agent); - } else { - const instanceName = safeBotName(item.persona, usedNames); - usedNames.add(instanceName); - toCreate.push({ persona: item.persona, instanceName }); - } - } - - try { - for (const agent of toAttach) { - await attachMutation.mutateAsync({ agent, ensureRunning: true }); - if (agent.personaId) pushRecent(agent.personaId); - } - - if (toCreate.length > 0 && defaultProvider) { - const inputs = toCreate.map(({ persona, instanceName }) => { - const { provider } = resolvePersonaProvider( - persona.provider, - providers, - defaultProvider, - ); - const providerToUse = provider ?? defaultProvider; - return { - provider: { - id: providerToUse.id, - label: providerToUse.label, - command: providerToUse.command, - defaultArgs: providerToUse.defaultArgs, - mcpCommand: providerToUse.mcpCommand, - }, - name: instanceName, - systemPrompt: persona.systemPrompt, - avatarUrl: persona.avatarUrl ?? undefined, - personaId: persona.id, - model: persona.model ?? undefined, - }; - }); - - await batchCreateMutation.mutateAsync(inputs); - for (const { persona } of toCreate) { - pushRecent(persona.id); - } - } - - setPendingKey(null); - setSelectMode(false); - setSelectedKeys(new Set()); - setSelectedTeamIds(new Set()); - } catch (err) { - setErrorMessage( - err instanceof Error ? err.message : "Failed to add agents.", - ); - setPendingKey(null); - } - } - - // ── Item click dispatcher ───────────────────────────────────────────────── - - function handleItemClick(item: QuickAddAgentItem) { - if (item.kind === "running-in-channel") return; - if (pendingKey) return; - if (!channelId) return; - - if (selectMode) { - toggleSelection(getItemKey(item)); - } else { - if (item.kind === "running-available") { - void handleAddRunningAgent(item.agent); - } else { - void handleAddPersona(item.persona); - } - } - } - - const isLoading = - managedAgentsQuery.isLoading || - personasQuery.isLoading || - providersQuery.isLoading; + if (!open) reset(); + }, [open, reset]); const multiSelectActive = selectMode && selectedKeys.size > 0; @@ -497,9 +81,11 @@ export function QuickAddAgentPopover({ className="w-72 overflow-hidden p-0" sideOffset={6} > + {/* biome-ignore lint/a11y/useSemanticElements: composite widget with roving focus */}
{ const container = e.currentTarget; const buttons = Array.from( @@ -524,23 +110,18 @@ export function QuickAddAgentPopover({ } }} > - {/* Header with animated title / team toggles */} {/* Header */}

Add agent

- {usableTeams.length > 0 ? (
- {/* Team toggles row — always mounted, height animates based on selectMode */} + {/* Team toggles row */} ))}
- {/* Gradient fade on right edge — scroll affordance */}
- {/* Scrollable content — clips mid-item to hint at more */} + {/* Scrollable content */} {items.map((item) => { const itemKey = getItemKey(item); - const isInChannel = item.kind === "running-in-channel"; - const isItemPending = - pendingKey === itemKey || pendingKey === "batch"; - const isSelected = selectedKeys.has(itemKey); - return ( - - - ) : null} - {isItemPending ? ( - - ) : null} -
- - + onRemove={(pubkey) => removeMutation.mutate(pubkey)} + /> ); })} @@ -751,42 +272,3 @@ export function QuickAddAgentPopover({ ); } - -// ── Avatar helper ───────────────────────────────────────────────────────────── - -function QuickAddAgentAvatar({ - avatarUrl, - label, - isRunning, -}: { - avatarUrl: string | null; - label: string; - isRunning: boolean; -}) { - const initials = label - .split(" ") - .map((part) => part[0]) - .join("") - .slice(0, 2) - .toUpperCase(); - - return ( -
- {avatarUrl ? ( - {label} - ) : ( - - {initials} - - )} - {isRunning ? ( - - ) : null} -
- ); -} diff --git a/desktop/src/features/channels/ui/useQuickAddAgentActions.ts b/desktop/src/features/channels/ui/useQuickAddAgentActions.ts new file mode 100644 index 0000000000..e969e3545f --- /dev/null +++ b/desktop/src/features/channels/ui/useQuickAddAgentActions.ts @@ -0,0 +1,294 @@ +import * as React from "react"; + +import { + useAttachManagedAgentToChannelMutation, + useCreateChannelManagedAgentMutation, + useCreateChannelManagedAgentsMutation, +} from "@/features/agents/hooks"; +import { useRemoveChannelMemberMutation } from "@/features/channels/hooks"; +import { resolvePersonaProvider } from "@/features/agents/lib/resolvePersonaProvider"; +import { pickBotName } from "@/features/agents/lib/pickBotName"; +import { resolveTeamPersonas } from "@/features/agents/lib/teamPersonas"; +import type { + AcpProvider, + AgentPersona, + AgentTeam, + ManagedAgent, +} from "@/shared/api/types"; +import { getItemKey, type QuickAddAgentItem } from "./useQuickAddAgentItems"; + +function safeBotName(persona: AgentPersona, usedNames: Set): string { + const pool = persona.namePool ?? []; + const name = pickBotName(pool, usedNames); + if (name && name.trim().length > 0) return name; + return persona.displayName || "Agent"; +} + +type UseQuickAddAgentActionsParams = { + channelId: string | null; + items: QuickAddAgentItem[]; + managedAgents: ManagedAgent[]; + personas: AgentPersona[]; + providers: AcpProvider[]; + defaultProvider: AcpProvider | null; + usableTeams: AgentTeam[]; + pushRecent: (personaId: string) => void; +}; + +export function useQuickAddAgentActions({ + channelId, + items, + managedAgents, + personas, + providers, + defaultProvider, + usableTeams, + pushRecent, +}: UseQuickAddAgentActionsParams) { + const attachMutation = useAttachManagedAgentToChannelMutation(channelId); + const createMutation = useCreateChannelManagedAgentMutation(channelId); + const batchCreateMutation = useCreateChannelManagedAgentsMutation(channelId); + const removeMutation = useRemoveChannelMemberMutation(channelId); + + const [pendingKey, setPendingKey] = React.useState(null); + const [errorMessage, setErrorMessage] = React.useState(null); + const [selectMode, setSelectMode] = React.useState(false); + const [selectedKeys, setSelectedKeys] = React.useState>( + new Set(), + ); + const [selectedTeamIds, setSelectedTeamIds] = React.useState>( + new Set(), + ); + + // Reset state when popover closes (caller should pass `open`) + const reset = React.useCallback(() => { + setPendingKey(null); + setErrorMessage(null); + setSelectMode(false); + setSelectedKeys(new Set()); + setSelectedTeamIds(new Set()); + }, []); + + // ── Single-add handlers ───────────────────────────────────────────────── + + async function handleAddRunningAgent(agent: ManagedAgent) { + if (!channelId) return; + const key = `agent:${agent.pubkey}`; + setPendingKey(key); + setErrorMessage(null); + try { + await attachMutation.mutateAsync({ agent, ensureRunning: true }); + if (agent.personaId) pushRecent(agent.personaId); + setPendingKey(null); + } catch (err) { + setErrorMessage( + err instanceof Error ? err.message : "Failed to add agent.", + ); + setPendingKey(null); + } + } + + async function handleAddPersona(persona: AgentPersona) { + if (!channelId) return; + const key = `persona:${persona.id}`; + setPendingKey(key); + setErrorMessage(null); + const { provider } = resolvePersonaProvider( + persona.provider, + providers, + defaultProvider, + ); + if (!provider) { + setErrorMessage("No agent runtime available."); + setPendingKey(null); + return; + } + const usedNames = new Set(managedAgents.map((a) => a.name)); + const instanceName = safeBotName(persona, usedNames); + try { + await createMutation.mutateAsync({ + provider, + name: instanceName, + systemPrompt: persona.systemPrompt, + avatarUrl: persona.avatarUrl ?? undefined, + personaId: persona.id, + model: persona.model ?? undefined, + }); + pushRecent(persona.id); + setPendingKey(null); + } catch (err) { + setErrorMessage( + err instanceof Error ? err.message : "Failed to add agent.", + ); + setPendingKey(null); + } + } + + // ── Multi-select handlers ─────────────────────────────────────────────── + + function handleCancelSelect() { + setSelectMode(false); + setSelectedKeys(new Set()); + setSelectedTeamIds(new Set()); + } + + function toggleSelection(key: string) { + setSelectedKeys((prev) => { + const next = new Set(prev); + if (next.has(key)) { + next.delete(key); + } else { + next.add(key); + } + setSelectedTeamIds((prevTeams) => { + const nextTeams = new Set(prevTeams); + for (const team of usableTeams) { + if (!nextTeams.has(team.id)) continue; + const resolution = resolveTeamPersonas(team, personas); + const allSelected = resolution.resolvedPersonas.every((p) => { + const runningItem = items.find( + (i) => + i.kind === "running-available" && i.agent.personaId === p.id, + ); + const ik = runningItem + ? getItemKey(runningItem) + : (() => { + const pi = items.find( + (i) => i.kind === "persona" && i.persona.id === p.id, + ); + return pi ? getItemKey(pi) : null; + })(); + return ik ? next.has(ik) : true; + }); + if (!allSelected) nextTeams.delete(team.id); + } + return nextTeams; + }); + return next; + }); + } + + function handleTeamToggle(team: AgentTeam, pressed: boolean) { + const resolution = resolveTeamPersonas(team, personas); + const memberKeys: string[] = []; + for (const persona of resolution.resolvedPersonas) { + const runningItem = items.find( + (i) => + i.kind === "running-available" && i.agent.personaId === persona.id, + ); + if (runningItem) { + memberKeys.push(getItemKey(runningItem)); + } else { + const personaItem = items.find( + (i) => i.kind === "persona" && i.persona.id === persona.id, + ); + if (personaItem) memberKeys.push(getItemKey(personaItem)); + } + } + setSelectedTeamIds((prev) => { + const next = new Set(prev); + if (pressed) next.add(team.id); + else next.delete(team.id); + return next; + }); + setSelectedKeys((prev) => { + const next = new Set(prev); + for (const key of memberKeys) { + if (pressed) next.add(key); + else next.delete(key); + } + return next; + }); + } + + async function handleBatchAdd() { + if (!channelId || selectedKeys.size === 0) return; + setPendingKey("batch"); + setErrorMessage(null); + const usedNames = new Set(managedAgents.map((a) => a.name)); + const toAttach: ManagedAgent[] = []; + const toCreate: Array<{ persona: AgentPersona; instanceName: string }> = []; + for (const key of selectedKeys) { + const item = items.find((i) => getItemKey(i) === key); + if (!item || item.kind === "running-in-channel") continue; + if (item.kind === "running-available") { + toAttach.push(item.agent); + } else { + const instanceName = safeBotName(item.persona, usedNames); + usedNames.add(instanceName); + toCreate.push({ persona: item.persona, instanceName }); + } + } + try { + for (const agent of toAttach) { + await attachMutation.mutateAsync({ agent, ensureRunning: true }); + if (agent.personaId) pushRecent(agent.personaId); + } + if (toCreate.length > 0 && defaultProvider) { + const inputs = toCreate.map(({ persona, instanceName }) => { + const { provider } = resolvePersonaProvider( + persona.provider, + providers, + defaultProvider, + ); + const providerToUse = provider ?? defaultProvider; + return { + provider: { + id: providerToUse.id, + label: providerToUse.label, + command: providerToUse.command, + defaultArgs: providerToUse.defaultArgs, + mcpCommand: providerToUse.mcpCommand, + }, + name: instanceName, + systemPrompt: persona.systemPrompt, + avatarUrl: persona.avatarUrl ?? undefined, + personaId: persona.id, + model: persona.model ?? undefined, + }; + }); + await batchCreateMutation.mutateAsync(inputs); + for (const { persona } of toCreate) pushRecent(persona.id); + } + setPendingKey(null); + setSelectMode(false); + setSelectedKeys(new Set()); + setSelectedTeamIds(new Set()); + } catch (err) { + setErrorMessage( + err instanceof Error ? err.message : "Failed to add agents.", + ); + setPendingKey(null); + } + } + + // ── Item click dispatcher ─────────────────────────────────────────────── + + function handleItemClick(item: QuickAddAgentItem) { + if (item.kind === "running-in-channel") return; + if (pendingKey) return; + if (!channelId) return; + if (selectMode) { + toggleSelection(getItemKey(item)); + } else if (item.kind === "running-available") { + void handleAddRunningAgent(item.agent); + } else { + void handleAddPersona(item.persona); + } + } + + return { + pendingKey, + errorMessage, + selectMode, + setSelectMode, + selectedKeys, + selectedTeamIds, + reset, + handleCancelSelect, + handleTeamToggle, + handleBatchAdd, + handleItemClick, + removeMutation, + }; +} diff --git a/desktop/src/features/channels/ui/useQuickAddAgentItems.ts b/desktop/src/features/channels/ui/useQuickAddAgentItems.ts new file mode 100644 index 0000000000..b258456391 --- /dev/null +++ b/desktop/src/features/channels/ui/useQuickAddAgentItems.ts @@ -0,0 +1,213 @@ +import * as React from "react"; + +import { + useAcpProvidersQuery, + useManagedAgentsQuery, + usePersonasQuery, + useTeamsQuery, +} from "@/features/agents/hooks"; +import { useChannelMembersQuery } from "@/features/channels/hooks"; +import { getActivePersonas } from "@/features/agents/lib/catalog"; +import { useBotRecents } from "@/features/agents/lib/useBotRecents"; +import { + getUsableTeams, + resolveTeamPersonas, +} from "@/features/agents/lib/teamPersonas"; +import type { AgentPersona, ManagedAgent } from "@/shared/api/types"; +import { normalizePubkey } from "@/shared/lib/pubkey"; + +// ── Types ───────────────────────────────────────────────────────────────────── + +export type RunningAvailableItem = { + kind: "running-available"; + agent: ManagedAgent; + persona: AgentPersona | null; + label: string; + avatarUrl: string | null; +}; + +export type RunningInChannelItem = { + kind: "running-in-channel"; + agent: ManagedAgent; + persona: AgentPersona | null; + label: string; + avatarUrl: string | null; +}; + +export type PersonaItem = { + kind: "persona"; + persona: AgentPersona; + label: string; + avatarUrl: string | null; +}; + +export type QuickAddAgentItem = + | RunningAvailableItem + | RunningInChannelItem + | PersonaItem; + +// ── Helpers ─────────────────────────────────────────────────────────────────── + +export function getItemKey(item: QuickAddAgentItem): string { + switch (item.kind) { + case "persona": + return `persona:${item.persona.id}`; + case "running-available": + case "running-in-channel": + return `agent:${item.agent.pubkey}`; + } +} + +// ── Hook ────────────────────────────────────────────────────────────────────── + +export function useQuickAddAgentItems( + channelId: string | null, + enabled: boolean, +) { + const managedAgentsQuery = useManagedAgentsQuery(); + const personasQuery = usePersonasQuery(); + const providersQuery = useAcpProvidersQuery(); + const teamsQuery = useTeamsQuery(); + const membersQuery = useChannelMembersQuery(channelId, enabled); + const { recentIds, pushRecent } = useBotRecents(); + + const managedAgents = managedAgentsQuery.data ?? []; + const personas = React.useMemo( + () => getActivePersonas(personasQuery.data ?? []), + [personasQuery.data], + ); + const providers = providersQuery.data ?? []; + const defaultProvider = providers[0] ?? null; + const members = membersQuery.data ?? []; + const teams = teamsQuery.data ?? []; + + const channelMemberPubkeys = React.useMemo( + () => new Set(members.map((m) => normalizePubkey(m.pubkey))), + [members], + ); + + const usableTeams = React.useMemo(() => { + const allUsable = getUsableTeams(teams, personas); + // Filter out teams whose members are ALL already in the channel + return allUsable.filter((team) => { + const resolution = resolveTeamPersonas(team, personas); + return resolution.resolvedPersonas.some((persona) => { + // Check if this persona has a running agent not in channel, or no agent at all + const runningAgent = managedAgents.find( + (a) => + a.personaId === persona.id && + (a.status === "running" || a.status === "deployed"), + ); + if (runningAgent) { + return !channelMemberPubkeys.has( + normalizePubkey(runningAgent.pubkey), + ); + } + // Persona has no running agent — it's addable (will create new) + return true; + }); + }); + }, [teams, personas, managedAgents, channelMemberPubkeys]); + + const items: QuickAddAgentItem[] = React.useMemo(() => { + const result: QuickAddAgentItem[] = []; + + const runningAvailable = managedAgents.filter( + (agent) => + (agent.status === "running" || agent.status === "deployed") && + !channelMemberPubkeys.has(normalizePubkey(agent.pubkey)), + ); + + const runningInChannel = managedAgents.filter( + (agent) => + (agent.status === "running" || agent.status === "deployed") && + channelMemberPubkeys.has(normalizePubkey(agent.pubkey)), + ); + + const personaIdsInChannel = new Set( + managedAgents + .filter((agent) => + channelMemberPubkeys.has(normalizePubkey(agent.pubkey)), + ) + .map((agent) => agent.personaId) + .filter((id): id is string => Boolean(id)), + ); + + const availablePersonas = personas.filter( + (persona) => + !personaIdsInChannel.has(persona.id) && + !runningAvailable.some((agent) => agent.personaId === persona.id), + ); + + const sortedRunningAvailable = [...runningAvailable].sort((a, b) => { + const aPersonaIdx = a.personaId ? recentIds.indexOf(a.personaId) : -1; + const bPersonaIdx = b.personaId ? recentIds.indexOf(b.personaId) : -1; + const aScore = aPersonaIdx >= 0 ? aPersonaIdx : 999; + const bScore = bPersonaIdx >= 0 ? bPersonaIdx : 999; + return aScore - bScore; + }); + + for (const agent of runningInChannel) { + const persona = agent.personaId + ? (personas.find((p) => p.id === agent.personaId) ?? null) + : null; + result.push({ + kind: "running-in-channel", + agent, + persona, + label: agent.name, + avatarUrl: persona?.avatarUrl ?? null, + }); + } + + for (const agent of sortedRunningAvailable) { + const persona = agent.personaId + ? (personas.find((p) => p.id === agent.personaId) ?? null) + : null; + result.push({ + kind: "running-available", + agent, + persona, + label: agent.name, + avatarUrl: persona?.avatarUrl ?? null, + }); + } + + const sortedPersonas = [...availablePersonas].sort((a, b) => { + const aIdx = recentIds.indexOf(a.id); + const bIdx = recentIds.indexOf(b.id); + if (aIdx >= 0 && bIdx >= 0) return aIdx - bIdx; + if (aIdx >= 0) return -1; + if (bIdx >= 0) return 1; + return a.displayName.localeCompare(b.displayName); + }); + + for (const persona of sortedPersonas) { + result.push({ + kind: "persona", + persona, + label: persona.displayName, + avatarUrl: persona.avatarUrl, + }); + } + + return result; + }, [managedAgents, personas, channelMemberPubkeys, recentIds]); + + const isLoading = + managedAgentsQuery.isLoading || + personasQuery.isLoading || + providersQuery.isLoading; + + return { + items, + isLoading, + managedAgents, + personas, + providers, + defaultProvider, + usableTeams, + teamsQuery, + pushRecent, + }; +}