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