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

ClaudeAccounts.tsx

252 lines8.1 KB

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