Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

IntegrationsSettings.tsx

1,208 lines45.4 KB

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