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

IntegrationsSettings.tsx

1,464 lines55.1 KB

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