import { DeviceHostUpdates } from "./DeviceHostUpdates"; import type { DevicePlatform, DeviceServiceState, DeviceSummary, ScopedThreadRef, } from "@t3tools/contracts"; import { ArrowUpRight, CircleAlert, Play, Smartphone, X } from "lucide-react"; import { useAtomMount } from "@effect/atom-react"; import { type ReactNode, useState } from "react"; import { usePreviewMiniPlayerStore } from "~/previewMiniPlayerStore"; import { selectThreadRightPanelState, useRightPanelStore, type RightPanelSurface, } from "~/rightPanelStore"; import { Button } from "~/components/ui/button"; import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "~/components/ui/collapsible"; import { DiscoveryList } from "~/components/ui/discovery-list"; import { Dialog } from "~/components/ui/dialog"; import { WizardPopup } from "~/components/ui/wizard"; import { Spinner } from "~/components/ui/spinner"; import { cn } from "~/lib/utils"; import { focusPanelTerminalAfterClose } from "~/lib/terminalFocus"; import { deviceEnvironment, deviceHostProbeAtom, NO_DEVICE_PROBE_ATOM, useDeviceState, } from "~/state/device"; import { formatEnvironmentQueryError } from "~/state/query"; import { useAtomCommand } from "~/state/use-atom-command"; import { DeviceLoadingView } from "./DeviceLoadingView"; import { DeviceSetup, deviceHubReadiness, incompleteListings, isAndroidDiscoveryUncertain, } from "./DeviceSetup"; import { DeviceWorkspace } from "./DeviceWorkspace"; import { PreviewPanelShell, type PreviewPanelMode } from "../preview/PreviewPanelShell"; const platformLabel = (platform: DevicePlatform) => platform === "ios" ? "iOS Simulators" : "Android Emulators"; const deviceKey = (device: Pick) => `${device.hostId}\u0000${device.id}`; export function DevicePanel(props: { readonly mode: PreviewPanelMode; readonly threadRef: ScopedThreadRef; readonly surface: Extract; readonly visible: boolean; readonly onDismissSetup: () => void; }) { const { environmentId, threadId } = props.threadRef; const { state, loaded, error: stateError, refresh: refreshState } = useDeviceState(environmentId); const list = useAtomCommand(deviceEnvironment.list, { reportFailure: false }); const open = useAtomCommand(deviceEnvironment.open); const close = useAtomCommand(deviceEnvironment.close); // The panel stays mounted across thread switches, so an in-flight open or // power-off is tagged with the thread it belongs to and only shown there. const scope = `${environmentId}\u0000${threadId}`; const [operation, setOperation] = useState<{ readonly scope: string; readonly pending: DeviceSummary | null; readonly error: string | null; } | null>(null); const pendingDevice = operation?.scope === scope ? operation.pending : null; const operationError = operation?.scope === scope ? operation.error : null; const pendingDeviceKey = pendingDevice ? deviceKey(pendingDevice) : null; const hostDisabled = state.hostStatus === "disabled"; useAtomMount( props.visible && loaded && !hostDisabled ? deviceHostProbeAtom(environmentId) : NO_DEVICE_PROBE_ATOM, ); const sessions = state.sessions.filter((session) => session.threadId === threadId); const activeSession = props.surface.target ? sessions.find( (session) => session.deviceId === props.surface.target?.deviceId && session.hostId === props.surface.target.hostId, ) : undefined; const activeDevice = activeSession ? state.devices.find( (device) => device.hostId === activeSession.hostId && device.id === activeSession.deviceId, ) : undefined; const activeHost = activeDevice ? state.hosts.find((host) => host.id === activeDevice.hostId) : undefined; const grouped = groupDevices(state); const startOperation = (pending: DeviceSummary | null) => { const started = { scope, pending, error: null }; setOperation(started); // Returning to the same thread can start a newer operation before this one settles. return (error: string | null) => setOperation((current) => current === started ? { ...started, pending: null, error } : current, ); }; const selectDevice = async (value: string) => { const device = state.devices.find((candidate) => deviceKey(candidate) === value); if (!device) return; const settleOperation = startOperation(device); const result = await open({ environmentId, input: { threadId, hostId: device.hostId, deviceId: device.id, platform: device.platform, }, }); if (result._tag === "Failure") settleOperation(formatEnvironmentQueryError(result.cause)); else { // The server opened the device for the starting thread, so its tab opens there. useRightPanelStore.getState().openDevice(props.threadRef, { hostId: result.value.hostId, deviceId: result.value.deviceId, platform: device.platform, name: device.name, }); settleOperation(null); } }; const floatActive = () => { if (!activeDevice) return; usePreviewMiniPlayerStore.getState().open(props.threadRef, { kind: "device", hostId: activeDevice.hostId, deviceId: activeDevice.id, platform: activeDevice.platform, name: activeDevice.name, }); useRightPanelStore.getState().close(props.threadRef); }; const closeSurface = () => { const store = useRightPanelStore.getState(); const { activeSurfaceId } = selectThreadRightPanelState(store.byThreadKey, props.threadRef); store.closeSurface(props.threadRef, props.surface.id); focusPanelTerminalAfterClose(props.threadRef, activeSurfaceId); }; const closeActive = (powerOff: boolean) => { if (!powerOff) { closeSurface(); return; } if (!activeSession) return; const settleOperation = startOperation(null); void close({ environmentId, input: { threadId, hostId: activeSession.hostId, deviceId: activeSession.deviceId, shutdown: powerOff, }, }).then((result) => { if (result._tag === "Failure") settleOperation(formatEnvironmentQueryError(result.cause)); else closeSurface(); }); }; const bootingDevices = state.bootingDevices?.filter((device) => device.threadId === threadId) ?? []; const { ready: hostReady, busy: hostBusy } = deviceHubReadiness(state); const loading = !activeDevice && (pendingDevice !== null || hostBusy || !loaded); // Without a first snapshot a failed subscription never settles on its own. const loadError = loaded ? null : stateError; const diagnostics = state.hosts.flatMap((host) => { const status = state.hostStatuses[host.id]; const detail = status?.detail ?? (host.kind === "local" ? state.hostStatusDetail : undefined); return detail && (status?.status ?? state.hostStatus) === "ready" ? [ { hostId: host.id, label: host.label, detail, incompletePlatforms: incompleteListings(status), }, ] : []; }); const unavailablePlatforms = state.hosts.flatMap((host) => host.platforms .filter((platform) => !platform.available) .map((platform) => ({ ...platform, hostId: host.id, hostLabel: host.label })), ); if (loaded && (!state.onboardingCompleted || hostDisabled)) { return ( { if (!isOpen) props.onDismissSetup(); }} > ); } return (
{bootingDevices.length > 0 ? (
Starting {bootingDevices.map((device) => device.name).join(", ")}… This can take a minute.
) : null} {operationError ? ( setOperation(null)}>{operationError} ) : null}
{activeDevice && activeSession ? ( hostId === activeDevice.hostId)?.detail } visible={props.visible} onFloat={floatActive} onClose={() => closeActive(false)} onPowerOff={() => closeActive(true)} /> ) : loading ? ( host.id === pendingDevice.hostId)?.label ?? "Device host"} · ${pendingDevice.version}` : "" } stage="opening" message={ loadError ?? (pendingDevice ? pendingDevice.booted ? "Opening device…" : "Starting device…" : state.hostStatus === "installing" ? (state.hostStatusDetail ?? "Installing device support…") : "Finding devices…") } error={loadError !== null} > {loadError !== null ? ( ) : null} ) : (
{grouped.length === 0 ? ( <>

{state.hostStatus === "failed" ? (state.hostStatusDetail ?? "The device hub failed to start.") : "No simulators or emulators were found on this environment."}

) : null} {hostReady && grouped.length > 0 ? (
{grouped.map((group) => (

{platformLabel(group.platform)}

{group.devices.map((device) => (
{device.name} {`${state.hosts.find((host) => host.id === device.hostId)?.label} · ${device.version} · ${device.booted ? "Running" : "Stopped"}`}
))}
))}
) : null} {hostReady && !isAndroidDiscoveryUncertain(state) && !state.devices.some((device) => device.platform === "android") && !unavailablePlatforms.some((platform) => platform.platform === "android") ? (

No Android virtual devices found. Create one in Android Studio's Device Manager, then refresh.

) : null} {loaded && !hostBusy ? ( ) : null}
)}
); } function DeviceNotice(props: { readonly onDismiss: () => void; readonly children: ReactNode }) { return (
{props.children}
); } function DeviceDiscoveryWarning(props: { readonly label: string; readonly detail: string; readonly incompletePlatforms: readonly DevicePlatform[]; readonly onRetry: () => Promise; }) { const [open, setOpen] = useState(false); const [retrying, setRetrying] = useState(false); const [dismissedDetail, setDismissedDetail] = useState(null); if (dismissedDetail === props.detail) return null; const platforms = props.incompletePlatforms.map((platform) => platform === "ios" ? "iOS" : "Android", ); return (
{platforms.length > 0 ? `${platforms.join(" and ")} ${platforms.length > 1 ? "lists" : "list"} on ${props.label} may be incomplete.` : `Device discovery on ${props.label} reported a warning.`} {platforms.length > 0 ? ( ) : null} } > Details
{props.detail}
); } function groupDevices(state: DeviceServiceState) { const groups: Array<{ platform: DevicePlatform; devices: DeviceSummary[] }> = []; for (const platform of ["ios", "android"] as const) { const devices = state.devices .filter((device) => device.platform === platform) .toSorted((a, b) => Number(b.booted) - Number(a.booted) || a.name.localeCompare(b.name)); if (devices.length > 0) groups.push({ platform, devices }); } return groups; }