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

IntegrationsSettings.tsx

1,390 lines52.4 KB

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