Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import { createDeviceEnvironmentAtoms } from "@t3tools/client-runtime/state/device";
3import {
4 type DeviceHubAccess,
5 resolveDeviceHubAccess,
6} from "@t3tools/client-runtime/state/deviceHubAccess";
7import {
8 createEnvironmentRpcQueryAtomFamily,
9 runAtomCommand,
10} from "@t3tools/client-runtime/state/runtime";
11import {
12 type DeviceDetail,
13 type DeviceServiceState,
14 type EnvironmentId,
15 WS_METHODS,
16} from "@t3tools/contracts";
17import * as Effect from "effect/Effect";
18import * as Option from "effect/Option";
19import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
20
21import { connectionAtomRuntime } from "../connection/runtime";
22import { appAtomRegistry } from "../rpc/atomRegistry";
23import { environmentSession } from "./session";
24import { formatEnvironmentQueryError, useEnvironmentQuery } from "./query";
25
26export const deviceEnvironment = createDeviceEnvironmentAtoms(connectionAtomRuntime);
27
28const EMPTY_DEVICE_STATE: DeviceServiceState = {
29 hosts: [],
30 hostStatus: "disabled",
31 hostStatuses: {},
32 devices: [],
33 sessions: [],
34 onboardingCompleted: false,
35 agentAccessEnabled: false,
36 hubBasePath: "/api/device-hub",
37 revision: 0,
38};
39
40export function useDeviceState(environmentId: EnvironmentId | null): {
41 readonly state: DeviceServiceState;
42 readonly loaded: boolean;
43} {
44 const query = useEnvironmentQuery(
45 environmentId === null ? null : deviceEnvironment.state({ environmentId, input: {} }),
46 );
47 return { state: query.data ?? EMPTY_DEVICE_STATE, loaded: query.data !== undefined };
48}
49
50const deviceHubAccessAtom = Atom.family((environmentId: EnvironmentId) =>
51 connectionAtomRuntime
52 .atom((get) => {
53 const prepared = Option.getOrNull(
54 get(environmentSession.preparedConnectionValueAtom(environmentId)),
55 );
56 if (prepared === null) return Effect.never;
57 return resolveDeviceHubAccess({ prepared, hubBasePath: EMPTY_DEVICE_STATE.hubBasePath });
58 })
59 .pipe(Atom.setIdleTTL(60_000), Atom.withLabel(`device-hub-access:${environmentId}`)),
60);
61
62export function useDeviceHubAccess(
63 environmentId: EnvironmentId | null,
64 hostId = "local",
65): DeviceHubAccess | null {
66 const result = useAtomValue(
67 environmentId === null ? EMPTY_ACCESS_ATOM : deviceHubAccessAtom(environmentId),
68 );
69 return AsyncResult.isSuccess(result)
70 ? { ...result.value, query: { ...result.value.query, hostId } }
71 : null;
72}
73
74const EMPTY_ACCESS_ATOM = Atom.make(AsyncResult.initial<DeviceHubAccess, never>()).pipe(
75 Atom.withLabel("device-hub-access:empty"),
76);
77
78export function refreshDeviceHubAccess(environmentId: EnvironmentId): void {
79 appAtomRegistry.refresh(deviceHubAccessAtom(environmentId));
80}
81
82/** Mints a fresh hub ticket for a one-off request that failed with 401. Resolves null on failure. */
83export function renewDeviceHubAccess(
84 environmentId: EnvironmentId,
85 hostId = "local",
86): Promise<DeviceHubAccess | null> {
87 const atom = deviceHubAccessAtom(environmentId);
88 appAtomRegistry.refresh(atom);
89 return Effect.runPromise(
90 AtomRegistry.getResult(appAtomRegistry, atom, { suspendOnWaiting: true }).pipe(
91 Effect.map((access) => ({ ...access, query: { ...access.query, hostId } })),
92 Effect.timeout("10 seconds"),
93 Effect.orElseSucceed(() => null),
94 ),
95 );
96}
97
98export interface DeviceDetailKey {
99 readonly environmentId: EnvironmentId;
100 readonly hostId: string;
101 readonly deviceId: string;
102}
103
104export interface DeviceDetailView {
105 /** Settings the host last confirmed, by a read or by an action's answer. */
106 readonly detail: DeviceDetail | null;
107 readonly error: string | null;
108}
109
110export const deviceDetailAtom = Atom.family((key: DeviceDetailKey) =>
111 Atom.make<DeviceDetailView>({ detail: null, error: null }).pipe(
112 Atom.withLabel(`device-detail:${key.hostId}:${key.deviceId}`),
113 ),
114);
115
116/**
117 * Reads a device's settings into its detail view while mounted. Reads and
118 * actions share one serial lane per environment, so a read never answers
119 * before an action that was sent ahead of it.
120 */
121export const deviceDetailReadAtom = Atom.family((key: DeviceDetailKey) =>
122 Atom.make((get) =>
123 Effect.promise(() =>
124 runAtomCommand(
125 get.registry,
126 deviceEnvironment.detail,
127 { environmentId: key.environmentId, input: { hostId: key.hostId, deviceId: key.deviceId } },
128 { reportFailure: false },
129 ),
130 ).pipe(
131 Effect.map((result) =>
132 get.set(
133 deviceDetailAtom(key),
134 result._tag === "Success"
135 ? { detail: result.value, error: null }
136 : { detail: null, error: formatEnvironmentQueryError(result.cause) },
137 ),
138 ),
139 ),
140 ).pipe(Atom.withLabel(`device-detail-read:${key.hostId}:${key.deviceId}`)),
141);
142
143/**
144 * Probes the environment's device hosts while mounted. Remote hosts report
145 * their platforms only after a probe. Probing never installs or starts helpers.
146 */
147export const deviceHostProbeAtom = Atom.family((environmentId: EnvironmentId) =>
148 Atom.make((get) =>
149 Effect.promise(() =>
150 runAtomCommand(
151 get.registry,
152 deviceEnvironment.list,
153 { environmentId, input: {} },
154 { reportFailure: false },
155 ),
156 ).pipe(Effect.asVoid),
157 ).pipe(Atom.withLabel(`device-host-probe:${environmentId}`)),
158);
159
160export const NO_DEVICE_PROBE_ATOM = Atom.make(AsyncResult.initial<void, never>()).pipe(
161 Atom.withLabel("device-host-probe:none"),
162);
163
164/**
165 * The Expo account an EAS host editor shows as it opens, for the saved
166 * credential. Each open checks again; edits and manual checks use the command.
167 */
168export const deviceEasAccountCheck = createEnvironmentRpcQueryAtomFamily(connectionAtomRuntime, {
169 label: "environment-data:device:eas-account-check",
170 tag: WS_METHODS.deviceEasAccount,
171 staleTimeMs: 0,
172 idleTtlMs: 0,
173});
174
175/** Who a Simlock token is, checked as the host editor's URL and token fields change. */
176export const deviceSimlockIdentityCheck = createEnvironmentRpcQueryAtomFamily(
177 connectionAtomRuntime,
178 {
179 label: "environment-data:device:simlock-identity-check",
180 tag: WS_METHODS.deviceSimlockIdentity,
181 staleTimeMs: 0,
182 idleTtlMs: 0,
183 },
184);