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

IntegrationsSettings.tsx

940 lines34.5 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 BROWSER_PROFILE_MAX_COUNT,
11 type BrowserLinkTarget,
12 type BrowserProfile,
13 type EnvironmentId,
14 BROWSER_PROFILE_NAME_MAX_LENGTH,
15 BROWSER_RECORDING_FRAME_RATES,
16 DEFAULT_BROWSER_AUTO_SHOW_FLOATING_PREVIEW,
17 DEFAULT_BROWSER_PROFILE_ID,
18 DEFAULT_BROWSER_LINK_TARGET,
19 DEFAULT_BROWSER_RECORDING_FRAME_RATE,
20 DEFAULT_BROWSER_VIEWPORT,
21 DEFAULT_PREVIEW_APPEARANCE,
22 DEFAULT_UNIFIED_SETTINGS,
23 DEFAULT_PREVIEW_ZOOM_FACTOR,
24 FILL_PREVIEW_VIEWPORT,
25 PREVIEW_VIEWPORT_MAX_AREA,
26 PREVIEW_VIEWPORT_MAX_DIMENSION,
27 PREVIEW_VIEWPORT_MIN_DIMENSION,
28 PREVIEW_ZOOM_LEVELS,
29 findBrowserProfile,
30 isBuiltInBrowserProfileId,
31 resolveBrowserProfiles,
32 type PreviewAppearancePreference,
33 type PreviewViewportSetting,
34} from "@t3tools/contracts";
35import { PREVIEW_VIEWPORT_PRESETS } from "@t3tools/shared/previewViewport";
36import { InfoIcon, Plus as PlusIcon, Trash2 as Trash2Icon } from "lucide-react";
37import { useState } from "react";
38import type { ReactNode } from "react";
39​
40import { ScreenRotationIcon } from "~/browser/ScreenRotationIcon";
41import { previewBridge } from "~/components/preview/previewBridge";
42import { cn, randomUUID } from "~/lib/utils";
43import { useEnvironments } from "~/state/environments";
44import { isElectron } from "../../env";
45​
46import { Badge } from "../ui/badge";
47import {
48 AlertDialog,
49 AlertDialogClose,
50 AlertDialogDescription,
51 AlertDialogFooter,
52 AlertDialogHeader,
53 AlertDialogPopup,
54 AlertDialogTitle,
55} from "../ui/alert-dialog";
56import { Button } from "../ui/button";
57import { DraftInput } from "../ui/draft-input";
58import { NumberField, NumberFieldGroup, NumberFieldInput } from "../ui/number-field";
59import {
60 Select,
61 SelectGroup,
62 SelectGroupLabel,
63 SelectItem,
64 SelectPopup,
65 SelectTrigger,
66 SelectValue,
67} from "../ui/select";
68import { Switch } from "../ui/switch";
69import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
70import {
71 getClientSettings,
72 useClientSettings,
73 useClientSettingsHydrated,
74 usePrimarySettings,
75 useUpdatePrimarySettings,
76} from "~/hooks/useSettings";
77​
78import {
79 SettingResetButton,
80 SettingsPageContainer,
81 SettingsRow,
82 SettingsSection,
83} from "./settingsLayout";
84import { ITEM_ROW_INNER_CLASSNAME } from "./itemRows";
85import { searchableSetting } from "./settingsSearch";
86​
87const FILL_VALUE = "fill";
88const RESPONSIVE_VALUE = "responsive";
89​
90type BrowserProfileDataBridge = Pick<
91 NonNullable<typeof previewBridge>,
92 "clearCookies" | "clearCache"
93>;
94​
95export async function clearBrowserProfileData(
96 bridge: BrowserProfileDataBridge | null,
97 environmentIds: ReadonlyArray<EnvironmentId>,
98 profileId: string,
99): Promise<void> {
100 if (bridge === null || environmentIds.length === 0) {
101 throw new Error("Browser profile data is not available to clear.");
102 }
103 await Promise.all(
104 environmentIds.flatMap((environmentId) => [
105 bridge.clearCookies(environmentId, profileId),
106 bridge.clearCache(environmentId, profileId),
107 ]),
108 );
110​
111export function browserProfileRemovalAvailable(
112 bridgeAvailable: boolean,
113 environmentsReady: boolean,
114 environmentCount: number,
115): boolean {
116 return bridgeAvailable && environmentsReady && environmentCount > 0;
118​
119/**
120 * The size a "Responsive" default falls back to when the user switches away
121 * from Fill and hasn't typed dimensions yet. Fill has no dimensions to carry
122 * over, so the picker needs something concrete to seed the inputs with.
123 */
124const RESPONSIVE_SEED_SIZE = { width: 1280, height: 800 } as const;
125​
126const NO_GROUPING: Intl.NumberFormatOptions = { useGrouping: false };
127​
128const APPEARANCE_LABELS: Readonly<Record<PreviewAppearancePreference, string>> = {
129 system: "System",
130 light: "Light",
131 dark: "Dark",
132};
133​
134const zoomLabel = (zoomFactor: number) => `${Math.round(zoomFactor * 100)}%`;
135​
136const viewportSelectValue = (viewport: PreviewViewportSetting): string => {
137 if (viewport._tag === "fill") return FILL_VALUE;
138 if (
139 viewport._tag === "preset" &&
140 PREVIEW_VIEWPORT_PRESETS.some((preset) => preset.id === viewport.presetId)
141 ) {
142 return viewport.presetId;
143 }
144 return RESPONSIVE_VALUE;
145};
146​
147/**
148 * The trigger renders this rather than a bare `SelectValue`, which would fall
149 * back to printing the raw stored value ("fill") because the options are built
150 * inline instead of from an `items` map.
151 */
152const viewportSelectLabel = (viewport: PreviewViewportSetting): string => {
153 const value = viewportSelectValue(viewport);
154 if (value === FILL_VALUE) return "Fill panel";
155 if (value === RESPONSIVE_VALUE) return "Responsive";
156 return PREVIEW_VIEWPORT_PRESETS.find((preset) => preset.id === value)?.label ?? "Responsive";
157};
158​
159const isValidDimension = (value: number) =>
160 Number.isInteger(value) &&
161 value >= PREVIEW_VIEWPORT_MIN_DIMENSION &&
162 value <= PREVIEW_VIEWPORT_MAX_DIMENSION;
163​
164/**
165 * A sized viewport with width and height swapped. Presets keep their identity
166 * through a rotation — `resolvePreviewViewport` already stores rotated presets
167 * as the preset id plus swapped dimensions — so a rotated iPad is still an
168 * iPad, not an anonymous custom size.
169 */
170const rotateViewport = (
171 viewport: Exclude<PreviewViewportSetting, { readonly _tag: "fill" }>,
172): PreviewViewportSetting => ({
173 ...viewport,
174 width: viewport.height,
175 height: viewport.width,
176});
177​
178function BrowserViewportSetting({ disabled }: { readonly disabled: boolean }) {
179 const viewport = useClientSettings((settings) => settings.browserDefaultViewport);
180 const updateSettings = useUpdatePrimarySettings();
181​
182 const sized = viewport._tag === "fill" ? null : viewport;
183 const presentedSize = {
184 width: sized?.width ?? RESPONSIVE_SEED_SIZE.width,
185 height: sized?.height ?? RESPONSIVE_SEED_SIZE.height,
186 };
187​
188 const selectViewport = (value: string | null) => {
189 if (value === FILL_VALUE) {
190 updateSettings({ browserDefaultViewport: FILL_PREVIEW_VIEWPORT });
191 return;
192 }
193 if (value === RESPONSIVE_VALUE) {
194 updateSettings({
195 browserDefaultViewport: {
196 _tag: "freeform",
197 width: sized?.width ?? RESPONSIVE_SEED_SIZE.width,
198 height: sized?.height ?? RESPONSIVE_SEED_SIZE.height,
199 },
200 });
201 return;
202 }
203 const preset = PREVIEW_VIEWPORT_PRESETS.find((candidate) => candidate.id === value);
204 if (!preset) return;
205 updateSettings({
206 browserDefaultViewport: {
207 _tag: "preset",
208 width: preset.width,
209 height: preset.height,
210 presetId: preset.id,
211 },
212 });
213 };
214​
215 // Committed on blur rather than per keystroke: typing "2560" passes through
216 // "256", which is a legal dimension, so an onValueChange handler would
217 // persist that intermediate size and churn the settings file on every key.
218 const commitDimension = (axis: "width" | "height", value: number | null) => {
219 if (value === null || !isValidDimension(value)) return;
220 const next = { ...presentedSize, [axis]: value };
221 if (next.width * next.height > PREVIEW_VIEWPORT_MAX_AREA) return;
222 if (sized && next.width === sized.width && next.height === sized.height) return;
223 // Typing a size means the preset no longer describes it.
224 updateSettings({ browserDefaultViewport: { _tag: "freeform", ...next } });
225 };
226​
227 return (
228 <SettingsRow
229 {...searchableSetting("browser-default-viewport")}
230 description="The viewport a browser tab opens at, for both you and agents. Fill sizes the page to the panel; any other choice opens the device toolbar at that size."
231 resetAction={
232 !disabled && viewport._tag !== DEFAULT_BROWSER_VIEWPORT._tag ? (
233 <SettingResetButton
234 label="default browser viewport"
235 onClick={() => updateSettings({ browserDefaultViewport: DEFAULT_BROWSER_VIEWPORT })}
236 />
237 ) : null
238 }
239 control={
240 <div className="flex w-full flex-wrap items-center justify-end gap-2 sm:w-auto">
241 <Select
242 value={viewportSelectValue(viewport)}
243 onValueChange={selectViewport}
244 disabled={disabled}
245 >
246 <SelectTrigger
247 size="sm"
248 className="w-full min-w-0 sm:w-44"
249 aria-label="Default browser viewport"
250 >
251 <SelectValue>{viewportSelectLabel(viewport)}</SelectValue>
252 </SelectTrigger>
253 <SelectPopup align="end" alignItemWithTrigger={false} className="min-w-64">
254 <SelectItem value={FILL_VALUE}>Fill panel</SelectItem>
255 <SelectItem value={RESPONSIVE_VALUE}>Responsive</SelectItem>
256 <SelectGroup>
257 <SelectGroupLabel>Standard</SelectGroupLabel>
258 {PREVIEW_VIEWPORT_PRESETS.map((preset) => (
259 <SelectItem key={preset.id} value={preset.id}>
260 <span className="flex w-full items-center justify-between gap-5">
261 <span>{preset.label}</span>
262 <span className="text-xs tabular-nums text-muted-foreground">
263 {preset.detail}
264 </span>
265 </span>
266 </SelectItem>
267 ))}
268 </SelectGroup>
269 </SelectPopup>
270 </Select>
271​
272 {sized ? (
273 <div className="flex min-w-0 items-center gap-1">
274 <NumberField
275 value={presentedSize.width}
276 min={PREVIEW_VIEWPORT_MIN_DIMENSION}
277 max={PREVIEW_VIEWPORT_MAX_DIMENSION}
278 disabled={disabled}
279 // Pixel counts read as raw numbers; grouping would show "1,024".
280 format={NO_GROUPING}
281 size="sm"
282 className="w-20"
283 onValueCommitted={(value) => commitDimension("width", value)}
284 >
285 <NumberFieldGroup>
286 <NumberFieldInput aria-label="Default viewport width" />
287 </NumberFieldGroup>
288 </NumberField>
289 <span className="text-xs text-muted-foreground">×</span>
290 <NumberField
291 value={presentedSize.height}
292 min={PREVIEW_VIEWPORT_MIN_DIMENSION}
293 max={PREVIEW_VIEWPORT_MAX_DIMENSION}
294 disabled={disabled}
295 format={NO_GROUPING}
296 size="sm"
297 className="w-20"
298 onValueCommitted={(value) => commitDimension("height", value)}
299 >
300 <NumberFieldGroup>
301 <NumberFieldInput aria-label="Default viewport height" />
302 </NumberFieldGroup>
303 </NumberField>
304 <Tooltip>
305 <TooltipTrigger
306 render={
307 <Button
308 size="icon-sm"
309 variant="ghost-muted"
310 disabled={disabled}
311 aria-label={`Rotate to ${
312 presentedSize.height >= presentedSize.width ? "landscape" : "portrait"
313 }`}
314 onClick={() =>
315 updateSettings({ browserDefaultViewport: rotateViewport(sized) })
316 }
317 >
318 <ScreenRotationIcon />
319 </Button>
320 }
321 />
322 <TooltipPopup side="top">Rotate</TooltipPopup>
323 </Tooltip>
324 </div>
325 ) : null}
326 </div>
327 }
328 />
329 );
331​
332function BrowserZoomSetting({ disabled }: { readonly disabled: boolean }) {
333 const zoomFactor = useClientSettings((settings) => settings.browserDefaultZoomFactor);
334 const updateSettings = useUpdatePrimarySettings();
335​
336 return (
337 <SettingsRow
338 {...searchableSetting("browser-default-zoom")}
339 description="Page zoom applied to new browser tabs."
340 resetAction={
341 !disabled && zoomFactor !== DEFAULT_PREVIEW_ZOOM_FACTOR ? (
342 <SettingResetButton
343 label="default browser zoom"
344 onClick={() =>
345 updateSettings({ browserDefaultZoomFactor: DEFAULT_PREVIEW_ZOOM_FACTOR })
346 }
347 />
348 ) : null
349 }
350 control={
351 <Select
352 disabled={disabled}
353 value={String(zoomFactor)}
354 onValueChange={(value) => {
355 const next = PREVIEW_ZOOM_LEVELS.find((level) => String(level) === value);
356 if (next !== undefined) updateSettings({ browserDefaultZoomFactor: next });
357 }}
358 >
359 <SelectTrigger size="sm" className="w-full sm:w-40" aria-label="Default browser zoom">
360 <SelectValue>{zoomLabel(zoomFactor)}</SelectValue>
361 </SelectTrigger>
362 <SelectPopup align="end" alignItemWithTrigger={false}>
363 {PREVIEW_ZOOM_LEVELS.map((level) => (
364 <SelectItem hideIndicator key={level} value={String(level)}>
365 {zoomLabel(level)}
366 </SelectItem>
367 ))}
368 </SelectPopup>
369 </Select>
370 }
371 />
372 );
374​
375function BrowserAppearanceSetting({ disabled }: { readonly disabled: boolean }) {
376 const appearance = useClientSettings((settings) => settings.browserDefaultAppearance);
377 const updateSettings = useUpdatePrimarySettings();
378​
379 return (
380 <SettingsRow
381 {...searchableSetting("browser-default-appearance")}
382 description="The color scheme pages are told to prefer. System follows your OS setting."
383 resetAction={
384 !disabled && appearance !== DEFAULT_PREVIEW_APPEARANCE ? (
385 <SettingResetButton
386 label="default browser appearance"
387 onClick={() => updateSettings({ browserDefaultAppearance: DEFAULT_PREVIEW_APPEARANCE })}
388 />
389 ) : null
390 }
391 control={
392 <Select
393 disabled={disabled}
394 value={appearance}
395 onValueChange={(value) => {
396 if (value === "system" || value === "light" || value === "dark") {
397 updateSettings({ browserDefaultAppearance: value });
398 }
399 }}
400 >
401 <SelectTrigger
402 size="sm"
403 className="w-full sm:w-40"
404 aria-label="Default browser appearance"
405 >
406 <SelectValue>{APPEARANCE_LABELS[appearance]}</SelectValue>
407 </SelectTrigger>
408 <SelectPopup align="end" alignItemWithTrigger={false}>
409 {Object.entries(APPEARANCE_LABELS).map(([value, label]) => (
410 <SelectItem hideIndicator key={value} value={value}>
411 {label}
412 </SelectItem>
413 ))}
414 </SelectPopup>
415 </Select>
416 }
417 />
418 );
420​
421function BrowserRecordingFrameRateSetting({ disabled }: { readonly disabled: boolean }) {
422 const frameRate = useClientSettings((settings) => settings.browserRecordingFrameRate);
423 const updateSettings = useUpdatePrimarySettings();
424​
425 return (
426 <SettingsRow
427 {...searchableSetting("browser-recording-frame-rate")}
428 description="Maximum frame rate for browser recordings. 30 fps is the default and uses less CPU and storage; 60 fps captures smoother motion."
429 resetAction={
430 !disabled && frameRate !== DEFAULT_BROWSER_RECORDING_FRAME_RATE ? (
431 <SettingResetButton
432 label="browser recording frame rate"
433 onClick={() =>
434 updateSettings({ browserRecordingFrameRate: DEFAULT_BROWSER_RECORDING_FRAME_RATE })
435 }
436 />
437 ) : null
438 }
439 control={
440 <Select
441 disabled={disabled}
442 value={String(frameRate)}
443 onValueChange={(value) => {
444 const next = BROWSER_RECORDING_FRAME_RATES.find((rate) => String(rate) === value);
445 if (next !== undefined) {
446 updateSettings({ browserRecordingFrameRate: next });
447 }
448 }}
449 >
450 <SelectTrigger
451 size="sm"
452 className="w-full sm:w-40"
453 aria-label="Browser recording frame rate"
454 >
455 <SelectValue>{frameRate} fps</SelectValue>
456 </SelectTrigger>
457 <SelectPopup align="end" alignItemWithTrigger={false}>
458 {BROWSER_RECORDING_FRAME_RATES.map((rate) => (
459 <SelectItem hideIndicator key={rate} value={String(rate)}>
460 {rate} fps
461 </SelectItem>
462 ))}
463 </SelectPopup>
464 </Select>
465 }
466 />
467 );
469​
470const LINK_TARGET_LABELS: Readonly<Record<BrowserLinkTarget, string>> = {
471 system: "Your default browser",
472 app: "T3 Code",
473};
474​
475function BrowserLinkTargetSetting({ disabled }: { readonly disabled: boolean }) {
476 const linkTarget = useClientSettings((settings) => settings.browserLinkTarget);
477 const updateSettings = useUpdatePrimarySettings();
478​
479 return (
480 <SettingsRow
481 {...searchableSetting("browser-link-target")}
482 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."
483 resetAction={
484 !disabled && linkTarget !== DEFAULT_BROWSER_LINK_TARGET ? (
485 <SettingResetButton
486 label="link target"
487 onClick={() => updateSettings({ browserLinkTarget: DEFAULT_BROWSER_LINK_TARGET })}
488 />
489 ) : null
490 }
491 control={
492 <Select
493 disabled={disabled}
494 value={linkTarget}
495 onValueChange={(value) => {
496 if (value === "system" || value === "app") {
497 updateSettings({ browserLinkTarget: value });
498 }
499 }}
500 >
501 <SelectTrigger size="sm" className="w-full sm:w-40" aria-label="Open links in">
502 <SelectValue>{LINK_TARGET_LABELS[linkTarget]}</SelectValue>
503 </SelectTrigger>
504 <SelectPopup align="end" alignItemWithTrigger={false}>
505 {(Object.keys(LINK_TARGET_LABELS) as ReadonlyArray<BrowserLinkTarget>).map((target) => (
506 <SelectItem hideIndicator key={target} value={target}>
507 {LINK_TARGET_LABELS[target]}
508 </SelectItem>
509 ))}
510 </SelectPopup>
511 </Select>
512 }
513 />
514 );
516​
517function AgentBrowserAccessSetting() {
518 const settings = usePrimarySettings();
519 const updateSettings = useUpdatePrimarySettings();
520​
521 return (
522 <SettingsRow
523 serverScoped
524 {...searchableSetting("agent-browser-access")}
525 description="Let agents open and drive the preview browser. When off, the browser tools and the instructions describing them are withheld from agent sessions. Your own browser panel is unaffected."
526 status={
527 settings.enableAgentBrowserAccess
528 ? undefined
529 : "Applies to sessions started from now on; a running agent keeps the tools it was given."
530 }
531 resetAction={
532 settings.enableAgentBrowserAccess !== DEFAULT_UNIFIED_SETTINGS.enableAgentBrowserAccess ? (
533 <SettingResetButton
534 label="agent browser access"
535 onClick={() =>
536 updateSettings({
537 enableAgentBrowserAccess: DEFAULT_UNIFIED_SETTINGS.enableAgentBrowserAccess,
538 })
539 }
540 />
541 ) : null
542 }
543 control={
544 <Switch
545 checked={settings.enableAgentBrowserAccess}
546 onCheckedChange={(checked) =>
547 updateSettings({ enableAgentBrowserAccess: Boolean(checked) })
548 }
549 aria-label="Allow agent browser access"
550 />
551 }
552 />
553 );
555​
556function BrowserAutoShowFloatingPreviewSetting({ disabled }: { readonly disabled: boolean }) {
557 const autoShow = useClientSettings((settings) => settings.browserAutoShowFloatingPreview);
558 const updateSettings = useUpdatePrimarySettings();
559​
560 return (
561 <SettingsRow
562 {...searchableSetting("browser-auto-show-floating-preview")}
563 description="Pop the floating preview into view when an agent opens a browser. An agent that explicitly asks to show or hide its preview still gets what it asked for."
564 resetAction={
565 !disabled && autoShow !== DEFAULT_BROWSER_AUTO_SHOW_FLOATING_PREVIEW ? (
566 <SettingResetButton
567 label="auto-show floating preview"
568 onClick={() =>
569 updateSettings({
570 browserAutoShowFloatingPreview: DEFAULT_BROWSER_AUTO_SHOW_FLOATING_PREVIEW,
571 })
572 }
573 />
574 ) : null
575 }
576 control={
577 <Switch
578 disabled={disabled}
579 checked={autoShow}
580 onCheckedChange={(checked) =>
581 updateSettings({ browserAutoShowFloatingPreview: Boolean(checked) })
582 }
583 aria-label="Auto-show floating preview"
584 />
585 }
586 />
587 );
589​
590/**
591 * Frames the client-local preview defaults as one unavailable block.
592 *
593 * Disabling each control on its own left the labels and descriptions at full
594 * strength, so the group still read as editable. Boxing it puts the reason at
595 * the top and dims everything it covers, which is also why the explanation
596 * sits outside the dimmed area — the one part that must stay readable is the
597 * part saying why the rest isn't.
598 *
599 * Disabled rather than hidden because these are *client* settings: editing
600 * them from a browser tab would write preferences belonging to a different
601 * client, reading as though the desktop app had been configured when it
602 * hadn't.
603 */
604function DesktopOnlyBrowserDefaults({ children }: { readonly children: ReactNode }) {
605 return (
606 <div className="rounded-xl border border-border/60 bg-muted/20 py-1.5">
607 <div className="flex items-start gap-2 px-3 py-2 text-[12px] leading-relaxed text-muted-foreground sm:px-4">
608 <InfoIcon className="mt-0.5 size-3.5 shrink-0 text-warning" />
609 <p>Only available in the desktop app.</p>
610 </div>
611 <div className="[&_h3]:opacity-64 [&_p]:opacity-64">{children}</div>
612 </div>
613 );
615​
616/**
617 * Create, rename, and remove browser profiles.
618 *
619 * Built-ins render without controls: they are synthesized rather than stored,
620 * so there is nothing to rename and removing them would strand every tab that
621 * opened under them.
622 */
623function BrowserProfilesSetting({ disabled }: { readonly disabled: boolean }) {
624 const userProfiles = useClientSettings((settings) => settings.browserProfiles);
625 const settingsHydrated = useClientSettingsHydrated();
626 const updateSettings = useUpdatePrimarySettings();
627 const { environments, isReady: environmentsReady } = useEnvironments();
628 const [profilePendingRemoval, setProfilePendingRemoval] = useState<BrowserProfile | null>(null);
629 const [profileRemovalError, setProfileRemovalError] = useState<string | null>(null);
630 const [profileRemovalInFlight, setProfileRemovalInFlight] = useState(false);
631 const removalAvailable = browserProfileRemovalAvailable(
632 previewBridge !== null,
633 environmentsReady,
634 environments.length,
635 );
636 const profileWritesDisabled = disabled || !settingsHydrated;
637​
638 const addProfile = () => {
639 if (!settingsHydrated) return;
640 const currentProfiles = getClientSettings().browserProfiles;
641 if (currentProfiles.length >= BROWSER_PROFILE_MAX_COUNT) return;
642 const taken = new Set(resolveBrowserProfiles(currentProfiles).map((profile) => profile.name));
643 let name = "New profile";
644 for (let index = 2; taken.has(name); index += 1) name = `New profile ${index}`;
645 updateSettings({
646 browserProfiles: [
647 ...currentProfiles,
648 { id: `profile-${randomUUID()}`, name, kind: "persistent" as const },
649 ],
650 });
651 };
652​
653 const renameProfile = (id: string, next: string) => {
654 if (!settingsHydrated) return;
655 const name = next.trim().slice(0, BROWSER_PROFILE_NAME_MAX_LENGTH);
656 if (name === "") return;
657 const currentProfiles = getClientSettings().browserProfiles;
658 updateSettings({
659 browserProfiles: currentProfiles.map((profile) =>
660 profile.id === id ? { ...profile, name } : profile,
661 ),
662 });
663 };
664​
665 const removeProfile = async (id: string) => {
666 if (!settingsHydrated) return;
667 if (!removalAvailable) {
668 setProfileRemovalError("Connect to an environment before removing this profile.");
669 return;
670 }
671 setProfileRemovalError(null);
672 setProfileRemovalInFlight(true);
673 // Drop the partition's data too, otherwise a removed profile's cookies
674 // stay on disk with nothing in the UI pointing at them.
675 try {
676 await clearBrowserProfileData(
677 previewBridge,
678 environmentsReady ? environments.map((environment) => environment.environmentId) : [],
679 id,
680 );
681 } catch {
682 setProfileRemovalError("Profile data could not be deleted. Try again.");
683 setProfileRemovalInFlight(false);
684 return;
685 }
686 const currentSettings = getClientSettings();
687 updateSettings({
688 browserProfiles: currentSettings.browserProfiles.filter((profile) => profile.id !== id),
689 // Reassign the default rather than leaving it pointing at nothing.
690 ...(currentSettings.browserDefaultProfileId === id
691 ? { browserDefaultProfileId: DEFAULT_BROWSER_PROFILE_ID }
692 : {}),
693 });
694 setProfileRemovalInFlight(false);
695 setProfilePendingRemoval(null);
696 };
697​
698 return (
699 <SettingsRow
700 {...searchableSetting("browser-profiles")}
701 description="Each profile keeps its own cookies and logins, so a tab opened under one can't see another's. Incognito discards everything when the app closes."
702 control={
703 <Button
704 size="sm"
705 variant="outline"
706 disabled={profileWritesDisabled || userProfiles.length >= BROWSER_PROFILE_MAX_COUNT}
707 onClick={addProfile}
708 >
709 <PlusIcon />
710 Add profile
711 </Button>
712 }
713 >
714 {/*
715 Each profile is its own bounded row, and the list carries the bottom
716 spacing `SettingsRow` leaves to its children (`pt-3 pb-1`). Bare rows
717 stack on narrow viewports with a larger gap inside a row than between
718 rows, which reads as the remove button belonging to the profile below.
719 */}
720 <div className="mt-2 space-y-1 pb-2">
721 {resolveBrowserProfiles(userProfiles).map((profile) => {
722 const builtIn = isBuiltInBrowserProfileId(profile.id);
723 return (
724 <div
725 key={profile.id}
726 className={cn(
727 ITEM_ROW_INNER_CLASSNAME,
728 "rounded-lg border border-border/60 px-3 py-2",
729 )}
730 >
731 {builtIn ? (
732 // Dimmed here rather than on the list, which is the only
733 // content in the row without a disabled treatment of its own:
734 // a wrapper-level dim would stack with the rename field's and
735 // the remove button's, landing them near 0.41 while every
736 // other disabled control in the block sits at 0.64.
737 <span
738 className={cn(
739 "flex min-w-0 items-center gap-2 text-sm text-foreground",
740 profileWritesDisabled && "opacity-64",
741 )}
742 >
743 {profile.name}
744 <Badge variant="outline">
745 {profile.kind === "incognito" ? "Ephemeral" : "Built-in"}
746 </Badge>
747 </span>
748 ) : (
749 <DraftInput
750 nativeInput
751 size="sm"
752 className="w-full sm:w-64"
753 aria-label={`Rename ${profile.name}`}
754 disabled={profileWritesDisabled}
755 maxLength={BROWSER_PROFILE_NAME_MAX_LENGTH}
756 value={profile.name}
757 onCommit={(next) => renameProfile(profile.id, next)}
758 />
759 )}
760 {builtIn ? null : (
761 <Tooltip>
762 <TooltipTrigger
763 render={
764 <span className="inline-flex" {...(!removalAvailable ? { tabIndex: 0 } : {})}>
765 <Button
766 size="icon-xs"
767 variant="ghost-muted"
768 disabled={profileWritesDisabled || !removalAvailable}
769 aria-label={`Remove ${profile.name}`}
770 onClick={() => setProfilePendingRemoval(profile)}
771 >
772 <Trash2Icon />
773 </Button>
774 </span>
775 }
776 />
777 <TooltipPopup side="top">
778 {removalAvailable
779 ? "Remove profile and its data"
780 : "Connect to an environment to remove this profile"}
781 </TooltipPopup>
782 </Tooltip>
783 )}
784 </div>
785 );
786 })}
787 </div>
788 <AlertDialog
789 open={profilePendingRemoval !== null}
790 onOpenChange={(open) => {
791 if (!open && !profileRemovalInFlight) {
792 setProfilePendingRemoval(null);
793 setProfileRemovalError(null);
794 }
795 }}
796 >
797 <AlertDialogPopup>
798 <AlertDialogHeader>
799 <AlertDialogTitle>Remove “{profilePendingRemoval?.name}”?</AlertDialogTitle>
800 <AlertDialogDescription>
801 Its cookies, logins, and cache are deleted with it. Tabs already open in this profile
802 stay open until you close them.
803 </AlertDialogDescription>
804 {profileRemovalError ? (
805 <p aria-live="polite" className="text-sm text-destructive">
806 {profileRemovalError}
807 </p>
808 ) : null}
809 {!removalAvailable ? (
810 <p className="text-sm text-muted-foreground">
811 Connect to an environment to remove this profile and its data.
812 </p>
813 ) : null}
814 </AlertDialogHeader>
815 <AlertDialogFooter>
816 <AlertDialogClose
817 disabled={profileRemovalInFlight}
818 render={<Button variant="outline" disabled={profileRemovalInFlight} />}
819 >
820 Cancel
821 </AlertDialogClose>
822 <Button
823 variant="destructive"
824 disabled={profileRemovalInFlight || !settingsHydrated || !removalAvailable}
825 onClick={() => {
826 if (profilePendingRemoval && settingsHydrated && removalAvailable) {
827 void removeProfile(profilePendingRemoval.id);
828 }
829 }}
830 >
831 {profileRemovalInFlight ? "Removing…" : "Remove profile"}
832 </Button>
833 </AlertDialogFooter>
834 </AlertDialogPopup>
835 </AlertDialog>
836 </SettingsRow>
837 );
839​
840function BrowserDefaultProfileSetting({ disabled }: { readonly disabled: boolean }) {
841 const userProfiles = useClientSettings((settings) => settings.browserProfiles);
842 const defaultProfileId = useClientSettings((settings) => settings.browserDefaultProfileId);
843 const settingsHydrated = useClientSettingsHydrated();
844 const updateSettings = useUpdatePrimarySettings();
845 const profileWritesDisabled = disabled || !settingsHydrated;
846 // Incognito is deliberately absent: as a default it would open every tab
847 // into storage that is discarded on close.
848 const profiles = resolveBrowserProfiles(userProfiles).filter(
849 (profile) => profile.kind !== "incognito",
850 );
851 const selected = findBrowserProfile(profiles, defaultProfileId) ?? profiles[0];
852​
853 return (
854 <SettingsRow
855 {...searchableSetting("browser-default-profile")}
856 description="Profile new browser tabs open under, including tabs an agent opens."
857 resetAction={
858 !profileWritesDisabled && defaultProfileId !== DEFAULT_BROWSER_PROFILE_ID ? (
859 <SettingResetButton
860 label="default browser profile"
861 onClick={() => {
862 if (settingsHydrated) {
863 updateSettings({ browserDefaultProfileId: DEFAULT_BROWSER_PROFILE_ID });
864 }
865 }}
866 />
867 ) : null
868 }
869 control={
870 <Select
871 disabled={profileWritesDisabled}
872 value={selected?.id ?? DEFAULT_BROWSER_PROFILE_ID}
873 onValueChange={(value) => {
874 if (settingsHydrated && value !== null) {
875 updateSettings({ browserDefaultProfileId: value });
876 }
877 }}
878 >
879 <SelectTrigger size="sm" className="w-full sm:w-44" aria-label="Default browser profile">
880 <SelectValue>{selected?.name ?? "Default"}</SelectValue>
881 </SelectTrigger>
882 {/*
883 Capped and truncated like the tab menu's profile list: names are
884 user-supplied and run to 48 characters, which would otherwise
885 widen the popup to fit the longest one. The cap goes on the glass
886 shell (`popupClassName`), and the list fills that shell so it is
887 never narrower than the trigger it opens from — the same floor
888 every other settings select keeps. `ItemText` renders a block, so
889 the label must be a block too for `truncate` to apply.
890 */}
891 <SelectPopup
892 align="end"
893 alignItemWithTrigger={false}
894 popupClassName="max-w-64"
895 className="w-full"
896 >
897 {profiles.map((profile) => (
898 <SelectItem hideIndicator key={profile.id} value={profile.id}>
899 <span className="block min-w-0 truncate">{profile.name}</span>
900 </SelectItem>
901 ))}
902 </SelectPopup>
903 </Select>
904 }
905 />
906 );
908​
909export function IntegrationsSettingsPanel() {
910 // Client-local preview defaults are editable only where the preview exists.
911 const previewDefaultsDisabled = !isElectron;
912 const previewDefaults = (
913 <>
914 <BrowserProfilesSetting disabled={previewDefaultsDisabled} />
915 <BrowserDefaultProfileSetting disabled={previewDefaultsDisabled} />
916 <BrowserViewportSetting disabled={previewDefaultsDisabled} />
917 <BrowserZoomSetting disabled={previewDefaultsDisabled} />
918 <BrowserAppearanceSetting disabled={previewDefaultsDisabled} />
919 <BrowserRecordingFrameRateSetting disabled={previewDefaultsDisabled} />
920 <BrowserLinkTargetSetting disabled={previewDefaultsDisabled} />
921 <BrowserAutoShowFloatingPreviewSetting disabled={previewDefaultsDisabled} />
922 </>
923 );
924​
925 return (
926 <SettingsPageContainer>
927 <SettingsSection id="browser" title="Browser">
928 {/* Server-authoritative, so it stays editable on any client anchored to
929 a server; `serverScoped` covers the hosted app, which has none. It
930 sits outside the block covering the desktop-only defaults. */}
931 <AgentBrowserAccessSetting />
932 {previewDefaultsDisabled ? (
933 <DesktopOnlyBrowserDefaults>{previewDefaults}</DesktopOnlyBrowserDefaults>
934 ) : (
935 previewDefaults
936 )}
937 </SettingsSection>
938 </SettingsPageContainer>
939 );