Open History to see the last commit
1import { ACP_REGISTRY_MAX_AGENTS, AuthProvidersManageScope } from "@t3tools/contracts";
2import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";
3import {
4 isAtomCommandInterrupted,
5 squashAtomCommandFailure,
6} from "@t3tools/client-runtime/state/runtime";
7import type {
8 AcpRegistryPrepareResult,
9 AcpRegistrySearchAgent,
10 EnvironmentId,
11 ProviderInstanceConfig,
12} from "@t3tools/contracts";
13import { ExternalLinkIcon, SearchIcon } from "lucide-react";
14import { type FormEvent, useState } from "react";
15
16import { useDeadlinePassed } from "../../hooks/useDeadline";
17import { serverEnvironment } from "../../state/server";
18import { useEnvironmentQuery } from "../../state/query";
19import { useAtomCommand } from "../../state/use-atom-command";
20import { Alert, AlertDescription } from "../ui/alert";
21import { Button } from "../ui/button";
22import { InputGroup, InputGroupAddon, InputGroupInput } from "../ui/input-group";
23import { ScrollArea } from "../ui/scroll-area";
24import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
25import { isConfiguredAcpRegistryAgent } from "./AddProviderInstanceDialog.logic";
26import { ProviderDriverKind } from "@t3tools/contracts";
27import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon";
28import { providerClients } from "./providerDriverMeta";
29
30function errorMessage(error: unknown): string {
31 return error instanceof Error && error.message.trim()
32 ? error.message
33 : "The ACP could not be prepared.";
34}
35
36const ACP_REGISTRY_SEARCH_DEBOUNCE_MS = 300;
37const FIRST_CLASS_REGISTRY_AGENT_IDS = new Set(
38 providerClients.definitions.flatMap((definition) => definition.acpRegistryAgentIds ?? []),
39);
40
41function applyAcpRegistryPrepareResult(
42 agent: AcpRegistrySearchAgent,
43 prepared: AcpRegistryPrepareResult,
44): AcpRegistrySearchAgent {
45 return {
46 ...agent,
47 id: prepared.agentId,
48 version: prepared.version,
49 distribution: prepared.distribution,
50 };
51}
52
53/**
54 * Registry search and agent preparation. Owned by the dialog, which needs the
55 * loading and preparing state for its layout and navigation, and rendered by
56 * AcpRegistrySearchStep. Pass `enabled: false` while the step is hidden so the
57 * search is not kept subscribed.
58 */
59export function useAcpRegistrySearch(environmentId: EnvironmentId, enabled: boolean) {
60 const [input, setInput] = useState<{
61 readonly text: string;
62 readonly submitted: string;
63 readonly typedAt: number | null;
64 }>({ text: "", submitted: "", typedAt: null });
65 const typingSettled = useDeadlinePassed(
66 input.typedAt === null ? null : input.typedAt + ACP_REGISTRY_SEARCH_DEBOUNCE_MS,
67 );
68 const submittedQuery = typingSettled ? input.text.trim() : input.submitted;
69 const [preparingId, setPreparingId] = useState<string | null>(null);
70 const [prepareError, setPrepareError] = useState<string | null>(null);
71 const search = useEnvironmentQuery(
72 enabled
73 ? serverEnvironment.searchAcpRegistry({
74 environmentId,
75 input: submittedQuery
76 ? { query: submittedQuery }
77 : { query: "", limit: ACP_REGISTRY_MAX_AGENTS },
78 })
79 : null,
80 );
81 const prepareAgent = useAtomCommand(serverEnvironment.prepareAcpRegistryAgent, {
82 reportFailure: false,
83 });
84
85 return {
86 query: input.text,
87 search,
88 preparingId,
89 prepareError,
90 type: (text: string) => {
91 setPrepareError(null);
92 setInput({ text, submitted: submittedQuery, typedAt: Date.now() });
93 },
94 submit: () => {
95 const trimmed = input.text.trim();
96 setPrepareError(null);
97 setInput({ text: trimmed, submitted: trimmed, typedAt: null });
98 if (trimmed === submittedQuery) search.refresh();
99 },
100 prepare: async (
101 agent: AcpRegistrySearchAgent,
102 onPrepared: (agent: AcpRegistrySearchAgent) => void,
103 ) => {
104 if (!readEnvironmentScope(environmentId, AuthProvidersManageScope)) return;
105 setPrepareError(null);
106 setPreparingId(agent.id);
107 const result = await prepareAgent({ environmentId, input: { agentId: agent.id } });
108 setPreparingId(null);
109 if (result._tag === "Success") {
110 onPrepared(applyAcpRegistryPrepareResult(agent, result.value));
111 return;
112 }
113 if (!isAtomCommandInterrupted(result)) {
114 setPrepareError(errorMessage(squashAtomCommandFailure(result)));
115 }
116 },
117 };
118}
119
120export type AcpRegistrySearch = ReturnType<typeof useAcpRegistrySearch>;
121
122interface AcpRegistrySearchStepProps {
123 readonly environmentId: EnvironmentId;
124 readonly registry: AcpRegistrySearch;
125 readonly providerInstances: Readonly<Record<string, ProviderInstanceConfig>>;
126 readonly onPrepared: (agent: AcpRegistrySearchAgent) => void;
127 readonly onManualConfiguration: () => void;
128 readonly onLocalConfiguration?: () => void;
129}
130
131export function AcpRegistrySearchStep({
132 environmentId,
133 registry,
134 providerInstances,
135 onPrepared,
136 onManualConfiguration,
137 onLocalConfiguration,
138}: AcpRegistrySearchStepProps) {
139 const canManageProviders = useEnvironmentScope(environmentId, AuthProvidersManageScope);
140 const { query, search, preparingId, prepareError } = registry;
141
142 const handleSearch = (event: FormEvent<HTMLFormElement>) => {
143 event.preventDefault();
144 registry.submit();
145 };
146
147 const handlePrepare = (agent: AcpRegistrySearchAgent) => {
148 void registry.prepare(agent, onPrepared);
149 };
150
151 const results =
152 search.data?.agents.filter((agent) => !FIRST_CLASS_REGISTRY_AGENT_IDS.has(agent.id)) ?? null;
153 const isInitialSearch = search.isPending && results === null;
154 const isRefreshing = search.isPending && results !== null;
155 const resultCount = results?.length ?? 0;
156
157 return (
158 <section className="grid gap-3" aria-labelledby="acp-registry-search-heading">
159 <h3 className="sr-only" id="acp-registry-search-heading">
160 Choose an agent
161 </h3>
162
163 <form className="flex flex-wrap items-center gap-2" onSubmit={handleSearch}>
164 <InputGroup className="min-w-40 flex-1">
165 <InputGroupAddon>
166 <SearchIcon />
167 </InputGroupAddon>
168 <InputGroupInput
169 aria-label="Search ACP Registry"
170 disabled={preparingId !== null}
171 onChange={(event) => registry.type(event.currentTarget.value)}
172 placeholder="Search agents…"
173 size="sm"
174 type="search"
175 value={query}
176 />
177 </InputGroup>
178 <Button
179 disabled={preparingId !== null}
180 onClick={onManualConfiguration}
181 size="sm"
182 type="button"
183 variant="ghost-muted"
184 >
185 Enter manually
186 </Button>
187 {onLocalConfiguration ? (
188 <Button
189 disabled={preparingId !== null}
190 onClick={onLocalConfiguration}
191 size="sm"
192 type="button"
193 variant="outline"
194 >
195 Local ACP command
196 </Button>
197 ) : null}
198 </form>
199
200 <div className="sr-only" role="status">
201 {isInitialSearch
202 ? "Searching the ACP Registry."
203 : isRefreshing
204 ? "Refreshing ACP Registry results."
205 : results
206 ? `${resultCount} compatible ${resultCount === 1 ? "agent" : "agents"} found.`
207 : ""}
208 </div>
209
210 {search.error || prepareError ? (
211 <Alert variant="error" role="status" aria-live="polite">
212 <AlertDescription>{prepareError ?? search.error}</AlertDescription>
213 </Alert>
214 ) : null}
215
216 {isInitialSearch ? (
217 <div className="flex min-h-20 items-center justify-center text-sm text-muted-foreground">
218 Searching the registry...
219 </div>
220 ) : null}
221
222 {results ? (
223 results.length === 0 ? (
224 <div className="flex min-h-28 flex-col items-center justify-center rounded-2xl border border-dashed px-4 text-center">
225 <p className="text-sm font-medium">No compatible agents found</p>
226 <p className="mt-1 text-xs text-muted-foreground">Try a broader search.</p>
227 </div>
228 ) : (
229 <ScrollArea scrollFade className="max-h-64">
230 <div className="pr-2.5">
231 {results.map((agent) => (
232 <AcpRegistryAgentRow
233 agent={agent}
234 alreadyAdded={isConfiguredAcpRegistryAgent(providerInstances, agent.id)}
235 canAdd={canManageProviders && preparingId === null}
236 isPreparing={preparingId === agent.id}
237 key={agent.id}
238 onAdd={handlePrepare}
239 />
240 ))}
241 </div>
242 </ScrollArea>
243 )
244 ) : null}
245 </section>
246 );
247}
248
249function AcpRegistryAgentRow({
250 agent,
251 alreadyAdded,
252 canAdd,
253 isPreparing,
254 onAdd,
255}: {
256 readonly agent: AcpRegistrySearchAgent;
257 readonly alreadyAdded: boolean;
258 readonly canAdd: boolean;
259 readonly isPreparing: boolean;
260 readonly onAdd: (agent: AcpRegistrySearchAgent) => void;
261}) {
262 const progressLabel = agent.distribution === "binary" ? "Downloading" : "Preparing";
263 const aboutUrl = agent.website || agent.repository;
264 return (
265 <article className="min-w-0 py-2.5">
266 <div className="flex min-w-0 items-center justify-between gap-3">
267 <div className="flex min-w-0 flex-1 items-center gap-3">
268 <ProviderInstanceIcon
269 driverKind={ProviderDriverKind.make("acpRegistry")}
270 displayName={agent.name}
271 acpRegistryAgentId={agent.id}
272 acpRegistryIconUrl={agent.icon ?? undefined}
273 iconClassName="size-6 rounded-md text-muted-foreground"
274 />
275 <div className="min-w-0 flex-1">
276 <div className="flex min-w-0 items-baseline gap-2">
277 <h4 className="min-w-0 truncate text-sm font-medium text-foreground">{agent.name}</h4>
278 </div>
279 {agent.description ? (
280 <p className="mt-0.5 truncate text-xs text-muted-foreground">{agent.description}</p>
281 ) : null}
282 </div>
283 </div>
284 <div className="flex shrink-0 items-center gap-1.5">
285 {aboutUrl ? (
286 <Tooltip>
287 <TooltipTrigger
288 render={
289 <Button
290 size="icon-xs"
291 variant="ghost-muted"
292 aria-label={`About ${agent.name}`}
293 render={<a href={aboutUrl} target="_blank" rel="noreferrer" />}
294 >
295 <ExternalLinkIcon />
296 </Button>
297 }
298 />
299 <TooltipPopup>About {agent.name}</TooltipPopup>
300 </Tooltip>
301 ) : null}
302 <Button
303 aria-label={`${alreadyAdded ? "Already added" : isPreparing ? progressLabel : "Add"} ${agent.name}`}
304 disabled={!canAdd || alreadyAdded}
305 onClick={() => onAdd(agent)}
306 size="xs"
307 variant={isPreparing ? "secondary" : "outline"}
308 >
309 {alreadyAdded ? "Added" : isPreparing ? progressLabel : "Add"}
310 </Button>
311 </div>
312 </div>
313 </article>
314 );
315}