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