@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 603 lines 23.9 KB
Raw
1 import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
2 import { m } from "~/i18n/messages";
3 import { RegistryContext, useAtomValue } from "@effect/atom-react";
4 import {
5 isModifierPairShortcut,
6 type ClientSettingsPatch,
7 type DesktopSnapShotShortcutAvailability,
8 type DesktopSnapShotSetupAction,
9 type SnapShotShortcut,
10 } from "@t3tools/contracts";
11 import { PlayIcon } from "lucide-react";
12 import { settlePromise } from "@t3tools/client-runtime/state/runtime";
13 import * as Cause from "effect/Cause";
14 import { useContext, useRef, useState } from "react";
15 import { T, useGT, useMessages } from "gt-react";
16
17 import { useClientSettings, updateClientSettings } from "../../hooks/useSettings";
18 import { getDesktopSnapShotBridge } from "../../lib/desktopSnapShot";
19 import {
20 saveSnapShotSetupResume,
21 clearSnapShotSetupResume,
22 readSnapShotSetupResume,
23 } from "../../lib/snapShotSetupResume";
24 import { sameSnapShotShortcut, snapShotKeybindingConflict } from "../../lib/snapShotShortcut";
25 import { playSnapShotSound } from "../../lib/snapShotSound";
26 import {
27 desktopSnapShotAtom,
28 refreshDesktopSnapShotState,
29 snapShotSetupError,
30 type SnapShotSetupError,
31 } from "../../state/desktopSnapShot";
32 import { toastManager } from "../ui/toast";
33 import { primaryServerKeybindingsAtom } from "../../state/server";
34 import { commandLabel } from "./KeybindingsSettings.logic";
35 import {
36 snapShotStatus,
37 snapShotShortcutStatus,
38 snapShotSetupButtonLabel,
39 snapShotUnavailableMessage,
40 snapShotSoundPatch,
41 snapShotFeedbackUnavailableMessage,
42 snapShotDescription,
43 snapShotAccessibilityUnavailableMessage,
44 snapShotSetupComplete,
45 type SnapShotSoundSelection,
46 } from "./SnapShotSettings.logic";
47 import {
48 SettingsUnavailableGroup,
49 SettingsPageContainer,
50 SettingsRow,
51 SettingsSection,
52 } from "./settingsLayout";
53 import { useSearchableSetting } from "./settingsSearch";
54 import { Button } from "../ui/button";
55 import { Menu, MenuItem, MenuPopup, MenuRadioGroup, MenuRadioItem, MenuTrigger } from "../ui/menu";
56 import { SelectButton } from "../ui/select";
57 import { Switch } from "../ui/switch";
58 import { SnapShotSetupDialog } from "./SnapShotSetupDialog";
59 import { useSnapShotShortcutRecorder } from "./useSnapShotShortcutRecorder";
60 import {
61 captureSetupAccessReady,
62 captureSetupInitialStep,
63 captureSetupShouldDisableOnClose,
64 type CaptureSetupStep,
65 } from "./SnapShotSetupDialog.logic";
66
67 const soundOptionRowClassName = "grid grid-cols-[1fr_auto]";
68
69 type ShortcutCheck =
70 | { readonly status: "idle"; readonly availability: null }
71 | {
72 readonly status: "checking";
73 readonly availability: null;
74 readonly shortcut: SnapShotShortcut;
75 readonly savedShortcut: SnapShotShortcut;
76 }
77 | {
78 readonly status: "checked";
79 readonly shortcut: SnapShotShortcut;
80 readonly savedShortcut: SnapShotShortcut;
81 readonly availability: DesktopSnapShotShortcutAvailability;
82 };
83
84 export function SnapShotSettings() {
85 const messages = useMessages();
86 const setting = useSearchableSetting();
87 const gt = useGT();
88 const settings = useClientSettings((current) => ({
89 snapShotAnimations: current.snapShotAnimations,
90 snapShotEnabled: current.snapShotEnabled,
91 snapShotFlash: current.snapShotFlash,
92 snapShotIncludeAccessibility: current.snapShotIncludeAccessibility,
93 snapShotPlaySound: current.snapShotPlaySound,
94 snapShotShortcut: current.snapShotShortcut,
95 snapShotSound: current.snapShotSound,
96 }));
97 const keybindings = useAtomValue(primaryServerKeybindingsAtom);
98 const bridge = getDesktopSnapShotBridge();
99 const registry = useContext(RegistryContext);
100 const { state, refreshError } = useAtomValue(desktopSnapShotAtom);
101 const [setupBusy, setSetupBusy] = useState(false);
102 const [setupError, setSetupError] = useState<SnapShotSetupError | null>(null);
103 // macOS can quit the app from a permission prompt; until the user opens or closes the wizard
104 // themselves, a saved resume reopens it where it left off.
105 const [resume] = useState(readSnapShotSetupResume);
106 const [chosenWizard, setWizard] = useState<{
107 initialStep: CaptureSetupStep;
108 wasEnabled: boolean;
109 } | null>();
110 const wizard =
111 chosenWizard !== undefined
112 ? chosenWizard
113 : state?.macPermissions && resume
114 ? { initialStep: "access" as const, wasEnabled: resume.wasEnabled }
115 : null;
116 // The wizard shows errors inline; outside it there is nowhere to, so they become a toast.
117 const reportSetupError = (title: string, error: unknown) => {
118 const report = snapShotSetupError(title, error);
119 setSetupError(report);
120 if (!wizard)
121 toastManager.add({ type: "error", title: report.title, description: report.message });
122 };
123 const refreshState = () =>
124 refreshDesktopSnapShotState(registry, (error) =>
125 reportSetupError(gt("Couldn't check capture setup"), error),
126 );
127 const [candidate, setCandidate] = useState<SnapShotShortcut>(settings.snapShotShortcut);
128 const [latestShortcutCheck, setShortcutCheck] = useState<ShortcutCheck>({
129 status: "idle",
130 availability: null,
131 });
132 // A check answers for one candidate against one saved shortcut. Once either moves on (an edit,
133 // or hydration saving a new shortcut) a late answer no longer shows, so a check for the
134 // shortcut that just got saved can't claim it is ready to save.
135 const savedShortcut = settings.snapShotShortcut;
136 const shortcutCheck: ShortcutCheck =
137 latestShortcutCheck.status === "idle" ||
138 (sameSnapShotShortcut(latestShortcutCheck.shortcut, candidate) &&
139 sameSnapShotShortcut(latestShortcutCheck.savedShortcut, savedShortcut))
140 ? latestShortcutCheck
141 : { status: "idle", availability: null };
142 const shortcutCheckIdRef = useRef(0);
143 const unavailableMessage = snapShotUnavailableMessage(Boolean(bridge), messages);
144 const captureAvailable = Boolean(bridge) && state !== null && state.mode !== "unavailable";
145 const feedbackUnavailable = snapShotFeedbackUnavailableMessage(state, messages);
146 const managedShortcut = state?.linuxBackend === "niri" || state?.linuxBackend === "hyprland";
147 const shortcutChanged = !managedShortcut && !sameSnapShotShortcut(candidate, savedShortcut);
148 const displayShortcut = shortcutChanged ? candidate : (state?.shortcut ?? savedShortcut);
149 const candidateConflict = shortcutChanged
150 ? snapShotKeybindingConflict(candidate, keybindings)
151 : null;
152 const canSaveShortcut =
153 shortcutChanged && candidateConflict === null && shortcutCheck.availability?.available === true;
154 const soundSelection = settings.snapShotPlaySound ? settings.snapShotSound : "off";
155 const soundLabel =
156 soundSelection === "off"
157 ? gt("Off", { $context: "snapshot sound turned off" })
158 : soundSelection === "soft-pop"
159 ? gt("Whoosh (Default)")
160 : gt("Click", { $context: "name of a camera-shutter sound" });
161
162 const setup = async (action: DesktopSnapShotSetupAction) => {
163 if (!bridge || setupBusy) return;
164 setSetupBusy(true);
165 setSetupError(null);
166 const result = await settlePromise(async () => {
167 if (
168 state?.macPermissions &&
169 wizard &&
170 (action === "allow-screen-recording" || action === "allow-accessibility")
171 ) {
172 // macOS can quit the app from its permission prompt.
173 saveSnapShotSetupResume(wizard.wasEnabled);
174 }
175 await bridge.setupSnapShot(action);
176 await refreshState();
177 });
178 if (result._tag === "Failure") {
179 reportSetupError(
180 action === "retry-shortcut"
181 ? gt("Couldn't open shortcut permissions")
182 : gt("Couldn't complete capture setup"),
183 Cause.squash(result.cause),
184 );
185 }
186 setSetupBusy(false);
187 };
188
189 // Hydration can hand back an equal shortcut object; only a different shortcut resets the edit.
190 const [renderedSavedShortcut, setRenderedSavedShortcut] = useState(savedShortcut);
191 if (!sameSnapShotShortcut(renderedSavedShortcut, savedShortcut)) {
192 setRenderedSavedShortcut(savedShortcut);
193 setCandidate(savedShortcut);
194 setShortcutCheck({ status: "idle", availability: null });
195 }
196
197 const save = async (patch: ClientSettingsPatch) => {
198 setSetupError(null);
199 try {
200 await updateClientSettings(patch);
201 return await refreshState();
202 } catch (error) {
203 reportSetupError(gt("Couldn't save capture settings"), error);
204 }
205 };
206
207 const saveIncludeAccessibility = async (includeAccessibility: boolean) => {
208 try {
209 if (includeAccessibility && settings.snapShotEnabled)
210 await bridge?.requestSnapShotPermissions(true);
211 await save({ snapShotIncludeAccessibility: includeAccessibility });
212 } catch (error) {
213 reportSetupError(gt("Couldn't allow app text capture"), error);
214 }
215 };
216
217 const checkShortcut = async (shortcut: SnapShotShortcut) => {
218 const checkId = ++shortcutCheckIdRef.current;
219 setCandidate(shortcut);
220 const conflict = snapShotKeybindingConflict(shortcut, keybindings);
221 if (conflict || !bridge) return;
222 setShortcutCheck({ status: "checking", availability: null, shortcut, savedShortcut });
223 try {
224 const availability = await bridge.checkSnapShotShortcut(shortcut);
225 if (checkId === shortcutCheckIdRef.current) {
226 setShortcutCheck({ status: "checked", availability, shortcut, savedShortcut });
227 }
228 } catch (error) {
229 if (checkId !== shortcutCheckIdRef.current) return;
230 setShortcutCheck({
231 status: "checked",
232 shortcut,
233 savedShortcut,
234 availability: {
235 available: false,
236 message:
237 error instanceof Error
238 ? (thrownErrorMessage(error, m) ?? error.message)
239 : gt("Could not check this shortcut."),
240 },
241 });
242 }
243 };
244
245 const {
246 recording,
247 stopRecording,
248 input: shortcutInput,
249 } = useSnapShotShortcutRecorder({
250 shortcut: displayShortcut,
251 shortcutLabel: !shortcutChanged ? state?.shortcutLabel : undefined,
252 disabled: setupBusy,
253 allowModifierPairs: state?.mode !== "portal",
254 onRecord: (shortcut) => void checkShortcut(shortcut),
255 onStart: () => {
256 shortcutCheckIdRef.current++;
257 setShortcutCheck({ status: "idle", availability: null });
258 },
259 onError: (message) =>
260 setShortcutCheck({
261 status: "checked",
262 shortcut: candidate,
263 savedShortcut,
264 availability: { available: false, message },
265 }),
266 });
267
268 const shortcutStatus = recording
269 ? gt("Press your shortcut. Esc cancels.")
270 : candidateConflict
271 ? gt('T3 Code already uses this for "{command}".', {
272 command: commandLabel(candidateConflict, messages),
273 })
274 : shortcutCheck.status === "checking"
275 ? gt("Checking shortcut…")
276 : shortcutCheck.availability
277 ? shortcutCheck.availability.available
278 ? gt("Ready to save.")
279 : shortcutCheck.availability.message
280 : state?.mode === "portal" &&
281 !state.shortcutLabel &&
282 isModifierPairShortcut(displayShortcut)
283 ? gt("Try a shortcut such as Ctrl+Shift+2.")
284 : snapShotShortcutStatus(state, messages);
285
286 const openSetup = async (requested: CaptureSetupStep | "resume" = "resume") => {
287 if (!state || setupBusy) return;
288 stopRecording();
289 shortcutCheckIdRef.current++;
290 setCandidate(savedShortcut);
291 setShortcutCheck({ status: "idle", availability: null });
292 setSetupError(null);
293 setSetupBusy(true);
294 await prepareSetup(requested).finally(() => setSetupBusy(false));
295 };
296
297 const prepareSetup = async (requested: CaptureSetupStep | "resume") => {
298 let current = await refreshState();
299 if (!current) return;
300 if (current.macPermissions) requested = "access";
301 if (!settings.snapShotEnabled && captureSetupInitialStep(current, requested) !== "access") {
302 current = await save({ snapShotEnabled: true });
303 if (!current) {
304 // Settings may save before status checking fails; keep Finish later available to disable capture.
305 setWizard({ initialStep: "access", wasEnabled: false });
306 return;
307 }
308 }
309 setWizard({
310 initialStep: captureSetupInitialStep(current, requested),
311 wasEnabled: settings.snapShotEnabled,
312 });
313 };
314
315 const enableForSetup = async () => {
316 if (setupBusy) return false;
317 setSetupBusy(true);
318 setSetupError(null);
319 const verified = await settlePromise(async () => {
320 if (state?.macPermissions) {
321 saveSnapShotSetupResume(wizard?.wasEnabled ?? settings.snapShotEnabled);
322 await bridge?.setupSnapShot("test-mac-capture");
323 }
324 if (state?.mode === "direct")
325 await bridge?.requestSnapShotPermissions(settings.snapShotIncludeAccessibility);
326 const nextState =
327 settings.snapShotEnabled && !state?.message
328 ? await refreshState()
329 : await save({ snapShotEnabled: true });
330 return nextState !== undefined && captureSetupAccessReady(nextState);
331 });
332 setSetupBusy(false);
333 if (verified._tag === "Success") return verified.value;
334 reportSetupError(gt("Couldn't verify capture access"), Cause.squash(verified.cause));
335 return false;
336 };
337
338 const closeSetup = async (completed: boolean) => {
339 if (!wizard || setupBusy) return;
340 setSetupBusy(true);
341 const closed = await settlePromise(async () => {
342 if (
343 settings.snapShotEnabled &&
344 captureSetupShouldDisableOnClose(wizard.wasEnabled, completed)
345 ) {
346 if (!(await save({ snapShotEnabled: false }))) return;
347 }
348 stopRecording();
349 setSetupError(null);
350 clearSnapShotSetupResume();
351 setWizard(null);
352 });
353 if (closed._tag === "Failure") {
354 reportSetupError(gt("Couldn't close capture setup"), Cause.squash(closed.cause));
355 }
356 setSetupBusy(false);
357 };
358
359 const saveShortcut = async () => {
360 if (!canSaveShortcut || setupBusy) return false;
361 setSetupBusy(true);
362 const saved = await save({ snapShotShortcut: candidate }).finally(() => setSetupBusy(false));
363 return Boolean(saved?.shortcutRegistered || saved?.shortcutPending);
364 };
365
366 return (
367 <SettingsPageContainer>
368 <SettingsSection id="snap-shot" title={gt("SnapShots")}>
369 <SettingsUnavailableGroup message={unavailableMessage}>
370 <SettingsRow
371 {...setting("snap-shot-enabled")}
372 description={snapShotDescription(state, messages)}
373 status={
374 bridge
375 ? setupBusy && !wizard
376 ? gt("Updating capture settings…")
377 : refreshError
378 ? `${refreshError.title}. ${refreshError.message}`
379 : snapShotStatus(state, settings.snapShotEnabled, messages)
380 : undefined
381 }
382 control={
383 <>
384 {settings.snapShotEnabled &&
385 !snapShotSetupComplete(state, settings.snapShotIncludeAccessibility) ? (
386 <Button
387 size="xs"
388 variant="outline"
389 disabled={setupBusy}
390 onClick={() => void openSetup()}
391 >
392 {snapShotSetupButtonLabel(state, messages)}
393 </Button>
394 ) : null}
395 <Switch
396 checked={settings.snapShotEnabled || Boolean(wizard)}
397 disabled={!captureAvailable || setupBusy}
398 aria-label={gt("Enable snapshots")}
399 onCheckedChange={(checked) => {
400 if (!checked) void save({ snapShotEnabled: false });
401 else if (state?.windows) void save({ snapShotEnabled: true });
402 else void openSetup();
403 }}
404 />
405 </>
406 }
407 />
408 {settings.snapShotEnabled && captureAvailable ? (
409 <>
410 <SettingsRow
411 {...setting("snap-shot-accessibility")}
412 description={gt("Include text and controls when the app makes them available.")}
413 status={snapShotAccessibilityUnavailableMessage(state, messages)}
414 control={
415 <Switch
416 checked={
417 !snapShotAccessibilityUnavailableMessage(state, messages) &&
418 settings.snapShotIncludeAccessibility
419 }
420 disabled={
421 !captureAvailable ||
422 Boolean(snapShotAccessibilityUnavailableMessage(state, messages))
423 }
424 aria-label={gt("Include app text in snapshots")}
425 onCheckedChange={(checked) => void saveIncludeAccessibility(checked)}
426 />
427 }
428 />
429 <SettingsRow
430 {...setting("snap-shot-shortcut")}
431 description={
432 state?.linuxBackend === "picker"
433 ? gt("Choose a window to capture from any app.")
434 : gt("Capture the window you're using without switching apps.")
435 }
436 status={managedShortcut ? undefined : shortcutStatus}
437 control={
438 managedShortcut ? (
439 <Button
440 size="xs"
441 variant="outline"
442 disabled={setupBusy}
443 onClick={() => void openSetup("shortcut")}
444 >
445 <T>Change shortcut</T>
446 </Button>
447 ) : (
448 <>
449 {shortcutInput}
450 {shortcutChanged ? (
451 <>
452 <Button
453 size="xs"
454 disabled={!canSaveShortcut || setupBusy}
455 onClick={() => void saveShortcut()}
456 >
457 {setupBusy ? gt("Saving…") : gt("Save")}
458 </Button>
459 <Button
460 size="xs"
461 variant="ghost"
462 disabled={setupBusy}
463 onClick={() => {
464 stopRecording();
465 shortcutCheckIdRef.current++;
466 setCandidate(savedShortcut);
467 setShortcutCheck({ status: "idle", availability: null });
468 }}
469 >
470 <T>Cancel</T>
471 </Button>
472 </>
473 ) : state?.mode === "portal" &&
474 state.shortcutCanRetry !== false &&
475 !isModifierPairShortcut(savedShortcut) ? (
476 <Button
477 size="xs"
478 variant="ghost"
479 disabled={setupBusy || state.shortcutPending}
480 onClick={() => void setup("retry-shortcut")}
481 >
482 <T>Shortcut permissions</T>
483 </Button>
484 ) : null}
485 </>
486 )
487 }
488 />
489 <SettingsRow
490 {...setting("snap-shot-sound")}
491 description={gt("Choose the sound played when capture starts.")}
492 control={
493 <Menu>
494 <MenuTrigger
495 aria-label={gt("Snapshot sound: {sound}", { sound: soundLabel })}
496 render={<SelectButton size="sm" />}
497 className="w-auto min-w-0"
498 disabled={!captureAvailable}
499 >
500 {soundSelection === "off" ? (
501 gt("Off", { $context: "snapshot sound turned off" })
502 ) : soundSelection === "soft-pop" ? (
503 <T>
504 Whoosh <span className="text-muted-foreground">(Default)</span>
505 </T>
506 ) : (
507 gt("Click", { $context: "name of a camera-shutter sound" })
508 )}
509 </MenuTrigger>
510 <MenuPopup align="end">
511 <MenuRadioGroup
512 onValueChange={(value) =>
513 void save(snapShotSoundPatch(value as SnapShotSoundSelection))
514 }
515 value={soundSelection}
516 >
517 <MenuRadioItem closeOnClick value="off">
518 {gt("Off", { $context: "snapshot sound turned off" })}
519 </MenuRadioItem>
520 <div className={soundOptionRowClassName}>
521 <MenuRadioItem closeOnClick value="soft-pop">
522 <T>
523 Whoosh <span className="text-muted-foreground">(Default)</span>
524 </T>
525 </MenuRadioItem>
526 <MenuItem
527 aria-label={gt("Play Whoosh")}
528 closeOnClick={false}
529 onClick={() => playSnapShotSound("soft-pop")}
530 >
531 <PlayIcon />
532 </MenuItem>
533 </div>
534 <div className={soundOptionRowClassName}>
535 <MenuRadioItem closeOnClick value="camera-shutter">
536 {gt("Click", { $context: "name of a camera-shutter sound" })}
537 </MenuRadioItem>
538 <MenuItem
539 aria-label={gt("Play Click")}
540 closeOnClick={false}
541 onClick={() => playSnapShotSound("camera-shutter")}
542 >
543 <PlayIcon />
544 </MenuItem>
545 </div>
546 </MenuRadioGroup>
547 </MenuPopup>
548 </Menu>
549 }
550 />
551 <SettingsRow
552 {...setting("snap-shot-flash")}
553 description={gt("Show a gentle cue on the captured window.")}
554 status={feedbackUnavailable}
555 control={
556 <Switch
557 checked={!feedbackUnavailable && settings.snapShotFlash}
558 disabled={!captureAvailable || Boolean(feedbackUnavailable)}
559 aria-label={gt("Flash captured window")}
560 onCheckedChange={(checked) => void save({ snapShotFlash: checked })}
561 />
562 }
563 />
564 <SettingsRow
565 {...setting("snap-shot-animations")}
566 description={gt("Animate captured windows into your draft.")}
567 status={feedbackUnavailable}
568 control={
569 <Switch
570 checked={!feedbackUnavailable && settings.snapShotAnimations}
571 disabled={!captureAvailable || Boolean(feedbackUnavailable)}
572 aria-label={gt("Animate snapshots")}
573 onCheckedChange={(checked) => void save({ snapShotAnimations: checked })}
574 />
575 }
576 />
577 </>
578 ) : null}
579 </SettingsUnavailableGroup>
580 </SettingsSection>
581 {wizard && state ? (
582 <SnapShotSetupDialog
583 state={state}
584 initialStep={wizard.initialStep}
585 wasEnabled={wizard.wasEnabled}
586 includeAccessibility={settings.snapShotIncludeAccessibility}
587 busy={setupBusy}
588 error={(setupError ?? refreshError)?.message ?? null}
589 shortcutInput={shortcutInput}
590 shortcutStatus={shortcutStatus}
591 shortcutChanged={shortcutChanged}
592 canSaveShortcut={canSaveShortcut}
593 onSaveShortcut={saveShortcut}
594 onEnable={enableForSetup}
595 onAction={setup}
596 onRefresh={refreshState}
597 onClose={closeSetup}
598 onLeaveStep={stopRecording}
599 />
600 ) : null}
601 </SettingsPageContainer>
602 );
603 }