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