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

IntegrationsSettings.tsx

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