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

DeviceActions.ts

576 lines18.9 KB

1/**
2 * serve-sim's preview drives its "Simulator" panel by sending shell commands over a token-gated
3 * socket. Proxying that would hand any environment session arbitrary command execution on the
4 * host, so T3 runs the same underlying commands itself, typed per action: `xcrun simctl ui` and
5 * `simctl privacy` for iOS, the `serve-sim-ax-settings` helper that serve-sim bundles for the
6 * accessibility toggles, and `adb shell` for Android.
7 */
8import {
9 type DeviceActionInput,
10 type DeviceActionType,
11 type DeviceForegroundApp,
12 DeviceOperationError,
13 DeviceActionUnavailableError,
14 type DeviceOrientation,
15 type DevicePlatform,
16 type DeviceSettings,
17 type DeviceTextSize,
18} from "@t3tools/contracts";
19import * as Effect from "effect/Effect";
20import * as Schema from "effect/Schema";
21​
22import type { DeviceHostReady } from "./DeviceHost.ts";
23​
24type Runner = DeviceHostReady["run"];
25​
26const decodeAxStatus = Schema.decodeUnknownEffect(
27 Schema.fromJsonString(Schema.Record(Schema.String, Schema.String)),
28);
29const encodePushPayload = Schema.encodeUnknownEffect(
30 Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown)),
31);
32​
33const IOS_ACTIONS: ReadonlySet<DeviceActionType> = new Set([
34 "setAppearance",
35 "setTextSize",
36 "setToggle",
37 "setLiquidGlass",
38 "setColorFilter",
39 "setLocation",
40 "clearLocation",
41 "setPermission",
42 "openUrl",
43 "launchApp",
44 "terminateApp",
45 "sendPush",
46]);
47​
48const ANDROID_ACTIONS: ReadonlySet<DeviceActionType> = new Set([
49 "setAppearance",
50 "setTextSize",
51 "setToggle",
52 "setOrientation",
53 "setLocation",
54 "clearLocation",
55 "setPermission",
56 "openUrl",
57 "launchApp",
58 "terminateApp",
59]);
60​
61const IOS_TOGGLES = new Set([
62 "reduceMotion",
63 "increaseContrast",
64 "reduceTransparency",
65 "showBorders",
66 "voiceOver",
67]);
68const ANDROID_TOGGLES = new Set(["reduceMotion", "networkEnabled"]);
69​
70export const supportsAction = (platform: DevicePlatform, input: DeviceActionInput): boolean => {
71 const actions = platform === "ios" ? IOS_ACTIONS : ANDROID_ACTIONS;
72 if (!actions.has(input.type)) return false;
73 if (input.type === "setToggle") {
74 return (platform === "ios" ? IOS_TOGGLES : ANDROID_TOGGLES).has(input.setting);
75 }
76 return true;
77};
78​
79const ok = (operation: string) => (result: { code: number; stderr: string; stdout: string }) =>
80 result.code === 0
81 ? Effect.succeed(result.stdout)
82 : Effect.fail(
83 new DeviceOperationError({
84 operation,
85 reason: "command_failed",
86 exitCode: result.code,
87 cause: result,
88 }),
89 );
90​
91const IOS_TEXT_SIZES: Record<DeviceTextSize, string> = {
92 small: "small",
93 default: "large",
94 large: "extra-extra-large",
95 "extra-large": "accessibility-large",
96};
97const ANDROID_TEXT_SIZES: Record<DeviceTextSize, string> = {
98 small: "0.85",
99 default: "1.0",
100 large: "1.15",
101 "extra-large": "1.3",
102};
103​
104const textSizeFromIos = (category: string): DeviceTextSize | undefined => {
105 const entry = (Object.entries(IOS_TEXT_SIZES) as Array<[DeviceTextSize, string]>).find(
106 ([, value]) => value === category,
107 );
108 if (entry) return entry[0];
109 if (category.startsWith("accessibility")) return "extra-large";
110 if (category.includes("extra")) return "large";
111 return category === "extra-small" || category === "small" || category === "medium"
112 ? "small"
113 : "default";
114};
115​
116const textSizeFromAndroid = (scale: number): DeviceTextSize => {
117 if (scale <= 0.9) return "small";
118 if (scale >= 1.25) return "extra-large";
119 if (scale >= 1.1) return "large";
120 return "default";
121};
122​
123const IOS_TOGGLE_OPTIONS: Record<string, string> = {
124 reduceMotion: "reduce-motion",
125 increaseContrast: "increase-contrast",
126 reduceTransparency: "reduce-transparency",
127 showBorders: "show-borders",
128 voiceOver: "voiceover",
129};
130​
131const IOS_TCC_SERVICES: Record<string, string> = {
132 camera: "camera",
133 microphone: "microphone",
134 photos: "photos",
135 contacts: "contacts",
136 calendar: "calendar",
137 reminders: "reminders",
138 motion: "motion",
139 "media-library": "media-library",
140 faceid: "faceid",
141};
142​
143const ANDROID_PERMISSIONS: Record<string, ReadonlyArray<string>> = {
144 camera: ["android.permission.CAMERA"],
145 microphone: ["android.permission.RECORD_AUDIO"],
146 photos: ["android.permission.READ_MEDIA_IMAGES", "android.permission.READ_EXTERNAL_STORAGE"],
147 contacts: ["android.permission.READ_CONTACTS", "android.permission.WRITE_CONTACTS"],
148 calendar: ["android.permission.READ_CALENDAR", "android.permission.WRITE_CALENDAR"],
149 location: [
150 "android.permission.ACCESS_FINE_LOCATION",
151 "android.permission.ACCESS_COARSE_LOCATION",
152 ],
153 notifications: ["android.permission.POST_NOTIFICATIONS"],
154 motion: ["android.permission.ACTIVITY_RECOGNITION"],
155};
156​
157// Android numbers rotations from the display's natural orientation and the emulator's accelerometer
158// reports gravity in that same frame, so both tables are keyed by the orientation a portrait-native
159// device shows at each rotation.
160const ANDROID_GRAVITY: Record<DeviceOrientation, string> = {
161 portrait: "0:9.81:0",
162 landscape_left: "9.81:0:0",
163 portrait_upside_down: "0:-9.81:0",
164 landscape_right: "-9.81:0:0",
165};
166const ANDROID_ROTATION: Record<DeviceOrientation, string> = {
167 portrait: "0",
168 landscape_left: "1",
169 portrait_upside_down: "2",
170 landscape_right: "3",
171};
172// A landscape-native tablet sits a quarter turn further along that sequence: its portrait is
173// rotation 3 and its landscape is rotation 0.
174const ANDROID_LANDSCAPE_NATIVE_ROTATION: Record<DeviceOrientation, DeviceOrientation> = {
175 portrait: "landscape_right",
176 landscape_left: "portrait",
177 portrait_upside_down: "landscape_left",
178 landscape_right: "portrait_upside_down",
179};
180​
181// `wm size` reports the natural-orientation size; an `Override size:` line is what the window
182// manager uses and is printed after `Physical size:`.
183const isLandscapeNative = (wmSize: string | undefined) => {
184 const size = wmSize ? [...wmSize.matchAll(/size: (\d+)x(\d+)/g)].at(-1) : undefined;
185 return size !== undefined && Number(size[1]) > Number(size[2]);
186};
187​
188export const runDeviceAction = Effect.fn("DeviceActions.run")(function* (
189 ready: DeviceHostReady,
190 platform: DevicePlatform,
191 input: DeviceActionInput,
192) {
193 if (!supportsAction(platform, input)) {
194 return yield* new DeviceActionUnavailableError({
195 operation: input.type,
196 platform,
197 reason: "unsupported",
198 });
199 }
200 if (platform === "ios") return yield* runIos(ready, input);
201 return yield* runAndroid(ready.run, input);
202});
203​
204const simctl = (run: Runner, udid: string, args: ReadonlyArray<string>, operation: string) =>
205 run("xcrun", ["simctl", ...args.slice(0, 1), udid, ...args.slice(1)]).pipe(
206 Effect.flatMap(ok(operation)),
207 );
208​
209const axSettings = Effect.fn("DeviceActions.axSettings")(function* (
210 ready: DeviceHostReady,
211 udid: string,
212 args: ReadonlyArray<string>,
213) {
214 const helper = ready.helpers.serveSimAxSettings;
215 if (!helper) {
216 return yield* new DeviceActionUnavailableError({
217 operation: "accessibility",
218 platform: "ios",
219 reason: "helper_missing",
220 });
221 }
222 return yield* ready
223 .run("xcrun", ["simctl", "spawn", udid, helper, ...args])
224 .pipe(Effect.flatMap(ok("accessibility")));
225});
226​
227const runIos = Effect.fn("DeviceActions.runIos")(function* (
228 ready: DeviceHostReady,
229 input: DeviceActionInput,
230) {
231 const udid = input.deviceId;
232 const { run } = ready;
233 switch (input.type) {
234 case "setAppearance":
235 yield* simctl(run, udid, ["ui", "appearance", input.value], "appearance");
236 return;
237 case "setTextSize":
238 yield* simctl(run, udid, ["ui", "content_size", IOS_TEXT_SIZES[input.value]], "text size");
239 return;
240 case "setToggle":
241 if (input.setting === "increaseContrast") {
242 yield* simctl(
243 run,
244 udid,
245 ["ui", "increase_contrast", input.value ? "enabled" : "disabled"],
246 "increase contrast",
247 );
248 return;
249 }
250 yield* axSettings(ready, udid, [
251 "set",
252 IOS_TOGGLE_OPTIONS[input.setting]!,
253 input.value ? "on" : "off",
254 ]);
255 return;
256 case "setLiquidGlass":
257 yield* axSettings(ready, udid, ["set", "liquid-glass", input.value]);
258 return;
259 case "setColorFilter":
260 yield* axSettings(ready, udid, ["set", "color-filter", input.value]);
261 return;
262 case "setLocation":
263 yield* simctl(
264 run,
265 udid,
266 ["location", "set", `${input.latitude},${input.longitude}`],
267 "location",
268 );
269 return;
270 case "clearLocation":
271 yield* simctl(run, udid, ["location", "clear"], "location");
272 return;
273 case "setPermission": {
274 if (input.permission === "notifications") {
275 // simctl has no notification permission verb; serve-sim's CLI edits
276 // the BulletinBoard plist for it.
277 yield* serveSimPermissions(ready, udid, input);
278 return;
279 }
280 const service =
281 input.permission === "location" ? "location" : IOS_TCC_SERVICES[input.permission];
282 if (!service)
283 return yield* new DeviceActionUnavailableError({
284 operation: "permission",
285 platform: "ios",
286 reason: "unsupported",
287 });
288 yield* simctl(run, udid, ["privacy", input.decision, service, input.appId], "permission");
289 return;
290 }
291 case "openUrl":
292 yield* simctl(run, udid, ["openurl", input.url], "open url");
293 return;
294 case "launchApp":
295 yield* simctl(run, udid, ["launch", input.appId], "launch");
296 return;
297 case "terminateApp":
298 yield* simctl(run, udid, ["terminate", input.appId], "terminate");
299 return;
300 case "sendPush": {
301 const payload =
302 typeof input.payload === "string" ? { aps: { alert: input.payload } } : input.payload;
303 const encoded = yield* encodePushPayload(payload).pipe(
304 Effect.mapError(
305 (cause) =>
306 new DeviceOperationError({ operation: "push", reason: "invalid_payload", cause }),
307 ),
308 );
309 yield* run("xcrun", ["simctl", "push", udid, input.appId, "-"], { stdin: encoded }).pipe(
310 Effect.flatMap(ok("push")),
311 );
312 return;
313 }
314 case "shake":
315 case "setOrientation":
316 return yield* new DeviceActionUnavailableError({
317 operation: input.type,
318 platform: "ios",
319 reason: "unsupported",
320 });
321 }
322});
323​
324const serveSimPermissions = Effect.fn("DeviceActions.serveSimPermissions")(function* (
325 ready: DeviceHostReady,
326 udid: string,
327 input: Extract<DeviceActionInput, { type: "setPermission" }>,
328) {
329 const cli = ready.helpers.serveSimCli;
330 if (!cli)
331 return yield* new DeviceActionUnavailableError({
332 operation: "permission",
333 platform: "ios",
334 reason: "helper_missing",
335 });
336 yield* ready
337 .run(ready.nodePath, [
338 cli,
339 "permissions",
340 input.decision,
341 input.permission,
342 input.appId,
343 "-d",
344 udid,
345 ])
346 .pipe(Effect.flatMap(ok("permission")));
347});
348​
349const adb = (run: Runner, serial: string, args: ReadonlyArray<string>, operation: string) =>
350 run("adb", ["-s", serial, ...args]).pipe(Effect.flatMap(ok(operation)));
351​
352const runAndroid = Effect.fn("DeviceActions.runAndroid")(function* (
353 run: Runner,
354 input: DeviceActionInput,
355) {
356 const serial = input.deviceId;
357 const shell = (args: ReadonlyArray<string>, operation: string) =>
358 adb(run, serial, ["shell", ...args], operation);
359 switch (input.type) {
360 case "setAppearance":
361 yield* shell(["cmd", "uimode", "night", input.value === "dark" ? "yes" : "no"], "appearance");
362 return;
363 case "setTextSize":
364 yield* shell(
365 ["settings", "put", "system", "font_scale", ANDROID_TEXT_SIZES[input.value]],
366 "text size",
367 );
368 return;
369 case "setToggle":
370 if (input.setting === "networkEnabled") {
371 const state = input.value ? "enable" : "disable";
372 yield* shell(["svc", "wifi", state], "network");
373 yield* shell(["svc", "data", state], "network");
374 return;
375 }
376 if (input.setting === "reduceMotion") {
377 const scale = input.value ? "0" : "1";
378 for (const key of [
379 "animator_duration_scale",
380 "transition_animation_scale",
381 "window_animation_scale",
382 ]) {
383 yield* shell(["settings", "put", "global", key, scale], "reduce motion");
384 }
385 return;
386 }
387 return yield* new DeviceActionUnavailableError({
388 operation: input.type,
389 platform: "android",
390 reason: "unsupported",
391 });
392 case "setOrientation": {
393 const wmSize = yield* quiet(shell(["wm", "size"], "orientation"));
394 const rotation = isLandscapeNative(wmSize)
395 ? ANDROID_LANDSCAPE_NATIVE_ROTATION[input.value]
396 : input.value;
397 // `user-rotation lock` only rotates window content on recent images; the display the
398 // encoder captures stays put. Tilting the emulator's accelerometer rotates it for real, so
399 // that is used whenever the target is an emulator.
400 if (serial.startsWith("emulator-")) {
401 yield* shell(["settings", "put", "system", "accelerometer_rotation", "1"], "orientation");
402 yield* shell(["cmd", "window", "user-rotation", "free"], "orientation");
403 yield* adb(
404 run,
405 serial,
406 ["emu", "sensor", "set", "acceleration", ANDROID_GRAVITY[rotation]],
407 "orientation",
408 );
409 return;
410 }
411 yield* shell(
412 ["cmd", "window", "user-rotation", "lock", ANDROID_ROTATION[rotation]],
413 "orientation",
414 );
415 return;
416 }
417 case "setLocation":
418 yield* adb(
419 run,
420 serial,
421 ["emu", "geo", "fix", String(input.longitude), String(input.latitude)],
422 "location",
423 );
424 return;
425 case "clearLocation":
426 // The emulator has no "clear"; leaving the fix in place is the closest
427 // behavior, so this is a no-op that still refreshes the reading.
428 return;
429 case "setPermission": {
430 const permissions = ANDROID_PERMISSIONS[input.permission];
431 if (!permissions) {
432 return yield* new DeviceActionUnavailableError({
433 operation: "permission",
434 platform: "android",
435 reason: "unsupported",
436 });
437 }
438 const verb = input.decision === "grant" ? "grant" : "revoke";
439 for (const permission of permissions) {
440 yield* shell(["pm", verb, input.appId, permission], "permission").pipe(Effect.ignore);
441 }
442 return;
443 }
444 case "openUrl":
445 yield* shell(
446 ["am", "start", "-a", "android.intent.action.VIEW", "-d", input.url],
447 "open url",
448 );
449 return;
450 case "launchApp":
451 yield* shell(
452 ["monkey", "-p", input.appId, "-c", "android.intent.category.LAUNCHER", "1"],
453 "launch",
454 );
455 return;
456 case "terminateApp":
457 yield* shell(["am", "force-stop", input.appId], "terminate");
458 return;
459 case "setLiquidGlass":
460 case "setColorFilter":
461 case "shake":
462 case "sendPush":
463 return yield* new DeviceActionUnavailableError({
464 operation: input.type,
465 platform: "android",
466 reason: "unsupported",
467 });
468 }
469});
470​
471export const readDeviceDetail = Effect.fn("DeviceActions.readDetail")(function* (
472 ready: DeviceHostReady,
473 platform: DevicePlatform,
474 deviceId: string,
475): Effect.fn.Return<{ settings: DeviceSettings; foregroundApp: DeviceForegroundApp | null }> {
476 return platform === "ios"
477 ? yield* readIos(ready, deviceId)
478 : yield* readAndroid(ready.run, deviceId);
479});
480​
481const quiet = <A, E>(effect: Effect.Effect<A, E>) =>
482 effect.pipe(Effect.orElseSucceed((): A | undefined => undefined));
483​
484const readIos = Effect.fn("DeviceActions.readIos")(function* (
485 ready: DeviceHostReady,
486 udid: string,
487) {
488 const { run } = ready;
489 const uiValue = (option: string) =>
490 quiet(
491 simctl(run, udid, ["ui", option], option).pipe(Effect.map((out) => out.trim().toLowerCase())),
492 );
493 const [appearance, contentSize, contrast, axStatus] = yield* Effect.all(
494 [
495 uiValue("appearance"),
496 uiValue("content_size"),
497 uiValue("increase_contrast"),
498 quiet(axSettings(ready, udid, ["status"]).pipe(Effect.flatMap(decodeAxStatus))),
499 ],
500 { concurrency: 4 },
501 );
502 const onOff = (value: string | undefined) =>
503 value === "on" ? true : value === "off" ? false : undefined;
504 const settings: DeviceSettings = {
505 ...(appearance === "light" || appearance === "dark" ? { appearance } : {}),
506 ...(contentSize ? { textSize: textSizeFromIos(contentSize) } : {}),
507 ...(contrast ? { increaseContrast: contrast === "enabled" } : {}),
508 ...(axStatus
509 ? {
510 ...(onOff(axStatus["reduce-motion"]) === undefined
511 ? {}
512 : { reduceMotion: onOff(axStatus["reduce-motion"]) }),
513 ...(onOff(axStatus["reduce-transparency"]) === undefined
514 ? {}
515 : { reduceTransparency: onOff(axStatus["reduce-transparency"]) }),
516 ...(onOff(axStatus["show-borders"]) === undefined
517 ? {}
518 : { showBorders: onOff(axStatus["show-borders"]) }),
519 ...(onOff(axStatus.voiceover) === undefined
520 ? {}
521 : { voiceOver: onOff(axStatus.voiceover) }),
522 ...(axStatus["liquid-glass"] === "clear" || axStatus["liquid-glass"] === "tinted"
523 ? { liquidGlass: axStatus["liquid-glass"] }
524 : {}),
525 ...(isColorFilter(axStatus["color-filter"])
526 ? { colorFilter: axStatus["color-filter"] }
527 : {}),
528 }
529 : {}),
530 };
531 return { settings, foregroundApp: null };
532});
533​
534const isColorFilter = (value: unknown): value is DeviceSettings["colorFilter"] & string =>
535 value === "none" ||
536 value === "grayscale" ||
537 value === "red-green" ||
538 value === "green-red" ||
539 value === "blue-yellow";
540​
541const readAndroid = Effect.fn("DeviceActions.readAndroid")(function* (run: Runner, serial: string) {
542 const shell = (args: ReadonlyArray<string>) =>
543 quiet(
544 adb(run, serial, ["shell", ...args], args[0] ?? "shell").pipe(Effect.map((s) => s.trim())),
545 );
546 const [night, fontScale, animator, wifi, focus] = yield* Effect.all(
547 [
548 shell(["cmd", "uimode", "night"]),
549 shell(["settings", "get", "system", "font_scale"]),
550 shell(["settings", "get", "global", "animator_duration_scale"]),
551 shell(["settings", "get", "global", "wifi_on"]),
552 // `dumpsys window windows` stopped printing the focus on API 36; the
553 // unfiltered dump still does.
554 shell(["dumpsys", "window"]),
555 ],
556 { concurrency: 5 },
557 );
558 const scale = fontScale && fontScale !== "null" ? Number(fontScale) : Number.NaN;
559 const focused = focus?.match(/m(?:CurrentFocus|FocusedApp)=\w+\{[^ ]+ u\d+ ([^/ ]+)\//);
560 const settings: DeviceSettings = {
561 ...(night?.includes("yes")
562 ? { appearance: "dark" }
563 : night?.includes("no")
564 ? { appearance: "light" }
565 : {}),
566 ...(Number.isFinite(scale) ? { textSize: textSizeFromAndroid(scale) } : {}),
567 ...(animator !== undefined && animator !== "null"
568 ? { reduceMotion: Number(animator) === 0 }
569 : {}),
570 ...(wifi === "1" || wifi === "0" ? { networkEnabled: wifi === "1" } : {}),
571 };
572 return {
573 settings,
574 foregroundApp: focused ? { id: focused[1]! } : null,
575 };
576});