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

AcpSessionManagementSection.tsx

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