Open History to see the last commit
1/**
2 * Integrations settings - preferences for surfaces T3 Code embeds rather than
3 * owns. Browser is the first section: the defaults a preview tab opens at,
4 * applied to both hand-opened tabs and agent `preview_open` calls that don't
5 * state their own size.
6 *
7 * @module IntegrationsSettings
8 */
9import {
10 BrowserImportFailureReason,
11 BROWSER_PROFILE_MAX_COUNT,
12 type BrowserLinkTarget,
13 type BrowserProfile,
14 type EnvironmentId,
15 BROWSER_PROFILE_NAME_MAX_LENGTH,
16 BROWSER_RECORDING_FRAME_RATES,
17 DEFAULT_BROWSER_AUTO_SHOW_FLOATING_PREVIEW,
18 DEFAULT_BROWSER_PROFILE_ID,
19 DEFAULT_BROWSER_LINK_TARGET,
20 DEFAULT_BROWSER_RECORDING_FRAME_RATE,
21 DEFAULT_BROWSER_VIEWPORT,
22 DEFAULT_PREVIEW_APPEARANCE,
23 DEFAULT_UNIFIED_SETTINGS,
24 DEFAULT_PREVIEW_ZOOM_FACTOR,
25 FILL_PREVIEW_VIEWPORT,
26 PREVIEW_VIEWPORT_MAX_AREA,
27 PREVIEW_VIEWPORT_MAX_DIMENSION,
28 PREVIEW_VIEWPORT_MIN_DIMENSION,
29 PREVIEW_ZOOM_LEVELS,
30 findBrowserProfile,
31 isBuiltInBrowserProfileId,
32 resolveBrowserProfiles,
33 type BrowserImportSource,
34 type PreviewAppearancePreference,
35 type PreviewViewportSetting,
36} from "@t3tools/contracts";
37import { PREVIEW_VIEWPORT_PRESETS } from "@t3tools/shared/previewViewport";
38import { InfoIcon, MoreVertical, Plus as PlusIcon } from "lucide-react";
39import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";
40
41import { ScreenRotationIcon } from "~/browser/ScreenRotationIcon";
42import { resolveEnvironmentOptionLabel } from "~/components/BranchToolbar.logic";
43import { previewBridge } from "~/components/preview/previewBridge";
44import { cn, randomUUID } from "~/lib/utils";
45import { useEnvironments, usePrimaryEnvironment } from "~/state/environments";
46import { isElectron } from "../../env";
47
48import { Badge } from "../ui/badge";
49import {
50 Menu,
51 MenuGroup,
52 MenuGroupLabel,
53 MenuItem,
54 MenuPopup,
55 MenuSeparator,
56 MenuTrigger,
57} from "../ui/menu";
58import { readLocalApi } from "~/localApi";
59
60import { toastManager } from "../ui/toast";
61import {
62 AlertDialog,
63 AlertDialogClose,
64 AlertDialogDescription,
65 AlertDialogFooter,
66 AlertDialogHeader,
67 AlertDialogPopup,
68 AlertDialogTitle,
69} from "../ui/alert-dialog";
70import { Button } from "../ui/button";
71import { DraftInput } from "../ui/draft-input";
72import { NumberField, NumberFieldGroup, NumberFieldInput } from "../ui/number-field";
73import {
74 Select,
75 SelectGroup,
76 SelectGroupLabel,
77 SelectItem,
78 SelectPopup,
79 SelectTrigger,
80 SelectValue,
81} from "../ui/select";
82import { Switch } from "../ui/switch";
83import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
84import {
85 getClientSettings,
86 persistClientSettingsUpdate,
87 useClientSettings,
88 useClientSettingsHydrated,
89 usePrimarySettings,
90 useUpdatePrimarySettings,
91} from "~/hooks/useSettings";
92
93import {
94 SettingResetButton,
95 SettingsPageContainer,
96 SettingsRow,
97 SettingsSection,
98} from "./settingsLayout";
99import { searchableSetting } from "./settingsSearch";
100import { BrowserImportWizard, type WizardTarget } from "./BrowserImportWizard";
101import type { ImportOutcome } from "./browserImportWizard.logic";
102
103const FILL_VALUE = "fill";
104const RESPONSIVE_VALUE = "responsive";
105
106type BrowserProfileDataBridge = Pick<
107 NonNullable<typeof previewBridge>,
108 "clearCookies" | "clearCache"
109>;
110
111export async function clearBrowserProfileData(
112 bridge: BrowserProfileDataBridge | null,
113 environmentIds: ReadonlyArray<EnvironmentId>,
114 profileId: string,
115): Promise<void> {
116 if (bridge === null || environmentIds.length === 0) {
117 throw new Error("Browser profile data is not available to clear.");
118 }
119 await Promise.all(
120 environmentIds.flatMap((environmentId) => [
121 bridge.clearCookies(environmentId, profileId),
122 bridge.clearCache(environmentId, profileId),
123 ]),
124 );
125}
126
127export function browserProfileRemovalAvailable(
128 bridgeAvailable: boolean,
129 environmentsReady: boolean,
130 environmentCount: number,
131): boolean {
132 return bridgeAvailable && environmentsReady && environmentCount > 0;
133}
134
135/**
136 * The size a "Responsive" default falls back to when the user switches away
137 * from Fill and hasn't typed dimensions yet. Fill has no dimensions to carry
138 * over, so the picker needs something concrete to seed the inputs with.
139 */
140const RESPONSIVE_SEED_SIZE = { width: 1280, height: 800 } as const;
141
142const NO_GROUPING: Intl.NumberFormatOptions = { useGrouping: false };
143
144const APPEARANCE_LABELS: Readonly<Record<PreviewAppearancePreference, string>> = {
145 system: "System",
146 light: "Light",
147 dark: "Dark",
148};
149
150const zoomLabel = (zoomFactor: number) => `${Math.round(zoomFactor * 100)}%`;
151
152/**
153 * IPC flattens the failure to its message, so the reason token travels inside
154 * it. Anything unrecognised reads as a plain read failure rather than leaking
155 * the raw message into a toast.
156 */
157/** Thrown from the post-import settings updater when the cap was hit meanwhile. */
158class ProfileLimitReachedError extends Error {
159 constructor() {
160 super("Browser profile limit reached.");
161 this.name = "ProfileLimitReachedError";
162 }
163}
164
165export const importFailureReason = (cause: unknown): BrowserImportFailureReason => {
166 const message = String((cause as { message?: unknown } | undefined)?.message ?? "");
167 return (
168 BrowserImportFailureReason.literals.find((reason) => message.includes(`failed: ${reason}.`)) ??
169 "readFailed"
170 );
171};
172
173const viewportSelectValue = (viewport: PreviewViewportSetting): string => {
174 if (viewport._tag === "fill") return FILL_VALUE;
175 if (
176 viewport._tag === "preset" &&
177 PREVIEW_VIEWPORT_PRESETS.some((preset) => preset.id === viewport.presetId)
178 ) {
179 return viewport.presetId;
180 }
181 return RESPONSIVE_VALUE;
182};
183
184/**
185 * The trigger renders this rather than a bare `SelectValue`, which would fall
186 * back to printing the raw stored value ("fill") because the options are built
187 * inline instead of from an `items` map.
188 */
189const viewportSelectLabel = (viewport: PreviewViewportSetting): string => {
190 const value = viewportSelectValue(viewport);
191 if (value === FILL_VALUE) return "Fill panel";
192 if (value === RESPONSIVE_VALUE) return "Responsive";
193 return PREVIEW_VIEWPORT_PRESETS.find((preset) => preset.id === value)?.label ?? "Responsive";
194};
195
196const isValidDimension = (value: number) =>
197 Number.isInteger(value) &&
198 value >= PREVIEW_VIEWPORT_MIN_DIMENSION &&
199 value <= PREVIEW_VIEWPORT_MAX_DIMENSION;
200
201/**
202 * A sized viewport with width and height swapped. Presets keep their identity
203 * through a rotation — `resolvePreviewViewport` already stores rotated presets
204 * as the preset id plus swapped dimensions — so a rotated iPad is still an
205 * iPad, not an anonymous custom size.
206 */
207const rotateViewport = (
208 viewport: Exclude<PreviewViewportSetting, { readonly _tag: "fill" }>,
209): PreviewViewportSetting => ({
210 ...viewport,
211 width: viewport.height,
212 height: viewport.width,
213});
214
215function BrowserViewportSetting({ disabled }: { readonly disabled: boolean }) {
216 const viewport = useClientSettings((settings) => settings.browserDefaultViewport);
217 const updateSettings = useUpdatePrimarySettings();
218
219 const sized = viewport._tag === "fill" ? null : viewport;
220 const presentedSize = {
221 width: sized?.width ?? RESPONSIVE_SEED_SIZE.width,
222 height: sized?.height ?? RESPONSIVE_SEED_SIZE.height,
223 };
224
225 const selectViewport = (value: string | null) => {
226 if (value === FILL_VALUE) {
227 updateSettings({ browserDefaultViewport: FILL_PREVIEW_VIEWPORT });
228 return;
229 }
230 if (value === RESPONSIVE_VALUE) {
231 updateSettings({
232 browserDefaultViewport: {
233 _tag: "freeform",
234 width: sized?.width ?? RESPONSIVE_SEED_SIZE.width,
235 height: sized?.height ?? RESPONSIVE_SEED_SIZE.height,
236 },
237 });
238 return;
239 }
240 const preset = PREVIEW_VIEWPORT_PRESETS.find((candidate) => candidate.id === value);
241 if (!preset) return;
242 updateSettings({
243 browserDefaultViewport: {
244 _tag: "preset",
245 width: preset.width,
246 height: preset.height,
247 presetId: preset.id,
248 },
249 });
250 };
251
252 // Committed on blur rather than per keystroke: typing "2560" passes through
253 // "256", which is a legal dimension, so an onValueChange handler would
254 // persist that intermediate size and churn the settings file on every key.
255 const commitDimension = (axis: "width" | "height", value: number | null) => {
256 if (value === null || !isValidDimension(value)) return;
257 const next = { ...presentedSize, [axis]: value };
258 if (next.width * next.height > PREVIEW_VIEWPORT_MAX_AREA) return;
259 if (sized && next.width === sized.width && next.height === sized.height) return;
260 // Typing a size means the preset no longer describes it.
261 updateSettings({ browserDefaultViewport: { _tag: "freeform", ...next } });
262 };
263
264 return (
265 <SettingsRow
266 {...searchableSetting("browser-default-viewport")}
267 description="Tab size for you and agents. Fill fits the panel; other sizes show the device toolbar."
268 resetAction={
269 !disabled && viewport._tag !== DEFAULT_BROWSER_VIEWPORT._tag ? (
270 <SettingResetButton
271 label="default browser viewport"
272 onClick={() => updateSettings({ browserDefaultViewport: DEFAULT_BROWSER_VIEWPORT })}
273 />
274 ) : null
275 }
276 control={
277 <div className="flex w-full flex-wrap items-center justify-end gap-2 sm:w-auto">
278 <Select
279 value={viewportSelectValue(viewport)}
280 onValueChange={selectViewport}
281 disabled={disabled}
282 >
283 <SelectTrigger
284 size="sm"
285 className="w-full min-w-0 sm:w-44"
286 aria-label="Default browser viewport"
287 >
288 <SelectValue>{viewportSelectLabel(viewport)}</SelectValue>
289 </SelectTrigger>
290 <SelectPopup align="end" alignItemWithTrigger={false} className="min-w-64">
291 <SelectItem value={FILL_VALUE}>Fill panel</SelectItem>
292 <SelectItem value={RESPONSIVE_VALUE}>Responsive</SelectItem>
293 <SelectGroup>
294 <SelectGroupLabel>Standard</SelectGroupLabel>
295 {PREVIEW_VIEWPORT_PRESETS.map((preset) => (
296 <SelectItem key={preset.id} value={preset.id}>
297 <span className="flex w-full items-center justify-between gap-5">
298 <span>{preset.label}</span>
299 <span className="text-xs tabular-nums text-muted-foreground">
300 {preset.detail}
301 </span>
302 </span>
303 </SelectItem>
304 ))}
305 </SelectGroup>
306 </SelectPopup>
307 </Select>
308
309 {sized ? (
310 <div className="flex min-w-0 items-center gap-1">
311 <NumberField
312 value={presentedSize.width}
313 min={PREVIEW_VIEWPORT_MIN_DIMENSION}
314 max={PREVIEW_VIEWPORT_MAX_DIMENSION}
315 disabled={disabled}
316 // Pixel counts read as raw numbers; grouping would show "1,024".
317 format={NO_GROUPING}
318 size="sm"
319 className="w-20"
320 onValueCommitted={(value) => commitDimension("width", value)}
321 >
322 <NumberFieldGroup>
323 <NumberFieldInput aria-label="Default viewport width" />
324 </NumberFieldGroup>
325 </NumberField>
326 <span className="text-xs text-muted-foreground">×</span>
327 <NumberField
328 value={presentedSize.height}
329 min={PREVIEW_VIEWPORT_MIN_DIMENSION}
330 max={PREVIEW_VIEWPORT_MAX_DIMENSION}
331 disabled={disabled}
332 format={NO_GROUPING}
333 size="sm"
334 className="w-20"
335 onValueCommitted={(value) => commitDimension("height", value)}
336 >
337 <NumberFieldGroup>
338 <NumberFieldInput aria-label="Default viewport height" />
339 </NumberFieldGroup>
340 </NumberField>
341 <Tooltip>
342 <TooltipTrigger
343 render={
344 <Button
345 size="icon-sm"
346 variant="ghost-muted"
347 disabled={disabled}
348 aria-label={`Rotate to ${
349 presentedSize.height >= presentedSize.width ? "landscape" : "portrait"
350 }`}
351 onClick={() =>
352 updateSettings({ browserDefaultViewport: rotateViewport(sized) })
353 }
354 >
355 <ScreenRotationIcon />
356 </Button>
357 }
358 />
359 <TooltipPopup side="top">Rotate</TooltipPopup>
360 </Tooltip>
361 </div>
362 ) : null}
363 </div>
364 }
365 />
366 );
367}
368
369function BrowserZoomSetting({ disabled }: { readonly disabled: boolean }) {
370 const zoomFactor = useClientSettings((settings) => settings.browserDefaultZoomFactor);
371 const updateSettings = useUpdatePrimarySettings();
372
373 return (
374 <SettingsRow
375 {...searchableSetting("browser-default-zoom")}
376 description="Page zoom applied to new browser tabs."
377 resetAction={
378 !disabled && zoomFactor !== DEFAULT_PREVIEW_ZOOM_FACTOR ? (
379 <SettingResetButton
380 label="default browser zoom"
381 onClick={() =>
382 updateSettings({ browserDefaultZoomFactor: DEFAULT_PREVIEW_ZOOM_FACTOR })
383 }
384 />
385 ) : null
386 }
387 control={
388 <Select
389 disabled={disabled}
390 value={String(zoomFactor)}
391 onValueChange={(value) => {
392 const next = PREVIEW_ZOOM_LEVELS.find((level) => String(level) === value);
393 if (next !== undefined) updateSettings({ browserDefaultZoomFactor: next });
394 }}
395 >
396 <SelectTrigger size="sm" className="w-full sm:w-40" aria-label="Default browser zoom">
397 <SelectValue>{zoomLabel(zoomFactor)}</SelectValue>
398 </SelectTrigger>
399 <SelectPopup align="end" alignItemWithTrigger={false}>
400 {PREVIEW_ZOOM_LEVELS.map((level) => (
401 <SelectItem hideIndicator key={level} value={String(level)}>
402 {zoomLabel(level)}
403 </SelectItem>
404 ))}
405 </SelectPopup>
406 </Select>
407 }
408 />
409 );
410}
411
412function BrowserAppearanceSetting({ disabled }: { readonly disabled: boolean }) {
413 const appearance = useClientSettings((settings) => settings.browserDefaultAppearance);
414 const updateSettings = useUpdatePrimarySettings();
415
416 return (
417 <SettingsRow
418 {...searchableSetting("browser-default-appearance")}
419 description="The color scheme pages are told to prefer. System follows your OS setting."
420 resetAction={
421 !disabled && appearance !== DEFAULT_PREVIEW_APPEARANCE ? (
422 <SettingResetButton
423 label="default browser appearance"
424 onClick={() => updateSettings({ browserDefaultAppearance: DEFAULT_PREVIEW_APPEARANCE })}
425 />
426 ) : null
427 }
428 control={
429 <Select
430 disabled={disabled}
431 value={appearance}
432 onValueChange={(value) => {
433 if (value === "system" || value === "light" || value === "dark") {
434 updateSettings({ browserDefaultAppearance: value });
435 }
436 }}
437 >
438 <SelectTrigger
439 size="sm"
440 className="w-full sm:w-40"
441 aria-label="Default browser appearance"
442 >
443 <SelectValue>{APPEARANCE_LABELS[appearance]}</SelectValue>
444 </SelectTrigger>
445 <SelectPopup align="end" alignItemWithTrigger={false}>
446 {Object.entries(APPEARANCE_LABELS).map(([value, label]) => (
447 <SelectItem hideIndicator key={value} value={value}>
448 {label}
449 </SelectItem>
450 ))}
451 </SelectPopup>
452 </Select>
453 }
454 />
455 );
456}
457
458function BrowserRecordingFrameRateSetting({ disabled }: { readonly disabled: boolean }) {
459 const frameRate = useClientSettings((settings) => settings.browserRecordingFrameRate);
460 const updateSettings = useUpdatePrimarySettings();
461
462 return (
463 <SettingsRow
464 {...searchableSetting("browser-recording-frame-rate")}
465 description="Maximum recording rate. 30 fps saves CPU and storage; 60 fps is smoother."
466 resetAction={
467 !disabled && frameRate !== DEFAULT_BROWSER_RECORDING_FRAME_RATE ? (
468 <SettingResetButton
469 label="browser recording frame rate"
470 onClick={() =>
471 updateSettings({ browserRecordingFrameRate: DEFAULT_BROWSER_RECORDING_FRAME_RATE })
472 }
473 />
474 ) : null
475 }
476 control={
477 <Select
478 disabled={disabled}
479 value={String(frameRate)}
480 onValueChange={(value) => {
481 const next = BROWSER_RECORDING_FRAME_RATES.find((rate) => String(rate) === value);
482 if (next !== undefined) {
483 updateSettings({ browserRecordingFrameRate: next });
484 }
485 }}
486 >
487 <SelectTrigger
488 size="sm"
489 className="w-full sm:w-40"
490 aria-label="Browser recording frame rate"
491 >
492 <SelectValue>{frameRate} fps</SelectValue>
493 </SelectTrigger>
494 <SelectPopup align="end" alignItemWithTrigger={false}>
495 {BROWSER_RECORDING_FRAME_RATES.map((rate) => (
496 <SelectItem hideIndicator key={rate} value={String(rate)}>
497 {rate} fps
498 </SelectItem>
499 ))}
500 </SelectPopup>
501 </Select>
502 }
503 />
504 );
505}
506
507const LINK_TARGET_LABELS: Readonly<Record<BrowserLinkTarget, string>> = {
508 system: "Your default browser",
509 app: "T3 Code",
510};
511
512function BrowserLinkTargetSetting({ disabled }: { readonly disabled: boolean }) {
513 const linkTarget = useClientSettings((settings) => settings.browserLinkTarget);
514 const updateSettings = useUpdatePrimarySettings();
515
516 return (
517 <SettingsRow
518 {...searchableSetting("browser-link-target")}
519 description="Where links in the chat and terminal open. Hold ⌘ or Ctrl while clicking a chat link to open it in your default browser either way."
520 resetAction={
521 !disabled && linkTarget !== DEFAULT_BROWSER_LINK_TARGET ? (
522 <SettingResetButton
523 label="link target"
524 onClick={() => updateSettings({ browserLinkTarget: DEFAULT_BROWSER_LINK_TARGET })}
525 />
526 ) : null
527 }
528 control={
529 <Select
530 disabled={disabled}
531 value={linkTarget}
532 onValueChange={(value) => {
533 if (value === "system" || value === "app") {
534 updateSettings({ browserLinkTarget: value });
535 }
536 }}
537 >
538 <SelectTrigger size="sm" className="w-full sm:w-40" aria-label="Open links in">
539 <SelectValue>{LINK_TARGET_LABELS[linkTarget]}</SelectValue>
540 </SelectTrigger>
541 <SelectPopup align="end" alignItemWithTrigger={false}>
542 {(Object.keys(LINK_TARGET_LABELS) as ReadonlyArray<BrowserLinkTarget>).map((target) => (
543 <SelectItem hideIndicator key={target} value={target}>
544 {LINK_TARGET_LABELS[target]}
545 </SelectItem>
546 ))}
547 </SelectPopup>
548 </Select>
549 }
550 />
551 );
552}
553
554function AgentBrowserAccessSetting() {
555 const settings = usePrimarySettings();
556 const updateSettings = useUpdatePrimarySettings();
557
558 return (
559 <SettingsRow
560 serverScoped
561 {...searchableSetting("agent-browser-access")}
562 description="Allow agents to use the preview browser. Off hides browser tools from agents, not you."
563 status={
564 settings.enableAgentBrowserAccess
565 ? undefined
566 : "Applies to sessions started from now on; a running agent keeps the tools it was given."
567 }
568 resetAction={
569 settings.enableAgentBrowserAccess !== DEFAULT_UNIFIED_SETTINGS.enableAgentBrowserAccess ? (
570 <SettingResetButton
571 label="agent browser access"
572 onClick={() =>
573 updateSettings({
574 enableAgentBrowserAccess: DEFAULT_UNIFIED_SETTINGS.enableAgentBrowserAccess,
575 })
576 }
577 />
578 ) : null
579 }
580 control={
581 <Switch
582 checked={settings.enableAgentBrowserAccess}
583 onCheckedChange={(checked) =>
584 updateSettings({ enableAgentBrowserAccess: Boolean(checked) })
585 }
586 aria-label="Allow agent browser access"
587 />
588 }
589 />
590 );
591}
592
593function BrowserAutoShowFloatingPreviewSetting({ disabled }: { readonly disabled: boolean }) {
594 const autoShow = useClientSettings((settings) => settings.browserAutoShowFloatingPreview);
595 const updateSettings = useUpdatePrimarySettings();
596
597 return (
598 <SettingsRow
599 {...searchableSetting("browser-auto-show-floating-preview")}
600 description="Show the floating preview when an agent opens a browser unless the agent says otherwise."
601 resetAction={
602 !disabled && autoShow !== DEFAULT_BROWSER_AUTO_SHOW_FLOATING_PREVIEW ? (
603 <SettingResetButton
604 label="auto-show floating preview"
605 onClick={() =>
606 updateSettings({
607 browserAutoShowFloatingPreview: DEFAULT_BROWSER_AUTO_SHOW_FLOATING_PREVIEW,
608 })
609 }
610 />
611 ) : null
612 }
613 control={
614 <Switch
615 disabled={disabled}
616 checked={autoShow}
617 onCheckedChange={(checked) =>
618 updateSettings({ browserAutoShowFloatingPreview: Boolean(checked) })
619 }
620 aria-label="Auto-show floating preview"
621 />
622 }
623 />
624 );
625}
626
627/**
628 * Frames the client-local preview defaults as one unavailable block.
629 *
630 * Disabling each control on its own left the labels and descriptions at full
631 * strength, so the group still read as editable. Boxing it puts the reason at
632 * the top and dims everything it covers, which is also why the explanation
633 * sits outside the dimmed area — the one part that must stay readable is the
634 * part saying why the rest isn't.
635 *
636 * Disabled rather than hidden because these are *client* settings: editing
637 * them from a browser tab would write preferences belonging to a different
638 * client, reading as though the desktop app had been configured when it
639 * hadn't.
640 */
641function DesktopOnlyBrowserDefaults({ children }: { readonly children: ReactNode }) {
642 return (
643 <div className="border-border/60 bg-muted/20 py-1.5">
644 <div className="flex items-start gap-2 px-3 py-2 text-[12px] leading-relaxed text-muted-foreground sm:px-4">
645 <InfoIcon className="mt-0.5 size-3.5 shrink-0 text-warning" />
646 <p>Only available in the desktop app.</p>
647 </div>
648 <div className="[&_h3]:opacity-64 [&_p]:opacity-64">{children}</div>
649 </div>
650 );
651}
652
653/**
654 * Profile list, its header menu, and the import flow.
655 *
656 * One menu creates profiles and imports into them, because the two are the
657 * same decision from the user's side: "I want a profile that has my Helium
658 * logins in it". Import targets include "New profile" so that case does not
659 * require creating one first and then finding a second control.
660 *
661 * Built-ins render without a rename field: they are synthesized rather than
662 * stored, so there is nothing to rename and removing them would strand every
663 * tab that opened under them.
664 *
665 * Sources are listed lazily on open: detection touches the other browser's
666 * files, and the answer changes while the app is running (quitting the browser
667 * clears `browserRunning`), so a value cached at mount would go stale.
668 */
669function BrowserProfilesSetting({ disabled }: { readonly disabled: boolean }) {
670 const userProfiles = useClientSettings((settings) => settings.browserProfiles);
671 const defaultProfileId = useClientSettings((settings) => settings.browserDefaultProfileId);
672 const settingsHydrated = useClientSettingsHydrated();
673 const updateSettings = useUpdatePrimarySettings();
674 const { environments, isReady: environmentsReady } = useEnvironments();
675 const primaryEnvironment = usePrimaryEnvironment();
676 const [sources, setSources] = useState<ReadonlyArray<BrowserImportSource> | null>(null);
677 const [importSession, setImportSession] = useState<{
678 readonly source: BrowserImportSource;
679 readonly environmentId: EnvironmentId;
680 readonly environmentName: string;
681 } | null>(null);
682 const [profilePendingRemoval, setProfilePendingRemoval] = useState<BrowserProfile | null>(null);
683 const [profileRemovalError, setProfileRemovalError] = useState<string | null>(null);
684 const [profileRemovalInFlight, setProfileRemovalInFlight] = useState(false);
685 const removalAvailable = browserProfileRemovalAvailable(
686 previewBridge !== null,
687 environmentsReady,
688 environments.length,
689 );
690 const importInFlightRef = useRef(false);
691 const [importInFlight, setImportInFlight] = useState(false);
692 const profileWritesDisabled = disabled || !settingsHydrated;
693
694 const profiles = resolveBrowserProfiles(userProfiles);
695 // Incognito is deliberately not a row — it holds nothing to manage — so the
696 // default has to resolve against the list that renders. A stored
697 // `browserDefaultProfileId` of "incognito" would otherwise leave the section
698 // with no Default badge at all.
699 const listedProfiles = profiles.filter((profile) => profile.kind !== "incognito");
700 const resolvedDefaultId =
701 findBrowserProfile(listedProfiles, defaultProfileId)?.id ?? DEFAULT_BROWSER_PROFILE_ID;
702
703 const createProfile = (baseName: string) => {
704 if (!settingsHydrated || importInFlightRef.current) return undefined;
705 const currentProfiles = getClientSettings().browserProfiles;
706 // Checked against the live settings, not the rendered list: two clicks
707 // before a re-render would otherwise both pass the disabled control.
708 if (currentProfiles.length >= BROWSER_PROFILE_MAX_COUNT) return undefined;
709 const resolvedProfiles = resolveBrowserProfiles(currentProfiles);
710 const taken = new Set(resolvedProfiles.map((profile) => profile.name));
711 let name = baseName;
712 for (let index = 2; taken.has(name); index += 1) name = `${baseName} ${index}`;
713 const profile = { id: `profile-${randomUUID()}`, name, kind: "persistent" as const };
714 updateSettings({ browserProfiles: [...currentProfiles, profile] });
715 return profile;
716 };
717
718 const renameProfile = (id: string, next: string) => {
719 if (!settingsHydrated || importInFlightRef.current) return;
720 const name = next.trim().slice(0, BROWSER_PROFILE_NAME_MAX_LENGTH);
721 if (name === "") return;
722 const currentProfiles = getClientSettings().browserProfiles;
723 updateSettings({
724 browserProfiles: currentProfiles.map((profile) =>
725 profile.id === id ? { ...profile, name } : profile,
726 ),
727 });
728 };
729
730 const clearProfileData = (id: string, name: string) => {
731 if (!settingsHydrated || importInFlightRef.current) return;
732 if (!previewBridge || !environmentsReady || environments.length === 0) {
733 toastManager.add({
734 type: "error",
735 title: `Could not clear ${name}'s data`,
736 description: "You're not connected to a server yet.",
737 });
738 return;
739 }
740 void clearBrowserProfileData(
741 previewBridge,
742 environments.map((environment) => environment.environmentId),
743 id,
744 )
745 .then(() => {
746 toastManager.add({ type: "success", title: `Cleared ${name}'s cookies and cache` });
747 })
748 .catch(() => {
749 toastManager.add({ type: "error", title: `Could not clear ${name}'s data` });
750 });
751 };
752
753 const removeProfile = async (id: string) => {
754 if (!settingsHydrated || importInFlightRef.current) return;
755 if (!removalAvailable) {
756 setProfileRemovalError("Connect to an environment before removing this profile.");
757 return;
758 }
759 setProfileRemovalError(null);
760 setProfileRemovalInFlight(true);
761 // Drop the partition's data too, otherwise a removed profile's cookies
762 // stay on disk with nothing in the UI pointing at them.
763 try {
764 await clearBrowserProfileData(
765 previewBridge,
766 environmentsReady ? environments.map((environment) => environment.environmentId) : [],
767 id,
768 );
769 } catch {
770 setProfileRemovalError("Profile data could not be deleted. Try again.");
771 setProfileRemovalInFlight(false);
772 return;
773 }
774 const currentSettings = getClientSettings();
775 updateSettings({
776 browserProfiles: currentSettings.browserProfiles.filter((profile) => profile.id !== id),
777 // Reassign the default rather than leaving it pointing at nothing.
778 ...(currentSettings.browserDefaultProfileId === id
779 ? { browserDefaultProfileId: DEFAULT_BROWSER_PROFILE_ID }
780 : {}),
781 });
782 setProfileRemovalInFlight(false);
783 setProfilePendingRemoval(null);
784 };
785
786 // A browser that is not on this machine is left out rather than listed as a
787 // dead row: there is nothing to act on, and the menu is a list of things you
788 // can import from. An unsupported one is left out for the same reason — the
789 // blocked wizard step can't be fixed from here. Every other unavailable
790 // reason stays, since each names a step the user can take.
791 const importableSources = (sources ?? []).filter(
792 (source) =>
793 source.unavailable !== "notInstalled" && source.unavailable !== "unsupportedPlatform",
794 );
795
796 // Refreshed without blanking the last result: the menu shows the cached list
797 // straight away so it doesn't reflow on open, and the source list is stable
798 // (names only) since choosing what to import happens in the wizard, not here.
799 const loadSources = useCallback(() => {
800 if (!previewBridge) return;
801 void previewBridge
802 .listBrowserImportSources()
803 .then(setSources)
804 .catch(() => setSources((previous) => previous ?? []));
805 }, []);
806
807 // Loaded once so the first open is instant instead of flashing a spinner.
808 useEffect(() => {
809 loadSources();
810 }, [loadSources]);
811
812 // Runs one import for the wizard. A new profile is registered only once the
813 // import succeeds — the cookies land in its partition first — so a blocked
814 // attempt never leaves an empty profile behind.
815 const runWizardImport = async (
816 source: BrowserImportSource,
817 environmentId: EnvironmentId,
818 input: { readonly sourceProfileDirectory: string; readonly target: WizardTarget },
819 ): Promise<ImportOutcome> => {
820 if (!previewBridge) return { kind: "blocked", reason: "sessionUnavailable" };
821 if (!settingsHydrated) return { kind: "blocked", reason: "sessionUnavailable" };
822 if (
823 input.target.kind === "existing" &&
824 !resolveBrowserProfiles(getClientSettings().browserProfiles).some(
825 (profile) => profile.id === input.target.profileId,
826 )
827 ) {
828 return { kind: "blocked", reason: "readFailed" };
829 }
830 if (importInFlightRef.current) return { kind: "blocked", reason: "readFailed" };
831 importInFlightRef.current = true;
832 setImportInFlight(true);
833 try {
834 const result = await previewBridge.importBrowserCookies({
835 environmentId,
836 sourceId: source.id,
837 sourceProfileDirectory: input.sourceProfileDirectory,
838 targetProfileId: input.target.profileId,
839 });
840 if (
841 input.target.kind === "existing" &&
842 !resolveBrowserProfiles(getClientSettings().browserProfiles).some(
843 (profile) => profile.id === input.target.profileId,
844 )
845 ) {
846 return { kind: "blocked", reason: "readFailed" };
847 }
848 let targetName: string;
849 if (input.target.kind === "new") {
850 // Registered only when something actually came over: an import that
851 // found no cookies should not leave a new, empty profile behind.
852 if (result.imported > 0) {
853 try {
854 const persisted = await persistClientSettingsUpdate((current) => {
855 const existing = current.browserProfiles.find(
856 (profile) => profile.id === input.target.profileId,
857 );
858 if (existing) return current;
859 // The wizard refuses a new target at the cap, but the cap can be
860 // reached while the import runs; the updater sees the newest
861 // settings, so this is the check that holds.
862 if (current.browserProfiles.length >= BROWSER_PROFILE_MAX_COUNT) {
863 throw new ProfileLimitReachedError();
864 }
865 const taken = new Set(
866 resolveBrowserProfiles(current.browserProfiles).map((profile) => profile.name),
867 );
868 let name = source.name;
869 for (let index = 2; taken.has(name); index += 1) name = `${source.name} ${index}`;
870 return {
871 ...current,
872 browserProfiles: [
873 ...current.browserProfiles,
874 { id: input.target.profileId, name, kind: "persistent" as const },
875 ],
876 };
877 });
878 targetName =
879 persisted.browserProfiles.find((profile) => profile.id === input.target.profileId)
880 ?.name ?? source.name;
881 } catch (cause) {
882 // This target id belongs only to the attempted new profile. Clear
883 // its partition so a failed registration cannot strand imported
884 // cookies behind a profile that disappears on restart.
885 await clearBrowserProfileData(
886 previewBridge,
887 [environmentId],
888 input.target.profileId,
889 ).catch(() => undefined);
890 // Not a read failure: the cookies came over and were cleared again
891 // because the profile could not be kept. Name that, in the same
892 // token form `importFailureReason` recovers from a bridge error.
893 const reason =
894 cause instanceof ProfileLimitReachedError ? "profileLimitReached" : "profileNotSaved";
895 throw new Error(`Importing cookies from ${source.id} failed: ${reason}.`, { cause });
896 }
897 } else {
898 targetName = source.name;
899 }
900 } else {
901 targetName = input.target.name;
902 }
903 return {
904 kind: "imported",
905 imported: result.imported,
906 skipped: result.skipped,
907 skippedDomains: result.skippedDomains,
908 targetName,
909 };
910 } catch (cause) {
911 return { kind: "blocked", reason: importFailureReason(cause) };
912 } finally {
913 importInFlightRef.current = false;
914 setImportInFlight(false);
915 }
916 };
917
918 // Re-checks a source's availability after the user quits the browser, and
919 // keeps the cached list in step so the menu reflects it too.
920 const refreshImportSource = async (
921 sourceId: BrowserImportSource["id"],
922 ): Promise<BrowserImportSource | undefined> => {
923 if (!previewBridge) return undefined;
924 try {
925 const latest = await previewBridge.listBrowserImportSources();
926 setSources(latest);
927 return latest.find((source) => source.id === sourceId);
928 } catch {
929 return undefined;
930 }
931 };
932
933 const atProfileLimit = userProfiles.length >= BROWSER_PROFILE_MAX_COUNT;
934
935 return (
936 <SettingsRow
937 {...searchableSetting("browser-profiles")}
938 description="Profiles separate cookies and logins. Incognito data is cleared when the app closes."
939 control={
940 <Menu onOpenChange={(open) => open && loadSources()}>
941 <MenuTrigger
942 render={
943 <Button
944 size="sm"
945 variant="outline"
946 disabled={profileWritesDisabled || importInFlight}
947 />
948 }
949 >
950 <PlusIcon />
951 Add profile
952 </MenuTrigger>
953 <MenuPopup align="end" className="min-w-56">
954 <MenuItem
955 disabled={!settingsHydrated || atProfileLimit}
956 onClick={() => createProfile("New profile")}
957 >
958 Blank profile
959 </MenuItem>
960 {atProfileLimit ? (
961 <MenuItem disabled>You’ve reached the profile limit</MenuItem>
962 ) : null}
963 <MenuSeparator />
964 <MenuGroup>
965 <MenuGroupLabel>Import from</MenuGroupLabel>
966 {sources === null ? (
967 <MenuItem disabled>Looking for browsers…</MenuItem>
968 ) : importableSources.length === 0 ? (
969 <MenuItem disabled>No supported browsers found</MenuItem>
970 ) : (
971 // Every source is a plain row — running, needs-permission and
972 // ready all look the same here. The wizard picks up whatever
973 // state the source is in and walks the user forward from there.
974 <>
975 {importableSources.map((source) => (
976 <MenuItem
977 key={source.id}
978 disabled={!settingsHydrated || primaryEnvironment == null}
979 onClick={() => {
980 if (!settingsHydrated || primaryEnvironment == null) return;
981 setImportSession({
982 source,
983 environmentId: primaryEnvironment.environmentId,
984 environmentName: resolveEnvironmentOptionLabel({
985 isPrimary: true,
986 environmentId: primaryEnvironment.environmentId,
987 runtimeLabel: primaryEnvironment.label,
988 }),
989 });
990 }}
991 >
992 {source.name}
993 </MenuItem>
994 ))}
995 {primaryEnvironment == null ? (
996 <MenuItem disabled>Connect to an environment to import cookies</MenuItem>
997 ) : null}
998 </>
999 )}
1000 </MenuGroup>
1001 </MenuPopup>
1002 </Menu>
1003 }
1004 >
1005 {/*
1006 The bordered container groups rows unambiguously at any width, and
1007 carries the bottom spacing `SettingsRow` leaves to its children
1008 (`pt-3 pb-1`).
1009 */}
1010 <div className="mt-2 mb-2 overflow-hidden rounded-lg border border-border/60">
1011 {listedProfiles.map((profile, index) => {
1012 const builtIn = isBuiltInBrowserProfileId(profile.id);
1013 const isDefault = profile.id === resolvedDefaultId;
1014 return (
1015 <div
1016 key={profile.id}
1017 className={cn(
1018 "flex items-center gap-3 px-3 py-2",
1019 index > 0 && "border-t border-border/60",
1020 )}
1021 >
1022 <span className="flex min-w-0 flex-1 items-center gap-2">
1023 {builtIn ? (
1024 // Dimmed here rather than on the table: a wrapper-level dim
1025 // stacks with the rename field's and the row menu button's
1026 // own, landing them near 0.41 while every other disabled
1027 // control in the block sits at 0.64.
1028 <span
1029 className={cn(
1030 "truncate text-sm text-foreground",
1031 profileWritesDisabled && "opacity-64",
1032 )}
1033 >
1034 {profile.name}
1035 </span>
1036 ) : (
1037 <DraftInput
1038 nativeInput
1039 size="sm"
1040 className="w-full max-w-56"
1041 aria-label={`Rename ${profile.name}`}
1042 disabled={profileWritesDisabled || importInFlight}
1043 maxLength={BROWSER_PROFILE_NAME_MAX_LENGTH}
1044 value={profile.name}
1045 onCommit={(next) => renameProfile(profile.id, next)}
1046 />
1047 )}
1048 {/*
1049 Dimmed with the rest of the row: a `Badge` has no disabled
1050 treatment of its own, so a solid `bg-primary` pill would
1051 otherwise sit at full strength beside a name, rename field
1052 and menu button that are all at 0.64.
1053 */}
1054 {isDefault ? (
1055 <Badge className={cn(profileWritesDisabled && "opacity-64")}>Default</Badge>
1056 ) : null}
1057 </span>
1058 <Menu>
1059 <MenuTrigger
1060 render={
1061 <Button
1062 size="icon-xs"
1063 variant="ghost-muted"
1064 disabled={profileWritesDisabled || importInFlight}
1065 aria-label={`${profile.name} options`}
1066 />
1067 }
1068 >
1069 <MoreVertical />
1070 </MenuTrigger>
1071 <MenuPopup align="end" className="min-w-44">
1072 <MenuItem
1073 disabled={!settingsHydrated || isDefault}
1074 onClick={() => {
1075 if (settingsHydrated) {
1076 updateSettings({ browserDefaultProfileId: profile.id });
1077 }
1078 }}
1079 >
1080 Set as default
1081 </MenuItem>
1082 <MenuItem
1083 disabled={!settingsHydrated || !removalAvailable}
1084 onClick={() => clearProfileData(profile.id, profile.name)}
1085 >
1086 Clear cookies and cache
1087 </MenuItem>
1088 {builtIn ? null : (
1089 <MenuItem
1090 variant="destructive"
1091 disabled={!settingsHydrated || !removalAvailable}
1092 onClick={() => {
1093 if (settingsHydrated) setProfilePendingRemoval(profile);
1094 }}
1095 >
1096 Remove profile and data
1097 </MenuItem>
1098 )}
1099 {!removalAvailable ? (
1100 <>
1101 <MenuSeparator />
1102 <MenuItem disabled>
1103 {environmentsReady
1104 ? "Connect to an environment to clear profile data"
1105 : "Checking environments…"}
1106 </MenuItem>
1107 </>
1108 ) : null}
1109 </MenuPopup>
1110 </Menu>
1111 </div>
1112 );
1113 })}
1114 </div>
1115 <AlertDialog
1116 open={profilePendingRemoval !== null}
1117 onOpenChange={(open) => {
1118 if (!open && !profileRemovalInFlight) {
1119 setProfilePendingRemoval(null);
1120 setProfileRemovalError(null);
1121 }
1122 }}
1123 >
1124 <AlertDialogPopup>
1125 <AlertDialogHeader>
1126 <AlertDialogTitle>Remove “{profilePendingRemoval?.name}”?</AlertDialogTitle>
1127 <AlertDialogDescription>
1128 Its cookies and logins are deleted. Tabs already open in this profile stay open until
1129 you close them.
1130 </AlertDialogDescription>
1131 {profileRemovalError ? (
1132 <p aria-live="polite" className="text-sm text-destructive">
1133 {profileRemovalError}
1134 </p>
1135 ) : null}
1136 {!removalAvailable ? (
1137 <p className="text-sm text-muted-foreground">
1138 Connect to an environment to remove this profile and its data.
1139 </p>
1140 ) : null}
1141 </AlertDialogHeader>
1142 <AlertDialogFooter>
1143 <AlertDialogClose
1144 disabled={profileRemovalInFlight}
1145 render={<Button variant="outline" disabled={profileRemovalInFlight} />}
1146 >
1147 Cancel
1148 </AlertDialogClose>
1149 <Button
1150 variant="destructive"
1151 disabled={profileRemovalInFlight || !settingsHydrated || !removalAvailable}
1152 onClick={() => {
1153 if (profilePendingRemoval && settingsHydrated && removalAvailable) {
1154 void removeProfile(profilePendingRemoval.id);
1155 }
1156 }}
1157 >
1158 {profileRemovalInFlight ? "Removing…" : "Remove profile"}
1159 </Button>
1160 </AlertDialogFooter>
1161 </AlertDialogPopup>
1162 </AlertDialog>
1163 {importSession ? (
1164 <BrowserImportWizard
1165 source={importSession.source}
1166 destinationEnvironmentName={importSession.environmentName}
1167 targetProfiles={listedProfiles.map((profile) => ({ id: profile.id, name: profile.name }))}
1168 canCreateProfile={settingsHydrated && !atProfileLimit}
1169 onImport={(input) =>
1170 runWizardImport(importSession.source, importSession.environmentId, input)
1171 }
1172 onRefreshSource={() => refreshImportSource(importSession.source.id)}
1173 onOpenFullDiskAccessSettings={() => {
1174 // Rejects outside the desktop shell (and on shells that predate the
1175 // method), so the one toast covers every way the link can fail.
1176 void readLocalApi()
1177 ?.shell.openSystemSettings("full-disk-access")
1178 .catch(() => {
1179 toastManager.add({
1180 type: "error",
1181 title: "Could not open System Settings",
1182 description: "Open Privacy & Security → Full Disk Access manually.",
1183 });
1184 });
1185 }}
1186 onClose={() => setImportSession(null)}
1187 />
1188 ) : null}
1189 </SettingsRow>
1190 );
1191}
1192
1193export function IntegrationsSettingsPanel() {
1194 // Client-local preview defaults are editable only where the preview exists.
1195 const previewDefaultsDisabled = !isElectron;
1196 const previewDefaults = (
1197 <>
1198 <BrowserProfilesSetting disabled={previewDefaultsDisabled} />
1199 <BrowserViewportSetting disabled={previewDefaultsDisabled} />
1200 <BrowserZoomSetting disabled={previewDefaultsDisabled} />
1201 <BrowserAppearanceSetting disabled={previewDefaultsDisabled} />
1202 <BrowserRecordingFrameRateSetting disabled={previewDefaultsDisabled} />
1203 <BrowserLinkTargetSetting disabled={previewDefaultsDisabled} />
1204 <BrowserAutoShowFloatingPreviewSetting disabled={previewDefaultsDisabled} />
1205 </>
1206 );
1207
1208 return (
1209 <SettingsPageContainer>
1210 <SettingsSection id="browser" title="Browser">
1211 {/* Server-authoritative, so it stays editable on any client anchored to
1212 a server; `serverScoped` covers the hosted app, which has none. It
1213 sits outside the block covering the desktop-only defaults. */}
1214 <AgentBrowserAccessSetting />
1215 {previewDefaultsDisabled ? (
1216 <DesktopOnlyBrowserDefaults>{previewDefaults}</DesktopOnlyBrowserDefaults>
1217 ) : (
1218 previewDefaults
1219 )}
1220 </SettingsSection>
1221 </SettingsPageContainer>
1222 );
1223}