Open History to see the last commit
1import type { DeviceHubAccess } from "@t3tools/client-runtime/state/deviceHubAccess";
2import type {
3 DeviceActionInput,
4 DeviceDetail,
5 DeviceSummary,
6 EnvironmentId,
7} from "@t3tools/contracts";
8import { useEffect, useRef, useState } from "react";
9import { deviceEnvironment } from "~/state/device";
10import { formatEnvironmentQueryError } from "~/state/query";
11import { useAtomCommand } from "~/state/use-atom-command";
12import { subscribeDeviceForeground, type DeviceForegroundInfo } from "./deviceHubApi";
13
14type ActionBody = DeviceActionInput extends infer A
15 ? A extends { readonly type: string }
16 ? Omit<A, "hostId" | "deviceId">
17 : never
18 : never;
19
20/** Mount keyed by device. */
21export function useDeviceControls(options: {
22 environmentId: EnvironmentId;
23 device: DeviceSummary;
24 access: DeviceHubAccess | null;
25 visible: boolean;
26}) {
27 const { environmentId, device, access, visible } = options;
28 const readDetail = useAtomCommand(deviceEnvironment.detail, { reportFailure: false });
29 const runAction = useAtomCommand(deviceEnvironment.action, { reportFailure: false });
30 const [detail, setDetail] = useState<DeviceDetail | null>(null);
31 const [pending, setPending] = useState(false);
32 const [error, setError] = useState<string | null>(null);
33 const [foreground, setForeground] = useState<DeviceForegroundInfo | null | undefined>();
34 // Hiding invalidates results without cancelling host commands; serialize through settlement across reopen.
35 const busy = useRef(false);
36 const generation = useRef(0);
37 const visibleRead = useRef<Parameters<typeof readDetail>[0] | null>(null);
38 const { hostId, id: deviceId } = device;
39
40 useEffect(() => {
41 const revision = ++generation.current;
42 if (!visible) return;
43 const request = { environmentId, input: { hostId, deviceId } };
44 visibleRead.current = request;
45 void readDetail(request).then((result) => {
46 if (generation.current !== revision) return;
47 if (result._tag === "Success") {
48 setDetail(result.value);
49 setError(null);
50 } else {
51 setDetail(null);
52 setError(formatEnvironmentQueryError(result.cause));
53 }
54 });
55 return () => {
56 visibleRead.current = null;
57 generation.current++;
58 };
59 }, [deviceId, environmentId, hostId, readDetail, visible]);
60
61 useEffect(() => {
62 if (!access || !visible) return;
63 let active = true;
64 const unsubscribe = subscribeDeviceForeground(
65 { access, platform: device.platform, deviceId: device.id },
66 (app) => {
67 if (active) setForeground(app);
68 },
69 );
70 return () => {
71 active = false;
72 unsubscribe();
73 setForeground(undefined);
74 };
75 }, [access, device.id, device.platform, visible]);
76
77 const available = detail !== null && visible;
78 const act = async (body: ActionBody) => {
79 if (busy.current || !available) return;
80 busy.current = true;
81 const revision = ++generation.current;
82 setPending(true);
83 setError(null);
84 return runAction({
85 environmentId,
86 input: { hostId, deviceId, ...body } as DeviceActionInput,
87 })
88 .then((result) => {
89 if (generation.current !== revision) {
90 const request = visibleRead.current;
91 if (!request) return;
92 // Reopening can read before pending commands settle; refresh again before allowing actions.
93 const refreshRevision = ++generation.current;
94 return readDetail(request).then((refreshed) => {
95 if (generation.current !== refreshRevision) return;
96 if (refreshed._tag === "Success") {
97 setDetail(refreshed.value);
98 setError(null);
99 } else {
100 setDetail(null);
101 setError(formatEnvironmentQueryError(refreshed.cause));
102 }
103 });
104 }
105 if (result._tag === "Success") setDetail(result.value);
106 else setError(formatEnvironmentQueryError(result.cause));
107 })
108 .finally(() => {
109 busy.current = false;
110 setPending(false);
111 });
112 };
113
114 return {
115 detail,
116 pending,
117 error,
118 act,
119 disabled: pending || !detail || !visible,
120 foregroundApp: foreground === undefined ? (detail?.foregroundApp ?? null) : foreground,
121 };
122}
123
124export type DeviceControls = ReturnType<typeof useDeviceControls>;