Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AcpRegistrySearchStep.tsx

292 lines11.0 KB

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