@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 1,737 lines 62.6 KB
Raw
1 import { managedCapabilityDenial } from "@t3tools/client-runtime/contract-labels";
2 import { DeviceHostUpdates } from "../device/DeviceHostUpdates";
3 import { DeviceToolVersions } from "../device/DeviceToolVersions";
4 import { useScopedSettings, useUpdateScopedSettings } from "./useScopedSettings";
5 import { ScopedSwitch } from "./ScopedSwitch";
6 import { DeviceSourcesSettings } from "./DeviceSourcesSettings";
7 import {
8 AuthSettingsWriteScope,
9 BrowserImportFailureReason,
10 BROWSER_PROFILE_MAX_COUNT,
11 type BrowserLinkTarget,
12 type BrowserProfile,
13 BrowserSearchEngine,
14 BROWSER_CUSTOM_SEARCH_URL_MAX_LENGTH,
15 type EnvironmentId,
16 BROWSER_PROFILE_NAME_MAX_LENGTH,
17 BROWSER_RECORDING_FRAME_RATES,
18 DEFAULT_BROWSER_AUTO_SHOW_FLOATING_PREVIEW,
19 DEFAULT_BROWSER_PROFILE_ID,
20 DEFAULT_BROWSER_LINK_TARGET,
21 DEFAULT_BROWSER_RECORDING_FRAME_RATE,
22 DEFAULT_BROWSER_SEARCH_ENGINE,
23 DEFAULT_BROWSER_VIEWPORT,
24 DEFAULT_PREVIEW_APPEARANCE,
25 DEFAULT_PREVIEW_ZOOM_FACTOR,
26 DEFAULT_SERVER_SETTINGS,
27 FILL_PREVIEW_VIEWPORT,
28 PREVIEW_VIEWPORT_MAX_AREA,
29 PREVIEW_VIEWPORT_MAX_DIMENSION,
30 PREVIEW_VIEWPORT_MIN_DIMENSION,
31 PREVIEW_ZOOM_LEVELS,
32 findBrowserProfile,
33 isBuiltInBrowserProfileId,
34 resolveBrowserProfiles,
35 type BrowserImportSource,
36 type PreviewAppearancePreference,
37 type PreviewViewportSetting,
38 } from "@t3tools/contracts";
39 import { usePrimaryManagedPolicy } from "~/state/managedPolicy";
40 import { isValidSearchUrlTemplate } from "@t3tools/shared/preview";
41 import { PREVIEW_VIEWPORT_PRESETS } from "@t3tools/shared/previewViewport";
42 import { MoreVertical, Plus as PlusIcon } from "lucide-react";
43 import * as Schema from "effect/Schema";
44 import { useRef, useState } from "react";
45 import { msg, T, useGT, useMessages, Var } from "gt-react";
46 import { m as resolveNow, type MessageResolver } from "../../i18n/messages";
47
48 import { ScreenRotationIcon } from "~/browser/ScreenRotationIcon";
49 import { resolveEnvironmentOptionLabel } from "~/components/BranchToolbar.logic";
50 import { previewBridge } from "~/components/preview/previewBridge";
51 import { cn, randomUUID } from "~/lib/utils";
52 import { useEnvironments, usePrimaryEnvironment } from "~/state/environments";
53 import { deviceEnvironment, useDeviceState } from "~/state/device";
54 import { readEnvironmentScope, useEnvironmentScope } from "~/state/session";
55 import { useAtomCommand } from "~/state/use-atom-command";
56 import { formatEnvironmentQueryError } from "~/state/query";
57 import { previewEnvironment } from "~/state/preview";
58 import { useServerConfigs } from "~/state/entities";
59 import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
60 import {
61 AgentDeviceSetupStatus,
62 DeviceHubSetupStatus,
63 deviceHubReadiness,
64 } from "~/components/device/DeviceSetup";
65 import { isElectron } from "../../env";
66
67 import { Badge } from "../ui/badge";
68 import {
69 Menu,
70 MenuGroup,
71 MenuGroupLabel,
72 MenuItem,
73 MenuPopup,
74 MenuSeparator,
75 MenuTrigger,
76 } from "../ui/menu";
77 import { readLocalApi } from "~/localApi";
78
79 import { toastManager } from "../ui/toast";
80 import {
81 AlertDialog,
82 AlertDialogClose,
83 AlertDialogDescription,
84 AlertDialogFooter,
85 AlertDialogHeader,
86 AlertDialogPopup,
87 AlertDialogTitle,
88 } from "../ui/alert-dialog";
89 import { Button } from "../ui/button";
90 import { DraftInput } from "../ui/draft-input";
91 import { NumberField, NumberFieldGroup, NumberFieldInput } from "../ui/number-field";
92 import {
93 Select,
94 SelectGroup,
95 SelectGroupLabel,
96 SelectItem,
97 SelectPopup,
98 SelectTrigger,
99 SelectValue,
100 } from "../ui/select";
101 import { Switch } from "../ui/switch";
102 import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
103 import {
104 getClientSettings,
105 persistClientSettingsUpdate,
106 useClientSettings,
107 useClientSettingsHydrated,
108 useUpdatePrimarySettings,
109 } from "~/hooks/useSettings";
110
111 import {
112 SettingsUnavailableGroup,
113 SettingResetButton,
114 SettingsPageContainer,
115 SettingsRow,
116 SettingsSection,
117 } from "./settingsLayout";
118 import { useSearchableSetting } from "./settingsSearch";
119 import { AdvancedSettings } from "./AdvancedSettings";
120 import { useSettingsScope } from "./SettingsScopeContext";
121 import { BrowserImportWizard, type WizardTarget } from "./BrowserImportWizard";
122 import type { ImportOutcome } from "./browserImportWizard.logic";
123
124 const FILL_VALUE = "fill";
125 const RESPONSIVE_VALUE = "responsive";
126
127 type BrowserProfileDataBridge = Pick<
128 NonNullable<typeof previewBridge>,
129 "clearCookies" | "clearCache"
130 >;
131
132 export interface ServerProfileData {
133 readonly environmentIds: ReadonlyArray<EnvironmentId>;
134 readonly clear: (environmentId: EnvironmentId, profileId: string) => Promise<void>;
135 }
136
137 export async function clearBrowserProfileData(
138 bridge: BrowserProfileDataBridge | null,
139 environmentIds: ReadonlyArray<EnvironmentId>,
140 profileId: string,
141 server?: ServerProfileData,
142 ): Promise<void> {
143 const desktopEnvironmentIds = bridge === null ? [] : environmentIds;
144 const serverEnvironmentIds = server?.environmentIds ?? [];
145 if (desktopEnvironmentIds.length === 0 && serverEnvironmentIds.length === 0) {
146 throw new Error(resolveNow(msg("Browser profile data is not available to clear.")));
147 }
148 await Promise.all([
149 ...desktopEnvironmentIds.flatMap((environmentId) => [
150 bridge!.clearCookies(environmentId, profileId),
151 bridge!.clearCache(environmentId, profileId),
152 ]),
153 ...serverEnvironmentIds.map((environmentId) => server!.clear(environmentId, profileId)),
154 ]);
155 }
156
157 function browserProfileRemovalAvailable(
158 bridgeAvailable: boolean,
159 environmentsReady: boolean,
160 environmentCount: number,
161 serverBrowserCount = 0,
162 ): boolean {
163 return (bridgeAvailable || serverBrowserCount > 0) && environmentsReady && environmentCount > 0;
164 }
165
166 const RESPONSIVE_SEED_SIZE = { width: 1280, height: 800 } as const;
167
168 const NO_GROUPING: Intl.NumberFormatOptions = { useGrouping: false };
169
170 const APPEARANCE_LABELS: Readonly<Record<PreviewAppearancePreference, string>> = {
171 system: msg("System", { $context: "appearance follows the system" }),
172 light: msg("Light", { $context: "appearance" }),
173 dark: msg("Dark", { $context: "appearance" }),
174 };
175
176 const zoomLabel = (zoomFactor: number) => `${Math.round(zoomFactor * 100)}%`;
177
178 /** IPC carries reason tokens inside messages; treat unknown tokens as read failures without exposing raw
179 * text. */
180 class ProfileLimitReachedError extends Schema.TaggedError<ProfileLimitReachedError>()(
181 "ProfileLimitReachedError",
182 {},
183 ) {
184 override get message(): string {
185 return "Browser profile limit reached.";
186 }
187 }
188
189 const isProfileLimitReachedError = Schema.is(ProfileLimitReachedError);
190
191 export const importFailureReason = (cause: unknown): BrowserImportFailureReason => {
192 const message = String((cause as { message?: unknown } | undefined)?.message ?? "");
193 return (
194 BrowserImportFailureReason.literals.find((reason) => message.includes(`failed: ${reason}.`)) ??
195 "readFailed"
196 );
197 };
198
199 /**
200 * The desktop's refusal when the machine's managed policy forbids cookie import. IPC wraps the
201 * message in its own prefixes, so the sentence is matched on the contract's wording.
202 */
203 export const importPolicyRefusal = (cause: unknown): string | undefined => {
204 const message = String((cause as { message?: unknown } | undefined)?.message ?? "");
205 return (
206 /The managed policy at .* importing browser cookies is not allowed\./u.exec(message)?.[0] ??
207 /(?:^|: )([^:]*'s policy does not allow importing browser cookies\.)/u.exec(message)?.[1]
208 );
209 };
210
211 async function importBrowserCookiesIntoTarget(
212 bridge: NonNullable<typeof previewBridge>,
213 source: BrowserImportSource,
214 environmentId: EnvironmentId,
215 input: { readonly sourceProfileDirectory: string; readonly target: WizardTarget },
216 ): Promise<ImportOutcome> {
217 try {
218 const result = await bridge.importBrowserCookies({
219 environmentId,
220 sourceId: source.id,
221 sourceProfileDirectory: input.sourceProfileDirectory,
222 targetProfileId: input.target.profileId,
223 });
224 if (
225 input.target.kind === "existing" &&
226 !resolveBrowserProfiles(getClientSettings().browserProfiles).some(
227 (profile) => profile.id === input.target.profileId,
228 )
229 ) {
230 return { kind: "blocked", reason: "readFailed" };
231 }
232 let targetName: string;
233 if (input.target.kind === "new") {
234 if (result.imported > 0) {
235 try {
236 const persisted = await persistClientSettingsUpdate((current) => {
237 const existing = current.browserProfiles.find(
238 (profile) => profile.id === input.target.profileId,
239 );
240 if (existing) return current;
241 // The profile cap may be reached during import; enforce it against the updater's latest settings.
242 if (current.browserProfiles.length >= BROWSER_PROFILE_MAX_COUNT) {
243 throw new ProfileLimitReachedError();
244 }
245 const taken = new Set(
246 resolveBrowserProfiles(current.browserProfiles).map((profile) => profile.name),
247 );
248 let name = source.name;
249 for (let index = 2; taken.has(name); index += 1) name = `${source.name} ${index}`;
250 return {
251 ...current,
252 browserProfiles: [
253 ...current.browserProfiles,
254 { id: input.target.profileId, name, kind: "persistent" as const },
255 ],
256 };
257 });
258 targetName =
259 persisted.browserProfiles.find((profile) => profile.id === input.target.profileId)
260 ?.name ?? source.name;
261 } catch (cause) {
262 // Clear the new target's partition on registration failure so imported cookies cannot outlive its
263 // profile.
264 await clearBrowserProfileData(bridge, [environmentId], input.target.profileId).catch(
265 () => undefined,
266 );
267 const reason = isProfileLimitReachedError(cause)
268 ? "profileLimitReached"
269 : "profileNotSaved";
270 throw new Error(`Importing cookies from ${source.id} failed: ${reason}.`, { cause });
271 }
272 } else {
273 targetName = source.name;
274 }
275 } else {
276 targetName = input.target.name;
277 }
278 return {
279 kind: "imported",
280 imported: result.imported,
281 skipped: result.skipped,
282 skippedDomains: result.skippedDomains,
283 targetName,
284 };
285 } catch (cause) {
286 const policyRefusal = importPolicyRefusal(cause);
287 return policyRefusal !== undefined
288 ? { kind: "blocked", reason: "readFailed", message: policyRefusal }
289 : { kind: "blocked", reason: importFailureReason(cause) };
290 }
291 }
292
293 const viewportSelectValue = (viewport: PreviewViewportSetting): string => {
294 if (viewport._tag === "fill") return FILL_VALUE;
295 if (
296 viewport._tag === "preset" &&
297 PREVIEW_VIEWPORT_PRESETS.some((preset) => preset.id === viewport.presetId)
298 ) {
299 return viewport.presetId;
300 }
301 return RESPONSIVE_VALUE;
302 };
303
304 /** Inline options lack an items map; bare SelectValue would display the stored fill token. */
305 const viewportSelectLabel = (
306 viewport: PreviewViewportSetting,
307 resolve: MessageResolver,
308 ): string => {
309 const value = viewportSelectValue(viewport);
310 if (value === FILL_VALUE) return resolve(msg("Fill panel"));
311 if (value === RESPONSIVE_VALUE) return resolve(msg("Responsive"));
312 return (
313 PREVIEW_VIEWPORT_PRESETS.find((preset) => preset.id === value)?.label ??
314 resolve(msg("Responsive"))
315 );
316 };
317
318 const isValidDimension = (value: number) =>
319 Number.isInteger(value) &&
320 value >= PREVIEW_VIEWPORT_MIN_DIMENSION &&
321 value <= PREVIEW_VIEWPORT_MAX_DIMENSION;
322
323 const rotateViewport = (
324 viewport: Exclude<PreviewViewportSetting, { readonly _tag: "fill" }>,
325 ): PreviewViewportSetting => ({
326 ...viewport,
327 width: viewport.height,
328 height: viewport.width,
329 });
330
331 function BrowserViewportSetting({ disabled }: { readonly disabled: boolean }) {
332 const searchableSetting = useSearchableSetting();
333 const gt = useGT();
334 const m = useMessages();
335 const viewport = useClientSettings((settings) => settings.browserDefaultViewport);
336 const updateSettings = useUpdateScopedSettings();
337
338 const sized = viewport._tag === "fill" ? null : viewport;
339 const presentedSize = {
340 width: sized?.width ?? RESPONSIVE_SEED_SIZE.width,
341 height: sized?.height ?? RESPONSIVE_SEED_SIZE.height,
342 };
343
344 const selectViewport = (value: string | null) => {
345 if (value === FILL_VALUE) {
346 updateSettings({ browserDefaultViewport: FILL_PREVIEW_VIEWPORT });
347 return;
348 }
349 if (value === RESPONSIVE_VALUE) {
350 updateSettings({
351 browserDefaultViewport: {
352 _tag: "freeform",
353 width: sized?.width ?? RESPONSIVE_SEED_SIZE.width,
354 height: sized?.height ?? RESPONSIVE_SEED_SIZE.height,
355 },
356 });
357 return;
358 }
359 const preset = PREVIEW_VIEWPORT_PRESETS.find((candidate) => candidate.id === value);
360 if (!preset) return;
361 updateSettings({
362 browserDefaultViewport: {
363 _tag: "preset",
364 width: preset.width,
365 height: preset.height,
366 presetId: preset.id,
367 },
368 });
369 };
370
371 // Commit on blur to avoid persisting valid intermediate dimensions and rewriting settings per keystroke.
372 const commitDimension = (axis: "width" | "height", value: number | null) => {
373 if (value === null || !isValidDimension(value)) return;
374 const next = { ...presentedSize, [axis]: value };
375 if (next.width * next.height > PREVIEW_VIEWPORT_MAX_AREA) return;
376 if (sized && next.width === sized.width && next.height === sized.height) return;
377 updateSettings({ browserDefaultViewport: { _tag: "freeform", ...next } });
378 };
379
380 return (
381 <SettingsRow
382 {...searchableSetting("browser-default-viewport")}
383 devicePreference
384 description={gt(
385 "Tab size for you and agents. Fill fits the panel; other sizes show the device toolbar.",
386 )}
387 resetAction={
388 !disabled && viewport._tag !== DEFAULT_BROWSER_VIEWPORT._tag ? (
389 <SettingResetButton
390 ariaLabel={gt("Reset default browser viewport to default")}
391 onClick={() => updateSettings({ browserDefaultViewport: DEFAULT_BROWSER_VIEWPORT })}
392 />
393 ) : null
394 }
395 control={
396 <div className="flex w-full flex-wrap items-center justify-end gap-2 sm:w-auto">
397 <Select
398 value={viewportSelectValue(viewport)}
399 onValueChange={selectViewport}
400 disabled={disabled}
401 >
402 <SelectTrigger
403 size="sm"
404 className="w-full min-w-0 sm:w-44"
405 aria-label={gt("Default browser viewport")}
406 >
407 <SelectValue>{viewportSelectLabel(viewport, m)}</SelectValue>
408 </SelectTrigger>
409 <SelectPopup align="end" alignItemWithTrigger={false}>
410 <SelectItem value={FILL_VALUE}>
411 <T>Fill panel</T>
412 </SelectItem>
413 <SelectItem value={RESPONSIVE_VALUE}>
414 <T>Responsive</T>
415 </SelectItem>
416 <SelectGroup>
417 <SelectGroupLabel>
418 {gt("Standard", { $context: "standard viewport sizes" })}
419 </SelectGroupLabel>
420 {PREVIEW_VIEWPORT_PRESETS.map((preset) => (
421 <SelectItem key={preset.id} value={preset.id}>
422 <span className="flex w-full items-center justify-between gap-5">
423 <span>{preset.label}</span>
424 <span className="text-xs tabular-nums text-muted-foreground">
425 {preset.detail}
426 </span>
427 </span>
428 </SelectItem>
429 ))}
430 </SelectGroup>
431 </SelectPopup>
432 </Select>
433
434 {sized ? (
435 <div className="flex min-w-0 items-center gap-1">
436 <NumberField
437 value={presentedSize.width}
438 min={PREVIEW_VIEWPORT_MIN_DIMENSION}
439 max={PREVIEW_VIEWPORT_MAX_DIMENSION}
440 disabled={disabled}
441 format={NO_GROUPING}
442 size="sm"
443 className="w-20"
444 onValueCommitted={(value) => commitDimension("width", value)}
445 >
446 <NumberFieldGroup>
447 <NumberFieldInput aria-label={gt("Default viewport width")} />
448 </NumberFieldGroup>
449 </NumberField>
450 <span className="text-xs text-muted-foreground">×</span>
451 <NumberField
452 value={presentedSize.height}
453 min={PREVIEW_VIEWPORT_MIN_DIMENSION}
454 max={PREVIEW_VIEWPORT_MAX_DIMENSION}
455 disabled={disabled}
456 format={NO_GROUPING}
457 size="sm"
458 className="w-20"
459 onValueCommitted={(value) => commitDimension("height", value)}
460 >
461 <NumberFieldGroup>
462 <NumberFieldInput aria-label={gt("Default viewport height")} />
463 </NumberFieldGroup>
464 </NumberField>
465 <Tooltip>
466 <TooltipTrigger
467 render={
468 <Button
469 size="icon-sm"
470 variant="ghost-muted"
471 disabled={disabled}
472 aria-label={
473 presentedSize.height >= presentedSize.width
474 ? gt("Rotate to landscape")
475 : gt("Rotate to portrait")
476 }
477 onClick={() =>
478 updateSettings({ browserDefaultViewport: rotateViewport(sized) })
479 }
480 >
481 <ScreenRotationIcon />
482 </Button>
483 }
484 />
485 <TooltipPopup side="top">
486 <T>Rotate</T>
487 </TooltipPopup>
488 </Tooltip>
489 </div>
490 ) : null}
491 </div>
492 }
493 />
494 );
495 }
496
497 function BrowserZoomSetting({ disabled }: { readonly disabled: boolean }) {
498 const searchableSetting = useSearchableSetting();
499 const gt = useGT();
500 const zoomFactor = useClientSettings((settings) => settings.browserDefaultZoomFactor);
501 const updateSettings = useUpdateScopedSettings();
502
503 return (
504 <SettingsRow
505 {...searchableSetting("browser-default-zoom")}
506 devicePreference
507 description={gt("Page zoom applied to new browser tabs.")}
508 resetAction={
509 !disabled && zoomFactor !== DEFAULT_PREVIEW_ZOOM_FACTOR ? (
510 <SettingResetButton
511 ariaLabel={gt("Reset default browser zoom to default")}
512 onClick={() =>
513 updateSettings({ browserDefaultZoomFactor: DEFAULT_PREVIEW_ZOOM_FACTOR })
514 }
515 />
516 ) : null
517 }
518 control={
519 <Select
520 disabled={disabled}
521 value={String(zoomFactor)}
522 onValueChange={(value) => {
523 const next = PREVIEW_ZOOM_LEVELS.find((level) => String(level) === value);
524 if (next !== undefined) updateSettings({ browserDefaultZoomFactor: next });
525 }}
526 >
527 <SelectTrigger
528 size="sm"
529 className="w-full sm:w-40"
530 aria-label={gt("Default browser zoom")}
531 >
532 <SelectValue>{zoomLabel(zoomFactor)}</SelectValue>
533 </SelectTrigger>
534 <SelectPopup align="end" alignItemWithTrigger={false}>
535 {PREVIEW_ZOOM_LEVELS.map((level) => (
536 <SelectItem hideIndicator key={level} value={String(level)}>
537 {zoomLabel(level)}
538 </SelectItem>
539 ))}
540 </SelectPopup>
541 </Select>
542 }
543 />
544 );
545 }
546
547 function BrowserAppearanceSetting({ disabled }: { readonly disabled: boolean }) {
548 const searchableSetting = useSearchableSetting();
549 const gt = useGT();
550 const m = useMessages();
551 const appearance = useClientSettings((settings) => settings.browserDefaultAppearance);
552 const updateSettings = useUpdateScopedSettings();
553
554 return (
555 <SettingsRow
556 {...searchableSetting("browser-default-appearance")}
557 devicePreference
558 description={gt("The color scheme pages are told to prefer. System follows your OS setting.")}
559 resetAction={
560 !disabled && appearance !== DEFAULT_PREVIEW_APPEARANCE ? (
561 <SettingResetButton
562 ariaLabel={gt("Reset default browser appearance to default")}
563 onClick={() => updateSettings({ browserDefaultAppearance: DEFAULT_PREVIEW_APPEARANCE })}
564 />
565 ) : null
566 }
567 control={
568 <Select
569 disabled={disabled}
570 value={appearance}
571 onValueChange={(value) => {
572 if (value === "system" || value === "light" || value === "dark") {
573 updateSettings({ browserDefaultAppearance: value });
574 }
575 }}
576 >
577 <SelectTrigger
578 size="sm"
579 className="w-full sm:w-40"
580 aria-label={gt("Default browser appearance")}
581 >
582 <SelectValue>{m(APPEARANCE_LABELS[appearance])}</SelectValue>
583 </SelectTrigger>
584 <SelectPopup align="end" alignItemWithTrigger={false}>
585 {Object.entries(APPEARANCE_LABELS).map(([value, label]) => (
586 <SelectItem hideIndicator key={value} value={value}>
587 {m(label)}
588 </SelectItem>
589 ))}
590 </SelectPopup>
591 </Select>
592 }
593 />
594 );
595 }
596
597 function BrowserRecordingInputSettings({ disabled }: { readonly disabled: boolean }) {
598 const searchableSetting = useSearchableSetting();
599 const gt = useGT();
600 const showKeys = useClientSettings((settings) => settings.browserRecordingShowKeyPresses);
601 const showMouse = useClientSettings((settings) => settings.browserRecordingShowMousePresses);
602 const updateSettings = useUpdateScopedSettings();
603 return (
604 <>
605 <SettingsRow
606 {...searchableSetting("browser-recording-key-presses")}
607 devicePreference
608 description={gt(
609 "Show pressed keys and shortcuts in new recordings. Password fields are excluded.",
610 )}
611 control={
612 <Switch
613 disabled={disabled}
614 checked={showKeys}
615 aria-label={gt("Show key presses in recordings")}
616 onCheckedChange={(checked) =>
617 updateSettings({ browserRecordingShowKeyPresses: Boolean(checked) })
618 }
619 />
620 }
621 />
622 <SettingsRow
623 {...searchableSetting("browser-recording-mouse-presses")}
624 devicePreference
625 description={gt("Highlight mouse presses and held buttons in new recordings.")}
626 control={
627 <Switch
628 disabled={disabled}
629 checked={showMouse}
630 aria-label={gt("Show mouse presses in recordings")}
631 onCheckedChange={(checked) =>
632 updateSettings({ browserRecordingShowMousePresses: Boolean(checked) })
633 }
634 />
635 }
636 />
637 </>
638 );
639 }
640
641 function BrowserRecordingFrameRateSetting({ disabled }: { readonly disabled: boolean }) {
642 const searchableSetting = useSearchableSetting();
643 const gt = useGT();
644 const frameRate = useClientSettings((settings) => settings.browserRecordingFrameRate);
645 const updateSettings = useUpdateScopedSettings();
646
647 return (
648 <SettingsRow
649 {...searchableSetting("browser-recording-frame-rate")}
650 devicePreference
651 description={gt("Maximum recording rate. 30 fps saves CPU and storage; 60 fps is smoother.")}
652 resetAction={
653 !disabled && frameRate !== DEFAULT_BROWSER_RECORDING_FRAME_RATE ? (
654 <SettingResetButton
655 ariaLabel={gt("Reset browser recording frame rate to default")}
656 onClick={() =>
657 updateSettings({ browserRecordingFrameRate: DEFAULT_BROWSER_RECORDING_FRAME_RATE })
658 }
659 />
660 ) : null
661 }
662 control={
663 <Select
664 disabled={disabled}
665 value={String(frameRate)}
666 onValueChange={(value) => {
667 const next = BROWSER_RECORDING_FRAME_RATES.find((rate) => String(rate) === value);
668 if (next !== undefined) {
669 updateSettings({ browserRecordingFrameRate: next });
670 }
671 }}
672 >
673 <SelectTrigger
674 size="sm"
675 className="w-full sm:w-40"
676 aria-label={gt("Browser recording frame rate")}
677 >
678 <SelectValue>{frameRate} fps</SelectValue>
679 </SelectTrigger>
680 <SelectPopup align="end" alignItemWithTrigger={false}>
681 {BROWSER_RECORDING_FRAME_RATES.map((rate) => (
682 <SelectItem hideIndicator key={rate} value={String(rate)}>
683 {rate} fps
684 </SelectItem>
685 ))}
686 </SelectPopup>
687 </Select>
688 }
689 />
690 );
691 }
692
693 const LINK_TARGET_LABELS: Readonly<Record<BrowserLinkTarget, string>> = {
694 system: msg("Your default browser"),
695 app: "T3 Code",
696 };
697
698 function BrowserLinkTargetSetting({ disabled }: { readonly disabled: boolean }) {
699 const searchableSetting = useSearchableSetting();
700 const gt = useGT();
701 const m = useMessages();
702 const linkTarget = useClientSettings((settings) => settings.browserLinkTarget);
703 const updateSettings = useUpdateScopedSettings();
704
705 return (
706 <SettingsRow
707 {...searchableSetting("browser-link-target")}
708 devicePreference
709 description={gt(
710 "Where links in the chat and terminal open. Hold ⌘ or Ctrl while clicking a link to open it in your default browser either way.",
711 )}
712 resetAction={
713 !disabled && linkTarget !== DEFAULT_BROWSER_LINK_TARGET ? (
714 <SettingResetButton
715 ariaLabel={gt("Reset link target to default")}
716 onClick={() => updateSettings({ browserLinkTarget: DEFAULT_BROWSER_LINK_TARGET })}
717 />
718 ) : null
719 }
720 control={
721 <Select
722 disabled={disabled}
723 value={linkTarget}
724 onValueChange={(value) => {
725 if (value === "system" || value === "app") {
726 updateSettings({ browserLinkTarget: value });
727 }
728 }}
729 >
730 <SelectTrigger size="sm" className="w-full sm:w-40" aria-label={gt("Open links in")}>
731 <SelectValue>{m(LINK_TARGET_LABELS[linkTarget])}</SelectValue>
732 </SelectTrigger>
733 <SelectPopup align="end" alignItemWithTrigger={false}>
734 {(Object.keys(LINK_TARGET_LABELS) as ReadonlyArray<BrowserLinkTarget>).map((target) => (
735 <SelectItem hideIndicator key={target} value={target}>
736 {m(LINK_TARGET_LABELS[target])}
737 </SelectItem>
738 ))}
739 </SelectPopup>
740 </Select>
741 }
742 />
743 );
744 }
745
746 const SEARCH_ENGINE_LABELS: Readonly<Record<BrowserSearchEngine, string>> = {
747 duckduckgo: "DuckDuckGo",
748 google: "Google",
749 bing: "Bing",
750 brave: "Brave Search",
751 kagi: "Kagi",
752 ecosia: "Ecosia",
753 custom: msg("Custom", { $context: "custom search engine" }),
754 };
755
756 function BrowserSearchEngineSetting() {
757 const searchableSetting = useSearchableSetting();
758 const gt = useGT();
759 const m = useMessages();
760 const engine = useClientSettings((settings) => settings.browserSearchEngine);
761 const customUrl = useClientSettings((settings) => settings.browserCustomSearchUrl);
762 const updateSettings = useUpdateScopedSettings();
763
764 return (
765 <>
766 <SettingsRow
767 {...searchableSetting("browser-search-engine")}
768 devicePreference
769 description={gt("What the address bar searches when you type something that isn't a URL.")}
770 resetAction={
771 engine !== DEFAULT_BROWSER_SEARCH_ENGINE || customUrl !== "" ? (
772 <SettingResetButton
773 ariaLabel={gt("Reset search engine to default")}
774 onClick={() =>
775 updateSettings({
776 browserSearchEngine: DEFAULT_BROWSER_SEARCH_ENGINE,
777 browserCustomSearchUrl: "",
778 })
779 }
780 />
781 ) : null
782 }
783 control={
784 <Select
785 value={engine}
786 onValueChange={(value) => {
787 const next = BrowserSearchEngine.literals.find((literal) => literal === value);
788 if (next !== undefined) {
789 updateSettings({ browserSearchEngine: next });
790 }
791 }}
792 >
793 <SelectTrigger size="sm" className="w-full sm:w-40" aria-label={gt("Search engine")}>
794 <SelectValue>{m(SEARCH_ENGINE_LABELS[engine])}</SelectValue>
795 </SelectTrigger>
796 <SelectPopup align="end" alignItemWithTrigger={false}>
797 {BrowserSearchEngine.literals.map((literal) => (
798 <SelectItem hideIndicator key={literal} value={literal}>
799 {m(SEARCH_ENGINE_LABELS[literal])}
800 </SelectItem>
801 ))}
802 </SelectPopup>
803 </Select>
804 }
805 />
806 {engine === "custom" ? (
807 <SettingsRow
808 title={gt("Custom search URL")}
809 devicePreference
810 description={gt("Use %s where the search terms go.")}
811 status={
812 isValidSearchUrlTemplate(customUrl)
813 ? undefined
814 : gt("Enter an http or https URL containing %s. Searches use DuckDuckGo until then.")
815 }
816 control={
817 <DraftInput
818 nativeInput
819 size="sm"
820 className="w-full sm:w-64"
821 aria-label={gt("Custom search URL")}
822 placeholder="https://example.com/search?q=%s"
823 autoCapitalize="none"
824 spellCheck={false}
825 maxLength={BROWSER_CUSTOM_SEARCH_URL_MAX_LENGTH}
826 value={customUrl}
827 onCommit={(next) => updateSettings({ browserCustomSearchUrl: next.trim() })}
828 />
829 }
830 />
831 ) : null}
832 </>
833 );
834 }
835
836 export function PullRequestLinksOpenInAppSetting() {
837 const searchableSetting = useSearchableSetting();
838 const gt = useGT();
839 const openInApp = useClientSettings((settings) => settings.pullRequestLinksOpenInApp);
840 const updateSettings = useUpdatePrimarySettings();
841
842 return (
843 <SettingsRow
844 {...searchableSetting("pull-request-links-open-in-app")}
845 description={gt(
846 "Clicking a pull request link opens it in T3 Code. Turn off to open pull request links like any other link, on your git host.",
847 )}
848 resetAction={
849 openInApp ? null : (
850 <SettingResetButton
851 ariaLabel={gt("Reset open pull requests in T3 Code to default")}
852 onClick={() => updateSettings({ pullRequestLinksOpenInApp: true })}
853 />
854 )
855 }
856 control={
857 <Switch
858 checked={openInApp}
859 onCheckedChange={(checked) =>
860 updateSettings({ pullRequestLinksOpenInApp: Boolean(checked) })
861 }
862 aria-label={gt("Open pull requests in T3 Code")}
863 />
864 }
865 />
866 );
867 }
868
869 function DeviceIntegrationSettings() {
870 const gt = useGT();
871 const { search, environment: selected } = useSettingsScope();
872 const settings = useScopedSettings();
873 const connected = selected?.connection.phase === "connected" && selected.serverConfig !== null;
874 const environmentId = connected ? selected.environmentId : null;
875
876 const { state } = useDeviceState(environmentId);
877
878 return (
879 <>
880 <SettingsSection id="devices" title={gt("Devices")}>
881 <DeviceIntegrationControls
882 key={`${environmentId}:${JSON.stringify(search)}`}
883 environmentId={environmentId}
884 enabled={settings.enableDeviceSupport}
885 agentAccessEnabled={settings.enableAgentDeviceAccess}
886 />
887 </SettingsSection>
888 <DeviceSourcesSettings
889 supportsEas={state.supportsEasHosts === true}
890 supportsSimlock={state.supportsSimlockHosts === true}
891 />
892 </>
893 );
894 }
895
896 function DeviceIntegrationControls({
897 environmentId,
898 enabled,
899 agentAccessEnabled,
900 }: {
901 environmentId: EnvironmentId | null;
902 enabled: boolean;
903 agentAccessEnabled: boolean;
904 }) {
905 const searchableSetting = useSearchableSetting();
906 const gt = useGT();
907 const canConfigure = useEnvironmentScope(environmentId, AuthSettingsWriteScope);
908 const { state, loaded } = useDeviceState(environmentId);
909 const { scope, environments, connectedEnvironments } = useSettingsScope();
910 const updateSettings = useUpdateScopedSettings();
911 const projectScope = scope.kind === "project" || scope.kind === "checkout";
912 const anyHubEnabled = connectedEnvironments.some(
913 (environment) => environment.serverConfig?.settings.enableDeviceSupport,
914 );
915 const configure = useAtomCommand(deviceEnvironment.configure, { reportFailure: false });
916 const list = useAtomCommand(deviceEnvironment.list, { reportFailure: false });
917 const [pending, setPending] = useState<
918 "hub" | "check" | "agent" | "update-hub" | "update-agent" | null
919 >(null);
920 const { busy } = deviceHubReadiness(state);
921
922 const update = async (
923 kind: NonNullable<typeof pending>,
924 input: { enabled?: boolean; agentAccessEnabled?: boolean },
925 ) => {
926 if (!environmentId || !readEnvironmentScope(environmentId, AuthSettingsWriteScope)) return;
927 setPending(kind);
928 const results = await Promise.allSettled(
929 environments.map(async (environment) => {
930 if (environment.connection.phase !== "connected" || !environment.serverConfig) {
931 throw new Error("Environment disconnected");
932 }
933 if (!readEnvironmentScope(environment.environmentId, AuthSettingsWriteScope)) {
934 throw new Error("This connection cannot change device settings.");
935 }
936 return configure({
937 environmentId: environment.environmentId,
938 input: { ...input, ...(input.enabled ? { onboardingCompleted: true } : {}) },
939 });
940 }),
941 );
942 setPending(null);
943 const failed = environments.filter((_, index) => {
944 const result = results[index];
945 return result?.status !== "fulfilled" || result.value._tag === "Failure";
946 });
947 if (failed.length > 0) {
948 toastManager.add({
949 type: "error",
950 title: gt("Device settings not saved on all environments"),
951 description: gt("Could not update {environments}.", {
952 environments: failed.map((environment) => environment.label).join(", "),
953 }),
954 });
955 }
956 };
957
958 const [updateError, setUpdateError] = useState<{ tool: "hub" | "agent"; message: string } | null>(
959 null,
960 );
961 const localTools = state.hosts.find((host) => host.kind === "local")?.tools;
962 const versionActions = (tool: "hub" | "agent") => {
963 const version = localTools?.[tool];
964 const needsUpdate = version && !version.installedVersions.includes(version.requiredVersion);
965 return (
966 <div className="space-y-2">
967 <div className="flex flex-wrap gap-2">
968 {state.supportsToolUpdate && needsUpdate ? (
969 <Button
970 size="sm"
971 disabled={!environmentId || pending !== null || busy}
972 onClick={() => {
973 if (!environmentId) return;
974 setUpdateError(null);
975 setPending(`update-${tool}`);
976 void list({ environmentId, input: { updateTool: tool } })
977 .then((result) => {
978 if (result._tag === "Failure")
979 setUpdateError({ tool, message: formatEnvironmentQueryError(result.cause) });
980 })
981 .finally(() => setPending(null));
982 }}
983 >
984 {pending === `update-${tool}` ? gt("Updating…") : gt("Update", { $context: "verb" })}
985 </Button>
986 ) : null}
987 {state.supportsToolInspection ? (
988 <Button
989 size="sm"
990 variant="outline"
991 disabled={!environmentId || pending !== null || busy}
992 onClick={() => {
993 if (!environmentId) return;
994 setPending("check");
995 void list({ environmentId, input: { inspectOnly: true } }).finally(() =>
996 setPending(null),
997 );
998 }}
999 >
1000 {pending === "check" ? gt("Checking…") : gt("Check versions")}
1001 </Button>
1002 ) : null}
1003 </div>
1004 {updateError?.tool === tool ? (
1005 <p role="alert" className="text-xs text-destructive">
1006 {updateError.message}
1007 </p>
1008 ) : null}
1009 </div>
1010 );
1011 };
1012
1013 return (
1014 <>
1015 <SettingsRow
1016 {...searchableSetting("device-hub")}
1017 serverScoped
1018 settingKeys={["enableDeviceSupport"]}
1019 description={
1020 <T>
1021 Open simulators and emulators in the Device panel. Hub:{" "}
1022 <DeviceToolVersions
1023 action={versionActions("hub")}
1024 kind="hub"
1025 tools={state.hosts.find((host) => host.kind === "local")?.tools}
1026 />
1027 </T>
1028 }
1029 control={
1030 <>
1031 {pending === "hub" ? <DeviceHubSetupStatus state={state} pending compact /> : null}
1032 <ScopedSwitch
1033 settingKeys={["enableDeviceSupport"]}
1034 checked={enabled}
1035 disabled={
1036 !canConfigure ||
1037 projectScope ||
1038 !loaded ||
1039 !environmentId ||
1040 busy ||
1041 pending !== null
1042 }
1043 aria-label={gt("Device hub")}
1044 onCheckedChange={(checked) =>
1045 void update("hub", {
1046 enabled: Boolean(checked),
1047 ...(checked ? {} : { agentAccessEnabled: false }),
1048 })
1049 }
1050 />
1051 </>
1052 }
1053 />
1054 <SettingsRow
1055 {...searchableSetting("agent-device-access")}
1056 serverScoped
1057 settingKeys={["enableAgentDeviceAccess"]}
1058 description={
1059 <T>
1060 New agent sessions can open and drive these devices. agent-device:{" "}
1061 <DeviceToolVersions
1062 action={versionActions("agent")}
1063 kind="agent"
1064 tools={state.hosts.find((host) => host.kind === "local")?.tools}
1065 />
1066 </T>
1067 }
1068 control={
1069 <>
1070 {pending === "agent" ? <AgentDeviceSetupStatus state={state} pending compact /> : null}
1071 <ScopedSwitch
1072 settingKeys={["enableAgentDeviceAccess"]}
1073 checked={agentAccessEnabled}
1074 disabled={
1075 !canConfigure ||
1076 connectedEnvironments.length === 0 ||
1077 (!projectScope && (!loaded || !anyHubEnabled || busy)) ||
1078 pending !== null
1079 }
1080 aria-label={gt("Agent device access")}
1081 onCheckedChange={(checked) =>
1082 projectScope
1083 ? updateSettings({ enableAgentDeviceAccess: Boolean(checked) })
1084 : void update("agent", { agentAccessEnabled: Boolean(checked) })
1085 }
1086 />
1087 </>
1088 }
1089 />
1090 {environmentId ? (
1091 <DeviceHostUpdates
1092 state={{ ...state, hosts: state.hosts.filter((host) => host.kind === "local") }}
1093 environmentId={environmentId}
1094 />
1095 ) : null}
1096 </>
1097 );
1098 }
1099
1100 function AgentBrowserAccessSetting() {
1101 const searchableSetting = useSearchableSetting();
1102 const gt = useGT();
1103 const { scope } = useSettingsScope();
1104 const settings = useScopedSettings();
1105 const updateSettings = useUpdateScopedSettings();
1106 const isProjectScope = scope.kind === "project" || scope.kind === "checkout";
1107
1108 return (
1109 <SettingsRow
1110 serverScoped
1111 settingKeys={["enableAgentBrowserAccess"]}
1112 {...searchableSetting("agent-browser-access")}
1113 description={
1114 isProjectScope
1115 ? gt(
1116 "Allow agents in this project to use the shared browser. Applies when the agent session next starts.",
1117 )
1118 : gt("Allow agents to use the shared browser. Projects can override it.")
1119 }
1120 resetAction={
1121 settings.enableAgentBrowserAccess !== DEFAULT_SERVER_SETTINGS.enableAgentBrowserAccess ? (
1122 <SettingResetButton
1123 ariaLabel={gt("Reset default browser access to default")}
1124 onClick={() =>
1125 updateSettings({
1126 enableAgentBrowserAccess: DEFAULT_SERVER_SETTINGS.enableAgentBrowserAccess,
1127 })
1128 }
1129 />
1130 ) : null
1131 }
1132 control={
1133 <ScopedSwitch
1134 settingKeys={["enableAgentBrowserAccess"]}
1135 aria-label={gt("Agent browser access")}
1136 checked={settings.enableAgentBrowserAccess}
1137 onCheckedChange={(enabled) => updateSettings({ enableAgentBrowserAccess: enabled })}
1138 />
1139 }
1140 />
1141 );
1142 }
1143
1144 function BrowserAutoShowFloatingPreviewSetting({ disabled }: { readonly disabled: boolean }) {
1145 const searchableSetting = useSearchableSetting();
1146 const gt = useGT();
1147 const autoShow = useClientSettings((settings) => settings.browserAutoShowFloatingPreview);
1148 const updateSettings = useUpdateScopedSettings();
1149
1150 return (
1151 <SettingsRow
1152 {...searchableSetting("browser-auto-show-floating-preview")}
1153 devicePreference
1154 description={gt(
1155 "Show the floating preview when an agent opens a browser or device unless the agent says otherwise.",
1156 )}
1157 resetAction={
1158 !disabled && autoShow !== DEFAULT_BROWSER_AUTO_SHOW_FLOATING_PREVIEW ? (
1159 <SettingResetButton
1160 ariaLabel={gt("Reset auto-show floating preview to default")}
1161 onClick={() =>
1162 updateSettings({
1163 browserAutoShowFloatingPreview: DEFAULT_BROWSER_AUTO_SHOW_FLOATING_PREVIEW,
1164 })
1165 }
1166 />
1167 ) : null
1168 }
1169 control={
1170 <Switch
1171 disabled={disabled}
1172 checked={autoShow}
1173 onCheckedChange={(checked) =>
1174 updateSettings({ browserAutoShowFloatingPreview: Boolean(checked) })
1175 }
1176 aria-label={gt("Auto-show floating preview")}
1177 />
1178 }
1179 />
1180 );
1181 }
1182
1183 function BrowserProfilesSetting({ disabled }: { readonly disabled: boolean }) {
1184 const searchableSetting = useSearchableSetting();
1185 const gt = useGT();
1186 const userProfiles = useClientSettings((settings) => settings.browserProfiles);
1187 const defaultProfileId = useClientSettings((settings) => settings.browserDefaultProfileId);
1188 const settingsHydrated = useClientSettingsHydrated();
1189 // Profile edits pair with profile data on disk, so they save for this device in every scope.
1190 const updateSettings = useUpdatePrimarySettings();
1191 const updateDefaultProfile = useUpdateScopedSettings();
1192 const { scope } = useSettingsScope();
1193 // The default profile is a device preference, which a project cannot override.
1194 const defaultProfileReadOnly = scope.kind === "project" || scope.kind === "checkout";
1195 const { environments, isReady: environmentsReady } = useEnvironments();
1196 const primaryEnvironment = usePrimaryEnvironment();
1197 // Cookie import runs on this desktop, whose policy the primary environment reports.
1198 const messages = useMessages();
1199 const cookieImportDenial = managedCapabilityDenial(
1200 usePrimaryManagedPolicy(),
1201 "browserCookieImport",
1202 messages,
1203 );
1204 const [sources, setSources] = useState<ReadonlyArray<BrowserImportSource> | null>(null);
1205 const [importSession, setImportSession] = useState<{
1206 readonly source: BrowserImportSource;
1207 readonly environmentId: EnvironmentId;
1208 readonly environmentName: string;
1209 } | null>(null);
1210 const [profilePendingRemoval, setProfilePendingRemoval] = useState<BrowserProfile | null>(null);
1211 const [profilePendingClear, setProfilePendingClear] = useState<BrowserProfile | null>(null);
1212 const [profileRemovalError, setProfileRemovalError] = useState<string | null>(null);
1213 const [profileRemovalInFlight, setProfileRemovalInFlight] = useState(false);
1214 const serverConfigs = useServerConfigs();
1215 const runClearServerProfile = useAtomCommand(previewEnvironment.clearProfile, {
1216 reportFailure: false,
1217 });
1218 const serverProfileData: ServerProfileData = {
1219 environmentIds: environments
1220 .map((environment) => environment.environmentId)
1221 .filter(
1222 (environmentId) =>
1223 serverConfigs.get(environmentId)?.environment.capabilities.serverBrowser === true,
1224 ),
1225 clear: async (environmentId, profileId) => {
1226 const result = await runClearServerProfile({ environmentId, input: { profileId } });
1227 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
1228 },
1229 };
1230 const removalAvailable = browserProfileRemovalAvailable(
1231 previewBridge !== null,
1232 environmentsReady,
1233 environments.length,
1234 serverProfileData.environmentIds.length,
1235 );
1236 const importInFlightRef = useRef(false);
1237 const [importInFlight, setImportInFlight] = useState(false);
1238 const profileWritesDisabled = disabled || !settingsHydrated;
1239
1240 const profiles = resolveBrowserProfiles(userProfiles);
1241 const listedProfiles = profiles.filter((profile) => profile.kind !== "incognito");
1242 const resolvedDefaultId =
1243 findBrowserProfile(listedProfiles, defaultProfileId)?.id ?? DEFAULT_BROWSER_PROFILE_ID;
1244
1245 const createProfile = (baseName: string) => {
1246 if (!settingsHydrated || importInFlightRef.current) return undefined;
1247 const currentProfiles = getClientSettings().browserProfiles;
1248 // Check live settings; repeated clicks before render can bypass the disabled control.
1249 if (currentProfiles.length >= BROWSER_PROFILE_MAX_COUNT) return undefined;
1250 const resolvedProfiles = resolveBrowserProfiles(currentProfiles);
1251 const taken = new Set(resolvedProfiles.map((profile) => profile.name));
1252 let name = baseName;
1253 for (let index = 2; taken.has(name); index += 1) name = `${baseName} ${index}`;
1254 const profile = { id: `profile-${randomUUID()}`, name, kind: "persistent" as const };
1255 updateSettings({ browserProfiles: [...currentProfiles, profile] });
1256 return profile;
1257 };
1258
1259 const renameProfile = (id: string, next: string) => {
1260 if (!settingsHydrated || importInFlightRef.current) return;
1261 const name = next.trim().slice(0, BROWSER_PROFILE_NAME_MAX_LENGTH);
1262 if (name === "") return;
1263 const currentProfiles = getClientSettings().browserProfiles;
1264 updateSettings({
1265 browserProfiles: currentProfiles.map((profile) =>
1266 profile.id === id ? { ...profile, name } : profile,
1267 ),
1268 });
1269 };
1270
1271 const clearProfileData = (id: string, name: string) => {
1272 if (!settingsHydrated || importInFlightRef.current) return;
1273 if (!removalAvailable) {
1274 toastManager.add({
1275 type: "error",
1276 title: gt("Could not clear {name}''s data", { name }),
1277 description: gt("You're not connected to a server yet."),
1278 });
1279 return;
1280 }
1281 void clearBrowserProfileData(
1282 previewBridge,
1283 environments.map((environment) => environment.environmentId),
1284 id,
1285 serverProfileData,
1286 )
1287 .then(() => {
1288 toastManager.add({
1289 type: "success",
1290 title: gt("Cleared {name}''s cookies and cache", { name }),
1291 });
1292 })
1293 .catch(() => {
1294 toastManager.add({ type: "error", title: gt("Could not clear {name}''s data", { name }) });
1295 });
1296 };
1297
1298 const removeProfile = async (id: string) => {
1299 if (!settingsHydrated || importInFlightRef.current) return;
1300 if (!removalAvailable) {
1301 setProfileRemovalError(gt("Connect to an environment before removing this profile."));
1302 return;
1303 }
1304 setProfileRemovalError(null);
1305 setProfileRemovalInFlight(true);
1306 try {
1307 await clearBrowserProfileData(
1308 previewBridge,
1309 environmentsReady ? environments.map((environment) => environment.environmentId) : [],
1310 id,
1311 serverProfileData,
1312 );
1313 } catch {
1314 setProfileRemovalError(gt("Profile data could not be deleted. Try again."));
1315 setProfileRemovalInFlight(false);
1316 return;
1317 }
1318 const currentSettings = getClientSettings();
1319 updateSettings({
1320 browserProfiles: currentSettings.browserProfiles.filter((profile) => profile.id !== id),
1321 ...(currentSettings.browserDefaultProfileId === id
1322 ? { browserDefaultProfileId: DEFAULT_BROWSER_PROFILE_ID }
1323 : {}),
1324 });
1325 setProfileRemovalInFlight(false);
1326 setProfilePendingRemoval(null);
1327 };
1328
1329 const importableSources = (sources ?? []).filter(
1330 (source) =>
1331 source.unavailable !== "notInstalled" && source.unavailable !== "unsupportedPlatform",
1332 );
1333
1334 const loadSources = () => {
1335 if (!previewBridge) return;
1336 void previewBridge
1337 .listBrowserImportSources()
1338 .then(setSources)
1339 .catch(() => setSources((previous) => previous ?? []));
1340 };
1341
1342 const runWizardImport = async (
1343 source: BrowserImportSource,
1344 environmentId: EnvironmentId,
1345 input: { readonly sourceProfileDirectory: string; readonly target: WizardTarget },
1346 ): Promise<ImportOutcome> => {
1347 if (!previewBridge) return { kind: "blocked", reason: "sessionUnavailable" };
1348 if (!settingsHydrated) return { kind: "blocked", reason: "sessionUnavailable" };
1349 if (
1350 input.target.kind === "existing" &&
1351 !resolveBrowserProfiles(getClientSettings().browserProfiles).some(
1352 (profile) => profile.id === input.target.profileId,
1353 )
1354 ) {
1355 return { kind: "blocked", reason: "readFailed" };
1356 }
1357 if (importInFlightRef.current) return { kind: "blocked", reason: "readFailed" };
1358 importInFlightRef.current = true;
1359 setImportInFlight(true);
1360 return importBrowserCookiesIntoTarget(previewBridge, source, environmentId, input).finally(
1361 () => {
1362 importInFlightRef.current = false;
1363 setImportInFlight(false);
1364 },
1365 );
1366 };
1367
1368 const refreshImportSource = async (
1369 sourceId: BrowserImportSource["id"],
1370 ): Promise<BrowserImportSource | undefined> => {
1371 if (!previewBridge) return undefined;
1372 try {
1373 const latest = await previewBridge.listBrowserImportSources();
1374 setSources(latest);
1375 return latest.find((source) => source.id === sourceId);
1376 } catch {
1377 return undefined;
1378 }
1379 };
1380
1381 const atProfileLimit = userProfiles.length >= BROWSER_PROFILE_MAX_COUNT;
1382
1383 return (
1384 <SettingsRow
1385 {...searchableSetting("browser-profiles")}
1386 description={gt(
1387 "Profiles separate cookies and logins. Incognito data is cleared when the app closes.",
1388 )}
1389 control={
1390 <Menu onOpenChange={(open) => open && loadSources()}>
1391 <MenuTrigger
1392 render={
1393 <Button
1394 size="sm"
1395 variant="outline"
1396 disabled={profileWritesDisabled || importInFlight}
1397 />
1398 }
1399 >
1400 <PlusIcon />
1401 <T>Add profile</T>
1402 </MenuTrigger>
1403 <MenuPopup align="end">
1404 <MenuItem
1405 disabled={!settingsHydrated || atProfileLimit}
1406 onClick={() => createProfile(gt("New profile"))}
1407 >
1408 <T>Blank profile</T>
1409 </MenuItem>
1410 {atProfileLimit ? (
1411 <MenuItem disabled>
1412 <T>You&rsquo;ve reached the profile limit</T>
1413 </MenuItem>
1414 ) : null}
1415 <MenuSeparator />
1416 <MenuGroup>
1417 <MenuGroupLabel>
1418 <T>Import from</T>
1419 </MenuGroupLabel>
1420 {cookieImportDenial !== undefined ? (
1421 <MenuItem disabled>{cookieImportDenial}</MenuItem>
1422 ) : sources === null ? (
1423 <MenuItem disabled>
1424 <T>Looking for browsers…</T>
1425 </MenuItem>
1426 ) : importableSources.length === 0 ? (
1427 <MenuItem disabled>
1428 <T>No supported browsers found</T>
1429 </MenuItem>
1430 ) : (
1431 <>
1432 {importableSources.map((source) => (
1433 <MenuItem
1434 key={source.id}
1435 disabled={!settingsHydrated || primaryEnvironment == null}
1436 onClick={() => {
1437 if (!settingsHydrated || primaryEnvironment == null) return;
1438 setImportSession({
1439 source,
1440 environmentId: primaryEnvironment.environmentId,
1441 environmentName: resolveEnvironmentOptionLabel({
1442 isPrimary: true,
1443 environmentId: primaryEnvironment.environmentId,
1444 runtimeLabel: primaryEnvironment.label,
1445 }),
1446 });
1447 }}
1448 >
1449 {source.name}
1450 </MenuItem>
1451 ))}
1452 {primaryEnvironment == null ? (
1453 <MenuItem disabled>
1454 <T>Connect to an environment to import cookies</T>
1455 </MenuItem>
1456 ) : null}
1457 </>
1458 )}
1459 </MenuGroup>
1460 </MenuPopup>
1461 </Menu>
1462 }
1463 >
1464 <div className="mt-2 mb-2 overflow-hidden rounded-lg border border-border/60">
1465 {listedProfiles.map((profile, index) => {
1466 const builtIn = isBuiltInBrowserProfileId(profile.id);
1467 const isDefault = profile.id === resolvedDefaultId;
1468 return (
1469 <div
1470 key={profile.id}
1471 className={cn(
1472 "flex items-center gap-3 px-3 py-2",
1473 index > 0 && "border-t border-border/60",
1474 )}
1475 >
1476 <span className="flex min-w-0 flex-1 items-center gap-2">
1477 {builtIn ? (
1478 <span
1479 className={cn(
1480 "truncate text-sm text-foreground",
1481 profileWritesDisabled && "opacity-64",
1482 )}
1483 >
1484 {profile.name}
1485 </span>
1486 ) : (
1487 <DraftInput
1488 nativeInput
1489 size="sm"
1490 className="w-full max-w-56"
1491 aria-label={gt("Rename {name}", { name: profile.name })}
1492 disabled={profileWritesDisabled || importInFlight}
1493 maxLength={BROWSER_PROFILE_NAME_MAX_LENGTH}
1494 value={profile.name}
1495 onCommit={(next) => renameProfile(profile.id, next)}
1496 />
1497 )}
1498 {isDefault ? (
1499 <span className={cn("flex", profileWritesDisabled && "opacity-64")}>
1500 <Badge>{gt("Default", { $context: "default browser profile badge" })}</Badge>
1501 </span>
1502 ) : null}
1503 </span>
1504 <Menu>
1505 <MenuTrigger
1506 render={
1507 <Button
1508 size="icon-xs"
1509 variant="ghost-muted"
1510 disabled={profileWritesDisabled || importInFlight}
1511 aria-label={gt("{name} options", { name: profile.name })}
1512 />
1513 }
1514 >
1515 <MoreVertical />
1516 </MenuTrigger>
1517 <MenuPopup align="end">
1518 <MenuItem
1519 disabled={!settingsHydrated || isDefault || defaultProfileReadOnly}
1520 onClick={() => {
1521 if (settingsHydrated) {
1522 updateDefaultProfile({ browserDefaultProfileId: profile.id });
1523 }
1524 }}
1525 >
1526 <T>Set as default</T>
1527 </MenuItem>
1528 <MenuItem
1529 disabled={!settingsHydrated || !removalAvailable}
1530 onClick={() => {
1531 if (serverProfileData.environmentIds.length > 0) {
1532 setProfilePendingClear(profile);
1533 } else clearProfileData(profile.id, profile.name);
1534 }}
1535 >
1536 <T>Clear cookies and cache</T>
1537 </MenuItem>
1538 {builtIn ? null : (
1539 <MenuItem
1540 variant="destructive"
1541 disabled={!settingsHydrated || !removalAvailable}
1542 onClick={() => {
1543 if (settingsHydrated) setProfilePendingRemoval(profile);
1544 }}
1545 >
1546 <T>Remove profile and data</T>
1547 </MenuItem>
1548 )}
1549 {!removalAvailable ? (
1550 <>
1551 <MenuSeparator />
1552 <MenuItem disabled>
1553 {environmentsReady
1554 ? gt("Connect to an environment to clear profile data")
1555 : gt("Checking environments…")}
1556 </MenuItem>
1557 </>
1558 ) : null}
1559 </MenuPopup>
1560 </Menu>
1561 </div>
1562 );
1563 })}
1564 </div>
1565 <AlertDialog
1566 open={profilePendingRemoval !== null}
1567 onOpenChange={(open) => {
1568 if (!open && !profileRemovalInFlight) {
1569 setProfilePendingRemoval(null);
1570 setProfileRemovalError(null);
1571 }
1572 }}
1573 >
1574 <AlertDialogPopup>
1575 <AlertDialogHeader>
1576 <AlertDialogTitle>
1577 <T>
1578 Remove “<Var>{profilePendingRemoval?.name}</Var>”?
1579 </T>
1580 </AlertDialogTitle>
1581 <AlertDialogDescription>
1582 <T>
1583 Its cookies and logins are deleted. Desktop tabs already open in this profile stay
1584 open until you close them; server browser tabs close now.
1585 </T>
1586 </AlertDialogDescription>
1587 {profileRemovalError ? (
1588 <p aria-live="polite" className="text-sm text-destructive">
1589 {profileRemovalError}
1590 </p>
1591 ) : null}
1592 {!removalAvailable ? (
1593 <p className="text-sm text-muted-foreground">
1594 <T>Connect to an environment to remove this profile and its data.</T>
1595 </p>
1596 ) : null}
1597 </AlertDialogHeader>
1598 <AlertDialogFooter>
1599 <AlertDialogClose
1600 disabled={profileRemovalInFlight}
1601 render={<Button variant="outline" disabled={profileRemovalInFlight} />}
1602 >
1603 <T>Cancel</T>
1604 </AlertDialogClose>
1605 <Button
1606 variant="destructive"
1607 disabled={profileRemovalInFlight || !settingsHydrated || !removalAvailable}
1608 onClick={() => {
1609 if (profilePendingRemoval && settingsHydrated && removalAvailable) {
1610 void removeProfile(profilePendingRemoval.id);
1611 }
1612 }}
1613 >
1614 {profileRemovalInFlight ? gt("Removing…") : gt("Remove profile")}
1615 </Button>
1616 </AlertDialogFooter>
1617 </AlertDialogPopup>
1618 </AlertDialog>
1619 <AlertDialog
1620 open={profilePendingClear !== null}
1621 onOpenChange={(open) => {
1622 if (!open) setProfilePendingClear(null);
1623 }}
1624 >
1625 <AlertDialogPopup>
1626 <AlertDialogHeader>
1627 <AlertDialogTitle>
1628 <T>
1629 Clear “<Var>{profilePendingClear?.name}</Var>”’s cookies and cache?
1630 </T>
1631 </AlertDialogTitle>
1632 <AlertDialogDescription>
1633 <T>
1634 You are signed out of its sites. Server browser tabs open in this profile close now.
1635 </T>
1636 </AlertDialogDescription>
1637 </AlertDialogHeader>
1638 <AlertDialogFooter>
1639 <AlertDialogClose render={<Button variant="outline" />}>
1640 <T>Cancel</T>
1641 </AlertDialogClose>
1642 <Button
1643 variant="destructive"
1644 onClick={() => {
1645 if (profilePendingClear)
1646 clearProfileData(profilePendingClear.id, profilePendingClear.name);
1647 setProfilePendingClear(null);
1648 }}
1649 >
1650 <T>Clear data</T>
1651 </Button>
1652 </AlertDialogFooter>
1653 </AlertDialogPopup>
1654 </AlertDialog>
1655 {importSession ? (
1656 <BrowserImportWizard
1657 source={importSession.source}
1658 destinationEnvironmentName={importSession.environmentName}
1659 targetProfiles={listedProfiles.map((profile) => ({ id: profile.id, name: profile.name }))}
1660 canCreateProfile={settingsHydrated && !atProfileLimit}
1661 onImport={(input) =>
1662 runWizardImport(importSession.source, importSession.environmentId, input)
1663 }
1664 onRefreshSource={() => refreshImportSource(importSession.source.id)}
1665 onCheckFullDiskAccess={
1666 window.desktopBridge
1667 ? () => window.desktopBridge!.checkSystemPermission("full-disk-access")
1668 : undefined
1669 }
1670 onOpenFullDiskAccessSettings={async () => {
1671 await readLocalApi()
1672 ?.shell.openSystemSettings("full-disk-access")
1673 .catch(() => {
1674 toastManager.add({
1675 type: "error",
1676 title: gt("Could not open System Settings"),
1677 description: gt("Open Privacy & Security → Full Disk Access manually."),
1678 });
1679 });
1680 }}
1681 onClose={() => setImportSession(null)}
1682 />
1683 ) : null}
1684 </SettingsRow>
1685 );
1686 }
1687
1688 export function BrowserSettingsPanel() {
1689 const searchableSetting = useSearchableSetting();
1690 const gt = useGT();
1691 const desktopOnly = !isElectron;
1692 const desktopOnlyMessage = desktopOnly ? gt("Only available in the desktop app.") : undefined;
1693
1694 return (
1695 <SettingsPageContainer>
1696 <SettingsSection id="browser-agent-access" title={gt("Agent access")}>
1697 <AgentBrowserAccessSetting />
1698 </SettingsSection>
1699 <SettingsSection id="browser" title={gt("Browsing")}>
1700 <SettingsUnavailableGroup message={desktopOnlyMessage}>
1701 <BrowserProfilesSetting disabled={desktopOnly} />
1702 <BrowserLinkTargetSetting disabled={desktopOnly} />
1703 <BrowserAutoShowFloatingPreviewSetting disabled={desktopOnly} />
1704 </SettingsUnavailableGroup>
1705 {/* Not desktop-only: web clients search from server-run browser tabs too. */}
1706 <BrowserSearchEngineSetting />
1707 <AdvancedSettings
1708 targetIds={[
1709 searchableSetting("browser-default-viewport").id,
1710 searchableSetting("browser-default-zoom").id,
1711 searchableSetting("browser-default-appearance").id,
1712 ]}
1713 >
1714 <SettingsUnavailableGroup message={desktopOnlyMessage}>
1715 <BrowserViewportSetting disabled={desktopOnly} />
1716 <BrowserZoomSetting disabled={desktopOnly} />
1717 <BrowserAppearanceSetting disabled={desktopOnly} />
1718 </SettingsUnavailableGroup>
1719 </AdvancedSettings>
1720 </SettingsSection>
1721 <SettingsSection id="browser-recordings" title={gt("Recordings")}>
1722 <SettingsUnavailableGroup message={desktopOnlyMessage}>
1723 <BrowserRecordingFrameRateSetting disabled={desktopOnly} />
1724 <BrowserRecordingInputSettings disabled={desktopOnly} />
1725 </SettingsUnavailableGroup>
1726 </SettingsSection>
1727 </SettingsPageContainer>
1728 );
1729 }
1730
1731 export function DevicesSettingsPanel() {
1732 return (
1733 <SettingsPageContainer>
1734 <DeviceIntegrationSettings />
1735 </SettingsPageContainer>
1736 );
1737 }