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

ClaudeAccounts.tsx

267 lines8.7 KB

1import { errorDisplayMessage } from "@t3tools/client-runtime/errors";
2import { useGT } from "gt-react-native";
3import type { MenuAction } from "@react-native-menu/menu";
4import {
5 isAtomCommandInterrupted,
6 squashAtomCommandFailure,
7} from "@t3tools/client-runtime/state/runtime";
8import {
9 isManagedSettingPath,
10 type ProviderInstanceId,
11 type ProviderInstanceMutation,
12 type ServerProvider,
13} from "@t3tools/contracts";
14import { useRef, useState } from "react";
15import { TextInput, View } from "react-native";
16import { m } from "../../i18n/messages";
17​
18import * as Dialog from "../../components/ui/Dialog";
19import { AppText as Text } from "../../components/ui/AppText";
20import { ControlPill } from "../../components/ui/ControlPill";
21import { ListActionRow } from "../../components/ui/ListActionRow";
22import { Menu } from "../../components/ui/Menu";
23import { serverEnvironment } from "../../state/server";
24import { useAtomCommand } from "../../state/use-atom-command";
25import {
26 claudeConfigDir,
27 DEFAULT_CLAUDE_INSTANCE_ID,
28 planClaudeAccountSave,
29 type ClaudeAccountDraft,
30} from "./claude-accounts";
31import type { SettingsTarget } from "./settings-environment-filter";
32​
33function useProviderInstanceMutation(environment: SettingsTarget) {
34 const gt = useGT();
35 const mutate = useAtomCommand(serverEnvironment.mutateProviderInstance, {
36 reportFailure: false,
37 reportDefect: false,
38 });
39 const pendingRef = useRef(false);
40 const [pending, setPending] = useState(false);
41 const [error, setError] = useState<string | null>(null);
42 async function run(providerInstanceMutation: ProviderInstanceMutation) {
43 if (pendingRef.current) return false;
44 pendingRef.current = true;
45 setPending(true);
46 setError(null);
47 const result = await mutate({
48 environmentId: environment.environmentId,
49 input: { patch: {}, providerInstanceMutation },
50 });
51 pendingRef.current = false;
52 setPending(false);
53 if (result._tag === "Success") return true;
54 if (!isAtomCommandInterrupted(result)) {
55 const failure = squashAtomCommandFailure(result);
56 setError(
57 failure instanceof Error
58 ? (errorDisplayMessage(failure, m) ?? failure.message)
59 : gt`Could not save the ${{ provider: "Claude" }} account.`,
60 );
61 }
62 return false;
63 }
64 return { run, pending, error, setError };
66​
67export function ClaudeAccount({
68 environment,
69 provider,
70}: {
71 readonly environment: SettingsTarget;
72 readonly provider: ServerProvider;
73}) {
74 const gt = useGT();
75 const [editing, setEditing] = useState(false);
76 const { run, pending, error } = useProviderInstanceMutation(environment);
77 const instance = environment.serverConfig.settings.providerInstances[provider.instanceId];
78 const configDir = claudeConfigDir(instance);
79 const name = provider.displayName ?? "Claude";
80 const status = !provider.enabled
81 ? gt`Turned off`
82 : provider.auth.status === "authenticated"
83 ? gt`Signed in`
84 : provider.auth.status === "unauthenticated"
85 ? gt`Not signed in`
86 : !provider.installed
87 ? gt`Not installed`
88 : null;
89 const removable =
90 provider.instanceId !== DEFAULT_CLAUDE_INSTANCE_ID &&
91 !isManagedSettingPath(
92 environment.serverConfig.managedPolicy,
93 `providerInstances.${provider.instanceId}`,
94 );
95 const actions: MenuAction[] = [
96 { id: "edit", title: gt`Edit`, image: "pencil" },
97 ...(removable
98 ? [
99 {
100 id: "remove",
101 title: gt`Remove`,
102 image: "trash",
103 attributes: { destructive: true },
104 } satisfies MenuAction,
105 ]
106 : []),
107 ];
108 function remove() {
109 Dialog.alert(
110 gt`Remove ${{ account: name }}?`,
111 gt`It leaves the model picker on ${{ environment: environment.label }}. The config folder and its sign-in stay on the server.`,
112 [
113 { text: gt`Cancel`, style: "cancel" },
114 {
115 text: gt`Remove`,
116 style: "destructive",
117 onPress: () => {
118 void run({ operation: "remove", instanceId: provider.instanceId });
119 },
120 },
121 ],
122 );
123 }
124 return (
125 <View className="border-t border-border-subtle">
126 <View className="min-h-16 flex-row items-center gap-3 px-4 py-3">
127 <View className="min-w-0 shrink grow gap-0.5">
128 <Text textRole="body" className="text-foreground" numberOfLines={1}>
129 {name}
130 </Text>
131 <Text textRole="footnote" className="text-foreground-muted" numberOfLines={2}>
132 {[status, configDir || gt`Default config folder`].filter(Boolean).join(" · ")}
133 </Text>
134 </View>
135 {editing ? null : (
136 <Menu
137 accessible
138 accessibilityRole="button"
139 accessibilityLabel={gt`${{ account: name }} options`}
140 title={name}
141 actions={actions}
142 onPressAction={({ nativeEvent }) => {
143 if (pending) return;
144 if (nativeEvent.event === "edit") setEditing(true);
145 else if (nativeEvent.event === "remove") remove();
146 }}
147 >
148 <ControlPill
149 icon="ellipsis"
150 accessibilityLabel={gt`${{ account: name }} options`}
151 disabled={pending}
152 />
153 </Menu>
154 )}
155 </View>
156 {editing ? (
157 <ClaudeAccountForm
158 environment={environment}
159 instanceId={provider.instanceId}
160 initial={{ name: instance?.displayName ?? "", configDir }}
161 onDone={() => setEditing(false)}
162 />
163 ) : error ? (
164 <Text accessibilityRole="alert" className="px-4 pb-3 text-danger-foreground">
165 {error}
166 </Text>
167 ) : null}
168 </View>
169 );
171​
172export function AddClaudeAccount({ environment }: { readonly environment: SettingsTarget }) {
173 const gt = useGT();
174 const [adding, setAdding] = useState(false);
175 return (
176 <View className="border-t border-border-subtle">
177 {adding ? (
178 <ClaudeAccountForm
179 environment={environment}
180 instanceId={null}
181 initial={{ name: "", configDir: "" }}
182 onDone={() => setAdding(false)}
183 />
184 ) : (
185 <ListActionRow
186 icon="plus"
187 label={gt`Add ${{ provider: "Claude" }} account`}
188 description={gt`Use a ${{ provider: "Claude" }} config folder that is already signed in on this server.`}
189 onPress={() => setAdding(true)}
190 />
191 )}
192 </View>
193 );
195​
196function ClaudeAccountForm({
197 environment,
198 instanceId,
199 initial,
200 onDone,
201}: {
202 readonly environment: SettingsTarget;
203 readonly instanceId: ProviderInstanceId | null;
204 readonly initial: ClaudeAccountDraft;
205 readonly onDone: () => void;
206}) {
207 const gt = useGT();
208 const [draft, setDraft] = useState(initial);
209 const { run, pending, error, setError } = useProviderInstanceMutation(environment);
210 function save() {
211 const plan = planClaudeAccountSave({
212 providerInstances: environment.serverConfig.settings.providerInstances,
213 policy: environment.serverConfig.managedPolicy,
214 instanceId,
215 draft,
216 });
217 if ("error" in plan) {
218 setError(plan.error);
219 return;
220 }
221 void run(plan.mutation).then((saved) => {
222 if (saved) onDone();
223 });
224 }
225 function field(key: keyof ClaudeAccountDraft, label: string, placeholder: string) {
226 return (
227 <TextInput
228 accessibilityLabel={label}
229 className="rounded-lg border border-border-subtle px-3 py-2 text-base text-foreground"
230 placeholderTextColorClassName="accent-foreground-muted"
231 placeholder={placeholder}
232 autoCapitalize="none"
233 autoCorrect={false}
234 editable={!pending}
235 value={draft[key]}
236 onChangeText={(value) => setDraft((current) => ({ ...current, [key]: value }))}
237 />
238 );
239 }
240 return (
241 <View className="gap-2 px-4 py-3">
242 <Text textRole="footnote" className="text-foreground-muted">
243 {gt`Point at a ${{ variable: "CLAUDE_CONFIG_DIR" }} folder on ${{ environment: environment.label }} where ${{ product: "Claude Code" }} is already signed in. Sign in there with the ${{ cli: "Claude CLI" }} first.`}
244 </Text>
245 {field("name", gt`Account name`, gt`Name, e.g. Work`)}
246 {field(
247 "configDir",
248 gt`${{ provider: "Claude" }} config folder`,
249 gt`Config folder, e.g. ${{ path: "~/.claude-work" }}`,
250 )}
251 {error ? (
252 <Text accessibilityRole="alert" className="text-danger-foreground">
253 {error}
254 </Text>
255 ) : null}
256 <View className="flex-row justify-end gap-2">
257 <ControlPill variant="pill" label={gt`Cancel`} disabled={pending} onPress={onDone} />
258 <ControlPill
259 variant="primary"
260 label={instanceId === null ? gt`Add` : gt`Save`}
261 disabled={pending}
262 onPress={save}
263 />
264 </View>
265 </View>
266 );