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