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

AcpRegistrySearchStep.tsx

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