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

IntegrationsSettings.tsx

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