mirror of
https://github.com/block/buzz.git
synced 2026-11-24 18:21:59 +00:00
feat: optimistic member updates + decompose QuickAddAgentPopover
- Add optimistic onMutate to useAttachManagedAgentToChannelMutation (instant member insertion, rollback on error) - Add onSuccess cache-set to create/batch mutations (member appears as soon as server confirms, before invalidation round-trip) - Decompose QuickAddAgentPopover (816→271 lines) into: - useQuickAddAgentItems.ts (data fetching + item list building) - useQuickAddAgentActions.ts (handlers + multi-select state) - QuickAddAgentItemRow.tsx (memoized item row component) - Fix ARIA: remove conflicting role="menu" on container, add role="group" with aria-label for keyboard navigation wrapper - Fix dead team toggles: filter out teams whose members are all already in the channel
This commit is contained in:
@@ -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<ChannelMember[]>(membersKey) ?? [];
|
||||
const optimistic: ChannelMember = {
|
||||
pubkey: normalizePubkey(input.agent.pubkey),
|
||||
role: input.role ?? "bot",
|
||||
joinedAt: new Date().toISOString(),
|
||||
displayName: input.agent.name,
|
||||
};
|
||||
queryClient.setQueryData<ChannelMember[]>(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<ChannelMember[]>(membersKey) ?? [];
|
||||
const alreadyPresent = current.some(
|
||||
(m) =>
|
||||
normalizePubkey(m.pubkey) === normalizePubkey(result.agent.pubkey),
|
||||
);
|
||||
if (!alreadyPresent) {
|
||||
queryClient.setQueryData<ChannelMember[]>(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<ChannelMember[]>(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<ChannelMember[]>(membersKey, [
|
||||
...current,
|
||||
...newMembers,
|
||||
]);
|
||||
}
|
||||
},
|
||||
onSettled: async () => {
|
||||
await invalidateAgentQueries(queryClient, channelId);
|
||||
},
|
||||
|
||||
152
desktop/src/features/channels/ui/QuickAddAgentItemRow.tsx
Normal file
152
desktop/src/features/channels/ui/QuickAddAgentItemRow.tsx
Normal file
@@ -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 (
|
||||
<div className="relative flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-border/50 bg-muted/30">
|
||||
{avatarUrl ? (
|
||||
<img
|
||||
alt={label}
|
||||
className="h-full w-full rounded-full object-cover"
|
||||
referrerPolicy="no-referrer"
|
||||
src={rewriteRelayUrl(avatarUrl)}
|
||||
/>
|
||||
) : (
|
||||
<span className="text-[10px] font-semibold text-muted-foreground">
|
||||
{initials}
|
||||
</span>
|
||||
)}
|
||||
{isRunning ? (
|
||||
<span className="absolute -bottom-0.5 -right-0.5 h-2.5 w-2.5 rounded-full border-2 border-popover bg-emerald-500" />
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ── 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 (
|
||||
<motion.div key={itemKey} layout transition={{ duration: 0.2 }}>
|
||||
<button
|
||||
aria-selected={isInChannel || isSelected}
|
||||
className={cn(
|
||||
"flex w-full items-center px-3 py-1.5 text-left text-sm transition-colors",
|
||||
isInChannel
|
||||
? "cursor-default"
|
||||
: "cursor-pointer hover:bg-accent focus-visible:bg-accent focus-visible:outline-none",
|
||||
isPending && "pointer-events-none opacity-60",
|
||||
isSelected && "bg-accent/50",
|
||||
)}
|
||||
data-quick-add-item
|
||||
disabled={!isInChannel && disabled}
|
||||
onClick={onClick}
|
||||
role="option"
|
||||
tabIndex={0}
|
||||
type="button"
|
||||
>
|
||||
{!isInChannel ? (
|
||||
<motion.div
|
||||
animate={{
|
||||
width: selectMode ? 16 : 0,
|
||||
marginRight: selectMode ? 8 : 0,
|
||||
opacity: selectMode ? 1 : 0,
|
||||
}}
|
||||
initial={false}
|
||||
transition={{ duration: 0.15 }}
|
||||
className="shrink-0 overflow-hidden"
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"flex h-4 w-4 items-center justify-center rounded border transition-colors",
|
||||
isSelected
|
||||
? "border-primary bg-primary text-primary-foreground"
|
||||
: "border-muted-foreground/40",
|
||||
)}
|
||||
>
|
||||
{isSelected ? <Check className="h-3 w-3" /> : null}
|
||||
</div>
|
||||
</motion.div>
|
||||
) : null}
|
||||
<div className="flex min-w-0 flex-1 items-center gap-2.5">
|
||||
<span className={cn("shrink-0", isInChannel && "opacity-50")}>
|
||||
<QuickAddAgentAvatar
|
||||
avatarUrl={item.avatarUrl}
|
||||
label={item.label}
|
||||
isRunning={item.kind !== "persona"}
|
||||
/>
|
||||
</span>
|
||||
<span
|
||||
className={cn(
|
||||
"min-w-0 flex-1 truncate font-medium",
|
||||
isInChannel && "opacity-50",
|
||||
)}
|
||||
>
|
||||
{item.label}
|
||||
</span>
|
||||
{isInChannel ? (
|
||||
<button
|
||||
className="flex h-5 w-5 shrink-0 items-center justify-center rounded-sm text-muted-foreground transition-colors hover:bg-destructive/10 hover:text-destructive"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onRemove(item.agent.pubkey);
|
||||
}}
|
||||
type="button"
|
||||
aria-label={`Remove ${item.label}`}
|
||||
>
|
||||
<X className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
) : null}
|
||||
{isPending ? (
|
||||
<Spinner className="h-3.5 w-3.5 shrink-0 text-primary" />
|
||||
) : null}
|
||||
</div>
|
||||
</button>
|
||||
</motion.div>
|
||||
);
|
||||
});
|
||||
@@ -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>): 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<string | null>(null);
|
||||
const [errorMessage, setErrorMessage] = React.useState<string | null>(null);
|
||||
const [selectMode, setSelectMode] = React.useState(false);
|
||||
const [selectedKeys, setSelectedKeys] = React.useState<Set<string>>(
|
||||
new Set(),
|
||||
);
|
||||
const [selectedTeamIds, setSelectedTeamIds] = React.useState<Set<string>>(
|
||||
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 */}
|
||||
<div
|
||||
className="relative flex flex-col"
|
||||
role="menu"
|
||||
role="group"
|
||||
aria-label="Add agent"
|
||||
onKeyDown={(e) => {
|
||||
const container = e.currentTarget;
|
||||
const buttons = Array.from(
|
||||
@@ -524,23 +110,18 @@ export function QuickAddAgentPopover({
|
||||
}
|
||||
}}
|
||||
>
|
||||
{/* Header with animated title / team toggles */}
|
||||
{/* Header */}
|
||||
<div className="flex min-h-10 items-center gap-2 border-b pl-3 pr-1.5 py-1.5">
|
||||
<h3 className="shrink-0 text-sm font-semibold text-foreground">
|
||||
Add agent
|
||||
</h3>
|
||||
|
||||
{usableTeams.length > 0 ? (
|
||||
<div className="ml-auto flex shrink-0 items-center">
|
||||
<Button
|
||||
className="border border-input bg-transparent"
|
||||
onClick={() => {
|
||||
if (selectMode) {
|
||||
handleCancelSelect();
|
||||
} else {
|
||||
setSelectMode(true);
|
||||
}
|
||||
if (selectMode) handleCancelSelect();
|
||||
else setSelectMode(true);
|
||||
}}
|
||||
size="sm"
|
||||
type="button"
|
||||
@@ -552,7 +133,7 @@ export function QuickAddAgentPopover({
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{/* Team toggles row — always mounted, height animates based on selectMode */}
|
||||
{/* Team toggles row */}
|
||||
<motion.div
|
||||
className="relative overflow-hidden"
|
||||
initial={false}
|
||||
@@ -570,7 +151,7 @@ export function QuickAddAgentPopover({
|
||||
initial={false}
|
||||
animate={{
|
||||
opacity: selectMode ? 1 : 0,
|
||||
x: selectMode ? 0 : (index === 0 ? 0 : 12),
|
||||
x: selectMode ? 0 : index === 0 ? 0 : 12,
|
||||
}}
|
||||
transition={{
|
||||
duration: 0.2,
|
||||
@@ -592,12 +173,11 @@ export function QuickAddAgentPopover({
|
||||
</motion.div>
|
||||
))}
|
||||
</div>
|
||||
{/* Gradient fade on right edge — scroll affordance */}
|
||||
<div className="pointer-events-none absolute right-0 top-0 h-full w-6 bg-gradient-to-l from-popover to-transparent" />
|
||||
</div>
|
||||
</motion.div>
|
||||
|
||||
{/* Scrollable content — clips mid-item to hint at more */}
|
||||
{/* Scrollable content */}
|
||||
<motion.div
|
||||
className="max-h-[13.75rem] flex-1 overflow-y-auto"
|
||||
layout
|
||||
@@ -619,79 +199,20 @@ export function QuickAddAgentPopover({
|
||||
>
|
||||
{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 (
|
||||
<motion.div key={itemKey} layout transition={{ duration: 0.2 }}>
|
||||
<button
|
||||
aria-selected={isInChannel || isSelected}
|
||||
className={cn(
|
||||
"flex w-full items-center px-3 py-1.5 text-left text-sm transition-colors",
|
||||
isInChannel
|
||||
? "cursor-default"
|
||||
: "cursor-pointer hover:bg-accent focus-visible:bg-accent focus-visible:outline-none",
|
||||
isItemPending && "pointer-events-none opacity-60",
|
||||
isSelected && "bg-accent/50",
|
||||
)}
|
||||
data-quick-add-item
|
||||
disabled={!isInChannel && Boolean(pendingKey)}
|
||||
<QuickAddAgentItemRow
|
||||
key={itemKey}
|
||||
item={item}
|
||||
itemKey={itemKey}
|
||||
isSelected={selectedKeys.has(itemKey)}
|
||||
isPending={
|
||||
pendingKey === itemKey || pendingKey === "batch"
|
||||
}
|
||||
selectMode={selectMode}
|
||||
disabled={Boolean(pendingKey)}
|
||||
onClick={() => handleItemClick(item)}
|
||||
role="option"
|
||||
tabIndex={0}
|
||||
type="button"
|
||||
>
|
||||
{!isInChannel ? (
|
||||
<motion.div
|
||||
animate={{ width: selectMode ? 16 : 0, marginRight: selectMode ? 8 : 0, opacity: selectMode ? 1 : 0 }}
|
||||
initial={false}
|
||||
transition={{ duration: 0.15 }}
|
||||
className="shrink-0 overflow-hidden"
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"flex h-4 w-4 items-center justify-center rounded border transition-colors",
|
||||
isSelected
|
||||
? "border-primary bg-primary text-primary-foreground"
|
||||
: "border-muted-foreground/40",
|
||||
)}
|
||||
>
|
||||
{isSelected ? <Check className="h-3 w-3" /> : null}
|
||||
</div>
|
||||
</motion.div>
|
||||
) : null}
|
||||
<div className="flex min-w-0 flex-1 items-center gap-2.5">
|
||||
<span className={cn("shrink-0", isInChannel && "opacity-50")}>
|
||||
<QuickAddAgentAvatar
|
||||
avatarUrl={item.avatarUrl}
|
||||
label={item.label}
|
||||
isRunning={item.kind !== "persona"}
|
||||
/>
|
||||
</span>
|
||||
<span className={cn("min-w-0 flex-1 truncate font-medium", isInChannel && "opacity-50")}>
|
||||
{item.label}
|
||||
</span>
|
||||
{isInChannel ? (
|
||||
<button
|
||||
className="flex h-5 w-5 shrink-0 items-center justify-center rounded-sm text-muted-foreground transition-colors hover:bg-destructive/10 hover:text-destructive"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
removeMutation.mutate(item.agent.pubkey);
|
||||
}}
|
||||
type="button"
|
||||
aria-label={`Remove ${item.label}`}
|
||||
>
|
||||
<X className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
) : null}
|
||||
{isItemPending ? (
|
||||
<Spinner className="h-3.5 w-3.5 shrink-0 text-primary" />
|
||||
) : null}
|
||||
</div>
|
||||
</button>
|
||||
</motion.div>
|
||||
onRemove={(pubkey) => removeMutation.mutate(pubkey)}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
@@ -751,42 +272,3 @@ export function QuickAddAgentPopover({
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
|
||||
// ── 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 (
|
||||
<div className="relative flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-border/50 bg-muted/30">
|
||||
{avatarUrl ? (
|
||||
<img
|
||||
alt={label}
|
||||
className="h-full w-full rounded-full object-cover"
|
||||
referrerPolicy="no-referrer"
|
||||
src={rewriteRelayUrl(avatarUrl)}
|
||||
/>
|
||||
) : (
|
||||
<span className="text-[10px] font-semibold text-muted-foreground">
|
||||
{initials}
|
||||
</span>
|
||||
)}
|
||||
{isRunning ? (
|
||||
<span className="absolute -bottom-0.5 -right-0.5 h-2.5 w-2.5 rounded-full border-2 border-popover bg-emerald-500" />
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
294
desktop/src/features/channels/ui/useQuickAddAgentActions.ts
Normal file
294
desktop/src/features/channels/ui/useQuickAddAgentActions.ts
Normal file
@@ -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>): 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<string | null>(null);
|
||||
const [errorMessage, setErrorMessage] = React.useState<string | null>(null);
|
||||
const [selectMode, setSelectMode] = React.useState(false);
|
||||
const [selectedKeys, setSelectedKeys] = React.useState<Set<string>>(
|
||||
new Set(),
|
||||
);
|
||||
const [selectedTeamIds, setSelectedTeamIds] = React.useState<Set<string>>(
|
||||
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,
|
||||
};
|
||||
}
|
||||
213
desktop/src/features/channels/ui/useQuickAddAgentItems.ts
Normal file
213
desktop/src/features/channels/ui/useQuickAddAgentItems.ts
Normal file
@@ -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,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user