Skip to content

Control a real USB-connected iPhone from Linux (no Mac, no paid developer account) and expose it to AI agents as MCP tools

fix(task): let a command that finished its task exit with its own code (#78)

Qinghe Li28045889bb2a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b8c3909..b03ec5f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -31,6 +31,7 @@ All notable changes to this project are documented here. The format is based on
### Fixed
+- `task run`: a command that ended its task with `task finish` is no longer stopped on its way out with exit code 1. It now has 5 seconds to exit with its own code; if it is stopped after that, the exit code is 0 when the task completed.
- Holding an arrow key in a setup menu keeps moving the selection without echoing key sequences into the menu.
- AI task summaries on the control page are formatted: bold, lists, inline code and line breaks show as such instead of raw Markdown.
- On iOS 27 and later, a system alert (a permission prompt such as "Allow Calendar to use your location?") that the live picture on the control page doesn't show is now drawn on the picture where it is, with its buttons; a button there taps it on the phone.
diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md
index f3783cc..2229384 100644
--- a/CHANGELOG.zh-CN.md
+++ b/CHANGELOG.zh-CN.md
@@ -31,6 +31,7 @@
### 修复
+- `task run`:命令自己用 `task finish` 结束任务后,不再在它正常退出时被立刻停掉、退出码变成 1。现在它有 5 秒自己退出,退出码就是它自己的;超时才停掉,这时任务完成则退出码为 0。
- 在设置菜单中长按方向键时,选项会连续移动,按键序列不会回显到菜单里。
- 控制台上 AI 任务的总结按格式显示:粗体、列表、行内代码和换行不再显示成 Markdown 原文。
- iOS 27 及以上,控制台实时画面里看不到的系统弹窗(例如「允许“日历”使用你的位置?」这类权限请求)现在画在画面里它所在的位置,带着弹窗的按钮,点按钮就是点手机上的那个按钮。
diff --git a/apps/iphone-control/src/task.rs b/apps/iphone-control/src/task.rs
index 9b5440e..a7f3a59 100644
--- a/apps/iphone-control/src/task.rs
+++ b/apps/iphone-control/src/task.rs
@@ -183,6 +183,8 @@ async fn run_command(
let mut term = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())?;
let mut outcome: Option<String> = None;
let mut ended = false;
+ // the command ended the task itself and is on its way out: stopped only if it is still there after this
+ let mut grace: Option<std::pin::Pin<Box<tokio::time::Sleep>>> = None;
let status = loop {
tokio::select! {
s = child.wait() => break s?,
@@ -190,9 +192,17 @@ async fn run_command(
if let Some(e) = &e && e.event != "done" {
continue;
}
- // ended elsewhere, or the daemon went away: the command can't go on
ended = true;
outcome = e.and_then(|e| e.data["outcome"].as_str().map(str::to_owned));
+ if finished_inside(outcome.as_deref()) {
+ grace = Some(Box::pin(tokio::time::sleep(FINISH_GRACE)));
+ } else {
+ // stopped or interrupted elsewhere, or the daemon went away: the command can't go on
+ stop_group(pid);
+ }
+ }
+ () = async { grace.as_mut().expect("guarded").await }, if grace.is_some() => {
+ grace = None;
stop_group(pid);
}
_ = tokio::signal::ctrl_c() => stop_here(socket, &opened.id, pid).await,
@@ -215,7 +225,21 @@ async fn run_command(
};
eprintln!("{}", ictl_l10n::trf!("任务 {} 结束:{outcome}", "Task {} ended: {outcome}", opened.id));
drop(lease);
- std::process::exit(status.code().unwrap_or(1));
+ std::process::exit(exit_code(status.code(), &outcome));
+}
+
+/// How long a command that ended its task (`task finish`) has to exit before it is stopped
+const FINISH_GRACE: Duration = Duration::from_secs(5);
+
+/// The task ended from inside the command: only a process with the task's token can finish it, and this one only
+/// finishes it after the command exited. Any other end (stopped, interrupted) came from elsewhere
+fn finished_inside(outcome: Option<&str>) -> bool {
+ matches!(outcome, Some("completed" | "failed" | "rejected"))
+}
+
+/// The command's own exit code; when it was stopped (a signal, no code), the task's result: 0 if it completed
+fn exit_code(code: Option<i32>, outcome: &str) -> i32 {
+ code.unwrap_or(if outcome == "completed" { 0 } else { 1 })
}
/// Ctrl-C or SIGTERM: the user stops the task (the lease stream then reports it, and the command is stopped)
@@ -242,3 +266,27 @@ fn stop_group(pid: Option<libc::pid_t>) {
unsafe { libc::kill(-pgid, libc::SIGKILL) };
});
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_command_that_finished_its_task_is_given_time_to_exit() {
+ for o in ["completed", "failed", "rejected"] {
+ assert!(finished_inside(Some(o)), "{o}");
+ }
+ for o in [Some("cancelled"), Some("interrupted"), Some("abandoned"), None] {
+ assert!(!finished_inside(o), "{o:?}: stop it now");
+ }
+ }
+
+ #[test]
+ fn the_exit_code_is_the_command_s_or_the_task_s_result() {
+ assert_eq!(exit_code(Some(0), "failed"), 0, "its own code wins");
+ assert_eq!(exit_code(Some(3), "completed"), 3);
+ assert_eq!(exit_code(None, "completed"), 0, "stopped after it completed the task");
+ assert_eq!(exit_code(None, "cancelled"), 1);
+ assert_eq!(exit_code(None, ""), 1);
+ }
+}
diff --git a/tests/device/tasks.py b/tests/device/tasks.py
index ebd75af..6b01e99 100644
--- a/tests/device/tasks.py
+++ b/tests/device/tasks.py
@@ -456,6 +456,24 @@ async def run_cmd(stack):
elif p.returncode is None:
p.kill()
+ # the command ends the task itself (`task finish`): its own exit code, not 1 from being stopped while leaving
+ for title_tail, script, want, max_s in (
+ ("finish 后退出", '"$@" task finish 完成; sleep 1', 0, 4),
+ ("finish 后不退出", '"$@" task finish 完成; sleep 600', 0, 12),
+ ("finish 失败后退出", '"$@" task finish --failed 没做成; exit 3', 3, 4),
+ ):
+ title = f"真机回归:task run {title_tail} {int(time.time())}"
+ t0 = time.time()
+ p = await asyncio.create_subprocess_exec(
+ *BIN, "task", "run", "--title", title, "--owner", OWNER, "--", "sh", "-c", script, "sh", *BIN,
+ stdout=asyncio.subprocess.DEVNULL, stderr=asyncio.subprocess.DEVNULL,
+ )
+ code = await asyncio.wait_for(p.wait(), 30)
+ dt = time.time() - t0
+ state = (next((t for t in reversed(await tasks()) if t["title"] == title), {})).get("state")
+ check(c, f"`task finish` then {title_tail}: exit {code} ({dt:.1f}s), task {state}",
+ code == want and dt < max_s and state == ("failed" if want else "completed"))
+
async def scope(stack):
"""#110: a task limited to Settings asks before going elsewhere; approving lets it in, rejecting refuses one step"""