Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

device.ts

320 lines11.6 KB

1// @effect-diagnostics nodeBuiltinImport:off globalJsonInEffect:off - drives agent-device and the Hermes inspector; the probe types its own JSON.
2/**
3 * One simulator, driven two ways: T3's `agent-device` CLI for real touches and system actions,
4 * and the dev-only behavior probe (`apps/mobile/src/features/development/behavior-probe.ts`)
5 * through Metro's Hermes inspector for exact app state.
6 */
7import * as NodeChildProcess from "node:child_process";
8import * as NodeOS from "node:os";
9import * as NodePath from "node:path";
10import * as NodeWS from "@effect/platform-node/NodeWS";
11import * as Clock from "effect/Clock";
12import * as Effect from "effect/Effect";
13import * as Schedule from "effect/Schedule";
14import * as Schema from "effect/Schema";
15import { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/http";
16import { Socket } from "effect/socket";
17​
18import { poolError } from "../mobile-e2e/device.ts";
19​
20const InspectorTargets = Schema.Array(
21 Schema.Struct({
22 appId: Schema.String,
23 deviceName: Schema.optional(Schema.String),
24 webSocketDebuggerUrl: Schema.String,
25 }),
26);
27​
28export class DeviceError extends Schema.TaggedError<DeviceError>()("DeviceError", {
29 message: Schema.String,
30 cause: Schema.optional(Schema.Defect()),
31}) {}
32​
33export const APP_ID = "com.t3tools.t3code.dev";
34export const SCHEME = "t3code-dev";
35​
36export interface ProbeState {
37 readonly route: {
38 readonly name: string | null;
39 readonly params: Record<string, unknown>;
40 readonly columns: boolean;
41 } | null;
42 readonly feed: FeedSample | null;
43 readonly composer: {
44 readonly key: string | null;
45 readonly draft: string | null;
46 readonly drafts: Record<string, string>;
47 readonly editors: ReadonlyArray<{ readonly value: string; readonly expanded: boolean }>;
48 readonly error: string | null;
49 readonly keyboard: boolean;
50 };
51 readonly floatingStatus: string | null;
52 readonly environments: ReadonlyArray<string>;
53 /** The app's status for every thread it knows, by thread id. */
54 readonly threads: Record<string, string>;
55 readonly homeList: ReadonlyArray<{
56 readonly type: string;
57 readonly threadId?: string;
58 readonly status?: string;
59 readonly pinned?: boolean;
60 readonly count?: number;
61 readonly expanded?: boolean;
62 }> | null;
64​
65export interface FeedSample {
66 readonly at?: number;
67 readonly threadId: string;
68 readonly ready: boolean;
69 readonly scroll?: number;
70 readonly viewport?: number;
71 readonly content?: number;
72 readonly fromEnd?: number;
73 readonly atEnd?: boolean;
74 readonly following?: boolean | null;
75 readonly count?: number;
76 readonly rows?: Record<string, number>;
78​
79export interface Recording {
80 readonly js: ReadonlyArray<number>;
81 readonly ui: ReadonlyArray<number>;
82 readonly feed: ReadonlyArray<FeedSample>;
84​
85export interface AxNode {
86 readonly type?: string;
87 readonly label?: string;
88 readonly value?: string;
89 readonly kind?: string;
90 readonly editable?: boolean;
91 readonly enabled?: boolean;
92 readonly rect?: {
93 readonly x: number;
94 readonly y: number;
95 readonly width: number;
96 readonly height: number;
97 };
99​
100export interface DeviceOptions {
101 /** `agent-device` executable and the target args `device_open` returned. */
102 readonly agentDevice: string;
103 readonly targetArgs: ReadonlyArray<string>;
104 readonly metro: string;
105 /** Simulator name as Metro's inspector lists it; empty for the only app on this run's Metro. */
106 readonly deviceName: string;
108​
109export function makeDevice(options: DeviceOptions) {
110 const run = (args: ReadonlyArray<string>, timeoutMs = 90_000) =>
111 Effect.try({
112 try: () =>
113 NodeChildProcess.execFileSync(options.agentDevice, [...args, ...options.targetArgs], {
114 encoding: "utf8",
115 timeout: timeoutMs,
116 stdio: ["ignore", "pipe", "pipe"],
117 }),
118 catch: (cause) => {
119 // The thrown message starts with the full command line; the reason is in its output.
120 const output = cause as { readonly stdout?: string; readonly stderr?: string };
121 const reason = `${output.stderr ?? ""}${output.stdout ?? ""}`.trim() || String(cause);
122 return new DeviceError({
123 message: `agent-device ${args.join(" ")} failed: ${reason.slice(-400)}`,
124 });
125 },
126 }).pipe(
127 // A shared pool's workers drop off the gateway for seconds at a time.
128 Effect.retry({
129 times: 4,
130 while: (error) => poolError(error.message),
131 schedule: Schedule.spaced("5 seconds"),
132 }),
133 Effect.withSpan("device.agentDevice", { attributes: { command: args[0] } }),
134 );
135​
136 const evaluate = Effect.fn("device.evaluate")(
137 function* (expression: string) {
138 const targets = yield* HttpClient.get(`${options.metro}/json/list`).pipe(
139 Effect.flatMap(HttpClientResponse.schemaBodyJson(InspectorTargets)),
140 Effect.provide(FetchHttpClient.layer),
141 Effect.mapError(
142 () => new DeviceError({ message: `Metro at ${options.metro} did not answer.` }),
143 ),
144 );
145 // Pool simulators carry generated names; a run's own Metro then serves only its device.
146 const target = targets.findLast(
147 (entry) =>
148 entry.appId === APP_ID &&
149 (!options.deviceName || entry.deviceName === options.deviceName),
150 );
151 if (!target)
152 return yield* new DeviceError({
153 message: `No app on ${options.deviceName} is attached to Metro.`,
154 });
155 // Expo drops inspector sockets whose Origin is not the URL Metro advertises.
156 const socket = yield* Socket.makeWebSocket(target.webSocketDebuggerUrl, {
157 headers: { origin: new URL(options.metro).origin },
158 openTimeout: "10 seconds",
159 });
160 const writer = yield* socket.writer;
161 const reader = yield* socket.reader;
162 yield* writer.write(
163 JSON.stringify({
164 id: 1,
165 method: "Runtime.evaluate",
166 params: { expression, returnByValue: true, awaitPromise: true },
167 }),
168 );
169 while (true) {
170 for (const frame of yield* reader.pull) {
171 const reply = JSON.parse(
172 typeof frame === "string" ? frame : new TextDecoder().decode(frame),
173 ) as {
174 id?: number;
175 result?: { result?: { value?: unknown }; exceptionDetails?: unknown };
176 };
177 if (reply.id !== 1) continue;
178 if (reply.result?.exceptionDetails)
179 return yield* new DeviceError({
180 message: `${expression} threw ${JSON.stringify(reply.result.exceptionDetails).slice(0, 400)}`,
181 });
182 return reply.result?.result?.value;
183 }
184 }
185 },
186 Effect.scoped,
187 Effect.provide(NodeWS.layerWebSocketConstructor),
188 Effect.timeoutOrElse({
189 duration: "20 seconds",
190 orElse: () => Effect.fail(new DeviceError({ message: "The inspector did not answer." })),
191 }),
192 Effect.mapError((error) =>
193 error._tag === "DeviceError"
194 ? error
195 : new DeviceError({ message: `Inspector: ${error.message}` }),
196 ),
197 );
198​
199 const state = evaluate("__t3Behavior.state()").pipe(
200 Effect.flatMap((value) =>
201 Effect.try({
202 try: () => JSON.parse(String(value)) as ProbeState,
203 catch: () =>
204 new DeviceError({ message: "The mobile behavior probe did not return state." }),
205 }),
206 ),
207 );
208​
209 /** Polls the probe until `predicate` holds; fails with the last state after `timeoutMs`. */
210 const waitFor = Effect.fn("device.waitFor")(function* (
211 description: string,
212 predicate: (state: ProbeState) => boolean,
213 timeoutMs = 15_000,
214 ) {
215 const deadline = (yield* Clock.currentTimeMillis) + timeoutMs;
216 let last: ProbeState | null = null;
217 while ((yield* Clock.currentTimeMillis) < deadline) {
218 last = yield* state.pipe(Effect.orElseSucceed(() => null));
219 if (last && predicate(last)) return last;
220 yield* Effect.sleep("250 millis");
221 }
222 return yield* new DeviceError({
223 message: `Timed out waiting for ${description}. Last route: ${JSON.stringify(last?.route ?? null)}`,
224 });
225 });
226​
227 const nodes = run(["snapshot", "--json"]).pipe(
228 Effect.map((out) => (JSON.parse(out) as { data: { nodes: ReadonlyArray<AxNode> } }).data.nodes),
229 );
230​
231 const center = (node: AxNode) => ({
232 x: Math.round(node.rect!.x + node.rect!.width / 2),
233 y: Math.round(node.rect!.y + node.rect!.height / 2),
234 });
235​
236 const screenSize = run([
237 "screenshot",
238 NodePath.join(NodeOS.tmpdir(), "t3-mobile-behavior-screen.png"),
239 "--json",
240 ]).pipe(
241 Effect.map((out) => {
242 const { data } = JSON.parse(out) as { data: { logicalWidth: number; logicalHeight: number } };
243 return { width: data.logicalWidth, height: data.logicalHeight };
244 }),
245 );
246​
247 return {
248 options,
249 run,
250 evaluate,
251 state,
252 waitFor,
253 nodes,
254 center,
255 open: (path: string) =>
256 evaluate(`__t3Behavior.open(${JSON.stringify(`${SCHEME}://${path.replace(/^\//, "")}`)})`),
257 openUrl: (url: string) =>
258 run(["open", APP_ID, url]).pipe(
259 Effect.mapError(
260 (error) =>
261 new DeviceError({ message: error.message.replaceAll(url, `${SCHEME}://[redacted]`) }),
262 ),
263 ),
264 /** Reloads JS, then opens Home; the app restores the last thread, and split layouts keep one open. */
265 reload: Effect.fn("device.reload")(function* (ready: (state: ProbeState) => boolean) {
266 yield* evaluate("__t3Behavior.reload()").pipe(Effect.ignore);
267 yield* Effect.sleep("2 seconds");
268 yield* waitFor("the thread list after reload", ready, 60_000);
269 yield* run(["open", APP_ID, `${SCHEME}://`]);
270 // Split layouts may keep a thread beside Home, so they get a short wait for the Home route.
271 const home = (value: ProbeState) => ready(value) && value.route?.name === "Home";
272 const state = yield* waitFor("Home", home, 5_000).pipe(Effect.option);
273 if (state._tag === "Some") return state.value;
274 return yield* waitFor(
275 "the split layout",
276 (value) => ready(value) && value.route?.columns === true,
277 );
278 }),
279 recordStart: (withFeed: boolean) => evaluate(`__t3Behavior.recordStart(${withFeed})`),
280 recordStop: evaluate("__t3Behavior.recordStop()").pipe(
281 Effect.map((value) => JSON.parse(String(value)) as Recording),
282 ),
283 press: (selector: string) => run(["press", selector]),
284 pressAt: (x: number, y: number) => run(["press", String(x), String(y)]),
285 longPress: (selector: string) => run(["longpress", selector, "800"]),
286 type: (text: string) => run(["type", text]),
287 /** Drags from y1 to y2 at x; a downward drag scrolls the content up. */
288 swipe: (x: number, y1: number, y2: number) =>
289 run(["swipe", String(x), String(y1), String(x), String(y2)]),
290 /**
291 * Answers iOS's "Open in" prompt. XCTest cannot see the iOS 27.1 prompt, so when `alert` fails
292 * this taps where its Open button sits, just right of and below the screen's center.
293 */
294 acceptOpenPrompt: run(["alert", "accept"], 60_000).pipe(
295 Effect.catch(() =>
296 screenSize.pipe(
297 Effect.flatMap(({ width, height }) =>
298 run(["press", String(Math.round(width / 2 + 76)), String(Math.round(height / 2 + 8))]),
299 ),
300 ),
301 ),
302 ),
303 home: run(["home"]),
304 /** The Duo simulator often follows a fold without a hinge reading, so the screen's shape confirms it. */
305 fold: (pose: "closed" | "open") =>
306 run(["fold", pose]).pipe(
307 Effect.catch((error) =>
308 screenSize.pipe(
309 Effect.filterOrFail(
310 ({ width, height }) => (pose === "closed") === width < height,
311 () => error,
312 ),
313 ),
314 ),
315 ),
316 back: run(["back"]),
317 };
319​
320export type Device = ReturnType<typeof makeDevice>;