1use std::{
18 sync::{
19 Arc, Mutex,
20 atomic::{AtomicBool, Ordering},
21 },
22 time::{Duration, Instant},
23};
24
25use rquickjs::{CaughtError, Context, Function, Runtime, context::EvalOptions};
26use serde_json::{Map, Value, json};
27
28use crate::{
29 actions::{Target, TapArgs, brief, parse_args, parse_target},
30 ax::tree::{BuildOptions, Screen},
31 device::session::Session,
32 fields,
33 i18n::t,
34 paths,
35 reply::{Fail, Outcome, Res, envelope},
36 selector::Selector,
37};
38
39const BUILTIN: &[(&str, &str)] = &[
41 ("settings-version", include_str!("../scripts/settings-version.js")),
42 ("calculator-multiply", include_str!("../scripts/calculator-multiply.js")),
43 ("clock-world-list", include_str!("../scripts/clock-world-list.js")),
44 ("settings-list", include_str!("../scripts/settings-list.js")),
45];
46
47fn description(code: &str) -> String {
49 code.lines()
50 .map(str::trim)
51 .find(|l| !l.is_empty())
52 .and_then(|l| l.strip_prefix("//"))
53 .map(|l| l.trim().to_string())
54 .unwrap_or_default()
55}
56
57pub fn list() -> Vec<(String, String, String)> {
59 let mut out: Vec<(String, String, String)> = Vec::new();
60 if let Ok(dir) = std::fs::read_dir(paths::personal_scripts()) {
61 let mut files: Vec<std::path::PathBuf> = dir
62 .filter_map(|e| e.ok().map(|e| e.path()))
63 .filter(|p| p.extension().and_then(|e| e.to_str()) == Some("js"))
64 .collect();
65 files.sort();
66 for path in files {
67 let name = path.file_stem().and_then(|s| s.to_str()).unwrap_or("?").to_string();
68 let about = std::fs::read_to_string(&path).map(|c| description(&c)).unwrap_or_default();
69 out.push((name, about, path.display().to_string()));
70 }
71 }
72 for (name, code) in BUILTIN {
73 if !out.iter().any(|(n, _, _)| n == name) {
74 out.push((name.to_string(), description(code), format!("builtin:{name}")));
75 }
76 }
77 out
78}
79
80pub fn load(name: &str) -> Res<(String, String)> {
83 if name.ends_with(".js") || name.contains('/') {
84 return Err(Fail::invalid(format!("\"{name}\" is a file, not the name of a saved script")).hint(t(
85 "파일은 `iph script <파일>`로 실행합니다.",
86 "Run a file with `iph script <file>`.",
87 )));
88 }
89 let path = paths::personal_scripts().join(format!("{name}.js"));
90 if let Ok(code) = std::fs::read_to_string(&path) {
91 return Ok((code, path.display().to_string()));
92 }
93 if let Some((_, code)) = BUILTIN.iter().find(|(n, _)| *n == name) {
94 return Ok((code.to_string(), format!("builtin:{name}")));
95 }
96 Err(Fail::not_sent("script_not_found", format!("no script named \"{name}\"")).hint(t(
97 "`iph scripts`로 목록을 확인하세요. 개인 스크립트는 ~/.config/iph/scripts/<이름>.js 에 둡니다.",
98 "List them with `iph scripts`. Personal scripts live in ~/.config/iph/scripts/<name>.js.",
99 )))
100}
101
102pub fn cmd_scripts() -> Res {
103 let list: Vec<Value> = list()
104 .into_iter()
105 .map(|(name, description, source)| json!({ "name": name, "description": description, "source": source }))
106 .collect();
107 Ok(fields! { "count": list.len(), "scripts": list })
108}
109
110const PRELUDE: &str = r#"
117"use strict";
118(() => {
119 const opts = (o) => (o && typeof o === "object" && !Array.isArray(o)) ? o : {};
120 const call = (cmd, args) => {
121 const r = JSON.parse(__iph(cmd, JSON.stringify(args === undefined ? {} : args)));
122 if (r.ok) return r;
123 const e = new Error((r.error && r.error.message) || "the call failed");
124 e.name = "IphError";
125 e.cmd = cmd;
126 e.code = r.error && r.error.code;
127 e.outcome = r.outcome;
128 e.hint = r.error && r.error.hint;
129 e.result = r;
130 throw e;
131 };
132 const text = (x) => (typeof x === "string" ? x : JSON.stringify(x));
133 const g = globalThis;
134 g.read = (o) => call("read", opts(o));
135 g.find = (selector, o) => call("find", { ...opts(o), selector });
136 g.tap = (target, o) => call("tap", { ...opts(o), target });
137 g.swipe = (how, o) => call("swipe", typeof how === "string" ? { ...opts(o), direction: how } : { ...opts(o), ...opts(how) });
138 g.pinch = (how, o) => call("pinch", typeof how === "string" ? { ...opts(o), direction: how } : { ...opts(o), ...opts(how) });
139 g.scroll = (direction, o) => call("scroll", { ...opts(o), direction });
140 g.type = (value, o) => call("type", { ...opts(o), text: String(value) });
141 g.key = (name, o) => call("key", { ...opts(o), key: name });
142 g.button = (name, o) => call("button", { ...opts(o), button: name });
143 g.launch = (app, o) => call("launch", { ...opts(o), app });
144 g.apps = () => call("apps", {});
145 g.waitFor = (selector, o) => call("wait_for", { ...opts(o), selector });
146 g.readField = (spec) => call("read_field", opts(spec)).value;
147 g.readList = (spec) => call("read_list", opts(spec));
148 g.syslog = (action, o) => call("syslog", { ...opts(o), action });
149 g.sleep = (ms) => { __sleep(Number(ms) || 0); };
150 g.log = (...xs) => { __emit("log", "", xs.map(text).join(" ")); };
151 g.output = (key, value) => { __emit("output", String(key), JSON.stringify(value === undefined ? null : value)); };
152 g.console = { log: g.log, info: g.log, warn: g.log, error: g.log };
153 g.__done = (value) => JSON.stringify({ ok: true, value });
154 g.__threw = (e) => {
155 const error = {
156 name: e && e.name,
157 message: e && e.message !== undefined ? String(e.message) : String(e),
158 stack: e && e.stack ? String(e.stack) : undefined,
159 };
160 if (e && e.result) {
161 error.cmd = e.cmd;
162 error.result = e.result;
163 }
164 return JSON.stringify({ ok: false, error });
165 };
166})();
167"#;
168
169const SCRIPT_FILE: &str = "script";
171
172const STOPPED: &str =
174 r#"{"ok":false,"outcome":"not_sent","error":{"code":"script_stopped","message":"the script was stopped"}}"#;
175
176const MAX_LOGS: usize = 200;
178const MAX_LOG_LINE: usize = 2000;
179
180pub const MAX_TIMEOUT_SECS: u64 = 840;
183
184pub struct Limits {
185 pub timeout: Duration,
186 pub memory: usize,
188}
189
190#[allow(async_fn_in_trait)]
192pub trait ScriptHost {
193 async fn call(&mut self, cmd: &str, args: Value) -> Value;
195 fn must_stop(&self) -> bool;
197 fn cut_off(&mut self, cmd: &str);
199}
200
201#[derive(Debug, Clone, PartialEq)]
202pub enum End {
203 Returned(Option<Value>),
205 Threw(Value),
208 Stopped(&'static str),
211 Engine(String),
213}
214
215#[derive(Debug)]
216pub struct Ended {
217 pub end: End,
218 pub outputs: Map<String, Value>,
219 pub logs: Vec<String>,
220 pub calls: u32,
221 pub lines: u64,
223}
224
225struct Call {
226 cmd: String,
227 args: String,
228 reply: std::sync::mpsc::Sender<String>,
229}
230
231#[derive(Default)]
232struct Shared {
233 stop: AtomicBool,
235 outputs: Mutex<Map<String, Value>>,
236 logs: Mutex<Vec<String>>,
237}
238
239fn js_main(
241 code: &str,
242 args: &Value,
243 memory: usize,
244 shared: &Arc<Shared>,
245 calls: tokio::sync::mpsc::UnboundedSender<Call>,
246) -> End {
247 let runtime = match Runtime::new() {
248 Ok(r) => r,
249 Err(e) => return End::Engine(format!("cannot start the engine: {e}")),
250 };
251 runtime.set_memory_limit(memory);
252 runtime.set_max_stack_size(1 << 20);
253 let flag = shared.clone();
254 runtime.set_interrupt_handler(Some(Box::new(move || flag.stop.load(Ordering::Relaxed))));
255 let context = match Context::full(&runtime) {
258 Ok(c) => c,
259 Err(e) => return End::Engine(format!("cannot start the engine: {e}")),
260 };
261 context.with(|ctx| {
262 let ran = (|| -> rquickjs::Result<String> {
263 let globals = ctx.globals();
264 let (stop, door) = (shared.clone(), calls.clone());
265 globals.set(
266 "__iph",
267 Function::new(ctx.clone(), move |cmd: String, args: String| -> String {
268 if stop.stop.load(Ordering::Relaxed) {
269 return STOPPED.to_string();
270 }
271 let (reply, answer) = std::sync::mpsc::channel();
272 if door.send(Call { cmd, args, reply }).is_err() {
273 return STOPPED.to_string();
274 }
275 answer.recv().unwrap_or_else(|_| STOPPED.to_string())
276 })?,
277 )?;
278 let stop = shared.clone();
279 globals.set(
280 "__sleep",
281 Function::new(ctx.clone(), move |ms: f64| {
282 let until = Instant::now() + Duration::from_millis(ms.clamp(0.0, 600_000.0) as u64);
283 while !stop.stop.load(Ordering::Relaxed) {
284 let left = until.saturating_duration_since(Instant::now());
285 if left.is_zero() {
286 break;
287 }
288 std::thread::sleep(left.min(Duration::from_millis(20)));
289 }
290 })?,
291 )?;
292 let kept = shared.clone();
293 globals.set(
294 "__emit",
295 Function::new(ctx.clone(), move |kind: String, key: String, body: String| {
296 if kind == "output" {
297 let value = serde_json::from_str(&body).unwrap_or(Value::Null);
298 kept.outputs.lock().unwrap().insert(key, value);
299 } else {
300 let mut logs = kept.logs.lock().unwrap();
301 if logs.len() < MAX_LOGS {
302 logs.push(body.chars().take(MAX_LOG_LINE).collect());
303 }
304 }
305 })?,
306 )?;
307 let named = |name: &str| {
309 let mut options = EvalOptions::default();
310 options.filename = Some(name.into());
311 options
312 };
313 ctx.eval_with_options::<(), _>(PRELUDE, named("iph"))?;
314 let run: Function = ctx.eval_with_options(
317 format!(
318 "(function(args){{try{{return __done((function(args){{\"use strict\";\n{code}\n}})(args))}}catch(e){{return __threw(e)}}}})"
319 ),
320 named(SCRIPT_FILE),
321 )?;
322 let args = ctx.json_parse(args.to_string())?;
323 run.call((args,))
324 })();
325 match ran {
326 Ok(text) => match serde_json::from_str::<Value>(&text) {
327 Ok(v) if v["ok"] == true => End::Returned(v.get("value").cloned().filter(|x| !x.is_null())),
328 Ok(v) => End::Threw(v["error"].clone()),
329 Err(e) => End::Engine(format!("the script's result is not JSON: {e}")),
330 },
331 Err(_) if shared.stop.load(Ordering::Relaxed) => End::Stopped("timeout"),
332 Err(e) => End::Threw(match CaughtError::from_error(&ctx, e) {
335 CaughtError::Exception(ex) => json!({
336 "name": "Error",
337 "message": ex.message().unwrap_or_else(|| "the script could not run".into()),
338 "stack": ex.stack(),
339 }),
340 other => json!({ "name": "Error", "message": other.to_string() }),
341 }),
342 }
343 })
344}
345
346pub async fn run<H: ScriptHost>(host: &mut H, code: &str, args: &Map<String, Value>, limits: &Limits) -> Ended {
348 let shared = Arc::new(Shared::default());
349 let lines = code.lines().count().max(1) as u64;
350 let (door, mut calls_in) = tokio::sync::mpsc::unbounded_channel::<Call>();
351 let (done, finished) = tokio::sync::oneshot::channel::<End>();
352 let (thread_shared, code_owned, args_owned, memory) =
353 (shared.clone(), code.to_string(), Value::Object(args.clone()), limits.memory);
354 let spawned = std::thread::Builder::new()
355 .name("iph-script".into())
356 .stack_size(8 << 20)
357 .spawn(move || {
358 let end = js_main(&code_owned, &args_owned, memory, &thread_shared, door);
359 let _ = done.send(end);
360 });
361 if let Err(e) = spawned {
362 return Ended {
363 end: End::Engine(format!("cannot start the script: {e}")),
364 outputs: Map::new(),
365 logs: Vec::new(),
366 calls: 0,
367 lines,
368 };
369 }
370
371 let deadline = tokio::time::Instant::now() + limits.timeout;
372 let mut calls = 0u32;
373 let mut stopped: Option<&'static str> = None;
374 loop {
375 let next = tokio::select! {
376 call = calls_in.recv() => call,
377 _ = tokio::time::sleep_until(deadline) => {
378 stopped = Some("timeout");
379 None
380 }
381 };
382 let Some(call) = next else { break };
384 calls += 1;
385 let args = serde_json::from_str(&call.args).unwrap_or_else(|_| json!({}));
386 let reply = match tokio::time::timeout_at(deadline, host.call(&call.cmd, args)).await {
387 Ok(result) => result.to_string(),
388 Err(_) => {
389 host.cut_off(&call.cmd);
390 stopped = Some("timeout");
391 STOPPED.to_string()
392 }
393 };
394 if stopped.is_none() && host.must_stop() {
395 stopped = Some("unknown_outcome");
396 }
397 if stopped.is_some() {
398 shared.stop.store(true, Ordering::Relaxed);
400 }
401 let _ = call.reply.send(reply);
402 if stopped.is_some() {
403 break;
404 }
405 }
406 if stopped.is_some() {
407 shared.stop.store(true, Ordering::Relaxed);
408 }
409 drop(calls_in);
411 let end = match tokio::time::timeout(Duration::from_secs(10), finished).await {
412 Ok(Ok(end)) => end,
413 Ok(Err(_)) => End::Engine("the script engine stopped unexpectedly".into()),
414 Err(_) => End::Engine("the script did not stop".into()),
415 };
416 let end = match stopped {
417 Some(why) => End::Stopped(why),
418 None => end,
419 };
420 Ended {
421 end,
422 outputs: std::mem::take(&mut *shared.outputs.lock().unwrap()),
423 logs: std::mem::take(&mut *shared.logs.lock().unwrap()),
424 calls,
425 lines,
426 }
427}
428
429const INPUTS: [&str; 9] = ["launch", "tap", "swipe", "pinch", "scroll", "type", "key", "button", "read_list"];
435const MANY_INPUTS: [&str; 2] = ["scroll", "read_list"];
437const NEEDS_APP: [&str; 9] = ["tap", "swipe", "pinch", "scroll", "type", "key", "button", "read_field", "read_list"];
439
440#[derive(Debug)]
442pub struct Prepared {
443 pub args: Value,
444 pub hint: Option<String>,
445}
446
447#[derive(Debug, Default)]
448pub struct RunState {
449 pub inputs_sent: u32,
451 pub expected_pid: Option<i64>,
453 pub unknown: Option<(String, Value)>,
455}
456
457impl RunState {
458 pub fn prepare(&mut self, cmd: &str, args: Value) -> Res<Prepared> {
460 let Value::Object(mut map) = args else {
461 return Err(Fail::invalid(format!("`{cmd}` takes an object of arguments")));
462 };
463 if cmd == "syslog" && map.get("output").is_some_and(|v| !v.is_null()) {
464 return Err(Fail::invalid("a script cannot write a file; read the log back with syslog(\"read\")"));
466 }
467 let hint = map.remove("hint").and_then(|v| v.as_str().map(String::from));
468 Ok(Prepared { args: Value::Object(map), hint })
469 }
470
471 pub fn note(&mut self, cmd: &str, result: &Value) {
473 let outcome = result["outcome"].as_str().unwrap_or("");
474 let sent = result["ok"] == true
475 || outcome == "unknown"
476 || outcome == "done"
477 || (MANY_INPUTS.contains(&cmd) && result["error"]["code"] != "invalid_argument");
479 if INPUTS.contains(&cmd) && sent {
480 self.inputs_sent += 1;
481 }
482 if outcome == "unknown" {
483 self.unknown = Some((cmd.to_string(), result.clone()));
484 }
485 }
486}
487
488fn script_line(stack: Option<&str>) -> Option<u64> {
491 let stack = stack?;
492 let mark = format!("{SCRIPT_FILE}:");
493 let mut from = 0;
494 while let Some(found) = stack[from..].find(&mark) {
495 let at = from + found;
496 from = at + mark.len();
497 if at > 0 && !matches!(stack.as_bytes()[at - 1], b'(' | b' ') {
499 continue;
500 }
501 let digits: String = stack[from..].chars().take_while(|c| c.is_ascii_digit()).collect();
502 if let Ok(n) = digits.parse::<u64>() {
503 return Some(n.saturating_sub(1)).filter(|n| *n > 0);
504 }
505 }
506 None
507}
508
509pub fn finish(ended: Ended, state: &RunState) -> Res {
511 let Ended { end, mut outputs, logs, calls, lines } = ended;
512 let sent = state.inputs_sent;
513 let outcome_of = |call: Option<&Value>| match call.and_then(|c| c["outcome"].as_str()) {
517 Some("unknown") => Outcome::Unknown,
518 _ if sent > 0 => Outcome::Unknown,
519 _ => Outcome::NotSent,
520 };
521 let failed_call = |result: &Value, cmd: &str, line: Option<u64>| -> Fail {
522 let reason = &result["error"];
523 let mut f = Fail::new(
524 outcome_of(Some(result)),
525 "script_failed",
526 format!("`{cmd}` failed: {}", reason["message"].as_str().unwrap_or("")),
527 );
528 f.hint = reason["hint"].as_str().map(String::from);
529 f = f
530 .with("failed_call", json!({ "cmd": cmd, "line": line, "outcome": result["outcome"] }))
531 .with("reason", json!({ "code": reason["code"], "message": reason["message"] }));
532 if let Some(extra) = result.as_object() {
534 for (k, v) in extra {
535 if !matches!(k.as_str(), "ok" | "outcome" | "error" | "elapsed_ms") {
536 f.extra.entry(k.clone()).or_insert(v.clone());
537 }
538 }
539 }
540 f
541 };
542
543 let fail = match end {
544 End::Returned(value) => {
545 match value {
546 Some(Value::Object(returned)) => outputs.extend(returned),
547 Some(other) => {
548 outputs.insert("result".into(), other);
549 }
550 None => {}
551 }
552 return Ok(fields! { "outputs": outputs, "logs": logs, "calls": calls, "inputs_sent": sent });
553 }
554 End::Threw(error) => {
555 let line = script_line(error["stack"].as_str()).map(|n| n.min(lines));
557 match (error.get("result"), error["cmd"].as_str()) {
558 (Some(result), Some(cmd)) if result.is_object() => failed_call(result, cmd, line),
559 _ => Fail::new(
560 outcome_of(None),
561 "script_error",
562 error["message"].as_str().unwrap_or("the script threw").to_string(),
563 )
564 .with("line", json!(line)),
565 }
566 }
567 End::Stopped("unknown_outcome") => match &state.unknown {
568 Some((cmd, result)) => failed_call(result, cmd, None),
569 None => Fail::unknown("script_stopped", "the script was stopped"),
570 },
571 End::Stopped(_) => Fail::new(
572 outcome_of(None),
573 "script_timeout",
574 "the script ran longer than it is allowed to",
575 )
576 .hint(t(
577 "config.toml의 [script] timeout_secs로 한도를 바꿀 수 있습니다. 입력을 보낸 뒤였다면 `iph read`로 화면부터 확인하세요.",
578 "[script] timeout_secs in config.toml changes the limit. If input had gone out, check the screen with `iph read` first.",
579 )),
580 End::Engine(message) => Fail::new(outcome_of(None), "script_error", message),
581 };
582 let fail = if sent > 0 && fail.hint.is_none() {
583 fail.hint(t(
584 "스크립트가 입력을 보낸 뒤에 멈췄습니다. 다시 실행하기 전에 `iph read`로 화면을 확인하세요.",
585 "The script stopped after it had sent input. Check the screen with `iph read` before running it again.",
586 ))
587 } else {
588 fail
589 };
590 Err(fail
591 .with("outputs", json!(outputs))
592 .with("logs", json!(logs))
593 .with("calls", calls)
594 .with("inputs_sent", sent))
595}
596
597struct PhoneHost<'a> {
602 session: &'a mut Session,
603 state: RunState,
604}
605
606impl PhoneHost<'_> {
607 async fn tap(&mut self, args: Value) -> Res {
608 let s = &mut *self.session;
609 let Value::Object(mut map) = args else {
610 return Err(Fail::invalid("tap takes a target"));
611 };
612 let wait = map.remove("timeout_ms").and_then(|v| v.as_u64()).unwrap_or(5000);
615 let settle = map.remove("settle").and_then(|v| v.as_bool()).unwrap_or(true);
616 let target = map.get("target").cloned().unwrap_or(Value::Null);
617 if let Some(list) = target.as_array() {
618 return Box::pin(s.tap_sequence(list)).await;
619 }
620 if let Target::Selector(sel) = parse_target(&target)? {
621 if wait > 0 {
622 Box::pin(s.wait_for(&sel, Duration::from_millis(wait))).await?;
623 }
624 if settle {
625 Box::pin(s.settle_target(&sel)).await?;
626 }
627 }
628 let tap: TapArgs = parse_args(&Value::Object(map))?;
629 Box::pin(s.cmd_tap(tap)).await
630 }
631
632 async fn dispatch(&mut self, cmd: &str, args: Value) -> Res {
633 if NEEDS_APP.contains(&cmd) {
634 Box::pin(self.session.check_expected_app(self.state.expected_pid)).await?;
635 }
636 match cmd {
637 "read" => Box::pin(self.session.cmd_read(parse_args(&args)?)).await,
638 "find" => Box::pin(self.session.cmd_find(parse_args(&args)?)).await,
639 "apps" => self.session.cmd_apps().await,
640 "launch" => {
641 let r = Box::pin(self.session.cmd_launch(parse_args(&args)?)).await?;
642 if r.get("foreground").and_then(|v| v.as_bool()) != Some(true) {
643 return Err(Fail::unknown("launch_not_verified", "the app was launched but is not in front"));
644 }
645 self.state.expected_pid = r.get("pid").and_then(|v| v.as_i64());
646 Ok(r)
647 }
648 "tap" => self.tap(args).await,
649 "swipe" | "pinch" | "scroll" | "type" | "key" | "button" | "read_list" => {
650 let s = &mut *self.session;
651 match cmd {
652 "swipe" => Box::pin(s.cmd_swipe(parse_args(&args)?)).await,
653 "pinch" => Box::pin(s.cmd_pinch(parse_args(&args)?)).await,
654 "scroll" => Box::pin(s.cmd_scroll(parse_args(&args)?)).await,
655 "type" => Box::pin(s.cmd_type(parse_args(&args)?)).await,
656 "key" => Box::pin(s.cmd_key(parse_args(&args)?)).await,
657 "button" => Box::pin(s.cmd_button(parse_args(&args)?)).await,
658 _ => Box::pin(s.read_list(&args)).await.map(|(_, rows, info)| {
659 let count = rows.as_array().map(|a| a.len()).unwrap_or(0);
660 fields! { "rows": rows, "count": count, "scrolls": info["scrolls"], "ended": info["ended"] }
661 }),
662 }
663 }
664 "wait_for" => {
665 let selector = args.get("selector").cloned().unwrap_or(Value::Null);
666 let sel = Selector::from_value(&selector).map_err(|e| Fail::invalid(e.to_string()))?;
667 let timeout = args.get("timeout_ms").and_then(|v| v.as_u64()).unwrap_or(8000);
668 let el = Box::pin(self.session.wait_for(&sel, Duration::from_millis(timeout))).await?;
669 Ok(fields! { "element": brief(&el) })
670 }
671 "read_field" => {
672 let (_, value) = Box::pin(self.session.read_field(&args)).await?;
673 Ok(fields! { "value": value })
674 }
675 "syslog" => Box::pin(self.session.cmd_syslog(&args)).await,
676 other => Err(Fail::invalid(format!(
677 "a script has no `{other}` (read, find, tap, swipe, pinch, scroll, type, key, button, launch, apps, waitFor, readField, readList, syslog)"
678 ))),
679 }
680 }
681}
682
683impl ScriptHost for PhoneHost<'_> {
684 async fn call(&mut self, cmd: &str, args: Value) -> Value {
685 let started = Instant::now();
686 let result = match self.state.prepare(cmd, args) {
687 Ok(Prepared { args, hint }) => {
688 Box::pin(self.dispatch(cmd, args)).await.map_err(|mut f| {
689 if let Some(hint) = hint {
691 f.hint = Some(hint);
692 }
693 f
694 })
695 }
696 Err(f) => Err(f),
697 };
698 let value = envelope(result, started);
699 self.state.note(cmd, &value);
700 value
701 }
702
703 fn must_stop(&self) -> bool {
704 self.state.unknown.is_some()
705 }
706
707 fn cut_off(&mut self, cmd: &str) {
708 self.session.reset();
710 if INPUTS.contains(&cmd) {
711 self.state.inputs_sent += 1;
712 }
713 }
714}
715
716pub fn request(code: &str, args: &Map<String, Value>, saved: Option<(&str, &str)>) -> Value {
719 let mut req = json!({ "code": code, "args": args });
720 if let Some((name, source)) = saved {
721 req["script"] = json!(name);
722 req["source"] = json!(source);
723 }
724 req
725}
726
727impl Session {
728 fn last_seen(&self) -> Option<Value> {
730 let (_, dump, _) = self.ax.as_ref()?.latest()?;
731 Some(Screen::build(&dump, BuildOptions::default()).summary(12))
732 }
733
734 pub async fn cmd_script(&mut self, code: &str, args: &Map<String, Value>) -> Res {
735 let limits = Limits {
736 timeout: Duration::from_secs(self.config.script.timeout_secs.clamp(1, MAX_TIMEOUT_SECS)),
737 memory: (self.config.script.memory_mb.clamp(8, 1024) as usize) << 20,
738 };
739 let mut host = PhoneHost { session: self, state: RunState::default() };
740 let ended = run(&mut host, code, args, &limits).await;
741 let PhoneHost { session, state } = host;
742 finish(ended, &state).map_err(|mut f| {
743 if !f.extra.contains_key("screen_summary")
744 && let Some(seen) = session.last_seen()
745 {
746 f = f.with("screen_summary", seen);
747 }
748 f
749 })
750 }
751
752 pub async fn serve_script(&mut self, req: &Value) -> Res {
754 let code = req
755 .get("code")
756 .and_then(|v| v.as_str())
757 .ok_or_else(|| Fail::invalid("script needs `code`"))?;
758 let empty = Map::new();
759 let args = req.get("args").and_then(|v| v.as_object()).unwrap_or(&empty);
760 let saved: Vec<(&str, Value)> = ["script", "source"]
761 .into_iter()
762 .filter_map(|k| req.get(k).filter(|v| v.is_string()).map(|v| (k, v.clone())))
763 .collect();
764 match Box::pin(self.cmd_script(code, args)).await {
765 Ok(mut out) => {
766 out.extend(saved.into_iter().map(|(k, v)| (k.to_string(), v)));
767 Ok(out)
768 }
769 Err(f) => Err(saved.into_iter().fold(f, |f, (k, v)| f.with(k, v))),
770 }
771 }
772}
773
774#[cfg(test)]
775mod tests {
776 use super::*;
777
778 #[derive(Default)]
780 struct Fake {
781 state: RunState,
782 asked: Vec<(String, Value)>,
783 answers: std::collections::HashMap<String, Value>,
785 delay: Option<Duration>,
786 }
787
788 impl ScriptHost for Fake {
789 async fn call(&mut self, cmd: &str, args: Value) -> Value {
790 if let Some(d) = self.delay {
791 tokio::time::sleep(d).await;
792 }
793 let value = match self.state.prepare(cmd, args) {
794 Ok(p) => {
795 self.asked.push((cmd.to_string(), p.args));
796 self.answers
797 .get(cmd)
798 .cloned()
799 .unwrap_or_else(|| json!({"ok": true, "outcome": "done", "cmd": cmd}))
800 }
801 Err(f) => envelope(Err(f), Instant::now()),
802 };
803 self.state.note(cmd, &value);
804 value
805 }
806 fn must_stop(&self) -> bool {
807 self.state.unknown.is_some()
808 }
809 fn cut_off(&mut self, _cmd: &str) {
810 self.state.inputs_sent += 1;
811 }
812 }
813
814 fn limits() -> Limits {
815 Limits { timeout: Duration::from_secs(5), memory: 32 << 20 }
816 }
817
818 fn go(fake: &mut Fake, code: &str, args: Value, limits: Limits) -> (Res, Ended0) {
819 let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
820 let args = args.as_object().cloned().unwrap_or_default();
821 let ended = rt.block_on(run(fake, code, &args, &limits));
822 let kept = Ended0 { end: ended.end.clone(), calls: ended.calls };
823 (finish(ended, &fake.state), kept)
824 }
825
826 struct Ended0 {
827 end: End,
828 calls: u32,
829 }
830
831 #[test]
832 fn a_script_returns_outputs_and_reads_its_arguments() {
833 let mut fake = Fake::default();
834 let (res, _) = go(
835 &mut fake,
836 "output('seen', read().cmd);\nlog('hello', {n: 1});\nreturn { who: args.name, twice: Number(args.n) * 2 };",
837 json!({"name": "설정", "n": "21"}),
838 limits(),
839 );
840 let out = res.unwrap();
841 assert_eq!(out["outputs"], json!({"seen": "read", "who": "설정", "twice": 42}));
842 assert_eq!(out["logs"], json!(["hello {\"n\":1}"]));
843 assert_eq!(out["calls"], 1);
844 assert_eq!(out["inputs_sent"], 0);
845 let (res, _) = go(&mut Fake::default(), "return 7", json!({}), limits());
847 assert_eq!(res.unwrap()["outputs"], json!({"result": 7}));
848 }
849
850 #[test]
851 fn calls_take_the_same_arguments_as_the_commands() {
852 let mut fake = Fake::default();
853 let code = r#"
854 tap("일반");
855 tap({label: "정보", role: "button"}, {long_ms: 300});
856 scroll("down", {until: "개발자", max: 5});
857 swipe("up"); swipe({from: [1, 2], to: [3, 4]}, {drag: true});
858 type("안녕", {submit: true}); key("return"); button("home");
859 launch("com.apple.Preferences", {restart: true});
860 find("label~=일"); waitFor("일반", {timeout_ms: 100});
861 pinch("out"); pinch({scale: 1.5, rotate: -30, at: "지도"}, {duration_ms: 300});
862 "#;
863 let (res, _) = go(&mut fake, code, json!({}), limits());
864 res.unwrap();
865 let asked: Vec<(&str, &Value)> = fake.asked.iter().map(|(c, a)| (c.as_str(), a)).collect();
866 assert_eq!(asked[0], ("tap", &json!({"target": "일반"})));
867 assert_eq!(asked[1], ("tap", &json!({"long_ms": 300, "target": {"label": "정보", "role": "button"}})));
868 assert_eq!(asked[2], ("scroll", &json!({"until": "개발자", "max": 5, "direction": "down"})));
869 assert_eq!(asked[3], ("swipe", &json!({"direction": "up"})));
870 assert_eq!(asked[4], ("swipe", &json!({"drag": true, "from": [1, 2], "to": [3, 4]})));
871 assert_eq!(asked[5], ("type", &json!({"submit": true, "text": "안녕"})));
872 assert_eq!(asked[8], ("launch", &json!({"restart": true, "app": "com.apple.Preferences"})));
873 assert_eq!(asked[10], ("wait_for", &json!({"timeout_ms": 100, "selector": "일반"})));
874 assert_eq!(asked[11], ("pinch", &json!({"direction": "out"})));
875 assert_eq!(asked[12], ("pinch", &json!({"scale": 1.5, "rotate": -30, "at": "지도", "duration_ms": 300})));
876 assert_eq!(fake.state.inputs_sent, 11);
877 }
878
879 #[test]
880 fn launch_passes_arguments_and_environment_on() {
881 let mut fake = Fake::default();
882 let code = r#"launch("a.b", {arguments: ["-AppleLanguages", "(ko)"], environment: {TZ: "UTC"}});"#;
883 let (res, _) = go(&mut fake, code, json!({}), limits());
884 res.unwrap();
885 assert_eq!(
886 fake.asked[0],
887 ("launch".to_string(), json!({"arguments": ["-AppleLanguages", "(ko)"], "environment": {"TZ": "UTC"}, "app": "a.b"}))
888 );
889 }
890
891 #[test]
892 fn syslog_is_not_an_input_reads_with_a_cursor_and_cannot_write_a_file() {
893 let mut fake = Fake::default();
894 let code = r#"
895 syslog("start", {process: ["Preferences"], level: "info"});
896 tap("일반");
897 const page = syslog("read", {after: 0, grep: "row", max: 5});
898 tap("정보");
899 syslog("read", {after: page.cursor});
900 const done = syslog("stop", {grep: "row", max: 5});
901 let refused = null;
902 try { syslog("start", {output: "/tmp/elsewhere.jsonl"}); } catch (e) { refused = e.code; }
903 return { refused };
904 "#;
905 let (res, _) = go(&mut fake, code, json!({}), limits());
906 let out = res.unwrap();
907 let asked: Vec<(&str, &Value)> = fake.asked.iter().map(|(c, a)| (c.as_str(), a)).collect();
908 assert_eq!(asked[0], ("syslog", &json!({"process": ["Preferences"], "level": "info", "action": "start"})));
909 assert_eq!(asked[2], ("syslog", &json!({"after": 0, "grep": "row", "max": 5, "action": "read"})));
910 assert_eq!(asked[4].0, "syslog");
911 assert_eq!(asked[4].1["action"], "read");
912 assert_eq!(asked[5], ("syslog", &json!({"grep": "row", "max": 5, "action": "stop"})));
913 assert_eq!(asked.len(), 6, "the refused start never reached the phone");
914 assert_eq!(out["outputs"]["refused"], "invalid_argument");
915 assert_eq!(out["inputs_sent"], 2);
916 }
917
918 #[test]
919 fn a_script_may_pass_a_null_output() {
920 let mut run = RunState::default();
921 assert!(run.prepare("syslog", json!({"action": "start", "output": null})).is_ok());
922 assert!(run.prepare("syslog", json!({"action": "start", "output": "/tmp/x.jsonl"})).is_err());
923 }
924
925 #[test]
926 fn a_failed_call_throws_and_stops_the_script_unless_caught() {
927 let not_found = json!({"ok": false, "outcome": "not_sent",
928 "error": {"code": "not_found", "message": "no element matches", "hint": "scroll"},
929 "screen_summary": {"labels": ["a", "b"]}});
930 let mut fake = Fake::default();
931 fake.answers.insert("tap".into(), not_found.clone());
932 let (res, _) = go(&mut fake, "read();\ntap('없는 것');\nread();", json!({}), limits());
933 let f = res.unwrap_err();
934 assert_eq!((f.code.as_str(), f.outcome), ("script_failed", Outcome::NotSent));
935 assert_eq!(f.extra["reason"]["code"], "not_found");
936 assert_eq!(f.extra["failed_call"], json!({"cmd": "tap", "line": 2, "outcome": "not_sent"}));
937 assert_eq!(f.extra["screen_summary"]["labels"], json!(["a", "b"]));
938 assert_eq!(f.hint.as_deref(), Some("scroll"));
939 assert_eq!(fake.asked.len(), 2, "nothing runs after the failure");
940
941 let mut fake = Fake::default();
943 fake.answers.insert("tap".into(), not_found);
944 let code = "try { tap('x') } catch (e) { output('code', e.code); output('outcome', e.outcome) }\nreturn { after: read().ok }";
945 let (res, _) = go(&mut fake, code, json!({}), limits());
946 assert_eq!(res.unwrap()["outputs"], json!({"code": "not_found", "outcome": "not_sent", "after": true}));
947 }
948
949 #[test]
950 fn a_pinch_counts_as_input_so_a_later_failure_is_unknown() {
951 let not_found = json!({"ok": false, "outcome": "not_sent", "error": {"code": "not_found", "message": "no element matches"}});
952 let mut fake = Fake::default();
953 fake.answers.insert("tap".into(), not_found);
954 let (res, _) = go(&mut fake, "pinch('out');\ntap('no such label');", json!({}), limits());
955 let f = res.unwrap_err();
956 assert_eq!((f.code.as_str(), f.outcome), ("script_failed", Outcome::Unknown));
957 assert_eq!(f.extra["inputs_sent"], 1);
958 assert!(NEEDS_APP.contains(&"pinch"));
959 }
960
961 #[test]
962 fn a_script_that_throws_reports_its_line() {
963 let mut fake = Fake::default();
964 let (res, _) = go(&mut fake, "tap('a');\n\nthrow new Error('기대한 화면이 아닙니다');", json!({}), limits());
965 let f = res.unwrap_err();
966 assert_eq!(f.code, "script_error");
967 assert_eq!(f.message, "기대한 화면이 아닙니다");
968 assert_eq!(f.extra["line"], 3);
969 assert_eq!(f.outcome, Outcome::Unknown);
971 assert_eq!(f.extra["inputs_sent"], 1);
972 let (res, kept) = go(&mut Fake::default(), "tap('a'", json!({}), limits());
974 let f = res.unwrap_err();
975 assert_eq!((f.code.as_str(), f.outcome, kept.calls), ("script_error", Outcome::NotSent, 0));
976 assert_eq!(f.extra["line"], 1);
977 }
978
979 #[test]
980 fn nothing_follows_a_call_with_an_unknown_outcome() {
981 let mut fake = Fake::default();
982 fake.answers.insert(
983 "tap".into(),
984 json!({"ok": false, "outcome": "unknown", "error": {"code": "input_failed", "message": "write failed"}}),
985 );
986 let code = "for (let i = 0; i < 5; i++) { try { tap('보내기 아님') } catch (e) {} }\nreturn 'went on'";
988 let (res, kept) = go(&mut fake, code, json!({}), limits());
989 let f = res.unwrap_err();
990 assert_eq!(f.outcome, Outcome::Unknown);
991 assert_eq!(f.extra["reason"]["code"], "input_failed");
992 assert_eq!(fake.asked.len(), 1, "the tap is not sent a second time");
993 assert_eq!(kept.end, End::Stopped("unknown_outcome"));
994 }
995
996 #[test]
997 fn type_observations_reach_scripts_and_a_withheld_submit_stops_them() {
998 let mut fake = Fake::default();
999 let observation = json!({
1000 "ok": true, "outcome": "done", "sent": true, "verified": true,
1001 "value_before": "", "value": "", "value_changed": false,
1002 "screen_changed": false, "submit_sent": false,
1003 "warning": {"code": "value_unchanged", "message": "unchanged"},
1004 });
1005 fake.answers.insert("type".into(), observation.clone());
1006 let (res, _) = go(&mut fake, "return type('hello')", json!({}), limits());
1007 assert_eq!(res.unwrap()["outputs"], observation);
1008
1009 let mut fake = Fake::default();
1010 let mut blocked = observation;
1011 blocked["ok"] = json!(false);
1012 blocked["outcome"] = json!("unknown");
1013 blocked["error"] = json!({"code": "type_not_verified", "message": "Return was not sent"});
1014 fake.answers.insert("type".into(), blocked);
1015 let (res, kept) = go(
1016 &mut fake,
1017 "try { type('hello', {submit: true}) } catch (e) {}\nkey('return'); type('hello');",
1018 json!({}),
1019 limits(),
1020 );
1021 let fail = res.unwrap_err();
1022 assert_eq!(fail.outcome, Outcome::Unknown);
1023 assert_eq!(fail.extra["reason"]["code"], "type_not_verified");
1024 assert_eq!(fail.extra["warning"]["code"], "value_unchanged");
1025 assert_eq!(
1026 fake.asked.len(),
1027 1,
1028 "neither Return nor a duplicate paste reaches the phone"
1029 );
1030 assert_eq!(kept.end, End::Stopped("unknown_outcome"));
1031 }
1032
1033 #[test]
1034 fn a_script_that_never_ends_is_stopped() {
1035 let short = || Limits { timeout: Duration::from_millis(300), memory: 32 << 20 };
1036 let began = Instant::now();
1037 let (res, _) = go(&mut Fake::default(), "while (true) {}", json!({}), short());
1038 let f = res.unwrap_err();
1039 assert_eq!((f.code.as_str(), f.outcome), ("script_timeout", Outcome::NotSent));
1040 assert!(began.elapsed() < Duration::from_secs(5));
1041 let (res, _) = go(&mut Fake::default(), "tap('a'); while (true) {}", json!({}), short());
1043 assert_eq!(res.unwrap_err().outcome, Outcome::Unknown);
1044 let (res, _) = go(&mut Fake::default(), "sleep(60000)", json!({}), short());
1046 assert_eq!(res.unwrap_err().code, "script_timeout");
1047 let mut slow = Fake { delay: Some(Duration::from_secs(30)), ..Default::default() };
1048 let (res, _) = go(&mut slow, "tap('a')", json!({}), short());
1049 let f = res.unwrap_err();
1050 assert_eq!((f.code.as_str(), f.outcome), ("script_timeout", Outcome::Unknown));
1051 }
1052
1053 #[test]
1054 fn a_script_that_eats_memory_is_stopped() {
1055 let small = Limits { timeout: Duration::from_secs(20), memory: 8 << 20 };
1056 let code = "const all = []; while (true) { all.push(new Array(100000).fill('x'.repeat(20))) }";
1057 let (res, _) = go(&mut Fake::default(), code, json!({}), small);
1058 let f = res.unwrap_err();
1059 assert_eq!(f.code, "script_error");
1060 assert!(f.message.contains("memory"), "{}", f.message);
1061 }
1062
1063 #[test]
1064 fn a_script_has_no_way_out_of_the_engine() {
1065 let code = r#"
1066 const names = ["require", "process", "fetch", "XMLHttpRequest", "std", "os", "Deno", "Bun",
1067 "WebSocket", "setTimeout", "importScripts", "Worker"];
1068 return { there: names.filter((n) => typeof globalThis[n] !== "undefined") };
1069 "#;
1070 let (res, _) = go(&mut Fake::default(), code, json!({}), limits());
1071 assert_eq!(res.unwrap()["outputs"]["there"], json!([]));
1072 let (res, _) = go(&mut Fake::default(), "import fs from 'fs'", json!({}), limits());
1074 assert_eq!(res.unwrap_err().code, "script_error");
1075 let (res, _) = go(
1076 &mut Fake::default(),
1077 "let got = 'nothing'; import('std').then(() => { got = 'loaded' }, () => { got = 'refused' }); return got",
1078 json!({}),
1079 limits(),
1080 );
1081 assert_ne!(res.map(|o| o["outputs"]["result"].clone()).unwrap_or(json!("refused")), json!("loaded"));
1082 }
1083
1084 #[test]
1085 fn the_line_comes_from_the_scripts_own_frame() {
1086 let stack = " at call (iph:9:15)\n at <anonymous> (iph:23:20)\n at <anonymous> (script:4:5)\n at <anonymous> (script:1:1)\n";
1087 assert_eq!(script_line(Some(stack)), Some(3));
1088 assert_eq!(script_line(Some(" at script:2:9\n")), Some(1));
1089 assert_eq!(script_line(Some(" at f (eval_script:7:1)\n")), None);
1090 assert_eq!(script_line(None), None);
1091 }
1092
1093 #[test]
1094 fn a_hint_on_a_call_is_what_the_person_is_told() {
1095 let mut state = RunState::default();
1096 let p = state.prepare("wait_for", json!({"selector": "홈", "hint": "폰을 봐 주세요"})).unwrap();
1097 assert_eq!(p.hint.as_deref(), Some("폰을 봐 주세요"));
1098 assert_eq!(p.args, json!({"selector": "홈"}));
1099 }
1100
1101 #[test]
1102 fn saved_scripts_are_listed_with_their_first_comment() {
1103 assert_eq!(description("// 설정에서 iOS 버전 읽기\nlaunch('x')"), "설정에서 iOS 버전 읽기");
1104 assert_eq!(description("\n\n // spaced \ncode"), "spaced");
1105 assert_eq!(description("launch('x')"), "");
1106 for (name, code) in BUILTIN {
1107 assert!(!description(code).is_empty(), "{name} has no description");
1108 }
1109 }
1110}