Open History to see the last commit
1import type {
2 AcpRegistryConfigurableProvider,
3 AcpRegistrySession,
4 EnvironmentId,
5 ProjectId,
6 ProviderInstanceId,
7 ServerProvider,
8} from "@t3tools/contracts";
9import {
10 isAtomCommandInterrupted,
11 squashAtomCommandFailure,
12 type AtomCommandResult,
13} from "@t3tools/client-runtime/state/runtime";
14import { useState } from "react";
15
16import { ensureLocalApi } from "../../localApi";
17import { serverEnvironment } from "../../state/server";
18import { useAtomCommand } from "../../state/use-atom-command";
19import { Button } from "../ui/button";
20import { Input } from "../ui/input";
21import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
22import { toastManager } from "../ui/toast";
23
24interface AcpSessionProject {
25 readonly id: ProjectId;
26 readonly title: string;
27 readonly workspaceRoot: string;
28}
29
30function reportFailure(title: string, result: AtomCommandResult<unknown, unknown>) {
31 if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return;
32 const error = squashAtomCommandFailure(result);
33 toastManager.add({
34 type: "error",
35 title,
36 description: error instanceof Error ? error.message : "The ACP operation failed.",
37 });
38}
39
40export function AcpSessionManagementSection(props: {
41 readonly environmentId: EnvironmentId;
42 readonly instanceId: ProviderInstanceId;
43 readonly provider: ServerProvider;
44 readonly projects: ReadonlyArray<AcpSessionProject>;
45 readonly readOnly: boolean;
46}) {
47 const [projectId, setProjectId] = useState<ProjectId | null>(props.projects[0]?.id ?? null);
48 const [sessions, setSessions] = useState<ReadonlyArray<AcpRegistrySession>>([]);
49 const [nextCursor, setNextCursor] = useState<string | null>(null);
50 const [loading, setLoading] = useState(false);
51 const [importingSessionId, setImportingSessionId] = useState<string | null>(null);
52 const [deletingSessionId, setDeletingSessionId] = useState<string | null>(null);
53 const [loggingOut, setLoggingOut] = useState(false);
54 const [providers, setProviders] = useState<ReadonlyArray<AcpRegistryConfigurableProvider>>([]);
55 const [loadingProviders, setLoadingProviders] = useState(false);
56 const [savingProviderId, setSavingProviderId] = useState<string | null>(null);
57 const [providerDrafts, setProviderDrafts] = useState<
58 Readonly<Record<string, { apiType: string; baseUrl: string; headers: string }>>
59 >({});
60 const listSessions = useAtomCommand(serverEnvironment.listAcpRegistrySessions, {
61 reportFailure: false,
62 });
63 const importSession = useAtomCommand(serverEnvironment.importAcpRegistrySession, {
64 reportFailure: false,
65 });
66 const deleteSession = useAtomCommand(serverEnvironment.deleteAcpRegistrySession, {
67 reportFailure: false,
68 });
69 const listProviders = useAtomCommand(serverEnvironment.listAcpRegistryProviders, {
70 reportFailure: false,
71 });
72 const setProvider = useAtomCommand(serverEnvironment.setAcpRegistryProvider, {
73 reportFailure: false,
74 });
75 const disableProvider = useAtomCommand(serverEnvironment.disableAcpRegistryProvider, {
76 reportFailure: false,
77 });
78 const logout = useAtomCommand(serverEnvironment.logoutAcpRegistry, { reportFailure: false });
79 const canList = props.provider.nativeSessions?.canList === true;
80 const canImport =
81 props.provider.nativeSessions?.canLoad === true ||
82 props.provider.nativeSessions?.canResume === true;
83 const canLogout = props.provider.auth.canLogout === true;
84 const canDelete = props.provider.nativeSessions?.canDelete === true;
85 const canConfigureProviders = props.provider.configurableProviders === true;
86 const projectOperationPending =
87 loading ||
88 importingSessionId !== null ||
89 deletingSessionId !== null ||
90 loadingProviders ||
91 savingProviderId !== null;
92
93 if (!canList && !canLogout && !canConfigureProviders) return null;
94
95 const loadSessions = async (cursor?: string) => {
96 if (projectId === null || loading) return;
97 setLoading(true);
98 const result = await listSessions({
99 environmentId: props.environmentId,
100 input: {
101 instanceId: props.instanceId,
102 projectId,
103 ...(cursor === undefined ? {} : { cursor }),
104 },
105 });
106 setLoading(false);
107 if (result._tag === "Success") {
108 setSessions((current) =>
109 cursor === undefined ? result.value.sessions : [...current, ...result.value.sessions],
110 );
111 setNextCursor(result.value.nextCursor);
112 return;
113 }
114 reportFailure("Could not list ACP sessions", result);
115 };
116
117 const importNativeSession = async (session: AcpRegistrySession) => {
118 if (projectId === null || importingSessionId !== null) return;
119 setImportingSessionId(session.sessionId);
120 const result = await importSession({
121 environmentId: props.environmentId,
122 input: {
123 instanceId: props.instanceId,
124 projectId,
125 sessionId: session.sessionId,
126 title: session.title,
127 updatedAt: session.updatedAt,
128 },
129 });
130 setImportingSessionId(null);
131 if (result._tag === "Success") {
132 setSessions((current) =>
133 current.map((candidate) =>
134 candidate.sessionId === session.sessionId
135 ? { ...candidate, importedThreadId: result.value.threadId }
136 : candidate,
137 ),
138 );
139 toastManager.add({
140 type: "success",
141 title: result.value.imported ? "ACP session imported" : "ACP session already imported",
142 });
143 return;
144 }
145 reportFailure("Could not import ACP session", result);
146 };
147
148 const deleteNativeSession = async (session: AcpRegistrySession) => {
149 if (projectId === null || deletingSessionId !== null || session.importedThreadId !== null)
150 return;
151 const confirmed = await ensureLocalApi().dialogs.confirm(
152 `Permanently delete native ACP session "${session.title ?? session.sessionId}"?`,
153 { variant: "destructive" },
154 );
155 if (!confirmed) return;
156 setDeletingSessionId(session.sessionId);
157 const result = await deleteSession({
158 environmentId: props.environmentId,
159 input: { instanceId: props.instanceId, projectId, sessionId: session.sessionId },
160 });
161 setDeletingSessionId(null);
162 if (result._tag === "Success") {
163 setSessions((current) =>
164 current.filter((candidate) => candidate.sessionId !== session.sessionId),
165 );
166 toastManager.add({ type: "success", title: "ACP session deleted" });
167 return;
168 }
169 reportFailure("Could not delete ACP session", result);
170 };
171
172 const loadProviders = async () => {
173 if (projectId === null || loadingProviders) return;
174 setLoadingProviders(true);
175 const result = await listProviders({
176 environmentId: props.environmentId,
177 input: { instanceId: props.instanceId, projectId },
178 });
179 setLoadingProviders(false);
180 if (result._tag === "Success") {
181 setProviders(result.value.providers);
182 setProviderDrafts(
183 Object.fromEntries(
184 result.value.providers.map((provider) => [
185 provider.providerId,
186 {
187 apiType: provider.current?.apiType ?? provider.supported[0] ?? "",
188 baseUrl: provider.current?.baseUrl ?? "",
189 headers: "",
190 },
191 ]),
192 ),
193 );
194 return;
195 }
196 reportFailure("Could not list ACP providers", result);
197 };
198
199 const saveProvider = async (provider: AcpRegistryConfigurableProvider) => {
200 if (projectId === null || savingProviderId !== null) return;
201 const draft = providerDrafts[provider.providerId];
202 if (draft === undefined || draft.apiType.length === 0 || draft.baseUrl.length === 0) return;
203 let headers: Record<string, string> | undefined;
204 if (draft.headers.trim().length > 0) {
205 try {
206 const parsed: unknown = JSON.parse(draft.headers);
207 if (
208 typeof parsed !== "object" ||
209 parsed === null ||
210 Array.isArray(parsed) ||
211 !Object.values(parsed).every((value) => typeof value === "string")
212 ) {
213 throw new Error("Headers must be a JSON object with string values.");
214 }
215 headers = parsed as Record<string, string>;
216 } catch (error) {
217 toastManager.add({
218 type: "error",
219 title: "Invalid provider headers",
220 description: error instanceof Error ? error.message : "Headers must be valid JSON.",
221 });
222 return;
223 }
224 }
225 setSavingProviderId(provider.providerId);
226 const result = await setProvider({
227 environmentId: props.environmentId,
228 input: {
229 instanceId: props.instanceId,
230 projectId,
231 providerId: provider.providerId,
232 apiType: draft.apiType,
233 baseUrl: draft.baseUrl,
234 ...(headers === undefined ? {} : { headers }),
235 },
236 });
237 setSavingProviderId(null);
238 if (result._tag === "Success") {
239 toastManager.add({ type: "success", title: "ACP provider configured" });
240 await loadProviders();
241 return;
242 }
243 reportFailure("Could not configure ACP provider", result);
244 };
245
246 const disableConfiguredProvider = async (provider: AcpRegistryConfigurableProvider) => {
247 if (projectId === null || savingProviderId !== null || provider.required) return;
248 const confirmed = await ensureLocalApi().dialogs.confirm(
249 `Disable ACP provider "${provider.providerId}"?`,
250 { variant: "destructive" },
251 );
252 if (!confirmed) return;
253 setSavingProviderId(provider.providerId);
254 const result = await disableProvider({
255 environmentId: props.environmentId,
256 input: { instanceId: props.instanceId, projectId, providerId: provider.providerId },
257 });
258 setSavingProviderId(null);
259 if (result._tag === "Success") {
260 toastManager.add({ type: "success", title: "ACP provider disabled" });
261 await loadProviders();
262 return;
263 }
264 reportFailure("Could not disable ACP provider", result);
265 };
266
267 const logoutProvider = async () => {
268 if (loggingOut) return;
269 setLoggingOut(true);
270 const result = await logout({
271 environmentId: props.environmentId,
272 input: { instanceId: props.instanceId },
273 });
274 setLoggingOut(false);
275 if (result._tag === "Success") {
276 setSessions([]);
277 setNextCursor(null);
278 toastManager.add({ type: "success", title: "Logged out of ACP agent" });
279 return;
280 }
281 reportFailure("Could not log out of ACP agent", result);
282 };
283
284 return (
285 <div className="grid gap-3 border-t border-border/60 pt-4">
286 <div className="flex flex-wrap items-center justify-between gap-2">
287 <div>
288 <p className="text-xs font-medium text-foreground">Native sessions</p>
289 <p className="text-xs text-muted-foreground">
290 Resume agent-owned conversations as T3 threads.
291 </p>
292 </div>
293 {canLogout ? (
294 <Button
295 type="button"
296 size="xs"
297 variant="outline"
298 disabled={props.readOnly || loggingOut}
299 onClick={() => void logoutProvider()}
300 >
301 {loggingOut ? "Logging out" : "Log out"}
302 </Button>
303 ) : null}
304 </div>
305
306 {canList ? (
307 props.projects.length === 0 ? (
308 <p className="text-xs text-muted-foreground">
309 Add a project on this device before importing native sessions.
310 </p>
311 ) : (
312 <>
313 <div className="flex flex-wrap items-center gap-2">
314 <Select
315 value={projectId ?? ""}
316 disabled={props.readOnly || projectOperationPending}
317 onValueChange={(value) => {
318 if (value === null) return;
319 setProjectId(value as ProjectId);
320 setSessions([]);
321 setNextCursor(null);
322 setProviders([]);
323 setProviderDrafts({});
324 }}
325 >
326 <SelectTrigger aria-label="Project for ACP sessions" className="min-w-48" size="xs">
327 <SelectValue>
328 {props.projects.find((project) => project.id === projectId)?.title}
329 </SelectValue>
330 </SelectTrigger>
331 <SelectPopup>
332 {props.projects.map((project) => (
333 <SelectItem key={project.id} value={project.id}>
334 {project.title}
335 </SelectItem>
336 ))}
337 </SelectPopup>
338 </Select>
339 <Button
340 type="button"
341 size="xs"
342 variant="outline"
343 disabled={props.readOnly || loading || projectId === null}
344 onClick={() => void loadSessions()}
345 >
346 {loading ? "Loading" : sessions.length === 0 ? "List sessions" : "Refresh"}
347 </Button>
348 </div>
349
350 {sessions.length > 0 ? (
351 <div className="divide-y divide-border/60 border-y border-border/60">
352 {sessions.map((session) => (
353 <div
354 key={session.sessionId}
355 className="flex min-w-0 items-center justify-between gap-3 py-2"
356 >
357 <div className="min-w-0">
358 <p className="truncate text-xs text-foreground">
359 {session.title ?? session.sessionId}
360 </p>
361 <code className="block truncate text-[10px] text-muted-foreground">
362 {session.sessionId}
363 </code>
364 </div>
365 <div className="flex shrink-0 items-center gap-1">
366 <Button
367 type="button"
368 size="xs"
369 variant="ghost-muted"
370 disabled={
371 props.readOnly ||
372 !canImport ||
373 session.importedThreadId !== null ||
374 importingSessionId !== null
375 }
376 onClick={() => void importNativeSession(session)}
377 >
378 {session.importedThreadId !== null
379 ? "Imported"
380 : importingSessionId === session.sessionId
381 ? "Importing"
382 : "Import"}
383 </Button>
384 {canDelete ? (
385 <Button
386 type="button"
387 size="xs"
388 variant="ghost-muted"
389 disabled={
390 props.readOnly ||
391 session.importedThreadId !== null ||
392 deletingSessionId !== null
393 }
394 onClick={() => void deleteNativeSession(session)}
395 >
396 {deletingSessionId === session.sessionId ? "Deleting" : "Delete"}
397 </Button>
398 ) : null}
399 </div>
400 </div>
401 ))}
402 </div>
403 ) : null}
404
405 {nextCursor !== null ? (
406 <Button
407 type="button"
408 size="xs"
409 variant="ghost-muted"
410 className="w-fit"
411 disabled={props.readOnly || loading}
412 onClick={() => void loadSessions(nextCursor)}
413 >
414 {loading ? "Loading" : "Load more"}
415 </Button>
416 ) : null}
417 </>
418 )
419 ) : null}
420
421 {canConfigureProviders ? (
422 <div className="grid gap-3 border-t border-border/60 pt-4">
423 <div className="flex flex-wrap items-center justify-between gap-2">
424 <div>
425 <p className="text-xs font-medium text-foreground">Agent providers</p>
426 <p className="text-xs text-muted-foreground">
427 Configure non-secret routing. Headers are write-only.
428 </p>
429 </div>
430 <Button
431 type="button"
432 size="xs"
433 variant="outline"
434 disabled={props.readOnly || loadingProviders || projectId === null}
435 onClick={() => void loadProviders()}
436 >
437 {loadingProviders ? "Loading" : providers.length === 0 ? "List providers" : "Refresh"}
438 </Button>
439 </div>
440
441 {!canList && props.projects.length > 1 ? (
442 <Select
443 value={projectId ?? ""}
444 disabled={props.readOnly || projectOperationPending}
445 onValueChange={(value) => {
446 if (value === null) return;
447 setProjectId(value as ProjectId);
448 setProviders([]);
449 setProviderDrafts({});
450 }}
451 >
452 <SelectTrigger aria-label="Project for ACP providers" className="min-w-48" size="xs">
453 <SelectValue>
454 {props.projects.find((project) => project.id === projectId)?.title}
455 </SelectValue>
456 </SelectTrigger>
457 <SelectPopup>
458 {props.projects.map((project) => (
459 <SelectItem key={project.id} value={project.id}>
460 {project.title}
461 </SelectItem>
462 ))}
463 </SelectPopup>
464 </Select>
465 ) : null}
466
467 {providers.length > 0 ? (
468 <div className="divide-y divide-border/60 border-y border-border/60">
469 {providers.map((provider) => {
470 const draft = providerDrafts[provider.providerId] ?? {
471 apiType: provider.current?.apiType ?? provider.supported[0] ?? "",
472 baseUrl: provider.current?.baseUrl ?? "",
473 headers: "",
474 };
475 const updateDraft = (update: Partial<typeof draft>) =>
476 setProviderDrafts((current) => ({
477 ...current,
478 [provider.providerId]: { ...draft, ...update },
479 }));
480 return (
481 <div key={provider.providerId} className="grid gap-2 py-3">
482 <div className="flex items-center justify-between gap-2">
483 <div className="min-w-0">
484 <p className="truncate text-xs font-medium text-foreground">
485 {provider.providerId}
486 </p>
487 <p className="text-[10px] text-muted-foreground">
488 {provider.current === null ? "Disabled" : "Configured"}
489 {provider.required ? " · Required" : ""}
490 </p>
491 </div>
492 <div className="flex items-center gap-1">
493 <Button
494 type="button"
495 size="xs"
496 variant="outline"
497 disabled={
498 props.readOnly ||
499 savingProviderId !== null ||
500 draft.apiType.length === 0 ||
501 draft.baseUrl.length === 0
502 }
503 onClick={() => void saveProvider(provider)}
504 >
505 {savingProviderId === provider.providerId ? "Saving" : "Save"}
506 </Button>
507 {!provider.required && provider.current !== null ? (
508 <Button
509 type="button"
510 size="xs"
511 variant="ghost-muted"
512 disabled={props.readOnly || savingProviderId !== null}
513 onClick={() => void disableConfiguredProvider(provider)}
514 >
515 Disable
516 </Button>
517 ) : null}
518 </div>
519 </div>
520 <div className="grid gap-2 sm:grid-cols-[9rem_minmax(0,1fr)]">
521 <Select
522 value={draft.apiType}
523 disabled={props.readOnly || savingProviderId !== null}
524 onValueChange={(value) => {
525 if (value !== null) updateDraft({ apiType: value });
526 }}
527 >
528 <SelectTrigger aria-label={`${provider.providerId} protocol`} size="sm">
529 <SelectValue>{draft.apiType}</SelectValue>
530 </SelectTrigger>
531 <SelectPopup>
532 {provider.supported.map((protocol) => (
533 <SelectItem key={protocol} value={protocol}>
534 {protocol}
535 </SelectItem>
536 ))}
537 </SelectPopup>
538 </Select>
539 <Input
540 size="sm"
541 type="url"
542 aria-label={`${provider.providerId} base URL`}
543 placeholder="https://api.example.com"
544 value={draft.baseUrl}
545 disabled={props.readOnly || savingProviderId !== null}
546 onValueChange={(value) => updateDraft({ baseUrl: value })}
547 />
548 </div>
549 <Input
550 size="sm"
551 type="password"
552 aria-label={`${provider.providerId} write-only headers JSON`}
553 placeholder='Write-only headers JSON, e.g. {"Authorization":"Bearer …"}'
554 value={draft.headers}
555 disabled={props.readOnly || savingProviderId !== null}
556 onValueChange={(value) => updateDraft({ headers: value })}
557 />
558 </div>
559 );
560 })}
561 </div>
562 ) : null}
563 </div>
564 ) : null}
565 </div>
566 );
567}