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

IntegrationsSettings.tsx

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