Skip to content
TypeScript

refactor(web): device panel reads hub state from atoms (#25265)

Julius Marminge0a3b561bc090
diff --git a/apps/web/src/components/device/DeviceAndroidFoldControls.tsx b/apps/web/src/components/device/DeviceAndroidFoldControls.tsx
index 709c1985292..b680a20f1df 100644
--- a/apps/web/src/components/device/DeviceAndroidFoldControls.tsx
+++ b/apps/web/src/components/device/DeviceAndroidFoldControls.tsx
@@ -1,75 +1,45 @@
import type { DeviceHubAccess } from "@t3tools/client-runtime/state/deviceHubAccess";
-import { useEffect, useRef, useState } from "react";
+import { useAtomMount, useAtomSet, useAtomValue } from "@effect/atom-react";
+import { useRef, useState } from "react";
import { Button } from "~/components/ui/button";
import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
-import {
- AndroidFoldError,
- readAndroidFold,
- setAndroidFold,
- type AndroidFoldPosture,
- type AndroidFoldState,
-} from "./deviceFold";
+import { AndroidFoldError, setAndroidFold, type AndroidFoldPosture } from "./deviceFold";
+import { androidFoldReadAtom, androidFoldViewAtom, foldAngle, NOOP_ATOM } from "./deviceHubAtoms";
import { DeviceDuoGlyph } from "./DeviceDuoGlyph";
export function DeviceAndroidFoldControls(props: {
readonly access: DeviceHubAccess;
+ readonly deviceKey: string;
readonly deviceId: string;
readonly visible: boolean;
readonly enabled: boolean;
readonly screenWidth: number | undefined;
readonly screenHeight: number | undefined;
- readonly onFoldAngle: (angle: number | null) => void;
readonly renewAccess: () => Promise<DeviceHubAccess | null>;
}) {
- const [fold, setFold] = useState<AndroidFoldState | null>(null);
const [pending, setPending] = useState(false);
const [error, setError] = useState<string | null>(null);
const busy = useRef(false);
- const mounted = useRef(true);
- const { access, deviceId, visible, enabled, screenWidth, screenHeight, onFoldAngle } = props;
-
- useEffect(() => {
- mounted.current = true;
- return () => {
- mounted.current = false;
- };
- }, []);
-
- useEffect(() => {
- if (!visible || !enabled || pending || !screenWidth || !screenHeight) return;
- const controller = new AbortController();
- let retry: number | undefined;
- const read = () => {
- void readAndroidFold(access, deviceId, controller.signal)
- .then((next) => {
- if (!controller.signal.aborted) {
- setFold(next);
- onFoldAngle(
- next.supported ? (next.hingeAngle ?? (next.posture === "closed" ? 0 : 180)) : null,
- );
- }
- })
- .catch((cause: unknown) => {
- // Retrying an expired ticket cannot succeed. New access re-runs this effect.
- const expired = cause instanceof AndroidFoldError && cause.status === 401;
- if (!controller.signal.aborted && !expired) retry = window.setTimeout(read, 3_000);
- });
- };
- read();
- return () => {
- controller.abort();
- window.clearTimeout(retry);
- };
- }, [access, deviceId, visible, enabled, screenWidth, screenHeight, pending, onFoldAngle]);
+ const { access, deviceKey, deviceId, visible, enabled, screenWidth, screenHeight } = props;
+ const viewAtom = androidFoldViewAtom(deviceKey);
+ const { fold } = useAtomValue(viewAtom);
+ const setView = useAtomSet(viewAtom);
+ // A change in flight owns the posture; reading meanwhile could show the old one.
+ useAtomMount(
+ visible && enabled && !pending && screenWidth && screenHeight
+ ? androidFoldReadAtom({ deviceKey, access, deviceId, screenWidth, screenHeight })
+ : NOOP_ATOM,
+ );
if (!fold?.supported || !props.visible) return null;
+ const setAngle = (angle: number) => setView((current) => ({ ...current, angle }));
const change = (posture: AndroidFoldPosture) => {
if (busy.current || !props.enabled) return;
busy.current = true;
setPending(true);
setError(null);
- props.onFoldAngle(posture === "closed" ? 0 : 180);
+ setAngle(posture === "closed" ? 0 : 180);
const controller = new AbortController();
const timeout = window.setTimeout(() => controller.abort(), 12_000);
const send = (access: DeviceHubAccess) =>
@@ -82,28 +52,21 @@ export function DeviceAndroidFoldControls(props: {
if (!renewed || controller.signal.aborted) throw cause;
return send(renewed);
})
- .then((next) => {
- if (mounted.current) {
- setFold(next);
- props.onFoldAngle(next.hingeAngle ?? (next.posture === "closed" ? 0 : 180));
- }
- })
+ .then((next) => setView({ fold: next, angle: foldAngle(next) }))
.catch((cause: unknown) => {
- if (mounted.current) {
- props.onFoldAngle(fold.hingeAngle ?? (fold.posture === "closed" ? 0 : 180));
- setError(
- controller.signal.aborted
- ? "Fold command timed out."
- : cause instanceof Error
- ? cause.message
- : "Could not change fold posture.",
- );
- }
+ setAngle(foldAngle(fold));
+ setError(
+ controller.signal.aborted
+ ? "Fold command timed out."
+ : cause instanceof Error
+ ? cause.message
+ : "Could not change fold posture.",
+ );
})
.finally(() => {
window.clearTimeout(timeout);
busy.current = false;
- if (mounted.current) setPending(false);
+ setPending(false);
});
};
diff --git a/apps/web/src/components/device/DeviceDuoViewport.tsx b/apps/web/src/components/device/DeviceDuoViewport.tsx
index befd42981e3..fe3726de5dd 100644
--- a/apps/web/src/components/device/DeviceDuoViewport.tsx
+++ b/apps/web/src/components/device/DeviceDuoViewport.tsx
@@ -1,37 +1,43 @@
-import { useEffect, useRef, type RefObject } from "react";
+import { useEffect, useRef } from "react";
import type { DuoViewer } from "@t3tools/client-runtime/device/duo-viewer";
import type { DeviceModelSource } from "@t3tools/client-runtime/device/model";
-import { createPhoneInteraction } from "@t3tools/client-runtime/device/phone-interaction";
+import type { createPhoneInteraction } from "@t3tools/client-runtime/device/phone-interaction";
import { createCanvasFrameSink } from "@t3tools/client-runtime/device/frame";
import type { DeviceScreenSize, DeviceStreamClient } from "@t3tools/client-runtime/device/stream";
import { createDuoPinch } from "@t3tools/client-runtime/device/duo-control";
-import { bindPhoneTrackpad } from "./phoneTrackpad";
-import { observeResize } from "../../lib/observeResize";
+import { mountDeviceViewer } from "./mountDeviceViewer";
const loadDuoViewer = () => import("@t3tools/client-runtime/device/duo-viewer");
export function DeviceDuoViewport(props: {
readonly model: DeviceModelSource;
- readonly source: RefObject<HTMLCanvasElement | null>;
+ readonly source: HTMLCanvasElement;
readonly onFrameListener: (listener: (() => void) | null) => void;
readonly onResetReady: (reset: (() => void) | null) => void;
readonly onInputCancel: (cancel: (() => void) | null) => void;
- readonly client: RefObject<DeviceStreamClient | null>;
+ readonly client: DeviceStreamClient;
readonly screen: DeviceScreenSize | null;
readonly hingePreview: number | null;
- readonly controlError: string | null;
+ readonly onControlRejectedListener: (listener: (() => void) | null) => void;
readonly onUnavailable: () => void;
}) {
- const hostRef = useRef<HTMLDivElement | null>(null);
- const canvasRef = useRef<HTMLCanvasElement | null>(null);
- const viewerRef = useRef<DuoViewer | null>(null);
+ const viewerRef = useRef<
+ (DuoViewer & { readonly sources: Record<1 | 3, HTMLCanvasElement> }) | null
+ >(null);
const interactionRef = useRef<ReturnType<typeof createPhoneInteraction> | null>(null);
const pinchRef = useRef<ReturnType<typeof createDuoPinch> | null>(null);
- const trackpadRef = useRef<ReturnType<typeof bindPhoneTrackpad> | null>(null);
const screenRef = useRef(props.screen);
const modelRef = useRef(props.model);
const previewRef = useRef(props.hingePreview);
- const { source, client, onInputCancel, onResetReady, onUnavailable, onFrameListener } = props;
+ const {
+ source,
+ client,
+ onInputCancel,
+ onControlRejectedListener,
+ onResetReady,
+ onUnavailable,
+ onFrameListener,
+ } = props;
useEffect(() => {
screenRef.current = props.screen;
@@ -40,84 +46,60 @@ export function DeviceDuoViewport(props: {
viewerRef.current?.setScreen(props.screen);
}, [props.screen, props.model]);
- useEffect(() => {
- if (props.controlError || !props.screen) {
- trackpadRef.current?.cancel();
- viewerRef.current?.rejectOrientation();
- }
- }, [props.controlError, props.screen]);
-
useEffect(() => {
previewRef.current = props.hingePreview;
if (!pinchRef.current?.active) viewerRef.current?.setHingePreview(props.hingePreview);
}, [props.hingePreview]);
- useEffect(() => {
- const host = hostRef.current;
- const canvas = canvasRef.current;
- const decoded = source.current;
- if (!host || !canvas || !decoded) return;
- let disposed = false;
- let trackpad: ReturnType<typeof bindPhoneTrackpad> | null = null;
- let stopTrackpadEnd: (() => void) | undefined;
- const resize = () => {
- const { width, height } = host.getBoundingClientRect();
- viewerRef.current?.resize(width, height, window.devicePixelRatio);
- };
- const stopObserving = observeResize(host, resize);
- const blur = () => {
- interactionRef.current?.end();
- trackpad?.cancel();
- viewerRef.current?.cancelInput();
- };
- onInputCancel(blur);
- window.addEventListener("blur", blur);
- void loadDuoViewer()
- .then(({ createDuoViewer }) => {
- if (disposed) return;
- const sources = {
- 1: document.createElement("canvas"),
- 3: document.createElement("canvas"),
- };
- const viewer = createDuoViewer({
- canvas,
- sources,
- onUnavailable,
- onPanelRequested: (panel) =>
- client.current?.controlDuo({
- control: "physical",
- value: panel === 1 ? "facedown" : "faceup",
- }),
- onOrientationRequested: (value) =>
- client.current?.controlDuo({ control: "orientation", value }),
- onModelError: (cause) => console.warn("Device 3D asset could not load", cause),
- model: modelRef.current,
+ // The 3D viewer lives as long as its canvas; later prop changes are pushed into it above.
+ const mountViewer = (canvas: HTMLCanvasElement | null) => {
+ const host = canvas?.parentElement;
+ if (!canvas || !host) return;
+ return mountDeviceViewer(canvas, host, {
+ load: () =>
+ loadDuoViewer().then(({ createDuoViewer }) => () => {
+ const sources = {
+ 1: document.createElement("canvas"),
+ 3: document.createElement("canvas"),
+ };
+ const viewer = createDuoViewer({
+ canvas,
+ sources,
+ onUnavailable,
+ onPanelRequested: (panel) =>
+ client.controlDuo({
+ control: "physical",
+ value: panel === 1 ? "facedown" : "faceup",
+ }),
+ onOrientationRequested: (value) => client.controlDuo({ control: "orientation", value }),
+ onModelError: (cause) => console.warn("Device 3D asset could not load", cause),
+ model: modelRef.current,
+ });
+ return { ...viewer, sources };
+ }),
+ touch: (phase, point) => client.sendRawTouch(phase, point.x, point.y),
+ viewerRef,
+ interactionRef,
+ onInputCancel,
+ onResetReady,
+ onFrameListener,
+ onUnavailable,
+ cancelInput: (viewer) => viewer.cancelInput(),
+ ready: ({ viewer, cancelTrackpad }) => {
+ onControlRejectedListener(() => {
+ cancelTrackpad();
+ viewer.rejectOrientation();
});
- viewerRef.current = viewer;
- onResetReady(viewer.resetPose);
viewer.setScreen(screenRef.current);
- const primaryFrame = () => {
- const panel = screenRef.current?.screenId;
- if (panel === 1 || panel === 3) viewer.frameUpdated(panel, decoded);
- };
- onFrameListener(primaryFrame);
- primaryFrame();
viewer.setHingePreview(previewRef.current);
- client.current?.setDuoPanels({
+ client.setDuoPanels({
onScreen(next) {
screenRef.current = next;
interactionRef.current?.end();
viewer.setScreen(next);
},
- cover: createCanvasFrameSink(sources[1], () => viewer.frameUpdated(1)),
- inner: createCanvasFrameSink(sources[3], () => viewer.frameUpdated(3)),
- });
- interactionRef.current = createPhoneInteraction({
- screenPoint: (point, captured) => viewer.screenPoint(point.x, point.y, captured),
- touch: (phase, point) => client.current?.sendRawTouch(phase, point.x, point.y),
- orbit: viewer.orbit,
- zoomBy: () => {},
- onInteractionActive: viewer.setInteractionActive,
+ cover: createCanvasFrameSink(viewer.sources[1], () => viewer.frameUpdated(1)),
+ inner: createCanvasFrameSink(viewer.sources[3], () => viewer.frameUpdated(3)),
});
const pinch = createDuoPinch({
angle: () =>
@@ -127,43 +109,32 @@ export function DeviceDuoViewport(props: {
contains: (x, y) => !!screenRef.current && viewer.beginHinge(x, y),
change: (angle) => {
viewer.setHingePreview(angle ?? previewRef.current, true);
- if (angle !== null) client.current?.controlDuo({ control: "angle", value: angle });
+ if (angle !== null) client.controlDuo({ control: "angle", value: angle });
},
});
pinchRef.current = pinch;
- trackpad = bindPhoneTrackpad(canvas, interactionRef.current, {
- begin(x, y) {
- interactionRef.current?.end();
- return pinch.begin(x, y);
+ return {
+ frame: () => {
+ const panel = screenRef.current?.screenId;
+ if (panel === 1 || panel === 3) viewer.frameUpdated(panel, source);
},
- move: pinch.move,
- end: pinch.end,
- });
- trackpadRef.current = trackpad;
- stopTrackpadEnd = window.desktopBridge?.onTrackpadScrollEnd?.(() => trackpad?.endOrbit());
- resize();
- })
- .catch(() => {
- if (!disposed) onUnavailable();
- });
- return () => {
- disposed = true;
- stopTrackpadEnd?.();
- trackpad?.dispose();
- trackpadRef.current = null;
- pinchRef.current = null;
- interactionRef.current?.end();
- interactionRef.current = null;
- onInputCancel(null);
- onResetReady(null);
- onFrameListener(null);
- client.current?.setDuoPanels(null);
- stopObserving();
- window.removeEventListener("blur", blur);
- viewerRef.current?.dispose();
- viewerRef.current = null;
- };
- }, [onInputCancel, onResetReady, client, onUnavailable, source, onFrameListener]);
+ pinch: {
+ begin(x, y) {
+ interactionRef.current?.end();
+ return pinch.begin(x, y);
+ },
+ move: pinch.move,
+ end: pinch.end,
+ },
+ dispose: () => {
+ pinchRef.current = null;
+ onControlRejectedListener(null);
+ client.setDuoPanels(null);
+ },
+ };
+ },
+ });
+ };
const point = (event: React.PointerEvent<HTMLCanvasElement>) => {
const rect = event.currentTarget.getBoundingClientRect();
@@ -174,13 +145,13 @@ export function DeviceDuoViewport(props: {
};
return (
<div className="absolute inset-0">
- <div ref={hostRef} className="absolute inset-0">
+ <div className="absolute inset-0">
<div
aria-hidden
className="pointer-events-none absolute bottom-[6%] left-1/2 h-5 w-2/5 -translate-x-1/2 rounded-full bg-foreground/10 blur-xl"
/>
<canvas
- ref={canvasRef}
+ ref={mountViewer}
aria-label="Interactive 3D iPhone Duo. Drag the screen to interact. Drag outside it or swipe with two fingers to turn. Pinch over the device to open or close its hinge."
className="size-full touch-none"
onPointerDown={(event) => {
diff --git a/apps/web/src/components/device/DevicePanel.browser.test.tsx b/apps/web/src/components/device/DevicePanel.browser.test.tsx
index 6c509f67838..8e8e0d27eb9 100644
--- a/apps/web/src/components/device/DevicePanel.browser.test.tsx
+++ b/apps/web/src/components/device/DevicePanel.browser.test.tsx
@@ -20,6 +20,7 @@ type CommandResult =
const mocks = vi.hoisted(() => ({
open: vi.fn<(request: unknown) => Promise<CommandResult>>(),
close: vi.fn<(request: unknown) => Promise<CommandResult>>(),
+ list: vi.fn<(request: unknown) => Promise<CommandResult>>(),
openDevice: vi.fn(),
closeSurface: vi.fn(),
}));
@@ -61,17 +62,28 @@ const deviceState: DeviceServiceState = {
revision: 1,
};
let currentState = deviceState;
-vi.mock("~/state/device", () => ({
- deviceEnvironment: { list: "list", open: "open", close: "close" },
- useDeviceState: () => ({ state: currentState, loaded: true }),
-}));
+// One probe per environment, however many views mount it; each probe sends one list.
+vi.mock("~/state/device", async () => {
+ const Effect = await import("effect/Effect");
+ const { AsyncResult, Atom } = await import("effect/reactivity");
+ return {
+ deviceEnvironment: { list: "list", open: "open", close: "close" },
+ deviceHostProbeAtom: Atom.family((environmentId: string) =>
+ Atom.make(() => Effect.promise(() => mocks.list({ environmentId, input: {} }))),
+ ),
+ NO_DEVICE_PROBE_ATOM: Atom.make(AsyncResult.initial<void, never>()),
+ useDeviceState: () => ({ state: currentState, loaded: true }),
+ };
+});
vi.mock("~/state/use-atom-command", () => ({
useAtomCommand: (command: string) =>
command === "open"
? mocks.open
: command === "close"
? mocks.close
- : () => Promise.resolve({ _tag: "Success", value: {} }),
+ : command === "list"
+ ? mocks.list
+ : () => Promise.resolve({ _tag: "Success", value: {} }),
}));
vi.mock("~/state/query", () => ({ formatEnvironmentQueryError: () => "Device failed" }));
vi.mock("~/rightPanelStore", () => ({
@@ -141,6 +153,7 @@ const errors = () => container.querySelectorAll('[role="alert"]');
function setup() {
vi.resetAllMocks();
+ mocks.list.mockResolvedValue({ _tag: "Success", value: { hostId: "local", deviceId: "" } });
currentState = deviceState;
container = document.createElement("div");
container.style.width = "480px";
@@ -185,3 +198,18 @@ describe("DevicePanel thread switches", () => {
]);
});
});
+
+describe("DevicePanel host probe", () => {
+ it("probes the hosts once while setup shows inside the panel", async () => {
+ setup();
+ currentState = { ...deviceState, onboardingCompleted: false };
+ // An environment no other test probed, so its probe starts fresh.
+ const threadRef = { ...threadA, environmentId: EnvironmentId.make("environment-setup") };
+ await using _screen = await render(devicePanel(threadRef), { container });
+
+ await vi.waitFor(() => expect(mocks.list).toHaveBeenCalled());
+ expect(mocks.list.mock.calls).toEqual([
+ [{ environmentId: threadRef.environmentId, input: {} }],
+ ]);
+ });
+});
diff --git a/apps/web/src/components/device/DevicePanel.tsx b/apps/web/src/components/device/DevicePanel.tsx
index 9a2cb258f5c..8eb40a82325 100644
--- a/apps/web/src/components/device/DevicePanel.tsx
+++ b/apps/web/src/components/device/DevicePanel.tsx
@@ -6,7 +6,8 @@ import type {
ScopedThreadRef,
} from "@t3tools/contracts";
import { ArrowUpRight, CircleAlert, Play, Smartphone, X } from "lucide-react";
-import { type ReactNode, useEffect, useState } from "react";
+import { useAtomMount } from "@effect/atom-react";
+import { type ReactNode, useState } from "react";
import { usePreviewMiniPlayerStore } from "~/previewMiniPlayerStore";
import {
@@ -21,7 +22,12 @@ import { WizardPopup } from "~/components/ui/wizard";
import { Spinner } from "~/components/ui/spinner";
import { cn } from "~/lib/utils";
import { focusPanelTerminalAfterClose } from "~/lib/terminalFocus";
-import { deviceEnvironment, useDeviceState } from "~/state/device";
+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";
@@ -61,11 +67,11 @@ export function DevicePanel(props: {
const hostDisabled = state.hostStatus === "disabled";
- // Opening setup never grants permission to install or start helpers.
- useEffect(() => {
- if (!props.visible || !loaded || hostDisabled) return;
- void list({ environmentId, input: {} });
- }, [environmentId, list, loaded, props.visible, hostDisabled]);
+ 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
diff --git a/apps/web/src/components/device/DevicePhoneViewport.tsx b/apps/web/src/components/device/DevicePhoneViewport.tsx
index c1e5341e711..d524e9d9ded 100644
--- a/apps/web/src/components/device/DevicePhoneViewport.tsx
+++ b/apps/web/src/components/device/DevicePhoneViewport.tsx
@@ -1,14 +1,13 @@
-import { useEffect, useRef, type RefObject } from "react";
+import { useEffect, useRef } from "react";
import type { PhoneViewer } from "@t3tools/client-runtime/device/phone-viewer";
import type {
DeviceAccessorySource,
DeviceModelSource,
} from "@t3tools/client-runtime/device/model";
import type { DeviceShapeProfile } from "@t3tools/client-runtime/device/shape-profile";
-import { createPhoneInteraction } from "@t3tools/client-runtime/device/phone-interaction";
+import type { createPhoneInteraction } from "@t3tools/client-runtime/device/phone-interaction";
import type { DeviceScreenSize, DeviceStreamClient } from "@t3tools/client-runtime/device/stream";
-import { bindPhoneTrackpad } from "./phoneTrackpad";
-import { observeResize } from "../../lib/observeResize";
+import { mountDeviceViewer } from "./mountDeviceViewer";
const loadPhoneViewer = () => import("@t3tools/client-runtime/device/phone-viewer");
@@ -16,17 +15,15 @@ export function DevicePhoneViewport(props: {
readonly profile: DeviceShapeProfile;
readonly model: DeviceModelSource | null;
readonly accessory: DeviceAccessorySource | null;
- readonly source: RefObject<HTMLCanvasElement | null>;
+ readonly source: HTMLCanvasElement;
readonly onFrameListener: (listener: (() => void) | null) => void;
readonly onResetReady: (reset: (() => void) | null) => void;
readonly onInputCancel: (cancel: (() => void) | null) => void;
- readonly client: RefObject<DeviceStreamClient | null>;
+ readonly client: DeviceStreamClient;
readonly screen: DeviceScreenSize | null;
readonly foldAngle: number | null;
readonly onUnavailable: () => void;
}) {
- const hostRef = useRef<HTMLDivElement | null>(null);
- const canvasRef = useRef<HTMLCanvasElement | null>(null);
const viewerRef = useRef<PhoneViewer | null>(null);
const interactionRef = useRef<ReturnType<typeof createPhoneInteraction> | null>(null);
const screenRef = useRef(props.screen);
@@ -52,72 +49,39 @@ export function DevicePhoneViewport(props: {
viewerRef.current?.setScreen(props.screen, props.profile);
}, [props.screen, props.profile, props.model, props.accessory]);
- useEffect(() => {
- const host = hostRef.current;
- const canvas = canvasRef.current;
- const decoded = source.current;
- if (!host || !canvas || !decoded) return;
- let disposed = false;
- let trackpad: ReturnType<typeof bindPhoneTrackpad> | null = null;
- let stopTrackpadEnd: (() => void) | undefined;
- const resize = () => {
- const { width, height } = host.getBoundingClientRect();
- viewerRef.current?.resize(width, height, window.devicePixelRatio);
- };
- const stopObserving = observeResize(host, resize);
- const blur = () => {
- interactionRef.current?.end();
- trackpad?.cancel();
- };
- onInputCancel(blur);
- window.addEventListener("blur", blur);
- void loadPhoneViewer()
- .then(({ createPhoneViewer }) => {
- if (disposed) return;
- const viewer = createPhoneViewer({
- canvas,
- source: decoded,
- onUnavailable,
- onModelError: (cause) => console.warn("Device 3D asset could not load", cause),
- profile: profileRef.current,
- model: modelRef.current,
- accessory: accessoryRef.current,
- foldAngle: foldAngleRef.current,
- });
- viewerRef.current = viewer;
- onResetReady(viewer.resetPose);
+ // The 3D viewer lives as long as its canvas; later prop changes are pushed into it above.
+ const mountViewer = (canvas: HTMLCanvasElement | null) => {
+ const host = canvas?.parentElement;
+ if (!canvas || !host) return;
+ return mountDeviceViewer(canvas, host, {
+ load: () =>
+ loadPhoneViewer().then(
+ ({ createPhoneViewer }) =>
+ () =>
+ createPhoneViewer({
+ canvas,
+ source,
+ onUnavailable,
+ onModelError: (cause) => console.warn("Device 3D asset could not load", cause),
+ profile: profileRef.current,
+ model: modelRef.current,
+ accessory: accessoryRef.current,
+ foldAngle: foldAngleRef.current,
+ }),
+ ),
+ touch: (phase, point) => client.sendTouch(phase, point.x, point.y),
+ viewerRef,
+ interactionRef,
+ onInputCancel,
+ onResetReady,
+ onFrameListener,
+ onUnavailable,
+ ready: ({ viewer }) => {
viewer.setScreen(screenRef.current);
- onFrameListener(viewer.frameUpdated);
- interactionRef.current = createPhoneInteraction({
- screenPoint: (point, captured) => viewer.screenPoint(point.x, point.y, captured),
- touch: (phase, point) => client.current?.sendTouch(phase, point.x, point.y),
- orbit: viewer.orbit,
- zoomBy: () => {},
- onInteractionActive: viewer.setInteractionActive,
- });
- trackpad = bindPhoneTrackpad(canvas, interactionRef.current);
- stopTrackpadEnd = window.desktopBridge?.onTrackpadScrollEnd?.(() => trackpad?.endOrbit());
- resize();
- viewer.frameUpdated();
- })
- .catch(() => {
- if (!disposed) onUnavailable();
- });
- return () => {
- disposed = true;
- stopTrackpadEnd?.();
- trackpad?.dispose();
- interactionRef.current?.end();
- interactionRef.current = null;
- onInputCancel(null);
- onResetReady(null);
- onFrameListener(null);
- stopObserving();
- window.removeEventListener("blur", blur);
- viewerRef.current?.dispose();
- viewerRef.current = null;
- };
- }, [onInputCancel, onResetReady, client, onFrameListener, onUnavailable, source]);
+ return { frame: viewer.frameUpdated };
+ },
+ });
+ };
const point = (event: React.PointerEvent<HTMLCanvasElement>) => {
const rect = event.currentTarget.getBoundingClientRect();
@@ -128,13 +92,13 @@ export function DevicePhoneViewport(props: {
};
return (
<div className="absolute inset-0">
- <div ref={hostRef} className="absolute inset-0">
+ <div className="absolute inset-0">
<div
aria-hidden
className="pointer-events-none absolute bottom-[6%] left-1/2 h-5 w-2/5 -translate-x-1/2 rounded-full bg-foreground/10 blur-xl"
/>
<canvas
- ref={canvasRef}
+ ref={mountViewer}
aria-label="Interactive 3D device. Drag the screen to interact. Drag outside it or swipe with two fingers to turn."
className="size-full touch-none"
onPointerDown={(event) => {
diff --git a/apps/web/src/components/device/DeviceSetup.tsx b/apps/web/src/components/device/DeviceSetup.tsx
index 18a4fa60212..d3866129795 100644
--- a/apps/web/src/components/device/DeviceSetup.tsx
+++ b/apps/web/src/components/device/DeviceSetup.tsx
@@ -3,7 +3,8 @@ import type { DevicePlatform, DeviceServiceState, EnvironmentId } from "@t3tools
import { Check } from "lucide-react";
import { Check as CheckGlyph, CircleAlert } from "lucide";
import { AuthSettingsWriteScope } from "@t3tools/contracts";
-import { useEffect, useState } from "react";
+import { useAtomMount } from "@effect/atom-react";
+import { useState } from "react";
import { Button } from "~/components/ui/button";
import { DialogClose } from "~/components/ui/dialog";
@@ -11,7 +12,7 @@ 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 } from "~/state/device";
+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";
@@ -141,10 +142,7 @@ export function DeviceSetup(props: {
(host) => host.kind === "local" && !host.platforms.some((platform) => platform.available),
);
- // Remote hosts report platforms only after a probe, like the Device panel's refresh on open.
- useEffect(() => {
- if (enabled) void list({ environmentId: props.environmentId, input: {} });
- }, [enabled, list, props.environmentId]);
+ useAtomMount(enabled ? deviceHostProbeAtom(props.environmentId) : NO_DEVICE_PROBE_ATOM);
const update = async (
kind: NonNullable<typeof pending>,
diff --git a/apps/web/src/components/device/DeviceStreamView.tsx b/apps/web/src/components/device/DeviceStreamView.tsx
index e0ae786c762..222423bf2c8 100644
--- a/apps/web/src/components/device/DeviceStreamView.tsx
+++ b/apps/web/src/components/device/DeviceStreamView.tsx
@@ -1,31 +1,38 @@
import type { DevicePlatform, EnvironmentId } from "@t3tools/contracts";
-import { useEffect, useRef, useState, type ReactNode } from "react";
+import { useAtomValue } from "@effect/atom-react";
+import * as Option from "effect/Option";
+import { AsyncResult, Atom } from "effect/reactivity";
+import { useId, useRef, useState, type ReactNode } from "react";
import { cn } from "~/lib/utils";
import { Button } from "~/components/ui/button";
-import { refreshDeviceHubAccess, renewDeviceHubAccess, useDeviceHubAccess } from "~/state/device";
-import { createCanvasFrameSink } from "@t3tools/client-runtime/device/frame";
+import { renewDeviceHubAccess, useDeviceHubAccess } from "~/state/device";
import { resolveDeviceShape } from "@t3tools/client-runtime/device/shape-profile";
import { deviceKeyboard, deviceModel } from "./deviceModels";
import { fitDeviceFrame } from "./deviceFrameLayout";
import { DeviceDuoViewport } from "./DeviceDuoViewport";
import { DeviceDuoControls } from "./DeviceDuoControls";
import { DeviceAndroidFoldControls } from "./DeviceAndroidFoldControls";
-import type { DuoControlState } from "@t3tools/client-runtime/device/duo-control";
import { DevicePhoneViewport } from "./DevicePhoneViewport";
import { DeviceLoadingView } from "./DeviceLoadingView";
-import { type DeviceAxElement, fetchDeviceAxTree } from "./deviceHubApi";
+import type { DeviceAxElement } from "./deviceHubApi";
+import { androidFoldViewAtom, deviceAxElementsAtom } from "./deviceHubAtoms";
import {
- createDeviceStreamClient,
- type DeviceHardwareButton,
- type DeviceScreenSize,
- type DeviceStreamClient,
- type DeviceStreamStatus,
-} from "@t3tools/client-runtime/device/stream";
+ deviceScreenKey,
+ deviceStreamSessionAtom,
+ type DeviceStreamSession,
+ IDLE_DEVICE_STREAM_STATE,
+} from "./deviceStreamSession";
+import type { DeviceHardwareButton, DeviceScreenSize } from "@t3tools/client-runtime/device/stream";
import { observeResize } from "~/lib/observeResize";
-import { useStableCallback } from "~/hooks/useStableCallback";
-const AX_POLL_INTERVAL_MS = 2_000;
+const NO_SESSION_ATOM = Atom.make<DeviceStreamSession | null>(null).pipe(
+ Atom.withLabel("device-stream:none"),
+);
+const NO_AX_ELEMENTS: ReadonlyArray<DeviceAxElement> = [];
+const NO_AX_ATOM = Atom.make(AsyncResult.initial<ReadonlyArray<DeviceAxElement>, never>()).pipe(
+ Atom.withLabel("device-ax-elements:none"),
+);
const CONTROLS_RAIL_WIDTH = 56;
function screenAspect(platform: DevicePlatform, screen: DeviceScreenSize | null): number {
@@ -65,6 +72,7 @@ export interface DeviceViewControls {
readonly resetView: () => void;
readonly foldingControls?: ReactNode;
readonly keyboard: { readonly attached: boolean; readonly toggle: () => void } | null;
+ readonly handle: DeviceStreamHandle | null;
}
export interface DeviceStreamHandle {
@@ -84,120 +92,56 @@ export function DeviceStreamView(props: {
readonly allowPhoneView?: boolean;
readonly renderControls?: (view: DeviceViewControls) => ReactNode;
readonly axOverlay?: boolean;
- readonly onHandle?: (handle: DeviceStreamHandle | null) => void;
- readonly onScreen?: (screen: DeviceScreenSize | null) => void;
+ /** Lets a parent read this view's own stream state, such as its screen size. */
+ readonly viewId?: string;
}) {
- const [duoControl, setDuoControl] = useState<DuoControlState>({
- pending: false,
- requested: null,
- error: null,
- });
const model = deviceModel(props.platform, props.deviceName ?? "");
const isDuo = model?.id === "iphone-duo";
const [presentation, setPresentation] = useState<"phone" | "flat">("phone");
const [keyboardAttached, setKeyboardAttached] = useState(false);
- const [phoneUnavailable, setPhoneUnavailable] = useState(false);
- const onPhoneUnavailable = useStableCallback(() => setPhoneUnavailable(true));
const cancelPhoneInputRef = useRef<(() => void) | null>(null);
- const cancelPhoneInput = useStableCallback(() => cancelPhoneInputRef.current?.());
+ const cancelPhoneInput = () => cancelPhoneInputRef.current?.();
const resetViewRef = useRef<(() => void) | null>(null);
- const onResetReady = useStableCallback((reset: (() => void) | null) => {
+ const onResetReady = (reset: (() => void) | null) => {
resetViewRef.current = reset;
- });
- const frameListenerRef = useRef<(() => void) | null>(null);
- const onFrameListener = useStableCallback((listener: (() => void) | null) => {
- frameListenerRef.current = listener;
- });
- const onInputCancel = useStableCallback((cancel: (() => void) | null) => {
+ };
+ const onInputCancel = (cancel: (() => void) | null) => {
cancelPhoneInputRef.current = cancel;
- });
+ };
const access = useDeviceHubAccess(props.environmentId, props.hostId);
- const canvasRef = useRef<HTMLCanvasElement | null>(null);
- const clientRef = useRef<DeviceStreamClient | null>(null);
- const [status, setStatus] = useState<DeviceStreamStatus>("connecting");
- const [hasFrame, setHasFrame] = useState(false);
- const [detail, setDetail] = useState<string | undefined>(undefined);
- const [showRestartNotice, setShowRestartNotice] = useState(false);
- const [screen, setScreen] = useState<DeviceScreenSize | null>(null);
- const [foldAngle, setFoldAngle] = useState<number | null>(null);
- const [mjpegUrl, setMjpegUrl] = useState<string | null>(null);
- const [mjpegGeneration, setMjpegGeneration] = useState(0);
- const attachMjpegImage = useStableCallback((image: HTMLImageElement | null) => {
- clientRef.current?.setMjpegImage(image);
- });
- const [inputState, setInputState] = useState<{ connected: boolean; detail?: string }>({
- connected: false,
- });
- const { onHandle, onScreen } = props;
-
- useEffect(() => {
- const canvas = canvasRef.current;
- if (!access || !canvas || !props.visible) {
- setStatus("connecting");
- onHandle?.(null);
- return;
- }
- const client = createDeviceStreamClient(
- { platform: props.platform, deviceId: props.deviceId, access },
- createCanvasFrameSink(canvas, () => frameListenerRef.current?.()),
- {
- onDuoControl: setDuoControl,
- onDuoUnavailable: onPhoneUnavailable,
- onStatus: (next, nextDetail) => {
- setStatus(next);
- if (next === "streaming") setHasFrame(true);
- setDetail(nextDetail);
- if (next !== "connecting") setShowRestartNotice(false);
- },
- onScreen: (next) => {
- setScreen(next);
- onScreen?.(next);
- },
- onUnauthorized: () => {
- refreshDeviceHubAccess(props.environmentId);
- },
- onMjpegFallback: (url) => {
- setMjpegUrl(url);
- setMjpegGeneration((generation) => generation + 1);
- },
- onCanvasVideo: () => setMjpegUrl(null),
- onInputConnected: (connected, detail) => {
- setInputState({ connected, ...(detail ? { detail } : {}) });
- if (!connected) setShowRestartNotice(false);
- onHandle?.({
- pressButton: client.pressButton,
- rotate: client.rotate,
- inputConnected: connected,
- });
- },
- },
- );
- clientRef.current = client;
- setPhoneUnavailable(false);
- setHasFrame(false);
- setMjpegUrl(null);
- setInputState({ connected: false });
- client.start();
- onHandle?.({ pressButton: client.pressButton, rotate: client.rotate, inputConnected: false });
- return () => {
- cancelPhoneInput();
- client.stop();
- clientRef.current = null;
- onHandle?.(null);
- onScreen?.(null);
- setScreen(null);
- };
- }, [
- access,
- cancelPhoneInput,
- onHandle,
- onPhoneUnavailable,
- onScreen,
- props.deviceId,
- props.environmentId,
- props.platform,
- props.visible,
- ]);
+ const ownViewId = useId();
+ const viewId = props.viewId ?? ownViewId;
+ const session = useAtomValue(
+ access && props.visible
+ ? deviceStreamSessionAtom({
+ environmentId: props.environmentId,
+ hostId: props.hostId,
+ platform: props.platform,
+ deviceId: props.deviceId,
+ access,
+ viewId,
+ })
+ : NO_SESSION_ATOM,
+ );
+ const client = session?.stream ?? null;
+ const canvas = session?.canvas ?? null;
+ const { status, detail, hasFrame, screen, mjpegUrl, mjpegGeneration, duoControl } =
+ session?.state ?? IDLE_DEVICE_STREAM_STATE;
+ const inputState = session?.state.input ?? IDLE_DEVICE_STREAM_STATE.input;
+ const phoneUnavailable = session?.state.phoneUnavailable ?? false;
+ const foldAngle = useAtomValue(
+ androidFoldViewAtom(deviceScreenKey(props.environmentId, props.hostId, props.deviceId)),
+ ).angle;
+ const attachMjpegImage = (image: HTMLImageElement | null) => {
+ if (!client || !image) return;
+ client.setMjpegImage(image);
+ return () => client.setMjpegImage(null);
+ };
+ const mountCanvas = (node: HTMLDivElement | null) => {
+ if (!node || !canvas) return;
+ node.append(canvas);
+ return () => canvas.remove();
+ };
const aspect = screenAspect(props.platform, screen);
@@ -212,18 +156,11 @@ export function DeviceStreamView(props: {
!mjpegUrl &&
!props.axOverlay &&
(!isDuo || screen?.supportsHingeAngle === true);
- useEffect(() => {
- if (!retainingFrame || !showPhone) return;
- const timeout = window.setTimeout(() => setShowRestartNotice(true), 2_000);
- return () => window.clearTimeout(timeout);
- }, [retainingFrame, showPhone]);
const controlsInset = props.renderControls && !showPhone ? CONTROLS_RAIL_WIDTH : 0;
// Fit the frame in both dimensions; pinned CSS height plus a width clamp distorts aspect-ratio.
- const hostRef = useRef<HTMLDivElement | null>(null);
const [host, setHost] = useState({ width: 0, height: 0 });
- useEffect(() => {
- const element = hostRef.current;
+ const hostRef = (element: HTMLDivElement | null) => {
if (!element) return;
const update = () => {
const rect = element.getBoundingClientRect();
@@ -235,7 +172,7 @@ export function DeviceStreamView(props: {
};
update();
return observeResize(element, update);
- }, []);
+ };
const frame = fitDeviceFrame(aspect, host.width, host.height, controlsInset);
const rotation = screenRotation(props.platform, screen);
@@ -255,29 +192,12 @@ export function DeviceStreamView(props: {
...(rotation ? { transform: `rotate(${rotation}deg)` } : {}),
};
- const [axElements, setAxElements] = useState<ReadonlyArray<DeviceAxElement>>([]);
- useEffect(() => {
- if (!props.axOverlay || !access || !props.visible) return;
- const target = { access, platform: props.platform, deviceId: props.deviceId };
- let controller: AbortController | null = null;
- let timer: ReturnType<typeof setTimeout> | null = null;
- let stopped = false;
- const poll = async () => {
- controller = new AbortController();
- try {
- const tree = await fetchDeviceAxTree(target, controller.signal);
- if (!stopped) setAxElements(tree.elements);
- } catch {}
- if (!stopped) timer = setTimeout(() => void poll(), AX_POLL_INTERVAL_MS);
- };
- void poll();
- return () => {
- stopped = true;
- controller?.abort();
- if (timer) clearTimeout(timer);
- setAxElements([]);
- };
- }, [access, props.axOverlay, props.deviceId, props.platform, props.visible]);
+ const axResult = useAtomValue(
+ props.axOverlay && access && props.visible
+ ? deviceAxElementsAtom({ access, platform: props.platform, deviceId: props.deviceId })
+ : NO_AX_ATOM,
+ );
+ const axElements = Option.getOrElse(AsyncResult.value(axResult), () => NO_AX_ELEMENTS);
const pointerActive = useRef(false);
const normalizedPoint = (event: React.PointerEvent<HTMLElement>) => {
@@ -302,7 +222,7 @@ export function DeviceStreamView(props: {
const resetView = () => {
if (!isDuo) {
const orientation = keyboardAttached ? "landscape_right" : "portrait";
- if (screen?.orientation !== orientation) clientRef.current?.setOrientation(orientation);
+ if (screen?.orientation !== orientation) client?.setOrientation(orientation);
}
resetViewRef.current?.();
};
@@ -336,7 +256,7 @@ export function DeviceStreamView(props: {
enabled={status === "streaming"}
screenWidth={screen?.width}
screenHeight={screen?.height}
- onFoldAngle={setFoldAngle}
+ deviceKey={deviceScreenKey(props.environmentId, props.hostId, props.deviceId)}
renewAccess={() => renewDeviceHubAccess(props.environmentId, props.hostId)}
/>
) : showPhone && isDuo && screen?.supportsHingeAngle ? (
@@ -346,7 +266,7 @@ export function DeviceStreamView(props: {
enabled={inputState.connected}
onCommand={(command) => {
cancelPhoneInput();
- clientRef.current?.controlDuo(command);
+ client?.controlDuo(command);
}}
/>
) : null,
@@ -357,13 +277,20 @@ export function DeviceStreamView(props: {
toggle: () => {
cancelPhoneInput();
if (!keyboardAttached && screen?.orientation !== "landscape_right")
- clientRef.current?.setOrientation("landscape_right");
+ client?.setOrientation("landscape_right");
setKeyboardAttached(!keyboardAttached);
},
}
: null,
showPhone: () => setPresentation("phone"),
showFlat: () => setPresentation("flat"),
+ handle: client
+ ? {
+ pressButton: client.pressButton,
+ rotate: client.rotate,
+ inputConnected: inputState.connected,
+ }
+ : null,
}}
onResetView={resetView}
/>
@@ -390,16 +317,16 @@ export function DeviceStreamView(props: {
return;
}
event.preventDefault();
- clientRef.current?.sendKey(event.nativeEvent, "down");
+ client?.sendKey(event.nativeEvent, "down");
}}
onPaste={(event) => {
if (event.target !== event.currentTarget) return;
event.preventDefault();
- clientRef.current?.sendText(event.clipboardData.getData("text/plain"));
+ client?.sendText(event.clipboardData.getData("text/plain"));
}}
onKeyUp={(event) => {
if (event.target !== event.currentTarget) return;
- clientRef.current?.sendKey(event.nativeEvent, "up");
+ client?.sendKey(event.nativeEvent, "up");
}}
>
<div
@@ -411,28 +338,28 @@ export function DeviceStreamView(props: {
(event.currentTarget.parentElement as HTMLElement | null)?.focus();
pointerActive.current = true;
const { x, y } = normalizedPoint(event);
- clientRef.current?.sendTouch("begin", x, y);
+ client?.sendTouch("begin", x, y);
}}
onPointerMove={(event) => {
if (!pointerActive.current) return;
const { x, y } = normalizedPoint(event);
- clientRef.current?.sendTouch("move", x, y);
+ client?.sendTouch("move", x, y);
}}
onPointerUp={(event) => {
if (!pointerActive.current) return;
pointerActive.current = false;
const { x, y } = normalizedPoint(event);
- clientRef.current?.sendTouch("end", x, y);
+ client?.sendTouch("end", x, y);
}}
onPointerCancel={(event) => {
if (!pointerActive.current) return;
pointerActive.current = false;
const { x, y } = normalizedPoint(event);
- clientRef.current?.sendTouch("end", x, y);
+ client?.sendTouch("end", x, y);
}}
>
- <canvas
- ref={canvasRef}
+ <div
+ ref={mountCanvas}
className={cn("absolute top-0 left-0", mjpegUrl && "hidden")}
style={mediaStyle}
/>
@@ -469,34 +396,34 @@ export function DeviceStreamView(props: {
</div>
) : null}
</div>
- {showPhone && isDuo && model ? (
+ {session && showPhone && isDuo && model ? (
<DeviceDuoViewport
- onFrameListener={onFrameListener}
+ onFrameListener={session.setFrameListener}
+ onControlRejectedListener={session.setControlRejectedListener}
model={model}
- controlError={duoControl.error}
hingePreview={
duoControl.requested?.control === "angle" ? duoControl.requested.value : null
}
- source={canvasRef}
- client={clientRef}
+ source={session.canvas}
+ client={session.stream}
onInputCancel={onInputCancel}
onResetReady={onResetReady}
screen={screen}
- onUnavailable={onPhoneUnavailable}
+ onUnavailable={session.markPhoneUnavailable}
/>
- ) : showPhone ? (
+ ) : session && showPhone ? (
<DevicePhoneViewport
profile={profile}
model={deviceModel(props.platform, props.deviceName ?? "")}
accessory={keyboardAttached ? keyboardSource : null}
- source={canvasRef}
- onFrameListener={onFrameListener}
- client={clientRef}
+ source={session.canvas}
+ onFrameListener={session.setFrameListener}
+ client={session.stream}
onInputCancel={onInputCancel}
onResetReady={onResetReady}
screen={screen}
foldAngle={foldAngle}
- onUnavailable={onPhoneUnavailable}
+ onUnavailable={session.markPhoneUnavailable}
/>
) : null}
{props.allowPhoneView && !props.renderControls && status === "streaming" ? (
@@ -528,8 +455,9 @@ export function DeviceStreamView(props: {
</span>
</div>
) : null}
- {retainingFrame && showPhone && showRestartNotice ? (
- <div className="pointer-events-none absolute inset-x-0 bottom-0 flex justify-center p-2">
+ {retainingFrame && showPhone ? (
+ // Shown only once the device has been silent for two seconds.
+ <div className="pointer-events-none absolute inset-x-0 bottom-0 flex justify-center p-2 transition-opacity delay-2000 duration-0 starting:opacity-0">
<span className="rounded-md bg-background/85 px-2 py-1 text-xs text-muted-foreground">
Waiting for device video…
</span>
@@ -549,10 +477,9 @@ export function DeviceStreamView(props: {
size="sm"
variant="outline"
onClick={() => {
- // Restart's unauthorized response renews expired tickets through the effect.
- clientRef.current?.stop();
- setPhoneUnavailable(false);
- clientRef.current?.start();
+ // An expired ticket surfaces as unauthorized on restart and
+ // refreshes access, which starts a new session.
+ session?.reconnect();
}}
>
Reconnect
diff --git a/apps/web/src/components/device/DeviceToolsPanel.tsx b/apps/web/src/components/device/DeviceToolsPanel.tsx
index 9ea111874d4..23c5d009708 100644
--- a/apps/web/src/components/device/DeviceToolsPanel.tsx
+++ b/apps/web/src/components/device/DeviceToolsPanel.tsx
@@ -1,7 +1,8 @@
import type { DeviceHubAccess } from "@t3tools/client-runtime/state/deviceHubAccess";
import type { DevicePermission, DeviceSummary, DeviceTextSize } from "@t3tools/contracts";
import { ChevronDown, X } from "lucide-react";
-import { useEffect, useState } from "react";
+import { useAtomValue } from "@effect/atom-react";
+import { useState } from "react";
import { Button } from "~/components/ui/button";
import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "~/components/ui/collapsible";
@@ -18,7 +19,7 @@ import { Switch } from "~/components/ui/switch";
import { Toggle, ToggleGroup } from "~/components/ui/toggle-group";
import { cn } from "~/lib/utils";
import type { DeviceControls } from "./useDeviceControls";
-import { type DeviceEventLogEntry, subscribeDeviceEventLog } from "./deviceHubApi";
+import { deviceEventLogAtom } from "./deviceHubAtoms";
const TEXT_SIZES: ReadonlyArray<{ value: DeviceTextSize; label: string }> = [
{ value: "small", label: "Small" },
@@ -599,31 +600,11 @@ function PermissionsSection(props: {
);
}
-const EVENT_LOG_LIMIT = 100;
-
function EventLogSection(props: {
readonly access: DeviceHubAccess;
readonly device: DeviceSummary;
}) {
const [open, setOpen] = useState(false);
- const [entries, setEntries] = useState<ReadonlyArray<DeviceEventLogEntry>>([]);
-
- useEffect(() => {
- if (!open) return;
- const unsubscribe = subscribeDeviceEventLog(
- { access: props.access, platform: props.device.platform, deviceId: props.device.id },
- (incoming, reset) => {
- setEntries((current) => {
- const merged = reset ? [...incoming] : [...current, ...incoming];
- return merged.length > EVENT_LOG_LIMIT ? merged.slice(-EVENT_LOG_LIMIT) : merged;
- });
- },
- );
- return () => {
- unsubscribe();
- setEntries([]);
- };
- }, [open, props.access, props.device.id, props.device.platform]);
return (
<Collapsible open={open} onOpenChange={setOpen}>
@@ -634,21 +615,36 @@ function EventLogSection(props: {
/>
</CollapsibleTrigger>
<CollapsiblePanel>
- <ol className="max-h-64 overflow-y-auto px-3 py-2 font-mono text-2xs leading-relaxed">
- {entries.length === 0 ? (
- <li className="text-muted-foreground">No events yet.</li>
- ) : (
- entries.map((entry) => (
- <li key={entry.id} className="flex gap-2">
- <span className="shrink-0 text-muted-foreground">
- {entry.timestamp.slice(11, 19)}
- </span>
- <span className="truncate">{entry.summary}</span>
- </li>
- ))
- )}
- </ol>
+ <EventLogEntries access={props.access} device={props.device} />
</CollapsiblePanel>
</Collapsible>
);
}
+
+// The panel unmounts while closed, so the log streams only while it is open.
+function EventLogEntries(props: {
+ readonly access: DeviceHubAccess;
+ readonly device: DeviceSummary;
+}) {
+ const entries = useAtomValue(
+ deviceEventLogAtom({
+ access: props.access,
+ platform: props.device.platform,
+ deviceId: props.device.id,
+ }),
+ );
+ return (
+ <ol className="max-h-64 overflow-y-auto px-3 py-2 font-mono text-2xs leading-relaxed">
+ {entries.length === 0 ? (
+ <li className="text-muted-foreground">No events yet.</li>
+ ) : (
+ entries.map((entry) => (
+ <li key={entry.id} className="flex gap-2">
+ <span className="shrink-0 text-muted-foreground">{entry.timestamp.slice(11, 19)}</span>
+ <span className="truncate">{entry.summary}</span>
+ </li>
+ ))
+ )}
+ </ol>
+ );
+}
diff --git a/apps/web/src/components/device/DeviceWorkspace.tsx b/apps/web/src/components/device/DeviceWorkspace.tsx
index 59fdb86d633..b8d329bc0df 100644
--- a/apps/web/src/components/device/DeviceWorkspace.tsx
+++ b/apps/web/src/components/device/DeviceWorkspace.tsx
@@ -1,15 +1,17 @@
import type { DeviceSummary, EnvironmentId } from "@t3tools/contracts";
-import { useEffect, useRef, useState } from "react";
+import { useRef, useState } from "react";
import {
captureDeviceScreenshot,
DeviceScreenshotError,
} from "@t3tools/client-runtime/device/screenshot";
import { refreshDeviceHubAccess, useDeviceHubAccess } from "~/state/device";
import { DeviceControlsRail } from "./DeviceControlsRail";
-import { DeviceStreamView, type DeviceStreamHandle } from "./DeviceStreamView";
+import { DeviceStreamView } from "./DeviceStreamView";
import { DeviceToolsPanel } from "./DeviceToolsPanel";
import { useDeviceControls } from "./useDeviceControls";
+const DOWNLOAD_URL_LIFETIME_MS = 60_000;
+
export function DeviceWorkspace(props: {
environmentId: EnvironmentId;
device: DeviceSummary;
@@ -20,59 +22,45 @@ export function DeviceWorkspace(props: {
onClose: () => void;
onPowerOff: () => void;
}) {
- const [handle, setHandle] = useState<DeviceStreamHandle | null>(null);
const [toolsOpen, setToolsOpen] = useState(false);
const [axOverlay, setAxOverlay] = useState(false);
const [screenshotPending, setScreenshotPending] = useState(false);
const [screenshotError, setScreenshotError] = useState<string | null>(null);
- const captureRef = useRef<AbortController | null>(null);
- const downloadRef = useRef<string | null>(null);
+ // A capture always finishes, even if the panel hides or closes meanwhile; the user asked for it.
+ const capturing = useRef(false);
const access = useDeviceHubAccess(props.environmentId, props.device.hostId);
const controls = useDeviceControls({ ...props, access });
- useEffect(() => {
- if (!access || !props.visible) captureRef.current?.abort();
- return () => {
- captureRef.current?.abort();
- if (downloadRef.current) URL.revokeObjectURL(downloadRef.current);
- downloadRef.current = null;
- };
- }, [access, props.visible]);
const saveScreenshot = () => {
- if (!access || captureRef.current || !props.visible) return;
- const controller = new AbortController();
- captureRef.current = controller;
+ if (!access || capturing.current || !props.visible) return;
+ capturing.current = true;
setScreenshotPending(true);
setScreenshotError(null);
return captureDeviceScreenshot(
{ access, platform: props.device.platform, deviceId: props.device.id },
- controller.signal,
+ // Never aborted: see `capturing` above.
+ new AbortController().signal,
)
.then((image) => {
- if (controller.signal.aborted) return;
- if (downloadRef.current) URL.revokeObjectURL(downloadRef.current);
const url = URL.createObjectURL(image);
- downloadRef.current = url;
const link = document.createElement("a");
link.href = url;
link.download = `${props.device.name.replace(/[^a-z0-9-]/gi, "-")}-${Date.now()}.png`;
document.body.append(link);
link.click();
link.remove();
+ // The browser reads the blob after the click returns.
+ window.setTimeout(() => URL.revokeObjectURL(url), DOWNLOAD_URL_LIFETIME_MS);
})
.catch((cause: unknown) => {
- if (!controller.signal.aborted) {
- if (cause instanceof DeviceScreenshotError && cause.status === 401)
- refreshDeviceHubAccess(props.environmentId);
- setScreenshotError(
- cause instanceof Error ? cause.message : "Screenshot capture failed. Try again.",
- );
- }
+ if (cause instanceof DeviceScreenshotError && cause.status === 401)
+ refreshDeviceHubAccess(props.environmentId);
+ setScreenshotError(
+ cause instanceof Error ? cause.message : "Screenshot capture failed. Try again.",
+ );
})
.finally(() => {
- if (captureRef.current === controller) {
- captureRef.current = null;
- setScreenshotPending(false);
- }
+ capturing.current = false;
+ setScreenshotPending(false);
});
};
return (
@@ -94,11 +82,10 @@ export function DeviceWorkspace(props: {
visible={props.visible}
axOverlay={axOverlay}
allowPhoneView
- onHandle={setHandle}
renderControls={(view) => (
<DeviceControlsRail
platform={props.device.platform}
- handle={handle}
+ handle={view.handle}
view={view}
controls={controls}
screenshotPending={screenshotPending}
diff --git a/apps/web/src/components/device/deviceHubApi.test.ts b/apps/web/src/components/device/deviceHubApi.test.ts
index 52575f4a422..f0ef1ebdf91 100644
--- a/apps/web/src/components/device/deviceHubApi.test.ts
+++ b/apps/web/src/components/device/deviceHubApi.test.ts
@@ -1,5 +1,10 @@
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
-import { subscribeDeviceForeground } from "./deviceHubApi";
+import {
+ appendDeviceEventLog,
+ DEVICE_EVENT_LOG_LIMIT,
+ type DeviceEventLogEntry,
+ subscribeDeviceForeground,
+} from "./deviceHubApi";
describe("foreground app events", () => {
afterEach(() => vi.unstubAllGlobals());
@@ -42,3 +47,16 @@ describe("foreground app events", () => {
expect(source!.close).toHaveBeenCalledOnce();
});
});
+
+describe("event log buffer", () => {
+ const entry = (id: number): DeviceEventLogEntry => ({ id, timestamp: "", kind: "", summary: "" });
+
+ it("replaces the log on a reset batch and keeps only the newest entries", () => {
+ const full = Array.from({ length: DEVICE_EVENT_LOG_LIMIT }, (_, index) => entry(index));
+ const appended = appendDeviceEventLog(full, [entry(DEVICE_EVENT_LOG_LIMIT)], false);
+ expect(appended).toHaveLength(DEVICE_EVENT_LOG_LIMIT);
+ expect(appended[0]?.id).toBe(1);
+ expect(appended.at(-1)?.id).toBe(DEVICE_EVENT_LOG_LIMIT);
+ expect(appendDeviceEventLog(full, [entry(7)], true)).toEqual([entry(7)]);
+ });
+});
diff --git a/apps/web/src/components/device/deviceHubApi.ts b/apps/web/src/components/device/deviceHubApi.ts
index 4c4d00b8921..afe733c3e47 100644
--- a/apps/web/src/components/device/deviceHubApi.ts
+++ b/apps/web/src/components/device/deviceHubApi.ts
@@ -32,21 +32,25 @@ export interface DeviceForegroundInfo {
readonly isReactNative?: boolean;
}
-interface Target {
+export interface DeviceHubTarget {
readonly access: DeviceHubAccess;
readonly platform: DevicePlatform;
readonly deviceId: string;
}
-const vendorBase = (target: Target) =>
+const vendorBase = (target: DeviceHubTarget) =>
`${target.access.httpBase}${target.platform === "ios" ? "/vendor/serve-sim" : "/vendor/serve-emu"}`;
-const hubUrl = (target: Target, path: string, params?: Record<string, string>) => {
+const hubUrl = (target: DeviceHubTarget, path: string, params?: Record<string, string>) => {
const search = params ? `?${new URLSearchParams(params).toString()}` : "";
return withDeviceHubQuery(`${vendorBase(target)}${path}${search}`, target.access);
};
-const fetchJson = async (target: Target, url: string, signal?: AbortSignal): Promise<unknown> => {
+const fetchJson = async (
+ target: DeviceHubTarget,
+ url: string,
+ signal?: AbortSignal,
+): Promise<unknown> => {
const response = await fetch(url, {
cache: "no-store",
credentials: target.access.credentials ? "include" : "same-origin",
@@ -96,7 +100,7 @@ const flattenIosAxTree = (roots: ReadonlyArray<unknown>): ReadonlyArray<DeviceAx
};
export async function fetchDeviceAxTree(
- target: Target,
+ target: DeviceHubTarget,
signal?: AbortSignal,
): Promise<DeviceAxTree> {
if (target.platform === "ios") {
@@ -154,7 +158,7 @@ export async function fetchDeviceAxTree(
}
const openEventSource = (
- target: Target,
+ target: DeviceHubTarget,
url: string,
onMessage: (data: unknown) => void,
): (() => void) => {
@@ -168,7 +172,7 @@ const openEventSource = (
};
export function subscribeDeviceForeground(
- target: Target,
+ target: DeviceHubTarget,
onChange: (app: DeviceForegroundInfo | null) => void,
): () => void {
if (target.platform !== "ios") return () => {};
@@ -202,8 +206,20 @@ const toEventLogEntry = (raw: unknown): DeviceEventLogEntry | null => {
};
};
+export const DEVICE_EVENT_LOG_LIMIT = 100;
+
+/** A reset batch replaces the log; the log keeps the newest entries up to the limit. */
+export function appendDeviceEventLog(
+ current: ReadonlyArray<DeviceEventLogEntry>,
+ incoming: ReadonlyArray<DeviceEventLogEntry>,
+ reset: boolean,
+): ReadonlyArray<DeviceEventLogEntry> {
+ const merged = reset ? [...incoming] : [...current, ...incoming];
+ return merged.length > DEVICE_EVENT_LOG_LIMIT ? merged.slice(-DEVICE_EVENT_LOG_LIMIT) : merged;
+}
+
export function subscribeDeviceEventLog(
- target: Target,
+ target: DeviceHubTarget,
onEvents: (entries: ReadonlyArray<DeviceEventLogEntry>, reset: boolean) => void,
): () => void {
if (target.platform !== "ios") return () => {};
diff --git a/apps/web/src/components/device/deviceHubAtoms.ts b/apps/web/src/components/device/deviceHubAtoms.ts
new file mode 100644
index 00000000000..5a83f26824d
--- /dev/null
+++ b/apps/web/src/components/device/deviceHubAtoms.ts
@@ -0,0 +1,117 @@
+import type { DeviceHubAccess } from "@t3tools/client-runtime/state/deviceHubAccess";
+import * as Effect from "effect/Effect";
+import * as Schedule from "effect/Schedule";
+import * as Stream from "effect/Stream";
+import { AsyncResult, Atom } from "effect/reactivity";
+
+import {
+ appendDeviceEventLog,
+ type DeviceAxElement,
+ type DeviceEventLogEntry,
+ type DeviceForegroundInfo,
+ type DeviceHubTarget,
+ fetchDeviceAxTree,
+ subscribeDeviceEventLog,
+ subscribeDeviceForeground,
+} from "./deviceHubApi";
+import { AndroidFoldError, readAndroidFold, type AndroidFoldState } from "./deviceFold";
+
+const AX_POLL_INTERVAL_MS = 2_000;
+const FOLD_RETRY_MS = 3_000;
+
+/** `undefined` until the hub reports an app; the device detail's app fills in until then. */
+export const deviceForegroundAtom = Atom.family((target: DeviceHubTarget) =>
+ Atom.make<DeviceForegroundInfo | null | undefined>((get) => {
+ get.addFinalizer(subscribeDeviceForeground(target, (app) => get.setSelf(app)));
+ return undefined;
+ }).pipe(Atom.withLabel(`device-foreground:${target.deviceId}`)),
+);
+
+export const deviceEventLogAtom = Atom.family((target: DeviceHubTarget) =>
+ Atom.make<ReadonlyArray<DeviceEventLogEntry>>((get) => {
+ let entries: ReadonlyArray<DeviceEventLogEntry> = [];
+ get.addFinalizer(
+ subscribeDeviceEventLog(target, (incoming, reset) => {
+ entries = appendDeviceEventLog(entries, incoming, reset);
+ get.setSelf(entries);
+ }),
+ );
+ return entries;
+ }).pipe(Atom.withLabel(`device-event-log:${target.deviceId}`)),
+);
+
+// A failed poll keeps the last frames on screen; the next poll replaces them.
+export const deviceAxElementsAtom = Atom.family((target: DeviceHubTarget) =>
+ Atom.make(
+ Stream.fromEffectSchedule(
+ Effect.tryPromise((signal) => fetchDeviceAxTree(target, signal)).pipe(
+ Effect.map((tree): ReadonlyArray<DeviceAxElement> | null => tree.elements),
+ Effect.orElseSucceed(() => null),
+ ),
+ Schedule.spaced(AX_POLL_INTERVAL_MS),
+ ).pipe(Stream.filter((elements) => elements !== null)),
+ ).pipe(Atom.withLabel(`device-ax-elements:${target.deviceId}`)),
+);
+
+export interface AndroidFoldView {
+ readonly fold: AndroidFoldState | null;
+ /** Hinge angle the 3D phone shows, including an optimistic one while a change is in flight. */
+ readonly angle: number | null;
+}
+
+export const foldAngle = (fold: AndroidFoldState) =>
+ fold.hingeAngle ?? (fold.posture === "closed" ? 0 : 180);
+
+/**
+ * The fold controls and the 3D phone share one view of a device's fold. Keyed by
+ * host and device, not by hub access, so a renewed ticket keeps the known posture.
+ */
+export const androidFoldViewAtom = Atom.family((deviceKey: string) =>
+ Atom.make<AndroidFoldView>({ fold: null, angle: null }).pipe(
+ Atom.withLabel(`android-fold-view:${deviceKey}`),
+ ),
+);
+
+/**
+ * Reads the fold while mounted and records it in the device's fold view. The
+ * screen size is part of the key because folding resizes the screen, so a new
+ * size means the posture may have changed. An expired ticket stops retrying:
+ * renewed access is a new key and reads again.
+ */
+export const androidFoldReadAtom = Atom.family(
+ (input: {
+ readonly deviceKey: string;
+ readonly access: DeviceHubAccess;
+ readonly deviceId: string;
+ readonly screenWidth: number;
+ readonly screenHeight: number;
+ }) =>
+ Atom.make((get) =>
+ Effect.tryPromise({
+ try: (signal) => readAndroidFold(input.access, input.deviceId, signal),
+ catch: (cause) => ({ expired: cause instanceof AndroidFoldError && cause.status === 401 }),
+ }).pipe(
+ Effect.retry({
+ while: (failure) => !failure.expired,
+ schedule: Schedule.spaced(FOLD_RETRY_MS),
+ }),
+ Effect.tap((fold) =>
+ Effect.sync(() =>
+ get.set(androidFoldViewAtom(input.deviceKey), {
+ fold,
+ angle: fold.supported ? foldAngle(fold) : null,
+ }),
+ ),
+ ),
+ Effect.asVoid,
+ ),
+ ).pipe(Atom.withLabel(`android-fold-read:${input.deviceKey}`)),
+);
+
+export const NOOP_ATOM = Atom.make(AsyncResult.initial<void, never>()).pipe(
+ Atom.withLabel("device:noop"),
+);
+
+export const NO_FOREGROUND_ATOM = Atom.make<DeviceForegroundInfo | null | undefined>(
+ undefined,
+).pipe(Atom.withLabel("device-foreground:none"));
diff --git a/apps/web/src/components/device/deviceStreamSession.ts b/apps/web/src/components/device/deviceStreamSession.ts
new file mode 100644
index 00000000000..813a4f3fd8e
--- /dev/null
+++ b/apps/web/src/components/device/deviceStreamSession.ts
@@ -0,0 +1,139 @@
+import { createCanvasFrameSink } from "@t3tools/client-runtime/device/frame";
+import type { DuoControlState } from "@t3tools/client-runtime/device/duo-control";
+import {
+ createDeviceStreamClient,
+ type DeviceScreenSize,
+ type DeviceStreamClient,
+ type DeviceStreamStatus,
+} from "@t3tools/client-runtime/device/stream";
+import type { DeviceHubAccess } from "@t3tools/client-runtime/state/deviceHubAccess";
+import type { DevicePlatform, EnvironmentId } from "@t3tools/contracts";
+import { Atom } from "effect/reactivity";
+
+import { refreshDeviceHubAccess } from "~/state/device";
+
+export interface DeviceStreamState {
+ readonly status: DeviceStreamStatus;
+ readonly detail: string | undefined;
+ /** A frame arrived during this session, so a reconnect can keep showing it. */
+ readonly hasFrame: boolean;
+ readonly screen: DeviceScreenSize | null;
+ readonly mjpegUrl: string | null;
+ readonly mjpegGeneration: number;
+ readonly input: { readonly connected: boolean; readonly detail?: string };
+ readonly duoControl: DuoControlState;
+ readonly phoneUnavailable: boolean;
+}
+
+export interface DeviceStreamSession {
+ readonly stream: DeviceStreamClient;
+ /** The stream draws here; the view mounts it and the 3D viewers sample it. */
+ readonly canvas: HTMLCanvasElement;
+ readonly setFrameListener: (listener: (() => void) | null) => void;
+ /** Called when the hub rejects a Duo control, so the 3D viewer drops its optimistic pose. */
+ readonly setControlRejectedListener: (listener: (() => void) | null) => void;
+ readonly markPhoneUnavailable: () => void;
+ readonly reconnect: () => void;
+ readonly state: DeviceStreamState;
+}
+
+export interface DeviceStreamKey {
+ readonly environmentId: EnvironmentId;
+ readonly hostId: string;
+ readonly platform: DevicePlatform;
+ readonly deviceId: string;
+ readonly access: DeviceHubAccess;
+ /** Each mounted view owns its own client: one canvas cannot be in two places. */
+ readonly viewId: string;
+}
+
+export const IDLE_DEVICE_STREAM_STATE: DeviceStreamState = {
+ status: "connecting",
+ detail: undefined,
+ hasFrame: false,
+ screen: null,
+ mjpegUrl: null,
+ mjpegGeneration: 0,
+ input: { connected: false },
+ duoControl: { pending: false, requested: null, error: null },
+ phoneUnavailable: false,
+};
+
+export const deviceScreenKey = (environmentId: EnvironmentId, hostId: string, deviceId: string) =>
+ `${environmentId}\u0000${hostId}\u0000${deviceId}`;
+
+/**
+ * The screen one view's stream last reported, null while that view streams nothing.
+ * Keyed by view, not device: two views of one device stream independently, and one
+ * ending must not clear the other's size. The mini player lays out its frame from it.
+ */
+export const deviceStreamScreenAtom = Atom.family((viewId: string) =>
+ Atom.make<DeviceScreenSize | null>(null).pipe(Atom.withLabel(`device-stream-screen:${viewId}`)),
+);
+
+/** A device's video and input connection, live while a view reads it. */
+export const deviceStreamSessionAtom = Atom.family((key: DeviceStreamKey) =>
+ Atom.make((get): DeviceStreamSession => {
+ const screenAtom = deviceStreamScreenAtom(key.viewId);
+ const canvas = document.createElement("canvas");
+ canvas.style.display = "block";
+ canvas.style.width = "100%";
+ canvas.style.height = "100%";
+ let frameListener: (() => void) | null = null;
+ let controlRejectedListener: (() => void) | null = null;
+ let state = IDLE_DEVICE_STREAM_STATE;
+ let session: DeviceStreamSession;
+ const update = (patch: Partial<DeviceStreamState>) => {
+ state = { ...state, ...patch };
+ session = { ...session, state };
+ get.setSelf(session);
+ };
+ const client = createDeviceStreamClient(
+ { platform: key.platform, deviceId: key.deviceId, access: key.access },
+ createCanvasFrameSink(canvas, () => frameListener?.()),
+ {
+ onDuoControl: (duoControl) => {
+ if (duoControl.error && duoControl.error !== state.duoControl.error)
+ controlRejectedListener?.();
+ update({ duoControl });
+ },
+ onDuoUnavailable: () => update({ phoneUnavailable: true }),
+ onStatus: (status, detail) =>
+ update({ status, detail, ...(status === "streaming" ? { hasFrame: true } : {}) }),
+ onScreen: (screen) => {
+ get.set(screenAtom, screen);
+ update({ screen });
+ },
+ onUnauthorized: () => refreshDeviceHubAccess(key.environmentId),
+ onMjpegFallback: (mjpegUrl) =>
+ update({ mjpegUrl, mjpegGeneration: state.mjpegGeneration + 1 }),
+ onCanvasVideo: () => update({ mjpegUrl: null }),
+ onInputConnected: (connected, detail) =>
+ update({ input: { connected, ...(detail ? { detail } : {}) } }),
+ },
+ );
+ session = {
+ stream: client,
+ canvas,
+ setFrameListener: (listener) => {
+ frameListener = listener;
+ },
+ setControlRejectedListener: (listener) => {
+ controlRejectedListener = listener;
+ },
+ markPhoneUnavailable: () => update({ phoneUnavailable: true }),
+ reconnect: () => {
+ client.stop();
+ update({ phoneUnavailable: false });
+ client.start();
+ },
+ state,
+ };
+ get.addFinalizer(() => {
+ client.stop();
+ get.registry.set(screenAtom, null);
+ });
+ client.start();
+ return session;
+ }).pipe(Atom.withLabel(`device-stream:${key.platform}:${key.deviceId}`)),
+);
diff --git a/apps/web/src/components/device/mountDeviceViewer.ts b/apps/web/src/components/device/mountDeviceViewer.ts
new file mode 100644
index 00000000000..df1f9a77a38
--- /dev/null
+++ b/apps/web/src/components/device/mountDeviceViewer.ts
@@ -0,0 +1,110 @@
+import { createPhoneInteraction } from "@t3tools/client-runtime/device/phone-interaction";
+import { observeResize } from "../../lib/observeResize";
+import { bindPhoneTrackpad } from "./phoneTrackpad";
+
+type PhoneInteraction = ReturnType<typeof createPhoneInteraction>;
+type TrackpadPinch = NonNullable<Parameters<typeof bindPhoneTrackpad>[2]>;
+
+interface MountableViewer {
+ readonly resize: (width: number, height: number, pixelRatio: number) => void;
+ readonly screenPoint: (
+ x: number,
+ y: number,
+ captured?: boolean,
+ ) => { x: number; y: number } | null;
+ readonly orbit: (deltaX: number, deltaY: number) => void;
+ readonly setInteractionActive: (active: boolean, mode: "touch" | "orbit") => void;
+ readonly resetPose: () => void;
+ readonly dispose: () => void;
+}
+
+export interface DeviceViewerReady {
+ /** Draws the latest decoded frame; registered as the stream's frame listener. */
+ readonly frame: () => void;
+ readonly pinch?: TrackpadPinch;
+ readonly dispose?: () => void;
+}
+
+/**
+ * Mounts a lazily loaded 3D device viewer on a canvas and returns its teardown, for use from
+ * the canvas ref callback. Owns host resizing, input cancellation, trackpad gestures, and
+ * disposal shared by every viewport.
+ */
+export function mountDeviceViewer<V extends MountableViewer>(
+ canvas: HTMLCanvasElement,
+ host: HTMLElement,
+ options: {
+ /** Resolves to the constructor, so a canvas unmounted while loading never builds a viewer. */
+ readonly load: () => Promise<() => V>;
+ readonly touch: (phase: "begin" | "move" | "end", point: { x: number; y: number }) => void;
+ readonly viewerRef: { current: V | null };
+ readonly interactionRef: { current: PhoneInteraction | null };
+ readonly onInputCancel: (cancel: (() => void) | null) => void;
+ readonly onResetReady: (reset: (() => void) | null) => void;
+ readonly onFrameListener: (listener: (() => void) | null) => void;
+ readonly onUnavailable: () => void;
+ readonly cancelInput?: (viewer: V) => void;
+ readonly ready: (context: {
+ readonly viewer: V;
+ readonly cancelTrackpad: () => void;
+ }) => DeviceViewerReady;
+ },
+) {
+ const { viewerRef, interactionRef } = options;
+ let disposed = false;
+ let trackpad: ReturnType<typeof bindPhoneTrackpad> | null = null;
+ let stopTrackpadEnd: (() => void) | undefined;
+ let mounted: DeviceViewerReady | null = null;
+ const resize = () => {
+ const { width, height } = host.getBoundingClientRect();
+ viewerRef.current?.resize(width, height, window.devicePixelRatio);
+ };
+ const stopObserving = observeResize(host, resize);
+ const blur = () => {
+ interactionRef.current?.end();
+ trackpad?.cancel();
+ if (viewerRef.current) options.cancelInput?.(viewerRef.current);
+ };
+ options.onInputCancel(blur);
+ window.addEventListener("blur", blur);
+ void options
+ .load()
+ .then((create) => {
+ if (disposed) return;
+ const viewer = create();
+ viewerRef.current = viewer;
+ options.onResetReady(viewer.resetPose);
+ const interaction = createPhoneInteraction({
+ screenPoint: (point, captured) => viewer.screenPoint(point.x, point.y, captured),
+ touch: options.touch,
+ orbit: viewer.orbit,
+ zoomBy: () => {},
+ onInteractionActive: viewer.setInteractionActive,
+ });
+ interactionRef.current = interaction;
+ resize();
+ mounted = options.ready({ viewer, cancelTrackpad: () => trackpad?.cancel() });
+ options.onFrameListener(mounted.frame);
+ mounted.frame();
+ trackpad = bindPhoneTrackpad(canvas, interaction, mounted.pinch);
+ stopTrackpadEnd = window.desktopBridge?.onTrackpadScrollEnd?.(() => trackpad?.endOrbit());
+ })
+ .catch(() => {
+ if (!disposed) options.onUnavailable();
+ });
+ return () => {
+ disposed = true;
+ stopTrackpadEnd?.();
+ trackpad?.dispose();
+ mounted?.dispose?.();
+ interactionRef.current?.end();
+ interactionRef.current = null;
+ options.onInputCancel(null);
+ options.onResetReady(null);
+ options.onFrameListener(null);
+ stopObserving();
+ window.removeEventListener("blur", blur);
+ viewerRef.current?.dispose();
+ viewerRef.current = null;
+ };
+}
diff --git a/apps/web/src/components/device/useDeviceControls.browser.test.tsx b/apps/web/src/components/device/useDeviceControls.browser.test.tsx
index 7db819cdc5b..5633369dc1c 100644
--- a/apps/web/src/components/device/useDeviceControls.browser.test.tsx
+++ b/apps/web/src/components/device/useDeviceControls.browser.test.tsx
@@ -1,6 +1,9 @@
import { EnvironmentId, type DeviceDetail, type DeviceSummary } from "@t3tools/contracts";
import type { DeviceHubAccess } from "@t3tools/client-runtime/device/hub-access";
+import type { AtomCommandConcurrency } from "@t3tools/client-runtime/state/runtime";
+import { RegistryContext } from "@effect/atom-react";
import * as Cause from "effect/Cause";
+import { AtomRegistry } from "effect/reactivity";
import { useEffect } from "react";
import { expect, it, vi } from "vite-plus/test";
@@ -13,19 +16,41 @@ const { read, action, subscribe } = vi.hoisted(() => ({
subscribe:
vi.fn<(_target: unknown, onChange: (app: { id: string } | null) => void) => () => void>(),
}));
-vi.mock(import("~/state/use-atom-command"), async (original) => {
- const { deviceEnvironment } = await import("~/state/device");
- return {
- ...(await original()),
- useAtomCommand: ((command: unknown) =>
- command === deviceEnvironment.detail ? read : action) as never,
+// Stubs only the transport; the device atoms' real scheduler and lanes decide ordering.
+vi.mock(import("@t3tools/client-runtime/state/runtime"), async (original) => {
+ const runtime = await original();
+ const createEnvironmentRpcCommand = (
+ _runtime: unknown,
+ options: {
+ readonly label: string;
+ readonly scheduler?: {
+ readonly schedule: (
+ registry: AtomRegistry.AtomRegistry,
+ concurrency: AtomCommandConcurrency<unknown>,
+ input: unknown,
+ execute: () => Promise<Result>,
+ ) => Promise<Result>;
+ };
+ readonly concurrency?: AtomCommandConcurrency<unknown>;
+ },
+ ) => {
+ const send = options.label === "environment-data:device:detail" ? read : action;
+ return {
+ label: options.label,
+ run: (registry: AtomRegistry.AtomRegistry, input: unknown) =>
+ options.scheduler && options.concurrency
+ ? options.scheduler.schedule(registry, options.concurrency, input, () => send())
+ : send(),
+ };
};
+ return { ...runtime, createEnvironmentRpcCommand: createEnvironmentRpcCommand as never };
});
vi.mock(import("./deviceHubApi"), async (original) => ({
...(await original()),
subscribeDeviceForeground: subscribe as never,
}));
+import { deviceDetailReadAtom } from "~/state/device";
import { useDeviceControls, type DeviceControls } from "./useDeviceControls";
const offline = Cause.fail(new Error("Device offline"));
@@ -56,13 +81,9 @@ function deferred() {
return { promise, resolve };
}
let controls: DeviceControls;
+const environmentId = EnvironmentId.make("environment");
function Probe({ visible, access = null }: { visible: boolean; access?: DeviceHubAccess | null }) {
- const next = useDeviceControls({
- environmentId: EnvironmentId.make("environment"),
- device,
- access,
- visible,
- });
+ const next = useDeviceControls({ environmentId, device, access, visible });
useEffect(() => {
controls = next;
}, [next]);
@@ -74,11 +95,25 @@ function setup() {
subscribe.mockReset();
subscribe.mockReturnValue(() => {});
read.mockResolvedValue(snapshot("light"));
+ // No idle TTL, as in the app: hiding the panel ends its read.
+ const registry = AtomRegistry.make();
+ const view = (visible: boolean) => (
+ <RegistryContext.Provider value={registry}>
+ <Probe visible={visible} />
+ </RegistryContext.Provider>
+ );
+ const readAtom = deviceDetailReadAtom({ environmentId, hostId: "remote", deviceId: "phone" });
+ const hide = async (screen: { rerender: (element: React.ReactElement) => Promise<unknown> }) => {
+ await screen.rerender(view(false));
+ await vi.waitFor(() => expect(registry.getNodes().has(readAtom)).toBe(false));
+ };
+ return { view, hide };
}
it("serializes rapid actions and retains confirmed settings while pending or after failure", async () => {
- setup();
- await using _screen = await render(<Probe visible />);
+ const { view } = setup();
+ await using _screen = await render(view(true));
+ await vi.waitFor(() => expect(controls.detail?.settings.appearance).toBe("light"));
const response = deferred();
action.mockReturnValueOnce(response.promise);
let pending!: Promise<void>;
@@ -101,45 +136,51 @@ it("serializes rapid actions and retains confirmed settings while pending or aft
expect(controls.disabled).toBe(false);
});
-it("keeps actions disabled when settings cannot be confirmed after a detached command", async () => {
- setup();
- await using screen = await render(<Probe visible />);
+it("confirms settings again after a command sent before the panel reopened", async () => {
+ const { view, hide } = setup();
+ await using screen = await render(view(true));
+ await vi.waitFor(() => expect(controls.detail).not.toBeNull());
const response = deferred();
action.mockReturnValueOnce(response.promise);
let pending!: Promise<void>;
await act(async () => {
pending = controls.act({ type: "setAppearance", value: "dark" });
});
- await screen.rerender(<Probe visible={false} />);
- await screen.rerender(<Probe visible />);
+ await hide(screen);
read.mockResolvedValueOnce({ _tag: "Failure", cause: offline });
+ await screen.rerender(view(true));
await act(async () => {
response.resolve(snapshot("dark"));
await pending;
});
+ await vi.waitFor(() => expect(controls.error).toBe("Device offline"));
expect(controls.detail).toBeNull();
expect(controls.disabled).toBe(true);
- expect(controls.error).toBe("Device offline");
await act(async () => controls.act({ type: "setAppearance", value: "light" }));
expect(action).toHaveBeenCalledOnce();
- await screen.rerender(<Probe visible={false} />);
- await screen.rerender(<Probe visible />);
- expect(controls.disabled).toBe(false);
+ await hide(screen);
+ await screen.rerender(view(true));
+ await vi.waitFor(() => expect(controls.disabled).toBe(false));
expect(controls.error).toBeNull();
});
-it("does not let an older refresh overwrite a newer confirmed action", async () => {
- setup();
- await using screen = await render(<Probe visible />);
- await screen.rerender(<Probe visible={false} />);
+it("does not let a read sent before an action overwrite the action's answer", async () => {
+ const { view, hide } = setup();
+ await using screen = await render(view(true));
+ await vi.waitFor(() => expect(controls.detail).not.toBeNull());
+ await hide(screen);
const refresh = deferred();
read.mockReturnValueOnce(refresh.promise);
- await screen.rerender(<Probe visible />);
+ await screen.rerender(view(true));
+ await vi.waitFor(() => expect(read).toHaveBeenCalledTimes(2));
action.mockResolvedValueOnce(snapshot("dark"));
- await act(async () => controls.act({ type: "setAppearance", value: "dark" }));
+ let pending!: Promise<void>;
+ await act(async () => {
+ pending = controls.act({ type: "setAppearance", value: "dark" });
+ });
await act(async () => {
refresh.resolve(snapshot("light"));
- await refresh.promise;
+ await pending;
});
expect(controls.detail?.settings.appearance).toBe("dark");
});
diff --git a/apps/web/src/components/device/useDeviceControls.ts b/apps/web/src/components/device/useDeviceControls.ts
index d8b97f3f104..7b17bc4a624 100644
--- a/apps/web/src/components/device/useDeviceControls.ts
+++ b/apps/web/src/components/device/useDeviceControls.ts
@@ -1,15 +1,11 @@
+import { useAtomMount, useAtomSet, useAtomValue } from "@effect/atom-react";
import type { DeviceHubAccess } from "@t3tools/client-runtime/state/deviceHubAccess";
-import type {
- DeviceActionInput,
- DeviceDetail,
- DeviceSummary,
- EnvironmentId,
-} from "@t3tools/contracts";
-import { useEffect, useRef, useState } from "react";
-import { deviceEnvironment } from "~/state/device";
+import type { DeviceActionInput, DeviceSummary, EnvironmentId } from "@t3tools/contracts";
+import { useRef, useState } from "react";
+import { deviceDetailAtom, deviceDetailReadAtom, deviceEnvironment } from "~/state/device";
import { formatEnvironmentQueryError } from "~/state/query";
import { useAtomCommand } from "~/state/use-atom-command";
-import { subscribeDeviceForeground, type DeviceForegroundInfo } from "./deviceHubApi";
+import { deviceForegroundAtom, NO_FOREGROUND_ATOM, NOOP_ATOM } from "./deviceHubAtoms";
type ActionBody = DeviceActionInput extends infer A
? A extends { readonly type: string }
@@ -25,86 +21,39 @@ export function useDeviceControls(options: {
visible: boolean;
}) {
const { environmentId, device, access, visible } = options;
- const readDetail = useAtomCommand(deviceEnvironment.detail, { reportFailure: false });
const runAction = useAtomCommand(deviceEnvironment.action, { reportFailure: false });
- const [detail, setDetail] = useState<DeviceDetail | null>(null);
+ const { hostId, id: deviceId } = device;
+ const key = { environmentId, hostId, deviceId };
+ const { detail, error } = useAtomValue(deviceDetailAtom(key));
+ const setView = useAtomSet(deviceDetailAtom(key));
+ useAtomMount(visible ? deviceDetailReadAtom(key) : NOOP_ATOM);
+ const foreground = useAtomValue(
+ access && visible
+ ? deviceForegroundAtom({ access, platform: device.platform, deviceId })
+ : NO_FOREGROUND_ATOM,
+ );
const [pending, setPending] = useState(false);
- const [error, setError] = useState<string | null>(null);
- const [foreground, setForeground] = useState<DeviceForegroundInfo | null | undefined>();
- // Hiding invalidates results without cancelling host commands; serialize through settlement across reopen.
+ // Hiding does not cancel host commands, so actions stay serialized until settlement
+ // rather than letting a reopened panel race the previous command.
const busy = useRef(false);
- const generation = useRef(0);
- const visibleRead = useRef<Parameters<typeof readDetail>[0] | null>(null);
- const { hostId, id: deviceId } = device;
-
- useEffect(() => {
- const revision = ++generation.current;
- if (!visible) return;
- const request = { environmentId, input: { hostId, deviceId } };
- visibleRead.current = request;
- void readDetail(request).then((result) => {
- if (generation.current !== revision) return;
- if (result._tag === "Success") {
- setDetail(result.value);
- setError(null);
- } else {
- setDetail(null);
- setError(formatEnvironmentQueryError(result.cause));
- }
- });
- return () => {
- visibleRead.current = null;
- generation.current++;
- };
- }, [deviceId, environmentId, hostId, readDetail, visible]);
-
- useEffect(() => {
- if (!access || !visible) return;
- let active = true;
- const unsubscribe = subscribeDeviceForeground(
- { access, platform: device.platform, deviceId: device.id },
- (app) => {
- if (active) setForeground(app);
- },
- );
- return () => {
- active = false;
- unsubscribe();
- setForeground(undefined);
- };
- }, [access, device.id, device.platform, visible]);
const available = detail !== null && visible;
const act = async (body: ActionBody) => {
if (busy.current || !available) return;
busy.current = true;
- const revision = ++generation.current;
setPending(true);
- setError(null);
+ setView((current) => ({ ...current, error: null }));
return runAction({
environmentId,
input: { hostId, deviceId, ...body } as DeviceActionInput,
})
- .then((result) => {
- if (generation.current !== revision) {
- const request = visibleRead.current;
- if (!request) return;
- // Reopening can read before pending commands settle; refresh again before allowing actions.
- const refreshRevision = ++generation.current;
- return readDetail(request).then((refreshed) => {
- if (generation.current !== refreshRevision) return;
- if (refreshed._tag === "Success") {
- setDetail(refreshed.value);
- setError(null);
- } else {
- setDetail(null);
- setError(formatEnvironmentQueryError(refreshed.cause));
- }
- });
- }
- if (result._tag === "Success") setDetail(result.value);
- else setError(formatEnvironmentQueryError(result.cause));
- })
+ .then((result) =>
+ setView((current) =>
+ result._tag === "Success"
+ ? { detail: result.value, error: null }
+ : { ...current, error: formatEnvironmentQueryError(result.cause) },
+ ),
+ )
.finally(() => {
busy.current = false;
setPending(false);
diff --git a/apps/web/src/components/preview/ThreadPreviewMiniPlayer.tsx b/apps/web/src/components/preview/ThreadPreviewMiniPlayer.tsx
index bf880bf253a..614543093ca 100644
--- a/apps/web/src/components/preview/ThreadPreviewMiniPlayer.tsx
+++ b/apps/web/src/components/preview/ThreadPreviewMiniPlayer.tsx
@@ -1,11 +1,13 @@
import { FILL_PREVIEW_VIEWPORT, type ScopedThreadRef } from "@t3tools/contracts";
import { previewPdfAssetUrl } from "@t3tools/shared/preview";
+import { useAtomValue } from "@effect/atom-react";
import { useEnvironmentHttpBaseUrl } from "~/state/environments";
import { PanelRightIcon, PictureInPicture2, XIcon } from "lucide-react";
import {
type PointerEvent as ReactPointerEvent,
type ReactNode,
useEffect,
+ useId,
useLayoutEffect,
useRef,
useState,
@@ -46,7 +48,7 @@ import { useRightPanelStore } from "~/rightPanelStore";
import { useDeviceState } from "~/state/device";
import { DeviceStreamView } from "../device/DeviceStreamView";
-import type { DeviceScreenSize } from "@t3tools/client-runtime/device/stream";
+import { deviceStreamScreenAtom } from "../device/deviceStreamSession";
import type { PreviewStreamViewport } from "@t3tools/client-runtime/preview/server-browser-stream";
import { previewBridge } from "./previewBridge";
import { showPreviewPopup } from "./showPreviewPopup";
@@ -266,7 +268,8 @@ function DeviceMiniPlayer({
miniPlayer,
}: Props & { readonly source: Extract<PreviewMiniPlayerSource, { kind: "device" }> }) {
const { state: deviceState } = useDeviceState(threadRef.environmentId);
- const [screen, setScreen] = useState<DeviceScreenSize | null>(null);
+ const viewId = useId();
+ const screen = useAtomValue(deviceStreamScreenAtom(viewId));
const sourceSize = resolveDeviceMiniPlayerSourceSize(source.platform, screen);
const device = deviceState.devices.find(
(entry) => entry.hostId === source.hostId && entry.id === source.deviceId,
@@ -308,7 +311,7 @@ function DeviceMiniPlayer({
deviceName={device?.name ?? source.name}
deviceDescription={`${hostLabel} · ${device?.version ?? source.platform}`}
visible
- onScreen={setScreen}
+ viewId={viewId}
/>
</div>
)}
diff --git a/apps/web/src/components/settings/EasDeviceHostsSettings.tsx b/apps/web/src/components/settings/EasDeviceHostsSettings.tsx
index f067848ad96..43c80cdb740 100644
--- a/apps/web/src/components/settings/EasDeviceHostsSettings.tsx
+++ b/apps/web/src/components/settings/EasDeviceHostsSettings.tsx
@@ -1,4 +1,5 @@
-import { useEffect, useEffectEvent, useId, useRef, useState } from "react";
+import { useAtomValue } from "@effect/atom-react";
+import { useId, useRef, useState } from "react";
import * as Cause from "effect/Cause";
import * as Option from "effect/Option";
import {
@@ -10,7 +11,7 @@ import {
import { CloudIcon, PlusIcon, XIcon } from "lucide-react";
import { randomUUID } from "../../lib/utils";
-import { deviceEnvironment } from "../../state/device";
+import { deviceEasAccountCheck, deviceEnvironment } from "../../state/device";
import { serverEnvironment } from "../../state/server";
import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";
import { useAtomCommand } from "../../state/use-atom-command";
@@ -154,6 +155,12 @@ export function EasDeviceHostsSettings(props: { environmentId: EnvironmentId | n
);
}
+type AccountCheck =
+ | { status: "idle" }
+ | { status: "checking" }
+ | { status: "signed-in"; account: DeviceEasAccount }
+ | { status: "failed"; error: string };
+
function EasDeviceHostEditor(props: {
environmentId: EnvironmentId;
host: EasDeviceHostConfig;
@@ -169,13 +176,26 @@ function EasDeviceHostEditor(props: {
const [token, setToken] = useState<
{ kind: "saved" } | { kind: "new"; value: string } | { kind: "cleared" }
>(props.host.accessToken ? { kind: "saved" } : { kind: "cleared" });
- const [account, setAccount] = useState<
- | { status: "idle" }
- | { status: "checking" }
- | { status: "signed-in"; account: DeviceEasAccount }
- | { status: "failed"; error: string }
- // The editor checks the account as it opens.
- >({ status: "checking" });
+ // Checking on open names the saved project and shows a rejected credential
+ // before anything is changed. A manual check or a token edit replaces it.
+ const openCheck = useAtomValue(
+ deviceEasAccountCheck({
+ environmentId: props.environmentId,
+ input: props.host.accessToken
+ ? props.isNew
+ ? {}
+ : { hostId: props.host.id }
+ : { accessToken: "" },
+ }),
+ );
+ const [checked, setAccount] = useState<AccountCheck | null>(null);
+ const account: AccountCheck =
+ checked ??
+ (openCheck._tag === "Initial" || openCheck.waiting
+ ? { status: "checking" }
+ : openCheck._tag === "Success"
+ ? { status: "signed-in", account: openCheck.value }
+ : { status: "failed", error: failureMessage(openCheck.cause) });
const next: EasDeviceHostConfig = {
...draft,
label: draft.label.trim(),
@@ -225,13 +245,6 @@ function EasDeviceHostEditor(props: {
void requestCheck();
};
- // Checking on open names the saved project and shows a rejected credential
- // before anything is changed.
- const checkOnOpen = useEffectEvent(() => void requestCheck());
- useEffect(() => {
- checkOnOpen();
- }, []);
-
const limit = (
field: "maxSessionMinutes" | "idleMinutes" | "maxConcurrentSessions",
label: string,
diff --git a/apps/web/src/state/device.ts b/apps/web/src/state/device.ts
index 2afcff9066a..fcd4bb4b8f2 100644
--- a/apps/web/src/state/device.ts
+++ b/apps/web/src/state/device.ts
@@ -4,7 +4,16 @@ import {
type DeviceHubAccess,
resolveDeviceHubAccess,
} from "@t3tools/client-runtime/state/deviceHubAccess";
-import type { DeviceServiceState, EnvironmentId } from "@t3tools/contracts";
+import {
+ createEnvironmentRpcQueryAtomFamily,
+ runAtomCommand,
+} from "@t3tools/client-runtime/state/runtime";
+import {
+ type DeviceDetail,
+ type DeviceServiceState,
+ type EnvironmentId,
+ WS_METHODS,
+} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
@@ -12,7 +21,7 @@ import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
import { connectionAtomRuntime } from "../connection/runtime";
import { appAtomRegistry } from "../rpc/atomRegistry";
import { environmentSession } from "./session";
-import { useEnvironmentQuery } from "./query";
+import { formatEnvironmentQueryError, useEnvironmentQuery } from "./query";
export const deviceEnvironment = createDeviceEnvironmentAtoms(connectionAtomRuntime);
@@ -85,3 +94,80 @@ export function renewDeviceHubAccess(
),
);
}
+
+export interface DeviceDetailKey {
+ readonly environmentId: EnvironmentId;
+ readonly hostId: string;
+ readonly deviceId: string;
+}
+
+export interface DeviceDetailView {
+ /** Settings the host last confirmed, by a read or by an action's answer. */
+ readonly detail: DeviceDetail | null;
+ readonly error: string | null;
+}
+
+export const deviceDetailAtom = Atom.family((key: DeviceDetailKey) =>
+ Atom.make<DeviceDetailView>({ detail: null, error: null }).pipe(
+ Atom.withLabel(`device-detail:${key.hostId}:${key.deviceId}`),
+ ),
+);
+
+/**
+ * Reads a device's settings into its detail view while mounted. Reads and
+ * actions share one serial lane per environment, so a read never answers
+ * before an action that was sent ahead of it.
+ */
+export const deviceDetailReadAtom = Atom.family((key: DeviceDetailKey) =>
+ Atom.make((get) =>
+ Effect.promise(() =>
+ runAtomCommand(
+ get.registry,
+ deviceEnvironment.detail,
+ { environmentId: key.environmentId, input: { hostId: key.hostId, deviceId: key.deviceId } },
+ { reportFailure: false },
+ ),
+ ).pipe(
+ Effect.map((result) =>
+ get.set(
+ deviceDetailAtom(key),
+ result._tag === "Success"
+ ? { detail: result.value, error: null }
+ : { detail: null, error: formatEnvironmentQueryError(result.cause) },
+ ),
+ ),
+ ),
+ ).pipe(Atom.withLabel(`device-detail-read:${key.hostId}:${key.deviceId}`)),
+);
+
+/**
+ * Probes the environment's device hosts while mounted. Remote hosts report
+ * their platforms only after a probe. Probing never installs or starts helpers.
+ */
+export const deviceHostProbeAtom = Atom.family((environmentId: EnvironmentId) =>
+ Atom.make((get) =>
+ Effect.promise(() =>
+ runAtomCommand(
+ get.registry,
+ deviceEnvironment.list,
+ { environmentId, input: {} },
+ { reportFailure: false },
+ ),
+ ).pipe(Effect.asVoid),
+ ).pipe(Atom.withLabel(`device-host-probe:${environmentId}`)),
+);
+
+export const NO_DEVICE_PROBE_ATOM = Atom.make(AsyncResult.initial<void, never>()).pipe(
+ Atom.withLabel("device-host-probe:none"),
+);
+
+/**
+ * The Expo account an EAS host editor shows as it opens, for the saved
+ * credential. Each open checks again; edits and manual checks use the command.
+ */
+export const deviceEasAccountCheck = createEnvironmentRpcQueryAtomFamily(connectionAtomRuntime, {
+ label: "environment-data:device:eas-account-check",
+ tag: WS_METHODS.deviceEasAccount,
+ staleTimeMs: 0,
+ idleTtlMs: 0,
+});