Open History to see the last commit
1import { pipe } from "effect/Function";
2import {
3 ACP_REGISTRY_MAX_AGENTS,
4 ACP_REGISTRY_SEARCH_QUERY_MAX_LENGTH,
5 AuthProvidersManageScope,
6} from "@t3tools/contracts";
7import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";
8import {
9 isAtomCommandInterrupted,
10 squashAtomCommandFailure,
11} from "@t3tools/client-runtime/state/runtime";
12import type {
13 AcpRegistryPrepareResult,
14 AcpRegistrySearchAgent,
15 EnvironmentId,
16 ProviderInstanceConfig,
17} from "@t3tools/contracts";
18import { ExternalLinkIcon, SearchIcon } from "lucide-react";
19import { msg, T, useGT, useMessages, Var } from "gt-react";
20import { type FormEvent, useState } from "react";
21
22import { useDeadlinePassed } from "../../hooks/useDeadline";
23import { m } from "../../i18n/messages";
24import { serverEnvironment } from "../../state/server";
25import { useEnvironmentQuery } from "../../state/query";
26import { useAtomCommand } from "../../state/use-atom-command";
27import { Alert, AlertDescription } from "../ui/alert";
28import { Button } from "../ui/button";
29import { InputGroup, InputGroupAddon, InputGroupInput } from "../ui/input-group";
30import { ScrollArea } from "../ui/scroll-area";
31import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
32import { isConfiguredAcpRegistryAgent } from "./AddProviderInstanceDialog.logic";
33import { ProviderDriverKind } from "@t3tools/contracts";
34import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon";
35import { providerClients } from "./providerDriverMeta";
36
37function errorMessage(error: unknown): string {
38 return error instanceof Error && error.message.trim()
39 ? error.message
40 : m(msg("The ACP could not be prepared."));
41}
42
43const ACP_REGISTRY_SEARCH_DEBOUNCE_MS = 300;
44const FIRST_CLASS_REGISTRY_AGENT_IDS = new Set(
45 providerClients.definitions.flatMap((definition) => definition.acpRegistryAgentIds ?? []),
46);
47
48function applyAcpRegistryPrepareResult(
49 agent: AcpRegistrySearchAgent,
50 prepared: AcpRegistryPrepareResult,
51): AcpRegistrySearchAgent {
52 return {
53 ...agent,
54 id: prepared.agentId,
55 version: prepared.version,
56 distribution: prepared.distribution,
57 };
58}
59
60/**
61 * Registry search and agent preparation. Owned by the dialog, which needs the
62 * loading and preparing state for its layout and navigation, and rendered by
63 * AcpRegistrySearchStep. Pass `enabled: false` while the step is hidden so the
64 * search is not kept subscribed.
65 */
66export function useAcpRegistrySearch(environmentId: EnvironmentId, enabled: boolean) {
67 const [input, setInput] = useState<{
68 readonly text: string;
69 readonly submitted: string;
70 readonly typedAt: number | null;
71 }>({ text: "", submitted: "", typedAt: null });
72 const typingSettled = useDeadlinePassed(
73 input.typedAt === null ? null : input.typedAt + ACP_REGISTRY_SEARCH_DEBOUNCE_MS,
74 );
75 const submittedQuery = typingSettled ? input.text.trim() : input.submitted;
76 const [preparingId, setPreparingId] = useState<string | null>(null);
77 const [prepareError, setPrepareError] = useState<string | null>(null);
78 const search = useEnvironmentQuery(
79 enabled
80 ? serverEnvironment.searchAcpRegistry({
81 environmentId,
82 input: submittedQuery
83 ? { query: submittedQuery }
84 : { query: "", limit: ACP_REGISTRY_MAX_AGENTS },
85 })
86 : null,
87 useMessages(),
88 );
89 const prepareAgent = useAtomCommand(serverEnvironment.prepareAcpRegistryAgent, {
90 reportFailure: false,
91 });
92
93 return {
94 query: input.text,
95 search,
96 preparingId,
97 prepareError,
98 type: (text: string) => {
99 setPrepareError(null);
100 setInput({
101 text: text.slice(0, ACP_REGISTRY_SEARCH_QUERY_MAX_LENGTH),
102 submitted: submittedQuery,
103 typedAt: Date.now(),
104 });
105 },
106 submit: () => {
107 const trimmed = input.text.trim();
108 setPrepareError(null);
109 setInput({ text: trimmed, submitted: trimmed, typedAt: null });
110 if (trimmed === submittedQuery) search.refresh();
111 },
112 prepare: async (
113 agent: AcpRegistrySearchAgent,
114 onPrepared: (agent: AcpRegistrySearchAgent) => void,
115 ) => {
116 if (!readEnvironmentScope(environmentId, AuthProvidersManageScope)) return;
117 setPrepareError(null);
118 setPreparingId(agent.id);
119 const result = await prepareAgent({ environmentId, input: { agentId: agent.id } });
120 setPreparingId(null);
121 if (result._tag === "Success") {
122 onPrepared(applyAcpRegistryPrepareResult(agent, result.value));
123 return;
124 }
125 if (!isAtomCommandInterrupted(result)) {
126 pipe(squashAtomCommandFailure(result), errorMessage, setPrepareError);
127 }
128 },
129 };
130}
131
132export type AcpRegistrySearch = ReturnType<typeof useAcpRegistrySearch>;
133
134interface AcpRegistrySearchStepProps {
135 readonly environmentId: EnvironmentId;
136 readonly registry: AcpRegistrySearch;
137 readonly providerInstances: Readonly<Record<string, ProviderInstanceConfig>>;
138 readonly onPrepared: (agent: AcpRegistrySearchAgent) => void;
139 readonly onManualConfiguration: () => void;
140 readonly onLocalConfiguration?: () => void;
141}
142
143export function AcpRegistrySearchStep({
144 environmentId,
145 registry,
146 providerInstances,
147 onPrepared,
148 onManualConfiguration,
149 onLocalConfiguration,
150}: AcpRegistrySearchStepProps) {
151 const gt = useGT();
152 const canManageProviders = useEnvironmentScope(environmentId, AuthProvidersManageScope);
153 const { query, search, preparingId, prepareError } = registry;
154
155 const handleSearch = (event: FormEvent<HTMLFormElement>) => {
156 event.preventDefault();
157 registry.submit();
158 };
159
160 const handlePrepare = (agent: AcpRegistrySearchAgent) => {
161 void registry.prepare(agent, onPrepared);
162 };
163
164 const results =
165 search.data?.agents.filter((agent) => !FIRST_CLASS_REGISTRY_AGENT_IDS.has(agent.id)) ?? null;
166 const isInitialSearch = search.isPending && results === null;
167 const isRefreshing = search.isPending && results !== null;
168 const resultCount = results?.length ?? 0;
169
170 return (
171 <section className="grid gap-3" aria-labelledby="acp-registry-search-heading">
172 <h3 className="sr-only" id="acp-registry-search-heading">
173 <T>Choose an agent</T>
174 </h3>
175
176 <form className="flex flex-wrap items-center gap-2" onSubmit={handleSearch}>
177 <InputGroup className="min-w-40 flex-1">
178 <InputGroupAddon>
179 <SearchIcon />
180 </InputGroupAddon>
181 {/* Native search inputs clear on Escape even during IME composition. */}
182 <InputGroupInput
183 aria-label={gt("Search ACP Registry")}
184 maxLength={ACP_REGISTRY_SEARCH_QUERY_MAX_LENGTH}
185 disabled={preparingId !== null}
186 enterKeyHint="search"
187 onChange={(event) => registry.type(event.currentTarget.value)}
188 onKeyDown={(event) => {
189 if (event.key !== "Escape" || event.defaultPrevented) return;
190 if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return;
191 const composing = event.nativeEvent.isComposing || event.keyCode === 229;
192 if (!composing && !query && !event.repeat) return;
193 event.stopPropagation();
194 if (composing) return;
195 event.preventDefault();
196 if (query) registry.type("");
197 }}
198 placeholder={gt("Search agents…")}
199 role="searchbox"
200 size="sm"
201 type="text"
202 value={query}
203 />
204 </InputGroup>
205 <Button
206 disabled={preparingId !== null}
207 onClick={onManualConfiguration}
208 size="sm"
209 type="button"
210 variant="ghost-muted"
211 >
212 <T>Enter manually</T>
213 </Button>
214 {onLocalConfiguration ? (
215 <Button
216 disabled={preparingId !== null}
217 onClick={onLocalConfiguration}
218 size="sm"
219 type="button"
220 variant="outline"
221 >
222 <T>Local ACP command</T>
223 </Button>
224 ) : null}
225 </form>
226
227 <div className="sr-only" role="status">
228 {isInitialSearch
229 ? gt("Searching the ACP Registry.")
230 : isRefreshing
231 ? gt("Refreshing ACP Registry results.")
232 : results
233 ? gt(
234 "{count, plural, one {{count} compatible agent found.} other {{count} compatible agents found.}}",
235 { count: resultCount },
236 )
237 : ""}
238 </div>
239
240 {search.error || prepareError ? (
241 <Alert variant="error" role="status" aria-live="polite">
242 <AlertDescription>{prepareError ?? search.error}</AlertDescription>
243 </Alert>
244 ) : null}
245
246 {isInitialSearch ? (
247 <div className="flex min-h-20 items-center justify-center text-sm text-muted-foreground">
248 <T>Searching the registry...</T>
249 </div>
250 ) : null}
251
252 {results ? (
253 results.length === 0 ? (
254 <div className="flex min-h-28 flex-col items-center justify-center rounded-2xl border border-dashed px-4 text-center">
255 <p className="text-sm font-medium">
256 <T>No compatible agents found</T>
257 </p>
258 <p className="mt-1 text-xs text-muted-foreground">
259 <T>Try a broader search.</T>
260 </p>
261 </div>
262 ) : (
263 <ScrollArea scrollFade className="max-h-64">
264 <div className="pr-2.5">
265 {results.map((agent) => (
266 <AcpRegistryAgentRow
267 agent={agent}
268 alreadyAdded={isConfiguredAcpRegistryAgent(providerInstances, agent.id)}
269 canAdd={canManageProviders && preparingId === null}
270 isPreparing={preparingId === agent.id}
271 key={agent.id}
272 onAdd={handlePrepare}
273 />
274 ))}
275 </div>
276 </ScrollArea>
277 )
278 ) : null}
279 </section>
280 );
281}
282
283function AcpRegistryAgentRow({
284 agent,
285 alreadyAdded,
286 canAdd,
287 isPreparing,
288 onAdd,
289}: {
290 readonly agent: AcpRegistrySearchAgent;
291 readonly alreadyAdded: boolean;
292 readonly canAdd: boolean;
293 readonly isPreparing: boolean;
294 readonly onAdd: (agent: AcpRegistrySearchAgent) => void;
295}) {
296 const gt = useGT();
297 const progressLabel = agent.distribution === "binary" ? gt("Downloading") : gt("Preparing");
298 const aboutUrl = agent.website || agent.repository;
299 return (
300 <article className="min-w-0 py-2.5">
301 <div className="flex min-w-0 items-center justify-between gap-3">
302 <div className="flex min-w-0 flex-1 items-center gap-3">
303 <ProviderInstanceIcon
304 driverKind={ProviderDriverKind.make("acpRegistry")}
305 displayName={agent.name}
306 acpRegistryAgentId={agent.id}
307 acpRegistryIconUrl={agent.icon ?? undefined}
308 iconClassName="size-6 rounded-md text-muted-foreground"
309 />
310 <div className="min-w-0 flex-1">
311 <div className="flex min-w-0 items-baseline gap-2">
312 <h4 className="min-w-0 truncate text-sm font-medium text-foreground">{agent.name}</h4>
313 </div>
314 {agent.description ? (
315 <p className="mt-0.5 truncate text-xs text-muted-foreground">{agent.description}</p>
316 ) : null}
317 </div>
318 </div>
319 <div className="flex shrink-0 items-center gap-1.5">
320 {aboutUrl ? (
321 <Tooltip>
322 <TooltipTrigger
323 render={
324 <Button
325 size="icon-xs"
326 variant="ghost-muted"
327 aria-label={gt("About {name}", { name: agent.name })}
328 render={<a href={aboutUrl} target="_blank" rel="noreferrer" />}
329 >
330 <ExternalLinkIcon />
331 </Button>
332 }
333 />
334 <TooltipPopup>
335 <T>
336 About <Var>{agent.name}</Var>
337 </T>
338 </TooltipPopup>
339 </Tooltip>
340 ) : null}
341 <Button
342 aria-label={
343 alreadyAdded
344 ? gt("Already added {name}", { name: agent.name })
345 : isPreparing
346 ? agent.distribution === "binary"
347 ? gt("Downloading {name}", { name: agent.name })
348 : gt("Preparing {name}", { name: agent.name })
349 : gt("Add {name}", { name: agent.name })
350 }
351 disabled={!canAdd || alreadyAdded}
352 onClick={() => onAdd(agent)}
353 size="xs"
354 variant={isPreparing ? "secondary" : "outline"}
355 >
356 {alreadyAdded
357 ? gt("Added")
358 : isPreparing
359 ? progressLabel
360 : gt("Add", { $context: "verb, adds an agent" })}
361 </Button>
362 </div>
363 </div>
364 </article>
365 );
366}