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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ What changed in each release, one line per change. Versions follow [Semantic Ver
- Switching back to a phone made ready in the background takes effect at once even when the daemon was busy at that moment; it could wait 10 seconds. The daemon serves at most 256 clients at once; more wait their turn (#197).
- AI tasks limited to some apps: an action is checked again once it has the phone, in case another app came to the front meanwhile, and `iphone_web_eval` is checked against the app that shows the page (#197).
- `iphone_tap_element`'s scroll search and `iphone_wait_for` stop as soon as the task is paused or taken over or the caller goes away, instead of holding the phone until they time out; the daemon also limits a scroll search to 15 swipes (#197).
- The control page's server refuses malformed requests, so a crafted link can no longer send a browser from it to another site, and it no longer waits for request bodies from someone who isn't logged in (#196).
- AI tasks from the control page: a task whose text starts with `--` is no longer taken as an option by the agent, and the agent no longer gets the task's token on its command line or notification keys in its environment (#196).
- A malformed video report from a page no longer freezes its picture (#196).
- iOS 17–18: the developer disk image is mounted the way these versions need, so WebDriverAgent starts on them again (#186).
- Times in `status`, `doctor` and the event log are shown in local time with the time zone; they were UTC without saying so (#184).
- Errors from `iphone-control update`, `service` and the update panel on the control page follow the chosen language; they were always in English (#184).
Expand Down
3 changes: 3 additions & 0 deletions CHANGELOG.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@
- 切回一台在后台准备好的手机时,即使守护进程当时正忙也马上生效,之前可能要等 10 秒;守护进程同时最多服务 256 个客户端,更多的排队等候(#197)。
- 限定了 App 范围的 AI 任务:操作拿到手机后再查一次前台 App,以防期间换了别的 App;`iphone_web_eval` 按显示页面的 App 检查(#197)。
- `iphone_tap_element` 的边滑边找和 `iphone_wait_for` 在任务暂停、被接管或调用方离开时立刻停下,不再占着手机等到超时;守护进程也把边滑边找限制在 15 次以内(#197)。
- 控制台服务拒绝格式不对的请求,精心构造的链接不能再把浏览器从控制台跳到别的网站;也不再为没登录的人等请求体(#196)。
- 控制台上的 AI 任务:以 `--` 开头的任务描述不再被 agent 当成选项;agent 的命令行里不再有任务口令,环境里也没有通知密钥(#196)。
- 页面发来格式不对的视频回执时,画面不再卡住(#196)。
- iOS 17–18:开发者镜像按这些版本需要的方式挂载,WebDriverAgent 又能在上面启动了(#186)。
- `status`、`doctor` 和事件日志里的时间改为本地时间并标明时区,之前显示的是 UTC 却没有说明(#184)。
- `iphone-control update`、`service` 和控制台更新面板里的报错跟随界面语言,之前总是英文(#184)。
Expand Down
169 changes: 147 additions & 22 deletions apps/iphone-control/src/agent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,22 +75,74 @@ pub struct Agents {
/// This program, for the agent's MCP server
exe: PathBuf,
socket: PathBuf,
/// Where the agent works
workdir: PathBuf,
/// The tasks' token files ([`TokenFile`]), beside the working directory rather than in it
tokens: PathBuf,
/// The process groups of the agents running now ([`Self::stop_all`])
running: std::sync::Mutex<std::collections::HashSet<u32>>,
}

/// Takes an agent's process group off [`Agents::running`] when its run ends
struct Running<'a>(&'a Agents, Option<u32>);
/// Takes an agent's process group off [`Agents::running`] when its run ends. A run that ends before the agent was
/// waited for (an error reading its output) stops the group first, so nothing of it is left running; once it was
/// waited for (`waited`), the group isn't signalled any more: its id may be another process's by then
struct Running<'a> {
agents: &'a Agents,
pid: Option<u32>,
waited: bool,
}

impl Drop for Running<'_> {
fn drop(&mut self) {
if let Some(pid) = self.1 {
self.0.running.lock().unwrap_or_else(|p| p.into_inner()).remove(&pid);
if let Some(pid) = self.pid {
if !self.waited {
crate::procgroup::stop(pid);
}
self.agents.running.lock().unwrap_or_else(|p| p.into_inner()).remove(&pid);
}
}
}

/// The task's token for the agent's MCP server, in a file of its own (0600, in the agent's private directory) instead
/// of the command line, which every user on the machine can read (`ps`). Removed when the run ends
struct TokenFile(PathBuf);

impl TokenFile {
/// In `dir` (the private directory's `tokens`, not the agent's working directory), under a name no other run of
/// this process has (a counter: clocks with microseconds only gave two runs the same name)
fn new(dir: &Path, token: &str) -> std::io::Result<Self> {
use std::io::Write;
use std::os::unix::fs::OpenOptionsExt;
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let path = dir.join(format!("task-{}-{n}.token", std::process::id()));
let mut f = std::fs::OpenOptions::new().write(true).create_new(true).mode(0o600).open(&path)?;
// removed again if the write fails
let file = Self(path);
f.write_all(token.as_bytes())?;
Ok(file)
}
}

impl Drop for TokenFile {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
}

/// Variables of this program's settings that the agent has no use for and shouldn't see: notification keys, the
/// viewer's login (the agent's MCP server reads the settings file itself, so nothing it needs is lost)
const HIDDEN_FROM_AGENT: [&str; 6] = [
ictl_daemon::protocol::env::TG_BOT_TOKEN,
ictl_daemon::protocol::env::BARK_KEY,
ictl_daemon::protocol::env::VIEWER_TOKEN,
ictl_daemon::protocol::env::TASK_TOKEN,
// the agent works on this machine's phone: its MCP server mustn't be sent to another viewer (with the token file
// it would refuse to start)
ictl_daemon::protocol::env::URL,
ictl_daemon::protocol::env::CA,
];

/// The agent's working directory under `base`: this user's own (0700, not a link). The agent reads what is there
/// (`CLAUDE.md`, `AGENTS.md`, `.claude/`), so in a shared directory such as `/tmp` a name made by someone else first
/// isn't used: then one made just now, which nobody else can have
Expand Down Expand Up @@ -125,14 +177,30 @@ fn private_dir(base: &Path) -> std::io::Result<PathBuf> {
unreachable!("returns from the loop")
}

/// A directory of our own inside the private one (which nobody else can write to): made 0700 if it isn't there
fn sub_dir(private: &Path, name: &str) -> std::io::Result<PathBuf> {
use std::os::unix::fs::{DirBuilderExt, PermissionsExt};
let dir = private.join(name);
match std::fs::DirBuilder::new().mode(0o700).create(&dir) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists && std::fs::symlink_metadata(&dir)?.is_dir() => {
std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700))?;
}
Err(e) => return Err(e),
}
Ok(dir)
}

impl Agents {
pub fn new(socket: &Path) -> anyhow::Result<Arc<Self>> {
let base = std::env::var_os("XDG_RUNTIME_DIR").map(PathBuf::from).filter(|p| p.is_absolute());
let workdir = private_dir(&base.unwrap_or_else(std::env::temp_dir))?;
let private = private_dir(&base.unwrap_or_else(std::env::temp_dir))?;
// the agent works in `work`; the tasks' tokens are kept beside it, not in what it works on
Ok(Arc::new(Self {
exe: std::env::current_exe()?,
socket: socket.to_path_buf(),
workdir,
workdir: sub_dir(&private, "work")?,
tokens: sub_dir(&private, "tokens")?,
running: Default::default(),
}))
}
Expand Down Expand Up @@ -239,9 +307,13 @@ impl Agents {
prompt: &str,
apps: &[String],
) -> anyhow::Result<()> {
let token_file = TokenFile::new(&self.tokens, token)?;
let mut cmd = tokio::process::Command::new(program);
cmd.args(self.agent_args(backend, token, prompt, apps))
.current_dir(&self.workdir)
cmd.args(self.agent_args(backend, &token_file.0, prompt, apps));
for k in HIDDEN_FROM_AGENT {
cmd.env_remove(k);
}
cmd.current_dir(&self.workdir)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
Expand All @@ -257,14 +329,15 @@ impl Agents {
if let Some(pid) = pid {
self.running.lock().unwrap_or_else(|p| p.into_inner()).insert(pid);
}
let _running = Running(self, pid);
let mut running = Running { agents: self, pid, waited: false };
let stdout = child.stdout.take().ok_or_else(|| anyhow::anyhow!("no stdout"))?;
let stderr = child.stderr.take().ok_or_else(|| anyhow::anyhow!("no stderr"))?;
let errs = tokio::spawn(async move {
let mut tail: Vec<String> = Vec::new();
let mut lines = BufReader::new(stderr).lines();
while let Ok(Some(l)) = lines.next_line().await {
tail.push(l);
// by bytes like stdout: stopping at a line that isn't UTF-8 would leave the pipe full and the agent stuck
let mut lines = BufReader::new(stderr).split(b'\n');
while let Ok(Some(l)) = lines.next_segment().await {
tail.push(String::from_utf8_lossy(&l).trim_end_matches('\r').to_owned());
if tail.len() > 20 {
tail.remove(0);
}
Expand All @@ -273,12 +346,13 @@ impl Agents {
});
let (mut summary, mut failure, mut last_text) = (None, None, None);
let mut ended = false;
let mut lines = BufReader::new(stdout).lines();
// by bytes: a line that isn't UTF-8 (an agent printing raw output) is skipped, not the end of reading
let mut lines = BufReader::new(stdout).split(b'\n');
loop {
tokio::select! {
line = lines.next_line() => {
line = lines.next_segment() => {
let Some(line) = line? else { break };
let Ok(v) = serde_json::from_str::<Value>(&line) else { continue };
let Ok(v) = serde_json::from_slice::<Value>(&line) else { continue };
match parse_line(backend, &v) {
Some(Out::Thought(t)) => {
last_text = Some(t.clone());
Expand All @@ -301,6 +375,7 @@ impl Agents {
}
}
let status = child.wait().await?;
running.waited = true;
let tail = errs.await.unwrap_or_default();
if ended {
return Ok(());
Expand All @@ -323,21 +398,24 @@ impl Agents {
Ok(())
}

fn agent_args(&self, backend: Backend, token: &str, prompt: &str, apps: &[String]) -> Vec<String> {
/// The agent's command line. The task's token isn't on it (every user can read a command line): the MCP server
/// reads it from `token_file`. The prompt comes last, after `--`, so whatever it starts with is never taken for
/// an option (a prompt of `--permission-mode=bypassPermissions` would otherwise lift the agent's limits)
fn agent_args(&self, backend: Backend, token_file: &Path, prompt: &str, apps: &[String]) -> Vec<String> {
let guide = guidance(apps);
let exe = self.exe.to_string_lossy().into_owned();
let socket = self.socket.to_string_lossy().into_owned();
let token_file = token_file.to_string_lossy().into_owned();
let mut env = Map::new();
env.insert(protocol::TASK_TOKEN_ENV.into(), token.into());
// the agent's tools answer in the task's language (this runs in its scope, see `start`)
env.insert(ictl_daemon::protocol::env::LANG.into(), ictl_l10n::lang().code().into());
let s = |v: &str| v.to_owned();
match backend {
Backend::Claude => {
let mcp = json!({"mcpServers": {"iphone": {"command": exe, "args": ["--socket", socket, "mcp"], "env": env}}});
let args = ["--socket", &socket, "mcp", "--task-token-file", &token_file];
let mcp = json!({"mcpServers": {"iphone": {"command": exe, "args": args, "env": env}}});
vec![
s("-p"),
s(prompt),
s("--output-format"),
s("stream-json"),
s("--verbose"),
Expand All @@ -354,6 +432,8 @@ impl Agents {
s("--no-session-persistence"),
s("--append-system-prompt"),
guide.clone(),
s("--"),
s(prompt),
]
}
Backend::Codex => {
Expand All @@ -373,7 +453,14 @@ impl Agents {
s("-c"),
format!("mcp_servers.iphone.command={}", q(&exe)),
s("-c"),
format!("mcp_servers.iphone.args=[{},{},{}]", q("--socket"), q(&socket), q("mcp")),
format!(
"mcp_servers.iphone.args=[{},{},{},{},{}]",
q("--socket"),
q(&socket),
q("mcp"),
q("--task-token-file"),
q(&token_file)
),
s("-c"),
format!("mcp_servers.iphone.env={{{env_toml}}}"),
s("-c"),
Expand All @@ -384,6 +471,7 @@ impl Agents {
s("mcp_servers.iphone.default_tools_approval_mode=\"approve\""),
s("-c"),
s("suppress_unstable_features_warning=true"),
s("--"),
format!("{guide}\n\n{}{prompt}", ictl_l10n::tr!("任务:", "Task: ")),
]
}
Expand Down Expand Up @@ -510,13 +598,50 @@ mod tests {
let agents = Agents::new(Path::new("/nonexistent/ctl.sock")).unwrap();
let scoped = v(&["com.apple.Preferences", "com.apple.mobiletimer"]);
for backend in Backend::ALL {
let plain = agents.agent_args(backend, "t", "看看设置", &[]).join("\n");
let limited = agents.agent_args(backend, "t", "看看设置", &scoped).join("\n");
let plain = agents.agent_args(backend, Path::new("/x/t.token"), "看看设置", &[]).join("\n");
let limited = agents.agent_args(backend, Path::new("/x/t.token"), "看看设置", &scoped).join("\n");
assert!(!plain.contains("com.apple.Preferences"), "{backend:?}: no scope, nothing about one");
assert!(limited.contains("com.apple.Preferences、com.apple.mobiletimer"), "{backend:?}");
}
}

/// Whatever a prompt starts with, it is the prompt: it comes last, after `--`. The task's token isn't on the
/// command line (every user on the machine can read it), only the file it is in
#[test]
fn a_prompt_is_never_an_option_and_the_token_never_on_the_command_line() {
let agents = Agents::new(Path::new("/nonexistent/ctl.sock")).unwrap();
let hostile = "--permission-mode=bypassPermissions";
for backend in Backend::ALL {
let args = agents.agent_args(backend, Path::new("/x/t.token"), hostile, &[]);
let dashes = args.iter().position(|a| a == "--").expect("an end of options");
assert_eq!(dashes, args.len() - 2, "{backend:?}: the prompt alone follows it");
assert!(args.last().unwrap().contains(hostile), "{backend:?}");
assert!(!args[..dashes].iter().any(|a| a.contains(hostile)), "{backend:?}: not before it");
let all = args.join(" ");
assert!(all.contains("--task-token-file") && all.contains("/x/t.token"), "{backend:?}");
assert!(!all.contains(protocol::TASK_TOKEN_ENV), "{backend:?}: no token variable on the command line");
}
let dir = std::env::temp_dir().join(format!("ictl-agent-token-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let f = TokenFile::new(&dir, "secret").unwrap();
let path = f.0.clone();
use std::os::unix::fs::MetadataExt;
assert_eq!(std::fs::metadata(&path).unwrap().mode() & 0o777, 0o600);
assert_eq!(std::fs::read_to_string(&path).unwrap(), "secret");
drop(f);
assert!(!path.exists(), "removed with the run");
// two at once never share a name
let (a, b) = (TokenFile::new(&dir, "a").unwrap(), TokenFile::new(&dir, "b").unwrap());
assert_ne!(a.0, b.0);
drop((a, b));
std::fs::remove_dir_all(dir).unwrap();
// kept beside the agent's working directory, not in what it works on; both its own
assert!(!agents.tokens.starts_with(&agents.workdir) && !agents.workdir.starts_with(&agents.tokens));
for d in [&agents.tokens, &agents.workdir] {
assert_eq!(std::fs::metadata(d).unwrap().mode() & 0o777, 0o700, "{}", d.display());
}
}

#[test]
fn the_agent_works_in_a_directory_of_its_own() {
use std::os::unix::fs::{MetadataExt, PermissionsExt};
Expand Down
Loading
Loading