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

main
tsx 293 lines 10.3 KB
Raw
1 import {
2 secretRequestAnswerInput,
3 secretRequestDisplay,
4 secretRequestFailureMessage,
5 secretRequestInputs,
6 secretRequestLink,
7 secretRequestPrivacyNote,
8 secretRequestReference,
9 secretRequestSources,
10 secretRequestValue,
11 type SecretRequestItem,
12 type SecretRequestReply,
13 type SecretRequestSource,
14 } from "@t3tools/client-runtime/secret-request";
15 import {
16 isAtomCommandInterrupted,
17 squashAtomCommandFailure,
18 } from "@t3tools/client-runtime/state/runtime";
19 import type {
20 EnvironmentId,
21 OrchestrationV2ProjectedTurnItem,
22 SecretProviderId,
23 } from "@t3tools/contracts";
24 import { useAtomValue } from "@effect/atom-react";
25 import { useGT, useMessages } from "gt-react-native";
26 import { useRef, useState } from "react";
27 import { View, type ColorValue } from "react-native";
28
29 import { SymbolView, type AppSymbolName } from "../../components/ui/AppSymbol";
30 import { AppText as Text, AppTextInput as TextInput } from "../../components/ui/AppText";
31 import { SecretTextInput } from "../../components/ui/SecretTextInput";
32 import type { SecretTextInputHandle } from "../../components/ui/SecretTextInput.types";
33 import { serverEnvironment } from "../../state/server";
34 import { useAtomCommand } from "../../state/use-atom-command";
35 import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
36 import { Button } from "../../components/ui/Button";
37 import { Chip } from "../../components/ui/Chip";
38
39 const LOCK_SYMBOL: AppSymbolName = { ios: "lock", android: "lock" };
40 const PRIVATE_SYMBOL: AppSymbolName = { ios: "checkmark.shield", android: "lock" };
41 const NO_SOURCES: ReadonlyArray<SecretRequestSource> = [];
42
43 export function SecretRequestCard(props: {
44 readonly environmentId: EnvironmentId;
45 readonly projectedItem: OrchestrationV2ProjectedTurnItem;
46 readonly iconColor: ColorValue;
47 }) {
48 const m = useMessages();
49 const { item, visibility } = props.projectedItem;
50 if (item.type !== "secret_request") return null;
51 const display = secretRequestDisplay(item, visibility, m);
52 if (display.kind === "pending") {
53 return (
54 <PendingSecretRequestForm
55 environmentId={props.environmentId}
56 item={item}
57 iconColor={props.iconColor}
58 />
59 );
60 }
61 const icon: AppSymbolName =
62 display.kind === "pending-elsewhere"
63 ? LOCK_SYMBOL
64 : display.outcome === "saved"
65 ? "checkmark"
66 : "minus";
67 return (
68 <View className="mb-3 min-h-9 flex-row items-center gap-2 px-1">
69 <SymbolView name={icon} size={13} tintColor={props.iconColor} type="monochrome" />
70 <Text className="flex-1 font-sans text-sm text-foreground-muted" numberOfLines={2}>
71 {item.label} · {display.label}
72 </Text>
73 </View>
74 );
75 }
76
77 function PendingSecretRequestForm(props: {
78 readonly environmentId: EnvironmentId;
79 readonly item: SecretRequestItem;
80 readonly iconColor: ColorValue;
81 }) {
82 const gt = useGT();
83 const m = useMessages();
84 const { item } = props;
85 const answer = useAtomCommand(serverEnvironment.answerSecretRequest, {
86 label: "answer secret request",
87 // The failure cause holds the request; keep it out of the console.
88 reportFailure: false,
89 reportDefect: false,
90 });
91 const inputs = secretRequestInputs(item, m);
92 const multiple = item.fields !== undefined;
93 const config = useAtomValue(serverEnvironment.configValueAtom(props.environmentId));
94 // A reference answers one value, so a card with fields is always typed.
95 const sources = multiple
96 ? NO_SOURCES
97 : secretRequestSources(config, config?.settings.secretProviders ?? {}, m);
98 const [sourceId, setSourceId] = useState<SecretProviderId | null>(null);
99 const source = sources.find((candidate) => candidate.id === sourceId) ?? null;
100 const [values, setValues] = useState<Readonly<Record<string, string>>>({});
101 const [reference, setReference] = useState("");
102 const [submitting, setSubmitting] = useState(false);
103 const [error, setError] = useState<string | null>(null);
104 // Submit then a tap can both run before a re-render; this guard is synchronous.
105 const inFlight = useRef(false);
106 const inputRefs = useRef<Array<SecretTextInputHandle | null>>([]);
107
108 const send = async (reply: SecretRequestReply) => {
109 const input = secretRequestAnswerInput(item, reply);
110 if (input === null || inFlight.current) return;
111 inFlight.current = true;
112 setSubmitting(true);
113 setError(null);
114 // iOS offers to save a masked field that leaves the screen with text in it as a login
115 // password, so the card is emptied before it closes; a failed answer puts the values back.
116 const typed = reply.type === "save" ? reply.values : values;
117 setValues({});
118 const result = await answer({ environmentId: props.environmentId, input }).finally(() => {
119 inFlight.current = false;
120 setSubmitting(false);
121 });
122 if (result._tag === "Success") {
123 setReference("");
124 return;
125 }
126 setValues(typed);
127 if (!isAtomCommandInterrupted(result)) {
128 setError(secretRequestFailureMessage(squashAtomCommandFailure(result), m));
129 }
130 };
131 const save = (typed: Readonly<Record<string, string>>) => {
132 if (source === null) {
133 void send({ type: "save", values: typed });
134 } else if (secretRequestReference(source, reference) === undefined) {
135 setError(source.invalidReferenceMessage);
136 } else {
137 void send({ type: "reference", source, reference });
138 }
139 };
140 const canSave =
141 source === null
142 ? secretRequestAnswerInput(item, { type: "save", values }) !== null
143 : reference.trim().length > 0;
144 const link = secretRequestLink(item);
145
146 return (
147 <View className="mb-3 gap-3 rounded-[20px] border border-border bg-card-alt p-4">
148 <View className="gap-1">
149 <Text className="font-t3-bold text-base text-foreground">{item.label}</Text>
150 {item.reason.trim() ? (
151 <Text className="font-sans text-sm leading-5 text-foreground-muted" selectable>
152 {item.reason}
153 </Text>
154 ) : null}
155 </View>
156 {link !== null ? (
157 <View className="gap-1.5">
158 <Button
159 label={gt("Open {host}", { host: link.host })}
160 tone="secondary"
161 fullWidth
162 onPress={() => void tryOpenExternalUrl(link.href, "secret-request")}
163 />
164 {/* A link found in the reason is already shown there. */}
165 {item.url !== undefined ? (
166 <Text selectable className="font-mono text-xs text-foreground-muted">
167 {item.url}
168 </Text>
169 ) : null}
170 </View>
171 ) : null}
172 {sources.length > 0 ? (
173 <View className="flex-row flex-wrap gap-2">
174 <Chip
175 label={gt("Value", { $context: "noun, enter the secret value directly" })}
176 size="small"
177 selected={source === null}
178 disabled={submitting}
179 onPress={() => {
180 setSourceId(null);
181 setError(null);
182 }}
183 />
184 {sources.map((candidate) => (
185 <Chip
186 key={candidate.id}
187 label={candidate.label}
188 size="small"
189 selected={candidate.id === source?.id}
190 disabled={submitting}
191 onPress={() => {
192 setSourceId(candidate.id);
193 setError(null);
194 }}
195 />
196 ))}
197 </View>
198 ) : null}
199 {source === null ? (
200 inputs.map((input, index) => {
201 const last = index === inputs.length - 1;
202 const field = (
203 <SecretTextInput
204 key={input.key}
205 // A single input is labelled by the card title.
206 accessibilityLabel={multiple ? input.label : item.label}
207 secret={input.secret}
208 onMount={(handle) => {
209 inputRefs.current[index] = handle;
210 }}
211 placeholder={input.placeholder}
212 value={secretRequestValue(values, input.key)}
213 onChangeText={(value) => setValues((current) => ({ ...current, [input.key]: value }))}
214 editable={!submitting}
215 returnKeyType={last ? "done" : "next"}
216 onSubmitEditing={(value) =>
217 last
218 ? save({ ...values, [input.key]: value })
219 : inputRefs.current[index + 1]?.focus()
220 }
221 />
222 );
223 return multiple ? (
224 <View key={input.key} className="gap-1.5">
225 <Text className="font-t3-medium text-sm text-foreground-muted">{input.label}</Text>
226 {field}
227 </View>
228 ) : (
229 field
230 );
231 })
232 ) : (
233 <TextInput
234 key={source.id}
235 accessibilityLabel={gt("{label} reference in {source}", {
236 label: item.label,
237 source: source.label,
238 })}
239 placeholder={source.referencePlaceholder}
240 value={reference}
241 onChangeText={(next) => {
242 setReference(next);
243 setError(null);
244 }}
245 editable={!submitting}
246 autoCorrect={false}
247 autoCapitalize="none"
248 autoComplete="off"
249 textContentType="none"
250 importantForAutofill="no"
251 spellCheck={false}
252 returnKeyType="done"
253 onSubmitEditing={() => save(values)}
254 />
255 )}
256 {error !== null ? (
257 <Text
258 accessibilityRole="alert"
259 accessibilityLiveRegion="polite"
260 className="font-sans text-sm text-danger-foreground"
261 >
262 {error}
263 </Text>
264 ) : null}
265 <Button
266 label={gt("Save securely")}
267 tone="primary"
268 fullWidth
269 disabled={submitting || !canSave}
270 onPress={() => save(values)}
271 />
272 <View className="flex-row items-center justify-between gap-2">
273 <View className="flex-1 flex-row items-center gap-1.5">
274 <SymbolView
275 name={PRIVATE_SYMBOL}
276 size={13}
277 tintColor={props.iconColor}
278 type="monochrome"
279 />
280 <Text className="flex-1 font-sans text-xs text-foreground-muted">
281 {secretRequestPrivacyNote(item, m)}
282 </Text>
283 </View>
284 <Button
285 label={gt("Decline", { $context: "verb, refuses the secret request" })}
286 tone="text"
287 disabled={submitting}
288 onPress={() => void send({ type: "decline" })}
289 />
290 </View>
291 </View>
292 );
293 }