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

main
tsx 660 lines 21.1 KB
Raw
1 import { PermissionChecklist, PermissionContinueButton } from "../permissions/PermissionChecklist";
2 import { usePermissionStatus } from "../permissions/usePermissionStatus";
3 import { browserImportFailureMessage } from "@t3tools/client-runtime/contract-labels";
4 import type { BROWSER_IMPORT_FAILURE_COPY, BrowserImportSource } from "@t3tools/contracts";
5 import { ArrowDownIcon, ArrowRightIcon, CheckIcon, HardDriveIcon } from "lucide-react";
6 import { useRef, useState } from "react";
7 import { msg, T, useGT, useMessages, Var } from "gt-react";
8 import type { MessageResolver } from "~/i18n/messages";
9
10 import { cn, randomUUID } from "~/lib/utils";
11
12 import { Button } from "../ui/button";
13 import {
14 Dialog,
15 DialogClose,
16 DialogDescription,
17 DialogAction,
18 DialogFooter,
19 DialogHeader,
20 DialogPanel,
21 DialogPopup,
22 DialogTitle,
23 } from "../ui/dialog";
24 import { Spinner } from "../ui/spinner";
25 import {
26 initialWizardStep,
27 initialTargetSelection,
28 canCloseWizard,
29 isRetryableReason,
30 formatSkippedDomains,
31 fullDiskAccessRecheckStep,
32 outcomeToStep,
33 refreshedSourceProfileDirectory,
34 refreshedSourceStep,
35 resolveWizardTarget,
36 type ImportOutcome,
37 type WizardTarget,
38 type WizardTargetProfile,
39 type WizardTargetSelection,
40 type WizardStep,
41 } from "./browserImportWizard.logic";
42
43 export type { WizardTarget } from "./browserImportWizard.logic";
44
45 interface BrowserImportWizardProps {
46 readonly source: BrowserImportSource;
47 readonly destinationEnvironmentName: string;
48 readonly targetProfiles: ReadonlyArray<WizardTargetProfile>;
49 readonly canCreateProfile: boolean;
50 readonly onImport: (input: {
51 readonly sourceProfileDirectory: string;
52 readonly target: WizardTarget;
53 }) => Promise<ImportOutcome>;
54 readonly onRefreshSource: () => Promise<BrowserImportSource | undefined>;
55 readonly onOpenFullDiskAccessSettings: () => void | Promise<void>;
56 readonly onCheckFullDiskAccess?: (() => Promise<boolean>) | undefined;
57 readonly onClose: () => void;
58 }
59
60 export function BrowserImportWizard({
61 source: initialSource,
62 destinationEnvironmentName,
63 targetProfiles,
64 canCreateProfile,
65 onImport,
66 onRefreshSource,
67 onOpenFullDiskAccessSettings,
68 onCheckFullDiskAccess,
69 onClose,
70 }: BrowserImportWizardProps) {
71 const gt = useGT();
72 const [source, setSource] = useState(initialSource);
73 const [step, setStep] = useState<WizardStep>(() => initialWizardStep(initialSource));
74 const [sourceProfileDirectory, setSourceProfileDirectory] = useState(
75 () => initialSource.profiles[0]?.directory ?? "",
76 );
77 const [target, setTarget] = useState<WizardTargetSelection>(() =>
78 initialTargetSelection(canCreateProfile, targetProfiles),
79 );
80 const [targetError, setTargetError] = useState<string>();
81 const newProfileId = useRef(`profile-${randomUUID()}`);
82 // Guard synchronously so a second click's refusal cannot leave the importing step during the first write.
83 const importInFlight = useRef(false);
84
85 const runImport = () => {
86 if (importInFlight.current) return;
87 const chosen = resolveWizardTarget(target, newProfileId.current, targetProfiles);
88 if (chosen === undefined) {
89 setTargetError(
90 gt("That profile is no longer available. Choose where to import these cookies."),
91 );
92 setStep({ step: "configure" });
93 return;
94 }
95 setTargetError(undefined);
96 importInFlight.current = true;
97 setStep({ step: "importing" });
98 void onImport({ sourceProfileDirectory, target: chosen })
99 .then((outcome) => setStep(outcomeToStep(outcome)))
100 .catch(() => setStep({ step: "blocked", reason: "readFailed" }))
101 .finally(() => {
102 importInFlight.current = false;
103 });
104 };
105
106 const recheckSource = (
107 check: "browser" | "fullDiskAccess",
108 nextStep: (refreshed: BrowserImportSource | undefined) => WizardStep,
109 ) => {
110 setStep({ step: "checking", check });
111 void onRefreshSource()
112 .then((refreshed) => {
113 if (refreshed) {
114 setSource(refreshed);
115 setSourceProfileDirectory((current) =>
116 refreshedSourceProfileDirectory(current, refreshed),
117 );
118 }
119 setStep(nextStep(refreshed));
120 })
121 .catch(() => setStep({ step: "blocked", reason: "readFailed" }));
122 };
123 const recheckAfterQuit = () => recheckSource("browser", refreshedSourceStep);
124 const recheckFullDiskAccess = () => recheckSource("fullDiskAccess", fullDiskAccessRecheckStep);
125
126 return (
127 <Dialog open onOpenChange={(open) => (open || !canCloseWizard(step) ? undefined : onClose())}>
128 <DialogPopup className="max-w-lg" showCloseButton={canCloseWizard(step)}>
129 {step.step === "quit" ? (
130 <QuitStep source={source} onCancel={onClose} onRechecked={recheckAfterQuit} />
131 ) : step.step === "fullDiskAccess" ? (
132 <FullDiskAccessStep
133 source={source}
134 onCancel={onClose}
135 onOpenSettings={onOpenFullDiskAccessSettings}
136 onCheck={
137 onCheckFullDiskAccess ??
138 (async () => {
139 const refreshed = await onRefreshSource();
140 return refreshed !== undefined && refreshed.unavailable === undefined;
141 })
142 }
143 onGranted={step.resume === "import" ? runImport : recheckFullDiskAccess}
144 stillRequired={step.checked === true}
145 />
146 ) : step.step === "importing" ? (
147 <ImportingStep />
148 ) : step.step === "checking" ? (
149 <CheckingStep sourceName={source.name} check={step.check} />
150 ) : step.step === "done" ? (
151 <DoneStep
152 {...step}
153 destinationEnvironmentName={destinationEnvironmentName}
154 onClose={onClose}
155 />
156 ) : step.step === "blocked" ? (
157 <BlockedStep
158 source={source}
159 reason={step.reason}
160 message={step.message}
161 onClose={onClose}
162 onRetry={
163 step.message === undefined && isRetryableReason(step.reason) ? runImport : undefined
164 }
165 />
166 ) : (
167 <ConfigureStep
168 source={source}
169 destinationEnvironmentName={destinationEnvironmentName}
170 targetProfiles={targetProfiles}
171 canCreateProfile={canCreateProfile}
172 sourceProfileDirectory={sourceProfileDirectory}
173 onSourceProfileChange={setSourceProfileDirectory}
174 target={target}
175 onTargetChange={(selection) => {
176 setTarget(selection);
177 setTargetError(undefined);
178 }}
179 targetError={targetError}
180 onCancel={onClose}
181 onImport={runImport}
182 />
183 )}
184 </DialogPopup>
185 </Dialog>
186 );
187 }
188
189 function QuitStep({
190 source,
191 onCancel,
192 onRechecked,
193 }: {
194 readonly source: BrowserImportSource;
195 readonly onCancel: () => void;
196 readonly onRechecked: () => void;
197 }) {
198 return (
199 <>
200 <DialogHeader>
201 <DialogTitle>
202 <T>
203 Quit <Var>{source.name}</Var> to import
204 </T>
205 </DialogTitle>
206 <DialogDescription>
207 <T>
208 <Var>{source.name}</Var> is open, so its cookies can&rsquo;t be read yet. Quit it, then
209 continue.
210 </T>
211 </DialogDescription>
212 </DialogHeader>
213 <DialogFooter>
214 <Button variant="outline" onClick={onCancel}>
215 <T>Cancel</T>
216 </Button>
217 <DialogAction onClick={onRechecked}>
218 <T>I&rsquo;ve quit it</T>
219 </DialogAction>
220 </DialogFooter>
221 </>
222 );
223 }
224
225 function cookieCountLabel(count: number | undefined, resolve: MessageResolver): string | undefined {
226 if (count === undefined) return undefined;
227 if (count === 0) return resolve(msg("no cookies"));
228 return resolve(
229 msg("{count, plural, one {{formatted} cookie} other {{formatted} cookies}}", {
230 count,
231 formatted: count.toLocaleString(),
232 }),
233 );
234 }
235
236 type ConfigureStepProps = {
237 readonly source: BrowserImportSource;
238 readonly destinationEnvironmentName: string;
239 readonly targetProfiles: ReadonlyArray<WizardTargetProfile>;
240 readonly canCreateProfile: boolean;
241 readonly sourceProfileDirectory: string;
242 readonly onSourceProfileChange: (directory: string) => void;
243 readonly target: WizardTargetSelection;
244 readonly targetError: string | undefined;
245 readonly onTargetChange: (target: WizardTargetSelection) => void;
246 readonly onCancel: () => void;
247 readonly onImport: () => void;
248 };
249
250 function FullDiskAccessStep({
251 source,
252 onCancel,
253 onOpenSettings,
254 onGranted,
255 stillRequired,
256 onCheck,
257 }: {
258 readonly source: BrowserImportSource;
259 readonly onCancel: () => void;
260 readonly onOpenSettings: () => void | Promise<void>;
261 readonly onCheck: () => Promise<boolean>;
262 readonly onGranted: () => void;
263 readonly stillRequired: boolean;
264 }) {
265 const gt = useGT();
266 const [opening, setOpening] = useState(false);
267 const [openingError, setOpeningError] = useState<string | null>(null);
268 const permission = usePermissionStatus(async () => ({ fullDiskAccess: await onCheck() }), {
269 fullDiskAccess: false,
270 });
271 const allow = () => {
272 if (opening) return;
273 setOpening(true);
274 setOpeningError(null);
275 void Promise.resolve()
276 .then(onOpenSettings)
277 .catch(() => setOpeningError(gt("Could not open System Settings. Try Allow again.")))
278 .finally(() => setOpening(false));
279 };
280 return (
281 <>
282 <DialogHeader>
283 <DialogTitle>
284 <T>
285 Let T3 Code read <Var>{source.name}</Var>&rsquo;s cookies
286 </T>
287 </DialogTitle>
288 <DialogDescription>
289 <T>
290 To import cookies from <Var>{source.name}</Var>, T3 Code needs Full Disk Access. Turn it
291 on in System Settings, then come back to finish the import. You can revoke it again once
292 the import is done.
293 </T>
294 </DialogDescription>
295 </DialogHeader>
296 <DialogPanel>
297 <PermissionChecklist
298 busy={opening}
299 permissions={[
300 {
301 id: "fullDiskAccess",
302 icon: (
303 <HardDriveIcon
304 className="size-8 shrink-0 text-muted-foreground"
305 aria-hidden="true"
306 />
307 ),
308 title: gt("Full Disk Access"),
309 description: gt("Read {browser}''s cookies for this import.", {
310 browser: source.name,
311 }),
312 granted: permission.status.fullDiskAccess,
313 onAllow: () => void allow(),
314 },
315 ]}
316 />
317 {openingError || permission.error ? (
318 <p role="status" className="mt-3 text-xs text-muted-foreground">
319 {openingError ?? permission.error}
320 </p>
321 ) : null}
322 {!permission.isReady(["fullDiskAccess"]) ? (
323 <p className="mt-3 text-xs text-muted-foreground">
324 {stillRequired
325 ? gt(
326 "Access is still required. Quit and reopen T3 Code if you just allowed it, then retry the import.",
327 )
328 : gt(
329 "If access doesn't update after you allow it, quit and reopen T3 Code, then retry the import.",
330 )}
331 </p>
332 ) : null}
333 </DialogPanel>
334 <DialogFooter>
335 <Button variant="outline" onClick={onCancel}>
336 <T>Cancel</T>
337 </Button>
338 <PermissionContinueButton
339 ready={permission.isReady(["fullDiskAccess"])}
340 busy={opening}
341 onClick={onGranted}
342 >
343 <T>Continue</T>
344 </PermissionContinueButton>
345 </DialogFooter>
346 </>
347 );
348 }
349 function ConfigureStep({
350 source,
351 destinationEnvironmentName,
352 targetProfiles,
353 canCreateProfile,
354 sourceProfileDirectory,
355 onSourceProfileChange,
356 target,
357 targetError,
358 onTargetChange,
359 onCancel,
360 onImport,
361 }: ConfigureStepProps) {
362 const gt = useGT();
363 const m = useMessages();
364 const targetMissing =
365 target.kind === "existing" &&
366 !targetProfiles.some((profile) => profile.id === target.profileId);
367 const targetUncreatable = target.kind === "new" && !canCreateProfile;
368 const targetFeedback =
369 targetError ??
370 (targetMissing
371 ? gt("That profile is no longer available. Choose where to import these cookies.")
372 : targetUncreatable
373 ? gt("You've reached the profile limit. Choose an existing profile to import into.")
374 : undefined);
375 return (
376 <>
377 <DialogHeader>
378 <DialogTitle>
379 <T>
380 Import from <Var>{source.name}</Var>
381 </T>
382 </DialogTitle>
383 <DialogDescription>
384 <T>
385 Choose which cookies to import for <Var>{destinationEnvironmentName}</Var>.
386 </T>
387 </DialogDescription>
388 </DialogHeader>
389 <DialogPanel>
390 <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:gap-4">
391 <section className="flex-1 space-y-2">
392 <p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
393 {gt("From", { $context: "source browser profile" })}
394 </p>
395 {source.profiles.map((profile) => (
396 <SelectableTile
397 key={profile.directory}
398 selected={sourceProfileDirectory === profile.directory}
399 title={profile.name}
400 subtitle={cookieCountLabel(profile.cookieCount, m)}
401 onSelect={() => onSourceProfileChange(profile.directory)}
402 />
403 ))}
404 </section>
405 <div className="flex shrink-0 items-center justify-center text-muted-foreground">
406 <ArrowDownIcon className="size-4 sm:hidden" />
407 <ArrowRightIcon className="hidden size-4 sm:block" />
408 </div>
409 <section className="flex-1 space-y-2">
410 <p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
411 {gt("Into", { $context: "destination profile" })}
412 </p>
413 {canCreateProfile ? (
414 <SelectableTile
415 selected={target.kind === "new"}
416 title={gt("New profile")}
417 subtitle={gt("Created for these cookies")}
418 onSelect={() => onTargetChange({ kind: "new" })}
419 />
420 ) : null}
421 {targetProfiles.map((profile) => (
422 <SelectableTile
423 key={profile.id}
424 selected={target.kind === "existing" && target.profileId === profile.id}
425 title={profile.name}
426 subtitle={gt("Existing profile")}
427 onSelect={() => onTargetChange({ kind: "existing", profileId: profile.id })}
428 />
429 ))}
430 </section>
431 </div>
432 {targetFeedback ? (
433 <p role="alert" className="mt-3 text-sm text-destructive">
434 {targetFeedback}
435 </p>
436 ) : null}
437 </DialogPanel>
438 <DialogFooter>
439 <Button variant="outline" onClick={onCancel}>
440 <T>Cancel</T>
441 </Button>
442 <Button
443 disabled={sourceProfileDirectory === "" || targetMissing || targetUncreatable}
444 onClick={onImport}
445 >
446 {gt("Import", { $context: "verb" })}
447 </Button>
448 </DialogFooter>
449 </>
450 );
451 }
452
453 function SelectableTile({
454 selected,
455 title,
456 subtitle,
457 onSelect,
458 }: {
459 readonly selected: boolean;
460 readonly title: string;
461 readonly subtitle?: string | undefined;
462 readonly onSelect: () => void;
463 }) {
464 return (
465 <button
466 type="button"
467 aria-pressed={selected}
468 onClick={onSelect}
469 className={cn(
470 "flex w-full cursor-pointer items-center justify-between gap-3 rounded-lg border px-3 py-2 text-left outline-none transition-colors focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background",
471 selected
472 ? "border-primary bg-primary/8"
473 : "border-border/60 hover:border-border hover:bg-muted/40",
474 )}
475 >
476 <span className="min-w-0">
477 <span className="block truncate text-sm font-medium text-foreground">{title}</span>
478 {subtitle ? (
479 <span className="block truncate text-xs tabular-nums text-muted-foreground">
480 {subtitle}
481 </span>
482 ) : null}
483 </span>
484 <span
485 className={cn(
486 "grid size-4 shrink-0 place-items-center rounded-full border",
487 selected ? "border-primary bg-primary text-primary-foreground" : "border-input",
488 )}
489 >
490 {selected ? <CheckIcon className="size-2.5" /> : null}
491 </span>
492 </button>
493 );
494 }
495
496 function ImportingStep() {
497 return (
498 <>
499 <DialogHeader>
500 <DialogTitle>
501 <T>Importing cookies</T>
502 </DialogTitle>
503 <DialogDescription>
504 <T>This may take a moment.</T>
505 </DialogDescription>
506 </DialogHeader>
507 <DialogPanel>
508 <div className="flex items-center gap-3 py-2">
509 <Spinner size="md" tone="muted" />
510 <span className="text-sm text-muted-foreground">
511 <T>Importing…</T>
512 </span>
513 </div>
514 </DialogPanel>
515 </>
516 );
517 }
518
519 function CheckingStep({
520 sourceName,
521 check,
522 }: {
523 readonly sourceName: string;
524 readonly check: "browser" | "fullDiskAccess";
525 }) {
526 const gt = useGT();
527 return (
528 <>
529 <DialogHeader>
530 <DialogTitle>
531 <T>
532 Checking <Var>{sourceName}</Var>
533 </T>
534 </DialogTitle>
535 <DialogDescription>
536 {check === "fullDiskAccess"
537 ? gt("Checking Full Disk Access.")
538 : gt("Checking whether the browser has closed.")}
539 </DialogDescription>
540 </DialogHeader>
541 <DialogPanel>
542 <div className="flex items-center gap-3 py-2">
543 <Spinner size="md" tone="muted" />
544 <span className="text-sm text-muted-foreground">
545 {check === "fullDiskAccess" ? gt("Checking access…") : gt("Checking…")}
546 </span>
547 </div>
548 </DialogPanel>
549 </>
550 );
551 }
552
553 function DoneStep({
554 imported,
555 skipped,
556 skippedDomains,
557 targetName,
558 destinationEnvironmentName,
559 onClose,
560 }: {
561 readonly imported: number;
562 readonly skipped: number;
563 readonly skippedDomains: ReadonlyArray<string>;
564 readonly targetName: string;
565 readonly destinationEnvironmentName: string;
566 readonly onClose: () => void;
567 }) {
568 const gt = useGT();
569 const m = useMessages();
570 const environment = destinationEnvironmentName;
571 return (
572 <>
573 <DialogHeader>
574 <DialogTitle>
575 {imported > 0
576 ? gt(
577 "{count, plural, one {Imported {formatted} cookie} other {Imported {formatted} cookies}}",
578 { count: imported, formatted: imported.toLocaleString() },
579 )
580 : skipped > 0
581 ? gt(
582 "{count, plural, one {Skipped {formatted} cookie} other {Skipped {formatted} cookies}}",
583 { count: skipped, formatted: skipped.toLocaleString() },
584 )
585 : gt("No cookies found")}
586 </DialogTitle>
587 <DialogDescription>
588 {imported > 0
589 ? skipped > 0
590 ? gt(
591 "{count, plural, one {Added to {target} for {environment}. {formatted} cookie skipped.} other {Added to {target} for {environment}. {formatted} cookies skipped.}}",
592 {
593 count: skipped,
594 formatted: skipped.toLocaleString(),
595 target: targetName,
596 environment,
597 },
598 )
599 : gt("Added to {target} for {environment}.", { target: targetName, environment })
600 : skipped > 0
601 ? gt("No cookies were imported for {environment}.", { environment })
602 : gt("There were no cookies to import for {environment}.", { environment })}
603 </DialogDescription>
604 </DialogHeader>
605 {skippedDomains.length > 0 ? (
606 <DialogPanel>
607 <p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
608 {gt("Skipped", { $context: "heading, cookie domains that were skipped" })}
609 </p>
610 <p className="mt-1 text-sm text-foreground">{formatSkippedDomains(skippedDomains, m)}</p>
611 </DialogPanel>
612 ) : null}
613 <DialogFooter>
614 <DialogClose render={<Button />} onClick={onClose}>
615 <T>Done</T>
616 </DialogClose>
617 </DialogFooter>
618 </>
619 );
620 }
621
622 function BlockedStep({
623 source,
624 reason,
625 message,
626 onClose,
627 onRetry,
628 }: {
629 readonly source: BrowserImportSource;
630 readonly reason: keyof typeof BROWSER_IMPORT_FAILURE_COPY;
631 readonly message: string | undefined;
632 readonly onClose: () => void;
633 readonly onRetry: (() => void) | undefined;
634 }) {
635 const messages = useMessages();
636 return (
637 <>
638 <DialogHeader>
639 <DialogTitle>
640 <T>
641 Couldn&rsquo;t import from <Var>{source.name}</Var>
642 </T>
643 </DialogTitle>
644 <DialogDescription>
645 {message ?? browserImportFailureMessage(reason, messages)}
646 </DialogDescription>
647 </DialogHeader>
648 <DialogFooter>
649 <Button variant="outline" onClick={onClose}>
650 <T>Close</T>
651 </Button>
652 {onRetry ? (
653 <DialogAction onClick={onRetry}>
654 <T>Try again</T>
655 </DialogAction>
656 ) : null}
657 </DialogFooter>
658 </>
659 );
660 }