Open History to see the last commit
1import { errorDisplayMessage } from "@t3tools/client-runtime/errors";
2import { resolveProviderInstanceDisplayName } from "@t3tools/client-runtime/state/provider-instance-display";
3import { usageAccessReadsLabel } from "@t3tools/client-runtime/state/usage-access";
4import {
5 isAtomCommandInterrupted,
6 squashAtomCommandFailure,
7} from "@t3tools/client-runtime/state/runtime";
8import {
9 withProviderUsageAccess,
10 type EnvironmentId,
11 type ProviderUsageAccess,
12 type UsageAccessRequest,
13} from "@t3tools/contracts";
14import { useAtomValue } from "@effect/atom-react";
15import { useGT, useMessages } from "gt-react-native";
16import { useState } from "react";
17import { View } from "react-native";
18
19import { ProviderIcon } from "../../components/ProviderIcon";
20import { Button } from "../../components/ui/Button";
21import { EmptyState } from "../../components/ui/EmptyState";
22import { ErrorBanner } from "../../components/ui/ErrorBanner";
23import { ListRowLayout } from "../../components/ui/ListRowLayout";
24import { ThemedSwitch } from "../../components/ui/ThemedSwitch";
25import { m } from "../../i18n/messages";
26import { appAtomRegistry } from "../../state/atom-registry";
27import { environmentPresentations } from "../../state/presentation";
28import { serverEnvironment } from "../../state/server";
29import { useAtomCommand } from "../../state/use-atom-command";
30import { SettingsSection } from "../settings/components/SettingsSection";
31
32export interface UsageAccessPrompt extends UsageAccessRequest {
33 readonly environmentId: EnvironmentId;
34 readonly environmentLabel: string;
35}
36
37const promptKey = (prompt: UsageAccessPrompt) => `${prompt.environmentId}\0${prompt.instanceId}`;
38
39/** Asks before T3 reads an agent's usage files or sign-in. It stays until every agent is answered. */
40export function UsageAccessCard({ prompts }: { readonly prompts: readonly UsageAccessPrompt[] }) {
41 const gt = useGT();
42 const messages = useMessages();
43 const mutateProviderInstance = useAtomCommand(serverEnvironment.mutateProviderInstance, {
44 reportFailure: false,
45 reportDefect: false,
46 });
47 const providersByEnvironment = useAtomValue(environmentPresentations.providersByEnvironmentAtom);
48 const [declined, setDeclined] = useState<ReadonlySet<string>>(() => new Set());
49 const [saving, setSaving] = useState(false);
50 const [error, setError] = useState<string | null>(null);
51 const showEnvironment = new Set(prompts.map((prompt) => prompt.environmentId)).size > 1;
52
53 const answer = async (allowSelected: boolean) => {
54 const configs = prompts.map((prompt) =>
55 appAtomRegistry.get(serverEnvironment.configValueAtom(prompt.environmentId)),
56 );
57 // A save rewrites the instance from its saved settings, so it waits until they have loaded.
58 if (configs.some((config) => config === null)) {
59 setError(gt`Could not save usage access`);
60 return;
61 }
62 setSaving(true);
63 setError(null);
64 const results = await Promise.all(
65 prompts.map((prompt, index) => {
66 const access: ProviderUsageAccess =
67 allowSelected && !declined.has(promptKey(prompt)) ? "allowed" : "denied";
68 const config = configs[index];
69 return mutateProviderInstance({
70 environmentId: prompt.environmentId,
71 input: {
72 patch: {},
73 providerInstanceMutation: {
74 operation: "upsert",
75 instanceId: prompt.instanceId,
76 instance: withProviderUsageAccess(
77 config?.settings.providerInstances[prompt.instanceId],
78 prompt.driver,
79 access,
80 ),
81 },
82 },
83 });
84 }),
85 );
86 setSaving(false);
87 const failure = results.find(
88 (result) => result._tag === "Failure" && !isAtomCommandInterrupted(result),
89 );
90 if (failure !== undefined && failure._tag === "Failure") {
91 const cause = squashAtomCommandFailure(failure);
92 setError(
93 cause instanceof Error
94 ? (errorDisplayMessage(cause, m) ?? cause.message)
95 : gt`Could not save usage access`,
96 );
97 }
98 };
99
100 return (
101 <View>
102 <EmptyState
103 variant="plain"
104 title={gt`Show agent usage?`}
105 detail={gt`T3 Code reads these from each agent, system-wide. Pick which agents to allow.`}
106 />
107 <View className="gap-5">
108 <SettingsSection
109 footer={gt`You can change this for each agent in web or desktop Settings → Providers.`}
110 >
111 {prompts.map((prompt) => {
112 const key = promptKey(prompt);
113 const snapshot = providersByEnvironment
114 .get(prompt.environmentId)
115 ?.find((provider) => provider.instanceId === prompt.instanceId);
116 const label = resolveProviderInstanceDisplayName(
117 snapshot ?? { instanceId: prompt.instanceId, driver: prompt.driver },
118 );
119 const allowed = !declined.has(key);
120 return (
121 <ListRowLayout
122 key={key}
123 leading={
124 <ProviderIcon provider={prompt.driver} iconUrl={snapshot?.iconUrl} size={20} />
125 }
126 label={label}
127 description={
128 showEnvironment
129 ? gt`${{ environment: prompt.environmentLabel }} · ${{ detail: usageAccessReadsLabel(prompt.driver, messages) }}`
130 : usageAccessReadsLabel(prompt.driver, messages)
131 }
132 disabled={saving}
133 accessory={
134 <ThemedSwitch
135 accessibilityLabel={label}
136 disabled={saving}
137 style={{ alignSelf: "center" }}
138 value={allowed}
139 onValueChange={(value) =>
140 setDeclined((current) => {
141 const next = new Set(current);
142 if (value) next.delete(key);
143 else next.add(key);
144 return next;
145 })
146 }
147 />
148 }
149 />
150 );
151 })}
152 </SettingsSection>
153 {error ? <ErrorBanner message={error} /> : null}
154 <View className="gap-2.5">
155 <Button
156 label={gt`Allow`}
157 tone="primary"
158 fullWidth
159 loading={saving}
160 disabled={prompts.every((prompt) => declined.has(promptKey(prompt)))}
161 onPress={() => void answer(true)}
162 />
163 <Button
164 label={gt`Don't allow`}
165 fullWidth
166 disabled={saving}
167 onPress={() => void answer(false)}
168 />
169 </View>
170 </View>
171 </View>
172 );
173}