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

main
tsx 364 lines 12.2 KB
Raw
1 import { pipe } from "effect/Function";
2 import {
3 secretRequestAnswerInput,
4 secretRequestDisplay,
5 secretRequestFailureMessage,
6 secretRequestInputs,
7 secretRequestLink,
8 secretRequestPrivacyNote,
9 secretRequestReference,
10 secretRequestSources,
11 secretRequestValue,
12 type SecretRequestInput,
13 type SecretRequestItem,
14 type SecretRequestReply,
15 type SecretRequestSource,
16 } from "@t3tools/client-runtime/secret-request";
17 import {
18 isAtomCommandInterrupted,
19 squashAtomCommandFailure,
20 } from "@t3tools/client-runtime/state/runtime";
21 import type {
22 EnvironmentId,
23 OrchestrationV2ProjectedTurnItem,
24 SecretProviderId,
25 } from "@t3tools/contracts";
26 import { useAtomValue } from "@effect/atom-react";
27 import { T, useGT, useMessages, Var } from "gt-react";
28 import {
29 CheckIcon,
30 ExternalLinkIcon,
31 EyeIcon,
32 EyeOffIcon,
33 LockIcon,
34 MinusIcon,
35 ShieldCheckIcon,
36 } from "lucide-react";
37 import { useId, useRef, useState, type FormEvent } from "react";
38
39 import { isSecretsFeatureEnabled } from "../../env";
40 import { serverEnvironment } from "../../state/server";
41 import { useAtomCommand } from "../../state/use-atom-command";
42 import { Button } from "../ui/button";
43 import { Input } from "../ui/input";
44 import { InputGroup, InputGroupAddon, InputGroupInput } from "../ui/input-group";
45 import { SecretSourceSelect } from "../settings/SecretSourceInput";
46 import { WorkLogRow } from "./WorkLog";
47
48 export function SecretRequestCard(props: {
49 readonly environmentId: EnvironmentId;
50 readonly item: SecretRequestItem;
51 readonly visibility: OrchestrationV2ProjectedTurnItem["visibility"];
52 }) {
53 const { item } = props;
54 const messages = useMessages();
55 const display = secretRequestDisplay(item, props.visibility, messages);
56 if (display.kind === "answered" || display.kind === "pending-elsewhere") {
57 const Icon =
58 display.kind === "pending-elsewhere"
59 ? LockIcon
60 : display.outcome === "saved"
61 ? CheckIcon
62 : MinusIcon;
63 return (
64 <WorkLogRow
65 data-v2-item-type={item.type}
66 icon={<Icon className="size-3.5 text-icon-muted" aria-hidden />}
67 label={
68 <>
69 {item.label} · {display.label}
70 </>
71 }
72 />
73 );
74 }
75 return <PendingSecretRequestForm environmentId={props.environmentId} item={item} />;
76 }
77
78 const NO_SOURCES: ReadonlyArray<SecretRequestSource> = [];
79
80 function useSecretRequestSources(environmentId: EnvironmentId) {
81 const config = useAtomValue(serverEnvironment.configValueAtom(environmentId));
82 const messages = useMessages();
83 return isSecretsFeatureEnabled
84 ? secretRequestSources(config, config?.settings.secretProviders ?? {}, messages)
85 : NO_SOURCES;
86 }
87
88 function PendingSecretRequestForm(props: {
89 readonly environmentId: EnvironmentId;
90 readonly item: SecretRequestItem;
91 }) {
92 const { item } = props;
93 const messages = useMessages();
94 const formId = useId();
95 const errorId = useId();
96 const privacyId = useId();
97 const answer = useAtomCommand(serverEnvironment.answerSecretRequest, {
98 label: "answer secret request",
99 // The failure cause holds the request; keep it out of the console.
100 reportFailure: false,
101 reportDefect: false,
102 });
103 const multiple = item.fields !== undefined;
104 // A reference answers one value, so a card with fields is always typed.
105 const configuredSources = useSecretRequestSources(props.environmentId);
106 const sources = multiple ? NO_SOURCES : configuredSources;
107 const [sourceId, setSourceId] = useState<SecretProviderId | null>(null);
108 const source = sources.find((candidate) => candidate.id === sourceId) ?? null;
109 const [values, setValues] = useState<Readonly<Record<string, string>>>({});
110 const [reference, setReference] = useState("");
111 const [submitting, setSubmitting] = useState(false);
112 const [error, setError] = useState<string | null>(null);
113 // Enter and click can both submit before a render.
114 const inFlight = useRef(false);
115 const inputs = secretRequestInputs(item, messages);
116 const inputId = (index: number) => `${formId}-${index}`;
117 const describedBy = error !== null ? `${privacyId} ${errorId}` : privacyId;
118 const canSave =
119 source === null
120 ? secretRequestAnswerInput(item, { type: "save", values }) !== null
121 : reference.trim().length > 0;
122
123 const send = async (reply: SecretRequestReply) => {
124 const input = secretRequestAnswerInput(item, reply);
125 if (input === null || inFlight.current) return;
126 inFlight.current = true;
127 setSubmitting(true);
128 setError(null);
129 // A password field that leaves the page with text in it can prompt to save a login,
130 // so the card is emptied before it closes; a failed answer puts the values back.
131 const typed = values;
132 setValues({});
133 const result = await answer({ environmentId: props.environmentId, input }).finally(() => {
134 inFlight.current = false;
135 setSubmitting(false);
136 });
137 if (result._tag === "Success") {
138 setReference("");
139 return;
140 }
141 setValues(typed);
142 if (!isAtomCommandInterrupted(result)) {
143 pipe(
144 squashAtomCommandFailure(result),
145 (failure) => secretRequestFailureMessage(failure, messages),
146 setError,
147 );
148 }
149 };
150
151 const onSubmit = (event: FormEvent<HTMLFormElement>) => {
152 event.preventDefault();
153 if (source === null) {
154 void send({ type: "save", values });
155 } else if (secretRequestReference(source, reference) === undefined) {
156 setError(source.invalidReferenceMessage);
157 } else {
158 void send({ type: "reference", source, reference });
159 }
160 };
161
162 const link = secretRequestLink(item);
163 const field = (input: SecretRequestInput, index: number) => (
164 <SecretRequestField
165 key={input.key}
166 id={inputId(index)}
167 input={input}
168 // A single input is labelled by the card title.
169 label={multiple ? input.label : undefined}
170 value={secretRequestValue(values, input.key)}
171 disabled={submitting}
172 invalid={error !== null}
173 describedBy={describedBy}
174 onChange={(value) => setValues((current) => ({ ...current, [input.key]: value }))}
175 />
176 );
177 const saveButton = (
178 <Button type="submit" disabled={submitting || !canSave}>
179 <T>Save securely</T>
180 </Button>
181 );
182
183 return (
184 <form
185 data-v2-item-type={item.type}
186 className="flex min-w-0 flex-col gap-3 rounded-xl border border-border/60 bg-card p-4"
187 onSubmit={onSubmit}
188 autoComplete="off"
189 // On click, not pointerdown: the mousedown that follows a pointerdown
190 // moves focus back off the input. A click that ends a text selection
191 // leaves it alone so the reason can still be copied.
192 onClick={(event) => {
193 if (!(event.target instanceof Element)) return;
194 if (event.target.closest("input, button, a")) return;
195 if (window.getSelection()?.isCollapsed === false) return;
196 const empty = inputs.findIndex((input) => !secretRequestValue(values, input.key).trim());
197 document.getElementById(inputId(Math.max(empty, 0)))?.focus();
198 }}
199 >
200 <div className="flex min-w-0 flex-col gap-1">
201 {multiple ? (
202 <p className="text-sm font-medium text-foreground">{item.label}</p>
203 ) : (
204 <label htmlFor={inputId(0)} className="text-sm font-medium text-foreground">
205 {item.label}
206 </label>
207 )}
208 {item.reason.trim() ? (
209 <p className="text-sm wrap-anywhere text-muted-foreground">{item.reason}</p>
210 ) : null}
211 </div>
212 {link !== null ? (
213 <div className="flex min-w-0 flex-col items-start gap-1.5">
214 <Button
215 variant="outline"
216 size="sm"
217 render={<a href={link.href} target="_blank" rel="noopener noreferrer" />}
218 >
219 <T>
220 Open <Var>{link.host}</Var>
221 </T>
222 <ExternalLinkIcon aria-hidden />
223 </Button>
224 {/* A link found in the reason is already shown there. */}
225 {item.url !== undefined ? (
226 <p className="font-mono text-xs wrap-anywhere text-muted-foreground">{item.url}</p>
227 ) : null}
228 </div>
229 ) : null}
230 {multiple ? (
231 <div className="flex min-w-0 flex-col gap-2.5">{inputs.map(field)}</div>
232 ) : (
233 <div className="flex min-w-0 items-center gap-2">
234 {sources.length > 0 ? (
235 <SecretSourceSelect
236 value={source?.id ?? null}
237 sources={sources}
238 label={item.label}
239 disabled={submitting}
240 onValueChange={(next) => {
241 setSourceId(next);
242 setError(null);
243 }}
244 />
245 ) : null}
246 <div className="min-w-0 flex-1">
247 {source === null ? (
248 inputs.map(field)
249 ) : (
250 <Input
251 id={inputId(0)}
252 font="mono"
253 autoComplete="off"
254 autoCorrect="off"
255 autoCapitalize="off"
256 spellCheck={false}
257 placeholder={source.referencePlaceholder}
258 value={reference}
259 disabled={submitting}
260 aria-invalid={error !== null || undefined}
261 aria-describedby={describedBy}
262 onChange={(event) => {
263 setReference(event.currentTarget.value);
264 setError(null);
265 }}
266 />
267 )}
268 </div>
269 {saveButton}
270 </div>
271 )}
272 {error !== null ? (
273 <p id={errorId} role="alert" className="text-xs text-destructive">
274 {error}
275 </p>
276 ) : null}
277 <div className="flex min-w-0 flex-wrap items-center justify-between gap-2">
278 <p
279 id={privacyId}
280 className="flex min-w-0 grow basis-52 items-center gap-1.5 text-xs text-muted-foreground"
281 >
282 <ShieldCheckIcon className="size-3.5 shrink-0" aria-hidden />
283 {secretRequestPrivacyNote(item, messages)}
284 </p>
285 <div className="ms-auto flex shrink-0 items-center gap-2">
286 <Button
287 type="button"
288 size="xs"
289 variant="ghost-muted"
290 disabled={submitting}
291 onClick={() => void send({ type: "decline" })}
292 >
293 <T>Decline</T>
294 </Button>
295 {multiple ? saveButton : null}
296 </div>
297 </div>
298 </form>
299 );
300 }
301
302 function SecretRequestField(props: {
303 readonly id: string;
304 readonly input: SecretRequestInput;
305 readonly label: string | undefined;
306 readonly value: string;
307 readonly disabled: boolean;
308 readonly invalid: boolean;
309 readonly describedBy: string;
310 readonly onChange: (value: string) => void;
311 }) {
312 const { input } = props;
313 const gt = useGT();
314 const [revealed, setRevealed] = useState(false);
315 const masked = input.secret && !revealed;
316 const control = (
317 <InputGroup>
318 <InputGroupInput
319 id={props.id}
320 // A CSS-masked text field still exposes its value to screen readers.
321 type={masked ? "password" : "text"}
322 autoComplete="off"
323 autoCorrect="off"
324 autoCapitalize="off"
325 spellCheck={false}
326 data-1p-ignore
327 data-lpignore="true"
328 data-bwignore
329 placeholder={input.placeholder}
330 value={props.value}
331 disabled={props.disabled}
332 aria-invalid={props.invalid || undefined}
333 aria-describedby={props.describedBy}
334 onChange={(event) => props.onChange(event.currentTarget.value)}
335 />
336 {input.secret ? (
337 <InputGroupAddon align="inline-end">
338 <Button
339 type="button"
340 size="icon-xs"
341 variant="ghost"
342 aria-label={gt("Show {label}", { label: input.label })}
343 aria-pressed={revealed}
344 disabled={props.disabled}
345 // Keep focus, and the caret, in the input.
346 onMouseDown={(event) => event.preventDefault()}
347 onClick={() => setRevealed((current) => !current)}
348 >
349 {revealed ? <EyeOffIcon aria-hidden /> : <EyeIcon aria-hidden />}
350 </Button>
351 </InputGroupAddon>
352 ) : null}
353 </InputGroup>
354 );
355 if (props.label === undefined) return control;
356 return (
357 <div className="flex min-w-0 flex-col gap-1">
358 <label htmlFor={props.id} className="text-xs font-medium text-muted-foreground">
359 {props.label}
360 </label>
361 {control}
362 </div>
363 );
364 }