The best way to control Claude Code, Codex and more from any computer or phone

main
tsx 353 lines 12 KB
Raw
1 import { pipe } from "effect/Function";
2 import {
3 ACP_REGISTRY_MAX_AGENTS,
4 ACP_REGISTRY_SEARCH_QUERY_MAX_LENGTH,
5 AuthProvidersManageScope,
6 } from "@t3tools/contracts";
7 import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";
8 import {
9 isAtomCommandInterrupted,
10 squashAtomCommandFailure,
11 } from "@t3tools/client-runtime/state/runtime";
12 import type {
13 AcpRegistryPrepareResult,
14 AcpRegistrySearchAgent,
15 EnvironmentId,
16 ProviderInstanceConfig,
17 } from "@t3tools/contracts";
18 import { ExternalLinkIcon, SearchIcon } from "lucide-react";
19 import { msg, T, useGT, useMessages, Var } from "gt-react";
20 import { type FormEvent, useState } from "react";
21
22 import { useDeadlinePassed } from "../../hooks/useDeadline";
23 import { m } from "../../i18n/messages";
24 import { serverEnvironment } from "../../state/server";
25 import { useEnvironmentQuery } from "../../state/query";
26 import { useAtomCommand } from "../../state/use-atom-command";
27 import { Alert, AlertDescription } from "../ui/alert";
28 import { Button } from "../ui/button";
29 import { InputGroup, InputGroupAddon, InputGroupInput } from "../ui/input-group";
30 import { ScrollArea } from "../ui/scroll-area";
31 import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
32 import { isConfiguredAcpRegistryAgent } from "./AddProviderInstanceDialog.logic";
33 import { ProviderDriverKind } from "@t3tools/contracts";
34 import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon";
35 import { providerClients } from "./providerDriverMeta";
36
37 function 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
43 const ACP_REGISTRY_SEARCH_DEBOUNCE_MS = 300;
44 const FIRST_CLASS_REGISTRY_AGENT_IDS = new Set(
45 providerClients.definitions.flatMap((definition) => definition.acpRegistryAgentIds ?? []),
46 );
47
48 function 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 */
66 export 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
132 export type AcpRegistrySearch = ReturnType<typeof useAcpRegistrySearch>;
133
134 interface 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
143 export 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 <InputGroupInput
182 aria-label={gt("Search ACP Registry")}
183 maxLength={ACP_REGISTRY_SEARCH_QUERY_MAX_LENGTH}
184 disabled={preparingId !== null}
185 onChange={(event) => registry.type(event.currentTarget.value)}
186 placeholder={gt("Search agents…")}
187 size="sm"
188 type="search"
189 value={query}
190 />
191 </InputGroup>
192 <Button
193 disabled={preparingId !== null}
194 onClick={onManualConfiguration}
195 size="sm"
196 type="button"
197 variant="ghost-muted"
198 >
199 <T>Enter manually</T>
200 </Button>
201 {onLocalConfiguration ? (
202 <Button
203 disabled={preparingId !== null}
204 onClick={onLocalConfiguration}
205 size="sm"
206 type="button"
207 variant="outline"
208 >
209 <T>Local ACP command</T>
210 </Button>
211 ) : null}
212 </form>
213
214 <div className="sr-only" role="status">
215 {isInitialSearch
216 ? gt("Searching the ACP Registry.")
217 : isRefreshing
218 ? gt("Refreshing ACP Registry results.")
219 : results
220 ? gt(
221 "{count, plural, one {{count} compatible agent found.} other {{count} compatible agents found.}}",
222 { count: resultCount },
223 )
224 : ""}
225 </div>
226
227 {search.error || prepareError ? (
228 <Alert variant="error" role="status" aria-live="polite">
229 <AlertDescription>{prepareError ?? search.error}</AlertDescription>
230 </Alert>
231 ) : null}
232
233 {isInitialSearch ? (
234 <div className="flex min-h-20 items-center justify-center text-sm text-muted-foreground">
235 <T>Searching the registry...</T>
236 </div>
237 ) : null}
238
239 {results ? (
240 results.length === 0 ? (
241 <div className="flex min-h-28 flex-col items-center justify-center rounded-2xl border border-dashed px-4 text-center">
242 <p className="text-sm font-medium">
243 <T>No compatible agents found</T>
244 </p>
245 <p className="mt-1 text-xs text-muted-foreground">
246 <T>Try a broader search.</T>
247 </p>
248 </div>
249 ) : (
250 <ScrollArea scrollFade className="max-h-64">
251 <div className="pr-2.5">
252 {results.map((agent) => (
253 <AcpRegistryAgentRow
254 agent={agent}
255 alreadyAdded={isConfiguredAcpRegistryAgent(providerInstances, agent.id)}
256 canAdd={canManageProviders && preparingId === null}
257 isPreparing={preparingId === agent.id}
258 key={agent.id}
259 onAdd={handlePrepare}
260 />
261 ))}
262 </div>
263 </ScrollArea>
264 )
265 ) : null}
266 </section>
267 );
268 }
269
270 function AcpRegistryAgentRow({
271 agent,
272 alreadyAdded,
273 canAdd,
274 isPreparing,
275 onAdd,
276 }: {
277 readonly agent: AcpRegistrySearchAgent;
278 readonly alreadyAdded: boolean;
279 readonly canAdd: boolean;
280 readonly isPreparing: boolean;
281 readonly onAdd: (agent: AcpRegistrySearchAgent) => void;
282 }) {
283 const gt = useGT();
284 const progressLabel = agent.distribution === "binary" ? gt("Downloading") : gt("Preparing");
285 const aboutUrl = agent.website || agent.repository;
286 return (
287 <article className="min-w-0 py-2.5">
288 <div className="flex min-w-0 items-center justify-between gap-3">
289 <div className="flex min-w-0 flex-1 items-center gap-3">
290 <ProviderInstanceIcon
291 driverKind={ProviderDriverKind.make("acpRegistry")}
292 displayName={agent.name}
293 acpRegistryAgentId={agent.id}
294 acpRegistryIconUrl={agent.icon ?? undefined}
295 iconClassName="size-6 rounded-md text-muted-foreground"
296 />
297 <div className="min-w-0 flex-1">
298 <div className="flex min-w-0 items-baseline gap-2">
299 <h4 className="min-w-0 truncate text-sm font-medium text-foreground">{agent.name}</h4>
300 </div>
301 {agent.description ? (
302 <p className="mt-0.5 truncate text-xs text-muted-foreground">{agent.description}</p>
303 ) : null}
304 </div>
305 </div>
306 <div className="flex shrink-0 items-center gap-1.5">
307 {aboutUrl ? (
308 <Tooltip>
309 <TooltipTrigger
310 render={
311 <Button
312 size="icon-xs"
313 variant="ghost-muted"
314 aria-label={gt("About {name}", { name: agent.name })}
315 render={<a href={aboutUrl} target="_blank" rel="noreferrer" />}
316 >
317 <ExternalLinkIcon />
318 </Button>
319 }
320 />
321 <TooltipPopup>
322 <T>
323 About <Var>{agent.name}</Var>
324 </T>
325 </TooltipPopup>
326 </Tooltip>
327 ) : null}
328 <Button
329 aria-label={
330 alreadyAdded
331 ? gt("Already added {name}", { name: agent.name })
332 : isPreparing
333 ? agent.distribution === "binary"
334 ? gt("Downloading {name}", { name: agent.name })
335 : gt("Preparing {name}", { name: agent.name })
336 : gt("Add {name}", { name: agent.name })
337 }
338 disabled={!canAdd || alreadyAdded}
339 onClick={() => onAdd(agent)}
340 size="xs"
341 variant={isPreparing ? "secondary" : "outline"}
342 >
343 {alreadyAdded
344 ? gt("Added")
345 : isPreparing
346 ? progressLabel
347 : gt("Add", { $context: "verb, adds an agent" })}
348 </Button>
349 </div>
350 </div>
351 </article>
352 );
353 }