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

AcpRegistrySearchStep.tsx

334 lines12.8 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​
26const SUGGESTED_SEARCHES = ["Codex", "Copilot", "Kimi"] as const;
27function errorMessage(error: unknown): string {
28 return error instanceof Error && error.message.trim()
29 ? error.message
30 : "The ACP could not be prepared.";
32​
33function authorDisplayName(author: string): string {
34 // Registry authors may be "Name <email>" package-style strings.
35 return author.replace(/<[^>]*>/g, "").trim();
37​
38function authorSummary(authors: ReadonlyArray<string>): string | null {
39 const names = authors.map(authorDisplayName).filter((name) => name.length > 0);
40 const first = names[0];
41 if (!first) return null;
42 return names.length === 1 ? first : `${first} +${names.length - 1}`;
44​
45function metadata(entry: AcpRegistrySearchAgent): ReadonlyArray<string> {
46 return [authorSummary(entry.authors), entry.distribution, entry.license].filter(
47 (value): value is string => Boolean(value),
48 );
50​
51interface AcpRegistrySearchStepProps {
52 readonly environmentId: EnvironmentId;
53 readonly providerInstances: Readonly<Record<string, ProviderInstanceConfig>>;
54 readonly onPrepared: (agent: AcpRegistrySearchAgent) => void;
55 readonly onManualConfiguration: () => void;
56 readonly onLoadingChange?: (loading: boolean) => void;
58​
59function applyAcpRegistryPrepareResult(
60 agent: AcpRegistrySearchAgent,
61 prepared: AcpRegistryPrepareResult,
62): AcpRegistrySearchAgent {
63 return {
64 ...agent,
65 id: prepared.agentId,
66 version: prepared.version,
67 distribution: prepared.distribution,
68 };
70​
71export function AcpRegistrySearchStep({
72 environmentId,
73 providerInstances,
74 onPrepared,
75 onManualConfiguration,
76 onLoadingChange,
77}: AcpRegistrySearchStepProps) {
78 const [query, setQuery] = useState("");
79 // An empty registry query is the compact compatible catalog. Start there so
80 // entering this step is useful before the user knows what to search for.
81 const [submittedQuery, setSubmittedQuery] = useState("");
82 const [preparingId, setPreparingId] = useState<string | null>(null);
83 const [prepareError, setPrepareError] = useState<string | null>(null);
84 const prepareGeneration = useRef(0);
85 const search = useEnvironmentQuery(
86 serverEnvironment.searchAcpRegistry({
87 environmentId,
88 input: { query: submittedQuery },
89 }),
90 );
91 const prepareAgent = useAtomCommand(serverEnvironment.prepareAcpRegistryAgent, {
92 reportFailure: false,
93 });
94​
95 useEffect(
96 () => () => {
97 prepareGeneration.current += 1;
98 },
99 [],
100 );
101​
102 const submitSearch = (nextQuery: string) => {
103 const trimmed = nextQuery.trim();
104 setQuery(trimmed);
105 setPrepareError(null);
106 if (trimmed === submittedQuery) {
107 search.refresh();
108 } else {
109 setSubmittedQuery(trimmed);
110 }
111 };
112​
113 const handleSearch = (event: FormEvent<HTMLFormElement>) => {
114 event.preventDefault();
115 submitSearch(query);
116 };
117​
118 const handlePrepare = async (agent: AcpRegistrySearchAgent) => {
119 const generation = ++prepareGeneration.current;
120 setPrepareError(null);
121 setPreparingId(agent.id);
122 const result = await prepareAgent({ environmentId, input: { agentId: agent.id } });
123 if (prepareGeneration.current !== generation) return;
124 setPreparingId(null);
125 if (result._tag === "Success") {
126 onPrepared(applyAcpRegistryPrepareResult(agent, result.value));
127 return;
128 }
129 if (!isAtomCommandInterrupted(result)) {
130 setPrepareError(errorMessage(squashAtomCommandFailure(result)));
131 }
132 };
133​
134 const results = search.data?.agents ?? null;
135 const isInitialSearch = search.isPending && results === null;
136 const isRefreshing = search.isPending && results !== null;
137 const resultCount = results?.length ?? 0;
138​
139 useLayoutEffect(() => {
140 onLoadingChange?.(search.isPending);
141 return () => onLoadingChange?.(false);
142 }, [onLoadingChange, search.isPending]);
143​
144 return (
145 <section className="grid gap-3" aria-labelledby="acp-registry-search-heading">
146 <div>
147 <h3 className="text-sm font-medium text-foreground" id="acp-registry-search-heading">
148 Find an ACP agent
149 </h3>
150 <p className="mt-0.5 text-xs text-muted-foreground">
151 Search compatible agents in the official ACP Registry for this environment.
152 </p>
153 </div>
154​
155 <form className="flex gap-2" onSubmit={handleSearch}>
156 <InputGroup>
157 <InputGroupAddon>
158 <SearchIcon />
159 </InputGroupAddon>
160 <InputGroupInput
161 aria-label="Search ACP Registry"
162 autoFocus
163 onChange={(event) => setQuery(event.currentTarget.value)}
164 placeholder="Search by agent, author, or description"
165 size="sm"
166 type="search"
167 value={query}
168 />
169 </InputGroup>
170 <Button
171 disabled={search.isPending || preparingId !== null}
172 size="sm"
173 type="submit"
174 variant="outline"
175 >
176 {isRefreshing ? "Refreshing" : "Search"}
177 </Button>
178 </form>
179​
180 {!isInitialSearch ? (
181 <div className="flex flex-wrap items-center gap-1.5">
182 <span className="text-xs text-muted-foreground">Try</span>
183 {SUGGESTED_SEARCHES.map((suggestion) => (
184 <Button
185 key={suggestion}
186 disabled={search.isPending || preparingId !== null}
187 onClick={() => submitSearch(suggestion)}
188 size="xs"
189 variant="ghost"
190 >
191 {suggestion}
192 </Button>
193 ))}
194 </div>
195 ) : null}
196​
197 <div className="sr-only" role="status">
198 {isInitialSearch
199 ? "Searching the ACP Registry."
200 : isRefreshing
201 ? "Refreshing ACP Registry results."
202 : results
203 ? `${resultCount} compatible ${resultCount === 1 ? "agent" : "agents"} found.`
204 : ""}
205 </div>
206​
207 {search.error || prepareError ? (
208 <Alert variant="error" role="status" aria-live="polite">
209 <AlertDescription>{prepareError ?? search.error}</AlertDescription>
210 </Alert>
211 ) : null}
212​
213 {isInitialSearch ? (
214 <div className="flex min-h-20 items-center justify-center text-sm text-muted-foreground">
215 Searching the registry...
216 </div>
217 ) : null}
218​
219 {isRefreshing ? (
220 <p className="text-xs text-muted-foreground">Refreshing registry results...</p>
221 ) : null}
222​
223 {results ? (
224 results.length === 0 ? (
225 <div className="flex min-h-28 flex-col items-center justify-center rounded-2xl border border-dashed px-4 text-center">
226 <p className="text-sm font-medium">No compatible agents found</p>
227 <p className="mt-1 text-xs text-muted-foreground">Try a broader search.</p>
228 </div>
229 ) : (
230 <ScrollArea scrollFade className="max-h-72 border-t border-border/70">
231 {/* The overlay scrollbar takes no layout space, so the rows
232 reserve its lane explicitly. */}
233 <div className="divide-y divide-border/70 pr-2.5">
234 {results.map((agent) => {
235 const alreadyAdded = isConfiguredAcpRegistryAgent(providerInstances, agent.id);
236 const isPreparing = preparingId === agent.id;
237 const progressLabel = agent.distribution === "binary" ? "Downloading" : "Preparing";
238 return (
239 <article className="grid min-w-0 gap-2 py-3 first:pt-2 last:pb-2" key={agent.id}>
240 <div className="flex min-w-0 items-start justify-between gap-3">
241 <div className="flex min-w-0 flex-1 items-start gap-3">
242 <ProviderInstanceIcon
243 driverKind={ProviderDriverKind.make("acpRegistry")}
244 displayName={agent.name}
245 acpRegistryAgentId={agent.id}
246 acpRegistryIconUrl={agent.icon ?? undefined}
247 iconClassName="size-8 rounded-lg bg-muted text-muted-foreground"
248 />
249 <div className="min-w-0 flex-1">
250 <div className="flex min-w-0 items-baseline gap-2">
251 <h4 className="min-w-0 truncate text-sm font-medium text-foreground">
252 {agent.name}
253 </h4>
254 <span className="shrink-0 text-[11px] text-muted-foreground">
255 {`v${agent.version}`}
256 </span>
257 </div>
258 <p className="mt-0.5 line-clamp-2 text-xs leading-4 text-muted-foreground">
259 {agent.description ||
260 "An agent available through the official ACP Registry."}
261 </p>
262 </div>
263 </div>
264 <Button
265 aria-label={`${alreadyAdded ? "Already added" : isPreparing ? progressLabel : "Add"} ${agent.name}`}
266 disabled={alreadyAdded || preparingId !== null}
267 onClick={() => void handlePrepare(agent)}
268 size="xs"
269 variant={isPreparing ? "secondary" : "outline"}
270 >
271 {alreadyAdded ? "Added" : isPreparing ? progressLabel : "Add"}
272 </Button>
273 </div>
274 <div className="flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-1 text-[11px] text-muted-foreground [&>*+*]:before:mr-1.5 [&>*+*]:before:content-['·']">
275 {metadata(agent).map((item) => (
276 <span key={item}>{item}</span>
277 ))}
278 {agent.integrity === "sha256" ? (
279 <Tooltip>
280 <TooltipTrigger render={<span>✓ checksum</span>} />
281 <TooltipPopup>
282 Binary checksum is verified against the registry
283 </TooltipPopup>
284 </Tooltip>
285 ) : null}
286 {agent.website ? (
287 <a
288 aria-label={`Open documentation for ${agent.name} (${agent.id})`}
289 className="inline-flex items-center gap-1 hover:text-foreground"
290 href={agent.website}
291 rel="noreferrer"
292 target="_blank"
293 >
294 Docs <ExternalLinkIcon className="size-3" />
295 </a>
296 ) : null}
297 {agent.repository ? (
298 <a
299 aria-label={`Open source for ${agent.name} (${agent.id})`}
300 className="inline-flex items-center gap-1 hover:text-foreground"
301 href={agent.repository}
302 rel="noreferrer"
303 target="_blank"
304 >
305 Source <ExternalLinkIcon className="size-3" />
306 </a>
307 ) : null}
308 </div>
309 </article>
310 );
311 })}
312 </div>
313 </ScrollArea>
314 )
315 ) : null}
316​
317 {/* DialogPanel collapses its own bottom padding when the dialog footer
318 is bare, so this row carries the breathing room itself. */}
319 <div className="flex items-center justify-between gap-3 border-t border-border/70 py-3">
320 <p className="text-[11px] text-muted-foreground">
321 Authentication is completed separately with the selected agent.
322 </p>
323 <Button
324 disabled={preparingId !== null}
325 onClick={onManualConfiguration}
326 size="xs"
327 variant="ghost"
328 >
329 Configure manually
330 </Button>
331 </div>
332 </section>
333 );