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

IntegrationsSettings.tsx

1,469 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}>
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 localPlatformsUnavailable = state.hosts.some(
650 (host) => host.kind === "local" && !host.platforms.some((platform) => platform.available),
651 );
652 const [platformsRevealed, setPlatformsRevealed] = useState(false);
653 // Keep diagnostics visible through subsequent agent setup and refresh phases.
654 if (platformsRevealed && !enabled) setPlatformsRevealed(false);
655 if (
656 enabled &&
657 !platformsRevealed &&
658 (state.hostStatus === "ready" || localPlatformsUnavailable) &&
659 pending !== "hub"
660 ) {
661 setPlatformsRevealed(true);
662 }
663​
664 const update = async (
665 kind: NonNullable<typeof pending>,
666 input: { enabled?: boolean; agentAccessEnabled?: boolean },
667 ) => {
668 if (!environmentId) return;
669 setPending(kind);
670 try {
671 const results = await Promise.allSettled(
672 environments.map(async (environment) => {
673 if (environment.connection.phase !== "connected" || !environment.serverConfig) {
674 throw new Error("Environment disconnected");
675 }
676 return configure({
677 environmentId: environment.environmentId,
678 input: { ...input, ...(input.enabled ? { onboardingCompleted: true } : {}) },
679 });
680 }),
681 );
682 const failed = environments.filter((_, index) => {
683 const result = results[index];
684 return result?.status !== "fulfilled" || result.value._tag === "Failure";
685 });
686 if (failed.length > 0) {
687 toastManager.add({
688 type: "error",
689 title: "Device settings not saved on all environments",
690 description: `Could not update ${failed.map((environment) => environment.label).join(", ")}.`,
691 });
692 }
693 } finally {
694 setPending(null);
695 }
696 };
697​
698 const [updateError, setUpdateError] = useState<{ tool: "hub" | "agent"; message: string } | null>(
699 null,
700 );
701 const localTools = state.hosts.find((host) => host.kind === "local")?.tools;
702 const versionActions = (tool: "hub" | "agent") => {
703 const version = localTools?.[tool];
704 const needsUpdate = version && !version.installedVersions.includes(version.requiredVersion);
705 return (
706 <div className="space-y-2">
707 <div className="flex flex-wrap gap-2">
708 {state.supportsToolUpdate && needsUpdate ? (
709 <Button
710 size="sm"
711 disabled={!environmentId || pending !== null || busy}
712 onClick={() => {
713 if (!environmentId) return;
714 setUpdateError(null);
715 setPending(`update-${tool}`);
716 void list({ environmentId, input: { updateTool: tool } })
717 .then((result) => {
718 if (result._tag === "Failure")
719 setUpdateError({
720 tool,
721 message:
722 "Update failed. Check this host's network connection and try again.",
723 });
724 })
725 .finally(() => setPending(null));
726 }}
727 >
728 {pending === `update-${tool}` ? "Updating…" : `Update to v${version.requiredVersion}`}
729 </Button>
730 ) : null}
731 {state.supportsToolInspection ? (
732 <Button
733 size="sm"
734 variant="outline"
735 disabled={!environmentId || pending !== null || busy}
736 onClick={() => {
737 if (!environmentId) return;
738 setPending("check");
739 void list({ environmentId, input: { inspectOnly: true } }).finally(() =>
740 setPending(null),
741 );
742 }}
743 >
744 {pending === "check" ? "Checking…" : "Check versions"}
745 </Button>
746 ) : null}
747 </div>
748 {updateError?.tool === tool ? (
749 <p role="alert" className="text-xs text-destructive">
750 {updateError.message}
751 </p>
752 ) : null}
753 </div>
754 );
755 };
756​
757 return (
758 <>
759 <SettingsRow
760 {...searchableSetting("device-hub")}
761 serverScoped
762 settingKeys={["enableDeviceSupport"]}
763 description={deviceHubDescription}
764 control={
765 <>
766 <DeviceToolVersions
767 action={versionActions("hub")}
768 kind="hub"
769 tools={state.hosts.find((host) => host.kind === "local")?.tools}
770 />
771 {pending === "hub" ? <DeviceHubSetupStatus state={state} pending compact /> : null}
772 <ScopedSwitch
773 settingKeys={["enableDeviceSupport"]}
774 checked={enabled}
775 disabled={projectScope || !loaded || !environmentId || busy || pending !== null}
776 aria-label="Device hub"
777 onCheckedChange={(checked) =>
778 void update("hub", {
779 enabled: Boolean(checked),
780 ...(checked ? {} : { agentAccessEnabled: false }),
781 })
782 }
783 />
784 </>
785 }
786 />
787 <AnimatedHeight>
788 {platformsRevealed ? (
789 <SettingsRow
790 {...searchableSetting("device-platform-support")}
791 description={
792 connectedEnvironments.length > 1
793 ? `Status for ${connectedEnvironments.find((environment) => environment.environmentId === environmentId)?.label}. Select an environment to inspect its simulator support.`
794 : undefined
795 }
796 status={
797 <div className="flex flex-wrap gap-x-5 gap-y-2">
798 <PlatformStatus compact platform="iOS" status={platformSetupStatus(state, "ios")} />
799 <PlatformStatus
800 compact
801 platform="Android"
802 status={platformSetupStatus(state, "android")}
803 />
804 </div>
805 }
806 control={
807 <Button
808 size="sm"
809 variant="outline"
810 disabled={!environmentId || !enabled || busy || pending !== null}
811 onClick={() => {
812 if (!environmentId) return;
813 setPending("check");
814 void list({ environmentId, input: {} }).finally(() => setPending(null));
815 }}
816 >
817 {pending === "check" ? "Checking…" : "Refresh"}
818 </Button>
819 }
820 />
821 ) : null}
822 </AnimatedHeight>
823 <SettingsRow
824 {...searchableSetting("agent-device-access")}
825 serverScoped
826 settingKeys={["enableAgentDeviceAccess"]}
827 description={agentDeviceDescription}
828 control={
829 <>
830 <DeviceToolVersions
831 action={versionActions("agent")}
832 kind="agent"
833 tools={state.hosts.find((host) => host.kind === "local")?.tools}
834 />
835 {pending === "agent" ? <AgentDeviceSetupStatus state={state} pending compact /> : null}
836 <ScopedSwitch
837 settingKeys={["enableAgentDeviceAccess"]}
838 checked={agentAccessEnabled}
839 disabled={
840 connectedEnvironments.length === 0 ||
841 (!projectScope && (!loaded || !anyHubEnabled || busy)) ||
842 pending !== null
843 }
844 aria-label="Agent device access"
845 onCheckedChange={(checked) =>
846 projectScope
847 ? updateSettings({ enableAgentDeviceAccess: Boolean(checked) })
848 : void update("agent", { agentAccessEnabled: Boolean(checked) })
849 }
850 />
851 </>
852 }
853 />
854 {environmentId ? (
855 <DeviceHostUpdates
856 state={{ ...state, hosts: state.hosts.filter((host) => host.kind === "local") }}
857 environmentId={environmentId}
858 />
859 ) : null}
860 <DeviceHostsSettings environmentId={environmentId} />
861 </>
862 );
864​
865function BrowserAutoShowFloatingPreviewSetting({ disabled }: { readonly disabled: boolean }) {
866 const autoShow = useClientSettings((settings) => settings.browserAutoShowFloatingPreview);
867 const updateSettings = useUpdatePrimarySettings();
868​
869 return (
870 <SettingsRow
871 {...searchableSetting("browser-auto-show-floating-preview")}
872 description="Show the floating preview when an agent opens a browser or device unless the agent says otherwise."
873 resetAction={
874 !disabled && autoShow !== DEFAULT_BROWSER_AUTO_SHOW_FLOATING_PREVIEW ? (
875 <SettingResetButton
876 label="auto-show floating preview"
877 onClick={() =>
878 updateSettings({
879 browserAutoShowFloatingPreview: DEFAULT_BROWSER_AUTO_SHOW_FLOATING_PREVIEW,
880 })
881 }
882 />
883 ) : null
884 }
885 control={
886 <Switch
887 disabled={disabled}
888 checked={autoShow}
889 onCheckedChange={(checked) =>
890 updateSettings({ browserAutoShowFloatingPreview: Boolean(checked) })
891 }
892 aria-label="Auto-show floating preview"
893 />
894 }
895 />
896 );
898​
899/**
900 * Profile list, its header menu, and the import flow.
901 *
902 * One menu creates profiles and imports into them, because the two are the
903 * same decision from the user's side: "I want a profile that has my Helium
904 * logins in it". Import targets include "New profile" so that case does not
905 * require creating one first and then finding a second control.
906 *
907 * Built-ins render without a rename field: they are synthesized rather than
908 * stored, so there is nothing to rename and removing them would strand every
909 * tab that opened under them.
910 *
911 * Sources are listed lazily on open: detection touches the other browser's
912 * files, and the answer changes while the app is running (quitting the browser
913 * clears `browserRunning`), so a value cached at mount would go stale.
914 */
915function BrowserProfilesSetting({ disabled }: { readonly disabled: boolean }) {
916 const userProfiles = useClientSettings((settings) => settings.browserProfiles);
917 const defaultProfileId = useClientSettings((settings) => settings.browserDefaultProfileId);
918 const settingsHydrated = useClientSettingsHydrated();
919 const updateSettings = useUpdatePrimarySettings();
920 const { environments, isReady: environmentsReady } = useEnvironments();
921 const primaryEnvironment = usePrimaryEnvironment();
922 const [sources, setSources] = useState<ReadonlyArray<BrowserImportSource> | null>(null);
923 const [importSession, setImportSession] = useState<{
924 readonly source: BrowserImportSource;
925 readonly environmentId: EnvironmentId;
926 readonly environmentName: string;
927 } | null>(null);
928 const [profilePendingRemoval, setProfilePendingRemoval] = useState<BrowserProfile | null>(null);
929 const [profileRemovalError, setProfileRemovalError] = useState<string | null>(null);
930 const [profileRemovalInFlight, setProfileRemovalInFlight] = useState(false);
931 const removalAvailable = browserProfileRemovalAvailable(
932 previewBridge !== null,
933 environmentsReady,
934 environments.length,
935 );
936 const importInFlightRef = useRef(false);
937 const [importInFlight, setImportInFlight] = useState(false);
938 const profileWritesDisabled = disabled || !settingsHydrated;
939​
940 const profiles = resolveBrowserProfiles(userProfiles);
941 // Incognito is deliberately not a row — it holds nothing to manage — so the
942 // default has to resolve against the list that renders. A stored
943 // `browserDefaultProfileId` of "incognito" would otherwise leave the section
944 // with no Default badge at all.
945 const listedProfiles = profiles.filter((profile) => profile.kind !== "incognito");
946 const resolvedDefaultId =
947 findBrowserProfile(listedProfiles, defaultProfileId)?.id ?? DEFAULT_BROWSER_PROFILE_ID;
948​
949 const createProfile = (baseName: string) => {
950 if (!settingsHydrated || importInFlightRef.current) return undefined;
951 const currentProfiles = getClientSettings().browserProfiles;
952 // Checked against the live settings, not the rendered list: two clicks
953 // before a re-render would otherwise both pass the disabled control.
954 if (currentProfiles.length >= BROWSER_PROFILE_MAX_COUNT) return undefined;
955 const resolvedProfiles = resolveBrowserProfiles(currentProfiles);
956 const taken = new Set(resolvedProfiles.map((profile) => profile.name));
957 let name = baseName;
958 for (let index = 2; taken.has(name); index += 1) name = `${baseName} ${index}`;
959 const profile = { id: `profile-${randomUUID()}`, name, kind: "persistent" as const };
960 updateSettings({ browserProfiles: [...currentProfiles, profile] });
961 return profile;
962 };
963​
964 const renameProfile = (id: string, next: string) => {
965 if (!settingsHydrated || importInFlightRef.current) return;
966 const name = next.trim().slice(0, BROWSER_PROFILE_NAME_MAX_LENGTH);
967 if (name === "") return;
968 const currentProfiles = getClientSettings().browserProfiles;
969 updateSettings({
970 browserProfiles: currentProfiles.map((profile) =>
971 profile.id === id ? { ...profile, name } : profile,
972 ),
973 });
974 };
975​
976 const clearProfileData = (id: string, name: string) => {
977 if (!settingsHydrated || importInFlightRef.current) return;
978 if (!previewBridge || !environmentsReady || environments.length === 0) {
979 toastManager.add({
980 type: "error",
981 title: `Could not clear ${name}'s data`,
982 description: "You're not connected to a server yet.",
983 });
984 return;
985 }
986 void clearBrowserProfileData(
987 previewBridge,
988 environments.map((environment) => environment.environmentId),
989 id,
990 )
991 .then(() => {
992 toastManager.add({ type: "success", title: `Cleared ${name}'s cookies and cache` });
993 })
994 .catch(() => {
995 toastManager.add({ type: "error", title: `Could not clear ${name}'s data` });
996 });
997 };
998​
999 const removeProfile = async (id: string) => {
1000 if (!settingsHydrated || importInFlightRef.current) return;
1001 if (!removalAvailable) {
1002 setProfileRemovalError("Connect to an environment before removing this profile.");
1003 return;
1005 setProfileRemovalError(null);
1006 setProfileRemovalInFlight(true);
1007 // Drop the partition's data too, otherwise a removed profile's cookies
1008 // stay on disk with nothing in the UI pointing at them.
1009 try {
1010 await clearBrowserProfileData(
1011 previewBridge,
1012 environmentsReady ? environments.map((environment) => environment.environmentId) : [],
1013 id,
1014 );
1015 } catch {
1016 setProfileRemovalError("Profile data could not be deleted. Try again.");
1017 setProfileRemovalInFlight(false);
1018 return;
1020 const currentSettings = getClientSettings();
1021 updateSettings({
1022 browserProfiles: currentSettings.browserProfiles.filter((profile) => profile.id !== id),
1023 // Reassign the default rather than leaving it pointing at nothing.
1024 ...(currentSettings.browserDefaultProfileId === id
1025 ? { browserDefaultProfileId: DEFAULT_BROWSER_PROFILE_ID }
1026 : {}),
1027 });
1028 setProfileRemovalInFlight(false);
1029 setProfilePendingRemoval(null);
1030 };
1031​
1032 // A browser that is not on this machine is left out rather than listed as a
1033 // dead row: there is nothing to act on, and the menu is a list of things you
1034 // can import from. An unsupported one is left out for the same reason — the
1035 // blocked wizard step can't be fixed from here. Every other unavailable
1036 // reason stays, since each names a step the user can take.
1037 const importableSources = (sources ?? []).filter(
1038 (source) =>
1039 source.unavailable !== "notInstalled" && source.unavailable !== "unsupportedPlatform",
1040 );
1041​
1042 // Refreshed without blanking the last result: the menu shows the cached list
1043 // straight away so it doesn't reflow on open, and the source list is stable
1044 // (names only) since choosing what to import happens in the wizard, not here.
1045 const loadSources = useCallback(() => {
1046 if (!previewBridge) return;
1047 void previewBridge
1048 .listBrowserImportSources()
1049 .then(setSources)
1050 .catch(() => setSources((previous) => previous ?? []));
1051 }, []);
1052​
1053 // Runs one import for the wizard. A new profile is registered only once the
1054 // import succeeds — the cookies land in its partition first — so a blocked
1055 // attempt never leaves an empty profile behind.
1056 const runWizardImport = async (
1057 source: BrowserImportSource,
1058 environmentId: EnvironmentId,
1059 input: { readonly sourceProfileDirectory: string; readonly target: WizardTarget },
1060 ): Promise<ImportOutcome> => {
1061 if (!previewBridge) return { kind: "blocked", reason: "sessionUnavailable" };
1062 if (!settingsHydrated) return { kind: "blocked", reason: "sessionUnavailable" };
1063 if (
1064 input.target.kind === "existing" &&
1065 !resolveBrowserProfiles(getClientSettings().browserProfiles).some(
1066 (profile) => profile.id === input.target.profileId,
1068 ) {
1069 return { kind: "blocked", reason: "readFailed" };
1071 if (importInFlightRef.current) return { kind: "blocked", reason: "readFailed" };
1072 importInFlightRef.current = true;
1073 setImportInFlight(true);
1074 try {
1075 const result = await previewBridge.importBrowserCookies({
1076 environmentId,
1077 sourceId: source.id,
1078 sourceProfileDirectory: input.sourceProfileDirectory,
1079 targetProfileId: input.target.profileId,
1080 });
1081 if (
1082 input.target.kind === "existing" &&
1083 !resolveBrowserProfiles(getClientSettings().browserProfiles).some(
1084 (profile) => profile.id === input.target.profileId,
1086 ) {
1087 return { kind: "blocked", reason: "readFailed" };
1089 let targetName: string;
1090 if (input.target.kind === "new") {
1091 // Registered only when something actually came over: an import that
1092 // found no cookies should not leave a new, empty profile behind.
1093 if (result.imported > 0) {
1094 try {
1095 const persisted = await persistClientSettingsUpdate((current) => {
1096 const existing = current.browserProfiles.find(
1097 (profile) => profile.id === input.target.profileId,
1098 );
1099 if (existing) return current;
1100 // The wizard refuses a new target at the cap, but the cap can be
1101 // reached while the import runs; the updater sees the newest
1102 // settings, so this is the check that holds.
1103 if (current.browserProfiles.length >= BROWSER_PROFILE_MAX_COUNT) {
1104 throw new ProfileLimitReachedError();
1106 const taken = new Set(
1107 resolveBrowserProfiles(current.browserProfiles).map((profile) => profile.name),
1108 );
1109 let name = source.name;
1110 for (let index = 2; taken.has(name); index += 1) name = `${source.name} ${index}`;
1111 return {
1112 ...current,
1113 browserProfiles: [
1114 ...current.browserProfiles,
1115 { id: input.target.profileId, name, kind: "persistent" as const },
1116 ],
1117 };
1118 });
1119 targetName =
1120 persisted.browserProfiles.find((profile) => profile.id === input.target.profileId)
1121 ?.name ?? source.name;
1122 } catch (cause) {
1123 // This target id belongs only to the attempted new profile. Clear
1124 // its partition so a failed registration cannot strand imported
1125 // cookies behind a profile that disappears on restart.
1126 await clearBrowserProfileData(
1127 previewBridge,
1128 [environmentId],
1129 input.target.profileId,
1130 ).catch(() => undefined);
1131 // Not a read failure: the cookies came over and were cleared again
1132 // because the profile could not be kept. Name that, in the same
1133 // token form `importFailureReason` recovers from a bridge error.
1134 const reason =
1135 cause instanceof ProfileLimitReachedError ? "profileLimitReached" : "profileNotSaved";
1136 throw new Error(`Importing cookies from ${source.id} failed: ${reason}.`, { cause });
1138 } else {
1139 targetName = source.name;
1141 } else {
1142 targetName = input.target.name;
1144 return {
1145 kind: "imported",
1146 imported: result.imported,
1147 skipped: result.skipped,
1148 skippedDomains: result.skippedDomains,
1149 targetName,
1150 };
1151 } catch (cause) {
1152 return { kind: "blocked", reason: importFailureReason(cause) };
1153 } finally {
1154 importInFlightRef.current = false;
1155 setImportInFlight(false);
1157 };
1158​
1159 // Re-checks a source's availability after the user quits the browser, and
1160 // keeps the cached list in step so the menu reflects it too.
1161 const refreshImportSource = async (
1162 sourceId: BrowserImportSource["id"],
1163 ): Promise<BrowserImportSource | undefined> => {
1164 if (!previewBridge) return undefined;
1165 try {
1166 const latest = await previewBridge.listBrowserImportSources();
1167 setSources(latest);
1168 return latest.find((source) => source.id === sourceId);
1169 } catch {
1170 return undefined;
1172 };
1173​
1174 const atProfileLimit = userProfiles.length >= BROWSER_PROFILE_MAX_COUNT;
1175​
1176 return (
1177 <SettingsRow
1178 {...searchableSetting("browser-profiles")}
1179 description="Profiles separate cookies and logins. Incognito data is cleared when the app closes."
1180 control={
1181 <Menu onOpenChange={(open) => open && loadSources()}>
1182 <MenuTrigger
1183 render={
1184 <Button
1185 size="sm"
1186 variant="outline"
1187 disabled={profileWritesDisabled || importInFlight}
1188 />
1191 <PlusIcon />
1192 Add profile
1193 </MenuTrigger>
1194 <MenuPopup align="end">
1195 <MenuItem
1196 disabled={!settingsHydrated || atProfileLimit}
1197 onClick={() => createProfile("New profile")}
1199 Blank profile
1200 </MenuItem>
1201 {atProfileLimit ? (
1202 <MenuItem disabled>You&rsquo;ve reached the profile limit</MenuItem>
1203 ) : null}
1204 <MenuSeparator />
1205 <MenuGroup>
1206 <MenuGroupLabel>Import from</MenuGroupLabel>
1207 {sources === null ? (
1208 <MenuItem disabled>Looking for browsers…</MenuItem>
1209 ) : importableSources.length === 0 ? (
1210 <MenuItem disabled>No supported browsers found</MenuItem>
1211 ) : (
1212 // Every source is a plain row — running, needs-permission and
1213 // ready all look the same here. The wizard picks up whatever
1214 // state the source is in and walks the user forward from there.
1215 <>
1216 {importableSources.map((source) => (
1217 <MenuItem
1218 key={source.id}
1219 disabled={!settingsHydrated || primaryEnvironment == null}
1220 onClick={() => {
1221 if (!settingsHydrated || primaryEnvironment == null) return;
1222 setImportSession({
1223 source,
1224 environmentId: primaryEnvironment.environmentId,
1225 environmentName: resolveEnvironmentOptionLabel({
1226 isPrimary: true,
1227 environmentId: primaryEnvironment.environmentId,
1228 runtimeLabel: primaryEnvironment.label,
1229 }),
1230 });
1231 }}
1233 {source.name}
1234 </MenuItem>
1235 ))}
1236 {primaryEnvironment == null ? (
1237 <MenuItem disabled>Connect to an environment to import cookies</MenuItem>
1238 ) : null}
1239 </>
1240 )}
1241 </MenuGroup>
1242 </MenuPopup>
1243 </Menu>
1246 {/*
1247 The bordered container groups rows unambiguously at any width, and
1248 carries the bottom spacing `SettingsRow` leaves to its children
1249 (`pt-3 pb-1`).
1250 */}
1251 <div className="mt-2 mb-2 overflow-hidden rounded-lg border border-border/60">
1252 {listedProfiles.map((profile, index) => {
1253 const builtIn = isBuiltInBrowserProfileId(profile.id);
1254 const isDefault = profile.id === resolvedDefaultId;
1255 return (
1256 <div
1257 key={profile.id}
1258 className={cn(
1259 "flex items-center gap-3 px-3 py-2",
1260 index > 0 && "border-t border-border/60",
1261 )}
1263 <span className="flex min-w-0 flex-1 items-center gap-2">
1264 {builtIn ? (
1265 // Dimmed here rather than on the table: a wrapper-level dim
1266 // stacks with the rename field's and the row menu button's
1267 // own, landing them near 0.41 while every other disabled
1268 // control in the block sits at 0.64.
1269 <span
1270 className={cn(
1271 "truncate text-sm text-foreground",
1272 profileWritesDisabled && "opacity-64",
1273 )}
1275 {profile.name}
1276 </span>
1277 ) : (
1278 <DraftInput
1279 nativeInput
1280 size="sm"
1281 className="w-full max-w-56"
1282 aria-label={`Rename ${profile.name}`}
1283 disabled={profileWritesDisabled || importInFlight}
1284 maxLength={BROWSER_PROFILE_NAME_MAX_LENGTH}
1285 value={profile.name}
1286 onCommit={(next) => renameProfile(profile.id, next)}
1287 />
1288 )}
1289 {/* Dimmed with the rest of the row, whose controls are all disabled. */}
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={() => clearProfileData(profile.id, profile.name)}
1324 Clear cookies and cache
1325 </MenuItem>
1326 {builtIn ? null : (
1327 <MenuItem
1328 variant="destructive"
1329 disabled={!settingsHydrated || !removalAvailable}
1330 onClick={() => {
1331 if (settingsHydrated) setProfilePendingRemoval(profile);
1332 }}
1334 Remove profile and data
1335 </MenuItem>
1336 )}
1337 {!removalAvailable ? (
1338 <>
1339 <MenuSeparator />
1340 <MenuItem disabled>
1341 {environmentsReady
1342 ? "Connect to an environment to clear profile data"
1343 : "Checking environments…"}
1344 </MenuItem>
1345 </>
1346 ) : null}
1347 </MenuPopup>
1348 </Menu>
1349 </div>
1350 );
1351 })}
1352 </div>
1353 <AlertDialog
1354 open={profilePendingRemoval !== null}
1355 onOpenChange={(open) => {
1356 if (!open && !profileRemovalInFlight) {
1357 setProfilePendingRemoval(null);
1358 setProfileRemovalError(null);
1360 }}
1362 <AlertDialogPopup>
1363 <AlertDialogHeader>
1364 <AlertDialogTitle>Remove “{profilePendingRemoval?.name}”?</AlertDialogTitle>
1365 <AlertDialogDescription>
1366 Its cookies and logins are deleted. Tabs already open in this profile stay open until
1367 you close them.
1368 </AlertDialogDescription>
1369 {profileRemovalError ? (
1370 <p aria-live="polite" className="text-sm text-destructive">
1371 {profileRemovalError}
1372 </p>
1373 ) : null}
1374 {!removalAvailable ? (
1375 <p className="text-sm text-muted-foreground">
1376 Connect to an environment to remove this profile and its data.
1377 </p>
1378 ) : null}
1379 </AlertDialogHeader>
1380 <AlertDialogFooter>
1381 <AlertDialogClose
1382 disabled={profileRemovalInFlight}
1383 render={<Button variant="outline" disabled={profileRemovalInFlight} />}
1385 Cancel
1386 </AlertDialogClose>
1387 <Button
1388 variant="destructive"
1389 disabled={profileRemovalInFlight || !settingsHydrated || !removalAvailable}
1390 onClick={() => {
1391 if (profilePendingRemoval && settingsHydrated && removalAvailable) {
1392 void removeProfile(profilePendingRemoval.id);
1394 }}
1396 {profileRemovalInFlight ? "Removing…" : "Remove profile"}
1397 </Button>
1398 </AlertDialogFooter>
1399 </AlertDialogPopup>
1400 </AlertDialog>
1401 {importSession ? (
1402 <BrowserImportWizard
1403 source={importSession.source}
1404 destinationEnvironmentName={importSession.environmentName}
1405 targetProfiles={listedProfiles.map((profile) => ({ id: profile.id, name: profile.name }))}
1406 canCreateProfile={settingsHydrated && !atProfileLimit}
1407 onImport={(input) =>
1408 runWizardImport(importSession.source, importSession.environmentId, input)
1410 onRefreshSource={() => refreshImportSource(importSession.source.id)}
1411 onCheckFullDiskAccess={
1412 window.desktopBridge?.checkSystemPermission
1413 ? () => window.desktopBridge!.checkSystemPermission!("full-disk-access")
1414 : undefined
1416 onOpenFullDiskAccessSettings={async () => {
1417 // Rejects outside the desktop shell (and on shells that predate the
1418 // method), so the one toast covers every way the link can fail.
1419 await readLocalApi()
1420 ?.shell.openSystemSettings("full-disk-access")
1421 .catch(() => {
1422 toastManager.add({
1423 type: "error",
1424 title: "Could not open System Settings",
1425 description: "Open Privacy & Security → Full Disk Access manually.",
1426 });
1427 });
1428 }}
1429 onClose={() => setImportSession(null)}
1430 />
1431 ) : null}
1432 </SettingsRow>
1433 );
1435​
1436export function IntegrationsSettingsPanel() {
1437 // Client-local preview defaults are editable only where the preview exists.
1438 const previewDefaultsDisabled = !isElectron;
1439 const previewDefaults = (
1440 <>
1441 <BrowserProfilesSetting disabled={previewDefaultsDisabled} />
1442 <BrowserViewportSetting disabled={previewDefaultsDisabled} />
1443 <BrowserZoomSetting disabled={previewDefaultsDisabled} />
1444 <BrowserAppearanceSetting disabled={previewDefaultsDisabled} />
1445 <BrowserRecordingFrameRateSetting disabled={previewDefaultsDisabled} />
1446 <BrowserRecordingInputSettings disabled={previewDefaultsDisabled} />
1447 <BrowserLinkTargetSetting disabled={previewDefaultsDisabled} />
1448 <BrowserAutoShowFloatingPreviewSetting disabled={previewDefaultsDisabled} />
1449 </>
1450 );
1451​
1452 return (
1453 <SettingsPageContainer>
1454 {/* Server-authoritative agent access is scoped by the header selection;
1455 the preview defaults below are device-local and ignore it. */}
1456 <ProjectDefaultsSettings category="integrations" />
1457 <SettingsSection id="browser" title="Browser">
1458 {previewDefaultsDisabled ? (
1459 <SettingsUnavailableGroup message="Only available in the desktop app.">
1460 {previewDefaults}
1461 </SettingsUnavailableGroup>
1462 ) : (
1463 previewDefaults
1464 )}
1465 </SettingsSection>
1466 <DeviceIntegrationSettings />
1467 </SettingsPageContainer>
1468 );