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

DeviceActions.ts

552 lines17.7 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​
157const ANDROID_GRAVITY: Record<DeviceOrientation, string> = {
158 portrait: "0:9.81:0",
159 landscape_left: "9.81:0:0",
160 portrait_upside_down: "0:-9.81:0",
161 landscape_right: "-9.81:0:0",
162};
163const ANDROID_ROTATION: Record<DeviceOrientation, string> = {
164 portrait: "0",
165 landscape_left: "1",
166 portrait_upside_down: "2",
167 landscape_right: "3",
168};
169​
170export const runDeviceAction = Effect.fn("DeviceActions.run")(function* (
171 ready: DeviceHostReady,
172 platform: DevicePlatform,
173 input: DeviceActionInput,
174) {
175 if (!supportsAction(platform, input)) {
176 return yield* new DeviceActionUnavailableError({
177 operation: input.type,
178 platform,
179 reason: "unsupported",
180 });
181 }
182 if (platform === "ios") return yield* runIos(ready, input);
183 return yield* runAndroid(ready.run, input);
184});
185​
186const simctl = (run: Runner, udid: string, args: ReadonlyArray<string>, operation: string) =>
187 run("xcrun", ["simctl", ...args.slice(0, 1), udid, ...args.slice(1)]).pipe(
188 Effect.flatMap(ok(operation)),
189 );
190​
191const axSettings = (ready: DeviceHostReady, udid: string, args: ReadonlyArray<string>) =>
192 Effect.gen(function* () {
193 const helper = ready.helpers.serveSimAxSettings;
194 if (!helper) {
195 return yield* new DeviceActionUnavailableError({
196 operation: "accessibility",
197 platform: "ios",
198 reason: "helper_missing",
199 });
200 }
201 return yield* ready
202 .run("xcrun", ["simctl", "spawn", udid, helper, ...args])
203 .pipe(Effect.flatMap(ok("accessibility")));
204 });
205​
206const runIos = Effect.fn("DeviceActions.runIos")(function* (
207 ready: DeviceHostReady,
208 input: DeviceActionInput,
209) {
210 const udid = input.deviceId;
211 const { run } = ready;
212 switch (input.type) {
213 case "setAppearance":
214 yield* simctl(run, udid, ["ui", "appearance", input.value], "appearance");
215 return;
216 case "setTextSize":
217 yield* simctl(run, udid, ["ui", "content_size", IOS_TEXT_SIZES[input.value]], "text size");
218 return;
219 case "setToggle":
220 if (input.setting === "increaseContrast") {
221 yield* simctl(
222 run,
223 udid,
224 ["ui", "increase_contrast", input.value ? "enabled" : "disabled"],
225 "increase contrast",
226 );
227 return;
228 }
229 yield* axSettings(ready, udid, [
230 "set",
231 IOS_TOGGLE_OPTIONS[input.setting]!,
232 input.value ? "on" : "off",
233 ]);
234 return;
235 case "setLiquidGlass":
236 yield* axSettings(ready, udid, ["set", "liquid-glass", input.value]);
237 return;
238 case "setColorFilter":
239 yield* axSettings(ready, udid, ["set", "color-filter", input.value]);
240 return;
241 case "setLocation":
242 yield* simctl(
243 run,
244 udid,
245 ["location", "set", `${input.latitude},${input.longitude}`],
246 "location",
247 );
248 return;
249 case "clearLocation":
250 yield* simctl(run, udid, ["location", "clear"], "location");
251 return;
252 case "setPermission": {
253 if (input.permission === "notifications") {
254 // simctl has no notification permission verb; serve-sim's CLI edits
255 // the BulletinBoard plist for it.
256 yield* serveSimPermissions(ready, udid, input);
257 return;
258 }
259 const service =
260 input.permission === "location" ? "location" : IOS_TCC_SERVICES[input.permission];
261 if (!service)
262 return yield* new DeviceActionUnavailableError({
263 operation: "permission",
264 platform: "ios",
265 reason: "unsupported",
266 });
267 yield* simctl(run, udid, ["privacy", input.decision, service, input.appId], "permission");
268 return;
269 }
270 case "openUrl":
271 yield* simctl(run, udid, ["openurl", input.url], "open url");
272 return;
273 case "launchApp":
274 yield* simctl(run, udid, ["launch", input.appId], "launch");
275 return;
276 case "terminateApp":
277 yield* simctl(run, udid, ["terminate", input.appId], "terminate");
278 return;
279 case "sendPush": {
280 const payload =
281 typeof input.payload === "string" ? { aps: { alert: input.payload } } : input.payload;
282 const encoded = yield* encodePushPayload(payload).pipe(
283 Effect.mapError(
284 (cause) =>
285 new DeviceOperationError({ operation: "push", reason: "invalid_payload", cause }),
286 ),
287 );
288 yield* run("xcrun", ["simctl", "push", udid, input.appId, "-"], { stdin: encoded }).pipe(
289 Effect.flatMap(ok("push")),
290 );
291 return;
292 }
293 case "shake":
294 case "setOrientation":
295 return yield* new DeviceActionUnavailableError({
296 operation: input.type,
297 platform: "ios",
298 reason: "unsupported",
299 });
300 }
301});
302​
303const serveSimPermissions = (
304 ready: DeviceHostReady,
305 udid: string,
306 input: Extract<DeviceActionInput, { type: "setPermission" }>,
307) =>
308 Effect.gen(function* () {
309 const cli = ready.helpers.serveSimCli;
310 if (!cli)
311 return yield* new DeviceActionUnavailableError({
312 operation: "permission",
313 platform: "ios",
314 reason: "helper_missing",
315 });
316 yield* ready
317 .run(ready.nodePath, [
318 cli,
319 "permissions",
320 input.decision,
321 input.permission,
322 input.appId,
323 "-d",
324 udid,
325 ])
326 .pipe(Effect.flatMap(ok("permission")));
327 });
328​
329const adb = (run: Runner, serial: string, args: ReadonlyArray<string>, operation: string) =>
330 run("adb", ["-s", serial, ...args]).pipe(Effect.flatMap(ok(operation)));
331​
332const runAndroid = Effect.fn("DeviceActions.runAndroid")(function* (
333 run: Runner,
334 input: DeviceActionInput,
335) {
336 const serial = input.deviceId;
337 const shell = (args: ReadonlyArray<string>, operation: string) =>
338 adb(run, serial, ["shell", ...args], operation);
339 switch (input.type) {
340 case "setAppearance":
341 yield* shell(["cmd", "uimode", "night", input.value === "dark" ? "yes" : "no"], "appearance");
342 return;
343 case "setTextSize":
344 yield* shell(
345 ["settings", "put", "system", "font_scale", ANDROID_TEXT_SIZES[input.value]],
346 "text size",
347 );
348 return;
349 case "setToggle":
350 if (input.setting === "networkEnabled") {
351 const state = input.value ? "enable" : "disable";
352 yield* shell(["svc", "wifi", state], "network");
353 yield* shell(["svc", "data", state], "network");
354 return;
355 }
356 if (input.setting === "reduceMotion") {
357 const scale = input.value ? "0" : "1";
358 for (const key of [
359 "animator_duration_scale",
360 "transition_animation_scale",
361 "window_animation_scale",
362 ]) {
363 yield* shell(["settings", "put", "global", key, scale], "reduce motion");
364 }
365 return;
366 }
367 return yield* new DeviceActionUnavailableError({
368 operation: input.type,
369 platform: "android",
370 reason: "unsupported",
371 });
372 case "setOrientation": {
373 // `user-rotation lock` only rotates window content on recent images; the display the
374 // encoder captures stays put. Tilting the emulator's accelerometer rotates it for real, so
375 // that is used whenever the target is an emulator.
376 if (serial.startsWith("emulator-")) {
377 yield* shell(["settings", "put", "system", "accelerometer_rotation", "1"], "orientation");
378 yield* shell(["cmd", "window", "user-rotation", "free"], "orientation");
379 yield* adb(
380 run,
381 serial,
382 ["emu", "sensor", "set", "acceleration", ANDROID_GRAVITY[input.value]],
383 "orientation",
384 );
385 return;
386 }
387 yield* shell(
388 ["cmd", "window", "user-rotation", "lock", ANDROID_ROTATION[input.value]],
389 "orientation",
390 );
391 return;
392 }
393 case "setLocation":
394 yield* adb(
395 run,
396 serial,
397 ["emu", "geo", "fix", String(input.longitude), String(input.latitude)],
398 "location",
399 );
400 return;
401 case "clearLocation":
402 // The emulator has no "clear"; leaving the fix in place is the closest
403 // behavior, so this is a no-op that still refreshes the reading.
404 return;
405 case "setPermission": {
406 const permissions = ANDROID_PERMISSIONS[input.permission];
407 if (!permissions) {
408 return yield* new DeviceActionUnavailableError({
409 operation: "permission",
410 platform: "android",
411 reason: "unsupported",
412 });
413 }
414 const verb = input.decision === "grant" ? "grant" : "revoke";
415 for (const permission of permissions) {
416 yield* shell(["pm", verb, input.appId, permission], "permission").pipe(Effect.ignore);
417 }
418 return;
419 }
420 case "openUrl":
421 yield* shell(
422 ["am", "start", "-a", "android.intent.action.VIEW", "-d", input.url],
423 "open url",
424 );
425 return;
426 case "launchApp":
427 yield* shell(
428 ["monkey", "-p", input.appId, "-c", "android.intent.category.LAUNCHER", "1"],
429 "launch",
430 );
431 return;
432 case "terminateApp":
433 yield* shell(["am", "force-stop", input.appId], "terminate");
434 return;
435 case "setLiquidGlass":
436 case "setColorFilter":
437 case "shake":
438 case "sendPush":
439 return yield* new DeviceActionUnavailableError({
440 operation: input.type,
441 platform: "android",
442 reason: "unsupported",
443 });
444 }
445});
446​
447export const readDeviceDetail = Effect.fn("DeviceActions.readDetail")(function* (
448 ready: DeviceHostReady,
449 platform: DevicePlatform,
450 deviceId: string,
451): Effect.fn.Return<{ settings: DeviceSettings; foregroundApp: DeviceForegroundApp | null }> {
452 return platform === "ios"
453 ? yield* readIos(ready, deviceId)
454 : yield* readAndroid(ready.run, deviceId);
455});
456​
457const quiet = <A, E>(effect: Effect.Effect<A, E>) =>
458 effect.pipe(Effect.orElseSucceed((): A | undefined => undefined));
459​
460const readIos = Effect.fn("DeviceActions.readIos")(function* (
461 ready: DeviceHostReady,
462 udid: string,
463) {
464 const { run } = ready;
465 const uiValue = (option: string) =>
466 quiet(
467 simctl(run, udid, ["ui", option], option).pipe(Effect.map((out) => out.trim().toLowerCase())),
468 );
469 const [appearance, contentSize, contrast, axStatus] = yield* Effect.all(
470 [
471 uiValue("appearance"),
472 uiValue("content_size"),
473 uiValue("increase_contrast"),
474 quiet(axSettings(ready, udid, ["status"]).pipe(Effect.flatMap(decodeAxStatus))),
475 ],
476 { concurrency: 4 },
477 );
478 const onOff = (value: string | undefined) =>
479 value === "on" ? true : value === "off" ? false : undefined;
480 const settings: DeviceSettings = {
481 ...(appearance === "light" || appearance === "dark" ? { appearance } : {}),
482 ...(contentSize ? { textSize: textSizeFromIos(contentSize) } : {}),
483 ...(contrast ? { increaseContrast: contrast === "enabled" } : {}),
484 ...(axStatus
485 ? {
486 ...(onOff(axStatus["reduce-motion"]) === undefined
487 ? {}
488 : { reduceMotion: onOff(axStatus["reduce-motion"]) }),
489 ...(onOff(axStatus["reduce-transparency"]) === undefined
490 ? {}
491 : { reduceTransparency: onOff(axStatus["reduce-transparency"]) }),
492 ...(onOff(axStatus["show-borders"]) === undefined
493 ? {}
494 : { showBorders: onOff(axStatus["show-borders"]) }),
495 ...(onOff(axStatus.voiceover) === undefined
496 ? {}
497 : { voiceOver: onOff(axStatus.voiceover) }),
498 ...(axStatus["liquid-glass"] === "clear" || axStatus["liquid-glass"] === "tinted"
499 ? { liquidGlass: axStatus["liquid-glass"] }
500 : {}),
501 ...(isColorFilter(axStatus["color-filter"])
502 ? { colorFilter: axStatus["color-filter"] }
503 : {}),
504 }
505 : {}),
506 };
507 return { settings, foregroundApp: null };
508});
509​
510const isColorFilter = (value: unknown): value is DeviceSettings["colorFilter"] & string =>
511 value === "none" ||
512 value === "grayscale" ||
513 value === "red-green" ||
514 value === "green-red" ||
515 value === "blue-yellow";
516​
517const readAndroid = Effect.fn("DeviceActions.readAndroid")(function* (run: Runner, serial: string) {
518 const shell = (args: ReadonlyArray<string>) =>
519 quiet(
520 adb(run, serial, ["shell", ...args], args[0] ?? "shell").pipe(Effect.map((s) => s.trim())),
521 );
522 const [night, fontScale, animator, wifi, focus] = yield* Effect.all(
523 [
524 shell(["cmd", "uimode", "night"]),
525 shell(["settings", "get", "system", "font_scale"]),
526 shell(["settings", "get", "global", "animator_duration_scale"]),
527 shell(["settings", "get", "global", "wifi_on"]),
528 // `dumpsys window windows` stopped printing the focus on API 36; the
529 // unfiltered dump still does.
530 shell(["dumpsys", "window"]),
531 ],
532 { concurrency: 5 },
533 );
534 const scale = fontScale && fontScale !== "null" ? Number(fontScale) : Number.NaN;
535 const focused = focus?.match(/m(?:CurrentFocus|FocusedApp)=\w+\{[^ ]+ u\d+ ([^/ ]+)\//);
536 const settings: DeviceSettings = {
537 ...(night?.includes("yes")
538 ? { appearance: "dark" }
539 : night?.includes("no")
540 ? { appearance: "light" }
541 : {}),
542 ...(Number.isFinite(scale) ? { textSize: textSizeFromAndroid(scale) } : {}),
543 ...(animator !== undefined && animator !== "null"
544 ? { reduceMotion: Number(animator) === 0 }
545 : {}),
546 ...(wifi === "1" || wifi === "0" ? { networkEnabled: wifi === "1" } : {}),
547 };
548 return {
549 settings,
550 foregroundApp: focused ? { id: focused[1]! } : null,
551 };
552});