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