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

DeviceActions.ts

567 lines18.4 KB

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