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