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

UsageAccessDialog.tsx

290 lines9.4 KB

1import {
2 type EnvironmentId,
3 type ProviderDriverKind,
4 type ProviderInstanceId,
5 type ProviderUsageAccess,
6 withProviderUsageAccess,
7} from "@t3tools/contracts";
8import { resolveProviderInstanceDisplayName } from "@t3tools/client-runtime/state/provider-instance-display";
9import { usageAccessReadsLabel } from "@t3tools/client-runtime/state/usage-access";
10import {
11 isAtomCommandInterrupted,
12 squashAtomCommandFailure,
13} from "@t3tools/client-runtime/state/runtime";
14import { useAtomValue } from "@effect/atom-react";
15import { T, useGT, useMessages } from "gt-react";
16import { useState } from "react";
17​
18import { appAtomRegistry } from "~/rpc/atomRegistry";
19import { environmentPresentations } from "../../state/presentation";
20import { serverEnvironment } from "../../state/server";
21import { useAtomCommand } from "../../state/use-atom-command";
22import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon";
23import { SettingsGroup } from "../settings/SettingsGroup";
24import { Button } from "../ui/button";
25import {
26 Dialog,
27 DialogDescription,
28 DialogFooter,
29 DialogHeader,
30 DialogPanel,
31 DialogPopup,
32 DialogTitle,
33} from "../ui/dialog";
34import { Switch } from "../ui/switch";
35import { toastManager } from "../ui/toast";
36​
37export interface UsageAccessPrompt {
38 readonly environmentId: EnvironmentId;
39 /** Shown only when the prompt spans environments. */
40 readonly environmentLabel: string;
41 readonly instanceId: ProviderInstanceId;
42 readonly driver: ProviderDriverKind;
44​
45const promptKey = (prompt: UsageAccessPrompt) => `${prompt.environmentId}\0${prompt.instanceId}`;
46​
47/** Each environment keeps its own answer per agent; one choice here saves to every listed environment. */
48function useUsageAccessChoices(prompts: readonly UsageAccessPrompt[], onAnswered: () => void) {
49 const gt = useGT();
50 const mutateProviderInstance = useAtomCommand(serverEnvironment.mutateProviderInstance, {
51 reportFailure: false,
52 });
53 const [declined, setDeclined] = useState<ReadonlySet<string>>(() => new Set());
54 const [saving, setSaving] = useState(false);
55​
56 const toggle = (prompt: UsageAccessPrompt, checked: boolean) =>
57 setDeclined((current) => {
58 const next = new Set(current);
59 if (checked) next.delete(promptKey(prompt));
60 else next.add(promptKey(prompt));
61 return next;
62 });
63​
64 const answer = async (allowSelected: boolean) => {
65 const configs = prompts.map((prompt) =>
66 appAtomRegistry.get(serverEnvironment.configValueAtom(prompt.environmentId)),
67 );
68 // A save rewrites the instance from its saved settings, so it waits until they have loaded.
69 if (configs.some((config) => config === null)) {
70 toastManager.add({ type: "error", title: gt`Could not save usage access` });
71 return;
72 }
73 setSaving(true);
74 const results = await Promise.all(
75 prompts.map((prompt, index) => {
76 const access: ProviderUsageAccess =
77 allowSelected && !declined.has(promptKey(prompt)) ? "allowed" : "denied";
78 const config = configs[index];
79 return mutateProviderInstance({
80 environmentId: prompt.environmentId,
81 input: {
82 patch: {},
83 providerInstanceMutation: {
84 operation: "upsert",
85 instanceId: prompt.instanceId,
86 instance: withProviderUsageAccess(
87 config?.settings.providerInstances[prompt.instanceId],
88 prompt.driver,
89 access,
90 ),
91 },
92 },
93 });
94 }),
95 );
96 setSaving(false);
97 const failure = results.find(
98 (result) => result._tag === "Failure" && !isAtomCommandInterrupted(result),
99 );
100 if (failure !== undefined && failure._tag === "Failure") {
101 const cause = squashAtomCommandFailure(failure);
102 toastManager.add({
103 type: "error",
104 title: gt`Could not save usage access`,
105 ...(cause instanceof Error ? { description: cause.message } : {}),
106 });
107 return;
108 }
109 onAnswered();
110 };
111​
112 return {
113 declined,
114 toggle,
115 saving,
116 answer,
117 noneSelected: prompts.every((prompt) => declined.has(promptKey(prompt))),
118 };
120​
121type UsageAccessChoices = ReturnType<typeof useUsageAccessChoices>;
122​
123function usePromptLabels(prompts: readonly UsageAccessPrompt[]) {
124 const presentations = useAtomValue(environmentPresentations.presentationsWithProvidersAtom);
125 return prompts.map((prompt) => {
126 const snapshot = presentations
127 .get(prompt.environmentId)
128 ?.serverConfig?.providers.find((provider) => provider.instanceId === prompt.instanceId);
129 return {
130 prompt,
131 key: promptKey(prompt),
132 accentColor: snapshot?.accentColor,
133 label: resolveProviderInstanceDisplayName(
134 snapshot ?? { instanceId: prompt.instanceId, driver: prompt.driver },
135 ),
136 };
137 });
139​
140function UsageAccessRows({
141 prompts,
142 declined,
143 disabled,
144 onToggle,
145}: {
146 readonly prompts: readonly UsageAccessPrompt[];
147 readonly declined: ReadonlySet<string>;
148 readonly disabled: boolean;
149 readonly onToggle: (prompt: UsageAccessPrompt, checked: boolean) => void;
150}) {
151 const m = useMessages();
152 const agents = usePromptLabels(prompts);
153 const environments = [...new Set(prompts.map((prompt) => prompt.environmentId))];
154 return (
155 <div className="flex flex-col gap-4">
156 {environments.map((environmentId) => {
157 const group = agents.filter((agent) => agent.prompt.environmentId === environmentId);
158 return (
159 <section key={environmentId} className="flex flex-col gap-2">
160 {environments.length > 1 ? (
161 <h3 className="px-1 text-xs font-medium text-muted-foreground">
162 {group[0]?.prompt.environmentLabel}
163 </h3>
164 ) : null}
165 <SettingsGroup>
166 {group.map(({ prompt, key, label, accentColor }) => (
167 <div key={key} className="flex items-center gap-3 px-3.5 py-3">
168 <ProviderInstanceIcon
169 driverKind={prompt.driver}
170 displayName={label}
171 accentColor={accentColor}
172 />
173 <div className="flex min-w-0 flex-1 flex-col gap-0.5">
174 <span className="text-sm font-medium">{label}</span>
175 <span className="text-xs text-muted-foreground">
176 {usageAccessReadsLabel(prompt.driver, m)}
177 </span>
178 </div>
179 <Switch
180 aria-label={label}
181 checked={!declined.has(key)}
182 disabled={disabled}
183 onCheckedChange={(checked) => onToggle(prompt, Boolean(checked))}
184 />
185 </div>
186 ))}
187 </SettingsGroup>
188 </section>
189 );
190 })}
191 </div>
192 );
194​
195function UsageAccessTitle() {
196 return <T>Show agent usage?</T>;
198​
199function UsageAccessIntro() {
200 return <T>T3 Code reads these from each agent, system-wide. Pick which agents to allow.</T>;
202​
203function UsageAccessActions({ choices }: { readonly choices: UsageAccessChoices }) {
204 return (
205 <>
206 <Button
207 variant="outline"
208 disabled={choices.saving}
209 onClick={() => void choices.answer(false)}
210 >
211 <T>Don't allow</T>
212 </Button>
213 <Button
214 disabled={choices.saving || choices.noneSelected}
215 onClick={() => void choices.answer(true)}
216 >
217 <T>Allow</T>
218 </Button>
219 </>
220 );
222​
223/** The Usage page's own content until every listed agent has an answer. The rest of the app stays usable. */
224export function UsageAccessQuestion({
225 prompts,
226}: {
227 readonly prompts: readonly UsageAccessPrompt[];
228}) {
229 const choices = useUsageAccessChoices(prompts, () => {});
230 return (
231 <section
232 aria-labelledby="usage-access-title"
233 className="mx-auto flex min-h-[min(34rem,70vh)] w-full max-w-sm flex-col justify-center gap-5"
234 >
235 <div className="flex flex-col gap-1">
236 <h2 id="usage-access-title" className="text-xl leading-snug font-semibold">
237 <UsageAccessTitle />
238 </h2>
239 <p className="text-sm text-muted-foreground">
240 <UsageAccessIntro />
241 </p>
242 </div>
243 <UsageAccessRows
244 prompts={prompts}
245 declined={choices.declined}
246 disabled={choices.saving}
247 onToggle={choices.toggle}
248 />
249 <div className="flex justify-end gap-2">
250 <UsageAccessActions choices={choices} />
251 </div>
252 </section>
253 );
255​
256/** Asks for one agent from outside the Usage page. Closing without an answer asks again next time. */
257export function UsageAccessDialog({
258 prompts,
259 onOpenChange,
260}: {
261 readonly prompts: readonly UsageAccessPrompt[];
262 readonly onOpenChange: (open: boolean) => void;
263}) {
264 const choices = useUsageAccessChoices(prompts, () => onOpenChange(false));
265 return (
266 <Dialog open onOpenChange={onOpenChange}>
267 <DialogPopup className="max-w-md">
268 <DialogHeader>
269 <DialogTitle>
270 <UsageAccessTitle />
271 </DialogTitle>
272 <DialogDescription>
273 <UsageAccessIntro />
274 </DialogDescription>
275 </DialogHeader>
276 <DialogPanel>
277 <UsageAccessRows
278 prompts={prompts}
279 declined={choices.declined}
280 disabled={choices.saving}
281 onToggle={choices.toggle}
282 />
283 </DialogPanel>
284 <DialogFooter>
285 <UsageAccessActions choices={choices} />
286 </DialogFooter>
287 </DialogPopup>
288 </Dialog>
289 );