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 () => {
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(
225 Object.fromEntries(
226 result.value.providers.map((provider) => [
227 provider.providerId,
228 {
229 apiType: provider.current?.apiType ?? provider.supported[0] ?? "",
230 baseUrl: provider.current?.baseUrl ?? "",
231 headers: "",
232 },
233 ]),
234 ),
235 );
236 return;
237 }
238 reportFailure("Could not list ACP providers", result);
239 };
240
241 const saveProvider = async (provider: AcpRegistryConfigurableProvider) => {
242 if (
243 !readEnvironmentScope(props.environmentId, AuthProvidersManageScope) ||
244 projectId === null ||
245 savingProviderId !== null
246 )
247 return;
248 const draft = providerDrafts[provider.providerId];
249 if (draft === undefined || draft.apiType.length === 0 || draft.baseUrl.length === 0) return;
250 const parsedHeaders = parseProviderHeaders(draft.headers);
251 if (!parsedHeaders.ok) {
252 toastManager.add({
253 type: "error",
254 title: "Invalid provider headers",
255 description: parsedHeaders.error,
256 });
257 return;
258 }
259 const headers = parsedHeaders.headers;
260 setSavingProviderId(provider.providerId);
261 const result = await setProvider({
262 environmentId: props.environmentId,
263 input: {
264 instanceId: props.instanceId,
265 projectId,
266 providerId: provider.providerId,
267 apiType: draft.apiType,
268 baseUrl: draft.baseUrl,
269 ...(headers === undefined ? {} : { headers }),
270 },
271 });
272 setSavingProviderId(null);
273 if (result._tag === "Success") {
274 toastManager.add({ type: "success", title: "ACP provider configured" });
275 await loadProviders();
276 return;
277 }
278 reportFailure("Could not configure ACP provider", result);
279 };
280
281 const disableConfiguredProvider = async (provider: AcpRegistryConfigurableProvider) => {
282 if (projectId === null || savingProviderId !== null || provider.required) return;
283 const confirmed = await ensureLocalApi().dialogs.confirm(
284 `Disable ACP provider "${provider.providerId}"?`,
285 { variant: "destructive" },
286 );
287 if (!confirmed || !readEnvironmentScope(props.environmentId, AuthProvidersManageScope)) return;
288 setSavingProviderId(provider.providerId);
289 const result = await disableProvider({
290 environmentId: props.environmentId,
291 input: { instanceId: props.instanceId, projectId, providerId: provider.providerId },
292 });
293 setSavingProviderId(null);
294 if (result._tag === "Success") {
295 toastManager.add({ type: "success", title: "ACP provider disabled" });
296 await loadProviders();
297 return;
298 }
299 reportFailure("Could not disable ACP provider", result);
300 };
301
302 const logoutProvider = async () => {
303 if (loggingOut || !readEnvironmentScope(props.environmentId, AuthProvidersManageScope)) return;
304 setLoggingOut(true);
305 const result = await logout({
306 environmentId: props.environmentId,
307 input: { instanceId: props.instanceId },
308 });
309 setLoggingOut(false);
310 if (result._tag === "Success") {
311 setSessions([]);
312 setNextCursor(null);
313 toastManager.add({ type: "success", title: "Logged out of ACP agent" });
314 return;
315 }
316 reportFailure("Could not log out of ACP agent", result);
317 };
318
319 return (
320 <div className="grid gap-3">
321 <SettingsRow
322 title="Native sessions"
323 description="Resume agent-owned conversations as T3 threads."
324 status={
325 canList && props.projects.length === 0
326 ? "Add a project before importing sessions."
327 : undefined
328 }
329 control={
330 <div className="flex flex-wrap items-center gap-2">
331 {canLogout ? (
332 <Button
333 type="button"
334 size="sm"
335 variant="outline"
336 disabled={props.readOnly || loggingOut}
337 onClick={() => void logoutProvider()}
338 >
339 {loggingOut ? "Logging out" : "Log out"}
340 </Button>
341 ) : null}
342 {canList && props.projects.length > 0 ? (
343 <>
344 <Select
345 value={projectId ?? ""}
346 disabled={!canRead || projectOperationPending}
347 onValueChange={(value) => {
348 if (value === null) return;
349 setProjectId(value as ProjectId);
350 setSessions([]);
351 setNextCursor(null);
352 setProviders([]);
353 setProviderDrafts({});
354 }}
355 >
356 <SelectTrigger aria-label="Project for ACP sessions" className="w-40" size="sm">
357 <SelectValue>
358 {props.projects.find((project) => project.id === projectId)?.title}
359 </SelectValue>
360 </SelectTrigger>
361 <SelectPopup>
362 {props.projects.map((project) => (
363 <SelectItem key={project.id} value={project.id}>
364 {project.title}
365 </SelectItem>
366 ))}
367 </SelectPopup>
368 </Select>
369 <Button
370 type="button"
371 size="sm"
372 variant="outline"
373 disabled={!canRead || loading || projectId === null}
374 onClick={() => void loadSessions()}
375 >
376 {loading ? "Loading" : sessions.length === 0 ? "List sessions" : "Refresh"}
377 </Button>
378 </>
379 ) : null}
380 </div>
381 }
382 >
383 {canList && (sessions.length > 0 || nextCursor !== null) ? (
384 <>
385 {sessions.length > 0 ? (
386 <div className="divide-y divide-border/60 border-y border-border/60">
387 {sessions.map((session) => (
388 <div
389 key={session.sessionId}
390 className="flex min-w-0 items-center justify-between gap-3 py-2"
391 >
392 <div className="min-w-0">
393 <p className="truncate text-xs text-foreground">
394 {session.title ?? session.sessionId}
395 </p>
396 <code className="block truncate text-3xs text-muted-foreground">
397 {session.sessionId}
398 </code>
399 </div>
400 <div className="flex shrink-0 items-center gap-1">
401 <Button
402 type="button"
403 size="xs"
404 variant="ghost-muted"
405 disabled={
406 !canOperate ||
407 !canImport ||
408 session.importedThreadId !== null ||
409 importingSessionId !== null
410 }
411 onClick={() => void importNativeSession(session)}
412 >
413 {session.importedThreadId !== null
414 ? "Imported"
415 : importingSessionId === session.sessionId
416 ? "Importing"
417 : "Import"}
418 </Button>
419 {canDelete ? (
420 <Button
421 type="button"
422 size="xs"
423 variant="ghost-muted"
424 disabled={
425 !canOperate ||
426 session.importedThreadId !== null ||
427 deletingSessionId !== null
428 }
429 onClick={() => void deleteNativeSession(session)}
430 >
431 {deletingSessionId === session.sessionId ? "Deleting" : "Delete"}
432 </Button>
433 ) : null}
434 </div>
435 </div>
436 ))}
437 </div>
438 ) : null}
439
440 {nextCursor !== null ? (
441 <Button
442 type="button"
443 size="xs"
444 variant="ghost-muted"
445 className="w-fit"
446 disabled={!canRead || loading}
447 onClick={() => void loadSessions(nextCursor)}
448 >
449 {loading ? "Loading" : "Load more"}
450 </Button>
451 ) : null}
452 </>
453 ) : null}
454 </SettingsRow>
455
456 {canConfigureProviders ? (
457 <div className="grid gap-3 border-t border-border/60 px-3 py-3 sm:px-4">
458 <div className="flex flex-wrap items-center justify-between gap-2">
459 <div>
460 <p className="text-xs font-medium text-foreground">Agent providers</p>
461 <p className="text-xs text-muted-foreground">
462 Configure non-secret routing. Headers are write-only.
463 </p>
464 </div>
465 <Button
466 type="button"
467 size="xs"
468 variant="outline"
469 disabled={!canRead || loadingProviders || projectId === null}
470 onClick={() => void loadProviders()}
471 >
472 {loadingProviders ? "Loading" : providers.length === 0 ? "List providers" : "Refresh"}
473 </Button>
474 </div>
475
476 {!canList && props.projects.length > 1 ? (
477 <Select
478 value={projectId ?? ""}
479 disabled={!canRead || projectOperationPending}
480 onValueChange={(value) => {
481 if (value === null) return;
482 setProjectId(value as ProjectId);
483 setProviders([]);
484 setProviderDrafts({});
485 }}
486 >
487 <SelectTrigger aria-label="Project for ACP providers" className="min-w-48" size="xs">
488 <SelectValue>
489 {props.projects.find((project) => project.id === projectId)?.title}
490 </SelectValue>
491 </SelectTrigger>
492 <SelectPopup>
493 {props.projects.map((project) => (
494 <SelectItem key={project.id} value={project.id}>
495 {project.title}
496 </SelectItem>
497 ))}
498 </SelectPopup>
499 </Select>
500 ) : null}
501
502 {providers.length > 0 ? (
503 <div className="divide-y divide-border/60 border-y border-border/60">
504 {providers.map((provider) => {
505 const draft = providerDrafts[provider.providerId] ?? {
506 apiType: provider.current?.apiType ?? provider.supported[0] ?? "",
507 baseUrl: provider.current?.baseUrl ?? "",
508 headers: "",
509 };
510 const updateDraft = (update: Partial<typeof draft>) =>
511 setProviderDrafts((current) => ({
512 ...current,
513 [provider.providerId]: { ...draft, ...update },
514 }));
515 return (
516 <div key={provider.providerId} className="grid gap-2 py-3">
517 <div className="flex items-center justify-between gap-2">
518 <div className="min-w-0">
519 <p className="truncate text-xs font-medium text-foreground">
520 {provider.providerId}
521 </p>
522 <p className="text-3xs text-muted-foreground">
523 {provider.current === null ? "Disabled" : "Configured"}
524 {provider.required ? " · Required" : ""}
525 </p>
526 </div>
527 <div className="flex items-center gap-1">
528 <Button
529 type="button"
530 size="xs"
531 variant="outline"
532 disabled={
533 props.readOnly ||
534 savingProviderId !== null ||
535 draft.apiType.length === 0 ||
536 draft.baseUrl.length === 0
537 }
538 onClick={() => void saveProvider(provider)}
539 >
540 {savingProviderId === provider.providerId ? "Saving" : "Save"}
541 </Button>
542 {!provider.required && provider.current !== null ? (
543 <Button
544 type="button"
545 size="xs"
546 variant="ghost-muted"
547 disabled={props.readOnly || savingProviderId !== null}
548 onClick={() => void disableConfiguredProvider(provider)}
549 >
550 Disable
551 </Button>
552 ) : null}
553 </div>
554 </div>
555 <div className="grid gap-2 sm:grid-cols-[9rem_minmax(0,1fr)]">
556 <Select
557 value={draft.apiType}
558 disabled={props.readOnly || savingProviderId !== null}
559 onValueChange={(value) => {
560 if (value !== null) updateDraft({ apiType: value });
561 }}
562 >
563 <SelectTrigger aria-label={`${provider.providerId} protocol`} size="sm">
564 <SelectValue>{draft.apiType}</SelectValue>
565 </SelectTrigger>
566 <SelectPopup>
567 {provider.supported.map((protocol) => (
568 <SelectItem key={protocol} value={protocol}>
569 {protocol}
570 </SelectItem>
571 ))}
572 </SelectPopup>
573 </Select>
574 <Input
575 size="sm"
576 type="url"
577 aria-label={`${provider.providerId} base URL`}
578 placeholder="https://api.example.com"
579 value={draft.baseUrl}
580 disabled={props.readOnly || savingProviderId !== null}
581 onValueChange={(value) => updateDraft({ baseUrl: value })}
582 />
583 </div>
584 <Input
585 size="sm"
586 type="password"
587 aria-label={`${provider.providerId} write-only headers JSON`}
588 placeholder='Write-only headers JSON, e.g. {"Authorization":"Bearer …"}'
589 value={draft.headers}
590 disabled={props.readOnly || savingProviderId !== null}
591 onValueChange={(value) => updateDraft({ headers: value })}
592 />
593 </div>
594 );
595 })}
596 </div>
597 ) : null}
598 </div>
599 ) : null}
600 </div>
601 );
602}