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: tasks keep the user's pause through questions; viewer survives slow and failed connections (#88)

Qinghe Libe6ae0ce2129
diff --git a/apps/iphone-control/src/main.rs b/apps/iphone-control/src/main.rs
index 3d54aa2..08d6449 100644
--- a/apps/iphone-control/src/main.rs
+++ b/apps/iphone-control/src/main.rs
@@ -1372,26 +1372,33 @@ const MAX_CONNECTIONS: usize = 32;
const MAX_HEAD: usize = 16 * 1024;
/// 客户端发请求头、请求体时单次读的等待上限:连上不发的连接不能一直占着名额
const READ_TIMEOUT: Duration = Duration::from_secs(10);
+/// 整个请求头(以及 TLS 握手)的时限:每隔几秒发一个字节的连接也不能一直占着名额
+const HEAD_TIMEOUT: Duration = Duration::from_secs(10);
/// 读到请求头结束;返回头部和跟着一起到的那部分请求体
async fn read_head(client: &mut (impl tokio::io::AsyncRead + Unpin)) -> anyhow::Result<(Vec<u8>, Vec<u8>)> {
use tokio::io::AsyncReadExt;
- let mut data = Vec::new();
- let mut buf = [0u8; 4096];
- loop {
- if let Some(i) = data.windows(4).position(|w| w == b"\r\n\r\n") {
- let body = data.split_off(i + 4);
- return Ok((data, body));
- }
- if data.len() > MAX_HEAD {
- bail!("{}", ictl_l10n::tr!("请求头太长", "request headers too long"));
- }
- let n = tokio::time::timeout(READ_TIMEOUT, client.read(&mut buf)).await??;
- if n == 0 {
- bail!("{}", ictl_l10n::tr!("连接已关闭", "connection closed"));
+ let read = async {
+ let mut data = Vec::new();
+ let mut buf = [0u8; 4096];
+ loop {
+ if let Some(i) = data.windows(4).position(|w| w == b"\r\n\r\n") {
+ let body = data.split_off(i + 4);
+ return Ok((data, body));
+ }
+ if data.len() > MAX_HEAD {
+ bail!("{}", ictl_l10n::tr!("请求头太长", "request headers too long"));
+ }
+ let n = tokio::time::timeout(READ_TIMEOUT, client.read(&mut buf)).await??;
+ if n == 0 {
+ bail!("{}", ictl_l10n::tr!("连接已关闭", "connection closed"));
+ }
+ data.extend_from_slice(&buf[..n]);
}
- data.extend_from_slice(&buf[..n]);
- }
+ };
+ tokio::time::timeout(HEAD_TIMEOUT, read)
+ .await
+ .map_err(|_| anyhow::anyhow!("{}", ictl_l10n::tr!("请求头没有按时发完", "request headers took too long")))?
}
/// HTTP 请求头里的 Host 是不是 localhost / 127.0.0.1 / [::1](端口不限)
diff --git a/apps/iphone-control/src/viewer.rs b/apps/iphone-control/src/viewer.rs
index 885f4b7..1df68ce 100644
--- a/apps/iphone-control/src/viewer.rs
+++ b/apps/iphone-control/src/viewer.rs
@@ -286,31 +286,47 @@ pub async fn run(
auth: Some(auth),
});
let slots = Arc::new(tokio::sync::Semaphore::new(crate::MAX_CONNECTIONS));
+ let arriving = Arriving::default();
loop {
- let (client, peer) = listener.accept().await?;
+ let (client, peer) = match listener.accept().await {
+ Ok(c) => c,
+ // for example out of file descriptors: the viewer goes on (and retrying at once would only spin)
+ Err(e) => {
+ tracing::warn!("viewer: accepting a connection failed: {e}");
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ continue;
+ }
+ };
// open to the network: only from the local network (a machine reachable from the internet isn't operated
// from there)
if !lan::peer_allowed(peer.ip()) {
tracing::warn!("viewer: refused a connection from {}", peer.ip());
continue;
}
+ // one machine on the network can't take every place with connections that never send a request
+ let Some(early) = arriving.enter(peer.ip()) else { continue };
// too many open connections (for example many tabs): drop the new one
let Ok(slot) = slots.clone().try_acquire_owned() else { continue };
let ctx = ctx.clone();
tokio::spawn(async move {
let client = match &ctx.tls {
// the handshake in the connection's own task: a slow client doesn't hold up the others
- Some(t) => match t.accept(client).await {
- Ok(c) => c,
- Err(e) => {
+ Some(t) => match tokio::time::timeout(crate::HEAD_TIMEOUT, t.accept(client)).await {
+ Ok(Ok(c)) => c,
+ Ok(Err(e)) => {
tracing::debug!("viewer TLS: {e}");
drop(slot);
return;
}
+ Err(_) => {
+ tracing::debug!("viewer TLS: the handshake took too long");
+ drop(slot);
+ return;
+ }
},
None => Conn::Plain(client),
};
- if let Err(e) = serve(client, &ctx).await {
+ if let Err(e) = serve(client, &ctx, Some(early)).await {
tracing::debug!("viewer connection: {e}");
}
drop(slot);
@@ -318,6 +334,48 @@ pub async fn run(
}
}
+/// Connections from a machine on the network that haven't sent their request yet (handshake and head), at most
+/// [`ARRIVING_PER_PEER`] each. This machine isn't limited: the page's own requests come from it, and so does
+/// everything a reverse proxy forwards
+#[derive(Default, Clone)]
+struct Arriving(Arc<Mutex<std::collections::HashMap<std::net::IpAddr, usize>>>);
+
+const ARRIVING_PER_PEER: usize = 8;
+
+/// One connection counted in [`Arriving`] until it has sent its request
+struct Early(Option<(Arriving, std::net::IpAddr)>);
+
+impl Arriving {
+ fn enter(&self, ip: std::net::IpAddr) -> Option<Early> {
+ let ip = ip.to_canonical();
+ if ip.is_loopback() {
+ return Some(Early(None));
+ }
+ let mut m = self.0.lock().unwrap_or_else(|p| p.into_inner());
+ let n = m.entry(ip).or_default();
+ if *n >= ARRIVING_PER_PEER {
+ tracing::debug!("viewer: too many connections from {ip} still sending their request");
+ return None;
+ }
+ *n += 1;
+ Some(Early(Some((self.clone(), ip))))
+ }
+}
+
+impl Drop for Early {
+ fn drop(&mut self) {
+ if let Some((a, ip)) = self.0.take() {
+ let mut m = a.0.lock().unwrap_or_else(|p| p.into_inner());
+ if let Some(n) = m.get_mut(&ip) {
+ *n -= 1;
+ if *n == 0 {
+ m.remove(&ip);
+ }
+ }
+ }
+ }
+}
+
/// This machine's network addresses `--lan` serves on (for `viewer token`)
pub fn lan_addresses(lan_hosts: &[String]) -> Vec<std::net::Ipv4Addr> {
lan::Access::lan(lan_hosts).addresses().to_vec()
@@ -334,8 +392,9 @@ fn page_in(lang: ictl_l10n::Lang) -> String {
/// One request per connection (`Connection: close`), which keeps the parser small. It is handled in the page's
/// language (`X-Ictl-Lang`), so the daemon's messages match the page
-async fn serve(mut client: Conn, ctx: &Ctx) -> anyhow::Result<()> {
+async fn serve(mut client: Conn, ctx: &Ctx, early: Option<Early>) -> anyhow::Result<()> {
let (head, body) = crate::read_head(&mut client).await?;
+ drop(early);
let Some(req) = Head::parse(&head) else {
return reply(&mut client, 400, "text/plain", b"bad request").await;
};
@@ -381,8 +440,8 @@ async fn handle(mut client: Conn, ctx: &Ctx, head: Vec<u8>, req: Head, mut body:
};
picture(client, ctx, &req).await
}
- ("GET", p) if p.starts_with("/api/agent/tasks/") && p.ends_with("/events") => {
- let id = &p["/api/agent/tasks/".len()..p.len() - "/events".len()];
+ ("GET", p) if task_events_id(p).is_some() => {
+ let id = task_events_id(p).unwrap_or_default();
match protocol::task_events(&ctx.socket, id).await {
Ok(stream) => events(&mut client, stream).await,
Err(m) => json_reply(&mut client, 404, &json!({"message": m})).await,
@@ -777,20 +836,32 @@ fn sse(e: &protocol::TaskEvent) -> String {
format!("event: {}\ndata: {}\n\n", e.event, e.data)
}
+/// `/api/agent/tasks/<id>/events`: the task's id
+fn task_events_id(path: &str) -> Option<&str> {
+ path.strip_prefix("/api/agent/tasks/")?.strip_suffix("/events").filter(|id| !id.is_empty() && !id.contains('/'))
+}
+
/// The rest of a request body: `body` holds what came with the head; `len` bytes in all
async fn read_body(client: &mut Conn, body: &mut Vec<u8>, len: usize) -> anyhow::Result<()> {
- while body.len() < len {
- let mut buf = [0u8; 4096];
- let n = tokio::time::timeout(crate::READ_TIMEOUT, client.read(&mut buf)).await??;
- if n == 0 {
- bail!("body cut off");
+ let read = async {
+ while body.len() < len {
+ let mut buf = [0u8; 4096];
+ let n = tokio::time::timeout(crate::READ_TIMEOUT, client.read(&mut buf)).await??;
+ if n == 0 {
+ bail!("body cut off");
+ }
+ body.extend_from_slice(&buf[..n]);
}
- body.extend_from_slice(&buf[..n]);
- }
+ anyhow::Ok(())
+ };
+ // a whole body (at most `mcp::MAX_BODY`) in this time, however slowly it trickles in
+ tokio::time::timeout(BODY_TIMEOUT, read).await.map_err(|_| anyhow::anyhow!("body took too long"))??;
body.truncate(len);
Ok(())
}
+const BODY_TIMEOUT: Duration = Duration::from_secs(60);
+
async fn json_reply(client: &mut Conn, status: u16, v: &Value) -> anyhow::Result<()> {
reply(client, status, "application/json", v.to_string().as_bytes()).await
}
@@ -1444,7 +1515,7 @@ mod tests {
out
});
let (tcp, _) = listener.accept().await.unwrap();
- serve(Conn::Plain(tcp), ctx).await.unwrap();
+ serve(Conn::Plain(tcp), ctx, None).await.unwrap();
client.await.unwrap()
}
@@ -1626,7 +1697,7 @@ mod tests {
tokio::spawn(async move {
while let Ok((tcp, _)) = listener.accept().await {
let ctx = served.clone();
- tokio::spawn(async move { serve(Conn::Plain(tcp), &ctx).await });
+ tokio::spawn(async move { serve(Conn::Plain(tcp), &ctx, None).await });
}
});
@@ -1672,6 +1743,32 @@ mod tests {
bridge.await.unwrap().unwrap();
}
+ #[test]
+ fn the_task_events_route_takes_an_id() {
+ assert_eq!(task_events_id("/api/agent/tasks/0a1b2c/events"), Some("0a1b2c"));
+ // starts with the prefix and ends with the suffix, overlapping: no id (this used to panic)
+ assert_eq!(task_events_id("/api/agent/tasks/events"), None);
+ assert_eq!(task_events_id("/api/agent/tasks//events"), None);
+ assert_eq!(task_events_id("/api/agent/tasks/a/b/events"), None);
+ assert_eq!(task_events_id("/api/agent/tasks/abc"), None);
+ }
+
+ #[test]
+ fn a_machine_on_the_network_has_a_few_connections_arriving_at_a_time() {
+ let a = Arriving::default();
+ let lan: std::net::IpAddr = "192.168.1.9".parse().unwrap();
+ let other: std::net::IpAddr = "192.168.1.10".parse().unwrap();
+ let held: Vec<_> = (0..ARRIVING_PER_PEER).map(|_| a.enter(lan).unwrap()).collect();
+ assert!(a.enter(lan).is_none());
+ assert!(a.enter(other).is_some(), "another machine isn't held up");
+ let local: std::net::IpAddr = "127.0.0.1".parse().unwrap();
+ let many: Vec<_> = (0..100).map(|_| a.enter(local)).collect();
+ assert!(many.iter().all(Option::is_some), "this machine isn't limited");
+ drop(held);
+ assert!(a.enter(lan).is_some(), "once they sent their requests");
+ assert!(a.0.lock().unwrap().get(&lan).is_none_or(|n| *n == 0));
+ }
+
#[test]
fn plain_http_from_the_network_goes_to_the_same_page_over_https() {
let at = |raw: &[u8]| https_location(raw, &Head::parse(raw).unwrap(), 8202);
diff --git a/crates/ictl-daemon/src/core.rs b/crates/ictl-daemon/src/core.rs
index daab408..0648270 100644
--- a/crates/ictl-daemon/src/core.rs
+++ b/crates/ictl-daemon/src/core.rs
@@ -753,14 +753,48 @@ impl Daemon {
_ => None,
};
let t0 = Instant::now();
+ let looks = crate::tasks::observes(&req);
// boxed: the request's state machine is large, and a connection's task shouldn't carry it on the stack
- let resp = Box::pin(self.handle_admitted(req, queued_at, ctx)).await;
+ let resp = Box::pin(self.handle_admitted(req, queued_at, ctx, &admission)).await;
if let Some((t, step)) = auto {
self.tasks.auto_step_done(&t, step, &resp, t0.elapsed().as_millis() as u64);
}
+ // the agent has seen the screen only once its look succeeded
+ if let crate::tasks::Admission::Actor(t) = &admission
+ && looks
+ && !matches!(resp, Response::Error { .. })
+ {
+ t.observed();
+ }
resp
}
+ /// A request's lock, once the tasks still let it through ([`crate::tasks::Tasks::still`]): it may have queued
+ /// behind other requests while the user paused, took over or handed back. A task's request waits for the task to
+ /// run again, without the lock
+ async fn lock_admitted<'a, T>(
+ &self,
+ lock: &'a Mutex<T>,
+ req: &Request,
+ admission: &crate::tasks::Admission,
+ queued_at: &mut Instant,
+ gone: &mut Option<tokio::sync::oneshot::Receiver<()>>,
+ ) -> Result<tokio::sync::MutexGuard<'a, T>, Response> {
+ use crate::tasks::Still;
+ loop {
+ let g = acquire(lock, gone).await?;
+ match self.tasks.still(admission, req) {
+ Still::Admitted => return Ok(g),
+ Still::Refused(r) => return Err(r),
+ Still::Wait(t) => {
+ drop(g);
+ t.wait_running(gone).await?;
+ *queued_at = Instant::now();
+ }
+ }
+ }
+ }
+
/// What an action of a scoped task touches, then [`crate::tasks::Task::check_scope`]. The device lock is only held
/// to look it up, not while the user decides (the user may take over meanwhile). Returns whether it waited
async fn scope_gate(
@@ -815,7 +849,13 @@ impl Daemon {
}
/// [`Self::handle`] once the tasks let the request through
- async fn handle_admitted(self: &Arc<Self>, req: Request, queued_at: Instant, mut ctx: CallCtx) -> Response {
+ async fn handle_admitted(
+ self: &Arc<Self>,
+ req: Request,
+ mut queued_at: Instant,
+ mut ctx: CallCtx,
+ admission: &crate::tasks::Admission,
+ ) -> Response {
let text = |r: Result<String, String>| {
r.map(|t| Response::text_with(t, crate::protocol::Outcome::default())).unwrap_or_else(Response::error)
};
@@ -834,7 +874,8 @@ impl Daemon {
}
// Web Inspector talks to the page, not to WDA: its own lock, the device lock only to look up the device
Lane::Web => {
- let mut slot = match acquire(&self.web, &mut ctx.gone).await {
+ let mut slot = match self.lock_admitted(&self.web, &req, admission, &mut queued_at, &mut ctx.gone).await
+ {
Ok(s) => s,
Err(r) => return r,
};
@@ -858,6 +899,18 @@ impl Daemon {
if ctx.gone.as_mut().is_some_and(|g| g.try_recv().is_ok()) {
return cancelled();
}
+ loop {
+ match self.tasks.still(admission, &req) {
+ crate::tasks::Still::Admitted => break,
+ crate::tasks::Still::Refused(r) => return r,
+ crate::tasks::Still::Wait(t) => {
+ if let Err(r) = t.wait_running(&mut ctx.gone).await {
+ return r;
+ }
+ queued_at = Instant::now();
+ }
+ }
+ }
let device = self.inner.lock().await.device.clone();
if let Err(r) = admit(&req, queued_at, &ctx, device.as_ref().map(|d| d.udid.as_str())) {
return r;
@@ -875,7 +928,8 @@ impl Daemon {
Lane::Device => {}
}
- let mut g = match acquire(&self.inner, &mut ctx.gone).await {
+ // still let through now that it holds the lock: the task may have been paused or taken over meanwhile
+ let mut g = match self.lock_admitted(&self.inner, &req, admission, &mut queued_at, &mut ctx.gone).await {
Ok(g) => g,
Err(r) => return r,
};
diff --git a/crates/ictl-daemon/src/maintenance.rs b/crates/ictl-daemon/src/maintenance.rs
index 669e5f3..473e14d 100644
--- a/crates/ictl-daemon/src/maintenance.rs
+++ b/crates/ictl-daemon/src/maintenance.rs
@@ -147,6 +147,21 @@ mod tests {
shared_in(&dir).unwrap();
std::fs::remove_dir_all(dir).unwrap();
}
+ /// A lock that is free again: another test spawning a process meanwhile (procs.rs) briefly holds a copy of the
+ /// dropped descriptor in the child until it execs, and the lock with it
+ fn once_free(dir: &Path, operation: libc::c_int) -> File {
+ for _ in 0..100 {
+ match lock(dir, operation) {
+ Ok(f) => return f,
+ Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
+ std::thread::sleep(std::time::Duration::from_millis(20))
+ }
+ Err(e) => panic!("{e}"),
+ }
+ }
+ panic!("still locked after 2 s");
+ }
+
#[test]
fn readers_exclude_maintenance_and_resume_after_it() {
let dir = std::env::temp_dir().join(format!("ictl-lease-{}", std::process::id()));
@@ -156,10 +171,10 @@ mod tests {
drop(client);
assert!(lock(&dir, libc::LOCK_EX).is_err());
drop(signing);
- let update = lock(&dir, libc::LOCK_EX).unwrap();
+ let update = once_free(&dir, libc::LOCK_EX);
assert!(lock(&dir, libc::LOCK_SH).is_err());
drop(update);
- lock(&dir, libc::LOCK_SH).unwrap();
+ once_free(&dir, libc::LOCK_SH);
std::fs::remove_dir_all(dir).unwrap();
}
}
diff --git a/crates/ictl-daemon/src/tasks.rs b/crates/ictl-daemon/src/tasks.rs
index c597f85..edcc2cc 100644
--- a/crates/ictl-daemon/src/tasks.rs
+++ b/crates/ictl-daemon/src/tasks.rs
@@ -126,6 +126,21 @@ pub struct Task {
changed: Notify,
}
+/// [`Tasks::still`]: whether an admitted request may go on once it holds its lock
+pub enum Still {
+ Admitted,
+ /// The task's request waits for it to run again (then is checked again)
+ Wait(Arc<Task>),
+ Refused(Response),
+}
+
+fn look_first() -> Response {
+ refuse(ictl_l10n::tr!(
+ "用户刚才操作过手机,界面可能已经变了:先用 iphone_screenshot 或 iphone_list_elements 重新看一遍,再决定下一步",
+ "The user acted on the phone, so the screen may have changed: look again with iphone_screenshot or iphone_list_elements before the next step"
+ ))
+}
+
/// How [`Tasks::admit`] lets a request through
pub enum Admission {
/// No task is involved
@@ -157,7 +172,7 @@ fn ended_message() -> &'static str {
}
/// Requests that show the agent the screen: after one, it may act again ([`TaskState::recheck`])
-fn observes(req: &Request) -> bool {
+pub(crate) fn observes(req: &Request) -> bool {
matches!(req, Request::Screenshot { .. } | Request::ListElements { .. } | Request::WaitFor { .. })
}
@@ -402,8 +417,13 @@ impl Task {
);
}
+ /// The agent saw the screen (an observation that succeeded): it may act again ([`TaskState::recheck`])
+ pub fn observed(&self) {
+ self.lock().recheck = false;
+ }
+
/// Holds until the task runs; `Err` when it ended or the caller went away
- async fn wait_running(&self, gone: &mut Option<oneshot::Receiver<()>>) -> Result<bool, Response> {
+ pub(crate) async fn wait_running(&self, gone: &mut Option<oneshot::Receiver<()>>) -> Result<bool, Response> {
let mut waited = false;
loop {
let notified = self.changed.notified();
@@ -499,12 +519,20 @@ impl Task {
self.emit(&mut st, "step", d);
}
- /// Shows a confirmation on the page and holds until the user answers, the task ends or the caller goes away
+ /// Shows a confirmation on the page and holds until the user answers, the task ends or the caller goes away.
+ /// Asks only while the task runs, like a step: a pause or takeover holds the question (it doesn't replace the
+ /// user's pause), and so does another question (one at a time, each answered on its own)
async fn ask_user(&self, action: &str, detail: &str, gone: &mut Option<oneshot::Receiver<()>>) -> Asked {
- let (mut rx, id) = {
+ let (mut rx, id) = loop {
+ if self.wait_running(gone).await.is_err() {
+ return if self.lock().status.active() { Asked::Gone } else { Asked::Ended };
+ }
let mut st = self.lock();
- if !st.status.active() {
- return Asked::Ended;
+ match st.status {
+ Status::Running => {}
+ Status::Ended(_) => return Asked::Ended,
+ // paused, taken over or asked again between the wake-up and the lock: wait again
+ _ => continue,
}
let args = json!({"action": action, "detail": detail});
let id = self.begin_step(&mut st, "iphone_confirm", &args, None, "waiting");
@@ -512,14 +540,15 @@ impl Task {
let (tx, rx) = oneshot::channel();
st.confirm = Some((id, tx));
self.set_status(&mut st, Status::Waiting);
- (rx, id)
+ break (rx, id);
};
+ // a sender dropped without an answer isn't the user saying no: nothing to carry out either way
let answer = match gone {
Some(g) => tokio::select! {
- a = &mut rx => Some(a.unwrap_or(false)),
+ a = &mut rx => a.ok(),
_ = g => None,
},
- None => Some(rx.await.unwrap_or(false)),
+ None => rx.await.ok(),
};
let mut st = self.lock();
st.last = None;
@@ -543,7 +572,7 @@ impl Task {
),
};
self.emit(&mut st, "step", json!({"id": id, "status": status, "result": result}));
- if !ended {
+ if !ended && st.status == Status::Waiting {
self.set_status(&mut st, Status::Running);
}
asked
@@ -698,20 +727,29 @@ impl Tasks {
let mut list = Vec::new();
if let Some(dir) = &dir {
let _ = std::fs::create_dir_all(dir);
- let mut files: Vec<(u64, PathBuf)> = std::fs::read_dir(dir)
- .into_iter()
- .flatten()
- .flatten()
- .map(|e| e.path())
- .filter(|p| p.extension().is_some_and(|x| x == "jsonl"))
- .filter_map(|p| Some((first_started(&p)?, p)))
- .collect();
+ let mut files: Vec<(u64, PathBuf)> = Vec::new();
+ for p in std::fs::read_dir(dir).into_iter().flatten().flatten().map(|e| e.path()) {
+ if !p.extension().is_some_and(|x| x == "jsonl") {
+ continue;
+ }
+ match first_started(&p) {
+ Some(t) => files.push((t, p)),
+ // its first line was cut short (a power cut while it was written): no task to show, and left
+ // alone it would never count towards the limit, so never go
+ None => drop_unreadable(&p),
+ }
+ }
files.sort();
let extra = files.len().saturating_sub(KEEP);
for (_, p) in files.drain(..extra) {
let _ = std::fs::remove_file(p);
}
- list.extend(files.into_iter().filter_map(|(_, p)| restore(&p)).map(Arc::new));
+ for (_, p) in files {
+ match restore(&p) {
+ Some(t) => list.push(Arc::new(t)),
+ None => drop_unreadable(&p),
+ }
+ }
}
Self { dir, list: Mutex::new(list) }
}
@@ -845,22 +883,38 @@ impl Tasks {
)));
}
let waited = task.wait_running(gone).await?;
- {
- let mut st = task.lock();
- if acts(req) && st.recheck {
- return Err(refuse(ictl_l10n::tr!(
- "用户刚才操作过手机,界面可能已经变了:先用 iphone_screenshot 或 iphone_list_elements 重新看一遍,再决定下一步",
- "The user acted on the phone, so the screen may have changed: look again with iphone_screenshot or iphone_list_elements before the next step"
- )));
- }
- if observes(req) {
- st.recheck = false;
- }
+ if acts(req) && task.lock().recheck {
+ return Err(look_first());
}
*expect_udid = Some(task.udid.clone());
return Ok((Admission::Actor(task), waited));
}
- let Some(task) = self.active() else { return Ok((Admission::Free, false)) };
+ self.admit_other(req).map(|a| (a, false))
+ }
+
+ /// [`Self::admit`] again once the request holds its lock (it may have queued for it a while): the task may have
+ /// been paused or taken over, or handed back, meanwhile. A request of the task waits for it to run again
+ pub fn still(&self, admission: &Admission, req: &Request) -> Still {
+ match admission {
+ Admission::Actor(task) => {
+ let st = task.lock();
+ match st.status {
+ Status::Running if acts(req) && st.recheck => Still::Refused(look_first()),
+ Status::Running => Still::Admitted,
+ Status::Ended(_) => Still::Refused(refuse(ended_message())),
+ _ => Still::Wait(task.clone()),
+ }
+ }
+ Admission::Free | Admission::Supervisor(_) => match self.admit_other(req) {
+ Ok(_) => Still::Admitted,
+ Err(r) => Still::Refused(r),
+ },
+ }
+ }
+
+ /// [`Self::admit`] for a request without a task's token
+ fn admit_other(&self, req: &Request) -> Result<Admission, Response> {
+ let Some(task) = self.active() else { return Ok(Admission::Free) };
if matches!(req, Request::SelectDevice { .. }) {
return Err(refuse(&ictl_l10n::trf!(
"任务「{}」进行中,不能切换设备;先停止它",
@@ -869,14 +923,14 @@ impl Tasks {
)));
}
if !acts(req) || matches!(req, Request::Touch { phase: TouchPhase::Up, .. }) {
- return Ok((Admission::Free, false));
+ return Ok(Admission::Free);
}
let mut st = task.lock();
if st.status == Status::Takeover {
// the agent looks again before its next action
st.recheck = true;
drop(st);
- return Ok((Admission::Supervisor(task), false));
+ return Ok(Admission::Supervisor(task));
}
Err(refuse(&ictl_l10n::trf!(
"AI 任务「{}」正在操作这台设备({})。要自己操作,先接管或停止这个任务",
@@ -1014,6 +1068,18 @@ fn append(file: &Path, e: &TaskEvent) {
}
}
+fn drop_unreadable(file: &Path) {
+ tracing::warn!(
+ "{}",
+ ictl_l10n::log_trf!(
+ "任务日志读不出来,删掉:{}",
+ "A task log can't be read, so it was removed: {}",
+ file.display()
+ )
+ );
+ let _ = std::fs::remove_file(file);
+}
+
fn read_events(file: &Path) -> Vec<TaskEvent> {
let Ok(text) = std::fs::read_to_string(file) else { return Vec::new() };
text.lines().filter_map(|l| serde_json::from_str::<TaskEvent>(l).ok()).collect()
@@ -1253,9 +1319,34 @@ mod tests {
assert!(admit(&ts, &Request::Status, Some(&t.token)).await.is_ok(), "status isn't acting");
let look = Request::ListElements { filter: String::new(), limit: 10, max_age_ms: 0 };
assert!(admit(&ts, &look, Some(&t.token)).await.is_ok());
+ assert!(admit(&ts, &tap(), Some(&t.token)).await.is_err(), "a look let through isn't a look that worked");
+ t.observed();
assert!(admit(&ts, &tap(), Some(&t.token)).await.is_ok());
}
+ /// A request let through before the user paused, took over or handed back is checked again once it holds its lock
+ #[tokio::test]
+ async fn an_admitted_request_is_checked_again_once_it_has_its_lock() {
+ let ts = tasks();
+ let t = open(&ts);
+ let (agent, _) = admit(&ts, &tap(), Some(&t.token)).await.unwrap();
+ assert!(matches!(ts.still(&agent, &tap()), Still::Admitted));
+ t.control("pause", None, false, None).unwrap();
+ assert!(matches!(ts.still(&agent, &tap()), Still::Wait(_)), "waits for the task to run again");
+ t.control("takeover", None, false, None).unwrap();
+ assert!(matches!(ts.still(&agent, &tap()), Still::Wait(_)));
+ let (user, _) = admit(&ts, &tap(), None).await.unwrap();
+ assert!(matches!(user, Admission::Supervisor(_)));
+ t.control("handback", None, false, None).unwrap();
+ assert!(matches!(ts.still(&user, &tap()), Still::Refused(_)), "the user's tap after handing back");
+ assert!(matches!(ts.still(&agent, &tap()), Still::Refused(_)), "the agent looks first");
+ let shot = Request::Screenshot { region: None };
+ assert!(matches!(ts.still(&agent, &shot), Still::Admitted));
+ t.end(End::Cancelled, "");
+ assert!(matches!(ts.still(&agent, &shot), Still::Refused(_)));
+ assert!(matches!(ts.still(&user, &tap()), Still::Admitted), "no task any more");
+ }
+
/// The agent may not answer its own questions or resume itself; it may give up
#[tokio::test]
async fn the_agent_cant_control_its_own_task() {
@@ -1361,6 +1452,54 @@ mod tests {
assert_eq!(t.info().state, "rejected");
}
+ fn ask(ts: &Arc<Tasks>, t: &Task) -> tokio::task::JoinHandle<Response> {
+ let (ts, token) = (ts.clone(), t.token.clone());
+ tokio::spawn(async move {
+ let req = Request::TaskConfirm { action: "发送消息".into(), detail: "给妈妈".into() };
+ ts.handle(&req, Some(&token), None, &mut None).await.unwrap()
+ })
+ }
+
+ /// A question doesn't replace the user's pause or takeover: it waits until the task runs again
+ #[tokio::test]
+ async fn a_question_waits_while_the_user_paused_or_took_over() {
+ let ts = Arc::new(tasks());
+ let t = open(&ts);
+ t.control("pause", None, false, None).unwrap();
+ let asked = ask(&ts, &t);
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ assert_eq!(t.info().state, "paused");
+ t.control("takeover", None, false, None).unwrap();
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ assert_eq!(t.info().state, "takeover");
+ assert!(admit(&ts, &tap(), None).await.is_ok(), "the user still acts while taken over");
+ t.control("handback", None, false, None).unwrap();
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ assert_eq!(t.info().state, "waiting");
+ t.control("confirm", None, true, None).unwrap();
+ assert!(matches!(asked.await.unwrap(), Response::Text { .. }));
+ assert_eq!(t.info().state, "running");
+ }
+
+ /// Two questions at once are asked one after the other, each answered on its own
+ #[tokio::test]
+ async fn two_questions_at_once_are_asked_in_turn() {
+ let ts = Arc::new(tasks());
+ let t = open(&ts);
+ let (a, b) = (ask(&ts, &t), ask(&ts, &t));
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ assert_eq!(t.info().state, "waiting");
+ t.control("confirm", None, true, None).unwrap();
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ assert_eq!(t.info().state, "waiting", "the second question, now");
+ t.control("confirm", None, true, None).unwrap();
+ assert!(matches!(a.await.unwrap(), Response::Text { .. }));
+ assert!(matches!(b.await.unwrap(), Response::Text { .. }));
+ assert_eq!(t.info().state, "running");
+ t.finish(true, "done");
+ assert_eq!(t.info().state, "completed", "nobody said no");
+ }
+
#[tokio::test]
async fn steps_get_thoughts_results_and_marks() {
let ts = tasks();
@@ -1575,4 +1714,25 @@ mod tests {
assert_eq!(std::fs::read_dir(&dir).unwrap().count(), KEEP);
std::fs::remove_dir_all(dir).unwrap();
}
+
+ /// A log cut short (power cut) is removed instead of lying there forever, outside the limit
+ #[test]
+ fn unreadable_logs_are_removed() {
+ let dir = std::env::temp_dir().join(format!("ictl-tasks-bad-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ std::fs::write(dir.join("cut.jsonl"), "{\"t\": 1, \"event\": \"ta").unwrap();
+ std::fs::write(dir.join("empty.jsonl"), "").unwrap();
+ std::fs::write(dir.join("notes.txt"), "not a log").unwrap();
+ let ts = Tasks::load(Some(dir.clone()));
+ open(&ts).end(End::Completed, "");
+ drop(ts);
+ let ts = Tasks::load(Some(dir.clone()));
+ assert_eq!(ts.infos().len(), 1);
+ let mut left: Vec<_> = std::fs::read_dir(&dir).unwrap().flatten().map(|e| e.file_name()).collect();
+ left.sort();
+ assert_eq!(left.len(), 2, "{left:?}");
+ assert!(left.iter().any(|n| n == "notes.txt"), "only task logs are touched");
+ std::fs::remove_dir_all(dir).unwrap();
+ }
}