Control a real USB-connected iPhone from Linux (no Mac, no paid developer account) and expose it to AI agents as MCP tools
Rust ai-agentautomationclaudeclaude-codedockeriosiphonelinuxmcpmcp-servermodel-context-protocolrustwebdriveragent
feat(cli): navigate setup menus with the keyboard and generate shell completions (#71)
MSKd435afc58d6a
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex f58e76f..d0adde8 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -51,7 +51,12 @@ jobs:run: for p in ictl-l10n ictl-webinspector ictl-device ictl-wda ictl-sign ictl-unlock ictl-daemon ictl-mcp ictl-protocol iphone-control; do cargo fmt -p $p -- --check; done# --all-features:默认不编的 debug-cmds(调试子命令)也要能编译- run: cargo clippy --workspace --all-targets --all-features --locked -- -D warnings+ # check_fish_candidates 的候选词断言需要真正的 fish;缺了它该段会被静默跳过+ - name: Install fish for completion tests+ run: sudo apt-get update && sudo apt-get install -y fish- run: cargo test --workspace --all-features --locked+ - name: Terminal menus (PTY)+ run: python3 tests/terminal.py --binary target/debug/iphone-control --test-dir target/debug/deps# macOS(Apple Silicon)上能编译、测试通过;格式和平台无关,上面已经查过macos:@@ -68,6 +73,8 @@ jobs:# --all-features:默认不编的 debug-cmds(调试子命令)也要能编译- run: cargo clippy --workspace --all-targets --all-features --locked -- -D warnings- run: cargo test --workspace --all-features --locked+ - name: Terminal menus (PTY)+ run: python3 tests/terminal.py --binary target/debug/iphone-control --test-dir target/debug/deps# 安装方式能用:deb 打得出、装得上;用临时签名发行包校验 install.sh;Homebrew formula 能生成packages:diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 323c7d5..a236c67 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,8 @@ All notable changes to this project are documented here. The format is based on### Added+- Navigate setup menus with arrow keys, confirm with Enter, or cancel with Esc. Number selection remains available, and basic terminals keep the line-by-line prompts.+- Generate Bash, Zsh and Fish completion scripts with `iphone-control completions <shell>`, without starting the daemon or accessing a device.- On the control page, a task can be limited to some apps before it starts (the App button next to the agent): in any other app each step waits for you, as with `task run --app`. The task card shows the scope, and running a task again keeps it.- AI tasks for any agent platform: `iphone-control task run -- <command>` runs a command in a task, and an `iphone-control mcp` it starts takes part (the control page shows its steps and can pause, take over, stop and confirm). `task list`, `task events`, `task pause`/`resume`/`takeover`/`handback`/`stop` and `task approve`/`reject` follow and steer tasks from the command line.- The control page picks up a task in progress: after a reload, and for tasks started elsewhere.diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.mdindex 09ccbfd..ac5c5f8 100644--- a/CHANGELOG.zh-CN.md+++ b/CHANGELOG.zh-CN.md@@ -8,6 +8,8 @@### 新增+- 设置菜单支持方向键选择、Enter 确认和 Esc 取消,保留数字选择;基础终端继续使用逐行提示。+- `iphone-control completions <shell>` 可生成 Bash、Zsh 和 Fish 补全脚本,不启动守护进程、不访问设备。- 控制台上开任务前可以限定 App 范围(Agent 旁边的 App 按钮):到了别的 App,每一步都先等你确认,和 `task run --app` 一样。任务卡片上显示范围,重新执行时沿用。- 任何 agent 平台都能用 AI 任务:`iphone-control task run -- <命令>` 在任务里运行命令,它启动的 `iphone-control mcp` 自动加入任务(控制台能看到每一步,可以暂停、接管、停止、确认)。`task list`、`task events`、`task pause`/`resume`/`takeover`/`handback`/`stop`、`task approve`/`reject` 在命令行里查看和控制任务。- 控制台会接上正在进行的任务:页面刷新后,以及在别处开的任务。diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex aa950dc..50cf2f8 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -18,6 +18,8 @@ You need Rust 1.88 or later (CI pins 1.99.1) and a C compiler. Everything except```bash# --all-features also builds the debug-cmds feature, as CI doescargo test --workspace --all-features --locked+# Linux/macOS PTY regression; temporary settings only, no daemon or device actions+python3 tests/terminal.py --binary target/debug/iphone-control --test-dir target/debug/depscargo clippy --workspace --all-targets --all-features --locked -- -D warnings# vendor/ is upstream code and isn't formatted; check only this repository's packages:for p in ictl-l10n ictl-webinspector ictl-device ictl-wda ictl-sign ictl-unlock ictl-daemon ictl-mcp ictl-protocol iphone-control; do cargo fmt -p $p -- --check; donediff --git a/Cargo.lock b/Cargo.lockindex 67230ce..df5440c 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -733,6 +733,15 @@ dependencies = ["strsim",]+[[package]]+name = "clap_complete"+version = "4.6.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "037e2a1a92236d0aff7e845093f64661d6df4c02c9fcc61a60e9e1d736fa392f"+dependencies = [+ "clap",+]+[[package]]name = "clap_derive"version = "4.6.7"@@ -2277,6 +2286,8 @@ dependencies = ["anyhow","chrono","clap",+ "clap_complete",+ "console","flate2","ictl-daemon","ictl-device",@@ -2295,6 +2306,7 @@ dependencies = ["sha2 0.10.9","tar","tempfile",+ "termion","tokio","tracing","tracing-subscriber",@@ -2795,6 +2807,12 @@ dependencies = ["libm",]+[[package]]+name = "numtoa"+version = "0.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6aa2c4e539b869820a2b82e1aef6ff40aa85e65decdd5185e83fb4b1249cd00f"+[[package]]name = "objc"version = "0.2.7"@@ -4589,6 +4607,16 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "termion"+version = "4.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f44138a9ae08f0f502f24104d82517ef4da7330c35acd638f1f29d3cd5475ecb"+dependencies = [+ "libc",+ "numtoa",+]+[[package]]name = "thiserror"version = "1.0.69"diff --git a/Cargo.toml b/Cargo.tomlindex e6b9988..12aa23a 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -58,6 +58,7 @@ rustls = { version = "=0.23.46", default-features = false, features = ["ring"] }quick-xml = "=0.42.0"image = { version = "=0.25.10", default-features = false, features = ["png", "jpeg"] }clap = { version = "=4.6.7", features = ["derive", "env"] }+clap_complete = "=4.6.11"serde = { version = "=1.0.229", features = ["derive"] }serde_json = "=1.0.154"thiserror = "=2.0.21"diff --git a/apps/iphone-control/Cargo.toml b/apps/iphone-control/Cargo.tomlindex f025774..1ca44b1 100644--- a/apps/iphone-control/Cargo.toml+++ b/apps/iphone-control/Cargo.toml@@ -16,7 +16,10 @@ ictl-device.workspace = trueictl-mcp.workspace = trueictl-sign.workspace = trueictl-wda = { workspace = true, optional = true }-clap.workspace = true+clap = { workspace = true, features = ["string"] }+clap_complete.workspace = true+console = "=0.15.11"+termion = "=4.0.6"tokio.workspace = trueanyhow.workspace = truerustls.workspace = truediff --git a/apps/iphone-control/src/completions.rs b/apps/iphone-control/src/completions.rsnew file mode 100644index 0000000..a8ceae7--- /dev/null+++ b/apps/iphone-control/src/completions.rs@@ -0,0 +1,185 @@+//! 静态 shell 补全:复用实际 Clap 命令树,不读取配置、获取维护锁或接触设备。++use std::ffi::OsString;+use std::io::{self, Write};++use clap::{CommandFactory, ValueEnum};++mod bash;+mod fish;++#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]+pub enum Shell {+ Bash,+ Zsh,+ Fish,+}++/// 只识别入口,不解析普通命令:构建 Clap 会提前缓存语言,必须留到 envfile 加载后。+/// 根选项的值可以恰好是 `completions`,所以不能只搜索这个单词。+pub fn requested(args: impl IntoIterator<Item = OsString>) -> bool {+ let mut args = args.into_iter();+ while let Some(arg) = args.next() {+ if arg == "--data-dir" || arg == "--socket" {+ if args.next().is_none() {+ return false;+ }+ } else if arg.as_encoded_bytes().starts_with(b"--data-dir=") || arg.as_encoded_bytes().starts_with(b"--socket=")+ {+ continue;+ } else if arg == "help" {+ return args.next().is_some_and(|arg| arg == "completions");+ } else {+ return arg == "completions";+ }+ }+ false+}++pub fn write(shell: Shell, output: &mut dyn Write) -> anyhow::Result<()> {+ // Generate in memory: closing a downstream pipe should never panic inside a generator.+ let mut command = public_command(&super::Cli::command());+ command.build();+ let mut script = Vec::new();+ match shell {+ Shell::Zsh => clap_complete::generate(clap_complete::Shell::Zsh, &mut command, "iphone-control", &mut script),+ Shell::Bash => bash::generate(&command, &mut script)?,+ Shell::Fish => fish::generate(&command, &mut script)?,+ }+ match output.write_all(&script) {+ Err(e) if e.kind() == io::ErrorKind::BrokenPipe => Ok(()),+ result => Ok(result?),+ }+}++// Project the public schema before Clap builds its help subcommands. Its stock+// generators otherwise include private scheduler commands and their flags.+fn public_command(source: &clap::Command) -> clap::Command {+ let mut cmd = clap::Command::new(source.get_name().to_owned())+ .visible_aliases(source.get_visible_aliases().map(str::to_owned))+ .args(source.get_arguments().filter(|arg| !arg.is_hide_set()).cloned())+ .subcommands(source.get_subcommands().filter(|cmd| !cmd.is_hide_set()).map(public_command));+ if let Some(about) = source.get_about() {+ cmd = cmd.about(about.clone());+ }+ if let Some(version) = source.get_version() {+ cmd = cmd.version(version.to_owned());+ }+ cmd+}++fn visit(+ cmd: &clap::Command,+ path: &str,+ emit: &mut impl FnMut(&clap::Command, &str) -> io::Result<()>,+) -> io::Result<()> {+ emit(cmd, path)?;+ for child in cmd.get_subcommands() {+ for name in child.get_name_and_visible_aliases() {+ visit(child, &format!("{path} {name}"), emit)?;+ }+ }+ Ok(())+}++fn enum_values(arg: &clap::Arg) -> String {+ arg.get_possible_values().iter().filter(|v| !v.is_hide_set()).map(|v| v.get_name()).collect::<Vec<_>>().join(" ")+}++#[cfg(test)]+mod tests {+ use super::*;+ use clap::Parser;++ #[test]+ fn early_route_recognizes_only_the_completion_command() {+ for args in [+ vec!["completions", "bash"],+ vec!["completions", "--help"],+ vec!["completions", "invalid"],+ vec!["help", "completions"],+ vec!["--data-dir", "somewhere", "--socket=elsewhere", "completions", "fish"],+ vec!["--data-dir=completions", "--socket", "completions", "completions", "zsh"],+ ] {+ assert!(requested(args.iter().map(OsString::from)), "{args:?}");+ }+ for args in [+ vec![],+ vec!["--help"],+ vec!["--data-dir", "completions"],+ vec!["--socket=completions", "status"],+ vec!["login", "completions"],+ vec!["select", "completions"],+ vec!["help", "update"],+ vec!["--unknown", "completions", "bash"],+ vec!["--data-dir"],+ ] {+ assert!(!requested(args.iter().map(OsString::from)), "{args:?}");+ }+ }++ #[test]+ fn all_shells_include_current_commands_options_and_enum_values() {+ for shell in [Shell::Bash, Shell::Zsh, Shell::Fish] {+ let mut script = Vec::new();+ write(shell, &mut script).unwrap();+ let script = String::from_utf8(script).unwrap();+ for word in [+ "iphone-control",+ "completions",+ "update",+ "policy",+ "check",+ "unpin",+ "recover",+ "service",+ "passcode",+ "viewer",+ "data-dir",+ "socket",+ "reconfigure",+ "force",+ "port",+ "json",+ "manual",+ "notify",+ "auto-patch",+ "bash",+ "zsh",+ "fish",+ ] {+ assert!(script.contains(word), "{shell:?} missing {word}");+ }+ assert!(!script.contains("--scheduled"), "{shell:?} exposed a private recovery flag");+ }+ }++ #[test]+ fn completion_argument_is_required_and_restricted_to_supported_shells() {+ for name in ["bash", "zsh", "fish"] {+ assert!(matches!(+ super::super::Cli::try_parse_from(["iphone-control", "completions", name]).unwrap().command,+ Some(super::super::Command::Completions { .. })+ ));+ }+ for args in [+ vec!["iphone-control", "completions"],+ vec!["iphone-control", "completions", "powershell"],+ vec!["iphone-control", "completions", "bash", "extra"],+ ] {+ assert!(super::super::Cli::try_parse_from(args).is_err());+ }+ }++ #[test]+ fn help_and_descriptions_follow_the_selected_language() {+ for (lang, expected) in [(ictl_l10n::Lang::En, "Generate Bash"), (ictl_l10n::Lang::Zh, "生成 Bash")] {+ ictl_l10n::with_lang(lang, || {+ let mut cmd = super::super::Cli::command();+ let help = cmd.find_subcommand_mut("completions").unwrap().render_long_help().to_string();+ assert!(help.contains(expected));+ assert!(help.contains("IPHONE_CONTROL_LANG"));+ });+ }+ }+}diff --git a/apps/iphone-control/src/completions/bash.rs b/apps/iphone-control/src/completions/bash.rsnew file mode 100644index 0000000..724baf9--- /dev/null+++ b/apps/iphone-control/src/completions/bash.rs@@ -0,0 +1,70 @@+use std::io::{self, Write};++use clap::Command;++use super::{enum_values, visit};++/// Each row describes a public command. Consume option values before recognizing+/// subcommands; neither directory names nor hyphens in the binary name change the path.+pub(super) fn generate(root: &Command, script: &mut Vec<u8>) -> io::Result<()> {+ script.extend_from_slice(+ br#"_iphone_control() {+ local path=iphone-control word cur options children takes position=0 pending=0 end=0 i+ local -a values+ COMPREPLY=()+ for ((i=1; i<=COMP_CWORD; i++)); do+ case "$path" in+"#,+ );+ visit(root, root.get_name(), &mut |cmd, path| {+ let mut flags = Vec::new();+ let mut takes = Vec::new();+ for arg in cmd.get_arguments().filter(|arg| !arg.is_positional()) {+ let mut names: Vec<_> =+ arg.get_short_and_visible_aliases().unwrap_or_default().into_iter().map(|s| format!("-{s}")).collect();+ names.extend(arg.get_long_and_visible_aliases().unwrap_or_default().into_iter().map(|s| format!("--{s}")));+ if arg.get_action().takes_values() {+ takes.extend_from_slice(&names);+ }+ flags.extend(names);+ }+ let children =+ cmd.get_subcommands().flat_map(|child| child.get_name_and_visible_aliases()).collect::<Vec<_>>().join(" ");+ let values = cmd+ .get_positionals()+ .map(|arg| format!("[{}]='{}'", arg.get_index().unwrap_or(1) - 1, enum_values(arg)))+ .collect::<Vec<_>>()+ .join(" ");+ writeln!(+ script,+ " '{path}') options='{}'; takes='{}'; children='{children}'; values=({values}) ;;",+ flags.join(" "),+ takes.join(" ")+ )+ })?;+ script.extend_from_slice(br#" esac+ word=${COMP_WORDS[i]}+ if (( i == COMP_CWORD )); then break; fi+ if (( pending )); then pending=0; continue; fi+ if (( !end )); then+ case "$word" in+ --) end=1; continue ;;+ -*) case " $takes " in *" $word "*) pending=1 ;; esac; continue ;;+ esac+ case " $children " in+ *" $word "*) path="$path $word"; position=0; continue ;;+ esac+ fi+ ((position++))+ done+ cur=${COMP_WORDS[COMP_CWORD]}+ # Bash's default completer supplies file names for option values.+ if (( pending )) || [[ $cur == --*=* ]]; then return 0; fi+ if (( end )); then options=""; children=""; fi+ while IFS= read -r word; do COMPREPLY+=("$word"); done < <(compgen -W "$options $children ${values[position]-}" -- "$cur")+ return 0+}+complete -F _iphone_control -o bashdefault -o default iphone-control+"#);+ Ok(())+}diff --git a/apps/iphone-control/src/completions/fish.rs b/apps/iphone-control/src/completions/fish.rsnew file mode 100644index 0000000..c3891b5--- /dev/null+++ b/apps/iphone-control/src/completions/fish.rs@@ -0,0 +1,112 @@+use std::io::{self, Write};++use clap::Command;++use super::{enum_values, visit};++fn quote(value: &str) -> String {+ format!("'{}'", value.replace('\\', "\\\\").replace('\'', "\\'"))+}++pub(super) fn generate(root: &Command, script: &mut Vec<u8>) -> io::Result<()> {+ // Parse each command's own options before deciding which child was selected.+ // The condition also accepts a positional index to stop offering a consumed enum.+ script.extend_from_slice(+ br#"function __fish_iphone_control_at+ set -l expected $argv[1]+ set -l index $argv[2]+ set -l words (commandline -opc)+ set -e words[1]+ set -l cmd iphone-control+ set -l children+ set -l specs+ while true+ switch $cmd+"#,+ );+ visit(root, root.get_name(), &mut |cmd, path| {+ let mut specs = Vec::new();+ for arg in cmd.get_arguments().filter(|arg| !arg.is_positional()) {+ let mut names = Vec::new();+ if let Some(short) = arg.get_short() {+ names.push(short.to_string());+ }+ if let Some(long) = arg.get_long() {+ names.push(long.to_owned());+ }+ let mut spec = names.join("/");+ if arg.get_action().takes_values() {+ spec.push('=');+ }+ specs.push(quote(&spec));+ }+ let children = cmd+ .get_subcommands()+ .flat_map(|child| child.get_name_and_visible_aliases())+ .map(quote)+ .collect::<Vec<_>>()+ .join(" ");+ writeln!(+ script,+ " case {}\n set children {children}\n set specs {}",+ quote(path),+ specs.join(" ")+ )+ })?;+ script.extend_from_slice(+ br#" end+ if set -q specs[1]+ argparse -s $specs -- $words 2>/dev/null; or return 1+ set words $argv+ end+ if not set -q words[1]; or not contains -- "$words[1]" $children+ test "$cmd" = "$expected"; and begin+ test -z "$index"; or test (count $words) -eq "$index"+ end+ return $status+ end+ set cmd "$cmd $words[1]"+ set -e words[1]+ end+end+"#,+ );+ visit(root, root.get_name(), &mut |cmd, path| {+ let cond = format!("__fish_iphone_control_at {}", quote(path));+ let prefix = format!("complete -c iphone-control -n {}", quote(&cond));+ for arg in cmd.get_arguments() {+ if arg.is_positional() {+ let values = enum_values(arg);+ if !values.is_empty() {+ let at = quote(&format!("{cond} {}", arg.get_index().unwrap_or(1) - 1));+ writeln!(script, "complete -c iphone-control -n {at} -f -a {}", quote(&values))?;+ }+ continue;+ }+ write!(script, "{prefix}")?;+ for short in arg.get_short_and_visible_aliases().unwrap_or_default() {+ write!(script, " -s {short}")?;+ }+ for long in arg.get_long_and_visible_aliases().unwrap_or_default() {+ write!(script, " -l {long}")?;+ }+ if arg.get_action().takes_values() {+ write!(script, " -r")?;+ }+ if let Some(help) = arg.get_help() {+ write!(script, " -d {}", quote(&help.to_string()))?;+ }+ writeln!(script)?;+ }+ for sub in cmd.get_subcommands() {+ for name in sub.get_name_and_visible_aliases() {+ write!(script, "{prefix} -f -a {}", quote(name))?;+ if let Some(help) = sub.get_about() {+ write!(script, " -d {}", quote(&help.to_string()))?;+ }+ writeln!(script)?;+ }+ }+ Ok(())+ })+}diff --git a/apps/iphone-control/src/guide.rs b/apps/iphone-control/src/guide.rsindex 1c3a222..9a4f858 100644--- a/apps/iphone-control/src/guide.rs+++ b/apps/iphone-control/src/guide.rs@@ -19,6 +19,29 @@ use ictl_l10n::Lang;use crate::envfile::{self, EnvFile};use crate::{Cli, service};+mod terminal;+use terminal::{ask_yes, choose};++/// Esc dismisses the guide. Ctrl+C also tells the calling shell it was interrupted.+fn finish(result: anyhow::Result<()>) -> anyhow::Result<()> {+ match result {+ Err(error) if error.is::<terminal::Cancelled>() => {+ println!(+ "\n{}",+ ictl_l10n::tr!(+ "已取消当前向导。已保存的设置和已完成的步骤会保留;当前未保存的输入会丢弃。重新运行可继续设置。",+ "Setup cancelled. Saved settings and completed steps are kept; unsaved input is discarded. Run setup again to continue."+ )+ );+ if error.downcast_ref::<terminal::Cancelled>() == Some(&terminal::Cancelled::Interrupt) {+ std::process::exit(128 + libc::SIGINT);+ }+ Ok(())+ }+ other => other,+ }+}+fn marker() -> PathBuf {envfile::config_dir().join("setup-done")}@@ -39,6 +62,8 @@ fn heading(zh: &str, en: &str) {}fn need_terminal() -> anyhow::Result<()> {+ // Keep setup's existing safety boundary: piped answers must not start+ // services or change a device. TERM=dumb still works with line prompts.if !std::io::stdin().is_terminal() {bail!("{}",@@ -51,40 +76,12 @@ fn need_terminal() -> anyhow::Result<()> {Ok(())}-/// `[Y/n]` or `[y/N]`; Enter takes the default-fn ask_yes(prompt: &str, default: bool) -> anyhow::Result<bool> {- let hint = if default { "[Y/n]" } else { "[y/N]" };- loop {- let a = crate::read_line(&format!("{prompt} {hint} "))?.to_ascii_lowercase();- match a.as_str() {- "" => return Ok(default),- "y" | "yes" | "是" | "好" => return Ok(true),- "n" | "no" | "否" | "不" => return Ok(false),- _ => println!("{}", ictl_l10n::tr!(" 输入 y 或 n", " Enter y or n")),- }- }-}--/// A numbered choice; Enter takes `default` (0-based). Returns the index-fn choose(prompt: &str, options: &[&str], default: usize) -> anyhow::Result<usize> {- println!("{prompt}");- for (i, o) in options.iter().enumerate() {- println!(" {}) {o}{}", i + 1, if i == default { ictl_l10n::tr!("(默认)", " (default)") } else { "" });- }- loop {- let a = crate::read_line(ictl_l10n::tr!("选择: ", "Choice: "))?;- if a.is_empty() {- return Ok(default);- }- match a.parse::<usize>() {- Ok(n) if (1..=options.len()).contains(&n) => return Ok(n - 1),- _ => println!("{}", ictl_l10n::trf!(" 输入 1 到 {}", " Enter 1 to {}", options.len())),- }- }-}-/// `iphone-control` with no argumentspub async fn first_run(cli: &Cli) -> anyhow::Result<()> {+ finish(first_run_inner(cli).await)+}++async fn first_run_inner(cli: &Cli) -> anyhow::Result<()> {if done() {return already_set_up(cli).await;}@@ -101,6 +98,10 @@ pub async fn first_run(cli: &Cli) -> anyhow::Result<()> {/// `iphone-control setup [--reconfigure]`pub async fn setup(cli: &Cli, reconfigure: bool) -> anyhow::Result<()> {+ finish(setup_inner(cli, reconfigure).await)+}++async fn setup_inner(cli: &Cli, reconfigure: bool) -> anyhow::Result<()> {need_terminal()?;if !reconfigure {return full(cli).await;@@ -119,10 +120,7 @@ pub async fn setup(cli: &Cli, reconfigure: bool) -> anyhow::Result<()> {let pick = choose(ictl_l10n::tr!("要重新设置哪一项?", "What do you want to set up again?"), &items, 0)?;let mut env = EnvFile::open(&envfile::path())?;match pick {- 0 => {- let _ = std::fs::remove_file(marker());- return full_with(cli, true).await;- }+ 0 => return full_with(cli, true).await,1 => {if language(&mut env, true)? {env.save()?;@@ -168,6 +166,8 @@ async fn full_with(cli: &Cli, force: bool) -> anyhow::Result<()> {let mut env = EnvFile::open(&envfile::path())?;heading("语言 / Language", "Language / 语言");+ // Save these together immediately before applying them to the daemon.+ // Cancelling at the proxy menu leaves the previous settings intact.let mut changed = language(&mut env, force)?;heading("代理", "Proxy");changed |= proxy(&mut env, force)?;diff --git a/apps/iphone-control/src/guide/terminal.rs b/apps/iphone-control/src/guide/terminal.rsnew file mode 100644index 0000000..d836deb--- /dev/null+++ b/apps/iphone-control/src/guide/terminal.rs@@ -0,0 +1,651 @@+//! Small, local menus for the guide. Text and secret input stay with the CLI.+//!+//! termion decodes complete key sequences and restores termios after each read.+//! We never hide the cursor or enter an alternate screen.+use std::fmt;+use std::io::{self, IsTerminal, Read};+use std::os::fd::{AsFd, AsRawFd};+use std::sync::atomic::{AtomicI32, Ordering};+use std::time::{Duration, Instant};++use termion::raw::IntoRawMode;++use console::{Key, Term};++// ESC alone is ambiguous on a byte stream. Only escape sequences need a timeout.+const SEQUENCE_WAIT: Duration = Duration::from_millis(250);+const INPUT_LIMIT: usize = 256;++// Only one setup menu owns stdin. Signal delivery can occur on any runtime thread.+static MENU_SIGNAL: AtomicI32 = AtomicI32::new(0);++extern "C" fn note_signal(signal: libc::c_int) {+ MENU_SIGNAL.store(signal, Ordering::Relaxed);+}++struct MenuSignals(Vec<(libc::c_int, libc::sigaction)>);++impl MenuSignals {+ fn install() -> io::Result<Self> {+ MENU_SIGNAL.store(0, Ordering::Relaxed);+ let mut guard = Self(Vec::new());+ // SAFETY: sigaction copies both structures. The handler only stores a signal number.+ unsafe {+ let mut action: libc::sigaction = std::mem::zeroed();+ action.sa_sigaction = note_signal as *const () as libc::sighandler_t;+ libc::sigemptyset(&mut action.sa_mask);+ for signal in [libc::SIGINT, libc::SIGTERM, libc::SIGHUP] {+ let mut previous = std::mem::zeroed();+ if libc::sigaction(signal, std::ptr::null(), &mut previous) == -1 {+ return Err(io::Error::last_os_error());+ }+ if previous.sa_sigaction == libc::SIG_IGN {+ continue;+ }+ if libc::sigaction(signal, &action, &mut previous) == -1 {+ return Err(io::Error::last_os_error());+ }+ guard.0.push((signal, previous));+ }+ }+ Ok(guard)+ }+}++impl Drop for MenuSignals {+ fn drop(&mut self) {+ // Restore before re-delivering, after read_key's raw terminal guard has dropped.+ unsafe {+ for (signal, previous) in self.0.iter().rev() {+ libc::sigaction(*signal, previous, std::ptr::null_mut());+ }+ let signal = MENU_SIGNAL.swap(0, Ordering::Relaxed);+ if signal != 0 {+ libc::raise(signal);+ }+ }+ }+}++fn read_byte(input: &mut std::fs::File, deadline: Instant) -> io::Result<Option<u8>> {+ loop {+ if MENU_SIGNAL.load(Ordering::Relaxed) != 0 {+ return Err(io::ErrorKind::Interrupted.into());+ }+ let remaining = deadline.saturating_duration_since(Instant::now());+ if remaining.is_zero() {+ return Ok(None);+ }+ // select works for terminal descriptors on macOS as well as Linux.+ let fd = input.as_raw_fd();+ if fd < 0 || fd as usize >= libc::FD_SETSIZE {+ return Err(io::Error::other("terminal descriptor exceeds select capacity"));+ }+ let mut timeout = libc::timeval {+ tv_sec: remaining.as_secs() as libc::time_t,+ tv_usec: remaining.subsec_micros().max(1) as libc::suseconds_t,+ };+ // SAFETY: fd is live and checked against FD_SETSIZE; the initialized+ // set and timeout remain valid for the duration of select.+ let ready = unsafe {+ let mut set = std::mem::zeroed::<libc::fd_set>();+ libc::FD_ZERO(&mut set);+ libc::FD_SET(fd, &mut set);+ libc::select(fd + 1, &mut set, std::ptr::null_mut(), std::ptr::null_mut(), &mut timeout)+ };+ if ready < 0 {+ let error = io::Error::last_os_error();+ if error.kind() == io::ErrorKind::Interrupted {+ continue;+ }+ return Err(error);+ }+ if ready == 0 {+ return Ok(None);+ }+ let mut byte = [0];+ match input.read(&mut byte) {+ Ok(0) => return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "terminal input closed")),+ Ok(_) => return Ok(Some(byte[0])),+ Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,+ Err(error) => return Err(error),+ }+ }+}++fn decode(bytes: &[u8]) -> Key {+ use termion::event::{Event, Key as Parsed};+ if bytes == b"\x1b" {+ return Key::Escape;+ }+ // termion's legacy mouse/numeric branches assume valid complete input.+ // Pass only bounded, complete keyboard sequences with valid u8 parameters.+ if bytes.starts_with(b"\x1b[") {+ let Some((&last, params)) = bytes[2..].split_last() else { return Key::Unknown };+ if !matches!(last, b'A' | b'B' | b'C' | b'D' | b'H' | b'F' | b'Z' | b'~')+ || (!params.is_empty()+ && (!params.iter().all(|b| b.is_ascii_digit() || *b == b';')+ || !params+ .split(|b| *b == b';')+ .all(|p| std::str::from_utf8(p).ok().and_then(|s| s.parse::<u8>().ok()).is_some())))+ {+ return Key::Unknown;+ }+ }+ // Application cursor mode uses SS3 rather than CSI.+ let normalized;+ let bytes = if bytes.len() == 3 && bytes.starts_with(b"\x1bO") && b"ABCDHF".contains(&bytes[2]) {+ normalized = [0x1b, b'[', bytes[2]];+ &normalized[..]+ } else {+ bytes+ };+ match termion::event::parse_event(bytes[0], &mut bytes[1..].iter().copied().map(Ok)) {+ Ok(Event::Key(key)) => match key {+ Parsed::Up => Key::ArrowUp,+ Parsed::Down => Key::ArrowDown,+ Parsed::Left => Key::ArrowLeft,+ Parsed::Right => Key::ArrowRight,+ Parsed::Home => Key::Home,+ Parsed::End => Key::End,+ Parsed::PageUp => Key::PageUp,+ Parsed::PageDown => Key::PageDown,+ Parsed::Backspace | Parsed::Ctrl('h') => Key::Backspace,+ Parsed::Char('\n') => Key::Enter,+ Parsed::Ctrl('c') => Key::CtrlC,+ Parsed::Char(c) => Key::Char(c),+ _ => Key::Unknown,+ },+ _ => Key::Unknown,+ }+}++/// Returns `Ok(None)` when no byte arrives within the first-read window: the+/// terminal is simply idle, so the caller can skip repainting an unchanged+/// frame. A byte that arrives but forms an unknown/partial sequence still+/// returns `Some(Key::Unknown)`, as does every later timeout.+fn read_key(utf8: &mut Vec<u8>, queued: &mut Option<u8>) -> io::Result<Option<Key>> {+ // The input and output may be separate terminals. Read keys in raw mode+ // on stdin and restore it before rendering the next frame.+ let input = std::fs::File::from(std::io::stdin().as_fd().try_clone_to_owned()?);+ let mut input = input.into_raw_mode()?;+ // Periodic wakeups let the caller notice a resize, even without keys.+ let first = match queued.take() {+ Some(byte) => byte,+ None => match read_byte(&mut input, Instant::now() + Duration::from_millis(100))? {+ Some(byte) => byte,+ None => return Ok(None),+ },+ };+ if !utf8.is_empty() && !(0x80..=0xbf).contains(&first) {+ // Surface the broken character and then process the new byte (possibly Enter or Ctrl+C).+ utf8.clear();+ *queued = Some(first);+ return Ok(Some(Key::Char(char::REPLACEMENT_CHARACTER)));+ }+ if !first.is_ascii() {+ utf8.push(first);+ return match std::str::from_utf8(utf8) {+ Err(error) if error.error_len().is_none() => Ok(None),+ decoded => {+ let key = decoded.ok().and_then(|s| s.chars().next()).unwrap_or(char::REPLACEMENT_CHARACTER);+ utf8.clear();+ Ok(Some(Key::Char(key)))+ }+ };+ }+ let deadline = Instant::now() + SEQUENCE_WAIT;+ let mut bytes = vec![first];+ if first == 0x1b {+ let Some(second) = read_byte(&mut input, deadline)? else { return Ok(Some(Key::Escape)) };+ bytes.push(second);+ if matches!(second, b'[' | b'O') {+ let mut overflow = false;+ loop {+ let Some(next) = read_byte(&mut input, deadline)? else {+ return Ok(Some(Key::Unknown));+ };+ if bytes.len() < 32 {+ bytes.push(next);+ } else {+ overflow = true;+ }+ if (0x40..=0x7e).contains(&next) {+ if overflow {+ return Ok(Some(Key::Unknown));+ }+ break;+ }+ }+ }+ }+ // An Alt-modified character is part of the ESC sequence.+ while std::str::from_utf8(&bytes).is_err_and(|error| error.error_len().is_none()) && bytes.len() < 6 {+ let Some(next) = read_byte(&mut input, deadline)? else { return Ok(Some(Key::Unknown)) };+ bytes.push(next);+ }+ Ok(Some(decode(&bytes)))+}++#[derive(Debug, PartialEq)]+pub(super) enum Cancelled {+ Escape,+ Interrupt,+}++impl fmt::Display for Cancelled {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ f.write_str("setup cancelled")+ }+}++impl std::error::Error for Cancelled {}++fn supports_menu(stdin: bool, stdout: bool, term: Option<&str>, size: (u16, u16)) -> bool {+ stdin && stdout && term.is_some_and(|t| !t.is_empty() && t != "dumb") && size.0 >= 6 && size.1 >= 40+}++fn interactive(term: &Term) -> bool {+ supports_menu(+ std::io::stdin().is_terminal(),+ std::io::stdout().is_terminal(),+ std::env::var("TERM").ok().as_deref(),+ term.size(),+ )+}++pub(super) fn choose(prompt: &str, options: &[&str], default: usize) -> anyhow::Result<usize> {+ anyhow::ensure!(!options.is_empty() && default < options.len(), "invalid menu default");+ let term = Term::stdout();+ if interactive(&term) {+ menu(&term, prompt, options, default, false)+ } else {+ choose_line(prompt, options, default)+ }+}++pub(super) fn ask_yes(prompt: &str, default: bool) -> anyhow::Result<bool> {+ let term = Term::stdout();+ if interactive(&term) {+ let options = [ictl_l10n::tr!("是", "Yes"), ictl_l10n::tr!("否", "No")];+ Ok(menu(&term, prompt, &options, usize::from(!default), true)? == 0)+ } else {+ ask_yes_line(prompt, default)+ }+}++fn ask_yes_line(prompt: &str, default: bool) -> anyhow::Result<bool> {+ let hint = if default { "[Y/n]" } else { "[y/N]" };+ loop {+ let a = crate::read_line(&format!("{prompt} {hint} "))?.to_ascii_lowercase();+ match a.as_str() {+ "" => return Ok(default),+ "y" | "yes" | "是" | "好" => return Ok(true),+ "n" | "no" | "否" | "不" => return Ok(false),+ _ => println!("{}", ictl_l10n::tr!(" 输入 y 或 n", " Enter y or n")),+ }+ }+}++fn choose_line(prompt: &str, options: &[&str], default: usize) -> anyhow::Result<usize> {+ println!("{prompt}");+ for (i, option) in options.iter().enumerate() {+ println!(" {}) {option}{}", i + 1, if i == default { ictl_l10n::tr!("(默认)", " (default)") } else { "" });+ }+ loop {+ let a = crate::read_line(ictl_l10n::tr!("选择: ", "Choice: "))?;+ if a.is_empty() {+ return Ok(default);+ }+ match a.parse::<usize>() {+ Ok(n) if (1..=options.len()).contains(&n) => return Ok(n - 1),+ _ => println!("{}", ictl_l10n::trf!(" 输入 1 到 {}", " Enter 1 to {}", options.len())),+ }+ }+}++struct Selection {+ selected: usize,+ count: usize,+ input: String,+ overflow: bool,+ confirmation: bool,+}++impl Selection {+ fn new(default: usize, count: usize, confirmation: bool) -> Self {+ Self { selected: default, count, input: String::new(), overflow: false, confirmation }+ }++ fn answer(&self) -> Option<usize> {+ if self.overflow {+ return None;+ }+ let input = self.input.trim();+ if self.confirmation {+ match input.to_ascii_lowercase().as_str() {+ "y" | "yes" | "是" | "好" => return Some(0),+ "n" | "no" | "否" | "不" => return Some(1),+ _ => {}+ }+ }+ input.parse::<usize>().ok().filter(|n| (1..=self.count).contains(n)).map(|n| n - 1)+ }++ fn key(&mut self, key: Key, page: usize) -> Result<Option<usize>, Cancelled> {+ let next = match key {+ Key::Escape => return Err(Cancelled::Escape),+ Key::CtrlC => return Err(Cancelled::Interrupt),+ Key::Enter => {+ return Ok(if self.input.is_empty() && !self.overflow { Some(self.selected) } else { self.answer() });+ }+ Key::ArrowUp => Some((self.selected + self.count - 1) % self.count),+ Key::ArrowDown => Some((self.selected + 1) % self.count),+ Key::ArrowLeft if self.confirmation => Some(0),+ Key::ArrowRight if self.confirmation => Some(1),+ Key::Home => Some(0),+ Key::End => Some(self.count - 1),+ Key::PageUp => Some(self.selected.saturating_sub(page)),+ Key::PageDown => Some(self.selected.saturating_add(page).min(self.count - 1)),+ Key::Char(c) if !c.is_control() => {+ // Never discard an unrecognized character: "1x" must not+ // confirm option 1, and a mistyped No must not accept Yes.+ if self.input.len() + c.len_utf8() <= INPUT_LIMIT && !self.overflow {+ self.input.push(c);+ } else {+ self.overflow = true;+ }+ if let Some(index) = self.answer() {+ self.selected = index;+ }+ None+ }+ Key::Backspace => {+ self.input.pop();+ if let Some(index) = self.answer() {+ self.selected = index;+ }+ None+ }+ _ => None,+ };+ if let Some(index) = next {+ self.selected = index;+ self.input.clear();+ self.overflow = false;+ }+ Ok(None)+ }+}++fn clean(text: &str) -> String {+ // Labels may eventually contain external device names. Never let them move+ // the cursor, create extra lines or inject terminal escape sequences.+ text.chars().map(|c| if c.is_control() { ' ' } else { c }).collect()+}++fn fit(text: &str, columns: usize) -> String {+ // console::truncate_str subtracts the tail width ("..." = 3 columns) from+ // the available width; a width below that underflows usize in debug builds+ // and wraps in release. A window this narrow cannot show the tail anyway, so+ // clamp to the smallest width truncate_str handles instead of panicking.+ let columns = columns.max(4);+ console::truncate_str(&clean(text), columns, "...").into_owned()+}++fn capacity(rows: u16) -> usize {+ usize::from(rows.saturating_sub(4)).clamp(1, 12)+}++fn frame(prompt: &str, options: &[&str], state: &Selection, size: (u16, u16)) -> Vec<String> {+ let page = capacity(size.0);+ let start = state.selected / page * page;+ let end = (start + page).min(options.len());+ // Leave the final column unused: terminals disagree about wrapping exactly+ // at the margin, especially when the last character occupies two columns.+ let columns = usize::from(size.1.saturating_sub(1));+ let help = if state.confirmation {+ ictl_l10n::tr!("↑↓/←→ 选择 · Enter 确认 · Esc 取消", "↑↓/←→ select · Enter confirm · Esc cancel")+ } else {+ ictl_l10n::tr!("↑↓ 选择 · Enter 确认 · Esc 取消", "↑↓ select · Enter confirm · Esc cancel")+ };+ let mut lines = vec![fit(prompt, columns), fit(help, columns)];+ for (index, option) in options.iter().enumerate().take(end).skip(start) {+ lines.push(fit(+ &format!("{} {}) {option}", if index == state.selected { ">" } else { " " }, index + 1),+ columns,+ ));+ }+ let status = if state.overflow {+ ictl_l10n::tr!("输入过长 · 用方向键重新选择", "Input too long · use arrows to select again").to_owned()+ } else if state.input.is_empty() {+ ictl_l10n::trf!(+ "{}–{}/{} · 数字 + Enter · Ctrl+C 取消",+ "{}–{}/{} · number + Enter · Ctrl+C cancel",+ start + 1,+ end,+ options.len()+ )+ } else if state.answer().is_some() {+ ictl_l10n::trf!("输入: {} · Enter 确认", "Input: {} · Enter confirm", state.input)+ } else if state.confirmation {+ ictl_l10n::trf!(+ "无效输入 · 输入 是/否、yes/no 或 1/2: {}",+ "Invalid input · use yes/no or 1/2: {}",+ state.input+ )+ } else {+ ictl_l10n::trf!("无效输入 · 输入 1 到 {}: {}", "Invalid input · enter 1 to {}: {}", options.len(), state.input)+ };+ lines.push(fit(&status, columns));+ lines+}++fn menu(term: &Term, prompt: &str, options: &[&str], default: usize, confirmation: bool) -> anyhow::Result<usize> {+ let _signals = MenuSignals::install()?;+ let mut utf8 = Vec::with_capacity(4);+ let mut queued = None;+ let mut state = Selection::new(default, options.len(), confirmation);+ // (size, rendered line count) for the frame currently shown on screen.+ let mut previous = None;+ let mut needs_render = true;+ loop {+ let size = term.size();+ let resized = previous.is_some_and(|(old_size, _)| old_size != size);+ if needs_render || resized {+ // A resize can reflow every previous line. Only erase a frame while+ // its dimensions are unchanged; otherwise leave history alone and append.+ if let Some((old_size, lines)) = previous+ && old_size == size+ {+ term.clear_last_lines(lines)?;+ }+ if size.0 < 6 || size.1 < 40 {+ // Initial small terminals use line prompts; shrinking an active+ // menu must never discard invalid input or accept a stale default.+ // The prompt is written once per size; idle wakeups must not spam.+ if resized {+ term.write_line(&fit(+ ictl_l10n::tr!("放大窗口;Esc 取消", "Enlarge window; Esc cancels"),+ usize::from(size.1.saturating_sub(1)),+ ))?;+ }+ previous = Some((size, 0));+ } else {+ let lines = frame(prompt, options, &state, size);+ for line in &lines {+ term.write_line(line)?;+ }+ previous = Some((size, lines.len()));+ }+ needs_render = false;+ }+ // An idle wait (no key) leaves the on-screen frame untouched; the next+ // iteration still re-checks term.size(), so resizes keep working.+ let Some(key) = read_key(&mut utf8, &mut queued)? else { continue };+ needs_render = true;+ let current_size = term.size();+ if (current_size.0 < 6 || current_size.1 < 40) && !matches!(key, Key::Escape | Key::CtrlC) {+ continue;+ }+ if let Some(index) = state.key(key, capacity(current_size.0))? {+ term.write_line(&format!("{}: {}", clean(prompt), clean(options[index])))?;+ return Ok(index);+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn decoder_rejects_malformed_and_unsupported_sequences() {+ for bytes in [b"\x1b[".as_slice(), b"\x1b[999~", b"\x1b[;~", b"\x1b[<0;1;1M", b"\x1b[M", b"\xff"] {+ assert_eq!(decode(bytes), Key::Unknown, "{bytes:?}");+ }+ assert_eq!(decode(b"\x1b[6~"), Key::PageDown);+ assert_eq!(decode(b"\x1bOA"), Key::ArrowUp);+ assert_eq!(decode("否".as_bytes()), Key::Char('否'));+ }++ #[test]+ fn oversized_input_cannot_accept_a_truncated_valid_answer() {+ let mut state = Selection::new(0, 2, true);+ state.key(Key::Char('1'), 2).unwrap();+ for _ in 0..INPUT_LIMIT * 2 {+ state.key(Key::Char(' '), 2).unwrap();+ }+ assert!(state.input.len() <= INPUT_LIMIT);+ assert_eq!(state.key(Key::Enter, 2).unwrap(), None);+ for _ in 0..INPUT_LIMIT {+ state.key(Key::Backspace, 2).unwrap();+ }+ assert_eq!(state.key(Key::Enter, 2).unwrap(), None);+ state.key(Key::ArrowRight, 2).unwrap();+ assert_eq!(state.key(Key::Enter, 2).unwrap(), Some(1));+ }++ #[test]+ fn arrows_defaults_and_confirmation() {+ let mut state = Selection::new(1, 3, false);+ assert_eq!(state.key(Key::Enter, 2).unwrap(), Some(1));+ state.key(Key::ArrowDown, 2).unwrap();+ state.key(Key::ArrowDown, 2).unwrap();+ assert_eq!(state.selected, 0);+ state.key(Key::ArrowUp, 2).unwrap();+ assert_eq!(state.selected, 2);+ let mut confirm = Selection::new(1, 2, true);+ confirm.key(Key::ArrowLeft, 2).unwrap();+ assert_eq!(confirm.key(Key::Enter, 2).unwrap(), Some(0));+ confirm.key(Key::ArrowRight, 2).unwrap();+ assert_eq!(confirm.key(Key::Enter, 2).unwrap(), Some(1));+ assert!(confirm.key(Key::Escape, 2).is_err());+ assert!(confirm.key(Key::CtrlC, 2).is_err());+ }++ #[test]+ fn numeric_input_is_buffered_validated_and_editable() {+ let mut state = Selection::new(0, 12, false);+ state.key(Key::Char('1'), 3).unwrap();+ state.key(Key::Char('2'), 3).unwrap();+ assert_eq!(state.key(Key::Enter, 3).unwrap(), Some(11));+ state.key(Key::Char('3'), 3).unwrap();+ assert_eq!(state.key(Key::Enter, 3).unwrap(), None);+ state.key(Key::Backspace, 3).unwrap();+ assert_eq!(state.key(Key::Enter, 3).unwrap(), Some(11));+ state.key(Key::Home, 3).unwrap();+ assert!(state.input.is_empty());+ state.key(Key::PageDown, 3).unwrap();+ assert_eq!(state.selected, 3);+ state.key(Key::End, 3).unwrap();+ assert_eq!(state.selected, 11);+ }++ #[test]+ fn confirmation_text_never_silently_accepts_the_default() {+ for (input, expected) in [("否", 1), ("不", 1), ("no", 1), ("NO", 1), ("是", 0), ("好", 0), ("yes", 0)] {+ let mut state = Selection::new(0, 2, true);+ for c in input.chars() {+ state.key(Key::Char(c), 2).unwrap();+ }+ assert_eq!(state.key(Key::Enter, 2).unwrap(), Some(expected), "{input}");+ }+ for confirmation in [false, true] {+ let mut state = Selection::new(0, 2, confirmation);+ for c in "1x".chars() {+ state.key(Key::Char(c), 2).unwrap();+ }+ assert_eq!(state.key(Key::Enter, 2).unwrap(), None);+ state.key(Key::Backspace, 2).unwrap();+ assert_eq!(state.key(Key::Enter, 2).unwrap(), Some(0));+ state.key(Key::Char('x'), 2).unwrap();+ state.key(Key::ArrowDown, 2).unwrap();+ assert!(state.input.is_empty());+ assert_eq!(state.key(Key::Enter, 2).unwrap(), Some(1));+ }+ }++ #[test]+ fn terminal_capability_requires_both_ttys_and_enough_space() {+ assert!(supports_menu(true, true, Some("xterm"), (24, 80)));+ for (input, output, term, size) in [+ (false, true, Some("xterm"), (24, 80)),+ (true, false, Some("xterm"), (24, 80)),+ (true, true, Some("dumb"), (24, 80)),+ (true, true, None, (24, 80)),+ (true, true, Some("xterm"), (5, 80)),+ (true, true, Some("xterm"), (24, 39)),+ ] {+ assert!(!supports_menu(input, output, term, size));+ }+ }++ #[test]+ fn fit_survives_widths_below_the_ellipsis_without_panicking() {+ let label = "中文很长的菜单选项 with extra text to truncate";+ for columns in 0..=4usize {+ let fitted = fit(label, columns);+ // Widths below the "..." tail (3) are clamped to the smallest+ // width truncate_str handles, so the result stays bounded and clean.+ assert!(console::measure_text_width(&fitted) <= 4);+ assert!(!fitted.chars().any(char::is_control));+ }+ assert!(fit("abcdefghij", 4).ends_with("..."));+ }++ #[test]+ fn frames_fit_chinese_long_labels_and_scroll_without_color() {+ let labels = vec!["中文很长的菜单选项\n\x1b[2J\t带有控制字符和额外文本"; 30];+ let state = Selection::new(29, labels.len(), false);+ for size in [(6, 40), (24, 80), (10, 50)] {+ let lines = frame("中文标题", &labels, &state, size);+ assert!(lines.len() < usize::from(size.0));+ assert!(lines.iter().all(|line| console::measure_text_width(line) < usize::from(size.1)));+ assert!(lines.iter().all(|line| !line.chars().any(char::is_control)));+ assert!(lines.iter().any(|line| line.starts_with("> 30)")));+ }+ }++ /// Driven by tests/terminal.py under a PTY. No setup/service/device effects.+ #[test]+ #[ignore = "interactive PTY harness; run tests/terminal.py"]+ fn pty_menu() {+ if std::env::var("ICTL_TEST_MENU").as_deref() == Ok("text-then-menu") {+ println!("TEXT_RESULT={}", crate::read_line("Text: ").unwrap());+ }+ let result = if std::env::var("ICTL_TEST_MENU").as_deref() == Ok("confirm") {+ ask_yes("Confirm?", std::env::var("ICTL_TEST_DEFAULT").as_deref() == Ok("yes")).map(usize::from)+ } else {+ let labels: Vec<_> =+ (1..=30).map(|i| format!("中文 menu item {i} with a long label for narrow windows")).collect();+ let options: Vec<_> = labels.iter().map(String::as_str).collect();+ choose("Menu test", &options, 1)+ };+ match result {+ Ok(index) => println!("MENU_RESULT={index}"),+ Err(error) if error.is::<Cancelled>() => println!("MENU_CANCELLED"),+ Err(error) => panic!("menu error: {error}"),+ }+ }+}diff --git a/apps/iphone-control/src/main.rs b/apps/iphone-control/src/main.rsindex fc67fba..da65cb5 100644--- a/apps/iphone-control/src/main.rs+++ b/apps/iphone-control/src/main.rs@@ -2,9 +2,9 @@//!//! 不带参数运行是首次运行引导([`guide`]):没设置好就一步步引导,设置好以后只显示状态。//! 运维命令(status、doctor、resign、unlock-reset)经控制接口问守护进程;-//! setup、login、passcode 需要交互,直接在本进程里做。每个命令启动时先读 ~/.config/iphone-control/env([`envfile`])。+//! setup、login、passcode 需要交互,直接在本进程里做。除静态补全外,命令启动时先读 ~/.config/iphone-control/env([`envfile`])。-use std::io::{BufRead, Write};+use std::io::Write;use std::path::{Path, PathBuf};use std::time::Duration;@@ -14,6 +14,7 @@ use ictl_daemon::config::env as env_nonempty;use ictl_daemon::protocol::{self, Request, Response};mod agent;+mod completions;#[cfg(feature = "debug-cmds")]mod debug;mod envfile;@@ -41,6 +42,12 @@ struct Cli {#[derive(Subcommand)]enum Command {+ #[command(about = ictl_l10n::tr!("生成 Bash、Zsh 或 Fish 补全脚本到标准输出(不读取设置或连接设备)", "Generate Bash, Zsh or Fish completions on stdout (without loading settings or connecting to devices)"))]+ #[command(after_help = ictl_l10n::tr!("用法示例:iphone-control completions bash > iphone-control.bash\n通过 IPHONE_CONTROL_LANG=en 或 zh 选择补全说明的语言。升级后重新生成脚本。", "Example: iphone-control completions bash > iphone-control.bash\nSet IPHONE_CONTROL_LANG=en or zh to choose completion descriptions. Regenerate after upgrading."))]+ Completions {+ #[arg(value_enum, help = ictl_l10n::tr!("要生成补全脚本的 shell", "Shell to generate completions for"))]+ shell: completions::Shell,+ },#[command(about = ictl_l10n::tr!("检查主机软件版本,有新版时升级", "Check for a new host software release and install it if available"))]Update {#[arg(short, long, help = ictl_l10n::tr!("不询问,直接升级(脚本里或没有终端时用)", "Upgrade without asking (for scripts, or without a terminal)"))]@@ -177,6 +184,13 @@ enum PasscodeAction {}fn main() -> anyhow::Result<()> {+ // 静态补全必须在读含密钥的设置、创建线程和维护锁之前返回。+ if completions::requested(std::env::args_os().skip(1)) {+ let cli = Cli::parse();+ if let Some(Command::Completions { shell }) = cli.command {+ return completions::write(shell, &mut std::io::stdout().lock());+ }+ }// 设置文件先读进环境(命令行上已设的优先),要在启动任何线程之前:语言、代理、通知等对所有命令都生效envfile::load_into_process();tokio::runtime::Runtime::new()?.block_on(run())@@ -234,11 +248,18 @@ async fn run() -> anyhow::Result<()> {// Lifetime clients hold this through pauses and confirmations, and direct-device CLI// commands participate even when they bypass the daemon.let _client = match &cli.command {- Some(Command::Daemon | Command::Update { .. } | Command::McpConfig | Command::Status) => None,+ Some(+ Command::Daemon+ | Command::Update { .. }+ | Command::McpConfig+ | Command::Status+ | Command::Completions { .. },+ ) => None,_ => Some(ictl_daemon::maintenance::shared()?),};let Some(command) = cli.command.take() else { return guide::first_run(&cli).await };match command {+ Command::Completions { shell } => completions::write(shell, &mut std::io::stdout().lock()),Command::Update { action: None, yes } => update::upgrade(&cli.socket, update::check(false).await?, yes).await,Command::Update { action: Some(action), .. } => update_command(action, &cli.socket).await,Command::Daemon => {@@ -579,8 +600,31 @@ async fn status(socket: &Path) -> anyhow::Result<()> {fn read_line(prompt: &str) -> anyhow::Result<String> {print!("{prompt}");std::io::stdout().flush()?;- let mut s = String::new();- if std::io::stdin().lock().read_line(&mut s)? == 0 {+ // Do not use Stdin's global BufReader here: it can read ahead into the+ // next menu's pasted answer, which the raw terminal reader cannot see.+ use std::io::Read;+ use std::os::fd::AsFd;+ let mut input = std::fs::File::from(std::io::stdin().as_fd().try_clone_to_owned()?);+ let mut bytes = Vec::new();+ let mut byte = [0];+ let mut overflow = false;+ loop {+ match input.read(&mut byte) {+ Ok(0) => break,+ Ok(_) if byte[0] == b'\n' => break,+ Ok(_) => {+ if bytes.len() < 4096 {+ bytes.push(byte[0]);+ } else {+ overflow = true;+ }+ }+ Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,+ Err(error) => return Err(error.into()),+ }+ }+ anyhow::ensure!(!overflow, "{}", ictl_l10n::tr!("输入超过 4096 字节", "Input exceeds 4096 bytes"));+ if byte[0] != b'\n' {bail!("{}",ictl_l10n::tr!(@@ -589,7 +633,7 @@ fn read_line(prompt: &str) -> anyhow::Result<String> {));}- Ok(s.trim().to_owned())+ Ok(String::from_utf8(bytes)?.trim().to_owned())}/// 不回显地读一行(用 stty 关回显,不引入额外依赖)diff --git a/apps/iphone-control/tests/completions.rs b/apps/iphone-control/tests/completions.rsnew file mode 100644index 0000000..8aaa932--- /dev/null+++ b/apps/iphone-control/tests/completions.rs@@ -0,0 +1,158 @@+//! Exercise the real executable before its config/runtime/maintenance initialization.++use std::ffi::CString;+use std::fs::{self, File};+use std::os::unix::ffi::OsStrExt;+use std::os::unix::net::UnixListener;+use std::path::Path;+use std::process::{Command, Output, Stdio};+use std::time::{Duration, Instant};++fn run(root: &Path, args: &[&str], language: &str) -> Output {+ let stdout = root.join("stdout");+ let stderr = root.join("stderr");+ let mut child = Command::new(env!("CARGO_BIN_EXE_iphone-control"))+ .args(args)+ .env_clear()+ .env("HOME", root.join("home"))+ .env("XDG_CONFIG_HOME", root.join("config"))+ .env("XDG_DATA_HOME", root.join("data"))+ .env("XDG_RUNTIME_DIR", root.join("runtime"))+ .env("ICTL_DATA_DIR", root.join("data"))+ .env("ICTL_SOCKET", root.join("ctl.sock"))+ .env("IPHONE_CONTROL_LANG", language)+ .stdin(Stdio::null())+ .stdout(File::create(&stdout).unwrap())+ .stderr(File::create(&stderr).unwrap())+ .spawn()+ .unwrap();+ let deadline = Instant::now() + Duration::from_secs(5);+ let status = loop {+ if let Some(status) = child.try_wait().unwrap() {+ break status;+ }+ if Instant::now() >= deadline {+ let _ = child.kill();+ let _ = child.wait();+ panic!("completion command blocked (possibly reading the settings FIFO): {args:?}");+ }+ std::thread::sleep(Duration::from_millis(10));+ };+ Output { status, stdout: fs::read(stdout).unwrap(), stderr: fs::read(stderr).unwrap() }+}++fn check_shell_candidates(shell: &str, script: &Path) {+ for (line, expected, present) in [+ ("iphone-control setup --rec", "--reconfigure", true),+ ("iphone-control update po", "policy", true),+ ("iphone-control update --", "--yes", true),+ ("iphone-control completions ", "bash", true),+ ("iphone-control --data-dir policy completions ", "zsh", true),+ ("iphone-control --data-dir status completions b", "bash", true),+ ("iphone-control --data-dir check update ", "apply", true),+ ("iphone-control --data-dir check update --", "--json", false),+ ("iphone-control --socket=policy update policy ", "manual", true),+ ("iphone-control update policy ", "auto-patch", true),+ ("iphone-control update policy manual ", "auto-patch", false),+ ("iphone-control --data-dir policy update check ", "manual", false),+ ("iphone-control --data-dir completions status ", "bash", false),+ ("iphone-control select policy ", "auto-patch", false),+ ("iphone-control ", "debug", false),+ ("iphone-control update ", "schedule", false),+ ("iphone-control update ", "run", false),+ ("iphone-control update ", "rollback", false),+ ("iphone-control update recover --", "--scheduled", false),+ ] {+ let mut cmd = Command::new(shell);+ if shell == "fish" {+ cmd.args(["--no-config", "-c", "source $argv[1]; complete -C $argv[2]", "--"]).arg(script).arg(line);+ } else {+ cmd.args([+ "--noprofile",+ "--norc",+ "-c",+ r#"+ source "$1" || exit 1+ shift+ COMP_WORDS=("$@")+ COMP_CWORD=$(( ${#COMP_WORDS[@]} - 1 ))+ fn=$(complete -p iphone-control) || exit 1+ fn=${fn#* -F }+ "${fn%% *}" iphone-control "${COMP_WORDS[COMP_CWORD]}" "${COMP_WORDS[COMP_CWORD-1]}"+ printf '%s\n' "${COMPREPLY[@]}"+ "#,+ "--",+ ])+ .arg(script)+ .args(line.split(' '));+ }+ let output = cmd.output().unwrap();+ assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));+ let candidates = String::from_utf8(output.stdout).unwrap();+ assert_eq!(+ candidates.lines().any(|value| value.split('\t').next() == Some(expected)),+ present,+ "{shell} {line:?}: {candidates}"+ );+ }+}++#[test]+fn scripts_help_and_errors_do_not_read_settings_create_state_or_contact_the_daemon() {+ let dir = tempfile::tempdir().unwrap();+ let root = dir.path();+ fs::create_dir_all(root.join("config/iphone-control")).unwrap();+ // With no writer, reading this FIFO hangs. The bounded subprocess check catches config+ // access reliably, even when tests run as root and mode 000 would still be readable.+ let fifo = CString::new(root.join("config/iphone-control/env").as_os_str().as_bytes()).unwrap();+ assert_eq!(unsafe { libc::mkfifo(fifo.as_ptr(), 0o600) }, 0);+ let listener = UnixListener::bind(root.join("ctl.sock")).unwrap();+ listener.set_nonblocking(true).unwrap();+ for shell in ["bash", "zsh", "fish"] {+ let output = run(root, &["completions", shell], "en");+ assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));+ assert!(output.stderr.is_empty());+ let script = String::from_utf8(output.stdout).unwrap();+ assert!(script.contains("iphone-control"));+ assert!(script.contains("auto-patch"));+ let path = root.join(format!("completion.{shell}"));+ fs::write(&path, script).unwrap();+ // Syntax-check each available shell. The Linux CI job installs fish so+ // its candidate assertions actually run; elsewhere a missing shell is+ // reported (not silently ignored) so the gap stays visible.+ match Command::new(shell).arg("--version").output() {+ Ok(_) => {+ let check = Command::new(shell).arg("-n").arg(&path).output().unwrap();+ assert!(check.status.success(), "{shell}: {}", String::from_utf8_lossy(&check.stderr));+ if shell != "zsh" {+ check_shell_candidates(shell, &path);+ }+ }+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {+ eprintln!("skipping {shell} syntax and completion checks: shell not installed");+ }+ Err(error) => panic!("cannot run {shell}: {error}"),+ }+ }+ let output = run(root, &["--data-dir", "completions", "--socket=completions", "completions", "fish"], "en");+ assert!(output.status.success());+ assert!(output.stderr.is_empty());+ for (language, description) in [("en", "Generate Bash"), ("zh", "生成 Bash")] {+ for args in [["completions", "--help"], ["help", "completions"]] {+ let output = run(root, &args, language);+ assert!(output.status.success());+ assert!(output.stderr.is_empty());+ assert!(String::from_utf8(output.stdout).unwrap().contains(description));+ }+ }+ for args in [vec!["completions"], vec!["completions", "powershell"], vec!["completions", "bash", "extra"]] {+ let output = run(root, &args, "en");+ assert!(!output.status.success());+ assert!(output.stdout.is_empty());+ assert!(!output.stderr.is_empty());+ }+ assert_eq!(listener.accept().unwrap_err().kind(), std::io::ErrorKind::WouldBlock);+ for name in ["home", "data", "runtime"] {+ assert!(!root.join(name).exists(), "completion created {name}");+ }+}diff --git a/docs/dev/regression-cases.md b/docs/dev/regression-cases.mdindex 8bac4fa..31c92fd 100644--- a/docs/dev/regression-cases.md+++ b/docs/dev/regression-cases.md@@ -117,3 +117,5 @@| 111 | 控制台上 AI 任务的总结直接显示 Markdown 原文(`**iOS 27.0.1**`、`- **设置**:…`),换行也被合并成一行 | 总结先整体转义,再按一小部分 Markdown 显示(粗体、斜体、行内代码、列表、标题、分隔线、换行、http(s) 链接),原始 HTML 一律当文字 | 页面测试(`tests/viewer/summary.test.mjs`)+ 真机(Claude Code、Codex 任务的总结) || 112 | iOS 27 上控制台用手机自己的视频时,系统权限弹窗(「允许“日历”使用你的位置?」)在画面里只剩变暗的屏幕,看不到弹窗本身,接管的人不知道该点哪里;agent 的截图里有 | 画面是手机自己的视频时,页面问守护进程有没有系统弹窗(`AlertCheck`;在 App 里每 2 秒,主屏幕上查一次约 0.6 秒,没弹窗时放慢到 6 秒,刚触摸后 3 秒内不问),有就照 iOS 弹窗的样子把它画在画面里它所在的位置(文字、按钮);按钮按坐标点(按名字点「允许」会点到「不允许」);AI 任务进行中按钮要先接管 | 单测(`a_system_alert_with_its_own_buttons`)+ 页面测试(`tests/viewer/alert.test.mjs`)+ 真机(弹出权限请求时页面显示弹窗和按钮,点按钮生效) || 113 | 在控制台画面上拖动、滑动时,触控板双指一碰就变成了缩放画面(双指捏合在浏览器里是按住 Ctrl 的滚轮) | 画面只用上方的加减号缩放;画面区域里的 Ctrl/⌘ + 滚轮、Safari 的 gesture 事件都拦下,既不缩放画面也不缩放整页;触屏上画面周围不允许双指缩放(`touch-action: pan-x pan-y`) | 页面测试(`tests/viewer/zoom.test.mjs`)+ 真机(在画面上双指捏合,缩放比例不变) |+| 114 | 设置菜单不能用方向键,取消后可能留下终端输入模式 | 方向键和编号选择一致,Esc/Ctrl+C 不提交当前选择并恢复终端;基础终端保留逐行输入 | 菜单状态单测 + PTY 回归(不连接设备) |+| 115 | 生成 Shell 补全触发配置读取或设备维护锁,脚本与 CLI 定义不同步 | Bash/Zsh/Fish 从实际命令树生成,生成路径不读取设置、不连接设备、不申请维护锁 | 补全单测、CLI 子进程回归、Bash/Fish 候选断言及 Zsh 交互验证 |diff --git a/docs/dev/terminal-menu-usb.png b/docs/dev/terminal-menu-usb.pngnew file mode 100644index 0000000..b5e6371Binary files /dev/null and b/docs/dev/terminal-menu-usb.png differdiff --git a/docs/dev/terminal-navigation-verification.md b/docs/dev/terminal-navigation-verification.mdnew file mode 100644index 0000000..ad03d11--- /dev/null+++ b/docs/dev/terminal-navigation-verification.md@@ -0,0 +1,60 @@+# 终端菜单与 Shell 补全验证++对应个人仓库 Issue #1、#4。离线检查使用临时配置目录。USB 真机验收沿用测试设备已有的配对和 WDA。++## 实现范围++- 设置向导提供方向键/数字菜单、确认与取消、明确选中态、长列表与宽度适配。Esc 取消当前向导;已保存步骤保留,不提供任意步骤回退或全流程事务回滚。+- 文本与密码输入沿用原行为;非交互设置仍拒绝执行,基础终端/重定向菜单回退逐行输入。+- `completions bash|zsh|fish` 从实际 Clap 定义生成,不读设置、不获取维护锁、不连接 daemon。+- Issue #1 的更广泛体验建议(所有长任务进度、完整多面板 TUI、Kaku 外观对照)没有在本次实现中宣称完成。++## 2026-11-13 USB 真机验收++iPhone 14(`iPhone14,7`),iOS 27.0.1,USB 连接 Apple Silicon Mac,macOS 26.6.2。功能分支 `eff3f45` 和上游 `b64b90c` 均以 Rust 1.99.1 构建 release,并运行各自的 daemon、MCP 和默认的 `tests/device/run.py`。每个构建连续运行三次。++| 构建 | 每轮成功调用 | 三轮总耗时(秒) | 中位数(秒) |+| --- | --- | --- | --- |+| 功能分支 `eff3f45` | 14/14 | 16.0 / 15.1 / 15.9 | 15.9 |+| 上游 `b64b90c` | 14/14 | 17.4 / 17.5 / 16.0 | 17.4 |++- 在 `setup --reconfigure` 按 ↓ 到第 6 项,Esc 退出并恢复终端。选择「手机」后依次识别了 USB 设备、已有配对和已开启的开发者模式。此 Mac 没有 CLI 的 Apple ID 登录记录,向导停在第 4 步的邮箱提示。此次沿用已有 WDA,登录、重签和重装未验证。+- 输入 `7` 选择这台手机的自动解锁设置,用 ←/→ 切换「是」「否」,最终确认「否」。向导显示完成并返回 0。+- Bash 3.2、Zsh 5.9 和 Fish 4.9 各验证五种补全,包括 `setup --rec`、`update po`、`completions zs`、`--data-dir check update app` 和上游新增的 `task ru`。+- 默认脚本实测不存在的元素返回未找到、打开系统时钟、选中「秒表」、整屏和局部截图、Spotlight 输入并找到「设置」、回到主屏。测试结束后恢复原有 daemon,并核对进程可执行文件和 WDA 就绪状态。+- Rust 全工作区 357 项通过、3 项标记为忽略。另行运行 PTY 回归,覆盖 Esc 退出码 0、Ctrl+C 退出码 130、退出后恢复终端及输入输出分别使用不同终端时单按 Esc 退出。Clippy、格式检查、21 项 Viewer 测试、17 项安装器测试和双语站点构建通过。++从 USB 验收时的终端记录截取的选中状态。++++## 2026-11-13 基于上游 `c4ffe03` 的复测++macOS 26.6.2(Apple Silicon),Rust 1.99.1。++- `cargo test --workspace --all-features --locked` 通过 342 项,3 项标记为忽略。另行运行 `tests/terminal.py` 执行其中的 PTY 菜单用例。+- PTY 验证 Esc 返回 0、Ctrl+C 返回 130,以及 SIGINT、SIGTERM、SIGHUP 退出后恢复 termios。预先写入的 `setup-done` 在取消全量重配后保持原内容。确认框收到间隔 350ms 的「否」仍选择否。空闲用例从首帧末行开始计数。+- Bash 3.2.57 和 Fish 4.9.3 验证实际候选,覆盖前置选项值与子命令同名、嵌套命令、枚举和隐藏的计划任务入口。Zsh 5.9 在 PTY 中用 Tab 验证 `update po`、`completions zs`、`--data-dir check update app` 以及隐藏命令和参数。+- Clippy 全工作区检查、Viewer 的 5 项测试、安装器的 17 项测试和双语站点构建通过。++## 初版 Linux x86_64 验证++以下结果记录于移植到上述上游版本之前。++- `cargo test --workspace --all-features --locked`。+- `cargo clippy --workspace --all-targets --all-features --locked -- -D warnings`。+- `cargo fmt` 对 CONTRIBUTING 指定的所有自有包执行 `--check`。+- `cargo build --release --locked -p iphone-control`。+- `python3 tests/terminal.py --binary <debug或release程序> --test-dir <target/debug/deps>`:方向键、编号与多位编号、确认左右键、Esc/Ctrl+C、termios 恢复、中文长列表、缩放、dumb/小窗口/重定向/管道回退及取消时保留已保存设置、丢弃未保存语言。已接入 Linux/macOS CI。+- 扩展 PTY 回归:默认“是”时输入“否/不”、非法编号 `1x`、无效输入后缩窗、跨提示粘贴、输入长度上限、EOF 截断;CSI/SS3 方向键及中文 UTF-8 以每字节 40ms 分批发送。当前实现仅对 Esc 开头的控制序列使用 250ms 超时,普通 UTF-8 文字跨读保留。+- 补全集成测试:FIFO 设置文件不被读取、未连接模拟 daemon socket、未创建状态目录、帮助中英文、错误参数,以及 Bash/Zsh/Fish 语法。Fish 3.6 通过临时解包的软件包验证实际 `complete -C` 候选、前置全局参数和相似参数值,不做全局安装。+- `[email protected] install --frozen-lockfile` 与 `pnpm run docs:build`,双语站点构建通过。+- `python3 packaging/test_installer.py`:16 项通过。+- `git diff --check`。++## 验证边界++- 本地复测在 macOS 上完成。真实 SSH/tmux/Kaku,以及 Apple ID 登录后的首次签名安装仍待验证。+- 本机 Rust 1.88.0 多次下载未能完成,最终停止了本次下载;尝试 MSRV 检查返回 `missing manifest in toolchain`,未得到有效的编译结果。保留现有 CI 的 1.88.0 检查。+- 未改变打包安装逻辑,补全安装方式为文档中的本地生成;未在本机执行 .deb 安装或 Homebrew 安装。+- 新依赖 clap_complete 4.6.11 声明 MSRV 1.85,MIT OR Apache-2.0 符合现有许可证白名单;console 0.15.11 复用现有锁定版本;termion 4.0.6 使用 MIT 许可证。diff --git a/tests/terminal.py b/tests/terminal.pynew file mode 100644index 0000000..fe3956e--- /dev/null+++ b/tests/terminal.py@@ -0,0 +1,387 @@+#!/usr/bin/env python3+"""Offline menu regression on Linux/macOS; only Python's standard library.++python3 tests/terminal.py --binary target/debug/iphone-control \+ --test-dir target/debug/deps++Run cargo test --workspace --all-features --locked first (or use --no-run).+--test-dir discovers the newest executable that lists the menu test with --list;+--test-binary can instead select an exact test executable for local debugging.+CLI cases cancel before service/device work. All settings use temporary XDG dirs.+"""+import argparse+import errno+import fcntl+import os+from pathlib import Path+import pty+import select+import signal+import struct+import subprocess+import sys+import tempfile+import termios+import time+++class Session:+ def __init__(self, command, env, size=(24, 80), redirect=False):+ self.master, self.slave = pty.openpty()+ self.resize(*size)+ self.original = termios.tcgetattr(self.slave)+ self.output = b""+ self.proc = subprocess.Popen(+ command, stdin=self.slave,+ stdout=subprocess.PIPE if redirect else self.slave,+ stderr=self.slave, env=env,+ )+ self.redirect = redirect+ self.reader = self.proc.stdout.fileno() if redirect else self.master++ def resize(self, rows, columns):+ fcntl.ioctl(self.slave, termios.TIOCSWINSZ, struct.pack("HHHH", rows, columns, 0, 0))++ def pump(self, timeout=0.05):+ if select.select([self.reader], [], [], timeout)[0]:+ try:+ self.output += os.read(self.reader, 65536)+ except OSError as error:+ if error.errno != errno.EIO:+ raise++ def expect(self, text):+ target = text.encode()+ deadline = time.monotonic() + 8+ while target not in self.output and time.monotonic() < deadline:+ self.pump()+ if self.proc.poll() is not None:+ self.pump(0)+ break+ assert target in self.output, (text, self.output.decode(errors="replace"))++ def wait_for_raw(self):+ deadline = time.monotonic() + 8+ while termios.tcgetattr(self.slave)[3] & termios.ICANON:+ assert time.monotonic() < deadline, "menu did not start reading keys"+ self.pump(0.01)++ def send(self, data, raw=True):+ if raw:+ self.wait_for_raw()+ os.write(self.master, data)++ def assert_restored(self):+ actual = termios.tcgetattr(self.slave)+ expected = self.original.copy()+ if sys.platform == "darwin":+ # Darwin sets this transient kernel bit when canonical input resumes.+ actual[3] &= ~termios.PENDIN+ expected[3] &= ~termios.PENDIN+ assert actual == expected, ("terminal flags were not restored", actual, expected)+ assert b"\x1b[?25l" not in self.output, "menu unexpectedly hid cursor"++ def finish(self, result, status=0):+ self.expect(result + "\r\n" if result.startswith("MENU_RESULT=") and not self.redirect else result)+ assert self.proc.wait(timeout=8) == status, self.output.decode(errors="replace")+ self.assert_restored()++ def close(self):+ if self.proc.poll() is None:+ self.proc.kill()+ self.proc.wait()+ if self.proc.stdout:+ self.proc.stdout.close()+ os.close(self.master)+ os.close(self.slave)+++def exercise(command, env, keys, result, ready="Esc", size=(24, 80), redirect=False, status=0):+ session = Session(command, env, size, redirect)+ try:+ session.expect(ready)+ session.send(keys, raw=ready != "Choice:")+ session.finish(result, status)+ return session.output+ finally:+ session.close()+++def escape_with_separate_input_terminal(command, env):+ # The terminal that receives keys can differ from the one showing the menu.+ key_stream, key_tty = pty.openpty()+ display, screen_tty = pty.openpty()+ try:+ fcntl.ioctl(screen_tty, termios.TIOCSWINSZ, struct.pack("HHHH", 24, 80, 0, 0))+ with subprocess.Popen(command, stdin=key_tty, stdout=screen_tty, stderr=screen_tty, env=env) as proc:+ try:+ output = b""+ while b"Ctrl+C cancel" not in output:+ assert select.select([display], [], [], 5)[0], "split-terminal menu did not appear"+ output += os.read(display, 8192)+ os.write(key_stream, b"\x1b")+ assert proc.wait(timeout=3) == 0+ finally:+ if proc.poll() is None:+ proc.terminate()+ finally:+ for fd in (key_stream, key_tty, display, screen_tty):+ os.close(fd)+++MENU_TEST = "guide::terminal::tests::pty_menu"+++def discover_test_binary(directory, env):+ candidates = sorted(+ (path for path in directory.glob("iphone_control-*")+ if path.is_file() and os.access(path, os.X_OK)),+ key=lambda path: path.stat().st_mtime_ns, reverse=True,+ )+ for candidate in candidates:+ # Cargo also puts ordinary binaries in deps. Never invoke one without+ # arguments: --list safely fails clap parsing instead of starting setup.+ try:+ listed = subprocess.run(+ [str(candidate.resolve()), "--list"], stdin=subprocess.DEVNULL,+ capture_output=True, timeout=8, env=env,+ )+ except (OSError, subprocess.TimeoutExpired):+ continue+ if listed.returncode == 0 and f"{MENU_TEST}: test".encode() in listed.stdout.splitlines():+ return candidate+ raise ValueError(f"no executable listing {MENU_TEST} in {directory}; run cargo test --workspace --all-features --locked --no-run")+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--binary", type=Path)+ tests = parser.add_mutually_exclusive_group()+ tests.add_argument("--test-binary", type=Path)+ tests.add_argument("--test-dir", type=Path)+ args = parser.parse_args()+ if not (args.binary or args.test_binary or args.test_dir):+ parser.error("provide --binary and/or --test-dir (or --test-binary)")+ with tempfile.TemporaryDirectory(prefix="ictl-terminal-") as directory:+ root = Path(directory)+ env = dict(os.environ, HOME=str(root), XDG_CONFIG_HOME=str(root / "config"),+ XDG_DATA_HOME=str(root / "data"), XDG_CACHE_HOME=str(root / "cache"),+ XDG_RUNTIME_DIR=str(root / "runtime"),+ IPHONE_CONTROL_LANG="en", TERM="xterm-256color", NO_COLOR="1")+ if args.test_dir:+ try:+ args.test_binary = discover_test_binary(args.test_dir, env)+ except ValueError as error:+ parser.error(str(error))+ print(f"Menu test executable: {args.test_binary}")+ if args.binary and os.geteuid() == 0:+ print("SKIP real CLI setup as root: it uses the system maintenance lock")+ elif args.binary:+ command = [str(args.binary.resolve()), "--data-dir", str(root / "data"),+ "--socket", str(root / "daemon.sock"), "setup", "--reconfigure"]+ escape_with_separate_input_terminal(command, env)+ for key, status in [(b"\x1b", 0), (b"\x03", 130)]:+ output = exercise(command, env, key, "Saved settings and completed steps are kept", status=status)+ assert b"Done." not in output+ for sig in (signal.SIGTERM, signal.SIGHUP, signal.SIGINT):+ session = Session(command, env)+ try:+ session.wait_for_raw()+ session.proc.send_signal(sig)+ assert session.proc.wait(timeout=8) in (-sig, 128 + sig)+ session.assert_restored()+ finally:+ session.close()+ for keys in [b"\x1b[B\r", b"2\r"]:+ session = Session(command, env)+ try:+ session.expect("What do you want to set up again?")+ session.send(keys)+ session.expect("界面语言 / Language")+ session.send(b"\x1b")+ session.finish("Saved settings and completed steps are kept")+ finally:+ session.close()+ # Language and proxy are saved together before daemon restart.+ # Cancelling proxy must leave both settings and setup-done untouched.+ settings = root / "config" / "iphone-control" / "env"+ settings.parent.mkdir(parents=True, exist_ok=True)+ settings.write_text("IPHONE_CONTROL_LANG=zh\n")+ before = settings.read_bytes()+ marker = settings.with_name("setup-done")+ assert not marker.exists()+ marker.write_bytes(b"previously completed\n")+ session = Session(command, env)+ try:+ session.expect("What do you want to set up again?")+ session.send(b"1\r")+ session.expect("界面语言 / Language")+ session.send(b"2\r")+ session.expect("Use a proxy?")+ session.send(b"\x1b")+ session.finish("Saved settings and completed steps are kept")+ finally:+ session.close()+ assert settings.read_bytes() == before+ assert marker.read_bytes() == b"previously completed\n"+ exercise(command, env, b"\x1b", "Saved settings and completed steps are kept")+ assert settings.read_bytes() == before+ completed = subprocess.run(command, input=b"2\n", capture_output=True, env=env, timeout=8)+ assert completed.returncode != 0+ assert b"Setup is interactive" in completed.stderr + completed.stdout+ print("PASS CLI cancellation, arrows, numbers, saved-step persistence, non-TTY restriction")+ if args.test_binary:+ command = [str(args.test_binary.resolve()), "--ignored", "--exact",+ MENU_TEST, "--nocapture", "--test-threads=1"]+ for keys, result in [(b"\r", 1), (b"\x1b[A\r", 0), (b"\x1b[B\r", 2),+ (b"12\r", 11), (b"12\x08\r", 0), (b"99\x7f\r", 8), (b"\x1b[F\r", 29)]:+ exercise(command, env, keys, f"MENU_RESULT={result}")+ for key in [b"\x1b", b"\x03"]:+ exercise(command, env, key, "MENU_CANCELLED")+ confirm_env = dict(env, ICTL_TEST_MENU="confirm")+ for keys, result in [(b"\r", 0), (b"\x1b[D\r", 1), (b"\x1b[D\x1b[C\r", 0),+ (b"1\r", 1), (b"y\r", 1)]:+ exercise(command, confirm_env, keys, f"MENU_RESULT={result}")+ for fallback_env, size, redirect in [(dict(env, TERM="dumb"), (24, 80), False),+ (env, (5, 30), False), (env, (24, 80), True)]:+ output = exercise(command, fallback_env, b"12\r", "MENU_RESULT=11",+ ready="Choice:", size=size, redirect=redirect)+ assert b"\x1b[" not in output+ completed = subprocess.run(command, input=b"12\n", capture_output=True, env=env, timeout=8)+ assert completed.returncode == 0+ assert b"MENU_RESULT=11" in completed.stdout+ completed = subprocess.run(command, input=b"invalid\nyes\n", capture_output=True,+ env=confirm_env, timeout=8)+ assert completed.returncode == 0+ assert b"MENU_RESULT=1" in completed.stdout+ session = Session(command, env)+ try:+ session.expect("Menu test")+ session.resize(8, 40)+ session.send(b"\x1b[F")+ session.expect("> 30)")+ session.send(b"\r")+ session.finish("MENU_RESULT=29")+ finally:+ session.close()+ # An idle menu (no keys) must not repaint: the 100ms wakeups only+ # poll for a resize, so a steady frame produces zero extra output.+ session = Session(command, env)+ try:+ session.expect("Ctrl+C cancel\r\n")+ baseline = len(session.output)+ time.sleep(0.5)+ session.pump(0.15)+ assert len(session.output) == baseline, (+ "idle menu repainted", session.output[baseline:].decode(errors="replace"))+ session.send(b"\r")+ session.finish("MENU_RESULT=1")+ finally:+ session.close()+ # Shrinking an active menu to 1-3 columns must not panic: fit()+ # once underflowed inside console::truncate_str below the "..." tail.+ for columns in (1, 2, 3):+ session = Session(command, env)+ try:+ session.expect("Esc")+ session.resize(24, columns)+ # Several 100ms idle wakeups at the hostile width, no keys.+ time.sleep(0.5)+ session.pump(0.05)+ assert session.proc.poll() is None, session.output.decode(errors="replace")+ assert b"panicked" not in session.output+ session.resize(24, 80)+ session.send(b"\r")+ session.finish("MENU_RESULT=1")+ finally:+ session.close()+ yes_env = dict(confirm_env, ICTL_TEST_DEFAULT="yes")+ for text in ["否", "不"]:+ exercise(command, yes_env, (text + "\r").encode(), "MENU_RESULT=0")+ session = Session(command, yes_env)+ try:+ session.expect("Esc")+ answer = "否".encode()+ session.send(answer[:1])+ time.sleep(0.35)+ session.send(answer[1:] + b"\r")+ session.finish("MENU_RESULT=0")+ finally:+ session.close()+ # Send one byte at a time, well apart: a single write is not a+ # fragmented-input test. Every fragment stays within the 250ms budget.+ for fragmented_env, keys, result in [(env, b"\x1b[B", 2),+ (env, b"\x1bOB", 2),+ (yes_env, "否".encode(), 0),+ (yes_env, "不".encode(), 0)]:+ session = Session(command, fragmented_env)+ try:+ session.expect("Esc")+ for byte in keys:+ session.send(bytes([byte]))+ time.sleep(0.04)+ session.send(b"\r")+ session.finish(f"MENU_RESULT={result}")+ finally:+ session.close()+ # A partial control sequence that times out is ignored, not Esc.+ session = Session(command, env)+ try:+ session.expect("Esc")+ session.send(b"\x1b[")+ time.sleep(0.35)+ session.pump(0.05)+ assert session.proc.poll() is None+ assert b"MENU_CANCELLED" not in session.output+ session.send(b"\x03")+ session.finish("MENU_CANCELLED")+ finally:+ session.close()+ for invalid_env in [env, yes_env]:+ session = Session(command, invalid_env)+ try:+ session.expect("Esc")+ session.send(b"1x\r")+ session.expect("Invalid input")+ session.pump(0.1)+ assert b"MENU_RESULT" not in session.output+ session.resize(4, 20)+ session.expect("Enlarge window")+ session.send(b"\r")+ session.pump(0.15)+ assert b"MENU_RESULT" not in session.output+ session.resize(24, 80)+ session.send(b"\r")+ session.pump(0.15)+ assert b"MENU_RESULT" not in session.output+ session.send(b"\x7f\r")+ session.finish("MENU_RESULT=1" if invalid_env == yes_env else "MENU_RESULT=0")+ finally:+ session.close()+ session = Session(command, dict(env, ICTL_TEST_MENU="text-then-menu"))+ try:+ session.expect("Text:")+ session.send(b"pasted text\n12\n", raw=False)+ session.expect("TEXT_RESULT=pasted text")+ session.finish("MENU_RESULT=11")+ finally:+ session.close()+ session = Session(command, env)+ try:+ session.expect("Esc")+ session.send(b"1" + b" " * 300 + b"\r")+ session.expect("Input too long")+ assert b"MENU_RESULT" not in session.output+ session.send(b"\x1b[B\r")+ session.finish("MENU_RESULT=1")+ finally:+ session.close()+ for data in [b"", b"invalid", b"x" * 4097 + b"\n"]:+ completed = subprocess.run(command, input=data, capture_output=True, env=env, timeout=8)+ assert completed.returncode != 0+ assert b"MENU_RESULT" not in completed.stdout+ print("PASS menu/confirmation keys, Chinese No with default Yes, invalid/oversized input, fragmented ESC/UTF-8, text-to-menu paste, resize, termios, fallback and EOF")+++if __name__ == "__main__":+ main()diff --git a/website/en/guide/cli.md b/website/en/guide/cli.mdindex 0d9d25f..49b2fa2 100644--- a/website/en/guide/cli.md+++ b/website/en/guide/cli.md@@ -21,6 +21,27 @@ These go before the command, for example `iphone-control --socket /path/ctl.sock| `mcp` | MCP stdio server, started by the AI client || `mcp-config` | Prints the command that registers the MCP server with Claude Code, with a program path that stays the same across upgrades (Homebrew's `opt` link) |+## Shell completion++`iphone-control completions <bash|zsh|fish>` writes a completion script to stdout, including the current build's subcommands, options and enum values. It does not read the settings file, acquire a device maintenance lock, or connect to the daemon or a phone. Descriptions default to Chinese; prefix the command with `IPHONE_CONTROL_LANG=en` for English.++```bash+# Bash: enable in the current session+mkdir -p ~/.config/iphone-control+iphone-control completions bash > ~/.config/iphone-control/completion.bash+source ~/.config/iphone-control/completion.bash++# Zsh: save in a custom completion directory+mkdir -p ~/.zsh/completions+iphone-control completions zsh > ~/.zsh/completions/_iphone-control++# Fish: use its automatically loaded completion directory+mkdir -p ~/.config/fish/completions+iphone-control completions fish > ~/.config/fish/completions/iphone-control.fish+```++For Zsh, add `fpath=(~/.zsh/completions $fpath)` before `compinit` in `~/.zshrc`, and make sure `autoload -Uz compinit; compinit` runs. For Bash, put the `source` line above in `~/.bashrc` to load completions on startup. Regenerate the completion file for your shell after upgrading. If you use a custom Fish configuration directory, use its `completions` subdirectory.+## Host software updatesRun `iphone-control update` to check the publisher's latest stable release. It reports when you are up to date. When an upgrade is available, it first says what it will do (from which version to which, and whether the background service restarts), asks whether to continue, then upgrades through the installation method of the running executable. In a script or without a terminal, add `--yes` to upgrade without asking.@@ -68,6 +89,12 @@ These commands find the service set up by the one-command install, `iphone-contr| `sign` | Sign and install WDA now, same as `resign --force`. Registers the device with the Apple ID || `resign [--force]` | Re-sign only when fewer than `RESIGN_MIN_DAYS` days remain; `--force` re-signs now. Without `--force` it doesn't register a device that has never had WDA |+In setup menus, use ↑/↓ to move and Enter to confirm, or type a number and press Enter. Confirmation prompts also accept ←/→. Esc dismisses the guide. Ctrl+C interrupts it with exit status 130. Both preserve saved steps. A `>` marker identifies the selection without relying on color. After resizing the terminal, the next key redraws the menu at the new width.++With `TERM=dumb`, redirected output or a terminal that is too small when the menu starts, menus use the original numbered/text prompts. Shrinking an active menu preserves its input and pauses confirmation until the window is enlarged; cancellation remains available. Setup still requires stdin to be a terminal; it cannot run unattended through a pipe. These shortcuts apply to menus only; passwords stay hidden.++Cancellation preserves saved settings and discards unsaved changes. In the full guide, language and proxy settings are saved together, so cancelling at the proxy step also discards the language choice made just before it.+## Checking state| Command | What it does |@@ -112,7 +139,7 @@ The `debug` subcommand for diagnostics isn't compiled by default; see the [contr- **Need the daemon running:** the phone part of `setup`, `status`, `doctor`, `sign`, `resign`, `devices`, `select`, `unlock-reset`, `wda-bridge`, `viewer`, `task`, and MCP tool calls.- **Need an interactive terminal:** `iphone-control` with no command (the first time), `setup`, `login`, `passcode set`.-- **Settings:** every command reads `~/.config/iphone-control/env` when it starts; a variable already in the environment wins. See [Configuration](./configuration#settings-file).+- **Settings:** every command except `completions` reads `~/.config/iphone-control/env` when it starts; a variable already in the environment wins. See [Configuration](./configuration#settings-file).## The control page's picture {#viewer-picture}diff --git a/website/guide/cli.md b/website/guide/cli.mdindex e05bf3a..367d55b 100644--- a/website/guide/cli.md+++ b/website/guide/cli.md@@ -21,6 +21,27 @@| `mcp` | MCP stdio 服务,由 AI 客户端拉起 || `mcp-config` | 打印把 MCP 注册到 Claude Code 的命令。程序路径用升级后不变的那个(Homebrew 用 `opt` 下的链接) |+## Shell 补全++`iphone-control completions <bash|zsh|fish>` 将补全脚本写到标准输出,包含当前构建的子命令、选项和枚举值。它不读取设置文件、不申请设备维护锁,也不连接守护进程或手机。生成的帮助文字默认中文;需要英文时,在命令前设置 `IPHONE_CONTROL_LANG=en`。++```bash+# Bash:当前会话启用+mkdir -p ~/.config/iphone-control+iphone-control completions bash > ~/.config/iphone-control/completion.bash+source ~/.config/iphone-control/completion.bash++# Zsh:保存到自定义补全目录+mkdir -p ~/.zsh/completions+iphone-control completions zsh > ~/.zsh/completions/_iphone-control++# Fish:自动加载目录+mkdir -p ~/.config/fish/completions+iphone-control completions fish > ~/.config/fish/completions/iphone-control.fish+```++Zsh 在 `~/.zshrc` 的 `compinit` 之前添加 `fpath=(~/.zsh/completions $fpath)`,并确保有 `autoload -Uz compinit; compinit`。Bash 若要每次启动生效,可将上面的 `source` 行放进 `~/.bashrc`。升级程序后,重新生成所用 shell 的补全文件。自定义 Fish 配置目录时使用对应的 `completions` 子目录。+## 主机软件更新运行 `iphone-control update` 检查发布者的最新稳定版。已是最新时,命令会显示结果并退出。有新版时,它先说明要做什么(从哪个版本升到哪个版本、会不会重启后台服务),问你是否继续,再按当前程序的安装方式升级。脚本里或没有终端时加 `--yes`,不询问直接升级。@@ -68,6 +89,12 @@ Viewer 只监听本机回环地址。同机其他用户也能查看安装信息| `sign` | 立即签名并安装 WDA,同 `resign --force`。会把设备注册到 Apple ID || `resign [--force]` | 描述文件剩余不到 `RESIGN_MIN_DAYS` 天才重签;`--force` 立即重签。不带 `--force` 时不会替没装过 WDA 的设备注册 |+设置菜单中用 ↑/↓ 移动、Enter 确认,也可以输入编号再回车;确认提示支持 ←/→ 选择。Esc 取消并退出向导。Ctrl+C 中断向导,退出码为 130。两者都会保留已保存的步骤。菜单始终用 `>` 标记选中项,不依赖颜色。窗口缩放后按键会按新宽度重绘。++`TERM=dumb`、输出重定向或启动菜单时终端过小,菜单使用原来的编号/文字输入。交互菜单打开后再缩小窗口,会保留当前输入并暂停确认,放大窗口后继续,也可取消。设置向导仍要求标准输入连接终端,不能用管道无人值守执行。这里的快捷键只作用于菜单,密码继续隐藏。++取消不会回滚已保存的设置;尚未保存的修改会丢弃。完整向导中的语言和代理设置会一起保存,因此在代理步骤取消时,刚选的语言也尚未保存。+## 查看状态| 命令 | 作用 |@@ -112,7 +139,7 @@ Viewer 只监听本机回环地址。同机其他用户也能查看安装信息- **要守护进程在运行的:** `setup` 的手机部分、`status`、`doctor`、`sign`、`resign`、`devices`、`select`、`unlock-reset`、`wda-bridge`、`viewer`、`task`,以及 MCP 工具调用。- **要在终端里交互运行的:** 不带命令的 `iphone-control`(首次运行时)、`setup`、`login`、`passcode set`。-- **设置:** 每个命令启动时都会读 `~/.config/iphone-control/env`,环境里已经有的变量优先,见[配置](./configuration#settings-file)。+- **设置:** 除 `completions` 外,每个命令启动时都会读 `~/.config/iphone-control/env`,环境里已经有的变量优先,见[配置](./configuration#settings-file)。## 控制台的画面 {#viewer-picture}