Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AcpSessionManagementSection.tsx

676 lines25.7 KB

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