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

IntegrationsSettings.tsx

1,499 lines54.6 KB

1import { DeviceHostUpdates } from "../device/DeviceHostUpdates";
2import { DeviceToolVersions } from "../device/DeviceToolVersions";
3import { useScopedSettings, useUpdateScopedSettings } from "./useScopedSettings";
4import { ScopedSwitch } from "./ScopedSwitch";
5import { DeviceHostsSettings } from "./DeviceHostsSettings";
6import {
7 AuthSettingsWriteScope,
8 BrowserImportFailureReason,
9 BROWSER_PROFILE_MAX_COUNT,
10 type BrowserLinkTarget,
11 type BrowserProfile,
12 type EnvironmentId,
13 BROWSER_PROFILE_NAME_MAX_LENGTH,
14 BROWSER_RECORDING_FRAME_RATES,
15 DEFAULT_BROWSER_AUTO_SHOW_FLOATING_PREVIEW,
16 DEFAULT_BROWSER_PROFILE_ID,
17 DEFAULT_BROWSER_LINK_TARGET,
18 DEFAULT_BROWSER_RECORDING_FRAME_RATE,
19 DEFAULT_BROWSER_VIEWPORT,
20 DEFAULT_PREVIEW_APPEARANCE,
21 DEFAULT_PREVIEW_ZOOM_FACTOR,
22 FILL_PREVIEW_VIEWPORT,
23 PREVIEW_VIEWPORT_MAX_AREA,
24 PREVIEW_VIEWPORT_MAX_DIMENSION,
25 PREVIEW_VIEWPORT_MIN_DIMENSION,
26 PREVIEW_ZOOM_LEVELS,
27 findBrowserProfile,
28 isBuiltInBrowserProfileId,
29 resolveBrowserProfiles,
30 type BrowserImportSource,
31 type PreviewAppearancePreference,
32 type PreviewViewportSetting,
33} from "@t3tools/contracts";
34import { PREVIEW_VIEWPORT_PRESETS } from "@t3tools/shared/previewViewport";
35import { MoreVertical, Plus as PlusIcon } from "lucide-react";
36import { useCallback, useRef, useState } from "react";
37​
38import { ScreenRotationIcon } from "~/browser/ScreenRotationIcon";
39import { AnimatedHeight } from "~/components/AnimatedHeight";
40import { resolveEnvironmentOptionLabel } from "~/components/BranchToolbar.logic";
41import { previewBridge } from "~/components/preview/previewBridge";
42import { cn, randomUUID } from "~/lib/utils";
43import { useEnvironments, usePrimaryEnvironment } from "~/state/environments";
44import { deviceEnvironment, useDeviceState } from "~/state/device";
45import { readEnvironmentScope, useEnvironmentScope } from "~/state/session";
46import { useAtomCommand } from "~/state/use-atom-command";
47import { previewEnvironment } from "~/state/preview";
48import { useServerConfigs } from "~/state/entities";
49import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
50import {
51 AgentDeviceSetupStatus,
52 DeviceHubSetupStatus,
53 deviceHubReadiness,
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 interface ServerProfileData {
127 readonly environmentIds: ReadonlyArray<EnvironmentId>;
128 readonly clear: (environmentId: EnvironmentId, profileId: string) => Promise<void>;
130​
131export async function clearBrowserProfileData(
132 bridge: BrowserProfileDataBridge | null,
133 environmentIds: ReadonlyArray<EnvironmentId>,
134 profileId: string,
135 server?: ServerProfileData,
136): Promise<void> {
137 const desktopEnvironmentIds = bridge === null ? [] : environmentIds;
138 const serverEnvironmentIds = server?.environmentIds ?? [];
139 if (desktopEnvironmentIds.length === 0 && serverEnvironmentIds.length === 0) {
140 throw new Error("Browser profile data is not available to clear.");
141 }
142 await Promise.all([
143 ...desktopEnvironmentIds.flatMap((environmentId) => [
144 bridge!.clearCookies(environmentId, profileId),
145 bridge!.clearCache(environmentId, profileId),
146 ]),
147 ...serverEnvironmentIds.map((environmentId) => server!.clear(environmentId, profileId)),
148 ]);
150​
151export function browserProfileRemovalAvailable(
152 bridgeAvailable: boolean,
153 environmentsReady: boolean,
154 environmentCount: number,
155 serverBrowserCount = 0,
156): boolean {
157 return (bridgeAvailable || serverBrowserCount > 0) && environmentsReady && environmentCount > 0;
159​
160const RESPONSIVE_SEED_SIZE = { width: 1280, height: 800 } as const;
161​
162const NO_GROUPING: Intl.NumberFormatOptions = { useGrouping: false };
163​
164const APPEARANCE_LABELS: Readonly<Record<PreviewAppearancePreference, string>> = {
165 system: "System",
166 light: "Light",
167 dark: "Dark",
168};
169​
170const zoomLabel = (zoomFactor: number) => `${Math.round(zoomFactor * 100)}%`;
171​
172/**
173 * IPC flattens the failure to its message, so the reason token travels inside
174 * it. Anything unrecognised reads as a plain read failure rather than leaking
175 * the raw message into a toast.
176 */
177class ProfileLimitReachedError extends Error {
178 constructor() {
179 super("Browser profile limit reached.");
180 this.name = "ProfileLimitReachedError";
181 }
183​
184export const importFailureReason = (cause: unknown): BrowserImportFailureReason => {
185 const message = String((cause as { message?: unknown } | undefined)?.message ?? "");
186 return (
187 BrowserImportFailureReason.literals.find((reason) => message.includes(`failed: ${reason}.`)) ??
188 "readFailed"
189 );
190};
191​
192const viewportSelectValue = (viewport: PreviewViewportSetting): string => {
193 if (viewport._tag === "fill") return FILL_VALUE;
194 if (
195 viewport._tag === "preset" &&
196 PREVIEW_VIEWPORT_PRESETS.some((preset) => preset.id === viewport.presetId)
197 ) {
198 return viewport.presetId;
199 }
200 return RESPONSIVE_VALUE;
201};
202​
203/**
204 * The trigger renders this rather than a bare `SelectValue`, which would fall
205 * back to printing the raw stored value ("fill") because the options are built
206 * inline instead of from an `items` map.
207 */
208const viewportSelectLabel = (viewport: PreviewViewportSetting): string => {
209 const value = viewportSelectValue(viewport);
210 if (value === FILL_VALUE) return "Fill panel";
211 if (value === RESPONSIVE_VALUE) return "Responsive";
212 return PREVIEW_VIEWPORT_PRESETS.find((preset) => preset.id === value)?.label ?? "Responsive";
213};
214​
215const isValidDimension = (value: number) =>
216 Number.isInteger(value) &&
217 value >= PREVIEW_VIEWPORT_MIN_DIMENSION &&
218 value <= PREVIEW_VIEWPORT_MAX_DIMENSION;
219​
220const rotateViewport = (
221 viewport: Exclude<PreviewViewportSetting, { readonly _tag: "fill" }>,
222): PreviewViewportSetting => ({
223 ...viewport,
224 width: viewport.height,
225 height: viewport.width,
226});
227​
228function BrowserViewportSetting({ disabled }: { readonly disabled: boolean }) {
229 const viewport = useClientSettings((settings) => settings.browserDefaultViewport);
230 const updateSettings = useUpdatePrimarySettings();
231​
232 const sized = viewport._tag === "fill" ? null : viewport;
233 const presentedSize = {
234 width: sized?.width ?? RESPONSIVE_SEED_SIZE.width,
235 height: sized?.height ?? RESPONSIVE_SEED_SIZE.height,
236 };
237​
238 const selectViewport = (value: string | null) => {
239 if (value === FILL_VALUE) {
240 updateSettings({ browserDefaultViewport: FILL_PREVIEW_VIEWPORT });
241 return;
242 }
243 if (value === RESPONSIVE_VALUE) {
244 updateSettings({
245 browserDefaultViewport: {
246 _tag: "freeform",
247 width: sized?.width ?? RESPONSIVE_SEED_SIZE.width,
248 height: sized?.height ?? RESPONSIVE_SEED_SIZE.height,
249 },
250 });
251 return;
252 }
253 const preset = PREVIEW_VIEWPORT_PRESETS.find((candidate) => candidate.id === value);
254 if (!preset) return;
255 updateSettings({
256 browserDefaultViewport: {
257 _tag: "preset",
258 width: preset.width,
259 height: preset.height,
260 presetId: preset.id,
261 },
262 });
263 };
264​
265 // Committed on blur rather than per keystroke: typing "2560" passes through
266 // "256", which is a legal dimension, so an onValueChange handler would
267 // persist that intermediate size and churn the settings file on every key.
268 const commitDimension = (axis: "width" | "height", value: number | null) => {
269 if (value === null || !isValidDimension(value)) return;
270 const next = { ...presentedSize, [axis]: value };
271 if (next.width * next.height > PREVIEW_VIEWPORT_MAX_AREA) return;
272 if (sized && next.width === sized.width && next.height === sized.height) return;
273 updateSettings({ browserDefaultViewport: { _tag: "freeform", ...next } });
274 };
275​
276 return (
277 <SettingsRow
278 {...searchableSetting("browser-default-viewport")}
279 description="Tab size for you and agents. Fill fits the panel; other sizes show the device toolbar."
280 resetAction={
281 !disabled && viewport._tag !== DEFAULT_BROWSER_VIEWPORT._tag ? (
282 <SettingResetButton
283 label="default browser viewport"
284 onClick={() => updateSettings({ browserDefaultViewport: DEFAULT_BROWSER_VIEWPORT })}
285 />
286 ) : null
287 }
288 control={
289 <div className="flex w-full flex-wrap items-center justify-end gap-2 sm:w-auto">
290 <Select
291 value={viewportSelectValue(viewport)}
292 onValueChange={selectViewport}
293 disabled={disabled}
294 >
295 <SelectTrigger
296 size="sm"
297 className="w-full min-w-0 sm:w-44"
298 aria-label="Default browser viewport"
299 >
300 <SelectValue>{viewportSelectLabel(viewport)}</SelectValue>
301 </SelectTrigger>
302 <SelectPopup align="end" alignItemWithTrigger={false}>
303 <SelectItem value={FILL_VALUE}>Fill panel</SelectItem>
304 <SelectItem value={RESPONSIVE_VALUE}>Responsive</SelectItem>
305 <SelectGroup>
306 <SelectGroupLabel>Standard</SelectGroupLabel>
307 {PREVIEW_VIEWPORT_PRESETS.map((preset) => (
308 <SelectItem key={preset.id} value={preset.id}>
309 <span className="flex w-full items-center justify-between gap-5">
310 <span>{preset.label}</span>
311 <span className="text-xs tabular-nums text-muted-foreground">
312 {preset.detail}
313 </span>
314 </span>
315 </SelectItem>
316 ))}
317 </SelectGroup>
318 </SelectPopup>
319 </Select>
320​
321 {sized ? (
322 <div className="flex min-w-0 items-center gap-1">
323 <NumberField
324 value={presentedSize.width}
325 min={PREVIEW_VIEWPORT_MIN_DIMENSION}
326 max={PREVIEW_VIEWPORT_MAX_DIMENSION}
327 disabled={disabled}
328 format={NO_GROUPING}
329 size="sm"
330 className="w-20"
331 onValueCommitted={(value) => commitDimension("width", value)}
332 >
333 <NumberFieldGroup>
334 <NumberFieldInput aria-label="Default viewport width" />
335 </NumberFieldGroup>
336 </NumberField>
337 <span className="text-xs text-muted-foreground">×</span>
338 <NumberField
339 value={presentedSize.height}
340 min={PREVIEW_VIEWPORT_MIN_DIMENSION}
341 max={PREVIEW_VIEWPORT_MAX_DIMENSION}
342 disabled={disabled}
343 format={NO_GROUPING}
344 size="sm"
345 className="w-20"
346 onValueCommitted={(value) => commitDimension("height", value)}
347 >
348 <NumberFieldGroup>
349 <NumberFieldInput aria-label="Default viewport height" />
350 </NumberFieldGroup>
351 </NumberField>
352 <Tooltip>
353 <TooltipTrigger
354 render={
355 <Button
356 size="icon-sm"
357 variant="ghost-muted"
358 disabled={disabled}
359 aria-label={`Rotate to ${
360 presentedSize.height >= presentedSize.width ? "landscape" : "portrait"
361 }`}
362 onClick={() =>
363 updateSettings({ browserDefaultViewport: rotateViewport(sized) })
364 }
365 >
366 <ScreenRotationIcon />
367 </Button>
368 }
369 />
370 <TooltipPopup side="top">Rotate</TooltipPopup>
371 </Tooltip>
372 </div>
373 ) : null}
374 </div>
375 }
376 />
377 );
379​
380function BrowserZoomSetting({ disabled }: { readonly disabled: boolean }) {
381 const zoomFactor = useClientSettings((settings) => settings.browserDefaultZoomFactor);
382 const updateSettings = useUpdatePrimarySettings();
383​
384 return (
385 <SettingsRow
386 {...searchableSetting("browser-default-zoom")}
387 description="Page zoom applied to new browser tabs."
388 resetAction={
389 !disabled && zoomFactor !== DEFAULT_PREVIEW_ZOOM_FACTOR ? (
390 <SettingResetButton
391 label="default browser zoom"
392 onClick={() =>
393 updateSettings({ browserDefaultZoomFactor: DEFAULT_PREVIEW_ZOOM_FACTOR })
394 }
395 />
396 ) : null
397 }
398 control={
399 <Select
400 disabled={disabled}
401 value={String(zoomFactor)}
402 onValueChange={(value) => {
403 const next = PREVIEW_ZOOM_LEVELS.find((level) => String(level) === value);
404 if (next !== undefined) updateSettings({ browserDefaultZoomFactor: next });
405 }}
406 >
407 <SelectTrigger size="sm" className="w-full sm:w-40" aria-label="Default browser zoom">
408 <SelectValue>{zoomLabel(zoomFactor)}</SelectValue>
409 </SelectTrigger>
410 <SelectPopup align="end" alignItemWithTrigger={false}>
411 {PREVIEW_ZOOM_LEVELS.map((level) => (
412 <SelectItem hideIndicator key={level} value={String(level)}>
413 {zoomLabel(level)}
414 </SelectItem>
415 ))}
416 </SelectPopup>
417 </Select>
418 }
419 />
420 );
422​
423function BrowserAppearanceSetting({ disabled }: { readonly disabled: boolean }) {
424 const appearance = useClientSettings((settings) => settings.browserDefaultAppearance);
425 const updateSettings = useUpdatePrimarySettings();
426​
427 return (
428 <SettingsRow
429 {...searchableSetting("browser-default-appearance")}
430 description="The color scheme pages are told to prefer. System follows your OS setting."
431 resetAction={
432 !disabled && appearance !== DEFAULT_PREVIEW_APPEARANCE ? (
433 <SettingResetButton
434 label="default browser appearance"
435 onClick={() => updateSettings({ browserDefaultAppearance: DEFAULT_PREVIEW_APPEARANCE })}
436 />
437 ) : null
438 }
439 control={
440 <Select
441 disabled={disabled}
442 value={appearance}
443 onValueChange={(value) => {
444 if (value === "system" || value === "light" || value === "dark") {
445 updateSettings({ browserDefaultAppearance: value });
446 }
447 }}
448 >
449 <SelectTrigger
450 size="sm"
451 className="w-full sm:w-40"
452 aria-label="Default browser appearance"
453 >
454 <SelectValue>{APPEARANCE_LABELS[appearance]}</SelectValue>
455 </SelectTrigger>
456 <SelectPopup align="end" alignItemWithTrigger={false}>
457 {Object.entries(APPEARANCE_LABELS).map(([value, label]) => (
458 <SelectItem hideIndicator key={value} value={value}>
459 {label}
460 </SelectItem>
461 ))}
462 </SelectPopup>
463 </Select>
464 }
465 />
466 );
468​
469function BrowserRecordingInputSettings({ disabled }: { readonly disabled: boolean }) {
470 const showKeys = useClientSettings((settings) => settings.browserRecordingShowKeyPresses);
471 const showMouse = useClientSettings((settings) => settings.browserRecordingShowMousePresses);
472 const updateSettings = useUpdatePrimarySettings();
473 return (
474 <>
475 <SettingsRow
476 {...searchableSetting("browser-recording-key-presses")}
477 description="Show pressed keys and shortcuts in new recordings. Password fields are excluded."
478 control={
479 <Switch
480 disabled={disabled}
481 checked={showKeys}
482 aria-label="Show key presses in recordings"
483 onCheckedChange={(checked) =>
484 updateSettings({ browserRecordingShowKeyPresses: Boolean(checked) })
485 }
486 />
487 }
488 />
489 <SettingsRow
490 {...searchableSetting("browser-recording-mouse-presses")}
491 description="Highlight mouse presses and held buttons in new recordings."
492 control={
493 <Switch
494 disabled={disabled}
495 checked={showMouse}
496 aria-label="Show mouse presses in recordings"
497 onCheckedChange={(checked) =>
498 updateSettings({ browserRecordingShowMousePresses: Boolean(checked) })
499 }
500 />
501 }
502 />
503 </>
504 );
506​
507function BrowserRecordingFrameRateSetting({ disabled }: { readonly disabled: boolean }) {
508 const frameRate = useClientSettings((settings) => settings.browserRecordingFrameRate);
509 const updateSettings = useUpdatePrimarySettings();
510​
511 return (
512 <SettingsRow
513 {...searchableSetting("browser-recording-frame-rate")}
514 description="Maximum recording rate. 30 fps saves CPU and storage; 60 fps is smoother."
515 resetAction={
516 !disabled && frameRate !== DEFAULT_BROWSER_RECORDING_FRAME_RATE ? (
517 <SettingResetButton
518 label="browser recording frame rate"
519 onClick={() =>
520 updateSettings({ browserRecordingFrameRate: DEFAULT_BROWSER_RECORDING_FRAME_RATE })
521 }
522 />
523 ) : null
524 }
525 control={
526 <Select
527 disabled={disabled}
528 value={String(frameRate)}
529 onValueChange={(value) => {
530 const next = BROWSER_RECORDING_FRAME_RATES.find((rate) => String(rate) === value);
531 if (next !== undefined) {
532 updateSettings({ browserRecordingFrameRate: next });
533 }
534 }}
535 >
536 <SelectTrigger
537 size="sm"
538 className="w-full sm:w-40"
539 aria-label="Browser recording frame rate"
540 >
541 <SelectValue>{frameRate} fps</SelectValue>
542 </SelectTrigger>
543 <SelectPopup align="end" alignItemWithTrigger={false}>
544 {BROWSER_RECORDING_FRAME_RATES.map((rate) => (
545 <SelectItem hideIndicator key={rate} value={String(rate)}>
546 {rate} fps
547 </SelectItem>
548 ))}
549 </SelectPopup>
550 </Select>
551 }
552 />
553 );
555​
556const LINK_TARGET_LABELS: Readonly<Record<BrowserLinkTarget, string>> = {
557 system: "Your default browser",
558 app: "T3 Code",
559};
560​
561function BrowserLinkTargetSetting({ disabled }: { readonly disabled: boolean }) {
562 const linkTarget = useClientSettings((settings) => settings.browserLinkTarget);
563 const updateSettings = useUpdatePrimarySettings();
564​
565 return (
566 <SettingsRow
567 {...searchableSetting("browser-link-target")}
568 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."
569 resetAction={
570 !disabled && linkTarget !== DEFAULT_BROWSER_LINK_TARGET ? (
571 <SettingResetButton
572 label="link target"
573 onClick={() => updateSettings({ browserLinkTarget: DEFAULT_BROWSER_LINK_TARGET })}
574 />
575 ) : null
576 }
577 control={
578 <Select
579 disabled={disabled}
580 value={linkTarget}
581 onValueChange={(value) => {
582 if (value === "system" || value === "app") {
583 updateSettings({ browserLinkTarget: value });
584 }
585 }}
586 >
587 <SelectTrigger size="sm" className="w-full sm:w-40" aria-label="Open links in">
588 <SelectValue>{LINK_TARGET_LABELS[linkTarget]}</SelectValue>
589 </SelectTrigger>
590 <SelectPopup align="end" alignItemWithTrigger={false}>
591 {(Object.keys(LINK_TARGET_LABELS) as ReadonlyArray<BrowserLinkTarget>).map((target) => (
592 <SelectItem hideIndicator key={target} value={target}>
593 {LINK_TARGET_LABELS[target]}
594 </SelectItem>
595 ))}
596 </SelectPopup>
597 </Select>
598 }
599 />
600 );
602​
603function PullRequestLinksOpenInAppSetting() {
604 const openInApp = useClientSettings((settings) => settings.pullRequestLinksOpenInApp);
605 const updateSettings = useUpdatePrimarySettings();
606​
607 return (
608 <SettingsRow
609 {...searchableSetting("pull-request-links-open-in-app")}
610 description="Clicking a pull request link opens it in T3 Code. Turn off to open pull request links like any other link, on GitHub or your git host."
611 resetAction={
612 openInApp ? null : (
613 <SettingResetButton
614 label="open pull requests in T3 Code"
615 onClick={() => updateSettings({ pullRequestLinksOpenInApp: true })}
616 />
617 )
618 }
619 control={
620 <Switch
621 checked={openInApp}
622 onCheckedChange={(checked) =>
623 updateSettings({ pullRequestLinksOpenInApp: Boolean(checked) })
624 }
625 aria-label="Open pull requests in T3 Code"
626 />
627 }
628 />
629 );
631​
632function DeviceIntegrationSettings() {
633 const { search, environment: selected } = useSettingsScope();
634 const settings = useScopedSettings();
635 const connected = selected?.connection.phase === "connected" && selected.serverConfig !== null;
636 const environmentId = connected ? selected.environmentId : null;
637​
638 return (
639 <SettingsSection id="devices" title="Devices">
640 <DeviceIntegrationControls
641 key={`${environmentId}:${JSON.stringify(search)}`}
642 environmentId={environmentId}
643 enabled={settings.enableDeviceSupport}
644 agentAccessEnabled={settings.enableAgentDeviceAccess}
645 />
646 </SettingsSection>
647 );
649​
650function DeviceIntegrationControls({
651 environmentId,
652 enabled,
653 agentAccessEnabled,
654}: {
655 environmentId: EnvironmentId | null;
656 enabled: boolean;
657 agentAccessEnabled: boolean;
658}) {
659 const canConfigure = useEnvironmentScope(environmentId, AuthSettingsWriteScope);
660 const { state, loaded } = useDeviceState(environmentId);
661 const { scope, environments, connectedEnvironments } = useSettingsScope();
662 const updateSettings = useUpdateScopedSettings();
663 const projectScope = scope.kind === "project" || scope.kind === "checkout";
664 const anyHubEnabled = connectedEnvironments.some(
665 (environment) => environment.serverConfig?.settings.enableDeviceSupport,
666 );
667 const configure = useAtomCommand(deviceEnvironment.configure, { reportFailure: false });
668 const list = useAtomCommand(deviceEnvironment.list, { reportFailure: false });
669 const [pending, setPending] = useState<
670 "hub" | "check" | "agent" | "update-hub" | "update-agent" | null
671 >(null);
672 const { ready: hubReady, busy } = deviceHubReadiness(state);
673 const localPlatformsUnavailable = state.hosts.some(
674 (host) => host.kind === "local" && !host.platforms.some((platform) => platform.available),
675 );
676 const [platformsRevealed, setPlatformsRevealed] = useState(false);
677 if (platformsRevealed && !enabled) setPlatformsRevealed(false);
678 if (
679 enabled &&
680 !platformsRevealed &&
681 (hubReady || localPlatformsUnavailable) &&
682 pending !== "hub"
683 ) {
684 setPlatformsRevealed(true);
685 }
686​
687 const update = async (
688 kind: NonNullable<typeof pending>,
689 input: { enabled?: boolean; agentAccessEnabled?: boolean },
690 ) => {
691 if (!environmentId || !readEnvironmentScope(environmentId, AuthSettingsWriteScope)) return;
692 setPending(kind);
693 try {
694 const results = await Promise.allSettled(
695 environments.map(async (environment) => {
696 if (environment.connection.phase !== "connected" || !environment.serverConfig) {
697 throw new Error("Environment disconnected");
698 }
699 if (!readEnvironmentScope(environment.environmentId, AuthSettingsWriteScope)) {
700 throw new Error("This connection cannot change device settings.");
701 }
702 return configure({
703 environmentId: environment.environmentId,
704 input: { ...input, ...(input.enabled ? { onboardingCompleted: true } : {}) },
705 });
706 }),
707 );
708 const failed = environments.filter((_, index) => {
709 const result = results[index];
710 return result?.status !== "fulfilled" || result.value._tag === "Failure";
711 });
712 if (failed.length > 0) {
713 toastManager.add({
714 type: "error",
715 title: "Device settings not saved on all environments",
716 description: `Could not update ${failed.map((environment) => environment.label).join(", ")}.`,
717 });
718 }
719 } finally {
720 setPending(null);
721 }
722 };
723​
724 const [updateError, setUpdateError] = useState<{ tool: "hub" | "agent"; message: string } | null>(
725 null,
726 );
727 const localTools = state.hosts.find((host) => host.kind === "local")?.tools;
728 const versionActions = (tool: "hub" | "agent") => {
729 const version = localTools?.[tool];
730 const needsUpdate = version && !version.installedVersions.includes(version.requiredVersion);
731 return (
732 <div className="space-y-2">
733 <div className="flex flex-wrap gap-2">
734 {state.supportsToolUpdate && needsUpdate ? (
735 <Button
736 size="sm"
737 disabled={!environmentId || pending !== null || busy}
738 onClick={() => {
739 if (!environmentId) return;
740 setUpdateError(null);
741 setPending(`update-${tool}`);
742 void list({ environmentId, input: { updateTool: tool } })
743 .then((result) => {
744 if (result._tag === "Failure")
745 setUpdateError({
746 tool,
747 message:
748 "Update failed. Check this host's network connection and try again.",
749 });
750 })
751 .finally(() => setPending(null));
752 }}
753 >
754 {pending === `update-${tool}` ? "Updating…" : `Update to v${version.requiredVersion}`}
755 </Button>
756 ) : null}
757 {state.supportsToolInspection ? (
758 <Button
759 size="sm"
760 variant="outline"
761 disabled={!environmentId || pending !== null || busy}
762 onClick={() => {
763 if (!environmentId) return;
764 setPending("check");
765 void list({ environmentId, input: { inspectOnly: true } }).finally(() =>
766 setPending(null),
767 );
768 }}
769 >
770 {pending === "check" ? "Checking…" : "Check versions"}
771 </Button>
772 ) : null}
773 </div>
774 {updateError?.tool === tool ? (
775 <p role="alert" className="text-xs text-destructive">
776 {updateError.message}
777 </p>
778 ) : null}
779 </div>
780 );
781 };
782​
783 return (
784 <>
785 <SettingsRow
786 {...searchableSetting("device-hub")}
787 serverScoped
788 settingKeys={["enableDeviceSupport"]}
789 description={deviceHubDescription}
790 control={
791 <>
792 <DeviceToolVersions
793 action={versionActions("hub")}
794 kind="hub"
795 tools={state.hosts.find((host) => host.kind === "local")?.tools}
796 />
797 {pending === "hub" ? <DeviceHubSetupStatus state={state} pending compact /> : null}
798 <ScopedSwitch
799 settingKeys={["enableDeviceSupport"]}
800 checked={enabled}
801 disabled={
802 !canConfigure ||
803 projectScope ||
804 !loaded ||
805 !environmentId ||
806 busy ||
807 pending !== null
808 }
809 aria-label="Device hub"
810 onCheckedChange={(checked) =>
811 void update("hub", {
812 enabled: Boolean(checked),
813 ...(checked ? {} : { agentAccessEnabled: false }),
814 })
815 }
816 />
817 </>
818 }
819 />
820 <AnimatedHeight>
821 {platformsRevealed ? (
822 <SettingsRow
823 {...searchableSetting("device-platform-support")}
824 description={
825 connectedEnvironments.length > 1
826 ? `Status for ${connectedEnvironments.find((environment) => environment.environmentId === environmentId)?.label}. Select an environment to inspect its simulator support.`
827 : undefined
828 }
829 status={
830 <div className="flex flex-wrap gap-x-5 gap-y-2">
831 <PlatformStatus compact platform="iOS" status={platformSetupStatus(state, "ios")} />
832 <PlatformStatus
833 compact
834 platform="Android"
835 status={platformSetupStatus(state, "android")}
836 />
837 </div>
838 }
839 control={
840 <Button
841 size="sm"
842 variant="outline"
843 disabled={!environmentId || !enabled || busy || pending !== null}
844 onClick={() => {
845 if (!environmentId) return;
846 setPending("check");
847 void list({ environmentId, input: {} }).finally(() => setPending(null));
848 }}
849 >
850 {pending === "check" ? "Checking…" : "Refresh"}
851 </Button>
852 }
853 />
854 ) : null}
855 </AnimatedHeight>
856 <SettingsRow
857 {...searchableSetting("agent-device-access")}
858 serverScoped
859 settingKeys={["enableAgentDeviceAccess"]}
860 description={agentDeviceDescription}
861 control={
862 <>
863 <DeviceToolVersions
864 action={versionActions("agent")}
865 kind="agent"
866 tools={state.hosts.find((host) => host.kind === "local")?.tools}
867 />
868 {pending === "agent" ? <AgentDeviceSetupStatus state={state} pending compact /> : null}
869 <ScopedSwitch
870 settingKeys={["enableAgentDeviceAccess"]}
871 checked={agentAccessEnabled}
872 disabled={
873 !canConfigure ||
874 connectedEnvironments.length === 0 ||
875 (!projectScope && (!loaded || !anyHubEnabled || busy)) ||
876 pending !== null
877 }
878 aria-label="Agent device access"
879 onCheckedChange={(checked) =>
880 projectScope
881 ? updateSettings({ enableAgentDeviceAccess: Boolean(checked) })
882 : void update("agent", { agentAccessEnabled: Boolean(checked) })
883 }
884 />
885 </>
886 }
887 />
888 {environmentId ? (
889 <DeviceHostUpdates
890 state={{ ...state, hosts: state.hosts.filter((host) => host.kind === "local") }}
891 environmentId={environmentId}
892 />
893 ) : null}
894 <DeviceHostsSettings environmentId={environmentId} />
895 </>
896 );
898​
899function BrowserAutoShowFloatingPreviewSetting({ disabled }: { readonly disabled: boolean }) {
900 const autoShow = useClientSettings((settings) => settings.browserAutoShowFloatingPreview);
901 const updateSettings = useUpdatePrimarySettings();
902​
903 return (
904 <SettingsRow
905 {...searchableSetting("browser-auto-show-floating-preview")}
906 description="Show the floating preview when an agent opens a browser or device unless the agent says otherwise."
907 resetAction={
908 !disabled && autoShow !== DEFAULT_BROWSER_AUTO_SHOW_FLOATING_PREVIEW ? (
909 <SettingResetButton
910 label="auto-show floating preview"
911 onClick={() =>
912 updateSettings({
913 browserAutoShowFloatingPreview: DEFAULT_BROWSER_AUTO_SHOW_FLOATING_PREVIEW,
914 })
915 }
916 />
917 ) : null
918 }
919 control={
920 <Switch
921 disabled={disabled}
922 checked={autoShow}
923 onCheckedChange={(checked) =>
924 updateSettings({ browserAutoShowFloatingPreview: Boolean(checked) })
925 }
926 aria-label="Auto-show floating preview"
927 />
928 }
929 />
930 );
932​
933function BrowserProfilesSetting({ disabled }: { readonly disabled: boolean }) {
934 const userProfiles = useClientSettings((settings) => settings.browserProfiles);
935 const defaultProfileId = useClientSettings((settings) => settings.browserDefaultProfileId);
936 const settingsHydrated = useClientSettingsHydrated();
937 const updateSettings = useUpdatePrimarySettings();
938 const { environments, isReady: environmentsReady } = useEnvironments();
939 const primaryEnvironment = usePrimaryEnvironment();
940 const [sources, setSources] = useState<ReadonlyArray<BrowserImportSource> | null>(null);
941 const [importSession, setImportSession] = useState<{
942 readonly source: BrowserImportSource;
943 readonly environmentId: EnvironmentId;
944 readonly environmentName: string;
945 } | null>(null);
946 const [profilePendingRemoval, setProfilePendingRemoval] = useState<BrowserProfile | null>(null);
947 const [profilePendingClear, setProfilePendingClear] = useState<BrowserProfile | null>(null);
948 const [profileRemovalError, setProfileRemovalError] = useState<string | null>(null);
949 const [profileRemovalInFlight, setProfileRemovalInFlight] = useState(false);
950 const serverConfigs = useServerConfigs();
951 const runClearServerProfile = useAtomCommand(previewEnvironment.clearProfile, {
952 reportFailure: false,
953 });
954 const serverProfileData: ServerProfileData = {
955 environmentIds: environments
956 .map((environment) => environment.environmentId)
957 .filter(
958 (environmentId) =>
959 serverConfigs.get(environmentId)?.environment.capabilities.serverBrowser === true,
960 ),
961 clear: async (environmentId, profileId) => {
962 const result = await runClearServerProfile({ environmentId, input: { profileId } });
963 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
964 },
965 };
966 const removalAvailable = browserProfileRemovalAvailable(
967 previewBridge !== null,
968 environmentsReady,
969 environments.length,
970 serverProfileData.environmentIds.length,
971 );
972 const importInFlightRef = useRef(false);
973 const [importInFlight, setImportInFlight] = useState(false);
974 const profileWritesDisabled = disabled || !settingsHydrated;
975​
976 const profiles = resolveBrowserProfiles(userProfiles);
977 const listedProfiles = profiles.filter((profile) => profile.kind !== "incognito");
978 const resolvedDefaultId =
979 findBrowserProfile(listedProfiles, defaultProfileId)?.id ?? DEFAULT_BROWSER_PROFILE_ID;
980​
981 const createProfile = (baseName: string) => {
982 if (!settingsHydrated || importInFlightRef.current) return undefined;
983 const currentProfiles = getClientSettings().browserProfiles;
984 // Checked against the live settings, not the rendered list: two clicks
985 // before a re-render would otherwise both pass the disabled control.
986 if (currentProfiles.length >= BROWSER_PROFILE_MAX_COUNT) return undefined;
987 const resolvedProfiles = resolveBrowserProfiles(currentProfiles);
988 const taken = new Set(resolvedProfiles.map((profile) => profile.name));
989 let name = baseName;
990 for (let index = 2; taken.has(name); index += 1) name = `${baseName} ${index}`;
991 const profile = { id: `profile-${randomUUID()}`, name, kind: "persistent" as const };
992 updateSettings({ browserProfiles: [...currentProfiles, profile] });
993 return profile;
994 };
995​
996 const renameProfile = (id: string, next: string) => {
997 if (!settingsHydrated || importInFlightRef.current) return;
998 const name = next.trim().slice(0, BROWSER_PROFILE_NAME_MAX_LENGTH);
999 if (name === "") return;
1000 const currentProfiles = getClientSettings().browserProfiles;
1001 updateSettings({
1002 browserProfiles: currentProfiles.map((profile) =>
1003 profile.id === id ? { ...profile, name } : profile,
1004 ),
1005 });
1006 };
1007​
1008 const clearProfileData = (id: string, name: string) => {
1009 if (!settingsHydrated || importInFlightRef.current) return;
1010 if (!removalAvailable) {
1011 toastManager.add({
1012 type: "error",
1013 title: `Could not clear ${name}'s data`,
1014 description: "You're not connected to a server yet.",
1015 });
1016 return;
1018 void clearBrowserProfileData(
1019 previewBridge,
1020 environments.map((environment) => environment.environmentId),
1021 id,
1022 serverProfileData,
1024 .then(() => {
1025 toastManager.add({ type: "success", title: `Cleared ${name}'s cookies and cache` });
1026 })
1027 .catch(() => {
1028 toastManager.add({ type: "error", title: `Could not clear ${name}'s data` });
1029 });
1030 };
1031​
1032 const removeProfile = async (id: string) => {
1033 if (!settingsHydrated || importInFlightRef.current) return;
1034 if (!removalAvailable) {
1035 setProfileRemovalError("Connect to an environment before removing this profile.");
1036 return;
1038 setProfileRemovalError(null);
1039 setProfileRemovalInFlight(true);
1040 try {
1041 await clearBrowserProfileData(
1042 previewBridge,
1043 environmentsReady ? environments.map((environment) => environment.environmentId) : [],
1044 id,
1045 serverProfileData,
1046 );
1047 } catch {
1048 setProfileRemovalError("Profile data could not be deleted. Try again.");
1049 setProfileRemovalInFlight(false);
1050 return;
1052 const currentSettings = getClientSettings();
1053 updateSettings({
1054 browserProfiles: currentSettings.browserProfiles.filter((profile) => profile.id !== id),
1055 ...(currentSettings.browserDefaultProfileId === id
1056 ? { browserDefaultProfileId: DEFAULT_BROWSER_PROFILE_ID }
1057 : {}),
1058 });
1059 setProfileRemovalInFlight(false);
1060 setProfilePendingRemoval(null);
1061 };
1062​
1063 const importableSources = (sources ?? []).filter(
1064 (source) =>
1065 source.unavailable !== "notInstalled" && source.unavailable !== "unsupportedPlatform",
1066 );
1067​
1068 const loadSources = useCallback(() => {
1069 if (!previewBridge) return;
1070 void previewBridge
1071 .listBrowserImportSources()
1072 .then(setSources)
1073 .catch(() => setSources((previous) => previous ?? []));
1074 }, []);
1075​
1076 const runWizardImport = async (
1077 source: BrowserImportSource,
1078 environmentId: EnvironmentId,
1079 input: { readonly sourceProfileDirectory: string; readonly target: WizardTarget },
1080 ): Promise<ImportOutcome> => {
1081 if (!previewBridge) return { kind: "blocked", reason: "sessionUnavailable" };
1082 if (!settingsHydrated) return { kind: "blocked", reason: "sessionUnavailable" };
1083 if (
1084 input.target.kind === "existing" &&
1085 !resolveBrowserProfiles(getClientSettings().browserProfiles).some(
1086 (profile) => profile.id === input.target.profileId,
1088 ) {
1089 return { kind: "blocked", reason: "readFailed" };
1091 if (importInFlightRef.current) return { kind: "blocked", reason: "readFailed" };
1092 importInFlightRef.current = true;
1093 setImportInFlight(true);
1094 try {
1095 const result = await previewBridge.importBrowserCookies({
1096 environmentId,
1097 sourceId: source.id,
1098 sourceProfileDirectory: input.sourceProfileDirectory,
1099 targetProfileId: input.target.profileId,
1100 });
1101 if (
1102 input.target.kind === "existing" &&
1103 !resolveBrowserProfiles(getClientSettings().browserProfiles).some(
1104 (profile) => profile.id === input.target.profileId,
1106 ) {
1107 return { kind: "blocked", reason: "readFailed" };
1109 let targetName: string;
1110 if (input.target.kind === "new") {
1111 if (result.imported > 0) {
1112 try {
1113 const persisted = await persistClientSettingsUpdate((current) => {
1114 const existing = current.browserProfiles.find(
1115 (profile) => profile.id === input.target.profileId,
1116 );
1117 if (existing) return current;
1118 // The wizard refuses a new target at the cap, but the cap can be
1119 // reached while the import runs; the updater sees the newest
1120 // settings, so this is the check that holds.
1121 if (current.browserProfiles.length >= BROWSER_PROFILE_MAX_COUNT) {
1122 throw new ProfileLimitReachedError();
1124 const taken = new Set(
1125 resolveBrowserProfiles(current.browserProfiles).map((profile) => profile.name),
1126 );
1127 let name = source.name;
1128 for (let index = 2; taken.has(name); index += 1) name = `${source.name} ${index}`;
1129 return {
1130 ...current,
1131 browserProfiles: [
1132 ...current.browserProfiles,
1133 { id: input.target.profileId, name, kind: "persistent" as const },
1134 ],
1135 };
1136 });
1137 targetName =
1138 persisted.browserProfiles.find((profile) => profile.id === input.target.profileId)
1139 ?.name ?? source.name;
1140 } catch (cause) {
1141 // This target id belongs only to the attempted new profile. Clear
1142 // its partition so a failed registration cannot strand imported
1143 // cookies behind a profile that disappears on restart.
1144 await clearBrowserProfileData(
1145 previewBridge,
1146 [environmentId],
1147 input.target.profileId,
1148 ).catch(() => undefined);
1149 const reason =
1150 cause instanceof ProfileLimitReachedError ? "profileLimitReached" : "profileNotSaved";
1151 throw new Error(`Importing cookies from ${source.id} failed: ${reason}.`, { cause });
1153 } else {
1154 targetName = source.name;
1156 } else {
1157 targetName = input.target.name;
1159 return {
1160 kind: "imported",
1161 imported: result.imported,
1162 skipped: result.skipped,
1163 skippedDomains: result.skippedDomains,
1164 targetName,
1165 };
1166 } catch (cause) {
1167 return { kind: "blocked", reason: importFailureReason(cause) };
1168 } finally {
1169 importInFlightRef.current = false;
1170 setImportInFlight(false);
1172 };
1173​
1174 const refreshImportSource = async (
1175 sourceId: BrowserImportSource["id"],
1176 ): Promise<BrowserImportSource | undefined> => {
1177 if (!previewBridge) return undefined;
1178 try {
1179 const latest = await previewBridge.listBrowserImportSources();
1180 setSources(latest);
1181 return latest.find((source) => source.id === sourceId);
1182 } catch {
1183 return undefined;
1185 };
1186​
1187 const atProfileLimit = userProfiles.length >= BROWSER_PROFILE_MAX_COUNT;
1188​
1189 return (
1190 <SettingsRow
1191 {...searchableSetting("browser-profiles")}
1192 description="Profiles separate cookies and logins. Incognito data is cleared when the app closes."
1193 control={
1194 <Menu onOpenChange={(open) => open && loadSources()}>
1195 <MenuTrigger
1196 render={
1197 <Button
1198 size="sm"
1199 variant="outline"
1200 disabled={profileWritesDisabled || importInFlight}
1201 />
1204 <PlusIcon />
1205 Add profile
1206 </MenuTrigger>
1207 <MenuPopup align="end">
1208 <MenuItem
1209 disabled={!settingsHydrated || atProfileLimit}
1210 onClick={() => createProfile("New profile")}
1212 Blank profile
1213 </MenuItem>
1214 {atProfileLimit ? (
1215 <MenuItem disabled>You&rsquo;ve reached the profile limit</MenuItem>
1216 ) : null}
1217 <MenuSeparator />
1218 <MenuGroup>
1219 <MenuGroupLabel>Import from</MenuGroupLabel>
1220 {sources === null ? (
1221 <MenuItem disabled>Looking for browsers…</MenuItem>
1222 ) : importableSources.length === 0 ? (
1223 <MenuItem disabled>No supported browsers found</MenuItem>
1224 ) : (
1225 <>
1226 {importableSources.map((source) => (
1227 <MenuItem
1228 key={source.id}
1229 disabled={!settingsHydrated || primaryEnvironment == null}
1230 onClick={() => {
1231 if (!settingsHydrated || primaryEnvironment == null) return;
1232 setImportSession({
1233 source,
1234 environmentId: primaryEnvironment.environmentId,
1235 environmentName: resolveEnvironmentOptionLabel({
1236 isPrimary: true,
1237 environmentId: primaryEnvironment.environmentId,
1238 runtimeLabel: primaryEnvironment.label,
1239 }),
1240 });
1241 }}
1243 {source.name}
1244 </MenuItem>
1245 ))}
1246 {primaryEnvironment == null ? (
1247 <MenuItem disabled>Connect to an environment to import cookies</MenuItem>
1248 ) : null}
1249 </>
1250 )}
1251 </MenuGroup>
1252 </MenuPopup>
1253 </Menu>
1256 <div className="mt-2 mb-2 overflow-hidden rounded-lg border border-border/60">
1257 {listedProfiles.map((profile, index) => {
1258 const builtIn = isBuiltInBrowserProfileId(profile.id);
1259 const isDefault = profile.id === resolvedDefaultId;
1260 return (
1261 <div
1262 key={profile.id}
1263 className={cn(
1264 "flex items-center gap-3 px-3 py-2",
1265 index > 0 && "border-t border-border/60",
1266 )}
1268 <span className="flex min-w-0 flex-1 items-center gap-2">
1269 {builtIn ? (
1270 <span
1271 className={cn(
1272 "truncate text-sm text-foreground",
1273 profileWritesDisabled && "opacity-64",
1274 )}
1276 {profile.name}
1277 </span>
1278 ) : (
1279 <DraftInput
1280 nativeInput
1281 size="sm"
1282 className="w-full max-w-56"
1283 aria-label={`Rename ${profile.name}`}
1284 disabled={profileWritesDisabled || importInFlight}
1285 maxLength={BROWSER_PROFILE_NAME_MAX_LENGTH}
1286 value={profile.name}
1287 onCommit={(next) => renameProfile(profile.id, next)}
1288 />
1289 )}
1290 {isDefault ? (
1291 <span className={cn("flex", profileWritesDisabled && "opacity-64")}>
1292 <Badge>Default</Badge>
1293 </span>
1294 ) : null}
1295 </span>
1296 <Menu>
1297 <MenuTrigger
1298 render={
1299 <Button
1300 size="icon-xs"
1301 variant="ghost-muted"
1302 disabled={profileWritesDisabled || importInFlight}
1303 aria-label={`${profile.name} options`}
1304 />
1307 <MoreVertical />
1308 </MenuTrigger>
1309 <MenuPopup align="end">
1310 <MenuItem
1311 disabled={!settingsHydrated || isDefault}
1312 onClick={() => {
1313 if (settingsHydrated) {
1314 updateSettings({ browserDefaultProfileId: profile.id });
1316 }}
1318 Set as default
1319 </MenuItem>
1320 <MenuItem
1321 disabled={!settingsHydrated || !removalAvailable}
1322 onClick={() => {
1323 if (serverProfileData.environmentIds.length > 0) {
1324 setProfilePendingClear(profile);
1325 } else clearProfileData(profile.id, profile.name);
1326 }}
1328 Clear cookies and cache
1329 </MenuItem>
1330 {builtIn ? null : (
1331 <MenuItem
1332 variant="destructive"
1333 disabled={!settingsHydrated || !removalAvailable}
1334 onClick={() => {
1335 if (settingsHydrated) setProfilePendingRemoval(profile);
1336 }}
1338 Remove profile and data
1339 </MenuItem>
1340 )}
1341 {!removalAvailable ? (
1342 <>
1343 <MenuSeparator />
1344 <MenuItem disabled>
1345 {environmentsReady
1346 ? "Connect to an environment to clear profile data"
1347 : "Checking environments…"}
1348 </MenuItem>
1349 </>
1350 ) : null}
1351 </MenuPopup>
1352 </Menu>
1353 </div>
1354 );
1355 })}
1356 </div>
1357 <AlertDialog
1358 open={profilePendingRemoval !== null}
1359 onOpenChange={(open) => {
1360 if (!open && !profileRemovalInFlight) {
1361 setProfilePendingRemoval(null);
1362 setProfileRemovalError(null);
1364 }}
1366 <AlertDialogPopup>
1367 <AlertDialogHeader>
1368 <AlertDialogTitle>Remove “{profilePendingRemoval?.name}”?</AlertDialogTitle>
1369 <AlertDialogDescription>
1370 Its cookies and logins are deleted. Desktop tabs already open in this profile stay
1371 open until you close them; server browser tabs close now.
1372 </AlertDialogDescription>
1373 {profileRemovalError ? (
1374 <p aria-live="polite" className="text-sm text-destructive">
1375 {profileRemovalError}
1376 </p>
1377 ) : null}
1378 {!removalAvailable ? (
1379 <p className="text-sm text-muted-foreground">
1380 Connect to an environment to remove this profile and its data.
1381 </p>
1382 ) : null}
1383 </AlertDialogHeader>
1384 <AlertDialogFooter>
1385 <AlertDialogClose
1386 disabled={profileRemovalInFlight}
1387 render={<Button variant="outline" disabled={profileRemovalInFlight} />}
1389 Cancel
1390 </AlertDialogClose>
1391 <Button
1392 variant="destructive"
1393 disabled={profileRemovalInFlight || !settingsHydrated || !removalAvailable}
1394 onClick={() => {
1395 if (profilePendingRemoval && settingsHydrated && removalAvailable) {
1396 void removeProfile(profilePendingRemoval.id);
1398 }}
1400 {profileRemovalInFlight ? "Removing…" : "Remove profile"}
1401 </Button>
1402 </AlertDialogFooter>
1403 </AlertDialogPopup>
1404 </AlertDialog>
1405 <AlertDialog
1406 open={profilePendingClear !== null}
1407 onOpenChange={(open) => {
1408 if (!open) setProfilePendingClear(null);
1409 }}
1411 <AlertDialogPopup>
1412 <AlertDialogHeader>
1413 <AlertDialogTitle>
1414 Clear “{profilePendingClear?.name}”’s cookies and cache?
1415 </AlertDialogTitle>
1416 <AlertDialogDescription>
1417 You are signed out of its sites. Server browser tabs open in this profile close now.
1418 </AlertDialogDescription>
1419 </AlertDialogHeader>
1420 <AlertDialogFooter>
1421 <AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
1422 <Button
1423 variant="destructive"
1424 onClick={() => {
1425 if (profilePendingClear)
1426 clearProfileData(profilePendingClear.id, profilePendingClear.name);
1427 setProfilePendingClear(null);
1428 }}
1430 Clear data
1431 </Button>
1432 </AlertDialogFooter>
1433 </AlertDialogPopup>
1434 </AlertDialog>
1435 {importSession ? (
1436 <BrowserImportWizard
1437 source={importSession.source}
1438 destinationEnvironmentName={importSession.environmentName}
1439 targetProfiles={listedProfiles.map((profile) => ({ id: profile.id, name: profile.name }))}
1440 canCreateProfile={settingsHydrated && !atProfileLimit}
1441 onImport={(input) =>
1442 runWizardImport(importSession.source, importSession.environmentId, input)
1444 onRefreshSource={() => refreshImportSource(importSession.source.id)}
1445 onCheckFullDiskAccess={
1446 window.desktopBridge?.checkSystemPermission
1447 ? () => window.desktopBridge!.checkSystemPermission!("full-disk-access")
1448 : undefined
1450 onOpenFullDiskAccessSettings={async () => {
1451 await readLocalApi()
1452 ?.shell.openSystemSettings("full-disk-access")
1453 .catch(() => {
1454 toastManager.add({
1455 type: "error",
1456 title: "Could not open System Settings",
1457 description: "Open Privacy & Security → Full Disk Access manually.",
1458 });
1459 });
1460 }}
1461 onClose={() => setImportSession(null)}
1462 />
1463 ) : null}
1464 </SettingsRow>
1465 );
1467​
1468export function IntegrationsSettingsPanel() {
1469 const previewDefaultsDisabled = !isElectron;
1470 const previewDefaults = (
1471 <>
1472 <BrowserProfilesSetting disabled={previewDefaultsDisabled} />
1473 <BrowserViewportSetting disabled={previewDefaultsDisabled} />
1474 <BrowserZoomSetting disabled={previewDefaultsDisabled} />
1475 <BrowserAppearanceSetting disabled={previewDefaultsDisabled} />
1476 <BrowserRecordingFrameRateSetting disabled={previewDefaultsDisabled} />
1477 <BrowserRecordingInputSettings disabled={previewDefaultsDisabled} />
1478 <BrowserLinkTargetSetting disabled={previewDefaultsDisabled} />
1479 <BrowserAutoShowFloatingPreviewSetting disabled={previewDefaultsDisabled} />
1480 </>
1481 );
1482​
1483 return (
1484 <SettingsPageContainer>
1485 <ProjectDefaultsSettings category="integrations" />
1486 <SettingsSection id="browser" title="Browser">
1487 {previewDefaultsDisabled ? (
1488 <SettingsUnavailableGroup message="Only available in the desktop app.">
1489 {previewDefaults}
1490 </SettingsUnavailableGroup>
1491 ) : (
1492 previewDefaults
1493 )}
1494 <PullRequestLinksOpenInAppSetting />
1495 </SettingsSection>
1496 <DeviceIntegrationSettings />
1497 </SettingsPageContainer>
1498 );