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