The best way to control Claude Code, Codex and more from any computer or phone

main
tsx 727 lines 27.3 KB
Raw
1 import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
2 import {
3 AuthOrchestrationOperateScope,
4 AuthProvidersManageScope,
5 AuthOrchestrationReadScope,
6 } from "@t3tools/contracts";
7 import { useEnvironmentScope, readEnvironmentScope } from "~/state/session";
8 import type {
9 AcpRegistryConfigurableProvider,
10 AcpRegistrySession,
11 EnvironmentId,
12 ProjectId,
13 ProviderInstanceId,
14 ServerProvider,
15 } from "@t3tools/contracts";
16 import {
17 isAtomCommandInterrupted,
18 squashAtomCommandFailure,
19 type AtomCommandResult,
20 } from "@t3tools/client-runtime/state/runtime";
21 import { useLayoutEffect, useRef, useState } from "react";
22 import { msg, T, useGT } from "gt-react";
23 import { m } from "../../i18n/messages";
24
25 import { ensureLocalApi } from "../../localApi";
26 import { serverEnvironment } from "../../state/server";
27 import { useAtomCommand } from "../../state/use-atom-command";
28 import { Button } from "../ui/button";
29 import { Input } from "../ui/input";
30 import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
31 import { toastManager } from "../ui/toast";
32 import { SettingsRow } from "./settingsLayout";
33
34 interface AcpSessionProject {
35 readonly id: ProjectId;
36 readonly title: string;
37 readonly workspaceRoot: string;
38 }
39
40 function needsImport(session: AcpRegistrySession) {
41 return session.importedThreadId === null || session.nativeHistoryPending === true;
42 }
43
44 function 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
57 function 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
86 interface AcpSessionManagementProps {
87 readonly environmentId: EnvironmentId;
88 readonly instanceId: ProviderInstanceId;
89 readonly provider: ServerProvider;
90 readonly projects: ReadonlyArray<AcpSessionProject>;
91 readonly readOnly: boolean;
92 }
93
94 export 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
112 function 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
256 ? gt("ACP session imported")
257 : gt("ACP session already imported"),
258 });
259 return;
260 }
261 reportFailure(gt("Could not import ACP session"), result);
262 };
263
264 const deleteNativeSession = async (session: AcpRegistrySession) => {
265 const generation = projectGeneration.current;
266 if (projectId === null || deletingSessionId !== null || session.importedThreadId !== null)
267 return;
268 const confirmed = await ensureLocalApi().dialogs.confirm(
269 gt('Permanently delete native ACP session "{session}"?', {
270 session: session.title ?? session.sessionId,
271 }),
272 { variant: "destructive" },
273 );
274 if (
275 generation !== projectGeneration.current ||
276 !confirmed ||
277 !readEnvironmentScope(props.environmentId, AuthOrchestrationOperateScope)
278 )
279 return;
280 setDeletingSessionId(session.sessionId);
281 const result = await deleteSession({
282 environmentId: props.environmentId,
283 input: { instanceId: props.instanceId, projectId, sessionId: session.sessionId },
284 });
285 if (generation !== projectGeneration.current) return;
286 setDeletingSessionId(null);
287 if (result._tag === "Success") {
288 deletionsDuringList.current?.add(session.sessionId);
289 setSessions((current) =>
290 current.filter((candidate) => candidate.sessionId !== session.sessionId),
291 );
292 return;
293 }
294 reportFailure(gt("Could not delete ACP session"), result);
295 };
296
297 const loadProviders = async (resetProviderId?: string) => {
298 const generation = projectGeneration.current;
299 if (projectId === null || loadingProviders) return;
300 setLoadingProviders(true);
301 const result = await listProviders({
302 environmentId: props.environmentId,
303 input: { instanceId: props.instanceId, projectId },
304 });
305 if (generation !== projectGeneration.current) return;
306 setLoadingProviders(false);
307 if (result._tag === "Success") {
308 setProviders(result.value.providers);
309 setProviderDrafts((current) =>
310 Object.fromEntries(
311 result.value.providers.map((provider) => [
312 provider.providerId,
313 (resetProviderId !== undefined && provider.providerId !== resetProviderId
314 ? current[provider.providerId]
315 : undefined) ?? {
316 apiType: provider.current?.apiType ?? provider.supported[0] ?? "",
317 baseUrl: provider.current?.baseUrl ?? "",
318 headers: "",
319 },
320 ]),
321 ),
322 );
323 return;
324 }
325 reportFailure(gt("Could not list ACP providers"), result);
326 };
327
328 const saveProvider = async (provider: AcpRegistryConfigurableProvider) => {
329 const generation = projectGeneration.current;
330 if (
331 !readEnvironmentScope(props.environmentId, AuthProvidersManageScope) ||
332 projectId === null ||
333 savingProviderId !== null ||
334 loadingProviders
335 )
336 return;
337 const draft = providerDrafts[provider.providerId];
338 if (draft === undefined || draft.apiType.length === 0 || draft.baseUrl.length === 0) return;
339 const parsedHeaders = parseProviderHeaders(draft.headers);
340 if (!parsedHeaders.ok) {
341 toastManager.add({
342 type: "error",
343 title: gt("Invalid provider headers"),
344 description: parsedHeaders.error,
345 });
346 return;
347 }
348 const headers = parsedHeaders.headers;
349 setSavingProviderId(provider.providerId);
350 const result = await setProvider({
351 environmentId: props.environmentId,
352 input: {
353 instanceId: props.instanceId,
354 projectId,
355 providerId: provider.providerId,
356 apiType: draft.apiType,
357 baseUrl: draft.baseUrl,
358 ...(headers === undefined ? {} : { headers }),
359 },
360 });
361 if (generation !== projectGeneration.current) return;
362 setSavingProviderId(null);
363 if (result._tag === "Success") {
364 await loadProviders(provider.providerId);
365 return;
366 }
367 reportFailure(gt("Could not configure ACP provider"), result);
368 };
369
370 const disableConfiguredProvider = async (provider: AcpRegistryConfigurableProvider) => {
371 const generation = projectGeneration.current;
372 if (projectId === null || savingProviderId !== null || loadingProviders || provider.required)
373 return;
374 const confirmed = await ensureLocalApi().dialogs.confirm(
375 gt('Disable ACP provider "{provider}"?', { provider: provider.providerId }),
376 { variant: "destructive" },
377 );
378 if (
379 generation !== projectGeneration.current ||
380 !confirmed ||
381 !readEnvironmentScope(props.environmentId, AuthProvidersManageScope)
382 )
383 return;
384 setSavingProviderId(provider.providerId);
385 const result = await disableProvider({
386 environmentId: props.environmentId,
387 input: { instanceId: props.instanceId, projectId, providerId: provider.providerId },
388 });
389 if (generation !== projectGeneration.current) return;
390 setSavingProviderId(null);
391 if (result._tag === "Success") {
392 await loadProviders(provider.providerId);
393 return;
394 }
395 reportFailure(gt("Could not disable ACP provider"), result);
396 };
397
398 const logoutProvider = async () => {
399 if (loggingOut || !readEnvironmentScope(props.environmentId, AuthProvidersManageScope)) return;
400 setLoggingOut(true);
401 const result = await logout({
402 environmentId: props.environmentId,
403 input: { instanceId: props.instanceId },
404 });
405 setLoggingOut(false);
406 if (result._tag === "Success") {
407 setSessions([]);
408 setNextCursor(null);
409 return;
410 }
411 reportFailure(gt("Could not log out of ACP agent"), result);
412 };
413
414 return (
415 <div className="grid gap-3">
416 <SettingsRow
417 title={gt("Native sessions")}
418 description={gt("Resume agent-owned conversations as T3 threads.")}
419 status={
420 canList && props.projects.length === 0
421 ? gt("Add a project before importing sessions.")
422 : undefined
423 }
424 control={
425 <div className="flex flex-wrap items-center gap-2">
426 {canLogout ? (
427 <Button
428 type="button"
429 size="sm"
430 variant="outline"
431 disabled={props.readOnly || loggingOut}
432 onClick={() => void logoutProvider()}
433 >
434 {loggingOut ? gt("Logging out") : gt("Log out")}
435 </Button>
436 ) : null}
437 {canList && props.projects.length > 0 ? (
438 <>
439 <Select
440 value={projectId ?? ""}
441 disabled={!canRead || projectOperationPending}
442 onValueChange={(value) => {
443 if (value === null) return;
444 props.onProjectChange(value as ProjectId);
445 }}
446 >
447 <SelectTrigger
448 aria-label={gt("Project for ACP sessions")}
449 className="w-40"
450 size="sm"
451 >
452 <SelectValue>
453 {props.projects.find((project) => project.id === projectId)?.title}
454 </SelectValue>
455 </SelectTrigger>
456 <SelectPopup>
457 {props.projects.map((project) => (
458 <SelectItem key={project.id} value={project.id}>
459 {project.title}
460 </SelectItem>
461 ))}
462 </SelectPopup>
463 </Select>
464 <Button
465 type="button"
466 size="sm"
467 variant="outline"
468 disabled={!canRead || loading || projectId === null}
469 onClick={() => void loadSessions()}
470 >
471 {loading
472 ? gt("Loading")
473 : sessions.length === 0
474 ? gt("List sessions")
475 : gt("Refresh")}
476 </Button>
477 </>
478 ) : null}
479 </div>
480 }
481 >
482 {canList && (sessions.length > 0 || nextCursor !== null) ? (
483 <>
484 {sessions.length > 0 ? (
485 <div className="divide-y divide-border/60 border-y border-border/60">
486 {sessions.map((session) => (
487 <div
488 key={session.sessionId}
489 className="flex min-w-0 items-center justify-between gap-3 py-2"
490 >
491 <div className="min-w-0">
492 <p className="truncate text-xs text-foreground">
493 {session.title ?? session.sessionId}
494 </p>
495 <code className="block truncate text-3xs text-muted-foreground">
496 {session.sessionId}
497 </code>
498 </div>
499 <div className="flex shrink-0 items-center gap-1">
500 <Button
501 type="button"
502 size="xs"
503 variant="ghost-muted"
504 disabled={
505 !canOperate ||
506 !canImport ||
507 !needsImport(session) ||
508 importingSessionId !== null
509 }
510 onClick={() => void importNativeSession(session)}
511 >
512 {!needsImport(session)
513 ? gt("Imported")
514 : importingSessionId === session.sessionId
515 ? gt("Importing")
516 : gt("Import", { $context: "verb" })}
517 </Button>
518 {canDelete ? (
519 <Button
520 type="button"
521 size="xs"
522 variant="ghost-muted"
523 disabled={
524 !canOperate ||
525 session.importedThreadId !== null ||
526 deletingSessionId !== null
527 }
528 onClick={() => void deleteNativeSession(session)}
529 >
530 {deletingSessionId === session.sessionId
531 ? gt("Deleting")
532 : gt("Delete", { $context: "verb, deletes a session" })}
533 </Button>
534 ) : null}
535 </div>
536 </div>
537 ))}
538 </div>
539 ) : null}
540
541 {nextCursor !== null ? (
542 <Button
543 type="button"
544 size="xs"
545 variant="ghost-muted"
546 className="w-fit"
547 disabled={!canRead || loading}
548 onClick={() => void loadSessions(nextCursor)}
549 >
550 {loading ? gt("Loading") : gt("Load more")}
551 </Button>
552 ) : null}
553 </>
554 ) : null}
555 </SettingsRow>
556
557 {canConfigureProviders ? (
558 <div className="grid gap-3 border-t border-border/60 px-3 py-3 sm:px-4">
559 <div className="flex flex-wrap items-center justify-between gap-2">
560 <div>
561 <p className="text-xs font-medium text-foreground">
562 <T>Agent providers</T>
563 </p>
564 <p className="text-xs text-muted-foreground">
565 <T>Configure non-secret routing. Headers are write-only.</T>
566 </p>
567 </div>
568 <Button
569 type="button"
570 size="xs"
571 variant="outline"
572 disabled={
573 !canRead || loadingProviders || savingProviderId !== null || projectId === null
574 }
575 onClick={() => void loadProviders()}
576 >
577 {loadingProviders
578 ? gt("Loading")
579 : providers.length === 0
580 ? gt("List providers")
581 : gt("Refresh")}
582 </Button>
583 </div>
584
585 {!canList && props.projects.length > 1 ? (
586 <Select
587 value={projectId ?? ""}
588 disabled={!canRead || projectOperationPending}
589 onValueChange={(value) => {
590 if (value === null) return;
591 props.onProjectChange(value as ProjectId);
592 }}
593 >
594 <SelectTrigger
595 aria-label={gt("Project for ACP providers")}
596 className="min-w-48"
597 size="xs"
598 >
599 <SelectValue>
600 {props.projects.find((project) => project.id === projectId)?.title}
601 </SelectValue>
602 </SelectTrigger>
603 <SelectPopup>
604 {props.projects.map((project) => (
605 <SelectItem key={project.id} value={project.id}>
606 {project.title}
607 </SelectItem>
608 ))}
609 </SelectPopup>
610 </Select>
611 ) : null}
612
613 {providers.length > 0 ? (
614 <div className="divide-y divide-border/60 border-y border-border/60">
615 {providers.map((provider) => {
616 const draft = providerDrafts[provider.providerId] ?? {
617 apiType: provider.current?.apiType ?? provider.supported[0] ?? "",
618 baseUrl: provider.current?.baseUrl ?? "",
619 headers: "",
620 };
621 const updateDraft = (update: Partial<typeof draft>) =>
622 setProviderDrafts((current) => ({
623 ...current,
624 [provider.providerId]: { ...draft, ...update },
625 }));
626 return (
627 <div key={provider.providerId} className="grid gap-2 py-3">
628 <div className="flex items-center justify-between gap-2">
629 <div className="min-w-0">
630 <p className="truncate text-xs font-medium text-foreground">
631 {provider.providerId}
632 </p>
633 <p className="text-3xs text-muted-foreground">
634 {provider.current === null
635 ? gt("Disabled", { $context: "ACP provider status" })
636 : gt("Configured")}
637 {provider.required ? ` · ${gt("Required")}` : ""}
638 </p>
639 </div>
640 <div className="flex items-center gap-1">
641 <Button
642 type="button"
643 size="xs"
644 variant="outline"
645 disabled={
646 props.readOnly ||
647 savingProviderId !== null ||
648 loadingProviders ||
649 draft.apiType.length === 0 ||
650 draft.baseUrl.length === 0
651 }
652 onClick={() => void saveProvider(provider)}
653 >
654 {savingProviderId === provider.providerId
655 ? gt("Saving")
656 : gt("Save", { $context: "verb" })}
657 </Button>
658 {!provider.required && provider.current !== null ? (
659 <Button
660 type="button"
661 size="xs"
662 variant="ghost-muted"
663 disabled={
664 props.readOnly || savingProviderId !== null || loadingProviders
665 }
666 onClick={() => void disableConfiguredProvider(provider)}
667 >
668 <T>Disable</T>
669 </Button>
670 ) : null}
671 </div>
672 </div>
673 <div className="grid gap-2 sm:grid-cols-[9rem_minmax(0,1fr)]">
674 <Select
675 value={draft.apiType}
676 disabled={props.readOnly || savingProviderId !== null}
677 onValueChange={(value) => {
678 if (value !== null) updateDraft({ apiType: value });
679 }}
680 >
681 <SelectTrigger
682 aria-label={gt("{provider} protocol", { provider: provider.providerId })}
683 size="sm"
684 >
685 <SelectValue>{draft.apiType}</SelectValue>
686 </SelectTrigger>
687 <SelectPopup>
688 {provider.supported.map((protocol) => (
689 <SelectItem key={protocol} value={protocol}>
690 {protocol}
691 </SelectItem>
692 ))}
693 </SelectPopup>
694 </Select>
695 <Input
696 size="sm"
697 type="url"
698 aria-label={gt("{provider} base URL", { provider: provider.providerId })}
699 placeholder="https://api.example.com"
700 value={draft.baseUrl}
701 disabled={props.readOnly || savingProviderId !== null}
702 onValueChange={(value) => updateDraft({ baseUrl: value })}
703 />
704 </div>
705 <Input
706 size="sm"
707 type="password"
708 aria-label={gt("{provider} write-only headers JSON", {
709 provider: provider.providerId,
710 })}
711 placeholder={gt("Write-only headers JSON, e.g. {example}", {
712 example: '{"Authorization":"Bearer …"}',
713 })}
714 value={draft.headers}
715 disabled={props.readOnly || savingProviderId !== null}
716 onValueChange={(value) => updateDraft({ headers: value })}
717 />
718 </div>
719 );
720 })}
721 </div>
722 ) : null}
723 </div>
724 ) : null}
725 </div>
726 );
727 }