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

AcpRegistrySearchStep.tsx

316 lines10.9 KB

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