@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
tsx 281 lines 9.04 KB
Raw
1 import { errorDisplayMessage } from "@t3tools/client-runtime/errors";
2 import { useGT } from "gt-react-native";
3 import type { MenuAction } from "@react-native-menu/menu";
4 import {
5 isAtomCommandInterrupted,
6 squashAtomCommandFailure,
7 } from "@t3tools/client-runtime/state/runtime";
8 import {
9 isManagedSettingPath,
10 type ProviderInstanceId,
11 type ProviderInstanceMutation,
12 type ServerProvider,
13 } from "@t3tools/contracts";
14 import { useRef, useState } from "react";
15 import { TextInput, View } from "react-native";
16 import { m } from "../../i18n/messages";
17
18 import * as Dialog from "../../components/ui/Dialog";
19 import { AppText as Text } from "../../components/ui/AppText";
20 import { ControlPill } from "../../components/ui/ControlPill";
21 import { ListActionRow } from "../../components/ui/ListActionRow";
22 import { Menu } from "../../components/ui/Menu";
23 import { serverEnvironment } from "../../state/server";
24 import { useAtomCommand } from "../../state/use-atom-command";
25 import {
26 claudeConfigDir,
27 DEFAULT_CLAUDE_INSTANCE_ID,
28 planClaudeAccountSave,
29 type ClaudeAccountDraft,
30 } from "./claude-accounts";
31 import type { SettingsTarget } from "./settings-environment-filter";
32
33 function 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} account.", { provider: "Claude" }),
60 );
61 }
62 return false;
63 }
64 return { run, pending, error, setError };
65 }
66
67 export 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}?", { account: name }),
111 gt(
112 "It leaves the model picker on {environment}. The config folder and its sign-in stay on the server.",
113 { environment: environment.label },
114 ),
115 [
116 { text: gt("Cancel"), style: "cancel" },
117 {
118 text: gt("Remove"),
119 style: "destructive",
120 onPress: () => {
121 void run({ operation: "remove", instanceId: provider.instanceId });
122 },
123 },
124 ],
125 );
126 }
127 return (
128 <View className="border-t border-border-subtle">
129 <View className="min-h-16 flex-row items-center gap-3 px-4 py-3">
130 <View className="min-w-0 shrink grow gap-0.5">
131 <Text textRole="body" className="text-foreground" numberOfLines={1}>
132 {name}
133 </Text>
134 <Text textRole="footnote" className="text-foreground-muted" numberOfLines={2}>
135 {[status, configDir || gt("Default config folder")].filter(Boolean).join(" · ")}
136 </Text>
137 </View>
138 {editing ? null : (
139 <Menu
140 accessible
141 accessibilityRole="button"
142 accessibilityLabel={gt("{account} options", { account: name })}
143 title={name}
144 actions={actions}
145 onPressAction={({ nativeEvent }) => {
146 if (pending) return;
147 if (nativeEvent.event === "edit") setEditing(true);
148 else if (nativeEvent.event === "remove") remove();
149 }}
150 >
151 <ControlPill
152 icon="ellipsis"
153 accessibilityLabel={gt("{account} options", { account: name })}
154 disabled={pending}
155 />
156 </Menu>
157 )}
158 </View>
159 {editing ? (
160 <ClaudeAccountForm
161 environment={environment}
162 instanceId={provider.instanceId}
163 initial={{ name: instance?.displayName ?? "", configDir }}
164 onDone={() => setEditing(false)}
165 />
166 ) : error ? (
167 <Text accessibilityRole="alert" className="px-4 pb-3 text-danger-foreground">
168 {error}
169 </Text>
170 ) : null}
171 </View>
172 );
173 }
174
175 export function AddClaudeAccount({ environment }: { readonly environment: SettingsTarget }) {
176 const gt = useGT();
177 const [adding, setAdding] = useState(false);
178 return (
179 <View className="border-t border-border-subtle">
180 {adding ? (
181 <ClaudeAccountForm
182 environment={environment}
183 instanceId={null}
184 initial={{ name: "", configDir: "" }}
185 onDone={() => setAdding(false)}
186 />
187 ) : (
188 <ListActionRow
189 icon="plus"
190 label={gt("Add {provider} account", { provider: "Claude" })}
191 description={gt(
192 "Use a {provider} config folder that is already signed in on this server.",
193 { provider: "Claude" },
194 )}
195 onPress={() => setAdding(true)}
196 />
197 )}
198 </View>
199 );
200 }
201
202 function ClaudeAccountForm({
203 environment,
204 instanceId,
205 initial,
206 onDone,
207 }: {
208 readonly environment: SettingsTarget;
209 readonly instanceId: ProviderInstanceId | null;
210 readonly initial: ClaudeAccountDraft;
211 readonly onDone: () => void;
212 }) {
213 const gt = useGT();
214 const [draft, setDraft] = useState(initial);
215 const { run, pending, error, setError } = useProviderInstanceMutation(environment);
216 function save() {
217 const plan = planClaudeAccountSave({
218 providerInstances: environment.serverConfig.settings.providerInstances,
219 policy: environment.serverConfig.managedPolicy,
220 instanceId,
221 draft,
222 });
223 if ("error" in plan) {
224 setError(plan.error);
225 return;
226 }
227 void run(plan.mutation).then((saved) => {
228 if (saved) onDone();
229 });
230 }
231 function field(key: keyof ClaudeAccountDraft, label: string, placeholder: string) {
232 return (
233 <TextInput
234 accessibilityLabel={label}
235 className="rounded-lg border border-border-subtle px-3 py-2 text-base text-foreground"
236 placeholderTextColorClassName="accent-foreground-muted"
237 placeholder={placeholder}
238 autoCapitalize="none"
239 autoCorrect={false}
240 editable={!pending}
241 value={draft[key]}
242 onChangeText={(value) => setDraft((current) => ({ ...current, [key]: value }))}
243 />
244 );
245 }
246 return (
247 <View className="gap-2 px-4 py-3">
248 <Text textRole="footnote" className="text-foreground-muted">
249 {gt(
250 "Point at a {variable} folder on {environment} where {product} is already signed in. Sign in there with the {cli} first.",
251 {
252 variable: "CLAUDE_CONFIG_DIR",
253 environment: environment.label,
254 product: "Claude Code",
255 cli: "Claude CLI",
256 },
257 )}
258 </Text>
259 {field("name", gt("Account name"), gt("Name, e.g. Work"))}
260 {field(
261 "configDir",
262 gt("{provider} config folder", { provider: "Claude" }),
263 gt("Config folder, e.g. {path}", { path: "~/.claude-work" }),
264 )}
265 {error ? (
266 <Text accessibilityRole="alert" className="text-danger-foreground">
267 {error}
268 </Text>
269 ) : null}
270 <View className="flex-row justify-end gap-2">
271 <ControlPill variant="pill" label={gt("Cancel")} disabled={pending} onPress={onDone} />
272 <ControlPill
273 variant="primary"
274 label={instanceId === null ? gt("Add") : gt("Save")}
275 disabled={pending}
276 onPress={save}
277 />
278 </View>
279 </View>
280 );
281 }