import { DeviceHostUpdates } from "./DeviceHostUpdates"; import type { DevicePlatform, DeviceServiceState, EnvironmentId } from "@t3tools/contracts"; import { Check } from "lucide-react"; import { Check as CheckGlyph, CircleAlert } from "lucide"; import { AuthSettingsWriteScope } from "@t3tools/contracts"; import { useAtomMount } from "@effect/atom-react"; import { useState } from "react"; import { Button } from "~/components/ui/button"; import { DialogClose } from "~/components/ui/dialog"; import { MorphIcon } from "~/components/MorphIcon"; import { WizardHeader, WizardPanel, WizardSteps, WizardFooter } from "~/components/ui/wizard"; import { Spinner } from "~/components/ui/spinner"; import { Switch } from "~/components/ui/switch"; import { deviceEnvironment, deviceHostProbeAtom, NO_DEVICE_PROBE_ATOM } from "~/state/device"; import { useAtomCommand } from "~/state/use-atom-command"; import { readEnvironmentScope, useEnvironmentScope } from "~/state/session"; import { cn } from "~/lib/utils"; const platformName = (platform: DevicePlatform) => (platform === "ios" ? "iOS" : "Android"); const deviceHubDescription = "Enable this environment to open simulators and emulators, whether they run here or on a remote device host."; const agentDeviceDescription = "Allow new agent sessions in this environment to start and control local and remote devices, with required tools set up automatically."; export const isAndroidDiscoveryUncertain = (state: DeviceServiceState) => Object.values(state.hostStatuses).some( (status) => status.status === "ready" && (status.androidDiscoveryIncomplete || status.incompletePlatforms?.includes("android")), ); /** * `hostStatus` only tracks this machine. A machine without simulator tooling never * starts its own hub, so setup and the panel must also count remote device hosts. */ export function deviceHubReadiness(state: DeviceServiceState) { const statuses = Object.values(state.hostStatuses).map((host) => host.status); const ready = state.hostStatus === "ready" || statuses.includes("ready"); const busy = !ready && [state.hostStatus, ...statuses].some( (status) => status === "installing" || status === "starting", ); return { ready, busy }; } /** A ready host keeps its devices usable but may still carry a discovery warning. */ function deviceHostDiagnostics( hosts: ReadonlyArray>, hostStatuses: DeviceServiceState["hostStatuses"], ) { return hosts.flatMap((host) => { const status = hostStatuses[host.id]; return status?.status === "ready" && status.detail ? [{ hostId: host.id, label: host.label, detail: status.detail }] : []; }); } function DeviceHostDiagnostics(props: { readonly hosts: ReadonlyArray>; readonly hostStatuses: DeviceServiceState["hostStatuses"]; readonly className?: string; }) { const diagnostics = deviceHostDiagnostics(props.hosts, props.hostStatuses); if (diagnostics.length === 0) return null; return (
{diagnostics.map(({ hostId, label, detail }) => (

{label}: {detail}

))}
); } export function platformSetupStatus(state: DeviceServiceState, platform: DevicePlatform) { const hasDevices = state.devices.some((device) => device.platform === platform); if (platform === "android" && !hasDevices && isAndroidDiscoveryUncertain(state)) { return { ready: false, message: "The Android device list may be incomplete. Check the device host and try again.", }; } const availabilities = state.hosts.flatMap((host) => host.platforms .filter((candidate) => candidate.platform === platform) .map((candidate) => ({ ...candidate, host })), ); const supportingHosts = availabilities .filter((candidate) => candidate.available) .map((candidate) => candidate.host); if (supportingHosts.length === 0) { return { ready: false, message: availabilities[0]?.reason ?? `${platformName(platform)} support was not detected.`, }; } const readyHosts = supportingHosts.filter( (host) => state.hostStatuses[host.id]?.status === "ready" || (host.kind === "local" && state.hostStatus === "ready"), ); if (readyHosts.length > 0 && !hasDevices) { if ( readyHosts.some((host) => state.hostStatuses[host.id]?.incompletePlatforms?.includes(platform), ) ) { return { ready: false, message: `No ${platformName(platform)} devices were listed because device discovery reported a problem.`, }; } return { ready: false, message: platform === "ios" ? "Xcode is installed, but no iOS Simulator is available. Install a runtime in Xcode Settings → Components." : "The Android SDK is installed, but no virtual device exists. Create one in Android Studio → Device Manager.", }; } const remoteHost = supportingHosts.every((host) => host.kind !== "local") ? supportingHosts[0] : undefined; const location = remoteHost ? ` on ${remoteHost.label}` : ""; return { ready: true, message: remoteHost?.kind === "eas" ? `${remoteHost.label} starts ${platform === "ios" ? "iOS Simulators" : "Android emulators"} in the cloud with EAS Simulator.` : platform === "ios" ? `Xcode and iOS Simulator are available${location}.` : `The Android SDK and Emulator are available${location}.`, }; } export function DeviceSetup(props: { readonly environmentId: EnvironmentId; readonly state: DeviceServiceState; readonly onComplete?: () => void; }) { const canConfigure = useEnvironmentScope(props.environmentId, AuthSettingsWriteScope); const configure = useAtomCommand(deviceEnvironment.configure); const list = useAtomCommand(deviceEnvironment.list, { reportFailure: false }); const [pending, setPending] = useState<"hub" | "check" | "agent" | "complete" | null>(null); const [step, setStep] = useState(0); const enabled = props.state.hostStatus !== "disabled"; const { ready, busy } = deviceHubReadiness(props.state); const localPlatformsUnavailable = props.state.hosts.some( (host) => host.kind === "local" && !host.platforms.some((platform) => platform.available), ); useAtomMount(enabled ? deviceHostProbeAtom(props.environmentId) : NO_DEVICE_PROBE_ATOM); const update = async ( kind: NonNullable, input: { enabled?: boolean; agentAccessEnabled?: boolean; onboardingCompleted?: boolean }, ) => { if (!readEnvironmentScope(props.environmentId, AuthSettingsWriteScope)) return; setPending(kind); const result = await configure({ environmentId: props.environmentId, input }); setPending(null); if (kind === "complete" && result._tag === "Success") props.onComplete?.(); }; return ( <> busy || pending !== null || requested > step} /> {step === 0 ? (

Enable the device hub

{deviceHubDescription}

void update("hub", { enabled: Boolean(checked), ...(checked ? {} : { agentAccessEnabled: false }), }) } />
) : null} {step === 1 || (step === 0 && enabled && localPlatformsUnavailable) ? (

Check simulator support

{ setPending("check"); void list({ environmentId: props.environmentId, input: {} }).finally(() => setPending(null), ); }} />
) : null} {step === 2 ? (

Allow agent control

{agentDeviceDescription}

void update("agent", { agentAccessEnabled: Boolean(checked) }) } />

Leave this off to keep manual device controls without giving agents access.

) : null} {props.state.hostStatus === "failed" && props.state.hostStatusDetail ? (

{props.state.hostStatusDetail}

) : null}
{step === 0 ? ( }>Cancel ) : ( )} {step < 2 ? ( ) : ( )} ); } export function DeviceHubSetupStatus({ state, pending, compact = false, }: { readonly state: DeviceServiceState; readonly pending: boolean; readonly compact?: boolean; }) { if (!pending && !deviceHubReadiness(state).ready) return null; return (

{pending ? : } {pending ? state.hostStatus === "installing" ? compact ? "Installing…" : "Installing device hub…" : state.hostStatus === "starting" ? compact ? "Starting…" : "Starting device hub…" : compact ? "Updating…" : "Updating device hub…" : "Device hub is ready."}

); } function DevicePlatformSetup(props: { readonly state: DeviceServiceState; readonly checking: boolean; readonly disabled: boolean; readonly onCheck: () => void; }) { return (

You can use either platform. Fixing a missing platform does not block the other one.

); } export function AgentDeviceSetupStatus(props: { readonly state: DeviceServiceState; readonly pending: boolean; readonly compact?: boolean; }) { if (props.pending) { const label = props.state.hostStatus === "installing" ? props.compact ? "Installing…" : "Installing agent tools…" : props.state.hostStatus === "starting" ? props.compact ? "Starting…" : "Starting agent tools…" : props.compact ? "Updating…" : "Updating agent access…"; return (

{label}

); } if ( props.state.agentAccessEnabled && deviceHubReadiness(props.state).ready && props.state.hosts.some((host) => host.agentDeviceInstalled) ) { return (

Agent tools are ready.

); } return null; } function PlatformStatus(props: { readonly platform: string; readonly status: { readonly ready: boolean; readonly message: string }; readonly compact?: boolean; }) { return (

{props.platform}

{props.compact && props.status.ready ? "Ready" : props.status.message}

); }