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.scroll = (direction, o) => call("scroll", { ...opts(o), direction });
139 g.type = (value, o) => call("type", { ...opts(o), text: String(value) });
140 g.key = (name, o) => call("key", { ...opts(o), key: name });
141 g.button = (name, o) => call("button", { ...opts(o), button: name });
142 g.launch = (app, o) => call("launch", { ...opts(o), app });
143 g.apps = () => call("apps", {});
144 g.waitFor = (selector, o) => call("wait_for", { ...opts(o), selector });
145 g.readField = (spec) => call("read_field", opts(spec)).value;
146 g.readList = (spec) => call("read_list", opts(spec));
147 g.sleep = (ms) => { __sleep(Number(ms) || 0); };
148 g.log = (...xs) => { __emit("log", "", xs.map(text).join(" ")); };
149 g.output = (key, value) => { __emit("output", String(key), JSON.stringify(value === undefined ? null : value)); };
150 g.console = { log: g.log, info: g.log, warn: g.log, error: g.log };
151 g.__done = (value) => JSON.stringify({ ok: true, value });
152 g.__threw = (e) => {
153 const error = {
154 name: e && e.name,
155 message: e && e.message !== undefined ? String(e.message) : String(e),
156 stack: e && e.stack ? String(e.stack) : undefined,
157 };
158 if (e && e.result) {
159 error.cmd = e.cmd;
160 error.result = e.result;
161 }
162 return JSON.stringify({ ok: false, error });
163 };
164})();
165"#;
166
167const SCRIPT_FILE: &str = "script";
169
170const STOPPED: &str =
172 r#"{"ok":false,"outcome":"not_sent","error":{"code":"script_stopped","message":"the script was stopped"}}"#;
173
174const MAX_LOGS: usize = 200;
176const MAX_LOG_LINE: usize = 2000;
177
178pub const MAX_TIMEOUT_SECS: u64 = 840;
181
182pub struct Limits {
183 pub timeout: Duration,
184 pub memory: usize,
186}
187
188#[allow(async_fn_in_trait)]
190pub trait ScriptHost {
191 async fn call(&mut self, cmd: &str, args: Value) -> Value;
193 fn must_stop(&self) -> bool;
195 fn cut_off(&mut self, cmd: &str);
197}
198
199#[derive(Debug, Clone, PartialEq)]
200pub enum End {
201 Returned(Option<Value>),
203 Threw(Value),
206 Stopped(&'static str),
209 Engine(String),
211}
212
213#[derive(Debug)]
214pub struct Ended {
215 pub end: End,
216 pub outputs: Map<String, Value>,
217 pub logs: Vec<String>,
218 pub calls: u32,
219 pub lines: u64,
221}
222
223struct Call {
224 cmd: String,
225 args: String,
226 reply: std::sync::mpsc::Sender<String>,
227}
228
229#[derive(Default)]
230struct Shared {
231 stop: AtomicBool,
233 outputs: Mutex<Map<String, Value>>,
234 logs: Mutex<Vec<String>>,
235}
236
237fn js_main(
239 code: &str,
240 args: &Value,
241 memory: usize,
242 shared: &Arc<Shared>,
243 calls: tokio::sync::mpsc::UnboundedSender<Call>,
244) -> End {
245 let runtime = match Runtime::new() {
246 Ok(r) => r,
247 Err(e) => return End::Engine(format!("cannot start the engine: {e}")),
248 };
249 runtime.set_memory_limit(memory);
250 runtime.set_max_stack_size(1 << 20);
251 let flag = shared.clone();
252 runtime.set_interrupt_handler(Some(Box::new(move || flag.stop.load(Ordering::Relaxed))));
253 let context = match Context::full(&runtime) {
256 Ok(c) => c,
257 Err(e) => return End::Engine(format!("cannot start the engine: {e}")),
258 };
259 context.with(|ctx| {
260 let ran = (|| -> rquickjs::Result<String> {
261 let globals = ctx.globals();
262 let (stop, door) = (shared.clone(), calls.clone());
263 globals.set(
264 "__iph",
265 Function::new(ctx.clone(), move |cmd: String, args: String| -> String {
266 if stop.stop.load(Ordering::Relaxed) {
267 return STOPPED.to_string();
268 }
269 let (reply, answer) = std::sync::mpsc::channel();
270 if door.send(Call { cmd, args, reply }).is_err() {
271 return STOPPED.to_string();
272 }
273 answer.recv().unwrap_or_else(|_| STOPPED.to_string())
274 })?,
275 )?;
276 let stop = shared.clone();
277 globals.set(
278 "__sleep",
279 Function::new(ctx.clone(), move |ms: f64| {
280 let until = Instant::now() + Duration::from_millis(ms.clamp(0.0, 600_000.0) as u64);
281 while !stop.stop.load(Ordering::Relaxed) {
282 let left = until.saturating_duration_since(Instant::now());
283 if left.is_zero() {
284 break;
285 }
286 std::thread::sleep(left.min(Duration::from_millis(20)));
287 }
288 })?,
289 )?;
290 let kept = shared.clone();
291 globals.set(
292 "__emit",
293 Function::new(ctx.clone(), move |kind: String, key: String, body: String| {
294 if kind == "output" {
295 let value = serde_json::from_str(&body).unwrap_or(Value::Null);
296 kept.outputs.lock().unwrap().insert(key, value);
297 } else {
298 let mut logs = kept.logs.lock().unwrap();
299 if logs.len() < MAX_LOGS {
300 logs.push(body.chars().take(MAX_LOG_LINE).collect());
301 }
302 }
303 })?,
304 )?;
305 let named = |name: &str| {
307 let mut options = EvalOptions::default();
308 options.filename = Some(name.into());
309 options
310 };
311 ctx.eval_with_options::<(), _>(PRELUDE, named("iph"))?;
312 let run: Function = ctx.eval_with_options(
315 format!(
316 "(function(args){{try{{return __done((function(args){{\"use strict\";\n{code}\n}})(args))}}catch(e){{return __threw(e)}}}})"
317 ),
318 named(SCRIPT_FILE),
319 )?;
320 let args = ctx.json_parse(args.to_string())?;
321 run.call((args,))
322 })();
323 match ran {
324 Ok(text) => match serde_json::from_str::<Value>(&text) {
325 Ok(v) if v["ok"] == true => End::Returned(v.get("value").cloned().filter(|x| !x.is_null())),
326 Ok(v) => End::Threw(v["error"].clone()),
327 Err(e) => End::Engine(format!("the script's result is not JSON: {e}")),
328 },
329 Err(_) if shared.stop.load(Ordering::Relaxed) => End::Stopped("timeout"),
330 Err(e) => End::Threw(match CaughtError::from_error(&ctx, e) {
333 CaughtError::Exception(ex) => json!({
334 "name": "Error",
335 "message": ex.message().unwrap_or_else(|| "the script could not run".into()),
336 "stack": ex.stack(),
337 }),
338 other => json!({ "name": "Error", "message": other.to_string() }),
339 }),
340 }
341 })
342}
343
344pub async fn run<H: ScriptHost>(host: &mut H, code: &str, args: &Map<String, Value>, limits: &Limits) -> Ended {
346 let shared = Arc::new(Shared::default());
347 let lines = code.lines().count().max(1) as u64;
348 let (door, mut calls_in) = tokio::sync::mpsc::unbounded_channel::<Call>();
349 let (done, finished) = tokio::sync::oneshot::channel::<End>();
350 let (thread_shared, code_owned, args_owned, memory) =
351 (shared.clone(), code.to_string(), Value::Object(args.clone()), limits.memory);
352 let spawned = std::thread::Builder::new()
353 .name("iph-script".into())
354 .stack_size(8 << 20)
355 .spawn(move || {
356 let end = js_main(&code_owned, &args_owned, memory, &thread_shared, door);
357 let _ = done.send(end);
358 });
359 if let Err(e) = spawned {
360 return Ended {
361 end: End::Engine(format!("cannot start the script: {e}")),
362 outputs: Map::new(),
363 logs: Vec::new(),
364 calls: 0,
365 lines,
366 };
367 }
368
369 let deadline = tokio::time::Instant::now() + limits.timeout;
370 let mut calls = 0u32;
371 let mut stopped: Option<&'static str> = None;
372 loop {
373 let next = tokio::select! {
374 call = calls_in.recv() => call,
375 _ = tokio::time::sleep_until(deadline) => {
376 stopped = Some("timeout");
377 None
378 }
379 };
380 let Some(call) = next else { break };
382 calls += 1;
383 let args = serde_json::from_str(&call.args).unwrap_or_else(|_| json!({}));
384 let reply = match tokio::time::timeout_at(deadline, host.call(&call.cmd, args)).await {
385 Ok(result) => result.to_string(),
386 Err(_) => {
387 host.cut_off(&call.cmd);
388 stopped = Some("timeout");
389 STOPPED.to_string()
390 }
391 };
392 if stopped.is_none() && host.must_stop() {
393 stopped = Some("unknown_outcome");
394 }
395 if stopped.is_some() {
396 shared.stop.store(true, Ordering::Relaxed);
398 }
399 let _ = call.reply.send(reply);
400 if stopped.is_some() {
401 break;
402 }
403 }
404 if stopped.is_some() {
405 shared.stop.store(true, Ordering::Relaxed);
406 }
407 drop(calls_in);
409 let end = match tokio::time::timeout(Duration::from_secs(10), finished).await {
410 Ok(Ok(end)) => end,
411 Ok(Err(_)) => End::Engine("the script engine stopped unexpectedly".into()),
412 Err(_) => End::Engine("the script did not stop".into()),
413 };
414 let end = match stopped {
415 Some(why) => End::Stopped(why),
416 None => end,
417 };
418 Ended {
419 end,
420 outputs: std::mem::take(&mut *shared.outputs.lock().unwrap()),
421 logs: std::mem::take(&mut *shared.logs.lock().unwrap()),
422 calls,
423 lines,
424 }
425}
426
427const INPUTS: [&str; 8] = ["launch", "tap", "swipe", "scroll", "type", "key", "button", "read_list"];
433const MANY_INPUTS: [&str; 2] = ["scroll", "read_list"];
435const NEEDS_APP: [&str; 8] = ["tap", "swipe", "scroll", "type", "key", "button", "read_field", "read_list"];
437
438#[derive(Debug)]
440pub struct Prepared {
441 pub args: Value,
442 pub hint: Option<String>,
443}
444
445#[derive(Debug, Default)]
446pub struct RunState {
447 pub inputs_sent: u32,
449 pub expected_pid: Option<i64>,
451 pub unknown: Option<(String, Value)>,
453}
454
455impl RunState {
456 pub fn prepare(&mut self, cmd: &str, args: Value) -> Res<Prepared> {
458 let Value::Object(mut map) = args else {
459 return Err(Fail::invalid(format!("`{cmd}` takes an object of arguments")));
460 };
461 let hint = map.remove("hint").and_then(|v| v.as_str().map(String::from));
462 Ok(Prepared { args: Value::Object(map), hint })
463 }
464
465 pub fn note(&mut self, cmd: &str, result: &Value) {
467 let outcome = result["outcome"].as_str().unwrap_or("");
468 let sent = result["ok"] == true
469 || outcome == "unknown"
470 || outcome == "done"
471 || (MANY_INPUTS.contains(&cmd) && result["error"]["code"] != "invalid_argument");
473 if INPUTS.contains(&cmd) && sent {
474 self.inputs_sent += 1;
475 }
476 if outcome == "unknown" {
477 self.unknown = Some((cmd.to_string(), result.clone()));
478 }
479 }
480}
481
482fn script_line(stack: Option<&str>) -> Option<u64> {
485 let stack = stack?;
486 let mark = format!("{SCRIPT_FILE}:");
487 let mut from = 0;
488 while let Some(found) = stack[from..].find(&mark) {
489 let at = from + found;
490 from = at + mark.len();
491 if at > 0 && !matches!(stack.as_bytes()[at - 1], b'(' | b' ') {
493 continue;
494 }
495 let digits: String = stack[from..].chars().take_while(|c| c.is_ascii_digit()).collect();
496 if let Ok(n) = digits.parse::<u64>() {
497 return Some(n.saturating_sub(1)).filter(|n| *n > 0);
498 }
499 }
500 None
501}
502
503pub fn finish(ended: Ended, state: &RunState) -> Res {
505 let Ended { end, mut outputs, logs, calls, lines } = ended;
506 let sent = state.inputs_sent;
507 let outcome_of = |call: Option<&Value>| match call.and_then(|c| c["outcome"].as_str()) {
511 Some("unknown") => Outcome::Unknown,
512 _ if sent > 0 => Outcome::Unknown,
513 _ => Outcome::NotSent,
514 };
515 let failed_call = |result: &Value, cmd: &str, line: Option<u64>| -> Fail {
516 let reason = &result["error"];
517 let mut f = Fail::new(
518 outcome_of(Some(result)),
519 "script_failed",
520 format!("`{cmd}` failed: {}", reason["message"].as_str().unwrap_or("")),
521 );
522 f.hint = reason["hint"].as_str().map(String::from);
523 f = f
524 .with("failed_call", json!({ "cmd": cmd, "line": line, "outcome": result["outcome"] }))
525 .with("reason", json!({ "code": reason["code"], "message": reason["message"] }));
526 if let Some(extra) = result.as_object() {
528 for (k, v) in extra {
529 if !matches!(k.as_str(), "ok" | "outcome" | "error" | "elapsed_ms") {
530 f.extra.entry(k.clone()).or_insert(v.clone());
531 }
532 }
533 }
534 f
535 };
536
537 let fail = match end {
538 End::Returned(value) => {
539 match value {
540 Some(Value::Object(returned)) => outputs.extend(returned),
541 Some(other) => {
542 outputs.insert("result".into(), other);
543 }
544 None => {}
545 }
546 return Ok(fields! { "outputs": outputs, "logs": logs, "calls": calls, "inputs_sent": sent });
547 }
548 End::Threw(error) => {
549 let line = script_line(error["stack"].as_str()).map(|n| n.min(lines));
551 match (error.get("result"), error["cmd"].as_str()) {
552 (Some(result), Some(cmd)) if result.is_object() => failed_call(result, cmd, line),
553 _ => Fail::new(
554 outcome_of(None),
555 "script_error",
556 error["message"].as_str().unwrap_or("the script threw").to_string(),
557 )
558 .with("line", json!(line)),
559 }
560 }
561 End::Stopped("unknown_outcome") => match &state.unknown {
562 Some((cmd, result)) => failed_call(result, cmd, None),
563 None => Fail::unknown("script_stopped", "the script was stopped"),
564 },
565 End::Stopped(_) => Fail::new(
566 outcome_of(None),
567 "script_timeout",
568 "the script ran longer than it is allowed to",
569 )
570 .hint(t(
571 "config.toml의 [script] timeout_secs로 한도를 바꿀 수 있습니다. 입력을 보낸 뒤였다면 `iph read`로 화면부터 확인하세요.",
572 "[script] timeout_secs in config.toml changes the limit. If input had gone out, check the screen with `iph read` first.",
573 )),
574 End::Engine(message) => Fail::new(outcome_of(None), "script_error", message),
575 };
576 let fail = if sent > 0 && fail.hint.is_none() {
577 fail.hint(t(
578 "스크립트가 입력을 보낸 뒤에 멈췄습니다. 다시 실행하기 전에 `iph read`로 화면을 확인하세요.",
579 "The script stopped after it had sent input. Check the screen with `iph read` before running it again.",
580 ))
581 } else {
582 fail
583 };
584 Err(fail
585 .with("outputs", json!(outputs))
586 .with("logs", json!(logs))
587 .with("calls", calls)
588 .with("inputs_sent", sent))
589}
590
591struct PhoneHost<'a> {
596 session: &'a mut Session,
597 state: RunState,
598}
599
600impl PhoneHost<'_> {
601 async fn tap(&mut self, args: Value) -> Res {
602 let s = &mut *self.session;
603 let Value::Object(mut map) = args else {
604 return Err(Fail::invalid("tap takes a target"));
605 };
606 let wait = map.remove("timeout_ms").and_then(|v| v.as_u64()).unwrap_or(5000);
609 let settle = map.remove("settle").and_then(|v| v.as_bool()).unwrap_or(true);
610 let target = map.get("target").cloned().unwrap_or(Value::Null);
611 if let Some(list) = target.as_array() {
612 return Box::pin(s.tap_sequence(list)).await;
613 }
614 if let Target::Selector(sel) = parse_target(&target)? {
615 if wait > 0 {
616 Box::pin(s.wait_for(&sel, Duration::from_millis(wait))).await?;
617 }
618 if settle {
619 Box::pin(s.settle_target(&sel)).await?;
620 }
621 }
622 let tap: TapArgs = parse_args(&Value::Object(map))?;
623 Box::pin(s.cmd_tap(tap)).await
624 }
625
626 async fn dispatch(&mut self, cmd: &str, args: Value) -> Res {
627 if NEEDS_APP.contains(&cmd)
628 && let Some(f) = self.session.unexpected_app(self.state.expected_pid)
629 {
630 return Err(f);
631 }
632 match cmd {
633 "read" => Box::pin(self.session.cmd_read(parse_args(&args)?)).await,
634 "find" => Box::pin(self.session.cmd_find(parse_args(&args)?)).await,
635 "apps" => self.session.cmd_apps().await,
636 "launch" => {
637 let r = Box::pin(self.session.cmd_launch(parse_args(&args)?)).await?;
638 if r.get("foreground").and_then(|v| v.as_bool()) != Some(true) {
639 return Err(Fail::unknown("launch_not_verified", "the app was launched but is not in front"));
640 }
641 self.state.expected_pid = r.get("pid").and_then(|v| v.as_i64());
642 Ok(r)
643 }
644 "tap" => self.tap(args).await,
645 "swipe" | "scroll" | "type" | "key" | "button" | "read_list" => {
646 let s = &mut *self.session;
647 match cmd {
648 "swipe" => Box::pin(s.cmd_swipe(parse_args(&args)?)).await,
649 "scroll" => Box::pin(s.cmd_scroll(parse_args(&args)?)).await,
650 "type" => Box::pin(s.cmd_type(parse_args(&args)?)).await,
651 "key" => Box::pin(s.cmd_key(parse_args(&args)?)).await,
652 "button" => Box::pin(s.cmd_button(parse_args(&args)?)).await,
653 _ => Box::pin(s.read_list(&args)).await.map(|(_, rows, info)| {
654 let count = rows.as_array().map(|a| a.len()).unwrap_or(0);
655 fields! { "rows": rows, "count": count, "scrolls": info["scrolls"], "ended": info["ended"] }
656 }),
657 }
658 }
659 "wait_for" => {
660 let selector = args.get("selector").cloned().unwrap_or(Value::Null);
661 let sel = Selector::from_value(&selector).map_err(|e| Fail::invalid(e.to_string()))?;
662 let timeout = args.get("timeout_ms").and_then(|v| v.as_u64()).unwrap_or(8000);
663 let el = Box::pin(self.session.wait_for(&sel, Duration::from_millis(timeout))).await?;
664 Ok(fields! { "element": brief(&el) })
665 }
666 "read_field" => {
667 let (_, value) = Box::pin(self.session.read_field(&args)).await?;
668 Ok(fields! { "value": value })
669 }
670 other => Err(Fail::invalid(format!(
671 "a script has no `{other}` (read, find, tap, swipe, scroll, type, key, button, launch, apps, waitFor, readField, readList)"
672 ))),
673 }
674 }
675}
676
677impl ScriptHost for PhoneHost<'_> {
678 async fn call(&mut self, cmd: &str, args: Value) -> Value {
679 let started = Instant::now();
680 let result = match self.state.prepare(cmd, args) {
681 Ok(Prepared { args, hint }) => {
682 Box::pin(self.dispatch(cmd, args)).await.map_err(|mut f| {
683 if let Some(hint) = hint {
685 f.hint = Some(hint);
686 }
687 f
688 })
689 }
690 Err(f) => Err(f),
691 };
692 let value = envelope(result, started);
693 self.state.note(cmd, &value);
694 value
695 }
696
697 fn must_stop(&self) -> bool {
698 self.state.unknown.is_some()
699 }
700
701 fn cut_off(&mut self, cmd: &str) {
702 self.session.reset();
704 if INPUTS.contains(&cmd) {
705 self.state.inputs_sent += 1;
706 }
707 }
708}
709
710pub fn request(code: &str, args: &Map<String, Value>, saved: Option<(&str, &str)>) -> Value {
713 let mut req = json!({ "code": code, "args": args });
714 if let Some((name, source)) = saved {
715 req["script"] = json!(name);
716 req["source"] = json!(source);
717 }
718 req
719}
720
721impl Session {
722 fn last_seen(&self) -> Option<Value> {
724 let (_, dump, _) = self.ax.as_ref()?.latest()?;
725 Some(Screen::build(&dump, BuildOptions::default()).summary(12))
726 }
727
728 pub async fn cmd_script(&mut self, code: &str, args: &Map<String, Value>) -> Res {
729 let limits = Limits {
730 timeout: Duration::from_secs(self.config.script.timeout_secs.clamp(1, MAX_TIMEOUT_SECS)),
731 memory: (self.config.script.memory_mb.clamp(8, 1024) as usize) << 20,
732 };
733 let mut host = PhoneHost { session: self, state: RunState::default() };
734 let ended = run(&mut host, code, args, &limits).await;
735 let PhoneHost { session, state } = host;
736 finish(ended, &state).map_err(|mut f| {
737 if !f.extra.contains_key("screen_summary")
738 && let Some(seen) = session.last_seen()
739 {
740 f = f.with("screen_summary", seen);
741 }
742 f
743 })
744 }
745
746 pub async fn serve_script(&mut self, req: &Value) -> Res {
748 let code = req
749 .get("code")
750 .and_then(|v| v.as_str())
751 .ok_or_else(|| Fail::invalid("script needs `code`"))?;
752 let empty = Map::new();
753 let args = req.get("args").and_then(|v| v.as_object()).unwrap_or(&empty);
754 let saved: Vec<(&str, Value)> = ["script", "source"]
755 .into_iter()
756 .filter_map(|k| req.get(k).filter(|v| v.is_string()).map(|v| (k, v.clone())))
757 .collect();
758 match Box::pin(self.cmd_script(code, args)).await {
759 Ok(mut out) => {
760 out.extend(saved.into_iter().map(|(k, v)| (k.to_string(), v)));
761 Ok(out)
762 }
763 Err(f) => Err(saved.into_iter().fold(f, |f, (k, v)| f.with(k, v))),
764 }
765 }
766}
767
768#[cfg(test)]
769mod tests {
770 use super::*;
771
772 #[derive(Default)]
774 struct Fake {
775 state: RunState,
776 asked: Vec<(String, Value)>,
777 answers: std::collections::HashMap<String, Value>,
779 delay: Option<Duration>,
780 }
781
782 impl ScriptHost for Fake {
783 async fn call(&mut self, cmd: &str, args: Value) -> Value {
784 if let Some(d) = self.delay {
785 tokio::time::sleep(d).await;
786 }
787 let value = match self.state.prepare(cmd, args) {
788 Ok(p) => {
789 self.asked.push((cmd.to_string(), p.args));
790 self.answers
791 .get(cmd)
792 .cloned()
793 .unwrap_or_else(|| json!({"ok": true, "outcome": "done", "cmd": cmd}))
794 }
795 Err(f) => envelope(Err(f), Instant::now()),
796 };
797 self.state.note(cmd, &value);
798 value
799 }
800 fn must_stop(&self) -> bool {
801 self.state.unknown.is_some()
802 }
803 fn cut_off(&mut self, _cmd: &str) {
804 self.state.inputs_sent += 1;
805 }
806 }
807
808 fn limits() -> Limits {
809 Limits { timeout: Duration::from_secs(5), memory: 32 << 20 }
810 }
811
812 fn go(fake: &mut Fake, code: &str, args: Value, limits: Limits) -> (Res, Ended0) {
813 let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
814 let args = args.as_object().cloned().unwrap_or_default();
815 let ended = rt.block_on(run(fake, code, &args, &limits));
816 let kept = Ended0 { end: ended.end.clone(), calls: ended.calls };
817 (finish(ended, &fake.state), kept)
818 }
819
820 struct Ended0 {
821 end: End,
822 calls: u32,
823 }
824
825 #[test]
826 fn a_script_returns_outputs_and_reads_its_arguments() {
827 let mut fake = Fake::default();
828 let (res, _) = go(
829 &mut fake,
830 "output('seen', read().cmd);\nlog('hello', {n: 1});\nreturn { who: args.name, twice: Number(args.n) * 2 };",
831 json!({"name": "설정", "n": "21"}),
832 limits(),
833 );
834 let out = res.unwrap();
835 assert_eq!(out["outputs"], json!({"seen": "read", "who": "설정", "twice": 42}));
836 assert_eq!(out["logs"], json!(["hello {\"n\":1}"]));
837 assert_eq!(out["calls"], 1);
838 assert_eq!(out["inputs_sent"], 0);
839 let (res, _) = go(&mut Fake::default(), "return 7", json!({}), limits());
841 assert_eq!(res.unwrap()["outputs"], json!({"result": 7}));
842 }
843
844 #[test]
845 fn calls_take_the_same_arguments_as_the_commands() {
846 let mut fake = Fake::default();
847 let code = r#"
848 tap("일반");
849 tap({label: "정보", role: "button"}, {long_ms: 300});
850 scroll("down", {until: "개발자", max: 5});
851 swipe("up"); swipe({from: [1, 2], to: [3, 4]}, {drag: true});
852 type("안녕", {submit: true}); key("return"); button("home");
853 launch("com.apple.Preferences", {restart: true});
854 find("label~=일"); waitFor("일반", {timeout_ms: 100});
855 "#;
856 let (res, _) = go(&mut fake, code, json!({}), limits());
857 res.unwrap();
858 let asked: Vec<(&str, &Value)> = fake.asked.iter().map(|(c, a)| (c.as_str(), a)).collect();
859 assert_eq!(asked[0], ("tap", &json!({"target": "일반"})));
860 assert_eq!(asked[1], ("tap", &json!({"long_ms": 300, "target": {"label": "정보", "role": "button"}})));
861 assert_eq!(asked[2], ("scroll", &json!({"until": "개발자", "max": 5, "direction": "down"})));
862 assert_eq!(asked[3], ("swipe", &json!({"direction": "up"})));
863 assert_eq!(asked[4], ("swipe", &json!({"drag": true, "from": [1, 2], "to": [3, 4]})));
864 assert_eq!(asked[5], ("type", &json!({"submit": true, "text": "안녕"})));
865 assert_eq!(asked[8], ("launch", &json!({"restart": true, "app": "com.apple.Preferences"})));
866 assert_eq!(asked[10], ("wait_for", &json!({"timeout_ms": 100, "selector": "일반"})));
867 assert_eq!(fake.state.inputs_sent, 9);
868 }
869
870 #[test]
871 fn a_failed_call_throws_and_stops_the_script_unless_caught() {
872 let not_found = json!({"ok": false, "outcome": "not_sent",
873 "error": {"code": "not_found", "message": "no element matches", "hint": "scroll"},
874 "screen_summary": {"labels": ["a", "b"]}});
875 let mut fake = Fake::default();
876 fake.answers.insert("tap".into(), not_found.clone());
877 let (res, _) = go(&mut fake, "read();\ntap('없는 것');\nread();", json!({}), limits());
878 let f = res.unwrap_err();
879 assert_eq!((f.code.as_str(), f.outcome), ("script_failed", Outcome::NotSent));
880 assert_eq!(f.extra["reason"]["code"], "not_found");
881 assert_eq!(f.extra["failed_call"], json!({"cmd": "tap", "line": 2, "outcome": "not_sent"}));
882 assert_eq!(f.extra["screen_summary"]["labels"], json!(["a", "b"]));
883 assert_eq!(f.hint.as_deref(), Some("scroll"));
884 assert_eq!(fake.asked.len(), 2, "nothing runs after the failure");
885
886 let mut fake = Fake::default();
888 fake.answers.insert("tap".into(), not_found);
889 let code = "try { tap('x') } catch (e) { output('code', e.code); output('outcome', e.outcome) }\nreturn { after: read().ok }";
890 let (res, _) = go(&mut fake, code, json!({}), limits());
891 assert_eq!(res.unwrap()["outputs"], json!({"code": "not_found", "outcome": "not_sent", "after": true}));
892 }
893
894 #[test]
895 fn a_script_that_throws_reports_its_line() {
896 let mut fake = Fake::default();
897 let (res, _) = go(&mut fake, "tap('a');\n\nthrow new Error('기대한 화면이 아닙니다');", json!({}), limits());
898 let f = res.unwrap_err();
899 assert_eq!(f.code, "script_error");
900 assert_eq!(f.message, "기대한 화면이 아닙니다");
901 assert_eq!(f.extra["line"], 3);
902 assert_eq!(f.outcome, Outcome::Unknown);
904 assert_eq!(f.extra["inputs_sent"], 1);
905 let (res, kept) = go(&mut Fake::default(), "tap('a'", json!({}), limits());
907 let f = res.unwrap_err();
908 assert_eq!((f.code.as_str(), f.outcome, kept.calls), ("script_error", Outcome::NotSent, 0));
909 assert_eq!(f.extra["line"], 1);
910 }
911
912 #[test]
913 fn nothing_follows_a_call_with_an_unknown_outcome() {
914 let mut fake = Fake::default();
915 fake.answers.insert(
916 "tap".into(),
917 json!({"ok": false, "outcome": "unknown", "error": {"code": "input_failed", "message": "write failed"}}),
918 );
919 let code = "for (let i = 0; i < 5; i++) { try { tap('보내기 아님') } catch (e) {} }\nreturn 'went on'";
921 let (res, kept) = go(&mut fake, code, json!({}), limits());
922 let f = res.unwrap_err();
923 assert_eq!(f.outcome, Outcome::Unknown);
924 assert_eq!(f.extra["reason"]["code"], "input_failed");
925 assert_eq!(fake.asked.len(), 1, "the tap is not sent a second time");
926 assert_eq!(kept.end, End::Stopped("unknown_outcome"));
927 }
928
929 #[test]
930 fn a_script_that_never_ends_is_stopped() {
931 let short = || Limits { timeout: Duration::from_millis(300), memory: 32 << 20 };
932 let began = Instant::now();
933 let (res, _) = go(&mut Fake::default(), "while (true) {}", json!({}), short());
934 let f = res.unwrap_err();
935 assert_eq!((f.code.as_str(), f.outcome), ("script_timeout", Outcome::NotSent));
936 assert!(began.elapsed() < Duration::from_secs(5));
937 let (res, _) = go(&mut Fake::default(), "tap('a'); while (true) {}", json!({}), short());
939 assert_eq!(res.unwrap_err().outcome, Outcome::Unknown);
940 let (res, _) = go(&mut Fake::default(), "sleep(60000)", json!({}), short());
942 assert_eq!(res.unwrap_err().code, "script_timeout");
943 let mut slow = Fake { delay: Some(Duration::from_secs(30)), ..Default::default() };
944 let (res, _) = go(&mut slow, "tap('a')", json!({}), short());
945 let f = res.unwrap_err();
946 assert_eq!((f.code.as_str(), f.outcome), ("script_timeout", Outcome::Unknown));
947 }
948
949 #[test]
950 fn a_script_that_eats_memory_is_stopped() {
951 let small = Limits { timeout: Duration::from_secs(20), memory: 8 << 20 };
952 let code = "const all = []; while (true) { all.push(new Array(100000).fill('x'.repeat(20))) }";
953 let (res, _) = go(&mut Fake::default(), code, json!({}), small);
954 let f = res.unwrap_err();
955 assert_eq!(f.code, "script_error");
956 assert!(f.message.contains("memory"), "{}", f.message);
957 }
958
959 #[test]
960 fn a_script_has_no_way_out_of_the_engine() {
961 let code = r#"
962 const names = ["require", "process", "fetch", "XMLHttpRequest", "std", "os", "Deno", "Bun",
963 "WebSocket", "setTimeout", "importScripts", "Worker"];
964 return { there: names.filter((n) => typeof globalThis[n] !== "undefined") };
965 "#;
966 let (res, _) = go(&mut Fake::default(), code, json!({}), limits());
967 assert_eq!(res.unwrap()["outputs"]["there"], json!([]));
968 let (res, _) = go(&mut Fake::default(), "import fs from 'fs'", json!({}), limits());
970 assert_eq!(res.unwrap_err().code, "script_error");
971 let (res, _) = go(
972 &mut Fake::default(),
973 "let got = 'nothing'; import('std').then(() => { got = 'loaded' }, () => { got = 'refused' }); return got",
974 json!({}),
975 limits(),
976 );
977 assert_ne!(res.map(|o| o["outputs"]["result"].clone()).unwrap_or(json!("refused")), json!("loaded"));
978 }
979
980 #[test]
981 fn the_line_comes_from_the_scripts_own_frame() {
982 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";
983 assert_eq!(script_line(Some(stack)), Some(3));
984 assert_eq!(script_line(Some(" at script:2:9\n")), Some(1));
985 assert_eq!(script_line(Some(" at f (eval_script:7:1)\n")), None);
986 assert_eq!(script_line(None), None);
987 }
988
989 #[test]
990 fn a_hint_on_a_call_is_what_the_person_is_told() {
991 let mut state = RunState::default();
992 let p = state.prepare("wait_for", json!({"selector": "홈", "hint": "폰을 봐 주세요"})).unwrap();
993 assert_eq!(p.hint.as_deref(), Some("폰을 봐 주세요"));
994 assert_eq!(p.args, json!({"selector": "홈"}));
995 }
996
997 #[test]
998 fn saved_scripts_are_listed_with_their_first_comment() {
999 assert_eq!(description("// 설정에서 iOS 버전 읽기\nlaunch('x')"), "설정에서 iOS 버전 읽기");
1000 assert_eq!(description("\n\n // spaced \ncode"), "spaced");
1001 assert_eq!(description("launch('x')"), "");
1002 for (name, code) in BUILTIN {
1003 assert!(!description(code).is_empty(), "{name} has no description");
1004 }
1005 }
1006}