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