Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,14 @@ What changed in each release, one line per change. Versions follow [Semantic Ver

### Fixes

- AI tasks: while a step waits for your confirmation you can take over first (to look or change something); the question stays, and can be answered while you're in control or after handing back (#201).
- The control page no longer stays on "running" when a task's event stream is closed for good: it follows the task again if it is still there, or marks it stopped. Reconnecting or reloading the page no longer redraws old gesture marks (#201).
- A page or `task events` that fell behind a busy task no longer misses its end and stays open; a task's end stops every step still under way (a step asking to leave the task's scope, and its question, are two), so none keeps spinning; nothing is recorded after the end (#201).
- `task run` waits for what the command started to stop (killing what ignores SIGTERM) before it exits; stopping a group no longer sends a late SIGKILL to a group number that may have been reused (#201).
- The picture of a phone driven by WebDriverAgent ends when you switch to another device, instead of showing the old one (#201).
- The H.264 copy of the phone's own video counts a crashed ffmpeg as a failure and moves on to the next encoder, instead of restarting it for ever (#201).
- `task run --url` stops within 10 seconds of Ctrl-C even if the viewer doesn't answer, and gives up an event stream that goes silent or sends an endless event (#201).
- Only one daemon runs per socket, even when two start at once, and the socket is private from the moment it is created; a lock that can't be taken at all is reported as such instead of as another daemon (#201).
- When pressing Home finds a system alert in the way, the daemon's answer now also marks it in its structured result (`alert_reported`), as launching an app or opening a link does; programs reading the result rather than its text missed it (#200).
- A long press falls back to HID like a tap when WebDriverAgent can't be reached (#200).
- Requests that can't run (a tap count of 0, an empty tap sequence, an unknown button, a point that isn't a number) are refused at once, before waiting for the phone and without dropping the cached screen (#200).
Expand Down
8 changes: 8 additions & 0 deletions CHANGELOG.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,14 @@

### 修复

- AI 任务:某一步在等你确认时,可以先接管(看看或改一下);问题会一直留着,接管时或交还后都能回答(#201)。
- 任务的事件流被彻底关掉时,控制台不再一直停在「执行中」:任务还在就重新跟上,不在了就标成已停止。重连或刷新页面时也不会再把以前的手势标记重画一遍(#201)。
- 跟着一个忙碌任务的页面或 `task events` 跟不上时,不再错过任务结束而一直挂着;任务结束时把还在进行的步骤都停下(要越出任务范围的一步和它的提问是两步),不会再有一直转圈的步骤;结束后也不会再记任何事件(#201)。
- `task run` 退出前会等命令启动的进程都停下(不理 SIGTERM 的会被强制结束);停进程组时不再在几秒后对可能已被复用的组号补发 SIGKILL(#201)。
- 用 WebDriverAgent 控制的手机,切换到别的设备后,原来的画面流会结束,不再一直显示旧设备(#201)。
- 手机原生视频转成 H.264 时,ffmpeg 崩溃算作失败,换下一个编码器,不再无休止地重启(#201)。
- `task run --url` 在控制台不应答时,按 Ctrl-C 后 10 秒内也能停下;事件流长时间没动静或发来没有结尾的事件时会放弃(#201)。
- 一个 socket 只会有一个守护进程在跑,两个同时启动也一样;socket 从创建那一刻起就只有自己能访问;根本拿不到锁时如实报错,不再说成已有守护进程(#201)。
- 按 Home 时发现有系统弹窗挡着,守护进程的应答现在也会在结构化结果里标出(`alert_reported`),和启动 App、打开链接一样;之前只读结果字段、不看文字的程序会漏掉(#200)。
- 长按和点击一样,连不上 WebDriverAgent 时改用 HID(#200)。
- 执行不了的请求(点击次数为 0、空的点击序列、不认识的按键、坐标不是有效数字)立刻拒绝,不再先排队等手机,也不会清掉缓存的界面(#200)。
Expand Down
53 changes: 46 additions & 7 deletions apps/iphone-control/src/procgroup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,17 @@ use std::time::Duration;
/// How long a group has after SIGTERM before SIGKILL
pub const GRACE: Duration = Duration::from_secs(3);

/// SIGTERM to the group led by `pid`, SIGKILL [`GRACE`] later if it is still there
/// How often a stopped group is looked for while it has [`GRACE`]
const POLL: Duration = Duration::from_millis(100);

/// Whether any process of the group is left (zombies count until reaped)
fn alive(pgid: libc::pid_t) -> bool {
unsafe { libc::kill(-pgid, 0) == 0 }
}

/// SIGTERM to the group led by `pid`, SIGKILL [`GRACE`] later if it is still there. Looked for every [`POLL`] and
/// left alone once gone: the system doesn't give a group's number to another process while the group exists, but
/// may once it is gone, and a SIGKILL sent blindly 3 s later could then hit someone else's group
pub fn stop(pid: u32) {
let Ok(pgid) = libc::pid_t::try_from(pid) else { return };
if pgid <= 1 {
Expand All @@ -16,31 +26,60 @@ pub fn stop(pid: u32) {
}
unsafe { libc::kill(-pgid, libc::SIGTERM) };
tokio::spawn(async move {
tokio::time::sleep(GRACE).await;
unsafe { libc::kill(-pgid, libc::SIGKILL) };
let deadline = tokio::time::Instant::now() + GRACE;
while tokio::time::Instant::now() < deadline {
if !alive(pgid) {
return;
}
tokio::time::sleep(POLL).await;
}
if alive(pgid) {
unsafe { libc::kill(-pgid, libc::SIGKILL) };
}
});
}

/// Whether the group led by `pid` still has a process in it
pub fn any_left(pid: u32) -> bool {
libc::pid_t::try_from(pid).is_ok_and(|g| g > 1 && alive(g))
}

/// [`stop`] for several groups, waiting for them here instead of in a task (the program is about to exit, which a
/// task wouldn't outlive): SIGTERM to each, then SIGKILL to those still there after [`GRACE`]
pub async fn stop_and_wait(leaders: &[u32]) {
let groups: Vec<libc::pid_t> =
let mut groups: Vec<libc::pid_t> =
leaders.iter().filter_map(|&p| libc::pid_t::try_from(p).ok()).filter(|&g| g > 1).collect();
for &g in &groups {
unsafe { libc::kill(-g, libc::SIGTERM) };
}
let alive = |g: libc::pid_t| unsafe { libc::kill(-g, 0) } == 0;
let deadline = tokio::time::Instant::now() + GRACE;
while groups.iter().any(|&g| alive(g)) && tokio::time::Instant::now() < deadline {
loop {
// a group seen gone is dropped at once: its number may go to another group while the others still have time
groups.retain(|&g| alive(g));
if groups.is_empty() || tokio::time::Instant::now() >= deadline {
break;
}
tokio::time::sleep(Duration::from_millis(50)).await;
}
for &g in groups.iter().filter(|&&g| alive(g)) {
for &g in &groups {
unsafe { libc::kill(-g, libc::SIGKILL) };
}
}

#[cfg(test)]
mod tests {
/// A group is seen while anything of it runs, and not once it is gone (then `stop` sends no SIGKILL)
#[tokio::test]
async fn a_group_is_seen_until_it_is_gone() {
use std::os::unix::process::CommandExt;
let mut leader = std::process::Command::new("sleep").arg("30").process_group(0).spawn().unwrap();
assert!(super::any_left(leader.id()));
super::stop(leader.id());
leader.wait().unwrap();
assert!(!super::any_left(leader.id()), "reaped and gone");
assert!(!super::any_left(0) && !super::any_left(1), "never this process's own group, or every process");
}

#[tokio::test]
async fn stopping_the_group_stops_what_it_started() {
use std::os::unix::process::CommandExt;
Expand Down
50 changes: 47 additions & 3 deletions apps/iphone-control/src/remote.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,9 @@ impl Remote {

/// Stops the task (the platform's Ctrl-C); whether the viewer took it
pub async fn stop(&self, id: &str) -> bool {
let r = self.post(&format!("/api/agent/tasks/{id}/stop"), &json!({})).send().await;
// Ctrl-C waits for this: a viewer that doesn't answer mustn't keep `task run` from stopping
let r =
self.post(&format!("/api/agent/tasks/{id}/stop"), &json!({})).timeout(Duration::from_secs(10)).send().await;
r.is_ok_and(|r| r.status().is_success())
}

Expand Down Expand Up @@ -241,14 +243,24 @@ impl Events {
}
continue;
}
match self.resp.chunk().await {
Ok(Some(c)) => self.buf.extend_from_slice(&c),
// nothing at all for this long, not even the viewer's ping every 15 s: it is gone; an event that never ends
// (no blank line in a megabyte) isn't one
if self.buf.len() > MAX_EVENT {
return None;
}
match tokio::time::timeout(EVENT_SILENCE, self.resp.chunk()).await {
Ok(Ok(Some(c))) => self.buf.extend_from_slice(&c),
_ => return None,
}
}
}
}

/// How long a task's event stream may stay silent: the viewer sends a ping every 15 s
const EVENT_SILENCE: Duration = Duration::from_secs(60);
/// The longest event taken: the viewer's are a few kilobytes at most
const MAX_EVENT: usize = 1024 * 1024;

/// Where the first event in `buf` ends, and where the next one starts
fn event_end(buf: &[u8]) -> Option<(usize, usize)> {
let lf = buf.windows(2).position(|w| w == b"\n\n").map(|i| (i, i + 2));
Expand Down Expand Up @@ -301,6 +313,38 @@ mod tests {
assert_eq!(event_end("data: \"设".as_bytes()), None, "not yet");
}

/// An event that never ends (no blank line in more than a megabyte) ends the stream instead of growing for ever
#[tokio::test]
async fn an_event_without_end_ends_the_stream() {
use tokio::io::AsyncWriteExt;
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let server = tokio::spawn(async move {
let (mut s, _) = listener.accept().await.unwrap();
let mut head = [0u8; 1024];
let _ = tokio::io::AsyncReadExt::read(&mut s, &mut head).await;
s.write_all(b"HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\n\r\nevent: step\ndata: ")
.await
.unwrap();
let chunk = vec![b'x'; 64 * 1024];
for _ in 0..32 {
if s.write_all(&chunk).await.is_err() {
break;
}
}
});
// as `Remote::new` does: a client built without a crypto provider panics, unless another test happened to
// install one first in this process
let _ = rustls::crypto::ring::default_provider().install_default();
let client = reqwest::Client::builder().no_proxy().build().unwrap();
let resp = client.get(format!("http://{addr}/")).send().await.unwrap();
let mut events = Events::new(resp);
let next = tokio::time::timeout(Duration::from_secs(10), events.next_raw()).await.expect("not waited for");
assert_eq!(next, None);
assert!(events.buf.len() <= MAX_EVENT + 64 * 1024, "{}", events.buf.len());
server.abort();
}

#[test]
fn the_address_is_the_viewer_s() {
let r = Remote::new("https://nas.local:8202/mcp/", None, None).unwrap();
Expand Down
11 changes: 11 additions & 0 deletions apps/iphone-control/src/task.rs
Original file line number Diff line number Diff line change
Expand Up @@ -359,6 +359,14 @@ async fn run_command(
_ = term.recv() => stop_here(backend, &opened.id, pid).await,
}
};
// the command is gone, but what it started may not be (an MCP server that ignores SIGTERM): stopped right away,
// while the group still holds its number (the leader was just reaped: once the group is empty the number may go
// to another process), and waited for before exiting, as exiting would take the delayed SIGKILL of `stop_group`
// with it. Its grace runs alongside telling the daemon, which unlocks the phone
let leftovers = pid
.and_then(|p| u32::try_from(p).ok())
.filter(|&p| crate::procgroup::any_left(p))
.map(|p| tokio::spawn(async move { crate::procgroup::stop_and_wait(&[p]).await }));
if !ended {
// the command may have ended the task itself (`task finish`); then this changes nothing
backend.finish(&opened.token, status.success(), "").await;
Expand All @@ -368,6 +376,9 @@ async fn run_command(
None => backend.state(&opened.id).await.unwrap_or_default(),
};
eprintln!("{}", ictl_l10n::trf!("任务 {} 结束:{outcome}", "Task {} ended: {outcome}", opened.id));
if let Some(h) = leftovers {
let _ = h.await;
}
drop(lease);
std::process::exit(exit_code(status.code(), &outcome));
}
Expand Down
28 changes: 18 additions & 10 deletions apps/iphone-control/src/video/ffmpeg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -444,6 +444,15 @@ pub struct Encoders {
picking: tokio::sync::Mutex<()>,
}

/// How to turn the phone's HEVC into H.264 ([`Encoders::hevc_command`])
pub struct HevcCommand {
pub ffmpeg: PathBuf,
pub args: Vec<String>,
pub label: &'static str,
/// The encoder in use, when it is the one ffmpeg runs here (its index, for [`Encoders::give_up`])
pub encoder: Option<usize>,
}

impl Encoders {
/// Finds and checks an encoder. `Err`: why the page keeps MJPEG (no ffmpeg, none works, or turned off)
pub async fn detect() -> Result<Arc<Self>, String> {
Expand Down Expand Up @@ -546,22 +555,20 @@ impl Encoders {
/// ffmpeg and its command line for transcoding the phone's own HEVC video with the encoder in use
/// ([`hevc_args`]); the native encoder (JPEG only) is replaced by VideoToolbox through ffmpeg. `Err` without
/// ffmpeg or a working encoder
pub fn hevc_command(
&self,
points: Option<(f64, f64)>,
qp: u8,
) -> Result<(PathBuf, Vec<String>, &'static str), String> {
pub fn hevc_command(&self, points: Option<(f64, f64)>, qp: u8) -> Result<HevcCommand, String> {
let c = self.current().ok_or_else(|| ictl_l10n::tr!("没有可用的编码器", "no working encoder").to_owned())?;
let ffmpeg = self.ffmpeg.clone().ok_or_else(|| {
ictl_l10n::tr!("没有 ffmpeg,转不了手机的 HEVC 画面", "no ffmpeg to transcode the phone's HEVC picture")
.to_owned()
})?;
let kind = match &self.list[c.index] {
Kind::Native => &Kind::VideoToolbox,
k => k,
let (kind, stand_in) = match &self.list[c.index] {
Kind::Native => (&Kind::VideoToolbox, true),
k => (k, false),
};
let args = hevc_args(kind, points, qp, self.old).ok_or("no encoder for HEVC input")?;
Ok((ffmpeg, args, kind.label()))
// the encoder in use, unless ffmpeg stands in for it (the built-in one takes JPEG only): only then is a failure
// here that encoder's, to give up ([`Self::give_up`])
Ok(HevcCommand { ffmpeg, args, label: kind.label(), encoder: (!stand_in).then_some(c.index) })
}

/// The quantizer set for the picture (`IPHONE_CONTROL_VIEWER_QP`)
Expand Down Expand Up @@ -697,7 +704,7 @@ async fn native_sample() -> Result<Vec<u8>, String> {
async fn version_line(ffmpeg: &Path) -> Option<String> {
let out = tokio::time::timeout(
Duration::from_secs(10),
Command::new(ffmpeg).arg("-version").stdin(Stdio::null()).stderr(Stdio::null()).output(),
Command::new(ffmpeg).arg("-version").stdin(Stdio::null()).stderr(Stdio::null()).kill_on_drop(true).output(),
)
.await
.ok()?
Expand All @@ -714,6 +721,7 @@ async fn sample_jpeg(ffmpeg: &Path) -> Result<Vec<u8>, String> {
.args(["-hide_banner", "-loglevel", "error", "-f", "lavfi", "-i", &size, "-frames:v", "1"])
.args(["-c:v", "mjpeg", "-pix_fmt", "yuvj420p", "-q:v", "5", "-f", "mjpeg", "pipe:1"])
.stdin(Stdio::null())
.kill_on_drop(true)
.output(),
)
.await
Expand Down
Loading
Loading